var K = Object.defineProperty;
var j = (o, e, t) => e in o ? K(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
var u = (o, e, t) => j(o, typeof e != "symbol" ? e + "" : e, t);
import { E as B, a as y, b as D, c as M, d as E, V as P, S as Z } from "./index-Crnj0IHn.mjs";
import { isEqual as W, isString as _, clone as J, throttle as Q } from "lodash";
import "white-web-sdk";
import "spritejs";
import "lz-string";
import "clipper-lib";
import "lineclip";
import "xss";
import "react-dom";
import "react";
import * as z from "markmap-view";
import { Transformer as ee } from "markmap-lib";
import { O as te } from "./ObserverMap-BudneEfB.mjs";
class re {
  constructor() {
    u(this, "threadEngine");
  }
  registerBackgroundThread(e) {
    return this.threadEngine = e, this;
  }
}
class ae extends re {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", B.CopyNode);
  }
  async consume(t) {
    const { msgType: r, dataType: s, emitEventType: i } = t;
    if (r === y.FullWork && s === D.Local && i === this.emitEventType)
      return this.consumeForLocalWorker(t), !0;
  }
  async consumeForLocalWorker(t) {
    var s;
    const { workId: r } = t;
    r && await ((s = this.threadEngine) == null ? void 0 : s.consumeFull(t));
  }
}
class se {
  constructor(e) {
    u(this, "builders", /* @__PURE__ */ new Map());
    this.builders = new Map(e.map((t) => [t, this.build(t)]));
  }
  build(e) {
    switch (e) {
      case B.CopyNode:
        return new ae();
    }
  }
  registerForBackgroundThread(e) {
    return this.builders.forEach((t) => {
      t && t.registerBackgroundThread(e);
    }), this;
  }
  async consumeForBackgroundThread(e) {
    for (const t of this.builders.values())
      if (await (t == null ? void 0 : t.consume(e)))
        return !0;
    return !1;
  }
}
let N = null, C = null, $ = !1;
function q(o) {
  return !o || typeof o != "string" ? !1 : /```\s*mermaid[\s\S]*?```/i.test(o);
}
async function ie() {
  return N || C || (C = import("mermaid").then((o) => (N = o, C = null, o)).catch((o) => {
    throw C = null, o;
  }), C);
}
async function ne() {
  const o = await ie();
  return $ || (o.default.initialize({
    startOnLoad: !1,
    theme: "default"
  }), $ = !0), o;
}
function oe() {
  return (N == null ? void 0 : N.default) || null;
}
const T = class T {
  constructor() {
    // 使用 workId 作为 key，存储每个实例的 mermaid 代码块
    u(this, "mermaidCodeBlocksByWorkId", /* @__PURE__ */ new Map());
  }
  /**
   * 获取 MermaidManager 单例实例
   */
  static getInstance() {
    return T.instance || (T.instance = new T()), T.instance;
  }
  /**
   * 生成唯一的 mermaid ID
   */
  generateId() {
    return `mermaid-${Math.random().toString(36).substr(2, 9)}`;
  }
  /**
   * 生成 mermaid HTML 容器
   * @param id mermaid ID
   * @param mermaidCode mermaid 代码（可选，如果提供则存储）
   * @param workId 工作 ID（用于命名空间隔离）
   * @returns HTML 字符串
   */
  createContainer(e, t, r) {
    if (t && r) {
      let s = this.mermaidCodeBlocksByWorkId.get(r);
      s || (s = /* @__PURE__ */ new Map(), this.mermaidCodeBlocksByWorkId.set(r, s)), s.set(e, t);
    }
    return `<div class="mermaid-container" data-mermaid-id="${e}"><div class="mermaid-placeholder" id="${e}">正在渲染图表...</div></div>`;
  }
  /**
   * 获取 mermaid 代码块
   * @param id mermaid ID
   * @param workId 工作 ID（用于命名空间隔离）
   * @returns mermaid 代码或 undefined
   */
  getCode(e, t) {
    const r = this.mermaidCodeBlocksByWorkId.get(t);
    return r == null ? void 0 : r.get(e);
  }
  /**
   * 清空指定 workId 的 mermaid 代码块
   * @param workId 工作 ID（如果未提供，清空所有）
   */
  clear(e) {
    e ? this.mermaidCodeBlocksByWorkId.delete(e) : this.mermaidCodeBlocksByWorkId.clear();
  }
  /**
   * 扩展 markdown-it 的渲染规则，处理 mermaid 代码块
   * @param transformer Transformer 实例
   * @param workId 工作 ID（用于命名空间隔离）
   */
  extendMarkdown(e, t) {
    const r = e.md.renderer, s = r.rules.fence, i = this;
    r.rules.fence = (a, n, c, h, g) => {
      const p = a[n];
      if (p.info.trim() === "mermaid") {
        const f = i.generateId();
        return i.createContainer(f, p.content, t);
      }
      return s ? s(a, n, c, h, g) : "";
    };
  }
  // 为了向后兼容，保留静态方法（内部使用单例）
  static generateId() {
    return T.getInstance().generateId();
  }
  static createContainer(e, t, r) {
    return T.getInstance().createContainer(
      e,
      t,
      r
    );
  }
  static getCode(e, t) {
    return T.getInstance().getCode(e, t);
  }
  static clear(e) {
    T.getInstance().clear(e);
  }
  static extendMarkdown(e, t) {
    T.getInstance().extendMarkdown(e, t);
  }
};
u(T, "instance", null);
let O = T;
class b {
  /**
   * 检查 markmap 节点及其子节点是否包含 mermaid 代码块
   * @param node markmap 节点数据
   * @returns 如果节点或其子节点包含 mermaid 代码块，返回 true
   */
  static checkNodeHasMermaid(e) {
    if (!e)
      return !1;
    if (e.content && typeof e.content == "string" && (e.content.includes('class="mermaid-container"') || e.content.includes("class='mermaid-container'") || e.content.includes("data-mermaid-id=") || e.content.includes("mermaid-placeholder")))
      return !0;
    if (e.children && Array.isArray(e.children)) {
      for (const t of e.children)
        if (b.checkNodeHasMermaid(t))
          return !0;
    }
    return !1;
  }
  /**
   * 等待 DOM 更新后渲染 Mermaid 图表
   * @param svgElement SVG 元素
   * @param workId 工作 ID
   * @returns Promise<void>
   */
  static async renderMermaidAfterDOMUpdate(e, t) {
    await b.renderMermaidBlocks(e, t);
  }
  /**
   * 渲染所有 mermaid 容器中的图表
   * @param svgElement SVG 元素
   * @param workId 工作 ID
   * @returns Promise<void>
   */
  static async renderMermaidBlocks(e, t) {
    if (!e)
      return;
    try {
      await ne();
    } catch (n) {
      console.error("[renderMermaidBlocks] error: ", n);
      return;
    }
    const r = oe();
    if (!r)
      return;
    let s = null, i = !1;
    for (let n = 0; n < 30; n++) {
      const c = e.querySelectorAll("foreignObject");
      if (s = e.querySelectorAll(".mermaid-container"), s.length > 0 || (c.length > 0 && (i = !0), await new Promise((h) => setTimeout(h, 50)), i && n >= 20))
        break;
    }
    if (!s || s.length === 0)
      return;
    const a = Array.from(s).map(
      async (n, c) => {
        const h = n, g = h.getAttribute("data-mermaid-id"), p = g ? O.getCode(g, t) : void 0, d = h.querySelector(
          ".mermaid-placeholder"
        );
        if (!(!d || !p))
          try {
            const w = `mermaid-${t.replace(/[^a-zA-Z0-9_-]/g, "-")}-${Date.now()}-${c}`, { svg: v } = await r.render(w, p);
            if (d && d.parentNode) {
              const I = document.createElement("div");
              I.innerHTML = v;
              const l = I.querySelector("svg");
              if (l) {
                if (!l.getAttribute("viewBox") && l.getAttribute("width") && l.getAttribute("height")) {
                  const S = l.getAttribute("width"), k = l.getAttribute("height"), x = parseFloat((S == null ? void 0 : S.replace(/px|%/, "")) || "0"), A = parseFloat(
                    (k == null ? void 0 : k.replace(/px|%/, "")) || "0"
                  );
                  x > 0 && A > 0 && l.setAttribute(
                    "viewBox",
                    `0 0 ${x} ${A}`
                  );
                }
                l.style.display = "block", l.style.maxWidth = "100%", l.style.width = "auto", l.style.height = "auto", l.style.overflow = "visible", l.style.verticalAlign = "top", l.style.objectFit = "contain";
                const m = document.createElement("div");
                m.className = "mermaid-wrapper", m.style.width = "100%", m.style.height = "auto", m.style.overflow = "hidden", m.style.display = "inline-block", m.style.verticalAlign = "top", m.style.margin = "0", m.style.padding = "0", m.style.boxSizing = "border-box", m.style.position = "relative", this.isSafari() && (m.style.clipPath = "inset(100% 0 0 0)", m.style.pointerEvents = "none"), m.appendChild(l), l.style.width = "100%", l.style.height = "100%", l.style.maxWidth = "100%", l.style.maxHeight = "100%", l.style.objectFit = "contain", l.setAttribute("data-type", "mermaid"), this.isSafari() && (l.style.opacity = "0"), d.parentNode.replaceChild(m, d);
              } else
                d.outerHTML = v;
            }
          } catch (f) {
            const w = f instanceof Error ? f.message : String(f);
            d && (d.textContent = `Mermaid 渲染失败: ${w}`, d.style.color = "red", d.style.fontSize = "12px");
          }
      }
    );
    await Promise.all(a);
  }
  /**
   * 检测是否是 Safari 浏览器
   * @returns 如果是 Safari 返回 true，否则返回 false
   */
  static isSafari() {
    const e = navigator.userAgent.toLowerCase(), t = e.indexOf("safari") !== -1 && e.indexOf("chrome") === -1 && e.indexOf("chromium") === -1, r = !!(navigator.vendor && navigator.vendor.indexOf("Apple") !== -1);
    return t || r;
  }
  /**
   * 将 mermaid SVG 从 foreignObject 移出，直接添加到 markmap SVG 中（Safari 兼容性处理）
   * 克隆 mermaid SVG 元素，设置正确的尺寸和位置，然后将 foreignObject 中的 mermaid-container 透明度设为 0
   * @param svgElement markmap SVG 元素
   * @returns Promise<void>
   */
  static async transformMermaidSvgToMarkmapSvg(e) {
    if (!e)
      return;
    await new Promise((a) => setTimeout(a, 200));
    const t = e.querySelectorAll(
      'g[data-mermaid-wrapper][data-mermaid-clone="true"]'
    ), r = e.querySelectorAll("foreignObject"), s = /* @__PURE__ */ new Set();
    if (r.forEach((a) => {
      const n = a.querySelector(
        ".mermaid-container"
      ), c = n == null ? void 0 : n.getAttribute("data-mermaid-id");
      c && s.add(c);
    }), t.forEach((a) => {
      const n = a.getAttribute("data-mermaid-id");
      n && !s.has(n) && a.remove();
    }), r.length === 0)
      return;
    const i = Array.from(r).map(
      async (a) => {
        let n = a.querySelector(
          'svg[data-type="mermaid"]'
        );
        if (!n) {
          const g = a.querySelector(".mermaid-wrapper");
          g && (n = g.querySelector(
            'svg[data-type="mermaid"]'
          ));
        }
        if (!n)
          return;
        const c = a.querySelector(
          ".mermaid-container"
        ), h = c == null ? void 0 : c.getAttribute("data-mermaid-id");
        if (h)
          try {
            const g = parseFloat(a.getAttribute("x") || "0"), p = parseFloat(a.getAttribute("y") || "0"), d = parseFloat(
              a.getAttribute("width") || "0"
            ), f = parseFloat(
              a.getAttribute("height") || "0"
            );
            if (d <= 0 || f <= 0)
              return;
            const w = a.parentElement;
            if (!w || w.tagName !== "g")
              return;
            let v = w.getAttribute("transform");
            if (!v)
              v = `translate(${g}, ${p})`;
            else {
              const k = v.match(
                /translate\(([^,]+),([^)]+)\)/
              );
              if (k) {
                const x = parseFloat(k[1]), A = parseFloat(k[2]), F = x + g, R = A + p;
                v = v.replace(
                  /translate\([^)]+\)/,
                  `translate(${F}, ${R})`
                );
              } else
                v = `translate(${g}, ${p}) ${v}`;
            }
            const I = e.querySelector(
              `g[data-mermaid-wrapper][data-mermaid-id="${h}"][data-mermaid-clone="true"]`
            );
            let l;
            if (I) {
              l = I;
              const k = l.querySelector('svg[data-type="mermaid"]');
              k && l.removeChild(k);
            } else
              l = document.createElementNS(
                "http://www.w3.org/2000/svg",
                "g"
              ), l.setAttribute("data-mermaid-wrapper", "true"), l.setAttribute("data-mermaid-clone", "true"), l.setAttribute("data-mermaid-id", h);
            l.setAttribute("transform", v);
            const m = n.cloneNode(!0);
            if (m.setAttribute("width", d.toString()), m.setAttribute("height", f.toString()), m.setAttribute("data-mermaid-transformed", "true"), m.style.width = "", m.style.height = "", m.style.maxWidth = "", m.style.maxHeight = "", m.style.transform = "", m.style.transformOrigin = "", m.style.display = "block", m.style.overflow = "visible", m.style.opacity = "1", !m.getAttribute("viewBox")) {
              const k = m.getAttribute("width"), x = m.getAttribute("height");
              if (k && x) {
                const A = parseFloat(
                  k.replace(/px|%/, "") || "0"
                ), F = parseFloat(
                  x.replace(/px|%/, "") || "0"
                );
                A > 0 && F > 0 && m.setAttribute(
                  "viewBox",
                  `0 0 ${A} ${F}`
                );
              }
            }
            l.appendChild(m), I || (w && w.parentNode ? w.parentNode.insertBefore(l, w.nextSibling) : e.appendChild(l)), c && (c.style.opacity = "0", c.style.pointerEvents = "none");
          } catch (g) {
            console.error("[transformMermaidSvgToMarkmapSvg] error: ", g);
          }
      }
    );
    await Promise.all(i);
  }
  /**
   * 在 root 数据中注入 mermaid HTML
   * 找到包含 mermaid 代码块的节点，将 HTML 添加到其 content 中
   * @param root markmap root 数据
   * @param markdown markdown 文本
   * @param workId 工作 ID（用于命名空间隔离）
   * @returns 修改后的 root 数据
   */
  static injectMermaidHtml(e, t, r) {
    const s = [], i = t.split(`
`);
    let a = "", n = !1, c = [], h = -1;
    for (let p = 0; p < i.length; p++) {
      const d = i[p], f = d.match(/^(#{1,6})\s+(.+)$/);
      if (f && (a = f[2].trim()), d.trim().startsWith("```mermaid"))
        n = !0, c = [], h = p;
      else if (n && d.trim() === "```") {
        n = !1;
        const w = c.join(`
`);
        w && a && s.push({
          title: a,
          content: w,
          index: h
        }), c = [];
      } else n && c.push(d);
    }
    const g = (p) => {
      if (!p) return;
      const d = p.content || "", f = b.decodeHtmlEntities(d);
      for (const w of s)
        if (f.includes(w.title) || d.includes(w.title)) {
          const v = O.generateId(), I = O.createContainer(
            v,
            w.content,
            r
          );
          p.content ? p.content = p.content + I : p.content = I;
          break;
        }
      p.children && p.children.length > 0 && p.children.forEach((w) => {
        g(w);
      });
    };
    return g(e), e;
  }
  /**
   * 解码 HTML 实体
   * @param str HTML 字符串
   * @returns 解码后的字符串
   */
  static decodeHtmlEntities(e) {
    const t = document.createElement("textarea");
    return t.innerHTML = e, t.value;
  }
  /**
   * 检查 divElement 中是否包含 mermaid SVG 元素
   * @param divElement HTMLDivElement 或 SVGSVGElement 元素
   * @returns 如果包含 mermaid SVG 元素，返回 true，否则返回 false
   */
  static hasMermaidSvg(e) {
    return e.querySelectorAll("svg[data-type='mermaid']").length > 0;
  }
}
class U extends ee {
  constructor(t) {
    super(t);
    u(this, "currentWorkId", null);
  }
  /**
   * 设置当前工作 ID（用于命名空间隔离）
   * @param workId 工作 ID
   */
  setWorkId(t) {
    this.currentWorkId = t, t && O.extendMarkdown(this, t);
  }
  transform(t, r) {
    this.currentWorkId ? O.clear(this.currentWorkId) : O.clear();
    const s = this.convertKatexToText(t), i = super.transform(s, r);
    return i.root && this.processKatexInRoot(i.root), i;
  }
  /**
   * 将 markdown 内容中的 katex 公式转换为普通文本
   * 处理 $...$ 和 $$...$$ 格式的公式
   * 由于 Safari 对 katex 的兼容性问题，将公式转换为普通文本显示
   * @param content markdown 内容
   * @returns 处理后的内容
   */
  convertKatexToText(t) {
    if (!t)
      return t;
    let r = t.replace(
      /\$\$([\s\S]*?)\$\$/g,
      (s, i) => i.replace(/\\/g, "").replace(/\{/g, "").replace(/\}/g, "").replace(/\\over/g, "/").replace(/\\pm/g, "±").replace(/\\sqrt/g, "√").replace(/\\frac/g, "/").trim()
    );
    return r = r.replace(
      /\$([^$\n]+?)\$/g,
      (s, i) => i.replace(/\\/g, "").replace(/\{/g, "").replace(/\}/g, "").replace(/\\over/g, "/").replace(/\\pm/g, "±").replace(/\\sqrt/g, "√").replace(/\\frac/g, "/").trim()
    ), r;
  }
  /**
   * 处理转换结果中的 katex HTML，将其转换为普通文本
   * 递归处理节点树，查找包含 katex 的内容并转换
   * 由于 Safari 对 katex 的兼容性问题，将 katex HTML 转换为普通文本显示
   * @param node markmap 节点
   */
  processKatexInRoot(t) {
    if (t) {
      if (t.content && typeof t.content == "string" && (t.content.includes("katex") || t.content.includes("katex-mathml"))) {
        const r = t.content.match(
          /<annotation[^>]*encoding="application\/x-tex">([^<]+)<\/annotation>/
        );
        if (r) {
          const s = r[1].replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/\\/g, "").replace(/\{/g, "").replace(/\}/g, "").replace(/\\over/g, "/").replace(/\\pm/g, "±").replace(/\\sqrt/g, "√").replace(/\\frac/g, "/").trim();
          t.content = t.content.replace(
            /<div[^>]*xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"[^>]*>Katex:\s*<span[^>]*class="katex"[^>]*>[\s\S]*?<\/span><\/div>/g,
            s
          );
        } else {
          const s = document.createElement("div");
          s.innerHTML = t.content;
          const i = s.querySelector(".katex");
          if (i) {
            let a = i.textContent || "";
            a = a.replace(/^Katex:\s*/i, "").trim(), t.content = t.content.replace(
              /<div[^>]*xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"[^>]*>Katex:\s*<span[^>]*class="katex"[^>]*>[\s\S]*?<\/span><\/div>/g,
              a || "公式"
            );
          } else {
            const a = t.content.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").replace(/^Katex:\s*/i, "").trim();
            t.content = a || "公式";
          }
        }
      }
      t.children && Array.isArray(t.children) && t.children.forEach((r) => {
        this.processKatexInRoot(r);
      });
    }
  }
  /**
   * 等待 markmap foreignObject 内所有图片加载完成
   * 用于在调用 fit() 之前确保所有图片都已加载，以便正确计算尺寸
   * @param svgElement SVG 元素
   * @param timeout 超时时间（毫秒），默认 10 秒
   * @returns Promise<void> 当所有图片加载完成时 resolve
   */
  static async waitForImagesInForeignObjects(t, r = 1e4) {
    if (!t)
      return;
    const s = t.querySelectorAll(
      "foreignObject.markmap-foreign img"
    );
    if (s.length === 0)
      return;
    const i = [], a = /* @__PURE__ */ new Set();
    s.forEach((n) => {
      const c = n.src || n.getAttribute("src");
      if (!c || a.has(c) || (a.add(c), n.complete && n.naturalWidth > 0))
        return;
      const h = new Promise((g) => {
        const p = setTimeout(() => {
          g();
        }, r);
        if (n.complete && n.naturalWidth > 0) {
          clearTimeout(p), g();
          return;
        }
        const d = () => {
          clearTimeout(p), n.removeEventListener("load", d), n.removeEventListener("error", f), g();
        }, f = () => {
          clearTimeout(p), n.removeEventListener("load", d), n.removeEventListener("error", f), g();
        };
        n.addEventListener("load", d), n.addEventListener("error", f), !n.src && c && (n.src = c);
      });
      i.push(h);
    }), i.length > 0 && await Promise.all(i);
  }
}
const L = new U(), { loadCSS: ce, loadJS: le, Markmap: he } = z, { scripts: H, styles: V } = L.getAssets();
V && ce(V);
H && le(H, {
  getMarkmap: () => z
});
async function de(o) {
  const e = o.querySelectorAll("img"), t = Array.from(e).map((i) => {
    if (!i.crossOrigin && i.src && !i.src.startsWith("data:") && (i.crossOrigin = "anonymous", i.complete)) {
      const a = i.src;
      i.src = "", i.src = a;
    }
    return i.complete && i.crossOrigin ? Promise.resolve() : new Promise((a) => {
      i.onload = () => {
        a(void 0);
      }, i.onerror = () => {
        a(void 0);
      };
    });
  });
  return o.querySelectorAll("svg").forEach((i) => {
    i.querySelectorAll("image").forEach((n) => {
      n.href && !n.href.baseVal.startsWith("data:") && (n.getAttribute("crossorigin") || n.setAttribute("crossorigin", "anonymous"), t.push(
        new Promise((c) => {
          const h = new Image();
          h.crossOrigin = "anonymous", h.onload = () => {
            c(void 0);
          }, h.onerror = () => {
            c(void 0);
          }, h.src = n.href.baseVal;
        })
      ));
    });
  }), await Promise.all(t);
}
async function me(o) {
  const r = Date.now();
  let s = !1;
  for (; Date.now() - r < 5e3; ) {
    const i = o.querySelectorAll("path");
    if (i.length > 0 && (s = Array.from(i).some((a) => {
      const n = a.getAttribute("d") || "";
      return n !== "M0,0C0,0,0,0,0,0" && n.length > 10;
    }), s))
      break;
    await new Promise((a) => setTimeout(a, 50));
  }
}
async function pe(o) {
  const e = o.querySelectorAll("svg");
  if (!e.length)
    return;
  const t = [];
  for (let r = 0; r < e.length; r++) {
    const s = e[r];
    t.push(me(s));
  }
  await Promise.all(t);
}
async function G(o) {
  if (b.hasMermaidSvg(o)) {
    const r = Date.now();
    let s = !1;
    for (; Date.now() - r < 5e3 && !s; ) {
      const i = o.querySelectorAll("foreignObject");
      if (i.length > 0) {
        let a = !0;
        for (const n of Array.from(i)) {
          const c = parseFloat(n.getAttribute("width") || "0"), h = parseFloat(n.getAttribute("height") || "0");
          if (n.querySelector(".mermaid-container") && (c < 50 || h < 50)) {
            a = !1;
            break;
          }
        }
        if (a) {
          s = !0;
          break;
        }
      } else
        s = !0;
      await new Promise((a) => setTimeout(a, 50));
    }
  }
}
async function ue(o, e = {}) {
  const { width: t = o.offsetWidth, height: r = o.offsetHeight } = e, s = o.offsetWidth || t, i = o.offsetHeight || r;
  try {
    const { loadSvgToImageLib: a, getSvgToImageLib: n } = await import("./svgToImageLoader-DZz5bAo4.mjs");
    let c = n();
    if (!c)
      try {
        c = await a();
      } catch (d) {
        return console.error("[loadSvgToImageLib] error: ", d), null;
      }
    const h = o.style.width, g = o.style.height, p = o.style.display;
    o.style.width || (o.style.width = `${s}px`), o.style.height || (o.style.height = `${i}px`), (!o.style.display || o.style.display === "none") && (o.style.display = "block");
    try {
      await new Promise((f) => {
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            f();
          });
        });
      });
      const d = await c.toPng(o, {
        width: s,
        height: i,
        quality: 1
      });
      return o.style.width = h, o.style.height = g, o.style.display = p, new Promise((f) => {
        const w = new Image();
        w.crossOrigin = "anonymous", w.onload = () => {
          f(w);
        }, w.onerror = () => {
          f(null);
        }, w.src = d;
      });
    } catch (d) {
      return o.style.width = h, o.style.height = g, o.style.display = p, console.error("[divToImageElement] error: ", d), null;
    }
  } catch (a) {
    return console.error("[divToImageElement] error: ", a), null;
  }
}
class ge {
  constructor(e) {
    u(this, "toolsType", M.BackgroundSVG);
    u(this, "vNodes");
    u(this, "workOptions");
    u(this, "workId");
    u(this, "markmapInstance", null);
    u(this, "isDestroyed", !1);
    u(this, "element");
    u(this, "manager");
    const { vNodes: t, workId: r, toolsOpt: s, manager: i } = e;
    this.workId = r, this.vNodes = t, this.workOptions = s, this.manager = i, this.element = this.createElement(), this.manager.fullLayer.appendChild(this.element), this.vNodes.setInfo(this.workId, {
      workShape: this
    });
  }
  get fullLayer() {
    return this.manager.fullLayer;
  }
  get collector() {
    return this.manager.master.control.collector;
  }
  get scenePath() {
    return this.manager.master.control.viewContainerManager.getCurScenePath(
      this.manager.viewId
    );
  }
  async init() {
    await this.render();
  }
  createElement() {
    const { type: e } = this.workOptions;
    let t;
    return e === E.markmap ? (t = document.createElementNS("http://www.w3.org/2000/svg", "svg"), t.classList.add("svg")) : (t = document.createElement("img"), t.classList.add("img")), t.id = this.workId, t.setAttribute("data-id", this.workId), t;
  }
  async render(e) {
    this.isDestroyed || !this.element || !this.element.parentNode || (this.updateElementPosition(e), await this.updateSvg(e));
  }
  isSameSize(e) {
    const { width: t, height: r } = e, { width: s, height: i } = this.workOptions, a = t * this.manager.camera.scale, n = r * this.manager.camera.scale, c = s * this.manager.camera.scale, h = i * this.manager.camera.scale;
    return a === c && n === h;
  }
  isSamePosition(e) {
    const { centerX: t, centerY: r } = e, { centerX: s, centerY: i } = this.workOptions, a = this.manager.getPagePoint(s, i), n = this.manager.getPagePoint(t, r);
    return W(n, a);
  }
  isSameZIndex(e) {
    const { zIndex: t } = e, { zIndex: r } = this.workOptions;
    return t === r;
  }
  isSameState(e) {
    const { state: t } = e, { state: r } = this.workOptions;
    return W(t, r);
  }
  isSameData(e) {
    const { data: t } = e, { data: r } = this.workOptions;
    return W(t, r);
  }
  updateElementPosition(e) {
    if (this.isDestroyed || !this.element || !this.fullLayer)
      return;
    const { centerX: t, centerY: r, width: s, height: i, zIndex: a } = this.workOptions, n = this.manager.getPagePoint(t, r), c = s * this.manager.camera.scale, h = i * this.manager.camera.scale;
    (!e || e && !this.isSameSize(e)) && (this.element.setAttribute("width", `${c}`), this.element.setAttribute("height", `${h}`), this.element.style.width = `${c}px`, this.element.style.height = `${h}px`), (!e || e && !this.isSamePosition(e)) && (this.element.style.left = `${n.x}px`, this.element.style.top = `${n.y}px`), (!e || e && !this.isSameZIndex(e)) && (this.element.style.zIndex = (a || 0).toString());
  }
  async updateSvg(e) {
    const { type: t, state: r } = this.workOptions;
    if (t === E.markmap) {
      const { data: s } = this.workOptions;
      if (this.markmapInstance || (this.markmapInstance = he.create(
        this.element,
        this.manager.markmapOptions
      ), this.markmapInstance.handleClick = async (n, c) => {
        var p, d, f;
        (p = this.markmapInstance) == null || p.toggleNode(c);
        const h = this.serializeData((d = this.markmapInstance) == null ? void 0 : d.state.data);
        this.setWorkOptions(
          {
            ...this.workOptions,
            state: h
          },
          !1
        ), b.checkNodeHasMermaid(c) && await b.renderMermaidAfterDOMUpdate(
          this.element,
          this.workId
        ), this.scenePath && this.collector && ((f = this.collector) == null || f.dispatch({
          type: y.UpdateNode,
          workId: this.workId,
          opt: this.workOptions,
          isSync: !0,
          viewId: this.manager.viewId,
          scenePath: this.scenePath
        }));
      }), e && this.isSameState(e) && this.isSameSize(e) && this.isSameData(e))
        return;
      L.setWorkId(this.workId);
      const i = L.transform(s);
      let { root: a } = i;
      s && q(s) && (a = b.injectMermaidHtml(a, s, this.workId));
      try {
        r && Array.isArray(r) && this.transformState(
          r,
          a
        ), await this.markmapInstance.setData(a), !this.isDestroyed && this.element && this.fullLayer && this.markmapInstance && (window.markmapInstance = this.markmapInstance, s && q(s) && await b.renderMermaidAfterDOMUpdate(
          this.element,
          this.workId
        ), await this.fit(
          !e || e && !this.isSameData(e)
        ));
      } catch (n) {
        console.error("[updateSvg] error: ", n);
      }
    } else {
      const { src: s, crossOrigin: i } = this.workOptions;
      this.element.src = s, this.element.crossOrigin = _(i) ? i : "anonymous";
      try {
        await new Promise((a, n) => {
          this.element.onload = () => {
            a();
          }, this.element.onerror = function() {
            n();
          };
        });
      } catch (a) {
        console.error("[updateSvg] error: ", a);
      }
    }
  }
  async fit(e = !0) {
    var t;
    !this.isDestroyed && this.element && this.fullLayer && this.markmapInstance && (e && this.element && await U.waitForImagesInForeignObjects(
      this.element
    ), await ((t = this.markmapInstance) == null ? void 0 : t.fit()), this.element && b.isSafari() && b.hasMermaidSvg(this.element) && (await G(this.element), await b.transformMermaidSvgToMarkmapSvg(
      this.element
    )));
  }
  serializeData(e) {
    var s;
    const t = [e], r = [];
    for (; t.length > 0; ) {
      const i = t.pop();
      i && (i != null && i.children && t.push(...i.children), r.push(((s = i == null ? void 0 : i.payload) == null ? void 0 : s.fold) || 0));
    }
    return r;
  }
  transformState(e, t) {
    const r = [t];
    for (; r.length > 0; ) {
      const s = r.pop();
      s && (s != null && s.children && r.push(...s.children), s.payload ? s.payload.fold = e.shift() : e.shift());
    }
  }
  async updateCamera() {
    this.updateElementPosition(), await this.fit(!1);
  }
  async setWorkOptions(e, t = !0) {
    if (!W(this.workOptions, e)) {
      const r = J(this.workOptions);
      this.workOptions = e, t && await this.render(r);
    }
  }
  destroy() {
    this.isDestroyed = !0, this.element.remove();
  }
  getRectFromLayer() {
    const e = this.element.getBoundingClientRect();
    return {
      x: e.x,
      y: e.y,
      w: e.width,
      h: e.height
    };
  }
}
function X(o) {
  const { toolsType: e, ...t } = o;
  switch (e) {
    case M.BackgroundSVG:
      return new ge(t);
    default:
      return;
  }
}
class Y {
  constructor(e) {
    u(this, "viewId");
    u(this, "fullLayer");
    u(this, "curNodeMap");
    this.viewId = e, this.curNodeMap = new te();
  }
  init(e) {
    this.fullLayer = e;
  }
  get(e) {
    return this.curNodeMap.get(e);
  }
  setInfo(e, t) {
    const r = this.curNodeMap.get(
      e
    ) || {
      name: e,
      workShape: t.workShape
    };
    t.workShape && (r.workShape = t.workShape), this.curNodeMap.set(e, r);
  }
  getNodeRectFormShape(e) {
    const t = this.curNodeMap.get(e);
    if (t && t.workShape)
      return t.workShape.getRectFromLayer();
  }
  delete(e) {
    const t = this.curNodeMap.get(e);
    t && t.workShape.destroy(), this.curNodeMap.delete(e);
  }
  clear() {
    for (const e of this.curNodeMap.values())
      e.workShape.destroy();
    this.curNodeMap.clear();
  }
}
class fe {
  constructor(e, t) {
    u(this, "opt");
    u(this, "viewId");
    u(this, "fullLayer");
    u(this, "vNodes");
    u(this, "master");
    u(this, "cameraOpt");
    u(this, "methodBuilder");
    u(this, "updateCamera", Q(async (e) => {
      const { cameraOpt: t } = e;
      t && !W(this.cameraOpt, t) && await this.setCameraOpt(t);
    }, 100));
    this.viewId = e, this.opt = t, this.master = t.master, this.fullLayer = t.container, this.methodBuilder = new se([
      B.CopyNode
    ]).registerForBackgroundThread(this), this.vNodes = new Y(e), this.vNodes.init(this.fullLayer);
  }
  get camera() {
    return this.cameraOpt || {
      scale: 1,
      centerX: 0,
      centerY: 0,
      width: 0,
      height: 0
    };
  }
  get view() {
    var e;
    return (e = this.master.control.viewContainerManager.getView(this.viewId)) == null ? void 0 : e.viewData;
  }
  get markmapOptions() {
    return this.master.control.pluginOptions.extras.markmap.options;
  }
  getPagePoint(e, t) {
    const { scale: r, centerX: s, centerY: i, width: a, height: n } = this.camera;
    return {
      x: (e - s) * r + a / 2,
      y: (t - i) * r + n / 2
    };
  }
  async setCameraOpt(e) {
    this.cameraOpt = e;
    for (const t of this.vNodes.curNodeMap.values()) {
      const { workShape: r } = t;
      r && await r.updateCamera();
    }
  }
  clearAll() {
    this.vNodes.clear();
  }
  canUseFullLayer(e) {
    return e === M.BackgroundSVG;
  }
  async consumeFull(e) {
    const { toolsType: t, opt: r, workId: s } = e;
    if (s != null && s.toString() && t && this.canUseFullLayer(t))
      switch (t) {
        case M.BackgroundSVG:
          await this.setFullWork({
            toolsType: t,
            opt: r,
            workId: s
          });
          break;
      }
  }
  async setFullWork(e) {
    const { workId: t, opt: r, toolsType: s } = e;
    if (t && r && s) {
      const i = t.toString();
      let a;
      const n = this.vNodes.get(i);
      return !n || !n.workShape ? (a = this.createWorkShapeNode({
        toolsOpt: r,
        toolsType: M.BackgroundSVG,
        workId: i
      }), a && await a.init()) : (a = n.workShape, await a.setWorkOptions(r)), a;
    }
  }
  createWorkShapeNode(e) {
    return X({
      ...e,
      vNodes: this.vNodes,
      manager: this
    });
  }
  removeWork(e) {
    const { workId: t } = e, r = t == null ? void 0 : t.toString();
    r && this.removeNode(r);
  }
  removeNode(e) {
    this.vNodes.delete(e);
  }
  async on(e) {
    if (!await this.methodBuilder.consumeForBackgroundThread(e)) {
      const { msgType: t, toolsType: r } = e;
      switch (t) {
        case y.Destroy: {
          this.destroy();
          break;
        }
        case y.Clear: {
          this.clearAll();
          break;
        }
        case y.UpdateCamera: {
          this.updateCamera(e);
          break;
        }
        case y.UpdateTools: {
          this.toggleFullLayer(r === M.Clicker);
          break;
        }
        case y.BackgroundSVGUpdate:
        case y.UpdateNode:
        case y.FullWork: {
          r && this.canUseFullLayer(r) && await this.consumeFull(e);
          break;
        }
        case y.BackgroundSVGDelete: {
          this.removeWork(e);
          break;
        }
      }
    }
  }
  toggleFullLayer(e) {
    this.fullLayer.classList.toggle(
      "appliance-plugin-background-svg-active",
      e
    );
  }
  destroy() {
    this.vNodes.clear();
  }
}
class we {
  constructor(e, t) {
    u(this, "viewId");
    u(this, "fullLayer");
    u(this, "master");
    u(this, "vNodes");
    u(this, "cameraOpt");
    u(this, "opt");
    u(this, "workShapes", /* @__PURE__ */ new Map());
    this.viewId = e, this.opt = t, this.master = t.master, this.fullLayer = t.container, this.vNodes = new Y(e), this.vNodes.init(this.fullLayer);
  }
  get camera() {
    return this.cameraOpt || {
      scale: 1,
      centerX: 0,
      centerY: 0,
      width: 0,
      height: 0
    };
  }
  get view() {
    var e;
    return (e = this.master.control.viewContainerManager.getView(this.viewId)) == null ? void 0 : e.viewData;
  }
  get markmapOptions() {
    return this.master.control.pluginOptions.extras.markmap.options;
  }
  createOffscreenCanvas(e) {
    const { width: t, height: r } = e.canvasOpt, s = new OffscreenCanvas(
      e.canvasOpt.width,
      e.canvasOpt.height
    );
    s.width = t, s.height = r;
  }
  async setCameraOpt(e) {
    this.cameraOpt = e;
    for (const t of this.vNodes.curNodeMap.values()) {
      const { workShape: r } = t;
      r && await r.updateCamera();
    }
  }
  getPagePoint(e, t) {
    const { scale: r, centerX: s, centerY: i, width: a, height: n } = this.camera;
    return {
      x: (e - s) * r + a / 2,
      y: (t - i) * r + n / 2
    };
  }
  async getSnapshot(e) {
    const { scenePath: t, scenes: r, cameraOpt: s } = e;
    if (t && r && s) {
      await this.setCameraOpt(s);
      for (const [i, a] of Object.entries(r))
        if (a != null && a.type && (a == null ? void 0 : a.toolsType) === M.BackgroundSVG)
          switch (a == null ? void 0 : a.type) {
            case y.UpdateNode:
            case y.FullWork: {
              const { opt: n } = a, c = {
                ...a,
                opt: n,
                workId: i,
                msgType: y.FullWork,
                dataType: D.Service,
                viewId: this.viewId
              };
              await this.runFullWork(c);
              break;
            }
          }
      try {
        if (t) {
          await G(this.fullLayer), await de(this.fullLayer), await pe(this.fullLayer);
          const i = await ue(this.fullLayer);
          i && this.opt.post({
            sp: [
              {
                type: y.Snapshot,
                scenePath: t,
                imageElement: i,
                viewId: this.viewId,
                index: 1
              }
            ]
          });
        }
      } catch (i) {
        const a = i && i instanceof Error ? i.message : i == null ? void 0 : i.toString();
        this.opt.post({
          sp: [
            {
              type: y.ReportError,
              reportString: `[SnapshotThreadImpl] getSnapshotRender error: ${a}`
            }
          ]
        });
      }
    }
  }
  createWorkShapeNode(e) {
    return X({
      ...e,
      vNodes: this.vNodes,
      manager: this
    });
  }
  async setFullWork(e) {
    const { workId: t, opt: r, toolsType: s } = e;
    if (t && r && s) {
      const i = t.toString();
      let a;
      const n = this.vNodes.get(i);
      return !n || !n.workShape ? (a = this.createWorkShapeNode({
        toolsOpt: r,
        toolsType: M.BackgroundSVG,
        workId: i
      }), a && await a.init()) : (a = n.workShape, await a.setWorkOptions(r)), a;
    }
  }
  async runFullWork(e) {
    const { toolsType: t, opt: r, workId: s } = e;
    await this.setFullWork({
      toolsType: t,
      opt: r,
      workId: s
    });
  }
  destroy() {
    this.fullLayer.innerHTML = "", this.fullLayer.style.width = "", this.fullLayer.style.height = "";
  }
}
class We {
  constructor(e) {
    u(this, "backgroundThreadMap", /* @__PURE__ */ new Map());
    u(this, "snapshotThread");
    u(this, "master");
    u(this, "post", (e) => {
      const { sp: t } = e;
      t && this.master.collectorSyncData(t);
    });
    this.master = e, this.backgroundThreadMap = /* @__PURE__ */ new Map();
  }
  createBackgroundThread(e, t) {
    return new fe(e, t);
  }
  createSnapshotThread(e, t) {
    return new we(e, t);
  }
  async consume(e) {
    var t, r, s, i, a, n;
    for (const c of e.values()) {
      const {
        msgType: h,
        viewId: g,
        layerOpt: p,
        offscreenCanvasOpt: d,
        cameraOpt: f,
        tasksqueue: w,
        mainTasksqueueCount: v
      } = c;
      if (h === y.Console) {
        console.log(this);
        continue;
      }
      if (h === y.Init) {
        const l = (t = this.master.control.viewContainerManager.getView(g)) == null ? void 0 : t.displayer, m = (r = l == null ? void 0 : l.backgroundContainerRef) == null ? void 0 : r.current;
        if (l && m && p && d) {
          const S = this.backgroundThreadMap.get(g);
          S == null || S.destroy();
          const k = this.createBackgroundThread(g, {
            displayer: l,
            container: m,
            layerOpt: p,
            master: this.master,
            canvasOpt: d,
            post: this.post
          });
          this.backgroundThreadMap.set(g, k), k && f && await k.setCameraOpt(f);
        }
        continue;
      }
      if (h === y.Snapshot) {
        const l = (s = this.master.control.viewContainerManager.getView(g)) == null ? void 0 : s.displayer, S = (a = ((i = this.master.control.viewContainerManager.mainView) == null ? void 0 : i.displayer).backgroundSnapshotContainerRef) == null ? void 0 : a.current;
        if (l && S && f) {
          (n = this.snapshotThread) == null || n.destroy(), S.style.width = `${f.width}px`, S.style.height = `${f.height}px`;
          const k = {
            ...P.defaultLayerOpt,
            offscreen: !1,
            width: f.width,
            height: f.height
          }, x = {
            ...P.defaultScreenCanvasOpt,
            width: f.width,
            height: f.height
          };
          this.snapshotThread = this.createSnapshotThread(g, {
            displayer: l,
            container: S,
            layerOpt: k,
            master: this.master,
            canvasOpt: x,
            post: this.post
          }), await this.snapshotThread.getSnapshot(c), this.snapshotThread.destroy(), this.snapshotThread = void 0;
          continue;
        }
      }
      if (h === y.TasksQueue && (w != null && w.size)) {
        for (const [l, m] of this.backgroundThreadMap.entries()) {
          const S = w.get(l);
          S && (await m.on(S), v && this.post({ workerTasksqueueCount: v }));
        }
        continue;
      }
      if (g === Z) {
        for (const l of this.backgroundThreadMap.values())
          await l.on(c);
        h === y.Destroy && this.backgroundThreadMap.clear();
        continue;
      }
      const I = this.backgroundThreadMap.get(g);
      I && (await I.on(c), h === y.Destroy && this.backgroundThreadMap.delete(g));
    }
  }
  async consumeTargetOne(e, t) {
    const r = this.backgroundThreadMap.get(e);
    r && await r.on(t);
  }
  destroy() {
    var e;
    (e = this.snapshotThread) == null || e.destroy(), this.snapshotThread = void 0;
    for (const t of this.backgroundThreadMap.values())
      t.destroy();
    this.backgroundThreadMap.clear();
  }
}
export {
  We as BackgroundThreadManagerImpl
};
