UNPKG

@wordpress/block-editor

Version:
65 lines (64 loc) 2.47 kB
// packages/block-editor/src/components/inner-blocks/use-inner-block-template-sync.js import fastDeepEqual from "fast-deep-equal/es6"; import { useRef, useLayoutEffect } from "@wordpress/element"; import { useRegistry } from "@wordpress/data"; import { synchronizeBlocksWithTemplate } from "@wordpress/blocks"; import { store as blockEditorStore } from "../../store"; function useInnerBlockTemplateSync(clientId, template, templateLock, templateInsertUpdatesSelection) { const registry = useRegistry(); const existingTemplateRef = useRef(null); useLayoutEffect(() => { let isCancelled = false; const { getBlocks, getSelectedBlocksInitialCaretPosition, isBlockSelected } = registry.select(blockEditorStore); const { replaceInnerBlocks, __unstableMarkNextChangeAsNotPersistent } = registry.dispatch(blockEditorStore); window.queueMicrotask(() => { if (isCancelled) { return; } const currentInnerBlocks = getBlocks(clientId); const shouldApplyTemplate = currentInnerBlocks.length === 0 || templateLock === "all" || templateLock === "contentOnly"; const hasTemplateChanged = !fastDeepEqual( template, existingTemplateRef.current ); if (!shouldApplyTemplate || !hasTemplateChanged) { return; } existingTemplateRef.current = template; const nextBlocks = synchronizeBlocksWithTemplate( currentInnerBlocks, template ); if (!fastDeepEqual(nextBlocks, currentInnerBlocks)) { __unstableMarkNextChangeAsNotPersistent(); replaceInnerBlocks( clientId, nextBlocks, currentInnerBlocks.length === 0 && templateInsertUpdatesSelection && nextBlocks.length !== 0 && isBlockSelected(clientId), // This ensures the "initialPosition" doesn't change when applying the template // If we're supposed to focus the block, we'll focus the first inner block // otherwise, we won't apply any auto-focus. // This ensures for instance that the focus stays in the inserter when inserting the "buttons" block. getSelectedBlocksInitialCaretPosition() ); } }); return () => { isCancelled = true; }; }, [ template, templateLock, clientId, registry, templateInsertUpdatesSelection ]); } export { useInnerBlockTemplateSync as default }; //# sourceMappingURL=use-inner-block-template-sync.js.map