index.js
65 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 { records, isLoading } = usePersistentAuthors( { |
| 22 | per_page: 10, |
| 23 | search: !! search ? search : undefined, |
| 24 | include: loadValues ? value : undefined, |
| 25 | } ); |
| 26 | |
| 27 | useEffect( () => { |
| 28 | if ( loadValues && records.some( ( author ) => ( value.includes( author.id ) ) ) ) { |
| 29 | setLoadValues( false ); |
| 30 | } |
| 31 | }, [ JSON.stringify( records ), JSON.stringify( value ) ] ); |
| 32 | |
| 33 | const authorOptions = useMemo( () => { |
| 34 | const options = records |
| 35 | .reduce( ( result, author ) => { |
| 36 | result.push( { value: author.id, label: author.name } ); |
| 37 | return result; |
| 38 | }, [] ); |
| 39 | |
| 40 | return applyFilters( filterName, options ); |
| 41 | }, [ records ] ); |
| 42 | |
| 43 | const selectedValues = authorOptions.filter( ( option ) => ( value.includes( option.value ) ) ); |
| 44 | |
| 45 | return ( |
| 46 | <AdvancedSelect |
| 47 | id={ 'gblocks-select-author' } |
| 48 | label={ label || __( 'Select authors', 'generateblocks' ) } |
| 49 | help={ help } |
| 50 | placeholder={ placeholder || __( 'Search authors…', 'generateblocks' ) } |
| 51 | options={ authorOptions } |
| 52 | isMulti |
| 53 | isSearchable |
| 54 | value={ selectedValues } |
| 55 | onChange={ onChange } |
| 56 | isLoading={ isLoading } |
| 57 | onInputChange={ ( inputValue, { action } ) => { |
| 58 | if ( 'input-change' === action ) { |
| 59 | setSearch( inputValue ); |
| 60 | } |
| 61 | } } |
| 62 | /> |
| 63 | ); |
| 64 | } |
| 65 |