"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 extension_exports = {};
__export(extension_exports, {
  HEADER_NAMES: () => HEADER_NAMES,
  heading: () => heading
});
module.exports = __toCommonJS(extension_exports);
var import_v1 = require("./../../ricos-schema/legacy/wix/rich_content/v1/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_direction_attribute = require("../decoration-plugins/direction-attribute.js");
var import_span_wrapper = require("../decoration-plugins/span-wrapper.js");
var import_is_inline_text_only = require("../transaction-predicates/is-inline-text-only.js");
var import_only_changes_unrelated_attrs = require("../transaction-predicates/only-changes-unrelated-attrs.js");
var import_headings_scss = __toESM(require("./headings-scss.js"));
const TEXTBLOCK_ID_RELEVANT_ATTRS = /* @__PURE__ */ new Set(["id"]);
const HEADER_NAMES = ["One", "Two", "Three", "Four", "Five", "Six"];
const heading = (0, import_plugin_commons.createRicosNodeExtension)({
  groups: ["no-trailing-node"],
  type: "html-node",
  name: import_v1.Node_Type.HEADING,
  reconfigure: (config, _extensions, _props, settings, services) => ({
    ...config,
    addOptions() {
      return {
        levels: [1, 2, 3, 4, 5, 6],
        ...settings
      };
    },
    addProseMirrorPlugins() {
      return [
        createTextblockIdDecorationPlugin({
          includeChildren: Boolean(this.options.includeChildren)
        }),
        (0, import_span_wrapper.createSpanWrapperDecorationPlugin)([import_v1.Node_Type.HEADING]),
        (0, import_direction_attribute.createDirectionAttributeDecorationPlugin)(import_v1.Node_Type.HEADING, services.context.localeContent)
      ];
    }
  }),
  createExtensionConfig({ mergeAttributes, textblockTypeInputRule }) {
    return {
      name: this.name,
      content: "inline*",
      group: "block smartBlockCellContent layoutCellContent collapsibleListItemTitleContent collapsibleListItemBodyContent tableCellContent listItemFirstChildContent listItemSecondChildContent",
      defining: true,
      addAttributes() {
        return {
          level: 0,
          textStyle: {
            default: null,
            parseHTML: (element) => {
              try {
                const attrValue = element.getAttribute("textstyle");
                return attrValue ? JSON.parse(attrValue) : null;
              } catch {
                return null;
              }
            }
          },
          indentation: null,
          renderedLevel: null
        };
      },
      parseHTML() {
        return this.options.levels.map((level) => ({
          tag: `h${level}`,
          attrs: { level }
        }));
      },
      renderHTML({ node, HTMLAttributes }) {
        const hasLevel = this.options.levels.includes(node.attrs.level);
        const level = hasLevel ? node.attrs.level : this.options.levels[0];
        const hasRenderedLevel = this.options.levels.includes(node.attrs.renderedLevel);
        const tagLevel = hasRenderedLevel ? node.attrs.renderedLevel : level;
        const attrs = mergeAttributes(
          this.options.HTMLAttributes,
          {
            ...HTMLAttributes,
            textStyle: JSON.stringify(HTMLAttributes.textStyle)
          },
          {
            class: import_headings_scss.default[`header${HEADER_NAMES[level - 1]}`]
          }
        );
        return [`h${tagLevel}`, attrs, 0];
      },
      addCommands() {
        return {
          setHeading: (attributes) => ({ commands }) => {
            if (!this.options.levels.includes(attributes.level)) {
              return false;
            }
            return commands.updateTextNode(this.name, attributes);
          },
          toggleHeading: (attributes) => ({ commands }) => {
            if (!this.options.levels.includes(attributes.level)) {
              return false;
            }
            return commands.toggleTextNode(this.name, import_v1.Node_Type.PARAGRAPH, attributes);
          }
        };
      },
      addKeyboardShortcuts() {
        return this.options.levels.reduce(
          (items, level) => ({
            ...items,
            ...{
              [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level })
            }
          }),
          {}
        );
      },
      addInputRules() {
        return this.options.levels.map((level) => {
          return textblockTypeInputRule({
            find: new RegExp(`^(#{1,${level}})\\s$`),
            type: this.type,
            getAttributes: {
              level
            }
          });
        });
      }
    };
  }
});
const createTextblockIdDecorationPlugin = ({
  includeChildren = false
} = {}) => {
  const key = new import_state.PluginKey("textblock-id");
  return new import_state.Plugin({
    key,
    state: {
      init: (_config, state) => buildTextblockIdDecorations(state.doc, includeChildren),
      apply: (tr, prev) => {
        if (!tr.docChanged) {
          return prev;
        }
        if ((0, import_is_inline_text_only.isInlineTextOnly)(tr)) {
          return prev.map(tr.mapping, tr.doc);
        }
        if ((0, import_only_changes_unrelated_attrs.onlyChangesUnrelatedAttrs)(tr, TEXTBLOCK_ID_RELEVANT_ATTRS)) {
          return prev;
        }
        return buildTextblockIdDecorations(tr.doc, includeChildren);
      }
    },
    props: {
      decorations(state) {
        return key.getState(state);
      }
    }
  });
};
const buildTextblockIdDecorations = (doc, includeChildren) => {
  const decorations = [];
  doc.descendants((node, pos) => {
    if (!node.isTextblock || !node.attrs.id) {
      return;
    }
    decorations.push(
      import_view.Decoration.node(pos, pos + node.nodeSize, {
        "data-ricos-id": node.attrs.id
      })
    );
    if (!includeChildren) {
      return false;
    }
  });
  return import_view.DecorationSet.create(doc, decorations);
};
//# sourceMappingURL=extension.js.map
