Skip to content

Commit

Permalink
add useFlatInnerBlocks hook
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiankaegy committed Sep 20, 2024
1 parent 1aafdfc commit b7a5fea
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
1 change: 1 addition & 0 deletions hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
12 changes: 10 additions & 2 deletions hooks/use-filtered-list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,16 @@ export function useFilteredList<TListItem extends { [key: string]: string }>(

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],
Expand Down
28 changes: 28 additions & 0 deletions hooks/use-flat-inner-blocks/index.ts
Original file line number Diff line number Diff line change
@@ -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<WPBlock> = [];

// @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],
);
};

0 comments on commit b7a5fea

Please sign in to comment.