"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 tiptap_exports = {};
__export(tiptap_exports, {
  createSketchPlugin: () => createSketchPlugin,
  tiptapSketchExtension: () => tiptapSketchExtension
});
module.exports = __toCommonJS(tiptap_exports);
var import_ricos_types = require("./../../ricos-types/index.js");
var import_state = require("./../../tiptap/pm/state.js");
var import_plugin_commons = require("./../../plugin-commons/index.js");
var import_is_inline_text_only = require("../../ricos-common-plugins/transaction-predicates/is-inline-text-only.js");
var import_data_hooks = require("./data-hooks.js");
var import_defaults = require("./defaults.js");
var import_editor_decorations = require("./editor-decorations.js");
var import_editor_preview_state = require("./editor-preview-state.js");
var import_editor_widget_controller = require("./editor-widget-controller.js");
var import_range_tracking = require("./range-tracking.js");
const sketchPreviewState = (0, import_editor_preview_state.createSketchPreviewState)();
const SKETCH_PREVIEW_OVERRIDE = "sketchPreviewOverride";
const ADD_TO_HISTORY_META = "addToHistory";
const createSketchPlugin = (previewState = sketchPreviewState) => new import_state.Plugin({
  key: import_editor_decorations.SKETCH_PLUGIN_KEY,
  state: {
    init: (_, state) => {
      const { trackedGroups, nextRangeId } = (0, import_range_tracking.reconcileTrackedAnnotationGroups)(state, [], 1);
      return {
        decorations: (0, import_editor_decorations.buildDecorationSet)(state, trackedGroups, previewState.getOverride()),
        trackedGroups,
        nextRangeId
      };
    },
    apply: (tr, value, _oldState, newState) => {
      if (!tr.docChanged) {
        const previewOverrideChanged = !!tr.getMeta(SKETCH_PREVIEW_OVERRIDE);
        return {
          ...value,
          decorations: previewOverrideChanged ? (0, import_editor_decorations.buildDecorationSet)(newState, value.trackedGroups, previewState.getOverride()) : value.decorations
        };
      }
      const mappedTrackedGroups = (0, import_range_tracking.mapTrackedGroupPositions)(tr, value.trackedGroups);
      const markType = newState.schema.marks[import_ricos_types.Mark_Type.SKETCH];
      const canSkipFullReconcile = !!markType && (0, import_is_inline_text_only.isInlineTextOnly)(tr) && !(0, import_range_tracking.transactionInsertsSketchMark)(tr, markType) && !(0, import_range_tracking.transactionTouchesTrackedGroup)(tr, value.trackedGroups);
      const { trackedGroups, nextRangeId } = canSkipFullReconcile ? {
        trackedGroups: (0, import_range_tracking.applyFastPathReconcile)(newState.doc, mappedTrackedGroups),
        nextRangeId: value.nextRangeId
      } : (0, import_range_tracking.reconcileTrackedAnnotationGroups)(newState, mappedTrackedGroups, value.nextRangeId);
      return {
        decorations: (0, import_editor_decorations.buildDecorationSet)(newState, trackedGroups, previewState.getOverride()),
        trackedGroups,
        nextRangeId
      };
    }
  },
  props: {
    decorations(state) {
      return (0, import_editor_decorations.getPluginState)(state)?.decorations;
    }
  },
  view: (view) => (0, import_editor_widget_controller.createWidgetController)(view, previewState)
});
const tiptapSketchExtension = (0, import_plugin_commons.createRicosMarkExtension)({
  type: "mark",
  name: import_ricos_types.Mark_Type.SKETCH,
  groups: [],
  reconfigure: (config, _extensions, _props, settings) => ({
    ...config,
    addOptions() {
      return {
        HTMLAttributes: {},
        ...settings
      };
    }
  }),
  createExtensionConfig() {
    return {
      name: this.name,
      addAttributes() {
        return {
          style: {
            default: import_defaults.DEFAULT_STYLE,
            parseHTML: (element) => element.getAttribute("data-style") || import_defaults.DEFAULT_STYLE,
            renderHTML: (attrs) => ({ "data-style": attrs.style || import_defaults.DEFAULT_STYLE })
          },
          color: {
            default: import_defaults.DEFAULT_COLOR,
            parseHTML: (element) => element.getAttribute("data-color") || import_defaults.DEFAULT_COLOR,
            renderHTML: (attrs) => ({ "data-color": attrs.color || import_defaults.DEFAULT_COLOR })
          },
          animate: {
            default: import_defaults.DEFAULT_ANIMATE,
            parseHTML: (element) => element.getAttribute("data-animate") !== "false",
            renderHTML: (attrs) => ({ "data-animate": String(attrs.animate ?? import_defaults.DEFAULT_ANIMATE) })
          }
        };
      },
      parseHTML() {
        return [
          {
            tag: `span[data-hook="${import_data_hooks.SKETCH_DATA_HOOK}"]`,
            getAttrs: (node) => {
              if (typeof node === "string") {
                return false;
              }
              return {
                style: node.getAttribute("data-style") || import_defaults.DEFAULT_STYLE,
                color: node.getAttribute("data-color") || import_defaults.DEFAULT_COLOR,
                animate: node.getAttribute("data-animate") !== "false"
              };
            }
          }
        ];
      },
      renderHTML({ mark }) {
        const { style, color, animate } = mark.attrs;
        const styleKey = style || import_defaults.DEFAULT_STYLE;
        const ariaLabel = import_defaults.STYLE_TO_ARIA_LABEL[styleKey] ?? import_defaults.STYLE_TO_ARIA_LABEL[import_defaults.DEFAULT_STYLE];
        return [
          "span",
          {
            "data-hook": import_data_hooks.SKETCH_DATA_HOOK,
            "data-style": style || import_defaults.DEFAULT_STYLE,
            "data-color": color || import_defaults.DEFAULT_COLOR,
            "data-animate": String(animate ?? import_defaults.DEFAULT_ANIMATE),
            "aria-label": ariaLabel,
            style: `position: relative; z-index: ${import_defaults.TEXT_LAYER_Z_INDEX};`
          },
          0
        ];
      },
      addCommands() {
        return {
          setSketch: (attrs = {}) => ({ commands }) => {
            const animate = (0, import_defaults.getExplicitAnimate)(attrs.animate);
            commands.setMark(this.name, {
              style: attrs.style ?? import_defaults.DEFAULT_STYLE,
              color: attrs.color ?? import_defaults.DEFAULT_COLOR,
              ...animate !== void 0 && { animate }
            });
            return true;
          },
          unsetSketch: () => ({ commands }) => commands.unsetMark(this.name),
          previewSketch: (override) => ({ state, tr, dispatch }) => {
            sketchPreviewState.setOverride(override);
            if (override.animate && (0, import_range_tracking.isOverlayPreviewStyle)(override.style)) {
              sketchPreviewState.setAnimationRange({
                from: override.from,
                to: override.to
              });
            }
            sketchPreviewState.hideBackgroundMarks(state, tr, override);
            tr.setMeta(SKETCH_PREVIEW_OVERRIDE, true);
            tr.setMeta(ADD_TO_HISTORY_META, false);
            dispatch?.(tr);
            return true;
          },
          clearSketchPreview: () => ({ tr, dispatch }) => {
            if (sketchPreviewState.getOverride() === null && !sketchPreviewState.hasBackgroundRestoreRanges()) {
              return true;
            }
            sketchPreviewState.setOverride(null);
            sketchPreviewState.restoreBackgroundMarks(tr);
            tr.setMeta(SKETCH_PREVIEW_OVERRIDE, true);
            tr.setMeta(ADD_TO_HISTORY_META, false);
            dispatch?.(tr);
            return true;
          }
        };
      },
      addProseMirrorPlugins() {
        return [createSketchPlugin()];
      }
    };
  }
});
//# sourceMappingURL=tiptap.js.map
