var ne = Object.defineProperty;
var ce = (L, t, e) => t in L ? ne(L, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : L[t] = e;
var u = (L, t, e) => ce(L, typeof t != "symbol" ? t + "" : t, e);
import { D as B, E as W, a as f, r as z, b as g, g as $, t as U, c as p, S as te, d as T, e as X, i as le, C as F, f as R, h as he, j as I, M as P, V as pe, k as se, T as Y, l as G, m as Q, n as V, o as de, p as K, q as J, s as ue } from "./index-BpYwcUSN.mjs";
import { Scene as oe, Group as re } from "spritejs";
import { cloneDeep as ie, xor as fe, isNumber as H, isEqual as ee } from "lodash";
import "lineclip";
import "white-web-sdk";
import "react-dom";
import "react";
import "eventemitter2";
class me {
  constructor(t) {
    u(this, "vNodes");
    u(this, "thread");
    u(this, "serviceWorkShapes", /* @__PURE__ */ new Map());
    u(this, "localWorkShapes", /* @__PURE__ */ new Map());
    u(this, "tmpOpt");
    u(this, "animationId");
    u(this, "syncUnitTime", B.syncOpt.interval);
    this.vNodes = t.vNodes, this.thread = t.thread;
  }
  createLocalWork(t) {
    const { workId: e, opt: s, toolsType: o } = t;
    if (e && s) {
      const r = e.toString();
      !this.getToolsOpt() && o && this.setToolsOpt({
        toolsType: o,
        toolsOpt: s
      }), this.setWorkOptions(r, s);
    }
  }
  getLocalWorkShape(t) {
    return this.localWorkShapes.get(t);
  }
  createLocalWorkShape(t, e) {
    if (t && this.tmpOpt) {
      const s = {
        toolsType: this.tmpOpt.toolsType,
        toolsOpt: e || this.tmpOpt.toolsOpt
      }, o = this.createWorkShapeNode({ ...s, workId: t });
      return o && this.localWorkShapes.set(t, {
        node: o,
        toolsType: o.toolsType,
        workState: W.Start
      }), o;
    }
  }
  canUseTopLayer(t) {
    return t === f.LaserPen;
  }
  destroy() {
    this.clearAll();
  }
  clearAll() {
    this.thread.topLayer.children.length && (this.thread.topLayer.parent.children.forEach((t) => {
      t.name !== "viewport" && t.remove();
    }), z(this.thread.serviceLayer, this.thread.serviceLayer.parent)), this.serviceWorkShapes.clear(), this.localWorkShapes.clear();
  }
  consumeDraw(t) {
    const { workId: e, dataType: s } = t;
    if (s === g.Service)
      this.activeServiceWorkShape(t);
    else {
      const o = e == null ? void 0 : e.toString(), r = o && this.localWorkShapes.get(o);
      if (!r)
        return;
      const i = r.node.consume({ data: t, isFullWork: !1, isSubWorker: !0 });
      i.rect && (r.result = i, r.workState = W.Doing, o && this.localWorkShapes.set(o, r));
    }
    this.runAnimation();
  }
  setToolsOpt(t) {
    var e;
    this.tmpOpt = t, (e = t.toolsOpt) != null && e.syncUnitTime && (this.syncUnitTime = t.toolsOpt.syncUnitTime);
  }
  getToolsOpt() {
    return this.tmpOpt;
  }
  createWorkShapeNode(t) {
    const { toolsType: e } = t;
    if (e === f.LaserPen)
      return $({ ...t, vNodes: this.vNodes, fullLayer: this.thread.topLayer, drawLayer: this.thread.topLayer });
  }
  setNodeKey(t, e, s, o) {
    return e.toolsType = s, e.node = this.createWorkShapeNode({ workId: t, toolsType: s, toolsOpt: o }), e;
  }
  activeServiceWorkShape(t) {
    var k, d;
    const { workId: e, opt: s, toolsType: o, type: r, updateNodeOpt: i, ops: a, op: c } = t;
    if (!e)
      return;
    const n = e.toString(), h = (k = this.vNodes.get(n)) == null ? void 0 : k.rect;
    if (!((d = this.serviceWorkShapes) != null && d.has(n))) {
      let S = {
        toolsType: o,
        animationWorkData: c || [],
        animationIndex: 0,
        type: r,
        updateNodeOpt: i,
        ops: a,
        oldRect: h
      };
      o && s && (S = this.setNodeKey(n, S, o, s)), this.serviceWorkShapes.set(n, S);
    }
    const l = this.serviceWorkShapes.get(n);
    r && (l.type = r), a && (l.animationWorkData = U(a), l.ops = a), i && (l.updateNodeOpt = i), c && (l.animationWorkData = c), l.node && l.node.getWorkId() !== n && l.node.setWorkId(n), h && (l.oldRect = h), o && s && (l.toolsType !== o && o && s && this.setNodeKey(n, l, o, s), l.node && l.node.setWorkOptions(s));
  }
  computNextAnimationIndex(t, e) {
    var r;
    const s = ((r = t.node) == null ? void 0 : r.syncUnitTime) || this.syncUnitTime, o = Math.floor((t.animationWorkData || []).slice(t.animationIndex).length * 32 / e / s) * e;
    return Math.min((t.animationIndex || 0) + (o || e), (t.animationWorkData || []).length);
  }
  animationDraw() {
    var o, r, i, a;
    this.animationId = void 0;
    let t = !1;
    const e = /* @__PURE__ */ new Map(), s = [];
    for (const [c, n] of this.serviceWorkShapes.entries())
      switch (n.toolsType) {
        case f.LaserPen: {
          const l = this.computNextAnimationIndex(n, 8), k = Math.max(0, n.animationIndex || 0), d = (n.animationWorkData || []).slice(k, l);
          if ((n.animationIndex || 0) < l && ((o = n.node) == null || o.consumeService({
            op: d,
            isFullWork: !1
          }), n.animationIndex = l, d.length && e.set(c, {
            workState: k === 0 ? W.Start : l === ((r = n.animationWorkData) == null ? void 0 : r.length) ? W.Done : W.Doing,
            op: d.slice(-2)
          })), n.isDel) {
            (i = n.node) == null || i.clearTmpPoints(), this.serviceWorkShapes.delete(c);
            break;
          }
          n.ops && n.animationIndex === ((a = n.animationWorkData) == null ? void 0 : a.length) && !n.isDel && (this.thread.topLayer.getElementsByName(c.toString())[0] || (n.isDel = !0, this.serviceWorkShapes.set(c, n))), t = !0;
          break;
        }
      }
    for (const [c, n] of this.localWorkShapes.entries()) {
      const { result: h, toolsType: l, isDel: k, workState: d } = n;
      switch (l) {
        case f.LaserPen: {
          if (k) {
            n.node.clearTmpPoints(), this.localWorkShapes.delete(c), s.push({
              removeIds: [c.toString()],
              type: p.RemoveNode
            });
            break;
          }
          h && ((h.op || h.ops) && s.push(h), n.result = void 0), !this.thread.topLayer.getElementsByName(c.toString())[0] && d === W.Done && (n.isDel = !0, this.localWorkShapes.set(c, n)), t = !0;
          break;
        }
      }
    }
    t && this.runAnimation(), e.size && e.forEach((c, n) => {
      s.push({
        type: p.Cursor,
        uid: n.split(te)[0],
        op: c.op,
        workState: c.workState,
        viewId: this.thread.viewId
      });
    }), s.length && this.thread.post({ sp: s });
  }
  runAnimation() {
    this.animationId || (this.animationId = requestAnimationFrame(this.animationDraw.bind(this)));
  }
  setWorkOptions(t, e) {
    var o;
    let s = (o = this.localWorkShapes.get(t)) == null ? void 0 : o.node;
    if (!s && this.tmpOpt) {
      const { toolsType: r } = this.tmpOpt;
      this.tmpOpt.toolsOpt = e, s = this.createWorkShapeNode({ workId: t, toolsType: r, toolsOpt: e }), s && this.localWorkShapes.set(t, {
        node: s,
        toolsType: r,
        workState: W.Start
      }), this.setToolsOpt(this.tmpOpt);
    }
    e != null && e.syncUnitTime || (e.syncUnitTime = this.syncUnitTime), s && s.setWorkOptions(e);
  }
  consumeDrawAll(t) {
    const { workId: e, dataType: s } = t;
    if (s === g.Service)
      this.activeServiceWorkShape(t);
    else {
      const o = e == null ? void 0 : e.toString(), r = o && this.localWorkShapes.get(o);
      if (!r)
        return;
      const i = r.node.consumeAll({ data: t });
      r.result = i, r.workState = W.Done, o && this.localWorkShapes.set(o, r);
    }
    this.runAnimation();
  }
}
class ke {
  constructor(t) {
    u(this, "vNodes");
    u(this, "thread");
    u(this, "workShapes", /* @__PURE__ */ new Map());
    u(this, "effectSelectNodeData", /* @__PURE__ */ new Set());
    u(this, "batchEraserRemoveNodes", /* @__PURE__ */ new Set());
    u(this, "batchEraserWorks", /* @__PURE__ */ new Set());
    u(this, "tmpOpt");
    u(this, "syncUnitTime", B.syncOpt.interval);
    u(this, "fullWorkerDrawCount", 0);
    u(this, "drawWorkActiveId");
    u(this, "consumeCount", 0);
    u(this, "batchEraserCombine", he(() => {
      this.updateBatchEraserCombineNode(this.batchEraserWorks, this.batchEraserRemoveNodes), this.batchEraserWorks.clear(), this.batchEraserRemoveNodes.clear();
    }, 100, { leading: !1 }));
    this.vNodes = t.vNodes, this.thread = t.thread;
  }
  async loadImageBitMap(t) {
    return await this.thread.loadImageBitMap(t);
  }
  createLocalWork(t) {
    const { workId: e, opt: s, toolsType: o } = t;
    if (e && s) {
      const r = e.toString();
      !this.getToolsOpt() && o && this.setToolsOpt({
        toolsType: o,
        toolsOpt: s
      }), this.setWorkOptions(r, s);
    }
  }
  // async workShapesDone(scenePath: string, serviceWork: SubServiceThread) {
  //     for (const key of this.workShapes.keys()) {
  //         await this.consumeDrawAll({
  //             workId: key,
  //             scenePath,
  //             viewId: this.thread.viewId,
  //             msgType: EPostMessageType.DrawWork,
  //             dataType: EDataType.Local
  //         }, serviceWork)
  //     }
  // }
  async updateSelector(t) {
    var k;
    const e = this.workShapes.get(T);
    if (!((k = e == null ? void 0 : e.selectIds) != null && k.length)) return;
    const { callback: s, ...o } = t, { updateSelectorOpt: r, willSerializeData: i } = o, a = await (e == null ? void 0 : e.updateSelector({
      updateSelectorOpt: r,
      selectIds: ie(e.selectIds),
      vNodes: this.vNodes,
      willSerializeData: i,
      worker: this
    })), c = /* @__PURE__ */ new Map();
    let n;
    a != null && a.selectIds && (n = fe(e.selectIds, a.selectIds), a.selectIds.forEach((d) => {
      const S = this.vNodes.get(d);
      if (S) {
        const { toolsType: y, op: w, opt: v } = S;
        c.set(d, {
          opt: v,
          toolsType: y,
          ops: (w == null ? void 0 : w.length) && X(w) || void 0
        });
      }
    }), e.selectIds = a.selectIds);
    const h = [], l = s && s({
      res: a,
      workShapeNode: e,
      param: o,
      postData: { sp: h },
      newServiceStore: c
    }) || { sp: h };
    n && l.sp.push({
      type: p.RemoveNode,
      removeIds: n,
      viewId: this.thread.viewId
    }), l.sp.length && this.thread.post(l);
  }
  destroy() {
    this.clearAll();
  }
  clearAll() {
    if (this.thread.localLayer.children.length && (this.thread.topLayer.parent.children.forEach((e) => {
      e.name !== "viewport" && e.remove();
    }), z(this.thread.localLayer, this.thread.localLayer.parent)), this.workShapes.get(T)) {
      const e = [];
      e.push({
        type: p.Select,
        dataType: g.Local,
        selectIds: [],
        willSyncService: !1
      }), this.thread.post({ sp: e });
    }
    this.workShapes.clear(), this.effectSelectNodeData.clear(), this.batchEraserWorks.clear(), this.batchEraserRemoveNodes.clear();
  }
  async checkTextActive(t) {
    const { op: e, viewId: s, dataType: o } = t;
    if (e != null && e.length) {
      let r;
      for (const i of this.vNodes.curNodeMap.values()) {
        const { rect: a, name: c, toolsType: n, opt: h } = i, l = e[0] * this.thread.fullLayer.worldScaling[0] + this.thread.fullLayer.worldPosition[0], k = e[1] * this.thread.fullLayer.worldScaling[1] + this.thread.fullLayer.worldPosition[1];
        if (n === f.Text && le([l, k], a) && h.workState === W.Done) {
          r = c;
          break;
        }
      }
      r && (await this.blurSelector({
        viewId: s,
        msgType: p.Select,
        dataType: o,
        isSync: !0
      }), this.thread.post({
        sp: [{
          type: p.GetTextActive,
          toolsType: f.Text,
          workId: r
        }]
      }));
    }
  }
  cursorHover(t) {
    const { opt: e, toolsType: s, point: o } = t, r = this.setFullWork({
      workId: F,
      toolsType: s,
      opt: e
    });
    r && o && r.cursorHover(o);
  }
  cursorBlur() {
    var e;
    const t = this.getWorkShape(F);
    t && ((e = t.selectIds) != null && e.length) && (t.cursorBlur(), this.clearWorkShapeNodeCache(F)), this.thread.fullLayer.parent.children.forEach((s) => {
      s.name === "Cursor_Hover_Id" && s.remove();
    });
  }
  updateFullSelectWork(t) {
    var o, r, i, a, c;
    const e = this.workShapes.get(T), { selectIds: s } = t;
    if (!(s != null && s.length)) {
      this.blurSelector(t);
      return;
    }
    if (!e) {
      const n = this.setFullWork(t);
      !n && t.workId && this.tmpOpt && ((o = this.tmpOpt) == null ? void 0 : o.toolsType) === f.Selector && this.setWorkOptions(t.workId.toString(), t.opt || this.tmpOpt.toolsOpt), n && this.updateFullSelectWork(t);
      return;
    }
    if (e && (s != null && s.length)) {
      const { selectRect: n } = e.updateSelectIds(s), h = [{
        ...t,
        selectorColor: ((r = t.opt) == null ? void 0 : r.strokeColor) || e.selectorColor,
        strokeColor: ((i = t.opt) == null ? void 0 : i.strokeColor) || e.strokeColor,
        fillColor: ((a = t.opt) == null ? void 0 : a.fillColor) || e.fillColor,
        textOpt: ((c = t.opt) == null ? void 0 : c.textOpt) || e.textOpt,
        canTextEdit: e.canTextEdit,
        canRotate: e.canRotate,
        scaleType: e.scaleType,
        type: p.Select,
        selectRect: n,
        points: e.getChildrenPoints(),
        willSyncService: (t == null ? void 0 : t.willSyncService) || !1,
        opt: (t == null ? void 0 : t.willSyncService) && e.getWorkOptions() || void 0,
        canLock: e.canLock,
        isLocked: e.isLocked,
        toolsTypes: e.toolsTypes,
        shapeOpt: e.shapeOpt,
        thickness: e.thickness,
        useStroke: e.useStroke,
        strokeType: e.strokeType
      }];
      this.thread.post({ sp: h });
    }
  }
  commandDeleteText(t) {
    const e = this.vNodes.get(t);
    if (e && e.toolsType === f.Text)
      return {
        type: p.TextUpdate,
        toolsType: f.Text,
        workId: t,
        dataType: g.Local
      };
  }
  async removeSelector(t) {
    const { willSyncService: e } = t, s = [], o = [], r = this.workShapes.get(T);
    if (!r)
      return;
    const i = r.selectIds && [...r.selectIds] || [];
    for (const a of i) {
      if (this.vNodes.get(a)) {
        const n = this.commandDeleteText(a);
        n && s.push(n);
      }
      this.removeNode(a), o.push(a);
    }
    o.length && s.push({
      type: p.RemoveNode,
      removeIds: o
    }), s.push({
      type: p.Select,
      selectIds: [],
      willSyncService: e
    }), await this.blurSelector(), s.length && this.thread.post({ sp: s });
  }
  removeWork(t) {
    const { workId: e } = t, s = e == null ? void 0 : e.toString();
    s && this.removeNode(s);
  }
  removeNode(t) {
    var o;
    this.vNodes.get(t) && ((o = this.thread.fullLayer) == null || o.getElementsByName(t).forEach((r) => {
      r.remove(), R(r, this.thread.fullLayer.parent);
    }), this.vNodes.delete(t)), this.workShapes.has(t) && (this.thread.localLayer.getElementsByName(t).forEach((r) => {
      r.remove(), R(r, this.thread.localLayer.parent);
    }), this.clearWorkShapeNodeCache(t));
  }
  setFullWork(t) {
    const { workId: e, opt: s, toolsType: o } = t;
    if (e && s && o) {
      const r = e.toString();
      let i;
      return e && this.workShapes.has(r) ? (i = this.workShapes.get(r), i == null || i.setWorkOptions(s)) : i = this.createWorkShapeNode({
        toolsOpt: s,
        toolsType: o,
        workId: r
      }), i ? (this.workShapes.set(r, i), i) : void 0;
    }
  }
  async consumeFull(t) {
    var o;
    const e = this.setFullWork(t), s = t.ops && U(t.ops);
    if (e) {
      const r = (o = t.workId) == null ? void 0 : o.toString();
      e.toolsType === f.Image ? await e.consumeServiceAsync({
        isFullWork: !0,
        replaceId: r,
        worker: this
      }) : e.toolsType === f.Text ? await e.consumeServiceAsync({
        isFullWork: !0,
        replaceId: r
      }) : e.consumeService({
        op: s,
        isFullWork: !0,
        replaceId: r
      }), t != null && t.updateNodeOpt && e.updataOptService(t.updateNodeOpt);
      const i = [];
      t.workId && this.workShapes.delete(t.workId.toString()), t.willSyncService && i.push({
        opt: t.opt,
        toolsType: t.toolsType,
        type: p.FullWork,
        workId: t.workId,
        ops: t.ops,
        updateNodeOpt: t.updateNodeOpt,
        viewId: this.thread.viewId
      }), i.length && this.thread.post({ sp: i });
    }
  }
  async colloctEffectSelectWork(t) {
    const e = this.workShapes.get(T), { workId: s, msgType: o } = t;
    if (e && s && e.selectIds && e.selectIds.includes(s.toString())) {
      o === p.RemoveNode ? e.selectIds = e.selectIds.filter((r) => r !== s.toString()) : this.effectSelectNodeData.add(t), await new Promise((r) => {
        setTimeout(() => {
          r(!0);
        }, 0);
      }), await this.runEffectSelectWork(!0).then(() => {
        var r;
        (r = this.effectSelectNodeData) == null || r.clear();
      });
      return;
    }
    return t;
  }
  async runEffectSelectWork(t) {
    var e;
    for (const s of this.effectSelectNodeData.values()) {
      const o = this.setFullWork(s);
      if (o) {
        const r = (e = s.workId) == null ? void 0 : e.toString();
        if (o.toolsType === f.Image)
          await o.consumeServiceAsync({
            isFullWork: !0,
            replaceId: r,
            worker: this
          });
        else if (o.toolsType === f.Text)
          await o.consumeServiceAsync({
            isFullWork: !0,
            replaceId: r
          });
        else {
          const i = s.ops && U(s.ops);
          o.consumeService({
            op: i,
            isFullWork: !0,
            replaceId: r
          }), s != null && s.updateNodeOpt && o.updataOptService(s.updateNodeOpt);
        }
        s.workId && this.workShapes.delete(s.workId.toString());
      }
    }
    this.reRenderSelector(t);
  }
  hasSelector() {
    return this.workShapes.has(T);
  }
  getSelector() {
    return this.workShapes.get(T);
  }
  reRenderSelector(t = !1) {
    var o;
    const e = this.workShapes.get(T);
    if (!e) return;
    if (e && !((o = e.selectIds) != null && o.length))
      return this.blurSelector();
    const s = e.reRenderSelector();
    s && this.thread.post({
      sp: [{
        type: p.Select,
        selectIds: e.selectIds,
        selectRect: s,
        willSyncService: t,
        viewId: this.thread.viewId,
        points: e.getChildrenPoints(),
        textOpt: e.textOpt,
        selectorColor: e.selectorColor,
        strokeColor: e.strokeColor,
        fillColor: e.fillColor,
        canTextEdit: e.canTextEdit,
        canRotate: e.canRotate,
        scaleType: e.scaleType,
        opt: e.getWorkOptions() || void 0,
        canLock: e.canLock,
        isLocked: e.isLocked,
        toolsTypes: e.toolsTypes,
        shapeOpt: e.shapeOpt,
        thickness: e.thickness,
        useStroke: e.useStroke,
        strokeType: e.strokeType
      }]
    });
  }
  async blurSelector(t) {
    var o;
    const e = this.workShapes.get(T), s = e == null ? void 0 : e.blurSelector();
    if (this.clearWorkShapeNodeCache(T), ((o = this.thread.fullLayer) == null ? void 0 : o.parent).children.forEach((r) => {
      r.name === T && r.remove();
    }), s) {
      const r = [];
      r.push({
        ...s,
        isSync: t == null ? void 0 : t.isSync
      }), this.thread.post({ sp: r });
    }
  }
  clearWorkShapeNodeCache(t) {
    var e;
    (e = this.getWorkShape(t)) == null || e.clearTmpPoints(), this.workShapes.delete(t);
  }
  async drawBitMapEraserFull(t, e, s) {
    const { willUpdateNodes: o, willDeleteNodes: r } = e, i = t.getWorkId(), a = [
      {
        type: p.RemoveNode,
        removeIds: [i],
        viewId: this.thread.viewId
      }
    ];
    if (s && a.push({
      type: p.None,
      isLockSentEventCursor: s
    }), o != null && o.size || r != null && r.size) {
      if (o != null && o.size)
        for (const [c, n] of o)
          a.push({
            type: p.UpdateNode,
            dataType: g.Local,
            opt: n.opt,
            workId: c,
            updateNodeOpt: {
              useAnimation: !1
            }
          });
      r != null && r.size && a.push({
        type: p.RemoveNode,
        removeIds: [...r],
        viewId: this.thread.viewId
      });
    }
    a.length && this.thread.post({ sp: a });
  }
  drawPencilEraser(t, e) {
    var o, r;
    const s = [];
    if ((o = t.newWorkDatas) != null && o.size) {
      for (const i of t.newWorkDatas.values()) {
        const a = i.workId.toString();
        this.batchEraserWorks.add(a), s.push({
          type: p.FullWork,
          workId: a,
          ops: X(i.op),
          opt: i.opt,
          toolsType: i.toolsType,
          updateNodeOpt: {
            useAnimation: !1
          }
        });
      }
      delete t.newWorkDatas;
    }
    (r = t.removeIds) == null || r.forEach((i) => {
      this.batchEraserRemoveNodes.add(i);
    }), e && s.push({
      type: p.None,
      isLockSentEventCursor: e
    }), t.rect, this.thread.post({ sp: s, consumeCount: this.consumeCount }), this.batchEraserCombine();
  }
  drawEraser(t, e) {
    const s = [];
    t.removeIds && s.push(t), e && s.push({
      type: p.None,
      isLockSentEventCursor: e
    }), this.thread.post({ sp: s, consumeCount: this.consumeCount });
  }
  updateBatchEraserCombineNode(t, e) {
    for (const s of e.keys())
      this.thread.fullLayer.getElementsByName(s).forEach((o) => {
        o.remove(), R(o, this.thread.fullLayer.parent);
      });
    t.forEach((s) => {
      const o = this.vNodes.get(s);
      if (o && o.toolsType === f.Pencil && !this.thread.fullLayer.getElementsByName(s)[0]) {
        const i = this.setFullWork({ ...o, workId: s });
        i && i.consumeService({
          op: o.op,
          isFullWork: !0
        });
      }
    });
  }
  getWorkShape(t) {
    return this.workShapes.get(t);
  }
  getWorkShapes() {
    return this.workShapes;
  }
  consumeDraw(t, e) {
    const { op: s, workId: o, scenePath: r, postCount: i } = t;
    if (s != null && s.length && o) {
      const a = o.toString(), c = this.workShapes.get(a);
      if (!c)
        return;
      const n = c.toolsType;
      if (n === f.LaserPen)
        return;
      switch (this.drawWorkActiveId && this.drawWorkActiveId !== a && (this.consumeDrawAll({
        workId: this.drawWorkActiveId,
        scenePath: r,
        viewId: this.thread.viewId,
        msgType: p.DrawWork,
        dataType: g.Local
      }, e), this.drawWorkActiveId = void 0), !this.drawWorkActiveId && a !== T && (this.drawWorkActiveId = a), H(i) && (this.consumeCount = i), n) {
        case f.Selector:
          {
            const h = c.consume({
              data: t,
              isFullWork: !0
            });
            h.type === p.Select && (h.selectIds && e.runReverseSelectWork(h.selectIds), this.thread.post({ sp: [h] }));
          }
          break;
        case f.PencilEraser:
          {
            const h = c.consume({
              data: t,
              isFullWork: !0
            });
            this.drawPencilEraser(h);
          }
          break;
        case f.BitMapEraser: {
          const h = c.consume({
            data: t,
            isFullWork: !1,
            isMainThread: !0
          });
          this.fullWorkerDrawCount++, this.thread.post({
            consumeCount: this.consumeCount,
            fullWorkerDrawCount: this.fullWorkerDrawCount,
            sp: h.op && [{ ...h, scenePath: r }] || void 0
          });
          break;
        }
        case f.Eraser:
          {
            const h = c.consume({
              data: t,
              isFullWork: !0
            });
            this.drawEraser(h);
          }
          break;
        case f.Arrow:
        case f.Straight:
        case f.Ellipse:
        case f.Rectangle:
        case f.Star:
        case f.Polygon:
        case f.SpeechBalloon:
        case f.Pencil:
          {
            const h = c.consume({
              data: t,
              isFullWork: !1,
              isMainThread: !0
            });
            h && (this.fullWorkerDrawCount++, this.thread.post({
              consumeCount: this.consumeCount,
              fullWorkerDrawCount: this.fullWorkerDrawCount,
              sp: h.op && [{ ...h, scenePath: r }] || void 0
            }));
          }
          break;
      }
    }
  }
  consumeDrawAll(t, e) {
    var i, a, c;
    const { workId: s, scenePath: o, isLockSentEventCursor: r } = t;
    if (s) {
      const n = s.toString();
      this.drawWorkActiveId === n && (this.drawWorkActiveId = void 0);
      const h = this.workShapes.get(n);
      if (!h)
        return;
      const l = h.toolsType;
      if (l === f.LaserPen)
        return;
      const k = this.workShapes.get(F), d = (i = k == null ? void 0 : k.selectIds) == null ? void 0 : i[0], S = h.consumeAll({ data: t, workerEngine: this });
      switch (l) {
        case f.Selector:
          {
            S.selectIds && d && ((a = S.selectIds) != null && a.includes(d)) && k.cursorBlur();
            const y = [];
            r && y.push({
              type: p.None,
              isLockSentEventCursor: r
            }), S.type === p.Select && (S.selectIds && e.runReverseSelectWork(S.selectIds), y.push({ ...S, scenePath: o })), y.length && this.thread.post({ sp: y }), (c = h.selectIds) != null && c.length ? h.clearTmpPoints() : this.clearWorkShapeNodeCache(n);
          }
          break;
        case f.PencilEraser:
          this.drawPencilEraser({ ...S, scenePath: o }, r), h.clearTmpPoints();
          break;
        case f.BitMapEraser:
          this.drawBitMapEraserFull(h, S, r), this.fullWorkerDrawCount = 0, this.clearWorkShapeNodeCache(n);
          break;
        case f.Eraser:
          this.drawEraser({ ...S, scenePath: o }, r), h.clearTmpPoints();
          break;
        case f.Arrow:
        case f.Straight:
        case f.Ellipse:
        case f.Rectangle:
        case f.Star:
        case f.Polygon:
        case f.SpeechBalloon:
        case f.Pencil: {
          const y = [];
          r && y.push({
            type: p.None,
            isLockSentEventCursor: r
          }), S && (y.push(S), this.fullWorkerDrawCount = 0, this.thread.post({
            fullWorkerDrawCount: this.fullWorkerDrawCount,
            sp: y
          })), this.clearWorkShapeNodeCache(n);
          break;
        }
      }
    }
  }
  getToolsOpt() {
    return this.tmpOpt;
  }
  setToolsOpt(t) {
    var e;
    this.tmpOpt = t, (e = t.toolsOpt) != null && e.syncUnitTime && (this.syncUnitTime = t.toolsOpt.syncUnitTime);
  }
  setWorkOptions(t, e) {
    let s = this.workShapes.get(t);
    if (!s && this.tmpOpt) {
      const { toolsType: o } = this.tmpOpt;
      this.tmpOpt.toolsOpt = e, s = this.createWorkShapeNode({ workId: t, toolsType: o, toolsOpt: e }), s && this.workShapes.set(t, s), this.setToolsOpt(this.tmpOpt);
    }
    e.syncUnitTime || (e.syncUnitTime = this.syncUnitTime), s == null || s.setWorkOptions(e);
  }
  createWorkShapeNode(t) {
    return $({ ...t, vNodes: this.vNodes, fullLayer: this.thread.fullLayer, drawLayer: this.thread.localLayer }, this.thread.serviceWork);
  }
}
class Se {
  constructor(t) {
    u(this, "vNodes");
    u(this, "thread");
    u(this, "workShapes", /* @__PURE__ */ new Map());
    u(this, "selectorWorkShapes", /* @__PURE__ */ new Map());
    u(this, "willRunEffectSelectorIds", /* @__PURE__ */ new Set());
    u(this, "runEffectId");
    u(this, "animationId");
    u(this, "syncUnitTime", B.syncOpt.interval);
    this.vNodes = t.vNodes, this.thread = t.thread;
  }
  async loadImageBitMap(t) {
    return await this.thread.loadImageBitMap(t);
  }
  destroy() {
    this.clearAll();
  }
  clearAll() {
    this.thread.serviceLayer.children.length && (this.thread.serviceLayer.parent.children.forEach((t) => {
      t.name !== "viewport" && t.remove();
    }), z(this.thread.serviceLayer, this.thread.serviceLayer.parent)), this.workShapes.clear(), this.selectorWorkShapes.clear(), this.willRunEffectSelectorIds.clear();
  }
  runEffect() {
    this.runEffectId || (this.runEffectId = setTimeout(this.effectRunSelector.bind(this), 0));
  }
  effectRunSelector() {
    this.runEffectId = void 0, this.willRunEffectSelectorIds.forEach((t) => {
      var s, o;
      const e = this.selectorWorkShapes.get(t);
      e && e.selectIds && ((s = e.node) == null || s.selectServiceNode(t, e, !0)), (o = e == null ? void 0 : e.selectIds) != null && o.length || this.selectorWorkShapes.delete(t);
    }), this.willRunEffectSelectorIds.clear();
  }
  runSelectWork(t) {
    this.activeSelectorShape(t);
    const { workId: e } = t, s = e == null ? void 0 : e.toString();
    s && this.willRunEffectSelectorIds.add(s), this.runEffect();
  }
  removeWork(t) {
    const { workId: e } = t, s = e == null ? void 0 : e.toString();
    if (s) {
      if (this.workShapes.get(s)) {
        this.workShapes.delete(s), this.removeNode(s, t);
        return;
      }
      this.removeNode(s, t);
    }
  }
  consumeFull(t) {
    this.activeWorkShape(t), this.runAnimation();
  }
  runReverseSelectWork(t) {
    t.forEach((e) => {
      this.selectorWorkShapes.forEach((s, o) => {
        var r;
        if ((r = s.selectIds) != null && r.length) {
          const i = s.selectIds.indexOf(e);
          i > -1 && (s.selectIds.splice(i, 1), this.willRunEffectSelectorIds.add(o));
        }
      });
    }), this.willRunEffectSelectorIds.size && this.runEffect();
  }
  consumeDraw(t) {
    this.activeWorkShape(t), this.runAnimation();
  }
  computNextAnimationIndex(t, e) {
    const s = Math.floor((t.animationWorkData || []).slice(t.animationIndex).length * 32 / e / this.syncUnitTime) * e;
    return Math.min((t.animationIndex || 0) + (s || e), (t.animationWorkData || []).length);
  }
  async animationDraw() {
    var s, o, r, i, a, c, n, h, l, k, d, S, y, w, v, D, x, Z, j;
    this.animationId = void 0;
    let t = !1;
    const e = /* @__PURE__ */ new Map();
    for (const [N, m] of this.workShapes.entries())
      switch (m.toolsType) {
        case f.Image: {
          await ((s = m.node) == null ? void 0 : s.consumeServiceAsync({
            isFullWork: !0,
            worker: this
          })), this.selectorWorkShapes.forEach((b, C) => {
            var O;
            (O = b.selectIds) != null && O.includes(N) && (this.willRunEffectSelectorIds.add(C), this.runEffect());
          }), this.workShapes.delete(N);
          break;
        }
        case f.Text: {
          m.node && (await ((o = m.node) == null ? void 0 : o.consumeServiceAsync({
            isFullWork: !0,
            replaceId: N
          })), this.selectorWorkShapes.forEach((b, C) => {
            var O;
            (O = b.selectIds) != null && O.includes(N) && (this.willRunEffectSelectorIds.add(C), this.runEffect());
          }), (r = m.node) == null || r.clearTmpPoints(), this.workShapes.delete(N));
          break;
        }
        case f.Arrow:
        case f.Straight:
        case f.Rectangle:
        case f.Ellipse:
        case f.Star:
        case f.Polygon:
        case f.SpeechBalloon: {
          const b = !!m.ops;
          if ((i = m.animationWorkData) != null && i.length) {
            const C = m.oldRect;
            (a = m.node) == null || a.consumeService({
              op: m.animationWorkData,
              isFullWork: b
            }), b && (this.selectorWorkShapes.forEach((O, E) => {
              var A;
              (A = O.selectIds) != null && A.includes(N) && (this.willRunEffectSelectorIds.add(E), this.runEffect());
            }), (c = m.node) == null || c.clearTmpPoints(), this.workShapes.delete(N)), e.set(N, {
              workState: C ? m.ops ? W.Done : W.Doing : W.Start,
              op: m.animationWorkData.filter((O, E) => {
                if (E % 3 !== 2)
                  return !0;
              }).slice(-2)
            }), m.animationWorkData.length = 0;
          }
          break;
        }
        case f.Pencil: {
          if (!m.useAnimation && m.ops)
            (n = m.node) == null || n.consumeService({
              op: m.animationWorkData || [],
              isFullWork: !0,
              replaceId: N
            }), (h = m.node) == null || h.updataOptService(m.updateNodeOpt), this.selectorWorkShapes.forEach((b, C) => {
              var O;
              (O = b.selectIds) != null && O.includes(N) && (this.willRunEffectSelectorIds.add(C), this.runEffect());
            }), (l = m.node) == null || l.clearTmpPoints(), this.workShapes.delete(N);
          else if (m.useAnimation) {
            if (m.isDel) {
              (k = m.node) == null || k.clearTmpPoints(), this.workShapes.delete(N);
              break;
            }
            const b = 3, C = this.computNextAnimationIndex(m, b), O = m.isDiff ? 0 : Math.max(0, (m.animationIndex || 0) - b), E = (m.animationWorkData || []).slice(O, C), A = (S = (d = m.node) == null ? void 0 : d.getWorkId()) == null ? void 0 : S.toString();
            if ((m.animationIndex || 0) < C || m.isDiff) {
              if ((y = m.node) == null || y.consumeService({
                op: E,
                isFullWork: !1
              }), m.animationIndex = C, m.isDiff && (m.isDiff = !1), E.length) {
                const q = E.filter((_, ae) => {
                  if (ae % b !== b - 1)
                    return !0;
                }).slice(-2);
                e.set(N, {
                  workState: O === 0 ? W.Start : C === ((w = m.animationWorkData) == null ? void 0 : w.length) ? W.Done : W.Doing,
                  op: q
                });
              }
            } else m.ops && ((v = m.node) == null || v.consumeService({
              op: m.animationWorkData || [],
              isFullWork: !0,
              replaceId: A
            }), m.isDel = !0, e.set(N, {
              workState: W.Done,
              op: E.filter((q, _) => {
                if (_ % b !== b - 1)
                  return !0;
              }).slice(-2)
            }));
            t = !0;
            break;
          }
          break;
        }
        case f.BitMapEraser:
        case f.PencilEraser: {
          if (m.isDel) {
            (D = m.node) == null || D.clearTmpPoints(), this.workShapes.delete(N);
            break;
          }
          if (m.ops && ((x = m.animationWorkData) != null && x.length)) {
            const b = m.animationWorkData.slice(-3, -1);
            e.set(N, {
              workState: W.Done,
              op: b
            }), m.isDel = !0;
            break;
          }
          if (m.useAnimation) {
            const C = this.computNextAnimationIndex(m, 3), O = m.isDiff ? 0 : Math.max(0, (m.animationIndex || 0) - 3), E = (m.animationWorkData || []).slice(O, C);
            if (((m.animationIndex || 0) < C || m.isDiff) && ((Z = m.node) == null || Z.consumeService({
              op: E,
              isFullWork: m.toolsType !== f.BitMapEraser
            }), m.animationIndex = C, m.isDiff && (m.isDiff = !1), E.length)) {
              const A = E.filter((q, _) => {
                if (_ % 3 !== 2)
                  return !0;
              }).slice(-2);
              e.set(N, {
                workState: O === 0 ? W.Start : C === ((j = m.animationWorkData) == null ? void 0 : j.length) ? W.Done : W.Doing,
                op: A
              });
            }
            t = !0;
            break;
          }
          break;
        }
      }
    if (t && this.runAnimation(), e.size) {
      const N = [];
      e.forEach((m, b) => {
        N.push({
          type: p.Cursor,
          uid: b.split(te)[0],
          op: m.op,
          workState: m.workState,
          viewId: this.thread.viewId
        });
      }), this.thread.post({ sp: N });
    }
  }
  runAnimation() {
    this.animationId || (this.animationId = requestAnimationFrame(this.animationDraw.bind(this)));
  }
  hasDiffData(t, e, s) {
    const o = t.length;
    if (e.length < o)
      return !0;
    switch (s) {
      case f.Pencil: {
        for (let r = 0; r < o; r += 3)
          if (e[r] !== t[r] || e[r + 1] !== t[r + 1])
            return !0;
        break;
      }
      case f.LaserPen: {
        for (let r = 0; r < o; r += 2)
          if (e[r] !== t[r] || e[r + 1] !== t[r + 1])
            return !0;
        break;
      }
    }
    return !1;
  }
  activeWorkShape(t) {
    var S, y, w, v;
    const { workId: e, opt: s, toolsType: o, type: r, updateNodeOpt: i, ops: a, op: c, useAnimation: n, imageBitmap: h } = t;
    if (!e)
      return;
    const l = e.toString(), k = (S = this.vNodes.get(l)) == null ? void 0 : S.rect;
    if (!((y = this.workShapes) != null && y.has(l))) {
      let D = {
        toolsType: o,
        animationWorkData: c || [],
        animationIndex: 0,
        type: r,
        updateNodeOpt: i,
        ops: a,
        useAnimation: typeof n < "u" ? n : typeof (i == null ? void 0 : i.useAnimation) < "u" ? i == null ? void 0 : i.useAnimation : !0,
        oldRect: k,
        isDiff: !1,
        imageBitmap: h
      };
      o && s && (D = this.setNodeKey(l, D, o, s)), (w = this.workShapes) == null || w.set(l, D);
    }
    const d = (v = this.workShapes) == null ? void 0 : v.get(l);
    r && (d.type = r), a && (d.animationWorkData = U(a), d.ops = a), i && (d.updateNodeOpt = i), c && (d.isDiff = this.hasDiffData(d.animationWorkData || [], c, d.toolsType), d.animationWorkData = c), d.node && d.node.getWorkId() !== l && d.node.setWorkId(l), k && (d.oldRect = k), o && s && (s.syncUnitTime && (this.syncUnitTime = s.syncUnitTime), d.toolsType !== o && o && s && this.setNodeKey(l, d, o, s), d.node && d.node.setWorkOptions(s)), h && (d.imageBitmap = h);
  }
  removeNode(t, e) {
    t.indexOf(T) > -1 && this.removeSelectWork(e), this.thread.fullLayer.getElementsByName(t).forEach((s) => {
      s.remove(), R(s, this.thread.fullLayer.parent);
    }), this.thread.serviceLayer.getElementsByName(t).forEach((s) => {
      s.remove(), R(s, this.thread.serviceLayer.parent);
    }), this.vNodes.delete(t);
  }
  removeSelectWork(t) {
    const { workId: e } = t, s = e == null ? void 0 : e.toString();
    s && (this.activeSelectorShape(t), this.willRunEffectSelectorIds.add(s)), this.runEffect();
  }
  activeSelectorShape(t) {
    var n, h, l;
    const { workId: e, opt: s, toolsType: o, type: r, selectIds: i } = t;
    if (!e)
      return;
    const a = e.toString();
    if (!((n = this.selectorWorkShapes) != null && n.has(a))) {
      let k = {
        toolsType: o,
        selectIds: i,
        type: r,
        opt: s
      };
      o && s && (k = this.setNodeKey(a, k, o, s)), (h = this.selectorWorkShapes) == null || h.set(a, k);
    }
    const c = (l = this.selectorWorkShapes) == null ? void 0 : l.get(a);
    r && (c.type = r), c.node && c.node.getWorkId() !== a && c.node.setWorkId(a), c.selectIds = i || [];
  }
  setNodeKey(t, e, s, o) {
    return e.toolsType = s, e.node = $({
      toolsType: s,
      toolsOpt: o,
      vNodes: this.vNodes,
      fullLayer: this.thread.fullLayer,
      drawLayer: this.thread.serviceLayer,
      workId: t
    }, this), e;
  }
}
class M {
  constructor() {
    u(this, "localWork");
    u(this, "serviceWork");
    u(this, "threadEngine");
  }
  registerMainThread(t) {
    return this.threadEngine = t, this.localWork = t.localWork, this.serviceWork = t.serviceWork, this;
  }
}
class ye extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.CopyNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.FullWork && o === g.Local && r === this.emitEventType)
      return this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var o;
    const { workId: s } = e;
    s && await ((o = this.localWork) == null ? void 0 : o.consumeFull(e));
  }
}
class we extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.SetColorNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a, textUpdateForWoker: c } = e;
    s === T && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      textUpdateForWoker: c,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r } = e, { willSyncService: i, isSync: a, textUpdateForWoker: c } = s, n = o.sp || [];
    if (i)
      for (const [h, l] of r.entries())
        c && l.toolsType === f.Text ? n.push({
          ...l,
          workId: h,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : n.push(
          {
            ...l,
            workId: h,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
    return {
      sp: n
    };
  }
}
class ve extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.ZIndexNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var c;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a } = e;
    s === T && o && await ((c = this.localWork) == null ? void 0 : c.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r } = e, { willSyncService: i, isSync: a } = s, c = o.sp || [];
    if (i && c)
      for (const [n, h] of r.entries())
        c.push(
          {
            ...h,
            workId: n,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
    return {
      sp: c
    };
  }
}
class ge extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.TranslateNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return await this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var h, l;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a, textUpdateForWoker: c, emitEventType: n } = e;
    s === T && o && (o.workState === W.Done && (o != null && o.translate) && (o.translate[0] || o.translate[1]) || o.workState !== W.Done ? await ((h = this.localWork) == null ? void 0 : h.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      isSync: !0,
      textUpdateForWoker: c,
      emitEventType: n,
      callback: this.updateSelectorCallback
    })) : o.workState === W.Done && ((l = this.localWork) == null || l.vNodes.deleteLastTarget()));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: a } = e, { willSyncService: c, isSync: n, updateSelectorOpt: h, textUpdateForWoker: l } = s, k = h.workState, d = o.sp || [];
    if (k === W.Start)
      return {
        sp: [],
        render: []
      };
    const S = a == null ? void 0 : a.selectRect;
    if (c) {
      k === W.Doing && d.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: S,
        willSyncService: !0,
        isSync: !0,
        points: i.getChildrenPoints(),
        textOpt: i.textOpt
      });
      for (const [y, w] of r.entries())
        l && w.toolsType === f.Text ? d.push({
          ...w,
          workId: y,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : d.push(
          {
            ...w,
            workId: y,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: n
          }
        );
    }
    return {
      sp: d
    };
  }
}
class Ie extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.DeleteNode);
  }
  async consume() {
    return !1;
  }
}
class We extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.ScaleNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return await this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var a;
    const { workId: s, updateNodeOpt: o, willSyncService: r, willSerializeData: i } = e;
    s === T && o && await ((a = this.localWork) == null ? void 0 : a.updateSelector({
      updateSelectorOpt: o,
      willSyncService: r,
      willSerializeData: i,
      isSync: !0,
      callback: this.updateSelectorCallback.bind(this)
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, workShapeNode: r, res: i, newServiceStore: a } = e, { updateSelectorOpt: c, willSyncService: n } = s, h = c.workState, l = o.sp || [], k = i == null ? void 0 : i.selectRect;
    if (h === W.Start)
      return {
        sp: [],
        render: []
      };
    if (n) {
      l.push({
        type: p.Select,
        selectIds: r.selectIds,
        selectRect: k,
        willSyncService: !0,
        isSync: !0,
        points: h === W.Done && r.getChildrenPoints() || void 0,
        textOpt: r.textOpt
      });
      for (const [d, S] of a.entries())
        S.toolsType === f.Text ? l.push({
          ...S,
          workId: d,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : l.push(
          {
            ...S,
            workId: d,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: !0
          }
        );
    }
    return {
      sp: l
    };
  }
}
class Te extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.RotateNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return await this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a, emitEventType: c } = e;
    s === T && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      emitEventType: c,
      isSync: !0,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, workShapeNode: r, res: i, newServiceStore: a } = e, { updateSelectorOpt: c, willSyncService: n, willSerializeData: h, isSync: l } = s, k = c.workState, d = o.sp || [], S = i == null ? void 0 : i.selectRect;
    if (n) {
      h && k === W.Done && d.push({
        type: p.Select,
        selectIds: r.selectIds,
        selectRect: S,
        willSyncService: !0,
        isSync: l,
        points: r.getChildrenPoints()
      });
      for (const [y, w] of a.entries())
        d.push(
          {
            ...w,
            workId: y,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: l
          }
        );
    }
    return {
      sp: d
    };
  }
}
class Le extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.SetFontStyle);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return await this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a, textUpdateForWoker: c } = e;
    s === T && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      textUpdateForWoker: c,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: a } = e, { willSyncService: c, isSync: n, updateSelectorOpt: h, textUpdateForWoker: l } = s, k = o.sp || [], d = a == null ? void 0 : a.selectRect;
    if (c && k) {
      h.fontSize && k.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: d,
        willSyncService: c,
        isSync: n,
        points: i.getChildrenPoints()
      });
      for (const [S, y] of r.entries())
        l && y.toolsType === f.Text ? k.push({
          ...y,
          workId: S,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : k.push(
          {
            ...y,
            workId: S,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: n
          }
        );
    }
    return {
      sp: k
    };
  }
}
class Ne extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.SetPoint);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a, textUpdateForWoker: c } = e;
    s === T && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      emitEventType: this.emitEventType,
      willSerializeData: a,
      isSync: !0,
      textUpdateForWoker: c,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: a } = e, { willSyncService: c, isSync: n } = s, h = o.sp || [], l = a == null ? void 0 : a.selectRect;
    if (c && h) {
      for (const [k, d] of r.entries())
        h.push(
          {
            ...d,
            workId: k,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: n
          }
        );
      h.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: l,
        willSyncService: c,
        isSync: n,
        points: i.getChildrenPoints()
      });
    }
    return {
      sp: h
    };
  }
}
class be extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.SetLock);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var c;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a } = e;
    s === T && o && await ((c = this.localWork) == null ? void 0 : c.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: a } = e, { willSyncService: c, isSync: n, updateSelectorOpt: h } = s, l = o.sp || [], k = a == null ? void 0 : a.selectRect;
    if (c && l) {
      for (const [d, S] of r.entries())
        l.push(
          {
            ...S,
            workId: d,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: n
          }
        );
      l.push({
        isLocked: h.isLocked,
        selectorColor: i.selectorColor,
        scaleType: i.scaleType,
        canRotate: i.canRotate,
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: k,
        willSyncService: c,
        isSync: n
      });
    }
    return {
      sp: l
    };
  }
}
class De extends M {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", I.SetShapeOpt);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === g.Local && r === this.emitEventType)
      return this.consumeForLocalWorker(e), !0;
  }
  async consumeForLocalWorker(e) {
    var c;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: a } = e;
    s === T && o && await ((c = this.localWork) == null ? void 0 : c.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: a,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r } = e, { willSyncService: i, isSync: a } = s, c = o.sp || [];
    if (i && c)
      for (const [n, h] of r.entries())
        c.push(
          {
            ...h,
            workId: n,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
    return {
      sp: c
    };
  }
}
class Ce {
  constructor(t) {
    u(this, "builders", /* @__PURE__ */ new Map());
    this.builders = new Map(t.map((e) => [e, this.build(e)]));
  }
  build(t) {
    switch (t) {
      case I.TranslateNode:
        return new ge();
      case I.ZIndexNode:
        return new ve();
      case I.CopyNode:
        return new ye();
      case I.SetColorNode:
        return new we();
      case I.DeleteNode:
        return new Ie();
      case I.ScaleNode:
        return new We();
      case I.RotateNode:
        return new Te();
      case I.SetFontStyle:
        return new Le();
      case I.SetPoint:
        return new Ne();
      case I.SetLock:
        return new be();
      case I.SetShapeOpt:
        return new De();
    }
  }
  registerForMainThread(t) {
    return this.builders.forEach((e) => {
      e && e.registerMainThread(t);
    }), this;
  }
  async consumeForMainThread(t) {
    for (const e of this.builders.values())
      if (await (e == null ? void 0 : e.consume(t)))
        return !0;
    return !1;
  }
}
class Oe {
  constructor(t, e) {
    u(this, "viewId");
    u(this, "fullLayer");
    u(this, "topLayer");
    u(this, "localLayer");
    u(this, "serviceLayer");
    u(this, "snapshotFullLayer");
    u(this, "vNodes");
    u(this, "master");
    u(this, "opt");
    u(this, "cameraOpt");
    u(this, "scene");
    u(this, "localWork");
    u(this, "serviceWork");
    u(this, "topWork");
    u(this, "taskUpdateCameraId");
    u(this, "debounceUpdateCameraId");
    u(this, "debounceUpdateCache", /* @__PURE__ */ new Set());
    u(this, "mainThreadPostId");
    u(this, "combinePostMsg", /* @__PURE__ */ new Set());
    u(this, "methodBuilder");
    u(this, "cacheImages", /* @__PURE__ */ new Map());
    u(this, "imageResolveMap", /* @__PURE__ */ new Map());
    this.viewId = t, this.opt = e, this.scene = this.createScene({ ...e.canvasOpt, container: e.container }), this.master = e.master;
    const s = B.bufferSize.full, o = B.bufferSize.sub;
    this.fullLayer = this.createLayer("fullLayer", this.scene, { ...e.layerOpt, bufferSize: this.viewId === P ? s : o * 2 }), this.topLayer = this.createLayer("topLayer", this.scene, { ...e.layerOpt, bufferSize: (this.viewId === P, o), contextType: "2d" }), this.localLayer = this.createLayer("localLayer", this.scene, { ...e.layerOpt, bufferSize: (this.viewId === P, o), contextType: "2d" }), this.serviceLayer = this.createLayer("serviceLayer", this.scene, { ...e.layerOpt, bufferSize: (this.viewId === P, o), contextType: "2d" }), this.vNodes = new pe(t, this.scene);
    const r = {
      thread: this,
      vNodes: this.vNodes
    };
    this.localWork = new ke(r), this.serviceWork = new Se(r), this.topWork = new me(r), this.vNodes.init(this.fullLayer), this.methodBuilder = new Ce([
      I.CopyNode,
      I.SetColorNode,
      I.DeleteNode,
      I.RotateNode,
      I.ScaleNode,
      I.TranslateNode,
      I.ZIndexNode,
      I.SetFontStyle,
      I.SetPoint,
      I.SetLock,
      I.SetShapeOpt
    ]).registerForMainThread(this);
  }
  getCachedImages(t) {
    var e;
    return (e = this.cacheImages.get(t)) == null ? void 0 : e.imageBitmap;
  }
  getCachedImagesByWorkId(t) {
    for (const [e, s] of this.cacheImages.entries())
      if (e === t && s.imageBitmap)
        return s.imageBitmap;
  }
  deleteCachedImagesByWorkId(t) {
    for (const [e, s] of this.cacheImages.entries())
      s.workId === t && (s.imageBitmap.close(), this.cacheImages.delete(e));
  }
  clearCacheImages() {
    this.cacheImages.forEach((t) => t.imageBitmap.close()), this.cacheImages.clear();
  }
  clearImageResolveMap() {
    this.imageResolveMap.forEach(({ timer: t }) => {
      t && clearTimeout(t);
    }), this.imageResolveMap.clear();
  }
  post(t) {
    this.combinePostMsg.add(t), this.runBatchPostData();
  }
  updateDpr(t) {
    this.scene.displayRatio = t;
  }
  async on(t) {
    if (!await this.methodBuilder.consumeForMainThread(t)) {
      const { msgType: e, toolsType: s, opt: o, dataType: r, workId: i, workState: a, imageSrc: c, imageBitmap: n, workIds: h, isLockSentEventCursor: l } = t, k = i == null ? void 0 : i.toString();
      switch (e) {
        case p.UpdateDpr:
          H(t.dpr) && this.updateDpr(t.dpr);
          break;
        case p.AuthClear: {
          const { clearUids: d, localUid: S } = t;
          this.vNodes.setCanClearUids(d), this.vNodes.setLocalUid(S);
          break;
        }
        case p.Destroy:
          this.destroy();
          break;
        case p.Clear:
          this.clearAll();
          break;
        case p.UpdateCamera:
          await this.updateCamera(t);
          break;
        case p.UpdateTools:
          if (s && o) {
            const d = {
              toolsType: s,
              toolsOpt: o
            };
            this.topWork.canUseTopLayer(s) ? this.topWork.setToolsOpt(d) : this.localWork.setToolsOpt(d);
          }
          break;
        case p.CreateWork:
          if (k && o && s) {
            if (this.topWork.canUseTopLayer(s)) {
              this.topWork.getToolsOpt() || this.topWork.setToolsOpt({
                toolsType: s,
                toolsOpt: o
              }), this.topWork.setWorkOptions(k, o);
              break;
            }
            this.localWork.getToolsOpt() || this.localWork.setToolsOpt({
              toolsType: s,
              toolsOpt: o
            }), this.localWork.setWorkOptions(k, o);
          }
          break;
        case p.DrawWork:
          a === W.Done && r === g.Local ? (this.consumeDrawAll(r, t), s === f.LaserPen && l && this.post({
            sp: [{
              type: p.None,
              isLockSentEventCursor: l
            }]
          })) : this.consumeDraw(r, t);
          break;
        case p.UpdateNode:
        case p.FullWork:
          if (s && this.topWork.canUseTopLayer(s)) {
            this.consumeDrawAll(r, t);
            break;
          }
          this.consumeFull(r, t);
          break;
        case p.RemoveNode:
          await this.removeNode(t);
          return;
        case p.Select:
          r === g.Service && (i === T ? this.localWork.updateFullSelectWork(t) : this.serviceWork.runSelectWork(t));
          break;
        case p.CursorBlur:
          this.localWork.cursorBlur();
          return;
        case p.CursorHover:
          this.localWork.cursorHover(t);
          break;
        case p.GetTextActive:
          r === g.Local && this.localWork.checkTextActive(t);
          break;
        case p.GetImageBitMap:
          if (c && n && i) {
            const d = i.toString();
            this.deleteCachedImagesByWorkId(d), this.cacheImages.set(c, {
              imageBitmap: n,
              workId: d
            });
            const S = this.imageResolveMap.get(c);
            if (S) {
              const { resolve: y, timer: w } = S;
              w && clearTimeout(w), y && y(c);
            }
          }
          break;
        case p.GetVNodeInfo:
          if (i && h) {
            const d = h.map((S) => this.vNodes.get(S));
            this.post({
              sp: [
                {
                  type: p.GetVNodeInfo,
                  dataType: g.Local,
                  workId: i,
                  vInfo: d
                }
              ]
            });
          }
          break;
      }
    }
  }
  getIconSize(t, e, s) {
    const o = t * s, r = e * s;
    return o <= 50 || r <= 50 ? [50, 50] : o <= 100 || r <= 100 ? [100, 100] : o <= 200 || r <= 200 ? [200, 200] : o <= 400 || r <= 400 ? [400, 400] : o <= 800 || r <= 800 ? [800, 800] : [1600, 1600];
  }
  async loadImageBitMap(t) {
    const { toolsType: e, opt: s, workId: o } = t;
    if (e === f.Image && s && o) {
      const r = o.toString(), { src: i, type: a, width: c, height: n, strokeColor: h } = s;
      if (!i || !a || !c || !n)
        return;
      let l = i;
      if (a === se.Iconify) {
        const [y, w] = this.getIconSize(c, n, this.opt.displayer.dpr);
        l = `${i}?width=${y}&height=${w}&color=${h}`;
      }
      if (this.cacheImages.has(l)) {
        const y = this.getCachedImages(l);
        if (y)
          return y;
      }
      if (this.imageResolveMap.has(l)) {
        const y = this.getCachedImagesByWorkId(r);
        if (y)
          return y;
      }
      const S = await new Promise((y) => {
        const w = this.imageResolveMap.get(l) || {
          resolve: void 0,
          timer: void 0
        };
        w.timer && clearTimeout(w.timer), w.resolve = y, w.timer = setTimeout(() => {
          const v = this.imageResolveMap.get(l);
          v != null && v.resolve && v.resolve(l);
        }, 5e3), this.imageResolveMap.set(l, w), this.opt.post({
          sp: [{
            imageSrc: l,
            workId: r,
            viewId: this.viewId,
            isgl: !!this.fullLayer.parent.gl,
            isSubWorker: !1,
            type: p.GetImageBitMap
          }]
        });
      });
      return this.imageResolveMap.delete(S), this.getCachedImages(l);
    }
  }
  async removeNode(t) {
    const { dataType: e, workId: s, removeIds: o } = t, r = o || [];
    if (s && r.push(s.toString()), r.length)
      for (const i of r) {
        if (i === T) {
          await this.localWork.removeSelector(t);
          continue;
        }
        e === g.Local ? this.localWork.removeWork(t) : e === g.Service && this.serviceWork.removeWork(t), await this.localWork.colloctEffectSelectWork(t);
      }
  }
  async consumeFull(t, e) {
    const s = await this.localWork.colloctEffectSelectWork(e);
    s && t === g.Local && await this.localWork.consumeFull(s), s && t === g.Service && this.serviceWork.consumeFull(s);
  }
  setCameraOpt(t) {
    this.cameraOpt = t;
    const { scale: e, centerX: s, centerY: o, width: r, height: i } = t;
    (r !== this.scene.width || i !== this.scene.height) && this.updateScene({ width: r, height: i }), this.fullLayer.setAttribute("scale", [e, e]), this.fullLayer.setAttribute("translate", [-s, -o]), this.topLayer.setAttribute("scale", [e, e]), this.topLayer.setAttribute("translate", [-s, -o]), this.localLayer.setAttribute("scale", [e, e]), this.localLayer.setAttribute("translate", [-s, -o]), this.serviceLayer.setAttribute("scale", [e, e]), this.serviceLayer.setAttribute("translate", [-s, -o]);
  }
  runBatchPostData() {
    this.mainThreadPostId || (this.mainThreadPostId = requestAnimationFrame(this.combinePost.bind(this)));
  }
  combinePostData() {
    var o;
    this.mainThreadPostId = void 0;
    const t = [];
    let e, s;
    for (const r of this.combinePostMsg.values()) {
      if ((o = r.sp) != null && o.length)
        for (const i of r.sp) {
          let a = !1;
          for (const c of t)
            if (ee(i, c)) {
              a = !0;
              break;
            }
          a || t.push(i);
        }
      H(r.fullWorkerDrawCount) && (e = r.fullWorkerDrawCount), H(r.consumeCount) && (s = r.consumeCount);
    }
    return this.combinePostMsg.clear(), {
      sp: t,
      fullWorkerDrawCount: e,
      consumeCount: s
    };
  }
  combinePost() {
    var s, o;
    const t = this.combinePostData(), e = (s = t.sp) == null ? void 0 : s.filter((r) => r.type !== p.None || r.isLockSentEventCursor);
    e != null && e.length ? t.sp = e.map((r) => r.viewId ? r : { ...r, viewId: this.viewId }) : delete t.sp, t.consumeCount === void 0 && delete t.consumeCount, t.fullWorkerDrawCount === void 0 && delete t.fullWorkerDrawCount, (t != null && t.consumeCount || t != null && t.fullWorkerDrawCount || (o = t.sp) != null && o.length) && this.opt.post(t);
  }
  clearAll() {
    this.fullLayer.children.length && (this.fullLayer.parent.children.forEach((t) => {
      t.name !== "viewport" && t.remove();
    }), z(this.fullLayer, this.fullLayer.parent)), this.clearCacheImages(), this.clearImageResolveMap(), this.localWork.clearAll(), this.topWork.clearAll(), this.serviceWork.clearAll(), this.vNodes.clear(), this.post({
      sp: [{
        type: p.Clear
      }]
    });
  }
  consumeDrawAll(t, e) {
    const { toolsType: s, workId: o } = e;
    if (o) {
      const r = o.toString();
      if (s && this.topWork.canUseTopLayer(s)) {
        t === g.Local && (this.topWork.getLocalWorkShape(o.toString()) || this.topWork.createLocalWork(e)), this.topWork.consumeDrawAll(e);
        return;
      }
      t === g.Local && (this.localWork.getWorkShape(r) || this.localWork.createLocalWork(e), this.localWork.consumeDrawAll(e, this.serviceWork));
    }
  }
  consumeDraw(t, e) {
    const { opt: s, workId: o, toolsType: r } = e;
    if (o && r && s) {
      const i = o.toString();
      if (this.topWork.canUseTopLayer(r)) {
        t === g.Local && (this.topWork.getLocalWorkShape(i) || this.topWork.createLocalWork(e)), this.topWork.consumeDraw(e);
        return;
      }
      t === g.Local ? (this.localWork.getWorkShape(i) || this.localWork.createLocalWork(e), this.localWork.consumeDraw(e, this.serviceWork)) : t === g.Service && this.serviceWork.consumeDraw(e);
      return;
    }
  }
  async updateCamera(t) {
    var o;
    const { cameraOpt: e, scenePath: s } = t;
    if (e && !ee(this.cameraOpt, e)) {
      if (this.taskUpdateCameraId && (clearTimeout(this.taskUpdateCameraId), this.taskUpdateCameraId = void 0), s) {
        let n = !1;
        for (const [h, l] of this.localWork.getWorkShapes().entries())
          switch (l.toolsType) {
            case f.Text:
            case f.BitMapEraser:
            case f.PencilEraser:
            case f.Eraser:
            case f.Selector:
            case f.LaserPen:
              break;
            default:
              h !== F && h !== T && (n = !0);
              break;
          }
        if (n) {
          this.taskUpdateCameraId = setTimeout(() => {
            this.taskUpdateCameraId = void 0, this.updateCamera(t);
          }, Y);
          return;
        }
      }
      const r = /* @__PURE__ */ new Map();
      for (const [n, h] of this.vNodes.getNodesByType(f.Text).entries()) {
        const l = h.rect;
        r.set(n, ie(l));
      }
      const i = new Set(r.keys());
      let a = !1;
      if (this.localWork.hasSelector()) {
        const n = (o = this.localWork.getSelector()) == null ? void 0 : o.selectIds;
        if (n) {
          a = !0;
          for (const h of n)
            i.add(h);
        }
      }
      let c = !1;
      if (this.serviceWork.selectorWorkShapes.size)
        for (const n of this.serviceWork.selectorWorkShapes.values()) {
          const h = n.selectIds;
          if (h) {
            c = !0;
            for (const l of h)
              i.add(l);
          }
        }
      if (this.setCameraOpt(e), this.vNodes.curNodeMap.size) {
        this.vNodes.clearTarget(), this.vNodes.updateHighLevelNodesRect(i), this.debounceUpdateCameraId && clearTimeout(this.debounceUpdateCameraId);
        for (const [n, h] of r.entries()) {
          const l = this.vNodes.get(n);
          if (l) {
            const k = h, d = l.rect, S = this.getSceneRect(), y = G(k, S), w = G(d, S);
            let v = !1;
            if ((y !== w || k.w !== d.w || k.h !== d.h || w === Q.intersect) && (v = !0), v) {
              const { toolsType: D, opt: x } = l;
              D === f.Text && x.workState === W.Done && this.debounceUpdateCache.add(n);
            }
          }
        }
        if (a && this.localWork.reRenderSelector(), c)
          for (const [n, h] of this.serviceWork.selectorWorkShapes.entries())
            this.serviceWork.runSelectWork({
              workId: n,
              selectIds: h.selectIds,
              msgType: p.Select,
              dataType: g.Service,
              viewId: this.viewId
            });
        this.debounceUpdateCameraId = setTimeout(() => {
          var h;
          this.debounceUpdateCameraId = void 0;
          const n = [];
          for (const l of this.debounceUpdateCache.values()) {
            if ((h = this.fullLayer) == null ? void 0 : h.getElementsByName(l)[0]) {
              const d = this.vNodes.get(l);
              if (d) {
                const { toolsType: S, opt: y, rect: w } = d, v = this.localWork.setFullWork({
                  toolsType: S,
                  opt: y,
                  workId: l
                });
                if (v) {
                  const D = this.getSceneRect(), x = G(w, D);
                  n.push(v.consumeServiceAsync({
                    isFullWork: !0,
                    replaceId: l,
                    isDrawLabel: x !== Q.outside
                  }));
                }
              }
            }
            this.debounceUpdateCache.delete(l);
          }
          this.vNodes.updateLowLevelNodesRect(), this.vNodes.clearHighLevelIds();
        }, Y);
      }
    }
  }
  getSceneRect() {
    const { width: t, height: e } = this.scene;
    return {
      x: 0,
      y: 0,
      w: Math.floor(t),
      h: Math.floor(e)
    };
  }
  createScene(t) {
    return new oe({
      displayRatio: this.opt.displayer.dpr,
      depth: !1,
      desynchronized: !0,
      ...t,
      autoRender: !0,
      id: this.viewId,
      contextType: "2d"
    });
  }
  createLayer(t, e, s) {
    const { width: o, height: r } = s, i = `canvas-${t}`, a = e.layer(i, { ...s, offscreen: !1 }), c = new re({
      anchor: [0.5, 0.5],
      pos: [o * 0.5, r * 0.5],
      size: [o, r],
      name: "viewport",
      id: t
    });
    return a.append(c), c;
  }
  updateScene(t) {
    this.scene.attr({ ...t });
    const { width: e, height: s } = t;
    this.scene.width = e, this.scene.height = s, this.updateLayer({ width: e, height: s });
  }
  updateLayer(t) {
    const { width: e, height: s } = t;
    this.fullLayer.parent.setAttribute("width", e), this.fullLayer.parent.setAttribute("height", s), this.fullLayer.setAttribute("size", [e, s]), this.fullLayer.setAttribute("pos", [e * 0.5, s * 0.5]), this.topLayer.parent.setAttribute("width", e), this.topLayer.parent.setAttribute("height", s), this.topLayer.setAttribute("size", [e, s]), this.topLayer.setAttribute("pos", [e * 0.5, s * 0.5]), this.localLayer.parent.setAttribute("width", e), this.localLayer.parent.setAttribute("height", s), this.localLayer.setAttribute("size", [e, s]), this.localLayer.setAttribute("pos", [e * 0.5, s * 0.5]), this.serviceLayer.parent.setAttribute("width", e), this.serviceLayer.parent.setAttribute("height", s), this.serviceLayer.setAttribute("size", [e, s]), this.serviceLayer.setAttribute("pos", [e * 0.5, s * 0.5]);
  }
  destroy() {
    this.clearCacheImages(), this.clearImageResolveMap(), this.vNodes.clear(), this.fullLayer.remove(), R(this.fullLayer, this.fullLayer.parent), this.topLayer.remove(), R(this.topLayer, this.topLayer.parent), this.localLayer.remove(), R(this.localLayer, this.localLayer.parent), this.serviceLayer.remove(), R(this.serviceLayer, this.serviceLayer.parent), this.scene.remove(), this.localWork.destroy(), this.serviceWork.destroy(), this.topWork.destroy();
  }
}
class Ee {
  constructor(t, e) {
    u(this, "viewId");
    u(this, "fullLayer");
    u(this, "master");
    u(this, "opt");
    u(this, "scene");
    u(this, "mainThreadPostId");
    u(this, "combinePostMsg", /* @__PURE__ */ new Set());
    u(this, "workShapes", /* @__PURE__ */ new Map());
    u(this, "cacheImages", /* @__PURE__ */ new Map());
    u(this, "imageResolveMap", /* @__PURE__ */ new Map());
    this.viewId = t, this.opt = e, this.scene = this.createScene({ ...e.canvasOpt, container: e.container }), this.master = e.master, this.fullLayer = this.createLayer("fullLayer", this.scene, { ...e.layerOpt, bufferSize: this.viewId === P ? 6e3 : 3e3, contextType: "2d" });
  }
  getCachedImages(t) {
    var e;
    return (e = this.cacheImages.get(t)) == null ? void 0 : e.imageBitmap;
  }
  getCachedImagesByWorkId(t) {
    for (const [e, s] of this.cacheImages.entries())
      if (e === t && s.imageBitmap)
        return s.imageBitmap;
  }
  deleteCachedImagesByWorkId(t) {
    for (const [e, s] of this.cacheImages.entries())
      s.workId === t && (s.imageBitmap.close(), this.cacheImages.delete(e));
  }
  clearCacheImages() {
    this.cacheImages.forEach((t) => t.imageBitmap.close()), this.cacheImages.clear();
  }
  clearImageResolveMap() {
    this.imageResolveMap.forEach(({ timer: t }) => {
      t && clearTimeout(t);
    }), this.imageResolveMap.clear();
  }
  post(t) {
    this.combinePostMsg.add(t), this.runBatchPostData();
  }
  async on(t) {
    const { msgType: e, imageSrc: s, imageBitmap: o, workId: r } = t;
    switch (e) {
      case p.Snapshot:
        await this.getSnapshot(t), this.destroy();
        return;
      case p.BoundingBox:
        await this.getBoundingRect(t), this.destroy();
        return;
      case p.GetImageBitMap:
        if (s && o && r) {
          const i = r.toString();
          this.deleteCachedImagesByWorkId(i), this.cacheImages.set(s, {
            imageBitmap: o,
            workId: i
          });
          const a = this.imageResolveMap.get(s);
          if (a) {
            const { resolve: c, timer: n } = a;
            n && clearTimeout(n), c && c(s);
          }
        }
        break;
    }
  }
  getIconSize(t, e, s) {
    const o = t * s, r = e * s;
    return o <= 50 || r <= 50 ? [50, 50] : o <= 100 || r <= 100 ? [100, 100] : o <= 200 || r <= 200 ? [200, 200] : o <= 400 || r <= 400 ? [400, 400] : o <= 800 || r <= 800 ? [800, 800] : [1600, 1600];
  }
  async loadImageBitMap(t) {
    const { toolsType: e, opt: s, workId: o } = t;
    if (e === f.Image && s && o) {
      const r = o.toString(), { src: i, type: a, width: c, height: n, strokeColor: h } = s;
      if (!i || !a || !c || !n)
        return;
      let l = i;
      if (a === se.Iconify) {
        const [y, w] = this.getIconSize(c, n, this.opt.displayer.dpr);
        l = `${i}?width=${y}&height=${w}&color=${h}`;
      }
      if (this.cacheImages.has(l)) {
        const y = this.getCachedImages(l);
        if (y)
          return y;
      }
      if (this.imageResolveMap.has(l)) {
        const y = this.getCachedImagesByWorkId(r);
        if (y)
          return y;
      }
      const S = await new Promise((y) => {
        const w = this.imageResolveMap.get(l) || {
          resolve: void 0,
          timer: void 0
        };
        w.timer && clearTimeout(w.timer), w.resolve = y, w.timer = setTimeout(() => {
          const v = this.imageResolveMap.get(l);
          v != null && v.resolve && v.resolve(l);
        }, 5e3), this.imageResolveMap.set(l, w), this.opt.post({
          sp: [{
            imageSrc: l,
            workId: r,
            viewId: this.viewId,
            isgl: !!this.fullLayer.parent.gl,
            isSubWorker: !0,
            type: p.GetImageBitMap
          }]
        });
      });
      return this.imageResolveMap.delete(S), this.getCachedImages(l);
    }
  }
  createWorkShapeNode(t) {
    return $({ ...t, fullLayer: this.fullLayer, drawLayer: void 0 });
  }
  setFullWork(t) {
    const { workId: e, opt: s, toolsType: o } = t;
    if (e && s && o) {
      const r = e.toString();
      let i;
      return e && this.workShapes.has(r) ? (i = this.workShapes.get(r), i == null || i.setWorkOptions(s)) : i = this.createWorkShapeNode({
        toolsOpt: s,
        toolsType: o,
        workId: r
      }), i ? (this.workShapes.set(r, i), i) : void 0;
    }
  }
  async runFullWork(t) {
    var o;
    const e = this.setFullWork(t), s = t.ops && U(t.ops);
    if (e) {
      let r, i;
      const a = (o = e.getWorkId()) == null ? void 0 : o.toString();
      return e.toolsType === f.Image ? r = await e.consumeServiceAsync({
        isFullWork: !0,
        worker: this
      }) : e.toolsType === f.Text ? r = await e.consumeServiceAsync({
        isFullWork: !0,
        replaceId: a,
        isDrawLabel: !0
      }) : (r = e.consumeService({
        op: s,
        isFullWork: !0,
        replaceId: a
      }), i = (t == null ? void 0 : t.updateNodeOpt) && e.updataOptService(t.updateNodeOpt)), V(r, i);
    }
  }
  async getSnapshot(t) {
    const { scenePath: e, scenes: s, cameraOpt: o, w: r, h: i } = t;
    if (e && s && o) {
      this.setCameraOpt(o);
      let a;
      for (const [n, h] of Object.entries(s))
        if (h != null && h.type)
          switch (h == null ? void 0 : h.type) {
            case p.UpdateNode:
            case p.FullWork: {
              const { opt: l } = h, k = {
                ...h,
                opt: l,
                workId: n,
                msgType: p.FullWork,
                dataType: g.Service,
                viewId: this.viewId
              }, d = await this.runFullWork(k);
              a = V(a, d);
              break;
            }
          }
      let c;
      r && i && (c = {
        resizeWidth: r,
        resizeHeight: i
      }), await this.getSnapshotRender({ scenePath: e, options: c });
    }
  }
  getSceneRect() {
    const { width: t, height: e } = this.scene;
    return {
      x: 0,
      y: 0,
      w: Math.floor(t),
      h: Math.floor(e)
    };
  }
  getRectImageBitmap(t, e) {
    const s = Math.floor(t.x * this.opt.displayer.dpr), o = Math.floor(t.y * this.opt.displayer.dpr), r = t.w > 0 && Math.floor(t.w * this.opt.displayer.dpr || 1) || 1, i = t.h > 0 && Math.floor(t.h * this.opt.displayer.dpr || 1) || 1;
    return createImageBitmap(this.fullLayer.parent.canvas, s, o, r, i, e);
  }
  async getSnapshotRender(t) {
    var r;
    const { scenePath: e, options: s } = t;
    ((r = this.fullLayer) == null ? void 0 : r.parent).render();
    const o = await this.getRectImageBitmap(this.getSceneRect(), s);
    o && (this.post({
      sp: [{
        type: p.Snapshot,
        scenePath: e,
        imageBitmap: o,
        viewId: this.viewId
      }]
    }), this.fullLayer && z(this.fullLayer, this.fullLayer.parent));
  }
  async getBoundingRect(t) {
    const { scenePath: e, scenes: s, cameraOpt: o } = t;
    if (e && s && o) {
      this.setCameraOpt(o);
      let r;
      for (const [i, a] of Object.entries(s))
        if (a != null && a.type)
          switch (a == null ? void 0 : a.type) {
            case p.UpdateNode:
            case p.FullWork: {
              const c = await this.runFullWork({
                ...a,
                workId: i,
                msgType: p.FullWork,
                dataType: g.Service,
                viewId: this.viewId
              });
              r = V(r, c);
              break;
            }
          }
      r && this.post({
        sp: [{
          type: p.BoundingBox,
          scenePath: e,
          rect: r
        }]
      });
    }
  }
  setCameraOpt(t) {
    const { scale: e, centerX: s, centerY: o, width: r, height: i } = t;
    this.updateScene({ width: r, height: i }), this.fullLayer.setAttribute("scale", [e, e]), this.fullLayer.setAttribute("translate", [-s, -o]);
  }
  runBatchPostData() {
    this.mainThreadPostId || (this.mainThreadPostId = requestAnimationFrame(this.combinePost.bind(this)));
  }
  combinePostData() {
    var e;
    this.mainThreadPostId = void 0;
    const t = [];
    for (const s of this.combinePostMsg.values())
      if ((e = s.sp) != null && e.length)
        for (const o of s.sp) {
          let r = !1;
          for (const i of t)
            if (de(o, i)) {
              r = !0;
              break;
            }
          r || t.push(o);
        }
    return this.combinePostMsg.clear(), {
      sp: t
    };
  }
  combinePost() {
    var s, o;
    const t = this.combinePostData(), e = (s = t.sp) == null ? void 0 : s.filter((r) => r.type !== p.None || r.isLockSentEventCursor);
    e != null && e.length ? t.sp = e.map((r) => r.viewId ? r : { ...r, viewId: this.viewId }) : delete t.sp, (o = t.sp) != null && o.length && this.opt.post(t);
  }
  createScene(t) {
    return new oe({
      displayRatio: this.opt.displayer.dpr,
      depth: !1,
      desynchronized: !0,
      ...t,
      autoRender: !1,
      contextType: "2d"
    });
  }
  createLayer(t, e, s) {
    const { width: o, height: r } = s, i = `canvas-${t}`, a = e.layer(i, s), c = new re({
      anchor: [0.5, 0.5],
      pos: [o * 0.5, r * 0.5],
      size: [o, r],
      name: "viewport",
      id: t
    });
    return a.append(c), c;
  }
  updateScene(t) {
    this.scene.attr({ ...t });
    const { width: e, height: s } = t;
    this.scene.width = e, this.scene.height = s, this.updateLayer({ width: e, height: s });
  }
  updateLayer(t) {
    const { width: e, height: s } = t;
    this.fullLayer.parent.setAttribute("width", e), this.fullLayer.parent.setAttribute("height", s), this.fullLayer.setAttribute("size", [e, s]), this.fullLayer.setAttribute("pos", [e * 0.5, s * 0.5]);
  }
  destroy() {
    this.clearCacheImages(), this.clearImageResolveMap(), this.fullLayer.remove(), R(this.fullLayer, this.fullLayer.parent), this.scene.remove();
  }
}
class _e {
  constructor(t) {
    u(this, "mainThreadMap", /* @__PURE__ */ new Map());
    u(this, "snapshotThread");
    u(this, "master");
    this.master = t;
  }
  post(t) {
    const { fullWorkerDrawCount: e, sp: s, workerTasksqueueCount: o, consumeCount: r } = t;
    this.master.isBusy && K(o) && this.master.setWorkerTasksqueueCount(o), K(e) && this.master.setMaxDrawCount(e), K(r) && this.master.setConsumeCount(r), s && this.master.collectorSyncData(s);
  }
  destroy() {
    this.mainThreadMap.clear();
  }
  createMainThread(t, e) {
    return new Oe(t, e);
  }
  createSnapshotThread(t, e) {
    return new Ee(t, e);
  }
  async consume(t) {
    var e, s, o, r;
    for (const i of t.values()) {
      const { msgType: a, viewId: c, tasksqueue: n, mainTasksqueueCount: h, layerOpt: l, offscreenCanvasOpt: k, cameraOpt: d, isSubWorker: S } = i;
      if (a === p.Console) {
        console.log(this);
        continue;
      }
      if (a === p.Init) {
        const w = (e = this.master.control.viewContainerManager.getView(c)) == null ? void 0 : e.displayer, v = w == null ? void 0 : w.canvasContainerRef.current;
        if (w && v && l && k) {
          const D = this.createMainThread(c, {
            displayer: w,
            container: v,
            layerOpt: l,
            master: this.master,
            canvasOpt: k,
            post: this.post.bind(this)
          });
          this.mainThreadMap.set(c, D), D && d && D.setCameraOpt(d);
        }
        continue;
      }
      if ((a === p.Snapshot || a === p.BoundingBox) && c === ((s = this.master.control.viewContainerManager.mainView) == null ? void 0 : s.id)) {
        const w = (o = this.master.control.viewContainerManager.getView(c)) == null ? void 0 : o.displayer, v = (r = w.snapshotContainerRef) == null ? void 0 : r.current;
        if (w && v && d) {
          v.style.width = `${d.width}px`, v.style.height = `${d.height}px`;
          const D = {
            ...J.defaultLayerOpt,
            offscreen: !1,
            width: d.width,
            height: d.height
          }, x = {
            ...J.defaultScreenCanvasOpt,
            width: d.width,
            height: d.height
          };
          this.snapshotThread = this.createSnapshotThread(c, {
            displayer: w,
            container: v,
            layerOpt: D,
            master: this.master,
            canvasOpt: x,
            post: this.post.bind(this)
          }), this.snapshotThread.on(i).then(() => {
            this.snapshotThread = void 0, v.innerHTML = "", v.style.width = "", v.style.height = "";
          });
          continue;
        }
      }
      if (a === p.GetImageBitMap && S && this.snapshotThread) {
        this.snapshotThread.on(i);
        continue;
      }
      if (a === p.TasksQueue && (n != null && n.size)) {
        for (const [w, v] of this.mainThreadMap.entries()) {
          const D = n.get(w);
          D && (await v.on(D), h && this.post({ workerTasksqueueCount: h }));
        }
        continue;
      }
      if (c === ue) {
        for (const w of this.mainThreadMap.values())
          w.on(i), a === p.Destroy && this.mainThreadMap.delete(c);
        continue;
      }
      const y = this.mainThreadMap.get(c);
      y && (y.on(i), a === p.Destroy && this.mainThreadMap.delete(c));
    }
  }
}
export {
  _e as MainThreadManagerImpl
};
