"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cell_extension_exports = {};
__export(cell_extension_exports, {
  cellExtension: () => cellExtension
});
module.exports = __toCommonJS(cell_extension_exports);
var import_ricos_content = require("./../../ricos-content/index.js");
var import_tiptap = require("./../../tiptap/index.js");
var import_state = require("./../../tiptap/pm/state.js");
var import_helpers = require("./../../tiptap-editor/helpers/index.js");
var import_tiptap_extensions = require("./../../tiptap-extensions/index.js");
var import_cell_node_view = require("./cell-node-view.js");
var import_shared_with_viewer = require("./shared-with-viewer.js");
var import_shared = require("./shared.js");
const canAddCells = (tr) => {
  const selection = tr.selection;
  const layoutNode = selection instanceof import_state.NodeSelection && selection.node.type.name === import_ricos_content.TIPTAP_LAYOUT_TYPE ? selection.node : (0, import_tiptap.findParentNodeClosestToPos)(
    tr.selection.$from,
    (node) => node.type?.name === import_ricos_content.TIPTAP_LAYOUT_TYPE
  )?.node;
  if (!layoutNode) {
    return false;
  }
  return layoutNode.childCount < import_shared_with_viewer.MAX_CELLS;
};
const getSiblingNode = (tr, nodeId, direction) => {
  const parentNodeId = (0, import_shared.getParentNodeId)(tr, nodeId);
  const parentNodeWithPos = (0, import_helpers.findNodeById)(tr, parentNodeId)[0];
  if (!parentNodeWithPos || parentNodeWithPos.node.childCount === 1) {
    return null;
  }
  let currentNodeIndex = -1;
  parentNodeWithPos.node.forEach((node, _offset, index) => {
    if (node.attrs.id === nodeId) {
      currentNodeIndex = index;
    }
  });
  if (currentNodeIndex < 0) {
    return null;
  }
  if (direction === "left" && currentNodeIndex === 0) {
    return null;
  }
  if (direction === "right" && currentNodeIndex === parentNodeWithPos.node.childCount - 1) {
    return null;
  }
  return parentNodeWithPos.node.child(currentNodeIndex + (direction === "left" ? -1 : 1));
};
const cellExtension = (0, import_tiptap_extensions.createRicosNodeExtension)({
  groups: ["custom-styles"],
  type: "html-node",
  name: import_ricos_content.TIPTAP_LAYOUT_CELL_TYPE,
  reconfigure: (config, _extensions, _props, _settings, services) => {
    return {
      ...config,
      draggable: !services.context.isMobile,
      addOptions: () => ({
        ...config,
        modals: services.modals
      })
    };
  },
  createExtensionConfig() {
    return {
      name: this.name,
      group: "block",
      isolating: true,
      selectable: true,
      draggable: true,
      content: "(PARAGRAPH|layoutCellContent)*",
      parseHTML() {
        return [
          {
            tag: "div[data-layout-cell]",
            getAttrs: (node) => {
              const colSpan = Number(
                node.getAttribute("data-layout-cell-colspan") ?? import_shared_with_viewer.MAX_COLUMNS / import_shared_with_viewer.MAX_CELLS
              );
              return {
                colSpan: isNaN(colSpan) ? import_shared_with_viewer.MAX_COLUMNS / import_shared_with_viewer.MAX_CELLS : colSpan
              };
            }
          }
        ];
      },
      renderHTML({ node }) {
        return [
          "div",
          {
            "data-layout-cell": true,
            "data-layout-cell-colspan": node.attrs.colSpan
          },
          0
        ];
      },
      addNodeView() {
        return (0, import_cell_node_view.cellNodeView)({ modals: this.options.modals });
      },
      addAttributes: () => ({
        colSpan: null
      }),
      addCommands() {
        return {
          selectCell: (nodeId) => ({ commands, tr }) => {
            const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId)[0];
            return commands.setNodeSelection(nodeWithPos.pos);
          },
          deleteCell: (nodeId) => ({ tr, chain }) => {
            const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId)[0];
            const parentNodeId = (0, import_shared.getParentNodeId)(tr, nodeId);
            const parentNodeWithPos = (0, import_helpers.findNodeById)(tr, parentNodeId)[0];
            if (parentNodeWithPos.node.childCount === 1) {
              return chain().deleteRange({
                from: parentNodeWithPos.pos,
                to: parentNodeWithPos.pos + parentNodeWithPos.node.nodeSize
              }).run();
            }
            return chain().deleteRange({
              from: nodeWithPos.pos,
              to: nodeWithPos.pos + nodeWithPos.node.nodeSize
            }).balanceLayoutCells(parentNodeId).focus().run();
          },
          addCellLeft: (nodeId) => ({ tr, dispatch, chain }) => {
            if (!dispatch) {
              return canAddCells(tr);
            }
            const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId)[0];
            const parentNodeId = (0, import_shared.getParentNodeId)(tr, nodeId);
            return chain().focus().insertContentAt(nodeWithPos.pos, (0, import_shared.createEmptyCell)(3)).balanceLayoutCells(parentNodeId).run();
          },
          addCellRight: (nodeId) => ({ tr, dispatch, chain }) => {
            if (!dispatch) {
              return canAddCells(tr);
            }
            const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId)[0];
            const parentNodeId = (0, import_shared.getParentNodeId)(tr, nodeId);
            return chain().focus().insertContentAt(nodeWithPos.pos + nodeWithPos.node.nodeSize, (0, import_shared.createEmptyCell)(3)).balanceLayoutCells(parentNodeId).run();
          },
          moveCellLeft: (nodeId) => ({ tr, dispatch, chain }) => {
            const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId)[0];
            const nodeBefore = getSiblingNode(tr, nodeId, "left");
            if (!nodeBefore) {
              return false;
            }
            const nodeBeforeWithPos = (0, import_helpers.findNodeById)(tr, nodeBefore.attrs.id)[0];
            if (dispatch) {
              return chain().focus().cut(
                { from: nodeWithPos.pos, to: nodeWithPos.pos + nodeWithPos.node.nodeSize },
                nodeBeforeWithPos.pos
              ).selectCell(nodeId).run();
            }
            return true;
          },
          moveCellRight: (nodeId) => ({ tr, dispatch, chain }) => {
            const nodeWithPos = (0, import_helpers.findNodeById)(tr, nodeId)[0];
            const nodeAfter = getSiblingNode(tr, nodeId, "right");
            if (!nodeAfter) {
              return false;
            }
            const nodeAfterWithPos = (0, import_helpers.findNodeById)(tr, nodeAfter.attrs.id)[0];
            if (dispatch) {
              return chain().focus().cut(
                { from: nodeWithPos.pos, to: nodeWithPos.pos + nodeWithPos.node.nodeSize },
                nodeAfterWithPos.pos + nodeAfterWithPos.node.nodeSize
              ).selectCell(nodeId).run();
            }
            return true;
          }
        };
      }
    };
  }
});
//# sourceMappingURL=cell-extension.js.map
