@wordpress/block-library
Version:
Block library for the WordPress editor.
49 lines (48 loc) • 2.02 kB
JavaScript
import { cloneBlock, createBlock, getDefaultBlockName } from "@wordpress/blocks";
import { useRefEffect } from "@wordpress/compose";
import { privateApis } from "@wordpress/rich-text";
import { useRegistry } from "@wordpress/data";
import { store } from "@wordpress/block-editor";
import { getOutdentTarget, outdentListItems } from "../utils.mjs";
import { unlock } from "../../lock-unlock.mjs";
// packages/block-library/src/list-item/hooks/use-enter.js
const { subscribeOwnedListener } = unlock(privateApis);
function useEnter(clientId) {
const registry = useRegistry();
return useRefEffect((element) => {
function onBeforeInput(event) {
if (event.defaultPrevented || event.inputType !== "insertParagraph") return;
const select = registry.select(store);
const { getBlock, getBlockAttributes, getBlockRootClientId, getBlockIndex } = select;
const { replaceBlocks, selectionChange } = registry.dispatch(store);
const { content } = getBlockAttributes(clientId) ?? {};
if (content?.length) return;
event.preventDefault();
if (!!getOutdentTarget(select, clientId)) {
outdentListItems(registry);
return;
}
const topParentListBlock = getBlock(getBlockRootClientId(clientId));
const blockIndex = getBlockIndex(clientId);
const head = cloneBlock({
...topParentListBlock,
innerBlocks: topParentListBlock.innerBlocks.slice(0, blockIndex)
});
const middle = createBlock(getDefaultBlockName());
const after = [...topParentListBlock.innerBlocks[blockIndex].innerBlocks[0]?.innerBlocks || [], ...topParentListBlock.innerBlocks.slice(blockIndex + 1)];
const tail = after.length ? [cloneBlock({
...topParentListBlock,
innerBlocks: after
})] : [];
replaceBlocks(topParentListBlock.clientId, [
head,
middle,
...tail
], 1);
selectionChange(middle.clientId);
}
return subscribeOwnedListener(element, "beforeinput", onBeforeInput, true);
}, [clientId, registry]);
}
export { useEnter as default };
//# sourceMappingURL=use-enter.mjs.map