index.js
68 lines
| 1 | import AdvancedSelect from '../advanced-select'; |
| 2 | import { useEffect, useMemo, useState } from '@wordpress/element'; |
| 3 | import { __ } from '@wordpress/i18n'; |
| 4 | import { usePersistentAuthors } from '../../hooks/useAuthors'; |
| 5 | import { applyFilters } from '@wordpress/hooks'; |
| 6 | import useDebounceState from '../../hooks/useDebounceState'; |
| 7 | |
| 8 | export default function AuthorsSelect( props ) { |
| 9 | const { |
| 10 | label, |
| 11 | onChange, |
| 12 | value, |
| 13 | help, |
| 14 | placeholder, |
| 15 | filterName = 'generateblocks.editor.authors-select', |
| 16 | } = props; |
| 17 | |
| 18 | const [ search, setSearch ] = useDebounceState( '', 400 ); |
| 19 | const [ loadValues, setLoadValues ] = useState( value.length > 0 ); |
| 20 | |
| 21 | const isSearchById = !! search.trim() && ! search.trim().match( /\D/g ); |
| 22 | const includeSearchId = isSearchById ? [ search.replace( /\D/g, '' ) ] : undefined; |
| 23 | |
| 24 | const { records, isLoading } = usePersistentAuthors( { |
| 25 | per_page: !! search ? 100 : 10, |
| 26 | search: !! search && ! isSearchById ? search : undefined, |
| 27 | include: loadValues ? value : includeSearchId, |
| 28 | } ); |
| 29 | |
| 30 | useEffect( () => { |
| 31 | if ( loadValues && records.some( ( author ) => ( value.includes( author.id ) ) ) ) { |
| 32 | setLoadValues( false ); |
| 33 | } |
| 34 | }, [ JSON.stringify( records ), JSON.stringify( value ) ] ); |
| 35 | |
| 36 | const authorOptions = useMemo( () => { |
| 37 | const options = records |
| 38 | .reduce( ( result, author ) => { |
| 39 | result.push( { value: author.id, label: author.name } ); |
| 40 | return result; |
| 41 | }, [] ); |
| 42 | |
| 43 | return applyFilters( filterName, options ); |
| 44 | }, [ records ] ); |
| 45 | |
| 46 | const selectedValues = authorOptions.filter( ( option ) => ( value.includes( option.value ) ) ); |
| 47 | |
| 48 | return ( |
| 49 | <AdvancedSelect |
| 50 | id={ 'gblocks-select-author' } |
| 51 | label={ label || __( 'Select authors', 'generateblocks' ) } |
| 52 | help={ help } |
| 53 | placeholder={ placeholder || __( 'Search authors…', 'generateblocks' ) } |
| 54 | options={ authorOptions } |
| 55 | isMulti |
| 56 | isSearchable |
| 57 | value={ selectedValues } |
| 58 | onChange={ onChange } |
| 59 | isLoading={ isLoading } |
| 60 | onInputChange={ ( inputValue, { action } ) => { |
| 61 | if ( 'input-change' === action ) { |
| 62 | setSearch( inputValue ); |
| 63 | } |
| 64 | } } |
| 65 | /> |
| 66 | ); |
| 67 | } |
| 68 |