// packages/block-library/src/list-item/hooks/use-enter.js
import {
  createBlock,
  getDefaultBlockName,
  cloneBlock
} from "@wordpress/blocks";
import { useRef } from "@wordpress/element";
import {
  useRefEffect,
  privateApis as composePrivateApis
} from "@wordpress/compose";
import { ENTER } from "@wordpress/keycodes";
import { useSelect, useDispatch } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import useOutdentListItem from "./use-outdent-list-item.mjs";
import { unlock } from "../../lock-unlock.mjs";
var { subscribeDelegatedListener } = unlock(composePrivateApis);
function useEnter(props) {
  const { replaceBlocks, selectionChange } = useDispatch(blockEditorStore);
  const { getBlock, getBlockRootClientId, getBlockIndex, getBlockName } = useSelect(blockEditorStore);
  const propsRef = useRef(props);
  propsRef.current = props;
  const outdentListItem = useOutdentListItem();
  return useRefEffect((element) => {
    function onKeyDown(event) {
      if (event.defaultPrevented || event.keyCode !== ENTER) {
        return;
      }
      const { content, clientId } = propsRef.current;
      if (content.length) {
        return;
      }
      event.preventDefault();
      const canOutdent = getBlockName(
        getBlockRootClientId(
          getBlockRootClientId(propsRef.current.clientId)
        )
      ) === "core/list-item";
      if (canOutdent) {
        outdentListItem();
        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 subscribeDelegatedListener(
      element,
      "keydown",
      onKeyDown,
      true
    );
  }, []);
}
export {
  useEnter as default
};
//# sourceMappingURL=use-enter.mjs.map
