From 4a27a9b4372f10c55d9c546d9d4d19650e3e16bf Mon Sep 17 00:00:00 2001 From: Adam Silverstein Date: Thu, 22 Oct 2020 11:07:52 -0600 Subject: [PATCH] Fix search & only build a hierarchical tree when not searching. --- .../src/components/page-attributes/parent.js | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/packages/editor/src/components/page-attributes/parent.js b/packages/editor/src/components/page-attributes/parent.js index f4f35dd31c665d..b6cea94bc1fc79 100644 --- a/packages/editor/src/components/page-attributes/parent.js +++ b/packages/editor/src/components/page-attributes/parent.js @@ -32,6 +32,7 @@ function getTitle( post ) { export function PageAttributesParent() { const { editPost } = useDispatch( 'core/editor' ); const [ fieldValue, setFieldValue ] = useState( false ); + const isSearching = fieldValue && '' !== fieldValue; const { parentPost, parentPostId, items, postType } = useSelect( ( select ) => { const { getPostType, getEntityRecords, getEntityRecord } = select( @@ -53,7 +54,9 @@ export function PageAttributesParent() { order: 'asc', _fields: 'id,title,parent', }; - if ( parentPost && fieldValue && '' !== fieldValue ) { + + // Perform a search when the field is changed. + if ( isSearching ) { query.search = fieldValue; } @@ -85,21 +88,29 @@ export function PageAttributesParent() { }; const parentOptions = useMemo( () => { - const tree = buildTermsTree( - pageItems.map( ( item ) => ( { - id: item.id, - parent: item.parent, - name: getTitle( item ), - } ) ) - ); + let tree = pageItems.map( ( item ) => ( { + id: item.id, + parent: item.parent, + name: getTitle( item ), + } ) ); + + // Only build a hierarchical tree when not searching. + if ( ! isSearching ) { + tree = buildTermsTree( tree ); + } + const opts = getOptionsFromTree( tree ); - const itemsHaveParent = find( opts, item => item.value === parentPostId ); - if ( parentPost && ! itemsHaveParent ) { + + // Ensure the current parent is in the options list. + const optsHasParent = find( + opts, + ( item ) => item.value === parentPostId + ); + if ( parentPost && ! optsHasParent ) { opts.unshift( { value: parentPostId, label: getTitle( parentPost ), - } ); - + } ); } return opts; }, [ pageItems ] );