"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 ricos_styles_exports = {};
__export(ricos_styles_exports, {
  getLineHeightStyleBySelectedNode: () => getLineHeightStyleBySelectedNode,
  getStylesDecorationBySelectedNode: () => getStylesDecorationBySelectedNode,
  ricosStyles: () => ricosStyles
});
module.exports = __toCommonJS(ricos_styles_exports);
var import_lodash = __toESM(require("lodash"));
var import_v1 = require("./../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_ricos_styles = require("./../ricos-styles/index.js");
var import_ricos_types = require("./../ricos-types/index.js");
var import_tiptap = require("./../tiptap/index.js");
var import_transform = require("./../tiptap/pm/transform.js");
var import_create_ricos_extension = require("./create-ricos-extension/index.js");
const STEP_TYPE = "setDocAttr";
const DOCUMENT_STYLES_MARKS = [
  import_ricos_types.Mark_Type.BOLD,
  import_ricos_types.Mark_Type.ITALIC,
  import_ricos_types.Mark_Type.COLOR_BACKGROUND,
  import_ricos_types.Mark_Type.COLOR_FOREGROUND,
  import_ricos_types.Mark_Type.FONT_SIZE
];
class SetDocAttrStep extends import_transform.Step {
  constructor(key, value) {
    super();
    this.key = key;
    this.value = value;
    this.key = key;
    this.value = value;
  }
  get stepType() {
    return STEP_TYPE;
  }
  apply(doc) {
    this.prevValue = doc.attrs[this.key];
    if (doc.attrs === doc.type.defaultAttrs) {
      doc.attrs = Object.assign({}, doc.attrs);
    }
    doc.attrs[this.key] = this.value;
    return import_transform.StepResult.ok(doc);
  }
  invert() {
    return new SetDocAttrStep(this.key, this.prevValue);
  }
  // position never changes so map should always return same step
  map() {
    return this;
  }
  toJSON() {
    return {
      stepType: this.stepType,
      key: this.key,
      value: this.value
    };
  }
  static fromJSON(schema, json) {
    return new SetDocAttrStep(json.key, json.value);
  }
  static register() {
    try {
      import_transform.Step.jsonID(STEP_TYPE, SetDocAttrStep);
    } catch (err) {
      if (err.message !== `Duplicate use of step JSON ID ${STEP_TYPE}`) {
        throw err;
      }
    }
    return true;
  }
}
const getStylesDecorationBySelectedNode = (decorationType, {
  state,
  styles,
  pmConverters
}) => {
  const { from, to } = state.selection;
  let node;
  state.doc.nodesBetween(from, to, (currNode) => {
    if ([import_v1.Node_Type.PARAGRAPH, import_v1.Node_Type.HEADING].includes(currNode?.type?.name)) {
      node = pmConverters.fromPmNode(currNode.toJSON());
      return false;
    }
  });
  return node && styles.getDecoration(node, decorationType);
};
const getLineHeightStyleBySelectedNode = ({
  tiptapEditor,
  styles
}) => {
  const { state, view } = tiptapEditor;
  const { from, to, $from } = state.selection;
  const domNode = $from.depth > 0 ? view.nodeDOM($from.before($from.depth)) : null;
  let node;
  state.doc.nodesBetween(from, to, (currNode) => {
    if ([import_v1.Node_Type.PARAGRAPH, import_v1.Node_Type.HEADING].includes(currNode?.type?.name)) {
      node = currNode.toJSON();
      return false;
    }
  });
  return node ? styles.getComputedLineHeight(node, domNode) : void 0;
};
const ricosStyles = (0, import_create_ricos_extension.createRicosFunctionalExtension)({
  type: "extension",
  groups: [],
  name: "ricos-styles-commands",
  reconfigure: (config, _extensions, _ricosProps, _settings, services) => {
    return {
      ...config,
      addOptions() {
        return {
          styles: services.styles,
          converters: services.converters
        };
      }
    };
  },
  createExtensionConfig() {
    return {
      name: this.name,
      addCommands() {
        return {
          getStylesDecorationBySelectedNode: (decorationType) => ({ state }) => {
            const { from, to } = state.selection;
            let node;
            state.doc.nodesBetween(from, to, (currNode) => {
              if ([import_v1.Node_Type.PARAGRAPH, import_v1.Node_Type.HEADING].includes(currNode?.type?.name)) {
                node = this.options.converters.fromPmNode(currNode.toJSON());
                return false;
              }
            });
            return node && this.options.styles.getDecoration(
              node,
              decorationType
            );
          },
          updateDocumentStyleBySelectedNode: () => ({ state, chain }) => {
            const { from, to } = state.selection;
            let node, proseNode;
            state.doc.nodesBetween(from, to, (currNode) => {
              if ([import_v1.Node_Type.PARAGRAPH, import_v1.Node_Type.HEADING].includes(currNode?.type?.name)) {
                node = this.options.converters.fromPmNode(currNode.toJSON());
                proseNode = currNode;
                return false;
              }
            });
            if (!proseNode || !node || !import_ricos_styles.DocumentStyle.isNodeTransformable(node)) {
              return false;
            }
            const documentStyleEntity = import_ricos_styles.DocumentStyle.fromNode(node);
            return chain().focus().updateDocumentStyle(documentStyleEntity.toContent()).command(({ state: state2, commands }) => {
              state2.doc.descendants((node2, pos) => {
                if (node2.isTextblock && node2.type.name === proseNode.type.name) {
                  commands.unsetAllDocumentStyleMarksByNode(node2);
                  commands.unsetAllDocumentStyleAttrsByNode(node2, pos);
                }
              });
              return true;
            }).run();
          },
          unsetAllDocumentStyleMarksByNode: (node) => ({ editor, tr, state }) => {
            const nodeElement = document.body.querySelector(`[data-ricos-id="${node.attrs.id}"]`);
            if (nodeElement) {
              const start = editor.view.posAtDOM(nodeElement, 0);
              const end = start + node.content.size;
              (0, import_tiptap.getMarksBetween)(start, end, state.doc).forEach((markRang) => {
                if (DOCUMENT_STYLES_MARKS.includes(markRang.mark.type.name)) {
                  tr.removeMark(start, end, markRang.mark);
                }
              });
            }
            return true;
          },
          unsetAllDocumentStyleAttrsByNode: (node, pos) => ({ tr }) => {
            const attrs = import_lodash.default.omit(node.attrs, ["style", "textStyle.lineHeight"]);
            tr.setNodeMarkup(pos, void 0, attrs);
            return true;
          },
          resetDocumentStyleByNodeType: (nodeType) => ({ state }) => {
            const updatedDocumentStyle = new import_ricos_styles.DocumentStyle(state.doc.attrs.documentStyle).resetStyle(nodeType).toContent();
            state.tr.step(new SetDocAttrStep("documentStyle", updatedDocumentStyle));
            this.options.styles.setDocumentStyle(updatedDocumentStyle);
            return true;
          },
          updateDocumentStyle: (documentStyle) => ({ state }) => {
            const updatedDocumentStyle = new import_ricos_styles.DocumentStyle(state.doc.attrs.documentStyle).mergeWith(documentStyle).toContent();
            state.tr.step(new SetDocAttrStep("documentStyle", updatedDocumentStyle));
            this.options.styles.setDocumentStyle(updatedDocumentStyle);
            return true;
          }
        };
      }
    };
  }
});
//# sourceMappingURL=ricos-styles.js.map
