From b7a5fea8b7acb2122cfc4b6212296877a3147d8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20Ka=CC=88gy?= Date: Fri, 20 Sep 2024 15:18:28 +0200 Subject: [PATCH] add useFlatInnerBlocks hook --- hooks/index.ts | 1 + hooks/use-filtered-list/index.ts | 12 ++++++++++-- hooks/use-flat-inner-blocks/index.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 hooks/use-flat-inner-blocks/index.ts diff --git a/hooks/index.ts b/hooks/index.ts index 652992e8..65d91d33 100644 --- a/hooks/index.ts +++ b/hooks/index.ts @@ -17,3 +17,4 @@ export { useScript } from './use-script'; export { usePostMetaValue } from './use-post-meta-value'; export { useTaxonomy } from './use-taxonomy'; export { useIsSupportedMetaField } from './use-is-supported-meta-value'; +export { useFlatInnerBlocks } from './use-flat-inner-blocks'; diff --git a/hooks/use-filtered-list/index.ts b/hooks/use-filtered-list/index.ts index fa6a9877..695cbd30 100644 --- a/hooks/use-filtered-list/index.ts +++ b/hooks/use-filtered-list/index.ts @@ -23,8 +23,16 @@ export function useFilteredList( const filterList = useCallback( (searchTerm: string) => { - const matchedNames = fuzzy.filter(propertyList, searchTerm); - const results = matchedNames?.map((index) => list[index]) || []; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [matchedIds, _idInfos, order] = fuzzy.search(propertyList, searchTerm); + + if (!matchedIds || !order) { + return []; + } + + // sort the matchedIds based on the order + const sortedItems = order.map((index) => matchedIds[index]); + const results = sortedItems.map((index) => list[index]); return results; }, [propertyList, list], diff --git a/hooks/use-flat-inner-blocks/index.ts b/hooks/use-flat-inner-blocks/index.ts new file mode 100644 index 00000000..2b169be5 --- /dev/null +++ b/hooks/use-flat-inner-blocks/index.ts @@ -0,0 +1,28 @@ +import { store as blockEditorStore } from '@wordpress/block-editor'; +import type { WPBlock } from '@wordpress/core-data'; +import { useSelect } from '@wordpress/data'; + +export const useFlatInnerBlocks = (clientId: string) => { + return useSelect( + (select) => { + function recursivelyGetInnerBlocks(clientId: string) { + let allInnerBlocks: Array = []; + + // @ts-expect-error - TS doesn't know about the block editor store + const innerBlocks = select(blockEditorStore).getBlocks(clientId); + + innerBlocks.forEach((block: WPBlock) => { + allInnerBlocks.push(block); + allInnerBlocks = allInnerBlocks.concat( + recursivelyGetInnerBlocks(block.clientId), + ); + }); + + return allInnerBlocks; + } + + return recursivelyGetInnerBlocks(clientId); + }, + [clientId], + ); +};