import { useSelect } from '@wordpress/data'; import isEmpty from 'lodash/isEmpty'; import has from 'lodash/has'; import { useEffect } from '@wordpress/element'; import { ItemProps } from '@components/DesignPanel/types'; type DefaultPresetProps = { props: any; isLayoutVisual: { layout: boolean; visual: boolean; }; isSelectedOrChild: boolean; currentPresetId: number | string; }; export const findPresetByBlockName = ( presets: any[], blockname: string ): any => { const defaultPreset = presets.find( (preset: any) => preset.is_default && preset.blockname === blockname ) as ItemProps; return getPresetProps(defaultPreset); }; export const findPresetById = (presets: any[], id: any): any => { const defaultPreset = presets.find( (preset: any) => preset.id === id ) as ItemProps; return getPresetProps(defaultPreset); }; export const getPresetProps = (defaultPreset: any) => { const newAttributes: any = {}; let content = {}; if (has(defaultPreset, 'content')) { content = JSON.parse(defaultPreset.content); } const picked = [ 'biteStyle', 'biteMotionStyle', 'flexStyle', 'mediaStyle', 'biteClass', 'biteMotionClass', 'flexClass', 'mediaClass', ]; picked.forEach((prop) => { if (has(content, prop)) { newAttributes[prop] = content[prop]; } }); return newAttributes; }; export const useDefaultPreset = ({ props: { attributes, setAttributes, name }, isSelectedOrChild, }: DefaultPresetProps) => { const presets = useSelect((select) => { // @ts-ignore return select('biteStore/presets').getAll(); }, []); const { biteMeta } = attributes; useEffect(() => { if (isEmpty(presets) || !biteMeta?.preset) return; const saveAttributes = findPresetByBlockName(presets, name); if (saveAttributes) { saveAttributes.biteMeta = { ...biteMeta, preset: false }; setAttributes(saveAttributes); } }, [isSelectedOrChild, presets]); }; export default { useDefaultPreset, findPresetByBlockName, findPresetById, getPresetProps, };