import { Node_Type } from "./../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { Plugin, PluginKey } from "./../../tiptap/pm/state.js";
import { Decoration, DecorationSet } from "./../../tiptap/pm/view.js";
import { createRicosNodeExtension } from "./../../plugin-commons/index.js";
import { createDirectionAttributeDecorationPlugin } from "../decoration-plugins/direction-attribute.js";
import { createSpanWrapperDecorationPlugin } from "../decoration-plugins/span-wrapper.js";
import { isInlineTextOnly } from "../transaction-predicates/is-inline-text-only.js";
import { onlyChangesUnrelatedAttrs } from "../transaction-predicates/only-changes-unrelated-attrs.js";
import styles from "./headings-scss.js";
const TEXTBLOCK_ID_RELEVANT_ATTRS = /* @__PURE__ */ new Set(["id"]);
const HEADER_NAMES = ["One", "Two", "Three", "Four", "Five", "Six"];
const heading = createRicosNodeExtension({
  groups: ["no-trailing-node"],
  type: "html-node",
  name: 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)
        }),
        createSpanWrapperDecorationPlugin([Node_Type.HEADING]),
        createDirectionAttributeDecorationPlugin(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: styles[`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, 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 PluginKey("textblock-id");
  return new Plugin({
    key,
    state: {
      init: (_config, state) => buildTextblockIdDecorations(state.doc, includeChildren),
      apply: (tr, prev) => {
        if (!tr.docChanged) {
          return prev;
        }
        if (isInlineTextOnly(tr)) {
          return prev.map(tr.mapping, tr.doc);
        }
        if (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(
      Decoration.node(pos, pos + node.nodeSize, {
        "data-ricos-id": node.attrs.id
      })
    );
    if (!includeChildren) {
      return false;
    }
  });
  return DecorationSet.create(doc, decorations);
};
export {
  HEADER_NAMES,
  heading
};
//# sourceMappingURL=extension.js.map
