2023-09-14 08:24:46 +00:00
|
|
|
/* eslint-disable @woocommerce/dependency-group */
|
|
|
|
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useSelect } from '@wordpress/data';
|
|
|
|
// @ts-ignore No types for this exist yet.
|
|
|
|
import { store as coreStore } from '@wordpress/core-data';
|
|
|
|
import { useMemo } from '@wordpress/element';
|
|
|
|
import { BlockInstance, parse } from '@wordpress/blocks';
|
|
|
|
|
2023-09-19 05:54:19 +00:00
|
|
|
export type Pattern = {
|
2023-09-14 08:24:46 +00:00
|
|
|
blockTypes: string[];
|
|
|
|
categories: string[];
|
|
|
|
content: string;
|
|
|
|
name: string;
|
|
|
|
source: string;
|
|
|
|
title: string;
|
|
|
|
};
|
|
|
|
|
2023-09-19 05:54:19 +00:00
|
|
|
export type PatternWithBlocks = Pattern & {
|
2023-09-14 08:24:46 +00:00
|
|
|
blocks: BlockInstance[];
|
|
|
|
};
|
|
|
|
|
2023-09-19 05:54:19 +00:00
|
|
|
export const usePatterns = () => {
|
2023-09-14 08:24:46 +00:00
|
|
|
const { blockPatterns, isLoading } = useSelect(
|
|
|
|
( select ) => ( {
|
2023-09-19 05:54:19 +00:00
|
|
|
blockPatterns: select(
|
|
|
|
coreStore
|
|
|
|
// @ts-ignore - This is valid.
|
|
|
|
).getBlockPatterns() as Pattern[],
|
2023-09-14 08:24:46 +00:00
|
|
|
isLoading:
|
|
|
|
// @ts-ignore - This is valid.
|
|
|
|
! select( coreStore ).hasFinishedResolution(
|
|
|
|
'getBlockPatterns'
|
|
|
|
),
|
|
|
|
} ),
|
|
|
|
[]
|
|
|
|
);
|
|
|
|
|
2023-09-19 05:54:19 +00:00
|
|
|
return {
|
|
|
|
blockPatterns,
|
|
|
|
isLoading,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export const usePatternsByCategory = ( category: string ) => {
|
|
|
|
const { blockPatterns, isLoading } = usePatterns();
|
|
|
|
|
2023-09-14 08:24:46 +00:00
|
|
|
const patternsByCategory: PatternWithBlocks[] = useMemo( () => {
|
|
|
|
return ( blockPatterns || [] )
|
|
|
|
.filter( ( pattern: Pattern ) =>
|
|
|
|
pattern.categories?.includes( category )
|
|
|
|
)
|
|
|
|
.map( ( pattern: Pattern ) => {
|
|
|
|
return {
|
|
|
|
...pattern,
|
|
|
|
// @ts-ignore - Passing options is valid, but not in the type.
|
|
|
|
blocks: parse( pattern.content, {
|
|
|
|
__unstableSkipMigrationLogs: true,
|
|
|
|
} ),
|
|
|
|
};
|
|
|
|
} );
|
|
|
|
}, [ blockPatterns, category ] );
|
|
|
|
|
|
|
|
return { isLoading, patterns: patternsByCategory };
|
|
|
|
};
|