"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 overlay_handle_exports = {};
__export(overlay_handle_exports, {
  createOverlayHandle: () => createOverlayHandle,
  translateRectsToContainerSpace: () => translateRectsToContainerSpace
});
module.exports = __toCommonJS(overlay_handle_exports);
var import_resolve_css_color = require("./../../_shared/resolve-css-color.js");
var import_defaults = require("./defaults.js");
var import_draw_rough_shapes = require("./draw-rough-shapes.js");
const SVGNS = "http://www.w3.org/2000/svg";
const SKETCH_CLASS = "sketch";
const KEYFRAMES_STYLE_ID = "sketch-keyframes";
const KEYFRAMES = `@keyframes sketch-dash { to { stroke-dashoffset: 0 } }`;
const HOST_STYLE_ID = "sketch-host";
const HOST_STYLE = `.ProseMirror :has(> [data-hook="sketch-widget"]) { position: relative; z-index: 0; }`;
const SVG_FIXED_CSS_SIZE = 100;
let cachedRendererPromise = null;
const loadRenderer = () => {
  if (!cachedRendererPromise) {
    cachedRendererPromise = Promise.resolve().then(() => __toESM(require("roughjs/bin/renderer.js"))).then(
      (mod) => mod
    );
  }
  return cachedRendererPromise;
};
const ensureGlobalStyle = (id, css) => {
  if (document.getElementById(id)) {
    return;
  }
  const styleEl = document.createElement("style");
  styleEl.id = id;
  styleEl.textContent = css;
  document.head.appendChild(styleEl);
};
const ensureKeyframes = () => ensureGlobalStyle(KEYFRAMES_STYLE_ID, KEYFRAMES);
const ensureHostStyle = () => ensureGlobalStyle(HOST_STYLE_ID, HOST_STYLE);
const createOverlaySvg = () => {
  const svg = document.createElementNS(SVGNS, "svg");
  svg.setAttribute("class", SKETCH_CLASS);
  const style = svg.style;
  style.position = "absolute";
  style.top = "0";
  style.left = "0";
  style.width = `${SVG_FIXED_CSS_SIZE}px`;
  style.height = `${SVG_FIXED_CSS_SIZE}px`;
  style.overflow = "visible";
  style.pointerEvents = "none";
  return svg;
};
const translateRectsToContainerSpace = (container, rects) => {
  const bcr = container.getBoundingClientRect();
  const cssWidth = container.clientWidth;
  const cssHeight = container.clientHeight;
  const scaleX = cssWidth > 0 && bcr.width > 0 ? bcr.width / cssWidth : 1;
  const scaleY = cssHeight > 0 && bcr.height > 0 ? bcr.height / cssHeight : scaleX;
  return rects.map((rect) => ({
    x: (rect.left - bcr.left) / scaleX,
    y: (rect.top - bcr.top) / scaleY,
    w: rect.width / scaleX,
    h: rect.height / scaleY
  }));
};
const measurePathLength = (path) => {
  try {
    const length = path.getTotalLength();
    return Number.isFinite(length) ? length : 0;
  } catch {
    return 0;
  }
};
const clearChildren = (node) => {
  while (node.firstChild) {
    node.removeChild(node.firstChild);
  }
};
const createPath = (color, d, strokeWidth) => {
  const path = document.createElementNS(SVGNS, "path");
  path.setAttribute("d", d);
  path.setAttribute("fill", "none");
  path.setAttribute("stroke", (0, import_resolve_css_color.resolveCssColor)(color) ?? color);
  path.setAttribute("stroke-width", String(strokeWidth));
  return path;
};
const animatePaths = (paths, groupDelay, totalDuration) => {
  if (paths.length === 0) {
    return;
  }
  const lengths = paths.map(measurePathLength);
  const totalLength = lengths.reduce((sum, length) => sum + length, 0);
  let offset = 0;
  paths.forEach((path, index) => {
    const length = lengths[index];
    const duration = totalLength > 0 ? totalDuration * (length / totalLength) : 0;
    path.style.strokeDasharray = String(length);
    path.style.strokeDashoffset = String(length);
    path.style.animation = `sketch-dash ${duration}ms ease-out ${groupDelay + offset}ms forwards`;
    offset += duration;
  });
};
const renderInto = (svg, renderer, opts, precomputedLocalRects) => {
  clearChildren(svg);
  if (opts.rects.length === 0) {
    return [];
  }
  const localRects = precomputedLocalRects ?? translateRectsToContainerSpace(opts.container, opts.rects);
  const totalWidth = localRects.reduce((sum, r) => sum + r.w, 0);
  const allPaths = [];
  let cumulativeDelay = 0;
  for (const rect of localRects) {
    const shapePaths = (0, import_draw_rough_shapes.generateShapePaths)({
      renderer,
      rect,
      style: opts.style,
      seed: opts.seed
    });
    const rectPaths = shapePaths.map(
      ({ d, strokeWidth }) => createPath(opts.color, d, strokeWidth)
    );
    rectPaths.forEach((p) => svg.appendChild(p));
    const rectDuration = totalWidth > 0 ? import_defaults.ANIMATION_DURATION_MS * (rect.w / totalWidth) : 0;
    if (opts.animate) {
      animatePaths(rectPaths, cumulativeDelay, rectDuration);
    }
    cumulativeDelay += rectDuration;
    allPaths.push(...rectPaths);
  }
  return allPaths;
};
const createOverlayHandle = (overlay) => {
  ensureKeyframes();
  ensureHostStyle();
  const svg = createOverlaySvg();
  overlay.appendChild(svg);
  let renderer = null;
  let generation = 0;
  const draw = (opts, requestGeneration, r, precomputedLocalRects) => {
    if (requestGeneration !== generation) {
      return;
    }
    renderInto(svg, r, opts, precomputedLocalRects);
    opts.onRendered?.();
  };
  return {
    redraw: (opts) => {
      generation += 1;
      const current = generation;
      if (renderer) {
        draw(opts, current, renderer);
        return;
      }
      const localRects = translateRectsToContainerSpace(opts.container, opts.rects);
      void loadRenderer().then((r) => {
        renderer = r;
        draw(opts, current, r, localRects);
      });
    },
    remove: () => {
      generation += 1;
      svg.remove();
    }
  };
};
//# sourceMappingURL=overlay-handle.js.map
