import { Mark_Type } from "./../../ricos-types/index.js";
const getBackgroundMarkType = (state) => state.schema.marks[Mark_Type.COLOR_BACKGROUND];
const collectBackgroundRestoreRanges = (doc, markType, from, to) => {
  const ranges = [];
  doc.nodesBetween(from, to, (node, pos) => {
    if (!node.isText) {
      return true;
    }
    const mark = node.marks.find((candidate) => candidate.type === markType);
    if (mark) {
      ranges.push({
        from: Math.max(from, pos),
        to: Math.min(to, pos + node.nodeSize),
        mark
      });
    }
    return true;
  });
  return ranges;
};
const createSketchPreviewState = () => {
  let animationRange = null;
  let override = null;
  let backgroundRestoreRanges = [];
  const restoreBackgroundMarks = (tr) => {
    const ranges = backgroundRestoreRanges;
    backgroundRestoreRanges = [];
    const docSize = tr.doc.content.size;
    for (const { from, to, mark } of ranges) {
      const safeFrom = Math.max(0, Math.min(from, docSize));
      const safeTo = Math.max(0, Math.min(to, docSize));
      if (safeFrom < safeTo) {
        tr.addMark(safeFrom, safeTo, mark);
      }
    }
  };
  const hideBackgroundMarks = (state, tr, nextOverride) => {
    restoreBackgroundMarks(tr);
    const markType = getBackgroundMarkType(state);
    if (!markType || nextOverride.style === "CLASSIC") {
      return;
    }
    const nextRestoreRanges = collectBackgroundRestoreRanges(
      tr.doc,
      markType,
      nextOverride.from,
      nextOverride.to
    );
    if (nextRestoreRanges.length === 0) {
      return;
    }
    backgroundRestoreRanges = nextRestoreRanges;
    tr.removeMark(nextOverride.from, nextOverride.to, markType);
  };
  return {
    getOverride: () => override,
    setOverride: (nextOverride) => {
      override = nextOverride;
    },
    getAnimationRange: () => animationRange,
    setAnimationRange: (range) => {
      animationRange = range;
    },
    consumeAnimationRange: () => {
      const range = animationRange;
      animationRange = null;
      return range;
    },
    hasBackgroundRestoreRanges: () => backgroundRestoreRanges.length > 0,
    hideBackgroundMarks,
    restoreBackgroundMarks
  };
};
export {
  createSketchPreviewState
};
//# sourceMappingURL=editor-preview-state.js.map
