var re = Object.defineProperty;
var ie = (N, t, e) => t in N ? re(N, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : N[t] = e;
var u = (N, t, e) => ie(N, typeof t != "symbol" ? t + "" : t, e);
import { D as x, E as W, a as f, r as B, b as v, g as z, t as F, c as p, S as Q, d as L, e as _, i as ae, C as E, f as R, h as ne, j as K, k as T, M as A, V as ce, l as J, T as Z, m as H, n as j, o as $, p as le, q, s as X, u as he } from "./index-BS5_t4VL.mjs";
import { Scene as ee, Group as te } from "spritejs";
import { cloneDeep as se, xor as pe, isNumber as U, isEqual as Y } from "lodash";
import "clipper-lib";
import "lineclip";
import "white-web-sdk";
import "react-dom";
import "react";
import "eventemitter2";
class de {
  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", x.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();
    }), B(
      this.thread.serviceLayer,
      this.thread.serviceLayer.parent
    )), this.serviceWorkShapes.clear(), this.localWorkShapes.clear();
  }
  consumeDraw(t) {
    const { workId: e, dataType: s } = t;
    if (s === v.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 z({
        ...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 m, 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 = (m = this.vNodes.get(n)) == null ? void 0 : m.rect;
    if (!((d = this.serviceWorkShapes) != null && d.has(n))) {
      let k = {
        toolsType: o,
        animationWorkData: c || [],
        animationIndex: 0,
        type: r,
        updateNodeOpt: i,
        ops: a,
        oldRect: h
      };
      o && s && (k = this.setNodeKey(n, k, o, s)), this.serviceWorkShapes.set(n, k);
    }
    const l = this.serviceWorkShapes.get(n);
    r && (l.type = r), a && (l.animationWorkData = F(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
          ), m = Math.max(0, n.animationIndex || 0), d = (n.animationWorkData || []).slice(
            m,
            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: m === 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: m, workState: d } = n;
      switch (l) {
        case f.LaserPen: {
          if (m) {
            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(Q)[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 === v.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 ue {
  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", x.syncOpt.interval);
    u(this, "fullWorkerDrawCount", 0);
    u(this, "drawWorkActiveId");
    u(this, "consumeCount", 0);
    u(this, "combineTimerId");
    u(this, "combineDrawResolve");
    u(this, "combineDrawActiveId");
    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 m;
    const e = this.workShapes.get(
      L
    );
    if (!((m = e == null ? void 0 : e.selectIds) != null && m.length)) return;
    const { callback: s, ...o } = t, { updateSelectorOpt: r, willSerializeData: i } = o, a = await (e == null ? void 0 : e.updateSelector({
      updateSelectorOpt: r,
      selectIds: se(e.selectIds),
      vNodes: this.vNodes,
      willSerializeData: i,
      worker: this
    })), c = /* @__PURE__ */ new Map();
    let n;
    a != null && a.selectIds && (n = pe(e.selectIds, a.selectIds), a.selectIds.forEach((d) => {
      const k = this.vNodes.get(d);
      if (k) {
        const { toolsType: S, op: y, opt: I } = k;
        c.set(d, {
          opt: I,
          toolsType: S,
          ops: (y == null ? void 0 : y.length) && _(y) || 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();
    }), B(
      this.thread.localLayer,
      this.thread.localLayer.parent
    )), this.workShapes.get(
      L
    )) {
      const e = [];
      e.push({
        type: p.Select,
        dataType: v.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], m = e[1] * this.thread.fullLayer.worldScaling[1] + this.thread.fullLayer.worldPosition[1];
        if (n === f.Text && ae([l, m], 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: E,
      toolsType: s,
      opt: e
    });
    r && o && r.cursorHover(o);
  }
  cursorBlur() {
    var e;
    const t = this.getWorkShape(E);
    t && ((e = t.selectIds) != null && e.length) && (t.cursorBlur(), this.clearWorkShapeNodeCache(E)), 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(
      L
    ), { 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: v.Local
      };
  }
  async removeSelector(t) {
    const { willSyncService: e } = t, s = [], o = [], r = this.workShapes.get(
      L
    );
    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 && F(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(
      L
    ), { 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 && F(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(L);
  }
  getSelector() {
    return this.workShapes.get(L);
  }
  reRenderSelector(t = !1) {
    var o;
    const e = this.workShapes.get(
      L
    );
    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(
      L
    ), s = e == null ? void 0 : e.blurSelector();
    if (this.clearWorkShapeNodeCache(L), ((o = this.thread.fullLayer) == null ? void 0 : o.parent).children.forEach((r) => {
      r.name === L && 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: v.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 });
  }
  drawPencilEraserFull(t, e, s) {
    const { willNewNodes: 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.FullWork,
            dataType: v.Local,
            toolsType: n.toolsType,
            ops: _(n.op),
            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 });
  }
  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 });
  }
  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.combineDrawActiveId && this.combineDrawActiveId !== a && (this.combineTimerId && (clearTimeout(this.combineTimerId), this.combineTimerId = void 0, this.combineDrawResolve && this.combineDrawResolve(!1), this.combineDrawActiveId = void 0), this.consumeDrawAll(
        {
          workId: this.combineDrawActiveId,
          scenePath: r,
          viewId: this.thread.viewId,
          msgType: p.DrawWork,
          dataType: v.Local
        },
        e
      )), this.drawWorkActiveId && this.drawWorkActiveId !== a && (this.consumeDrawAll(
        {
          workId: this.drawWorkActiveId,
          scenePath: r,
          viewId: this.thread.viewId,
          msgType: p.DrawWork,
          dataType: v.Local
        },
        e
      ), this.drawWorkActiveId = void 0), !this.drawWorkActiveId && a !== L && (this.drawWorkActiveId = a), U(i) && (this.consumeCount = i), n) {
        case f.Selector: {
          const h = c.consume({
            data: t,
            isFullWork: !0,
            isMainThread: !0
          });
          this.fullWorkerDrawCount++;
          const l = [];
          h.type === p.Select && (h.selectIds && e.runReverseSelectWork(h.selectIds), l.push(h)), this.thread.post({
            consumeCount: this.consumeCount,
            fullWorkerDrawCount: this.fullWorkerDrawCount,
            sp: l
          });
          break;
        }
        case f.PencilEraser:
        case f.BitMapEraser: {
          c.consume({
            data: t,
            isFullWork: !1,
            isMainThread: !0
          }), this.fullWorkerDrawCount++, this.thread.post({
            sp: void 0,
            consumeCount: this.consumeCount,
            fullWorkerDrawCount: this.fullWorkerDrawCount
          }), this.combineTimerId || new Promise((h) => {
            this.combineDrawActiveId = a, this.combineDrawResolve = h, this.combineTimerId = requestIdleCallback(
              () => {
                this.combineTimerId = void 0, this.combineDrawResolve && this.combineDrawResolve(!0);
              },
              { timeout: this.thread.master.maxCombineEraserTime }
            );
          }).then((h) => {
            h && this.drawEraserCombine(a), this.combineDrawResolve = 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;
      }
    }
  }
  drawEraserCombine(t) {
    var s, o, r, i;
    const e = (s = this.workShapes.get(t)) == null ? void 0 : s.combineConsume({ workerEngine: this });
    if (e) {
      const { willDeleteNodes: a, willNewNodes: c } = e, n = {
        render: [],
        sp: []
      };
      if (e != null && e.rect) {
        const h = ne(e.rect);
        (o = n.render) == null || o.push(
          {
            rect: h,
            isClear: !0,
            clearCanvas: K.Bg,
            viewId: this.thread.viewId
          },
          {
            rect: h,
            drawCanvas: K.Bg,
            viewId: this.thread.viewId
          }
        );
      }
      if (a != null && a.size && ((r = n.sp) == null || r.push({
        type: p.RemoveNode,
        removeIds: [...a],
        viewId: this.thread.viewId
      })), c != null && c.size)
        for (const [h, l] of c)
          (i = n.sp) == null || i.push({
            type: p.FullWork,
            dataType: v.Local,
            toolsType: l.toolsType,
            ops: _(l.op),
            opt: l.opt,
            workId: h,
            updateNodeOpt: {
              useAnimation: !1
            }
          });
      this.thread.post(n);
    }
  }
  consumeDrawAll(t, e) {
    var i, a, c;
    const { workId: s, scenePath: o, isLockSentEventCursor: r } = t;
    if (s) {
      this.combineTimerId && (clearTimeout(this.combineTimerId), this.combineTimerId = void 0, this.combineDrawResolve && this.combineDrawResolve(!1), this.combineDrawActiveId = void 0);
      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 m = this.workShapes.get(E), d = (i = m == null ? void 0 : m.selectIds) == null ? void 0 : i[0], k = h.consumeAll({ data: t, workerEngine: this });
      switch (l) {
        case f.Selector:
          {
            k.selectIds && d && ((a = k.selectIds) != null && a.includes(d)) && m.cursorBlur();
            const S = [];
            r && S.push({
              type: p.None,
              isLockSentEventCursor: r
            }), k.type === p.Select && (k.selectIds && e.runReverseSelectWork(k.selectIds), S.push({ ...k, scenePath: o })), S.length && this.thread.post({ sp: S }), (c = h.selectIds) != null && c.length ? h.clearTmpPoints() : this.clearWorkShapeNodeCache(n);
          }
          break;
        case f.PencilEraser:
          this.drawPencilEraserFull(
            h,
            k,
            r
          ), this.fullWorkerDrawCount = 0, this.clearWorkShapeNodeCache(n);
          break;
        case f.BitMapEraser:
          this.drawBitMapEraserFull(
            h,
            k,
            r
          ), this.fullWorkerDrawCount = 0, this.clearWorkShapeNodeCache(n);
          break;
        case f.Eraser:
          this.drawEraser({ ...k, 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 S = [];
          r && S.push({
            type: p.None,
            isLockSentEventCursor: r
          }), k && (S.push(k), this.fullWorkerDrawCount = 0, this.thread.post({
            fullWorkerDrawCount: this.fullWorkerDrawCount,
            sp: S
          })), 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 z(
      {
        ...t,
        vNodes: this.vNodes,
        fullLayer: this.thread.fullLayer,
        drawLayer: this.thread.localLayer
      },
      this.thread.serviceWork
    );
  }
}
class fe {
  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", x.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();
    }), B(
      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, m, d, k, S, y, I;
    this.animationId = void 0;
    let t = !1;
    const e = /* @__PURE__ */ new Map();
    for (const [g, w] of this.workShapes.entries())
      switch (w.toolsType) {
        case f.Image: {
          await ((s = w.node) == null ? void 0 : s.consumeServiceAsync({
            isFullWork: !0,
            worker: this
          })), this.selectorWorkShapes.forEach((b, D) => {
            var C;
            (C = b.selectIds) != null && C.includes(g) && (this.willRunEffectSelectorIds.add(D), this.runEffect());
          }), this.workShapes.delete(g);
          break;
        }
        case f.Text: {
          w.node && (await ((o = w.node) == null ? void 0 : o.consumeServiceAsync({
            isFullWork: !0,
            replaceId: g
          })), this.selectorWorkShapes.forEach((b, D) => {
            var C;
            (C = b.selectIds) != null && C.includes(g) && (this.willRunEffectSelectorIds.add(D), this.runEffect());
          }), (r = w.node) == null || r.clearTmpPoints(), this.workShapes.delete(g));
          break;
        }
        case f.Arrow:
        case f.Straight:
        case f.Rectangle:
        case f.Ellipse:
        case f.Star:
        case f.Polygon:
        case f.SpeechBalloon: {
          const b = !!w.ops;
          if ((i = w.animationWorkData) != null && i.length) {
            const D = w.oldRect;
            (a = w.node) == null || a.consumeService({
              op: w.animationWorkData,
              isFullWork: b
            }), b && (this.selectorWorkShapes.forEach((C, M) => {
              var P;
              (P = C.selectIds) != null && P.includes(g) && (this.willRunEffectSelectorIds.add(M), this.runEffect());
            }), (c = w.node) == null || c.clearTmpPoints(), this.workShapes.delete(g)), e.set(g, {
              workState: D ? w.ops ? W.Done : W.Doing : W.Start,
              op: w.animationWorkData.filter((C, M) => {
                if (M % 3 !== 2)
                  return !0;
              }).slice(-2)
            }), w.animationWorkData.length = 0;
          }
          break;
        }
        case f.Pencil: {
          if (!w.useAnimation && w.ops)
            (n = w.node) == null || n.consumeService({
              op: w.animationWorkData || [],
              isFullWork: !0,
              replaceId: g
            }), (h = w.node) == null || h.updataOptService(w.updateNodeOpt), this.selectorWorkShapes.forEach((b, D) => {
              var C;
              (C = b.selectIds) != null && C.includes(g) && (this.willRunEffectSelectorIds.add(D), this.runEffect());
            }), (l = w.node) == null || l.clearTmpPoints(), this.workShapes.delete(g);
          else if (w.useAnimation) {
            if (w.isDel) {
              (m = w.node) == null || m.clearTmpPoints(), this.workShapes.delete(g);
              break;
            }
            const b = 3, D = this.computNextAnimationIndex(
              w,
              b
            ), C = w.isDiff ? 0 : Math.max(0, (w.animationIndex || 0) - b), M = (w.animationWorkData || []).slice(
              C,
              D
            ), P = (k = (d = w.node) == null ? void 0 : d.getWorkId()) == null ? void 0 : k.toString();
            if ((w.animationIndex || 0) < D || w.isDiff) {
              if ((S = w.node) == null || S.consumeService({
                op: M,
                isFullWork: !1
              }), w.animationIndex = D, w.isDiff && (w.isDiff = !1), M.length) {
                const G = M.filter((V, oe) => {
                  if (oe % b !== b - 1)
                    return !0;
                }).slice(-2);
                e.set(g, {
                  workState: C === 0 ? W.Start : D === ((y = w.animationWorkData) == null ? void 0 : y.length) ? W.Done : W.Doing,
                  op: G
                });
              }
            } else w.ops && ((I = w.node) == null || I.consumeService({
              op: w.animationWorkData || [],
              isFullWork: !0,
              replaceId: P
            }), w.isDel = !0, e.set(g, {
              workState: W.Done,
              op: M.filter((G, V) => {
                if (V % b !== b - 1)
                  return !0;
              }).slice(-2)
            }));
            t = !0;
            break;
          }
          break;
        }
      }
    if (t && this.runAnimation(), e.size) {
      const g = [];
      e.forEach((w, b) => {
        g.push({
          type: p.Cursor,
          uid: b.split(Q)[0],
          op: w.op,
          workState: w.workState,
          viewId: this.thread.viewId
        });
      }), this.thread.post({ sp: g });
    }
  }
  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 k, S, y, I;
    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(), m = (k = this.vNodes.get(l)) == null ? void 0 : k.rect;
    if (!((S = this.workShapes) != null && S.has(l))) {
      let g = {
        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: m,
        isDiff: !1,
        imageBitmap: h
      };
      o && s && (g = this.setNodeKey(l, g, o, s)), (y = this.workShapes) == null || y.set(l, g);
    }
    const d = (I = this.workShapes) == null ? void 0 : I.get(l);
    r && (d.type = r), a && (d.animationWorkData = F(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), m && (d.oldRect = m), 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(L) > -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 m = {
        toolsType: o,
        selectIds: i,
        type: r,
        opt: s
      };
      o && s && (m = this.setNodeKey(a, m, o, s)), (h = this.selectorWorkShapes) == null || h.set(a, m);
    }
    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 = z(
      {
        toolsType: s,
        toolsOpt: o,
        vNodes: this.vNodes,
        fullLayer: this.thread.fullLayer,
        drawLayer: this.thread.serviceLayer,
        workId: t
      },
      this
    ), e;
  }
}
class O {
  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 me extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.CopyNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.FullWork && o === v.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 ke extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.SetColorNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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: v.Local,
          willSyncService: !0
        }) : n.push({
          ...l,
          workId: h,
          type: p.UpdateNode,
          updateNodeOpt: {
            useAnimation: !1
          },
          isSync: a
        });
    return {
      sp: n
    };
  }
}
class Se extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.ZIndexNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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 ye extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.TranslateNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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, m = h.workState, d = o.sp || [];
    if (m === W.Start)
      return {
        sp: [],
        render: []
      };
    const k = a == null ? void 0 : a.selectRect;
    if (c) {
      m === W.Doing && d.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: k,
        willSyncService: !0,
        isSync: !0,
        points: i.getChildrenPoints(),
        textOpt: i.textOpt
      });
      for (const [S, y] of r.entries())
        l && y.toolsType === f.Text ? d.push({
          ...y,
          workId: S,
          type: p.TextUpdate,
          dataType: v.Local,
          willSyncService: !0
        }) : d.push({
          ...y,
          workId: S,
          type: p.UpdateNode,
          updateNodeOpt: {
            useAnimation: !1
          },
          isSync: n
        });
    }
    return {
      sp: d
    };
  }
}
class we extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.DeleteNode);
  }
  async consume() {
    return !1;
  }
}
class ve extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.ScaleNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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 || [], m = i == null ? void 0 : i.selectRect;
    if (h === W.Start)
      return {
        sp: [],
        render: []
      };
    if (n) {
      l.push({
        type: p.Select,
        selectIds: r.selectIds,
        selectRect: m,
        willSyncService: !0,
        isSync: !0,
        points: h === W.Done && r.getChildrenPoints() || void 0,
        textOpt: r.textOpt
      });
      for (const [d, k] of a.entries())
        k.toolsType === f.Text ? l.push({
          ...k,
          workId: d,
          type: p.TextUpdate,
          dataType: v.Local,
          willSyncService: !0
        }) : l.push({
          ...k,
          workId: d,
          type: p.UpdateNode,
          updateNodeOpt: {
            useAnimation: !1
          },
          isSync: !0
        });
    }
    return {
      sp: l
    };
  }
}
class Ie extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.RotateNode);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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, m = c.workState, d = o.sp || [], k = i == null ? void 0 : i.selectRect;
    if (n) {
      h && m === W.Done && d.push({
        type: p.Select,
        selectIds: r.selectIds,
        selectRect: k,
        willSyncService: !0,
        isSync: l,
        points: r.getChildrenPoints()
      });
      for (const [S, y] of a.entries())
        d.push({
          ...y,
          workId: S,
          type: p.UpdateNode,
          updateNodeOpt: {
            useAnimation: !1
          },
          isSync: l
        });
    }
    return {
      sp: d
    };
  }
}
class ge extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.SetFontStyle);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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, m = o.sp || [], d = a == null ? void 0 : a.selectRect;
    if (c && m) {
      h.fontSize && m.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: d,
        willSyncService: c,
        isSync: n,
        points: i.getChildrenPoints()
      });
      for (const [k, S] of r.entries())
        l && S.toolsType === f.Text ? m.push({
          ...S,
          workId: k,
          type: p.TextUpdate,
          dataType: v.Local,
          willSyncService: !0
        }) : m.push({
          ...S,
          workId: k,
          type: p.UpdateNode,
          updateNodeOpt: {
            useAnimation: !1
          },
          isSync: n
        });
    }
    return {
      sp: m
    };
  }
}
class Te extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.SetPoint);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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 [m, d] of r.entries())
        h.push({
          ...d,
          workId: m,
          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 We extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.SetLock);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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 || [], m = a == null ? void 0 : a.selectRect;
    if (c && l) {
      for (const [d, k] of r.entries())
        l.push({
          ...k,
          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: m,
        willSyncService: c,
        isSync: n
      });
    }
    return {
      sp: l
    };
  }
}
class Le extends O {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.SetShapeOpt);
  }
  async consume(e) {
    const { msgType: s, dataType: o, emitEventType: r } = e;
    if (s === p.UpdateNode && o === v.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 === L && 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 Ne {
  constructor(t) {
    u(this, "builders", /* @__PURE__ */ new Map());
    this.builders = new Map(t.map((e) => [e, this.build(e)]));
  }
  build(t) {
    switch (t) {
      case T.TranslateNode:
        return new ye();
      case T.ZIndexNode:
        return new Se();
      case T.CopyNode:
        return new me();
      case T.SetColorNode:
        return new ke();
      case T.DeleteNode:
        return new we();
      case T.ScaleNode:
        return new ve();
      case T.RotateNode:
        return new Ie();
      case T.SetFontStyle:
        return new ge();
      case T.SetPoint:
        return new Te();
      case T.SetLock:
        return new We();
      case T.SetShapeOpt:
        return new Le();
    }
  }
  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 be {
  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 = x.bufferSize.full, o = x.bufferSize.sub;
    this.fullLayer = this.createLayer("fullLayer", this.scene, {
      ...e.layerOpt,
      bufferSize: this.viewId === A ? s : o * 2
    }), this.topLayer = this.createLayer("topLayer", this.scene, {
      ...e.layerOpt,
      bufferSize: (this.viewId === A, o),
      contextType: "2d"
    }), this.localLayer = this.createLayer("localLayer", this.scene, {
      ...e.layerOpt,
      bufferSize: (this.viewId === A, o),
      contextType: "2d"
    }), this.serviceLayer = this.createLayer("serviceLayer", this.scene, {
      ...e.layerOpt,
      bufferSize: (this.viewId === A, o),
      contextType: "2d"
    }), this.vNodes = new ce(t, this.scene);
    const r = {
      thread: this,
      vNodes: this.vNodes
    };
    this.localWork = new ue(r), this.serviceWork = new fe(r), this.topWork = new de(r), this.vNodes.init(this.fullLayer), this.methodBuilder = new Ne([
      T.CopyNode,
      T.SetColorNode,
      T.DeleteNode,
      T.RotateNode,
      T.ScaleNode,
      T.TranslateNode,
      T.ZIndexNode,
      T.SetFontStyle,
      T.SetPoint,
      T.SetLock,
      T.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, m = i == null ? void 0 : i.toString();
      switch (e) {
        case p.UpdateDpr:
          U(t.dpr) && this.updateDpr(t.dpr);
          break;
        case p.AuthClear: {
          const { clearUids: d, localUid: k } = t;
          this.vNodes.setCanClearUids(d), this.vNodes.setLocalUid(k);
          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 (m && o && s) {
            if (this.topWork.canUseTopLayer(s)) {
              this.topWork.getToolsOpt() || this.topWork.setToolsOpt({
                toolsType: s,
                toolsOpt: o
              }), this.topWork.setWorkOptions(m, o);
              break;
            }
            this.localWork.getToolsOpt() || this.localWork.setToolsOpt({
              toolsType: s,
              toolsOpt: o
            }), this.localWork.setWorkOptions(m, o);
          }
          break;
        case p.DrawWork:
          a === W.Done && r === v.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 === v.Service && (i === L ? 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 === v.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 k = this.imageResolveMap.get(c);
            if (k) {
              const { resolve: S, timer: y } = k;
              y && clearTimeout(y), S && S(c);
            }
          }
          break;
        case p.GetVNodeInfo:
          if (i && h) {
            const d = h.map((k) => this.vNodes.get(k));
            this.post({
              sp: [
                {
                  type: p.GetVNodeInfo,
                  dataType: v.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 === J.Iconify) {
        const [S, y] = this.getIconSize(c, n, this.opt.displayer.dpr);
        l = `${i}?width=${S}&height=${y}&color=${h}`;
      }
      if (this.cacheImages.has(l)) {
        const S = this.getCachedImages(l);
        if (S)
          return S;
      }
      if (this.imageResolveMap.has(l)) {
        const S = this.getCachedImagesByWorkId(r);
        if (S)
          return S;
      }
      const k = await new Promise((S) => {
        const y = this.imageResolveMap.get(l) || {
          resolve: void 0,
          timer: void 0
        };
        y.timer && clearTimeout(y.timer), y.resolve = S, y.timer = setTimeout(() => {
          const I = this.imageResolveMap.get(l);
          I != null && I.resolve && I.resolve(l);
        }, 5e3), this.imageResolveMap.set(l, y), 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(k), 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 === L) {
          await this.localWork.removeSelector(t);
          continue;
        }
        e === v.Local ? this.localWork.removeWork(t) : e === v.Service && this.serviceWork.removeWork(t), await this.localWork.colloctEffectSelectWork(t);
      }
  }
  async consumeFull(t, e) {
    const s = await this.localWork.colloctEffectSelectWork(e);
    s && t === v.Local && await this.localWork.consumeFull(s), s && t === v.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 (Y(i, c)) {
              a = !0;
              break;
            }
          a || t.push(i);
        }
      U(r.fullWorkerDrawCount) && (e = r.fullWorkerDrawCount), U(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();
    }), B(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 === v.Local && (this.topWork.getLocalWorkShape(
          o.toString()
        ) || this.topWork.createLocalWork(e)), this.topWork.consumeDrawAll(e);
        return;
      }
      t === v.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 === v.Local && (this.topWork.getLocalWorkShape(i) || this.topWork.createLocalWork(e)), this.topWork.consumeDraw(e);
        return;
      }
      t === v.Local ? (this.localWork.getWorkShape(i) || this.localWork.createLocalWork(e), this.localWork.consumeDraw(e, this.serviceWork)) : t === v.Service && this.serviceWork.consumeDraw(e);
      return;
    }
  }
  async updateCamera(t) {
    var o;
    const { cameraOpt: e, scenePath: s } = t;
    if (e && !Y(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 !== E && h !== L && (n = !0);
              break;
          }
        if (n) {
          this.taskUpdateCameraId = setTimeout(() => {
            this.taskUpdateCameraId = void 0, this.updateCamera(t);
          }, Z);
          return;
        }
      }
      const r = /* @__PURE__ */ new Map();
      for (const [n, h] of this.vNodes.getNodesByType(f.Text).entries()) {
        const l = h.rect;
        r.set(n, se(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 m = h, d = l.rect, k = this.getSceneRect(), S = H(m, k), y = H(d, k);
            let I = !1;
            if ((S !== y || m.w !== d.w || m.h !== d.h || y === j.intersect) && (I = !0), I) {
              const { toolsType: g, opt: w } = l;
              g === f.Text && w.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: v.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: k, opt: S, rect: y } = d, I = this.localWork.setFullWork({
                  toolsType: k,
                  opt: S,
                  workId: l
                });
                if (I) {
                  const g = this.getSceneRect(), w = H(y, g);
                  n.push(
                    I.consumeServiceAsync({
                      isFullWork: !0,
                      replaceId: l,
                      isDrawLabel: w !== j.outside
                    })
                  );
                }
              }
            }
            this.debounceUpdateCache.delete(l);
          }
          this.vNodes.updateLowLevelNodesRect(), this.vNodes.clearHighLevelIds();
        }, Z);
      }
    }
  }
  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 ee({
      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 te({
      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 Ce {
  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 === A ? 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 === J.Iconify) {
        const [S, y] = this.getIconSize(c, n, this.opt.displayer.dpr);
        l = `${i}?width=${S}&height=${y}&color=${h}`;
      }
      if (this.cacheImages.has(l)) {
        const S = this.getCachedImages(l);
        if (S)
          return S;
      }
      if (this.imageResolveMap.has(l)) {
        const S = this.getCachedImagesByWorkId(r);
        if (S)
          return S;
      }
      const k = await new Promise((S) => {
        const y = this.imageResolveMap.get(l) || {
          resolve: void 0,
          timer: void 0
        };
        y.timer && clearTimeout(y.timer), y.resolve = S, y.timer = setTimeout(() => {
          const I = this.imageResolveMap.get(l);
          I != null && I.resolve && I.resolve(l);
        }, 5e3), this.imageResolveMap.set(l, y), 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(k), this.getCachedImages(l);
    }
  }
  createWorkShapeNode(t) {
    return z({
      ...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 && F(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)), $(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, m = {
                ...h,
                opt: l,
                workId: n,
                msgType: p.FullWork,
                dataType: v.Service,
                viewId: this.viewId
              }, d = await this.runFullWork(m);
              a = $(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 && B(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: v.Service,
                viewId: this.viewId
              });
              r = $(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 (le(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 ee({
      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 te({
      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 Ue {
  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 && q(o) && this.master.setWorkerTasksqueueCount(o), q(e) && this.master.setMaxDrawCount(e), q(r) && this.master.setConsumeCount(r), s && this.master.collectorSyncData(s);
  }
  destroy() {
    this.mainThreadMap.clear();
  }
  createMainThread(t, e) {
    return new be(t, e);
  }
  createSnapshotThread(t, e) {
    return new Ce(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: m,
        cameraOpt: d,
        isSubWorker: k
      } = i;
      if (a === p.Console) {
        console.log(this);
        continue;
      }
      if (a === p.Init) {
        const y = (e = this.master.control.viewContainerManager.getView(c)) == null ? void 0 : e.displayer, I = y == null ? void 0 : y.canvasContainerRef.current;
        if (y && I && l && m) {
          const g = this.createMainThread(c, {
            displayer: y,
            container: I,
            layerOpt: l,
            master: this.master,
            canvasOpt: m,
            post: this.post.bind(this)
          });
          this.mainThreadMap.set(c, g), g && d && g.setCameraOpt(d);
        }
        continue;
      }
      if ((a === p.Snapshot || a === p.BoundingBox) && c === ((s = this.master.control.viewContainerManager.mainView) == null ? void 0 : s.id)) {
        const y = (o = this.master.control.viewContainerManager.getView(c)) == null ? void 0 : o.displayer, I = (r = y.snapshotContainerRef) == null ? void 0 : r.current;
        if (y && I && d) {
          I.style.width = `${d.width}px`, I.style.height = `${d.height}px`;
          const g = {
            ...X.defaultLayerOpt,
            offscreen: !1,
            width: d.width,
            height: d.height
          }, w = {
            ...X.defaultScreenCanvasOpt,
            width: d.width,
            height: d.height
          };
          this.snapshotThread = this.createSnapshotThread(c, {
            displayer: y,
            container: I,
            layerOpt: g,
            master: this.master,
            canvasOpt: w,
            post: this.post.bind(this)
          }), this.snapshotThread.on(i).then(() => {
            this.snapshotThread = void 0, I.innerHTML = "", I.style.width = "", I.style.height = "";
          });
          continue;
        }
      }
      if (a === p.GetImageBitMap && k && this.snapshotThread) {
        this.snapshotThread.on(i);
        continue;
      }
      if (a === p.TasksQueue && (n != null && n.size)) {
        for (const [y, I] of this.mainThreadMap.entries()) {
          const g = n.get(y);
          g && (await I.on(g), h && this.post({ workerTasksqueueCount: h }));
        }
        continue;
      }
      if (c === he) {
        for (const y of this.mainThreadMap.values())
          y.on(i), a === p.Destroy && this.mainThreadMap.delete(c);
        continue;
      }
      const S = this.mainThreadMap.get(c);
      S && (S.on(i), a === p.Destroy && this.mainThreadMap.delete(c));
    }
  }
}
export {
  Ue as MainThreadManagerImpl
};
