"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 table_extension_exports = {};
__export(table_extension_exports, {
  tableExtension: () => tableExtension
});
module.exports = __toCommonJS(table_extension_exports);
var import_ricos_content = require("./../../ricos-content/index.js");
var import_next_schema = require("./../../ricos-schema/next-schema/index.js");
var import_tiptap = require("./../../tiptap/index.js");
var import_state = require("./../../tiptap/pm/state.js");
var import_view = require("./../../tiptap/pm/view.js");
var import_plugin_commons = require("./../../plugin-commons/index.js");
var import_consts = require("../consts.js");
var import_border = require("./commands/border.js");
var import_cell_attributes = require("./commands/cell-attributes.js");
var import_fix = require("./commands/fix.js");
var import_mutations = require("./commands/mutations.js");
var import_navigation = require("./commands/navigation.js");
var import_reorder = require("./commands/reorder.js");
var import_selection = require("./commands/selection.js");
var import_plugins = require("./plugins/index.js");
var import_keyboard_shortcuts = require("./utilities/keyboard-shortcuts.js");
const TABLE_SUPPORTED_QUICK_ACTIONS = [
  import_next_schema.Node_Type.PARAGRAPH,
  import_next_schema.Node_Type.HEADING,
  import_next_schema.Node_Type.BULLETED_LIST,
  import_next_schema.Node_Type.ORDERED_LIST,
  import_next_schema.Node_Type.CHECKBOX_LIST,
  import_next_schema.Node_Type.BLOCKQUOTE,
  import_next_schema.Node_Type.AUDIO,
  import_next_schema.Node_Type.FILE,
  import_next_schema.Node_Type.IMAGE,
  import_next_schema.Node_Type.VIDEO,
  import_next_schema.Node_Type.GIF,
  import_next_schema.Node_Type.DIVIDER,
  import_next_schema.Node_Type.CODE_BLOCK,
  import_next_schema.Node_Type.HTML,
  import_next_schema.Node_Type.LINK_PREVIEW,
  import_next_schema.Node_Type.APP_EMBED,
  import_next_schema.Node_Type.BUTTON,
  import_next_schema.Node_Type.EMBED,
  import_next_schema.Node_Type.SHAPE
];
const TABLE_CELL_STYLE_PREVIEW_PLUGIN_KEY = new import_state.PluginKey(
  "tableCellStylePreview"
);
const PREVIEW_ROOT_STYLE_NAMES = [
  "--ricos-table-cell-background-color-preview",
  "--ricos-table-preview-selection-color",
  "--ricos-table-selection-overlay-z"
];
const syncTableCellStylePreview = (view) => {
  const rootStyle = TABLE_CELL_STYLE_PREVIEW_PLUGIN_KEY.getState(view.state)?.rootStyle ?? {};
  for (const name of PREVIEW_ROOT_STYLE_NAMES) {
    const value = rootStyle[name];
    if (value) {
      view.dom.style.setProperty(name, value);
    } else {
      view.dom.style.removeProperty(name);
    }
  }
};
const tableCellStylePreviewPlugin = () => new import_state.Plugin({
  key: TABLE_CELL_STYLE_PREVIEW_PLUGIN_KEY,
  state: {
    init() {
      return { cellDecorations: [] };
    },
    apply(tr, value) {
      const preview = tr.getMeta(TABLE_CELL_STYLE_PREVIEW_PLUGIN_KEY);
      return preview === void 0 ? value : preview;
    }
  },
  props: {
    decorations(state) {
      const preview = TABLE_CELL_STYLE_PREVIEW_PLUGIN_KEY.getState(state);
      const cellDecorations = preview?.cellDecorations ?? [];
      if (cellDecorations.length === 0) {
        return null;
      }
      return import_view.DecorationSet.create(
        state.doc,
        cellDecorations.map(
          ({ className, from, style, to }) => import_view.Decoration.node(from, to, {
            ...className ? { class: className } : {},
            ...style ? { style } : {}
          })
        )
      );
    }
  },
  view(view) {
    syncTableCellStylePreview(view);
    return {
      update(updatedView) {
        syncTableCellStylePreview(updatedView);
      },
      destroy() {
        for (const name of PREVIEW_ROOT_STYLE_NAMES) {
          view.dom.style.removeProperty(name);
        }
      }
    };
  }
});
const tableExtension = (0, import_plugin_commons.createRicosNodeExtension)({
  groups: ["shortcuts-enabled", "footer-disabled"],
  type: "html-node",
  reconfigure: (config, _extensions, _props, settings, services) => ({
    ...config,
    addOptions: () => ({
      services,
      ...settings,
      View: import_plugins.TableView
    })
  }),
  name: import_ricos_content.TIPTAP_TABLE_TYPE,
  createExtensionConfig() {
    return {
      name: this.name,
      group: "block collapsibleListItemBodyContent",
      selectable: true,
      isolating: true,
      draggable: true,
      content: "TABLE_ROW+",
      supportedQuickActions: TABLE_SUPPORTED_QUICK_ACTIONS,
      tableRole: "table",
      priority: 101,
      contentDOM: document.createElement("tbody"),
      addAttributes: () => ({
        containerData: null,
        dimensions: {
          default: null,
          parseHTML: (element) => {
            const dimensionsAttr = element.getAttribute("data-dimensions");
            if (!dimensionsAttr) {
              return null;
            }
            try {
              return JSON.parse(dimensionsAttr);
            } catch {
              return null;
            }
          },
          renderHTML: (attributes) => {
            if (!attributes.dimensions) {
              return {};
            }
            return { "data-dimensions": JSON.stringify(attributes.dimensions) };
          }
        },
        header: null,
        edgeMap: null,
        tableData: {
          default: null,
          parseHTML: (element) => {
            const style = element.getAttribute("style");
            if (!style) {
              return null;
            }
            const result = {};
            const borderSpacingMatch = style.match(/border-spacing:\s*(\d+)px/);
            if (borderSpacingMatch) {
              result.cellSpacing = parseInt(borderSpacingMatch[1], 10);
            }
            const cellPaddingMatch = style.match(/--ricos-table-cell-padding:\s*([^;]+)/);
            if (cellPaddingMatch) {
              const paddingValues = cellPaddingMatch[1].trim().split(/\s+/).map((v) => parseInt(v, 10)).filter((v) => !isNaN(v));
              if (paddingValues.length > 0) {
                result.cellPadding = paddingValues;
              }
            }
            return Object.keys(result).length > 0 ? result : null;
          },
          renderHTML: (attributes) => {
            if (!attributes.tableData) {
              return {};
            }
            const styles = [];
            const tableData = attributes.tableData;
            if (typeof tableData.cellSpacing === "number") {
              styles.push(`border-spacing: ${tableData.cellSpacing}px`);
            }
            if (Array.isArray(tableData.cellPadding) && tableData.cellPadding.length > 0) {
              styles.push(`--ricos-table-cell-padding: ${tableData.cellPadding.join(" ")}`);
            }
            return styles.length > 0 ? { style: styles.join("; ") } : {};
          }
        }
      }),
      parseHTML() {
        return [{ tag: "table" }];
      },
      renderHTML({ HTMLAttributes }) {
        return ["table", { ...HTMLAttributes }, ["tbody", 0]];
      },
      addProseMirrorPlugins() {
        const isMobile = this.options.services?.context?.isMobile;
        return [
          ...!isMobile ? [
            (0, import_plugins.columnResizingPlugin)({
              editor: this.editor,
              minColumnWidth: import_consts.CELL_MANUAL_MIN_WIDTH
            }),
            (0, import_plugins.rowResizingPlugin)({ editor: this.editor }),
            (0, import_plugins.handleDraggingPlugin)({ editor: this.editor })
          ] : [],
          (0, import_plugins.tableEditingPlugin)({ editor: this.editor, isMobile }),
          (0, import_plugins.cellEdgePlugin)(),
          tableCellStylePreviewPlugin()
        ];
      },
      extendNodeSchema(extension) {
        const context = {
          name: extension.name,
          options: extension.options,
          storage: extension.storage
        };
        return {
          tableRole: (0, import_tiptap.callOrReturn)((0, import_tiptap.getExtensionField)(extension, "tableRole", context))
        };
      },
      addNodeView() {
        const isMobile = this.options.services?.context?.isMobile;
        return ({ node, editor, getPos }) => new import_plugins.TableView(
          node,
          editor,
          getPos,
          {
            columnResizeHandleWidth: import_consts.RESIZE_HANDLE_SIZE,
            rowResizeHandleHeight: import_consts.ROW_RESIZE_HANDLE_SIZE
          },
          isMobile
        );
      },
      addCommands() {
        return {
          setTableCellStylePreview: (preview) => ({ tr, dispatch }) => {
            dispatch?.(
              tr.setMeta(TABLE_CELL_STYLE_PREVIEW_PLUGIN_KEY, preview ?? { cellDecorations: [] })
            );
            return true;
          },
          insertTable: (opts) => ({ state, dispatch }) => (0, import_cell_attributes.insertTable)(opts)(state, dispatch),
          addColumnBefore: () => ({ state, dispatch }) => (0, import_mutations.addColumnBeforeWithBorders)()(state, dispatch),
          addColumnAfter: () => ({ state, dispatch }) => (0, import_mutations.addColumnAfterWithBorders)()(state, dispatch),
          addColumnAtIndex: (index) => ({ state, dispatch }) => (0, import_cell_attributes.addColumnAtIndex)(index)(state, dispatch),
          deleteColumn: () => ({ state, dispatch }) => (0, import_mutations.deleteColumnWithBorders)()(state, dispatch),
          addRowBefore: () => ({ state, dispatch }) => (0, import_mutations.addRowBeforeWithBorders)()(state, dispatch),
          addRowAfter: () => ({ state, dispatch }) => (0, import_mutations.addRowAfterWithBorders)()(state, dispatch),
          addRowAtIndex: (index) => ({ state, dispatch }) => (0, import_cell_attributes.addRowAtIndex)(index)(state, dispatch),
          deleteRow: () => ({ state, dispatch }) => (0, import_mutations.deleteRowWithBorders)()(state, dispatch),
          deleteTable: () => ({ state, dispatch }) => (0, import_mutations.deleteTable)(state, dispatch),
          mergeCells: () => ({ state, dispatch }) => (0, import_mutations.mergeCellsWithBorders)()(state, dispatch),
          splitCell: () => ({ state, dispatch }) => (0, import_mutations.splitCellWithBorders)()(state, dispatch),
          toggleHeaderColumn: () => ({ state, dispatch }) => (0, import_mutations.toggleHeaderColumnCmd)()(state, dispatch),
          toggleHeaderRow: () => ({ state, dispatch }) => (0, import_mutations.toggleHeaderRowCmd)()(state, dispatch),
          mergeOrSplit: () => ({ state, dispatch }) => {
            if ((0, import_mutations.mergeCellsWithBorders)()(state, dispatch)) {
              return true;
            }
            return (0, import_mutations.splitCellWithBorders)()(state, dispatch);
          },
          setCellAttribute: (name, value) => ({ state, dispatch }) => (0, import_cell_attributes.setCellAttribute)(name, value)(state, dispatch),
          updateCellAttribute: (name, value) => ({ state, dispatch }) => (0, import_cell_attributes.updateCellAttribute)(name, value)(state, dispatch),
          toggleTableAttribute: (name) => ({ state, dispatch }) => (0, import_cell_attributes.toggleTableAttribute)(name)(state, dispatch),
          setTableAltText: (text) => ({ state, dispatch }) => (0, import_cell_attributes.setTableAltText)(text)(state, dispatch),
          goToNextCell: () => ({ state, dispatch }) => (0, import_navigation.goToNextCell)(1)(state, dispatch),
          goToPreviousCell: () => ({ state, dispatch }) => (0, import_navigation.goToNextCell)(-1)(state, dispatch),
          fixTables: () => ({ state, dispatch }) => {
            if (dispatch) {
              (0, import_fix.fixTables)(state);
            }
            return true;
          },
          setCellSelection: (pos) => ({ state, dispatch }) => (0, import_selection.setCellSelection)(pos)(state, dispatch),
          selectColumnAtIndex: (index) => ({ state, dispatch }) => (0, import_selection.selectColumnAtIndex)(index)(state, dispatch),
          selectColumn: () => ({ state, dispatch }) => (0, import_selection.selectColumnCmd)()(state, dispatch),
          selectRowAtIndex: (index) => ({ state, dispatch }) => (0, import_selection.selectRowAtIndex)(index)(state, dispatch),
          selectRow: () => ({ state, dispatch }) => (0, import_selection.selectRowCmd)()(state, dispatch),
          selectRows: (fromRow, toRow, tablePos) => ({ state, dispatch }) => (0, import_selection.selectRows)(fromRow, toRow, tablePos)(state, dispatch),
          selectColumns: (fromCol, toCol, tablePos) => ({ state, dispatch }) => (0, import_selection.selectColumns)(fromCol, toCol, tablePos)(state, dispatch),
          deleteRowAtIndex: (index) => ({ state, dispatch }) => (0, import_selection.deleteRowAtIndex)(index)(state, dispatch),
          selectWholeTable: () => ({ state, dispatch }) => (0, import_selection.selectWholeTable)()(state, dispatch),
          setTableRowHeight: (height, pos, node) => ({ state, dispatch }) => (0, import_cell_attributes.setTableRowHeight)(height, pos, node)(state, dispatch),
          distributeRows: () => ({ state, dispatch }) => (0, import_cell_attributes.distributeRows)()(state, dispatch),
          distributeColumns: () => ({ state, dispatch }) => (0, import_cell_attributes.distributeColumns)()(state, dispatch),
          setEditCell: () => ({ state, dispatch }) => (0, import_cell_attributes.setEditCell)()(state, dispatch),
          clearCell: () => ({ state, dispatch }) => (0, import_cell_attributes.clearCell)()(state, dispatch),
          setCellBorderColor: (color) => ({ state, dispatch }) => (0, import_border.setCellBorderColor)(color)(state, dispatch),
          setOutsiderCellsBorderColor: (color) => ({ state, dispatch }) => (0, import_border.setOutsiderCellsBorderColor)(color)(state, dispatch),
          setCellBorderWidth: (width) => ({ state, dispatch }) => (0, import_border.setCellBorderWidth)(width)(state, dispatch),
          setOutsiderCellsBorderWidth: (width) => ({ state, dispatch }) => (0, import_border.setOutsiderCellsBorderWidth)(width)(state, dispatch),
          setCellBorderColorBySide: (side, color) => ({ state, dispatch }) => (0, import_border.setCellBorderColorBySide)(side, color)(state, dispatch),
          setCellBorderWidthBySide: (side, width) => ({ state, dispatch }) => (0, import_border.setCellBorderWidthBySide)(side, width)(state, dispatch),
          setInnerHorizontalCellsBorderColor: (color) => ({ state, dispatch }) => (0, import_border.setInnerHorizontalCellsBorderColor)(color)(state, dispatch),
          setInnerHorizontalCellsBorderWidth: (width) => ({ state, dispatch }) => (0, import_border.setInnerHorizontalCellsBorderWidth)(width)(state, dispatch),
          setInnerVerticalCellsBorderColor: (color) => ({ state, dispatch }) => (0, import_border.setInnerVerticalCellsBorderColor)(color)(state, dispatch),
          setInnerVerticalCellsBorderWidth: (width) => ({ state, dispatch }) => (0, import_border.setInnerVerticalCellsBorderWidth)(width)(state, dispatch),
          setCellSpacing: (spacing) => ({ state, dispatch }) => (0, import_cell_attributes.setCellSpacing)(spacing)(state, dispatch),
          setCellPadding: (padding) => ({ state, dispatch }) => (0, import_cell_attributes.setCellPadding)(padding)(state, dispatch),
          reorderRows: (from, to) => ({ state, dispatch }) => (0, import_reorder.reorderRows)(from, to)(state, dispatch),
          reorderColumns: (from, to) => ({ state, dispatch }) => (0, import_reorder.reorderColumns)(from, to)(state, dispatch),
          moveColumns: (direction) => ({ state, dispatch, view }) => (0, import_reorder.moveColumns)(direction)(state, dispatch, view),
          moveRows: (direction) => ({ state, dispatch, view }) => (0, import_reorder.moveRows)(direction)(state, dispatch, view)
        };
      },
      addKeyboardShortcuts() {
        const newLine = import_keyboard_shortcuts.maybeToggleEditMode;
        const tiptapKeyboardShortcuts = import_keyboard_shortcuts.keyboardShortcuts;
        const newLineShortcuts = [];
        this.options.services.shortcuts.shortcuts.forEach((shortcut) => {
          if (shortcut.shortcut.name === "NewLine") {
            newLineShortcuts.push(shortcut);
          }
        });
        newLineShortcuts.forEach((newLineShortcut) => {
          const modifier = newLineShortcut.keys.macOs.modifiers[0];
          const key = newLineShortcut.keys.macOs.key;
          const shortcutKey = modifier ? `${modifier}-${key}` : key;
          tiptapKeyboardShortcuts[shortcutKey] = newLine;
        });
        return tiptapKeyboardShortcuts;
      }
    };
  }
});
//# sourceMappingURL=table-extension.js.map
