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