@wordpress/block-library
Version:
Block library for the WordPress editor.
83 lines (82 loc) • 2.57 kB
JavaScript
// packages/block-library/src/list-item/hooks/use-enter.js
import {
createBlock,
getDefaultBlockName,
cloneBlock
} from "@wordpress/blocks";
import { useRefEffect } from "@wordpress/compose";
import { privateApis as richTextPrivateApis } from "@wordpress/rich-text";
import { useRegistry } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { outdentListItems, getOutdentTarget } from "../utils.mjs";
import { unlock } from "../../lock-unlock.mjs";
var { subscribeOwnedListener } = unlock(richTextPrivateApis);
function useEnter(clientId) {
const registry = useRegistry();
return useRefEffect(
(element) => {
function onBeforeInput(event) {
if (event.defaultPrevented || event.inputType !== "insertParagraph") {
return;
}
const select = registry.select(blockEditorStore);
const {
getBlock,
getBlockAttributes,
getBlockRootClientId,
getBlockIndex
} = select;
const { replaceBlocks, selectionChange } = registry.dispatch(blockEditorStore);
const { content } = getBlockAttributes(clientId) ?? {};
if (content?.length) {
return;
}
event.preventDefault();
const canOutdent = !!getOutdentTarget(select, clientId);
if (canOutdent) {
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