PluginProbe ʕ •ᴥ•ʔ
GenerateBlocks / 2.0.2
GenerateBlocks v2.0.2
trunk 1.0 1.0.1 1.0.2 1.1.0 1.1.1 1.1.2 1.2.0 1.3.0 1.3.1 1.3.2 1.3.3 1.3.4 1.3.5 1.4.0 1.4.1 1.4.2 1.4.3 1.4.4 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.7.0 1.7.1 1.7.2 1.7.3 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 2.0.0 2.0.1 2.0.2 2.1.0 2.1.1 2.1.2 2.2.0 2.2.1 2.3.0
generateblocks / src / components / authors-select / index.js
generateblocks / src / components / authors-select Last commit date
index.js 3 years ago
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