"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var BlockPlugin_exports = {};
__export(BlockPlugin_exports, {
  BlockActions: () => BlockActions,
  BlockPlugin: () => BlockPlugin,
  ListActions: () => ListActions,
  onKeyDown: () => onKeyDown,
  withBlock: () => withBlock
});
module.exports = __toCommonJS(BlockPlugin_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_css = require("@emotion/css");
var import_slate = require("slate");
var import_controls = require("@makeswift/controls");
var import_setBlockKeyForDevice = require("./setBlockKeyForDevice");
var import_clearBlockKeyForDevice = require("./clearBlockKeyForDevice");
var import_wrapInline = require("./wrapInline");
var import_unwrapInline = require("./unwrapInline");
var import_selectors = require("../selectors");
var import_element = require("../utils/element");
var import_selectors2 = require("../selectors");
var import_unwrapList = require("./unwrapList");
var import_wrapList = require("./wrapList");
var import_indent = require("./indent");
var import_dedent = require("./dedent");
var import_toggleList = require("./toggleList");
var import_editor = require("../utils/editor");
var import_is_hotkey = __toESM(require("is-hotkey"));
var import_constants = require("./constants");
var import_use_style = require("../../runtimes/react/use-style");
var import_plugin = require("../../controls/rich-text-v2/plugin");
var import_types = require("../../slate/types");
const BlockActions = {
  setBlockKeyForDevice: import_setBlockKeyForDevice.setBlockKeyForDevice,
  clearBlockKeyForDevice: import_clearBlockKeyForDevice.clearBlockKeyForDevice,
  wrapInline: import_wrapInline.wrapInline,
  unwrapInline: import_unwrapInline.unwrapInline
};
const ListActions = {
  unwrapList: import_unwrapList.unwrapList,
  wrapList: import_wrapList.wrapList,
  indent: import_indent.indent,
  dedent: import_dedent.dedent,
  toggleList: import_toggleList.toggleList
};
function onKeyDown(e, editor) {
  if (!editor.selection || Array.from(import_slate.Editor.nodes(editor, { match: (node) => import_controls.Slate.isListItem(node) })).length === 0)
    return;
  if ((0, import_is_hotkey.default)("shift+tab", e)) {
    e.preventDefault();
    ListActions.dedent(editor);
  }
  if ((0, import_is_hotkey.default)("tab", e)) {
    e.preventDefault();
    ListActions.indent(editor);
  }
  if ((0, import_is_hotkey.default)("backspace", e)) {
    if (!editor.selection)
      return;
    if (import_slate.Range.isExpanded(editor.selection))
      return;
    const listItem = import_editor.EditorUtils.getFirstAncestorListItem(editor, editor.selection.anchor.path);
    if (editor.selection.anchor.offset === 0 && listItem) {
      e.preventDefault();
      const parentListItem = import_editor.EditorUtils.getFirstAncestorListItem(editor, listItem[1]);
      const list = import_editor.EditorUtils.getFirstAncestorList(editor, listItem[1]);
      if (parentListItem) {
        ListActions.dedent(editor);
      } else if (list) {
        ListActions.unwrapList(editor);
      }
      return;
    }
  }
  if ((0, import_is_hotkey.default)("enter", e)) {
    e.preventDefault();
    if (!editor.selection)
      return;
    if (import_slate.Range.isExpanded(editor.selection)) {
      import_slate.Transforms.delete(editor);
      return;
    }
    const listItem = import_editor.EditorUtils.getFirstAncestorListItem(editor, editor.selection.anchor.path);
    if (editor.selection.anchor.offset === 0 && listItem && import_slate.Editor.string(editor, listItem[1]) === "") {
      const parentListItem = import_editor.EditorUtils.getFirstAncestorListItem(editor, listItem[1]);
      if (parentListItem) {
        ListActions.dedent(editor);
      } else {
        ListActions.unwrapList(editor);
      }
      return;
    }
    import_slate.Transforms.splitNodes(editor, {
      at: editor.selection,
      always: true,
      match: (node) => import_controls.Slate.isListItem(node)
    });
  }
  if ((0, import_is_hotkey.default)("shift+enter", e)) {
    e.preventDefault();
    editor.insertText("\n");
  }
}
function withBlock(editor) {
  const { normalizeNode } = editor;
  editor.isInline = (entry) => {
    return import_controls.Slate.isInline(entry);
  };
  editor.normalizeNode = (entry) => {
    const [normalizationNode, normalizationPath] = entry;
    if (import_controls.Slate.isBlock(normalizationNode) && normalizationNode?.textAlign?.length == 0) {
      import_slate.Transforms.unsetNodes(editor, "textAlign", { at: normalizationPath });
      return;
    }
    if (normalizationPath.length === 1 && import_controls.Slate.isRootBlock(normalizationNode) && !import_controls.Slate.isList(normalizationNode)) {
      const children = Array.from(import_slate.Node.children(editor, normalizationPath));
      if (children.findIndex(([child]) => import_controls.Slate.isRootBlock(child)) !== -1) {
        import_slate.Transforms.unwrapNodes(editor, { at: normalizationPath });
        return;
      }
    }
    if (import_controls.Slate.isListItem(normalizationNode)) {
      const pathToListItemText = [...normalizationPath, import_constants.LIST_ITEM_CHILD_POSITION];
      if (import_slate.Node.has(editor, pathToListItemText)) {
        const nodeInListItemTextPosition = import_slate.Node.get(editor, pathToListItemText);
        if (import_controls.Slate.isRootBlock(nodeInListItemTextPosition)) {
          import_slate.Transforms.setNodes(
            editor,
            { type: import_types.BlockType.ListItemChild },
            {
              at: pathToListItemText
            }
          );
          return;
        }
      } else {
        import_slate.Transforms.insertNodes(editor, import_element.ElementUtils.createListItem(), {
          at: pathToListItemText
        });
        return;
      }
    }
    if (!import_slate.Text.isText(normalizationNode)) {
      const mergeableChildren = Array.from(import_slate.Node.children(editor, normalizationPath)).map((child, index, children) => {
        const potentialNodeToBeMerged = children.at(index + 1);
        if (!potentialNodeToBeMerged || !import_controls.Slate.isList(potentialNodeToBeMerged[0]) || !import_controls.Slate.isList(child[0]) || potentialNodeToBeMerged[0].type !== child[0].type) {
          return null;
        }
        return [
          import_slate.Editor.pathRef(editor, child[1]),
          import_slate.Editor.pathRef(editor, potentialNodeToBeMerged[1])
        ];
      }).filter((mergeableNodes) => Boolean(mergeableNodes));
      if (mergeableChildren.length !== 0) {
        mergeableChildren.reverse().forEach(([nodePathRef, nodeToBeMergedPathRef]) => {
          const nodePath = nodePathRef.current;
          const nodeToBeMergedPath = nodeToBeMergedPathRef.current;
          if (nodePath == null || nodeToBeMergedPath == null)
            return;
          const nodeChildren = Array.from(import_slate.Node.children(editor, nodePath));
          const childrenToBeMerged = Array.from(import_slate.Node.children(editor, nodeToBeMergedPath));
          import_slate.Editor.withoutNormalizing(editor, () => {
            childrenToBeMerged.reverse().forEach(([_, childPath]) => {
              import_slate.Transforms.moveNodes(editor, {
                at: childPath,
                to: [...nodePath, nodeChildren.length]
              });
            });
            import_slate.Transforms.removeNodes(editor, { at: nodeToBeMergedPath });
          });
          nodePathRef.unref();
          nodeToBeMergedPathRef.unref();
        });
        return;
      }
    }
    normalizeNode(entry);
  };
  return editor;
}
const definition = (0, import_controls.Select)({
  label: "Block",
  labelOrientation: "horizontal",
  options: [
    {
      value: import_types.BlockType.Paragraph,
      label: "Paragraph"
    },
    {
      value: import_types.BlockType.Heading1,
      label: "Heading 1"
    },
    {
      value: import_types.BlockType.Heading2,
      label: "Heading 2"
    },
    {
      value: import_types.BlockType.Heading3,
      label: "Heading 3"
    },
    {
      value: import_types.BlockType.Heading4,
      label: "Heading 4"
    },
    {
      value: import_types.BlockType.Heading5,
      label: "Heading 5"
    },
    {
      value: import_types.BlockType.Heading6,
      label: "Heading 6"
    },
    {
      value: import_types.BlockType.UnorderedList,
      label: "Bulleted list"
    },
    {
      value: import_types.BlockType.OrderedList,
      label: "Numbered list"
    },
    {
      value: import_types.BlockType.BlockQuote,
      label: "Quote"
    }
  ],
  defaultValue: import_types.BlockType.Paragraph
});
function BlockPlugin() {
  return (0, import_plugin.Plugin)({
    withPlugin: withBlock,
    onKeyDown,
    control: {
      definition,
      onChange: (editor, value) => {
        const activeBlockType = (0, import_selectors2.getActiveBlockType)(editor);
        if (value === import_types.BlockType.UnorderedList || value === import_types.BlockType.OrderedList) {
          ListActions.toggleList(editor, {
            type: value,
            at: (0, import_selectors.getSelection)(editor)
          });
        } else if (activeBlockType === value) {
          import_slate.Transforms.setNodes(
            editor,
            {
              type: import_types.BlockType.Default
            },
            { at: (0, import_selectors.getSelection)(editor) }
          );
        } else {
          ListActions.unwrapList(editor, {
            at: (0, import_selectors.getSelection)(editor)
          });
          import_slate.Transforms.setNodes(
            editor,
            {
              type: value ?? import_types.BlockType.Default
            },
            { at: (0, import_selectors.getSelection)(editor) }
          );
        }
      },
      getValue: (editor) => {
        const activeBlock = (0, import_selectors2.getActiveBlockType)(editor);
        if (activeBlock == null)
          return void 0;
        if (activeBlock === import_controls.Slate.RootBlockType.Default)
          return void 0;
        return activeBlock;
      }
    },
    renderElement: (renderElement) => (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockPluginComponent, { ...props, renderElement })
  });
}
function BlockPluginComponent({
  renderElement,
  ...props
}) {
  const blockStyles = [(0, import_use_style.useStyle)({ margin: 0 }), props.element.className];
  const quoteStyles = (0, import_use_style.useStyle)({
    padding: "0.5em 10px",
    fontSize: "1.25em",
    fontWeight: "300",
    borderLeft: "5px solid rgba(0, 0, 0, 0.1)"
  });
  const unorderedListStyles = (0, import_use_style.useStyle)({
    listStylePosition: "inside",
    paddingInlineStart: "20px",
    listStyleType: "disc",
    ul: {
      listStyleType: "circle"
    },
    "ul ul": {
      listStyleType: "square"
    }
  });
  const orderedListStyles = (0, import_use_style.useStyle)({
    listStylePosition: "inside",
    paddingInlineStart: "20px",
    listStyleType: "decimal"
  });
  switch (props.element.type) {
    case import_types.BlockType.Default:
    case import_types.BlockType.Paragraph:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.Heading1:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.Heading2:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.Heading3:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h3", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.Heading4:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h4", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.Heading5:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h5", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.Heading6:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h6", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.BlockQuote:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("blockquote", { ...props.attributes, className: (0, import_css.cx)(...blockStyles, quoteStyles), children: renderElement(props) });
    case import_types.BlockType.OrderedList:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ol", { ...props.attributes, className: (0, import_css.cx)(...blockStyles, orderedListStyles), children: renderElement(props) });
    case import_types.BlockType.UnorderedList:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { ...props.attributes, className: (0, import_css.cx)(...blockStyles, unorderedListStyles), children: renderElement(props) });
    case import_types.BlockType.ListItem:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    case import_types.BlockType.ListItemChild:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { ...props.attributes, className: (0, import_css.cx)(...blockStyles), children: renderElement(props) });
    default:
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: renderElement(props) });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BlockActions,
  BlockPlugin,
  ListActions,
  onKeyDown,
  withBlock
});
//# sourceMappingURL=index.js.map