/** * Specific pages/posts picker for a display condition. * * Backed by WordPress core's `/wp/v2/search` endpoint via apiFetch (no custom * REST route). Tokens read `Title (#id)` so they stay unique and the id is * recoverable on change; selected ids are resolved to titles on mount. */ import { useState, useEffect, useRef } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { FormTokenField } from '@wordpress/components'; import apiFetch from '@wordpress/api-fetch'; interface SearchResult { id: number; title: string; } interface SpecificPostsFieldProps { ids: number[]; onChange: ( ids: number[] ) => void; } const tokenFor = ( id: number, label: string ) => `${ label } (#${ id })`; const idFromToken = ( token: string ): number | null => { const match = token.match( /\(#(\d+)\)\s*$/ ); return match ? Number( match[ 1 ] ) : null; }; export default function SpecificPostsField( { ids, onChange, }: SpecificPostsFieldProps ) { const [ labelById, setLabelById ] = useState< Record< number, string > >( {} ); const [ results, setResults ] = useState< SearchResult[] >( [] ); const debounce = useRef< ReturnType< typeof setTimeout > >(); // Resolve titles for already-selected ids on mount / when ids change. useEffect( () => { const missing = ids.filter( ( id ) => ! labelById[ id ] ); if ( 0 === missing.length ) { return; } apiFetch< SearchResult[] >( { path: `/wp/v2/search?include=${ missing.join( ',' ) }&per_page=${ missing.length }&_fields=id,title`, } ) .then( ( items ) => setLabelById( ( prev ) => { const next = { ...prev }; items.forEach( ( item ) => { next[ item.id ] = item.title; } ); return next; } ) ) .catch( () => undefined ); // eslint-disable-next-line react-hooks/exhaustive-deps }, [ ids ] ); const search = ( query: string ) => { window.clearTimeout( debounce.current ); if ( query.length < 2 ) { setResults( [] ); return; } debounce.current = setTimeout( () => { apiFetch< SearchResult[] >( { path: `/wp/v2/search?search=${ encodeURIComponent( query ) }&per_page=10&_fields=id,title`, } ) .then( ( items ) => { setResults( items ); setLabelById( ( prev ) => { const next = { ...prev }; items.forEach( ( item ) => { next[ item.id ] = item.title; } ); return next; } ); } ) .catch( () => setResults( [] ) ); }, 250 ); }; const handleChange = ( tokens: ( string | { value: string } )[] ) => { const next = tokens .map( ( token ) => idFromToken( 'string' === typeof token ? token : token.value ) ) .filter( ( id ): id is number => null !== id ); onChange( Array.from( new Set( next ) ) ); }; return ( tokenFor( id, labelById[ id ] ?? `#${ id }` ) ) } suggestions={ results.map( ( item ) => tokenFor( item.id, item.title ) ) } onInputChange={ search } onChange={ handleChange } __experimentalExpandOnFocus /> ); }