2023-09-19 05:54:19 +00:00
|
|
|
/* eslint-disable @woocommerce/dependency-group */
|
|
|
|
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useMemo } from '@wordpress/element';
|
|
|
|
import { parse } from '@wordpress/blocks';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { usePatterns, Pattern, PatternWithBlocks } from './use-patterns';
|
2023-09-25 10:30:31 +00:00
|
|
|
import { HOMEPAGE_TEMPLATES } from '~/customize-store/data/homepageTemplates';
|
2023-09-21 01:47:59 +00:00
|
|
|
|
2023-09-21 05:30:57 +00:00
|
|
|
export const getTemplatePatterns = (
|
2023-09-19 05:54:19 +00:00
|
|
|
template: string[],
|
|
|
|
patternsByName: Record< string, Pattern >
|
|
|
|
) =>
|
|
|
|
template
|
|
|
|
.map( ( patternName: string ) => {
|
|
|
|
const pattern = patternsByName[ patternName ];
|
|
|
|
if ( pattern && pattern.content ) {
|
|
|
|
return {
|
|
|
|
...pattern,
|
|
|
|
// @ts-ignore - Passing options is valid, but not in the type.
|
|
|
|
blocks: parse( pattern.content, {
|
|
|
|
__unstableSkipMigrationLogs: true,
|
|
|
|
} ),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
} )
|
|
|
|
.filter( ( pattern ) => pattern !== null ) as PatternWithBlocks[];
|
|
|
|
|
2023-09-21 05:30:57 +00:00
|
|
|
export const patternsToNameMap = ( blockPatterns: Pattern[] ) =>
|
|
|
|
blockPatterns.reduce(
|
|
|
|
( acc: Record< string, Pattern >, pattern: Pattern ) => {
|
|
|
|
acc[ pattern.name ] = pattern;
|
|
|
|
return acc;
|
|
|
|
},
|
|
|
|
{}
|
|
|
|
);
|
|
|
|
|
2023-09-25 10:30:31 +00:00
|
|
|
// Returns home template patterns excluding header and footer.
|
2023-09-19 05:54:19 +00:00
|
|
|
export const useHomeTemplates = () => {
|
|
|
|
const { blockPatterns, isLoading } = usePatterns();
|
|
|
|
|
2023-09-21 05:30:57 +00:00
|
|
|
const patternsByName = useMemo(
|
|
|
|
() => patternsToNameMap( blockPatterns ),
|
|
|
|
[ blockPatterns ]
|
|
|
|
);
|
2023-09-19 05:54:19 +00:00
|
|
|
|
|
|
|
const homeTemplates = useMemo( () => {
|
|
|
|
if ( isLoading ) return {};
|
2023-09-25 10:30:31 +00:00
|
|
|
const recommendedTemplates = HOMEPAGE_TEMPLATES;
|
2023-09-19 05:54:19 +00:00
|
|
|
|
|
|
|
return Object.entries( recommendedTemplates ).reduce(
|
|
|
|
(
|
|
|
|
acc: Record< string, PatternWithBlocks[] >,
|
|
|
|
[ templateName, template ]
|
|
|
|
) => {
|
|
|
|
if ( templateName in recommendedTemplates ) {
|
|
|
|
acc[ templateName ] = getTemplatePatterns(
|
2024-02-29 14:32:44 +00:00
|
|
|
template.blocks,
|
2023-09-19 05:54:19 +00:00
|
|
|
patternsByName
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return acc;
|
|
|
|
},
|
|
|
|
{}
|
|
|
|
);
|
|
|
|
}, [ isLoading, patternsByName ] );
|
|
|
|
|
|
|
|
return {
|
|
|
|
homeTemplates,
|
|
|
|
isLoading,
|
|
|
|
};
|
|
|
|
};
|