var ee = Object.defineProperty;
var te = (L, t, e) => t in L ? ee(L, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : L[t] = e;
var u = (L, t, e) => te(L, typeof t != "symbol" ? t + "" : t, e);
import { D as R, E as W, a as f, b as g, g as F, t as A, c as p, S as Z, d as N, e as $, i as se, C as U, f as oe, h as T, M, V as re, j, T as H, k as P, l as q, m as B, n as ie, o as G, p as V, q as ae } from "./index-Bn_ebN3K.mjs";
import { Scene as X, Group as Y } from "spritejs";
import { cloneDeep as Q, xor as ce, isEqual as K, isNumber as ne } from "lodash";
import "lineclip";
import "white-web-sdk";
import "react-dom";
import "react";
import "eventemitter2";
class le {
  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", R.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();
    }), this.thread.serviceLayer.removeAllChildren()), 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 F({ ...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: c, op: n } = t;
    if (!e)
      return;
    const a = e.toString(), h = (m = this.vNodes.get(a)) == null ? void 0 : m.rect;
    if (!((d = this.serviceWorkShapes) != null && d.has(a))) {
      let w = {
        toolsType: o,
        animationWorkData: n || [],
        animationIndex: 0,
        type: r,
        updateNodeOpt: i,
        ops: c,
        oldRect: h
      };
      o && s && (w = this.setNodeKey(a, w, o, s)), this.serviceWorkShapes.set(a, w);
    }
    const l = this.serviceWorkShapes.get(a);
    r && (l.type = r), c && (l.animationWorkData = A(c), l.ops = c), i && (l.updateNodeOpt = i), n && (l.animationWorkData = n), l.node && l.node.getWorkId() !== a && l.node.setWorkId(a), h && (l.oldRect = h), o && s && (l.toolsType !== o && o && s && this.setNodeKey(a, 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, c;
    this.animationId = void 0;
    let t = !1;
    const e = /* @__PURE__ */ new Map(), s = [];
    for (const [n, a] of this.serviceWorkShapes.entries())
      switch (a.toolsType) {
        case f.LaserPen: {
          const l = this.computNextAnimationIndex(a, 8), m = Math.max(0, a.animationIndex || 0), d = (a.animationWorkData || []).slice(m, l);
          if ((a.animationIndex || 0) < l && ((o = a.node) == null || o.consumeService({
            op: d,
            isFullWork: !1
          }), a.animationIndex = l, d.length && e.set(n, {
            workState: m === 0 ? W.Start : l === ((r = a.animationWorkData) == null ? void 0 : r.length) ? W.Done : W.Doing,
            op: d.slice(-2)
          })), a.isDel) {
            (i = a.node) == null || i.clearTmpPoints(), this.serviceWorkShapes.delete(n);
            break;
          }
          a.ops && a.animationIndex === ((c = a.animationWorkData) == null ? void 0 : c.length) && !a.isDel && (this.thread.topLayer.getElementsByName(n.toString())[0] || (a.isDel = !0, this.serviceWorkShapes.set(n, a))), t = !0;
          break;
        }
      }
    for (const [n, a] of this.localWorkShapes.entries()) {
      const { result: h, toolsType: l, isDel: m, workState: d } = a;
      switch (l) {
        case f.LaserPen: {
          if (m) {
            a.node.clearTmpPoints(), this.localWorkShapes.delete(n), s.push({
              removeIds: [n.toString()],
              type: p.RemoveNode
            });
            break;
          }
          h && ((h.op || h.ops) && s.push(h), a.result = void 0), !this.thread.topLayer.getElementsByName(n.toString())[0] && d === W.Done && (a.isDel = !0, this.localWorkShapes.set(n, a)), t = !0;
          break;
        }
      }
    }
    t && this.runAnimation(), e.size && e.forEach((n, a) => {
      s.push({
        type: p.Cursor,
        uid: a.split(Z)[0],
        op: n.op,
        workState: n.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 he {
  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", R.syncOpt.interval);
    u(this, "drawCount", 0);
    u(this, "drawWorkActiveId");
    u(this, "batchEraserCombine", oe(() => {
      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);
    }
  }
  workShapesDone(t, e) {
    for (const s of this.workShapes.keys())
      this.consumeDrawAll({
        workId: s,
        scenePath: t,
        viewId: this.thread.viewId,
        msgType: p.DrawWork,
        dataType: g.Local
      }, e);
  }
  async updateSelector(t) {
    var m;
    const e = this.workShapes.get(N);
    if (!((m = e == null ? void 0 : e.selectIds) != null && m.length)) return;
    const { callback: s, ...o } = t, { updateSelectorOpt: r, willSerializeData: i } = o, c = await (e == null ? void 0 : e.updateSelector({
      updateSelectorOpt: r,
      selectIds: Q(e.selectIds),
      vNodes: this.vNodes,
      willSerializeData: i,
      worker: this
    })), n = /* @__PURE__ */ new Map();
    let a;
    c != null && c.selectIds && (a = ce(e.selectIds, c.selectIds), c.selectIds.forEach((d) => {
      const w = this.vNodes.get(d);
      if (w) {
        const { toolsType: k, op: S, opt: v } = w;
        n.set(d, {
          opt: v,
          toolsType: k,
          ops: (S == null ? void 0 : S.length) && $(S) || void 0
        });
      }
    }), e.selectIds = c.selectIds);
    const h = [], l = s && s({
      res: c,
      workShapeNode: e,
      param: o,
      postData: { sp: h },
      newServiceStore: n
    }) || { sp: h };
    a && l.sp.push({
      type: p.RemoveNode,
      removeIds: a,
      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();
    }), this.thread.localLayer.removeAllChildren()), this.workShapes.get(N)) {
      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: c, name: n, toolsType: a, 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 (a === f.Text && se([l, m], c) && h.workState === W.Done) {
          r = n;
          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: U,
      toolsType: s,
      opt: e
    });
    r && o && r.cursorHover(o);
  }
  updateFullSelectWork(t) {
    var o, r, i, c, n;
    const e = this.workShapes.get(N), { selectIds: s } = t;
    if (!(s != null && s.length)) {
      this.blurSelector(t);
      return;
    }
    if (!e) {
      const a = this.setFullWork(t);
      !a && t.workId && this.tmpOpt && ((o = this.tmpOpt) == null ? void 0 : o.toolsType) === f.Selector && this.setWorkOptions(t.workId.toString(), t.opt || this.tmpOpt.toolsOpt), a && this.updateFullSelectWork(t);
      return;
    }
    if (e && (s != null && s.length)) {
      const { selectRect: a } = 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: ((c = t.opt) == null ? void 0 : c.fillColor) || e.fillColor,
        textOpt: ((n = t.opt) == null ? void 0 : n.textOpt) || e.textOpt,
        canTextEdit: e.canTextEdit,
        canRotate: e.canRotate,
        scaleType: e.scaleType,
        type: p.Select,
        selectRect: a,
        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(N);
    if (!r)
      return;
    const i = r.selectIds && [...r.selectIds] || [];
    for (const c of i) {
      if (this.vNodes.get(c)) {
        const a = this.commandDeleteText(c);
        a && s.push(a);
      }
      this.removeNode(c), o.push(c);
    }
    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();
    }), this.vNodes.delete(t)), this.workShapes.has(t) && (this.thread.localLayer.getElementsByName(t).forEach((r) => {
      r.remove();
    }), 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 && A(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(N), { 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 && A(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(N);
  }
  getSelector() {
    return this.workShapes.get(N);
  }
  reRenderSelector(t = !1) {
    var o;
    const e = this.workShapes.get(N);
    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(N), s = e == null ? void 0 : e.blurSelector();
    if (this.clearWorkShapeNodeCache(N), ((o = this.thread.fullLayer) == null ? void 0 : o.parent).children.forEach((r) => {
      r.name === N && 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);
  }
  drawBitMapEraser(t) {
    const e = [];
    t.op && e.push(t), e.length && this.thread.post({ sp: e });
  }
  async drawBitMapEraserFull(t, e, s) {
    const { willUpdateNodes: o, scenePath: r, ...i } = e, c = t.getWorkId(), n = [
      {
        ...i,
        workId: c,
        scenePath: r,
        updateNodeOpt: {
          useAnimation: !1
        },
        isSync: !0,
        nextTasks: [
          {
            type: p.RemoveNode,
            removeIds: [c],
            viewId: this.thread.viewId
          }
        ]
      }
    ];
    if (s && n.push({
      type: p.None,
      isLockSentEventCursor: s
    }), o != null && o.size) {
      await (t == null ? void 0 : t.reRenderEffectNodes({
        willUpdateNodes: o,
        worker: this
      }));
      for (const [a, h] of o)
        n.push({
          type: p.UpdateNode,
          dataType: g.Local,
          opt: h.opt,
          workId: a,
          updateNodeOpt: {
            useAnimation: !1
          }
        });
    }
    n.length && this.thread.post({ sp: n });
  }
  drawPencilEraser(t, e) {
    var o, r;
    const s = [];
    if ((o = t.newWorkDatas) != null && o.size) {
      for (const i of t.newWorkDatas.values()) {
        const c = i.workId.toString();
        this.batchEraserWorks.add(c), s.push({
          type: p.FullWork,
          workId: c,
          ops: $(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 }), 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 });
  }
  updateBatchEraserCombineNode(t, e) {
    for (const s of e.keys())
      this.thread.fullLayer.getElementsByName(s).forEach((o) => {
        o.remove();
      });
    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 } = t;
    if (s != null && s.length && o) {
      const i = o.toString(), c = this.workShapes.get(i);
      if (!c)
        return;
      const n = c.toolsType;
      if (n === f.LaserPen)
        return;
      switch (this.drawWorkActiveId && this.drawWorkActiveId !== i && (this.consumeDrawAll({
        workId: this.drawWorkActiveId,
        scenePath: r,
        viewId: this.thread.viewId,
        msgType: p.DrawWork,
        dataType: g.Local
      }, e), this.drawWorkActiveId = void 0), !this.drawWorkActiveId && i !== N && (this.drawWorkActiveId = i), n) {
        case f.Selector:
          {
            const a = c.consume({
              data: t,
              isFullWork: !0
            });
            a.type === p.Select && (a.selectIds && e.runReverseSelectWork(a.selectIds), this.thread.post({ sp: [a] }));
          }
          break;
        case f.PencilEraser:
          {
            const a = c.consume({
              data: t,
              isFullWork: !0
            });
            a != null && a.rect && this.drawPencilEraser(a);
          }
          break;
        case f.BitMapEraser: {
          const a = c.consume({
            data: t,
            isFullWork: !0
          });
          a != null && a.rect && this.drawBitMapEraser(a);
          break;
        }
        case f.Eraser:
          {
            const a = c.consume({
              data: t,
              isFullWork: !0
            });
            a != null && a.rect && this.drawEraser(a);
          }
          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 a = c.consume({
              data: t,
              isFullWork: !1,
              isMainThread: !0
            });
            a && (this.drawCount++, this.thread.post({
              drawCount: this.drawCount,
              sp: a.op && [{ ...a, scenePath: r }] || void 0
            }));
          }
          break;
      }
    }
  }
  consumeDrawAll(t, e) {
    var i, c, n, a;
    const { workId: s, scenePath: o, isLockSentEventCursor: r } = t;
    if (s) {
      const h = s.toString();
      this.drawWorkActiveId === h && (this.drawWorkActiveId = void 0);
      const l = this.workShapes.get(h);
      if (!l)
        return;
      const m = l.toolsType;
      if (m === f.LaserPen)
        return;
      const d = this.workShapes.get(U), w = (i = d == null ? void 0 : d.selectIds) == null ? void 0 : i[0], k = l.consumeAll({ data: t });
      switch (m) {
        case f.Selector:
          k.selectIds && w && ((c = k.selectIds) != null && c.includes(w)) && d.cursorBlur(), k.type === p.Select && (k.selectIds && e.runReverseSelectWork(k.selectIds), this.thread.post({ sp: [{ ...k, scenePath: o }] })), (n = l.selectIds) != null && n.length ? l.clearTmpPoints() : this.clearWorkShapeNodeCache(h);
          break;
        case f.PencilEraser:
          this.drawPencilEraser({ ...k, scenePath: o }, r), l.clearTmpPoints();
          break;
        case f.BitMapEraser:
          (k.rect || (a = k.newWorkDatas) != null && a.size) && this.drawBitMapEraserFull(l, k, r);
          break;
        case f.Eraser:
          this.drawEraser({ ...k, scenePath: o }, r), l.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.drawCount = 0, this.thread.post({
            drawCount: this.drawCount,
            sp: S
          })), this.clearWorkShapeNodeCache(h);
          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 F({ ...t, vNodes: this.vNodes, fullLayer: this.thread.fullLayer, drawLayer: this.thread.localLayer }, this.thread.serviceWork);
  }
}
class pe {
  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", R.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();
    }), this.thread.serviceLayer.removeAllChildren()), 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, c, n, a, h, l, m, d, w, k, S, v;
    this.animationId = void 0;
    let t = !1;
    const e = /* @__PURE__ */ new Map();
    for (const [I, y] of this.workShapes.entries())
      switch (y.toolsType) {
        case f.Image: {
          await ((s = y.node) == null ? void 0 : s.consumeServiceAsync({
            isFullWork: !0,
            worker: this
          })), this.selectorWorkShapes.forEach((b, E) => {
            var O;
            (O = b.selectIds) != null && O.includes(I) && (this.willRunEffectSelectorIds.add(E), this.runEffect());
          }), this.workShapes.delete(I);
          break;
        }
        case f.Text: {
          y.node && (await ((o = y.node) == null ? void 0 : o.consumeServiceAsync({
            isFullWork: !0,
            replaceId: I
          })), this.selectorWorkShapes.forEach((b, E) => {
            var O;
            (O = b.selectIds) != null && O.includes(I) && (this.willRunEffectSelectorIds.add(E), this.runEffect());
          }), (r = y.node) == null || r.clearTmpPoints(), this.workShapes.delete(I));
          break;
        }
        case f.Arrow:
        case f.Straight:
        case f.Rectangle:
        case f.Ellipse:
        case f.Star:
        case f.Polygon:
        case f.SpeechBalloon: {
          const b = !!y.ops;
          if ((i = y.animationWorkData) != null && i.length) {
            const E = y.oldRect;
            (c = y.node) == null || c.consumeService({
              op: y.animationWorkData,
              isFullWork: b
            }), b && (this.selectorWorkShapes.forEach((O, D) => {
              var x;
              (x = O.selectIds) != null && x.includes(I) && (this.willRunEffectSelectorIds.add(D), this.runEffect());
            }), (n = y.node) == null || n.clearTmpPoints(), this.workShapes.delete(I)), e.set(I, {
              workState: E ? y.ops ? W.Done : W.Doing : W.Start,
              op: y.animationWorkData.filter((O, D) => {
                if (D % 3 !== 2)
                  return !0;
              }).slice(-2)
            }), y.animationWorkData.length = 0;
          }
          break;
        }
        case f.Pencil: {
          if (!y.useAnimation && y.ops)
            (a = y.node) == null || a.consumeService({
              op: y.animationWorkData || [],
              isFullWork: !0,
              replaceId: I
            }), (h = y.node) == null || h.updataOptService(y.updateNodeOpt), this.selectorWorkShapes.forEach((b, E) => {
              var O;
              (O = b.selectIds) != null && O.includes(I) && (this.willRunEffectSelectorIds.add(E), this.runEffect());
            }), (l = y.node) == null || l.clearTmpPoints(), this.workShapes.delete(I);
          else if (y.useAnimation) {
            if (y.isDel) {
              (m = y.node) == null || m.clearTmpPoints(), this.workShapes.delete(I);
              break;
            }
            const b = 3, E = this.computNextAnimationIndex(y, b), O = y.isDiff ? 0 : Math.max(0, (y.animationIndex || 0) - b), D = (y.animationWorkData || []).slice(O, E), x = (w = (d = y.node) == null ? void 0 : d.getWorkId()) == null ? void 0 : w.toString();
            if ((y.animationIndex || 0) < E || y.isDiff) {
              if ((k = y.node) == null || k.consumeService({
                op: D,
                isFullWork: !1
              }), y.animationIndex = E, y.isDiff && (y.isDiff = !1), D.length) {
                const z = D.filter((_, J) => {
                  if (J % b !== b - 1)
                    return !0;
                }).slice(-2);
                e.set(I, {
                  workState: O === 0 ? W.Start : E === ((S = y.animationWorkData) == null ? void 0 : S.length) ? W.Done : W.Doing,
                  op: z
                });
              }
            } else y.ops && ((v = y.node) == null || v.consumeService({
              op: y.animationWorkData || [],
              isFullWork: !0,
              replaceId: x
            }), y.isDel = !0, e.set(I, {
              workState: W.Done,
              op: D.filter((z, _) => {
                if (_ % b !== b - 1)
                  return !0;
              }).slice(-2)
            }));
            t = !0;
            break;
          }
          break;
        }
      }
    if (t && this.runAnimation(), e.size) {
      const I = [];
      e.forEach((y, b) => {
        I.push({
          type: p.Cursor,
          uid: b.split(Z)[0],
          op: y.op,
          workState: y.workState,
          viewId: this.thread.viewId
        });
      }), this.thread.post({ sp: I });
    }
  }
  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 w, k, S, v;
    const { workId: e, opt: s, toolsType: o, type: r, updateNodeOpt: i, ops: c, op: n, useAnimation: a, imageBitmap: h } = t;
    if (!e)
      return;
    const l = e.toString(), m = (w = this.vNodes.get(l)) == null ? void 0 : w.rect;
    if (!((k = this.workShapes) != null && k.has(l))) {
      let I = {
        toolsType: o,
        animationWorkData: n || [],
        animationIndex: 0,
        type: r,
        updateNodeOpt: i,
        ops: c,
        useAnimation: typeof a < "u" ? a : typeof (i == null ? void 0 : i.useAnimation) < "u" ? i == null ? void 0 : i.useAnimation : !0,
        oldRect: m,
        isDiff: !1,
        imageBitmap: h
      };
      o && s && (I = this.setNodeKey(l, I, o, s)), (S = this.workShapes) == null || S.set(l, I);
    }
    const d = (v = this.workShapes) == null ? void 0 : v.get(l);
    r && (d.type = r), c && (d.animationWorkData = A(c), d.ops = c), i && (d.updateNodeOpt = i), n && (d.isDiff = this.hasDiffData(d.animationWorkData || [], n, d.toolsType), d.animationWorkData = n), 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(N) > -1 && this.removeSelectWork(e), this.thread.fullLayer.getElementsByName(t).forEach((s) => {
      s.remove();
    }), this.thread.serviceLayer.getElementsByName(t).forEach((s) => {
      s.remove();
    }), 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 a, h, l;
    const { workId: e, opt: s, toolsType: o, type: r, selectIds: i } = t;
    if (!e)
      return;
    const c = e.toString();
    if (!((a = this.selectorWorkShapes) != null && a.has(c))) {
      let m = {
        toolsType: o,
        selectIds: i,
        type: r,
        opt: s
      };
      o && s && (m = this.setNodeKey(c, m, o, s)), (h = this.selectorWorkShapes) == null || h.set(c, m);
    }
    const n = (l = this.selectorWorkShapes) == null ? void 0 : l.get(c);
    r && (n.type = r), n.node && n.node.getWorkId() !== c && n.node.setWorkId(c), n.selectIds = i || [];
  }
  setNodeKey(t, e, s, o) {
    return e.toolsType = s, e.node = F({
      toolsType: s,
      toolsOpt: o,
      vNodes: this.vNodes,
      fullLayer: this.thread.fullLayer,
      drawLayer: this.thread.serviceLayer,
      workId: t
    }, this), e;
  }
}
class C {
  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 de extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 ue extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 a;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c, textUpdateForWoker: n } = e;
    s === N && o && await ((a = this.localWork) == null ? void 0 : a.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: c,
      textUpdateForWoker: n,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r } = e, { willSyncService: i, isSync: c, textUpdateForWoker: n } = s, a = o.sp || [];
    if (i)
      for (const [h, l] of r.entries())
        n && l.toolsType === f.Text ? a.push({
          ...l,
          workId: h,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : a.push(
          {
            ...l,
            workId: h,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: c
          }
        );
    return {
      sp: a
    };
  }
}
class fe extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c } = e;
    s === N && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: c,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r } = e, { willSyncService: i, isSync: c } = s, n = o.sp || [];
    if (i && n)
      for (const [a, h] of r.entries())
        n.push(
          {
            ...h,
            workId: a,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: c
          }
        );
    return {
      sp: n
    };
  }
}
class me extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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: c, textUpdateForWoker: n, emitEventType: a } = e;
    s === N && 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: c,
      isSync: !0,
      textUpdateForWoker: n,
      emitEventType: a,
      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: c } = e, { willSyncService: n, isSync: a, updateSelectorOpt: h, textUpdateForWoker: l } = s, m = h.workState, d = o.sp || [];
    if (m === W.Start)
      return {
        sp: [],
        render: []
      };
    const w = c == null ? void 0 : c.selectRect;
    if (n) {
      m === W.Doing && d.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: w,
        willSyncService: !0,
        isSync: !0,
        points: i.getChildrenPoints(),
        textOpt: i.textOpt
      });
      for (const [k, S] of r.entries())
        l && S.toolsType === f.Text ? d.push({
          ...S,
          workId: k,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : d.push(
          {
            ...S,
            workId: k,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
    }
    return {
      sp: d
    };
  }
}
class ke extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.DeleteNode);
  }
  async consume() {
    return !1;
  }
}
class Se extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 c;
    const { workId: s, updateNodeOpt: o, willSyncService: r, willSerializeData: i } = e;
    s === N && o && await ((c = this.localWork) == null ? void 0 : c.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: c } = e, { updateSelectorOpt: n, willSyncService: a } = s, h = n.workState, l = o.sp || [], m = i == null ? void 0 : i.selectRect;
    if (h === W.Start)
      return {
        sp: [],
        render: []
      };
    if (a) {
      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, w] of c.entries())
        w.toolsType === f.Text ? l.push({
          ...w,
          workId: d,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : l.push(
          {
            ...w,
            workId: d,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: !0
          }
        );
    }
    return {
      sp: l
    };
  }
}
class ye extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 a;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c, emitEventType: n } = e;
    s === N && o && await ((a = this.localWork) == null ? void 0 : a.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: c,
      emitEventType: n,
      isSync: !0,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, workShapeNode: r, res: i, newServiceStore: c } = e, { updateSelectorOpt: n, willSyncService: a, willSerializeData: h, isSync: l } = s, m = n.workState, d = o.sp || [], w = i == null ? void 0 : i.selectRect;
    if (a) {
      h && m === W.Done && d.push({
        type: p.Select,
        selectIds: r.selectIds,
        selectRect: w,
        willSyncService: !0,
        isSync: l,
        points: r.getChildrenPoints()
      });
      for (const [k, S] of c.entries())
        d.push(
          {
            ...S,
            workId: k,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: l
          }
        );
    }
    return {
      sp: d
    };
  }
}
class we extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 a;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c, textUpdateForWoker: n } = e;
    s === N && o && await ((a = this.localWork) == null ? void 0 : a.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: c,
      textUpdateForWoker: n,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: c } = e, { willSyncService: n, isSync: a, updateSelectorOpt: h, textUpdateForWoker: l } = s, m = o.sp || [], d = c == null ? void 0 : c.selectRect;
    if (n && m) {
      h.fontSize && m.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: d,
        willSyncService: n,
        isSync: a,
        points: i.getChildrenPoints()
      });
      for (const [w, k] of r.entries())
        l && k.toolsType === f.Text ? m.push({
          ...k,
          workId: w,
          type: p.TextUpdate,
          dataType: g.Local,
          willSyncService: !0
        }) : m.push(
          {
            ...k,
            workId: w,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
    }
    return {
      sp: m
    };
  }
}
class ve extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 a;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c, textUpdateForWoker: n } = e;
    s === N && o && await ((a = this.localWork) == null ? void 0 : a.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      emitEventType: this.emitEventType,
      willSerializeData: c,
      isSync: !0,
      textUpdateForWoker: n,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: c } = e, { willSyncService: n, isSync: a } = s, h = o.sp || [], l = c == null ? void 0 : c.selectRect;
    if (n && h) {
      for (const [m, d] of r.entries())
        h.push(
          {
            ...d,
            workId: m,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
      h.push({
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: l,
        willSyncService: n,
        isSync: a,
        points: i.getChildrenPoints()
      });
    }
    return {
      sp: h
    };
  }
}
class ge extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c } = e;
    s === N && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: c,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r, workShapeNode: i, res: c } = e, { willSyncService: n, isSync: a, updateSelectorOpt: h } = s, l = o.sp || [], m = c == null ? void 0 : c.selectRect;
    if (n && l) {
      for (const [d, w] of r.entries())
        l.push(
          {
            ...w,
            workId: d,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: a
          }
        );
      l.push({
        isLocked: h.isLocked,
        selectorColor: i.selectorColor,
        scaleType: i.scaleType,
        canRotate: i.canRotate,
        type: p.Select,
        selectIds: i.selectIds,
        selectRect: m,
        willSyncService: n,
        isSync: a
      });
    }
    return {
      sp: l
    };
  }
}
class Ie extends C {
  constructor() {
    super(...arguments);
    u(this, "emitEventType", T.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 n;
    const { workId: s, updateNodeOpt: o, willRefreshSelector: r, willSyncService: i, willSerializeData: c } = e;
    s === N && o && await ((n = this.localWork) == null ? void 0 : n.updateSelector({
      updateSelectorOpt: o,
      willRefreshSelector: r,
      willSyncService: i,
      willSerializeData: c,
      callback: this.updateSelectorCallback
    }));
  }
  updateSelectorCallback(e) {
    const { param: s, postData: o, newServiceStore: r } = e, { willSyncService: i, isSync: c } = s, n = o.sp || [];
    if (i && n)
      for (const [a, h] of r.entries())
        n.push(
          {
            ...h,
            workId: a,
            type: p.UpdateNode,
            updateNodeOpt: {
              useAnimation: !1
            },
            isSync: c
          }
        );
    return {
      sp: n
    };
  }
}
class Te {
  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 me();
      case T.ZIndexNode:
        return new fe();
      case T.CopyNode:
        return new de();
      case T.SetColorNode:
        return new ue();
      case T.DeleteNode:
        return new ke();
      case T.ScaleNode:
        return new Se();
      case T.RotateNode:
        return new ye();
      case T.SetFontStyle:
        return new we();
      case T.SetPoint:
        return new ve();
      case T.SetLock:
        return new ge();
      case T.SetShapeOpt:
        return new Ie();
    }
  }
  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 We {
  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 = R.bufferSize.full, o = R.bufferSize.sub;
    this.fullLayer = this.createLayer("fullLayer", this.scene, { ...e.layerOpt, bufferSize: this.viewId === M ? s : o }), this.topLayer = this.createLayer("topLayer", this.scene, { ...e.layerOpt, bufferSize: (this.viewId === M, o) }), this.localLayer = this.createLayer("localLayer", this.scene, { ...e.layerOpt, bufferSize: (this.viewId === M, o) }), this.serviceLayer = this.createLayer("serviceLayer", this.scene, { ...e.layerOpt, bufferSize: (this.viewId === M, o) }), this.vNodes = new re(t, this.scene);
    const r = {
      thread: this,
      vNodes: this.vNodes
    };
    this.localWork = new he(r), this.serviceWork = new pe(r), this.topWork = new le(r), this.vNodes.init(this.fullLayer), this.methodBuilder = new Te([
      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();
  }
  async on(t) {
    if (!await this.methodBuilder.consumeForMainThread(t)) {
      const { msgType: e, toolsType: s, opt: o, dataType: r, workId: i, workState: c, imageSrc: n, imageBitmap: a, workIds: h } = t, l = i == null ? void 0 : i.toString();
      switch (e) {
        case p.AuthClear: {
          const { clearUids: m, localUid: d } = t;
          this.vNodes.setCanClearUids(m), this.vNodes.setLocalUid(d);
          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 m = {
              toolsType: s,
              toolsOpt: o
            };
            this.topWork.canUseTopLayer(s) ? this.topWork.setToolsOpt(m) : this.localWork.setToolsOpt(m);
          }
          break;
        case p.CreateWork:
          if (l && o && s) {
            if (this.topWork.canUseTopLayer(s)) {
              this.topWork.getToolsOpt() || this.topWork.setToolsOpt({
                toolsType: s,
                toolsOpt: o
              }), this.topWork.setWorkOptions(l, o);
              break;
            }
            this.localWork.getToolsOpt() || this.localWork.setToolsOpt({
              toolsType: s,
              toolsOpt: o
            }), this.localWork.setWorkOptions(l, o);
          }
          break;
        case p.DrawWork:
          c === W.Done && r === g.Local ? this.consumeDrawAll(r, t) : 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 === N ? this.localWork.updateFullSelectWork(t) : this.serviceWork.runSelectWork(t));
          break;
        case p.CursorHover:
          this.localWork.cursorHover(t);
          break;
        case p.GetTextActive:
          r === g.Local && this.localWork.checkTextActive(t);
          break;
        case p.GetImageBitMap:
          if (n && a && i) {
            const m = i.toString();
            this.deleteCachedImagesByWorkId(m), this.cacheImages.set(n, {
              imageBitmap: a,
              workId: m
            });
            const d = this.imageResolveMap.get(n);
            if (d) {
              const { resolve: w, timer: k } = d;
              k && clearTimeout(k), w && w(n);
            }
          }
          break;
        case p.GetVNodeInfo:
          if (i && h) {
            const m = h.map((d) => this.vNodes.get(d));
            this.post({
              sp: [
                {
                  type: p.GetVNodeInfo,
                  dataType: g.Local,
                  workId: i,
                  vInfo: m
                }
              ]
            });
          }
          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: c, width: n, height: a, strokeColor: h } = s;
      if (!i || !c || !n || !a)
        return;
      let l = i;
      if (c === j.Iconify) {
        const [k, S] = this.getIconSize(n, a, this.opt.displayer.dpr);
        l = `${i}?width=${k}&height=${S}&color=${h}`;
      }
      if (this.cacheImages.has(l)) {
        const k = this.getCachedImages(l);
        if (k)
          return k;
      }
      if (this.imageResolveMap.has(l)) {
        const k = this.getCachedImagesByWorkId(r);
        if (k)
          return k;
      }
      const w = await new Promise((k) => {
        const S = this.imageResolveMap.get(l) || {
          resolve: void 0,
          timer: void 0
        };
        S.timer && clearTimeout(S.timer), S.resolve = k, S.timer = setTimeout(() => {
          const v = this.imageResolveMap.get(l);
          v != null && v.resolve && v.resolve(l);
        }, 5e3), this.imageResolveMap.set(l, S), 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(w), 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 === N) {
          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 s;
    this.mainThreadPostId = void 0;
    const t = [];
    let e;
    for (const o of this.combinePostMsg.values()) {
      if ((s = o.sp) != null && s.length)
        for (const r of o.sp) {
          let i = !1;
          for (const c of t)
            if (K(r, c)) {
              i = !0;
              break;
            }
          i || t.push(r);
        }
      ne(o.drawCount) && (e = o.drawCount);
    }
    return this.combinePostMsg.clear(), {
      sp: t,
      drawCount: e
    };
  }
  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.drawCount === void 0 && delete t.drawCount, (t != null && t.drawCount || (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();
    }), this.fullLayer.removeAllChildren()), 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 && !K(this.cameraOpt, e)) {
      if (this.taskUpdateCameraId && (clearTimeout(this.taskUpdateCameraId), this.taskUpdateCameraId = void 0), s) {
        let a = !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 !== U && h !== N && (a = !0);
              break;
          }
        if (a) {
          this.taskUpdateCameraId = setTimeout(() => {
            this.taskUpdateCameraId = void 0, this.updateCamera(t);
          }, H);
          return;
        }
      }
      const r = /* @__PURE__ */ new Map();
      for (const [a, h] of this.vNodes.getNodesByType(f.Text).entries()) {
        const l = h.rect;
        r.set(a, Q(l));
      }
      const i = new Set(r.keys());
      let c = !1;
      if (this.localWork.hasSelector()) {
        const a = (o = this.localWork.getSelector()) == null ? void 0 : o.selectIds;
        if (a) {
          c = !0;
          for (const h of a)
            i.add(h);
        }
      }
      let n = !1;
      if (this.serviceWork.selectorWorkShapes.size)
        for (const a of this.serviceWork.selectorWorkShapes.values()) {
          const h = a.selectIds;
          if (h) {
            n = !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 [a, h] of r.entries()) {
          const l = this.vNodes.get(a);
          if (l) {
            const m = h, d = l.rect, w = this.getSceneRect(), k = P(m, w), S = P(d, w);
            let v = !1;
            if ((k !== S || m.w !== d.w || m.h !== d.h || S === q.intersect) && (v = !0), v) {
              const { toolsType: I, opt: y } = l;
              I === f.Text && y.workState === W.Done && this.debounceUpdateCache.add(a);
            }
          }
        }
        if (c && this.localWork.reRenderSelector(), n)
          for (const [a, h] of this.serviceWork.selectorWorkShapes.entries())
            this.serviceWork.runSelectWork({
              workId: a,
              selectIds: h.selectIds,
              msgType: p.Select,
              dataType: g.Service,
              viewId: this.viewId
            });
        this.debounceUpdateCameraId = setTimeout(() => {
          var h;
          this.debounceUpdateCameraId = void 0;
          const a = [];
          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: w, opt: k, rect: S } = d, v = this.localWork.setFullWork({
                  toolsType: w,
                  opt: k,
                  workId: l
                });
                if (v) {
                  const I = this.getSceneRect(), y = P(S, I);
                  a.push(v.consumeServiceAsync({
                    isFullWork: !0,
                    replaceId: l,
                    isDrawLabel: y !== q.outside
                  }));
                }
              }
            }
            this.debounceUpdateCache.delete(l);
          }
          this.vNodes.updateLowLevelNodesRect(), this.vNodes.clearHighLevelIds();
        }, H);
      }
    }
  }
  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 X({
      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}`, c = e.layer(i, { ...s, offscreen: !1 }), n = new Y({
      anchor: [0.5, 0.5],
      pos: [o * 0.5, r * 0.5],
      size: [o, r],
      name: "viewport",
      id: t
    });
    return c.append(n), n;
  }
  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(), this.topLayer.remove(), this.localLayer.remove(), this.serviceLayer.remove(), this.scene.remove(), this.localWork.destroy(), this.serviceWork.destroy(), this.topWork.destroy();
  }
}
class Ne {
  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 === M ? 6e3 : 3e3 });
  }
  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 c = this.imageResolveMap.get(s);
          if (c) {
            const { resolve: n, timer: a } = c;
            a && clearTimeout(a), n && n(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: c, width: n, height: a, strokeColor: h } = s;
      if (!i || !c || !n || !a)
        return;
      let l = i;
      if (c === j.Iconify) {
        const [k, S] = this.getIconSize(n, a, this.opt.displayer.dpr);
        l = `${i}?width=${k}&height=${S}&color=${h}`;
      }
      if (this.cacheImages.has(l)) {
        const k = this.getCachedImages(l);
        if (k)
          return k;
      }
      if (this.imageResolveMap.has(l)) {
        const k = this.getCachedImagesByWorkId(r);
        if (k)
          return k;
      }
      const w = await new Promise((k) => {
        const S = this.imageResolveMap.get(l) || {
          resolve: void 0,
          timer: void 0
        };
        S.timer && clearTimeout(S.timer), S.resolve = k, S.timer = setTimeout(() => {
          const v = this.imageResolveMap.get(l);
          v != null && v.resolve && v.resolve(l);
        }, 5e3), this.imageResolveMap.set(l, S), 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(w), this.getCachedImages(l);
    }
  }
  createWorkShapeNode(t) {
    return F({ ...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 && A(t.ops);
    if (e) {
      let r, i;
      const c = (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: c,
        isDrawLabel: !0
      }) : (r = e.consumeService({
        op: s,
        isFullWork: !0,
        replaceId: c
      }), i = (t == null ? void 0 : t.updateNodeOpt) && e.updataOptService(t.updateNodeOpt)), B(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 c;
      for (const [a, 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: a,
                msgType: p.FullWork,
                dataType: g.Service,
                viewId: this.viewId
              }, d = await this.runFullWork(m);
              c = B(c, d);
              break;
            }
          }
      let n;
      r && i && (n = {
        resizeWidth: r,
        resizeHeight: i
      }), await this.getSnapshotRender({ scenePath: e, options: n });
    }
  }
  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, i;
    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
      }]
    }), (i = this.fullLayer) == null || i.removeAllChildren());
  }
  async getBoundingRect(t) {
    const { scenePath: e, scenes: s, cameraOpt: o } = t;
    if (e && s && o) {
      this.setCameraOpt(o);
      let r;
      for (const [i, c] of Object.entries(s))
        if (c != null && c.type)
          switch (c == null ? void 0 : c.type) {
            case p.UpdateNode:
            case p.FullWork: {
              const n = await this.runFullWork({
                ...c,
                workId: i,
                msgType: p.FullWork,
                dataType: g.Service,
                viewId: this.viewId
              });
              r = B(r, n);
              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 (ie(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, (t != null && t.drawCount || (o = t.sp) != null && o.length) && this.opt.post(t);
  }
  createScene(t) {
    return new X({
      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}`, c = e.layer(i, s), n = new Y({
      anchor: [0.5, 0.5],
      pos: [o * 0.5, r * 0.5],
      size: [o, r],
      name: "viewport",
      id: t
    });
    return c.append(n), n;
  }
  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(), this.scene.remove();
  }
}
class xe {
  constructor(t) {
    u(this, "mainThreadMap", /* @__PURE__ */ new Map());
    u(this, "snapshotThread");
    u(this, "master");
    this.master = t;
  }
  post(t) {
    const { drawCount: e, sp: s, workerTasksqueueCount: o } = t;
    this.master.isBusy && G(o) && this.master.setWorkerTasksqueueCount(o), G(e) && this.master.setMaxDrawCount(e), s && this.master.collectorSyncData(s);
  }
  destroy() {
    this.mainThreadMap.clear();
  }
  createMainThread(t, e) {
    return new We(t, e);
  }
  createSnapshotThread(t, e) {
    return new Ne(t, e);
  }
  async consume(t) {
    var e, s, o, r;
    for (const i of t.values()) {
      const { msgType: c, viewId: n, tasksqueue: a, mainTasksqueueCount: h, layerOpt: l, offscreenCanvasOpt: m, cameraOpt: d, isSubWorker: w } = i;
      if (c === p.Console) {
        console.log(this);
        continue;
      }
      if (c === p.Init) {
        const S = (e = this.master.control.viewContainerManager.getView(n)) == null ? void 0 : e.displayer, v = S == null ? void 0 : S.canvasContainerRef.current;
        if (S && v && l && m) {
          const I = this.createMainThread(n, {
            displayer: S,
            container: v,
            layerOpt: l,
            master: this.master,
            canvasOpt: m,
            post: this.post.bind(this)
          });
          this.mainThreadMap.set(n, I), I && d && I.setCameraOpt(d);
        }
        continue;
      }
      if ((c === p.Snapshot || c === p.BoundingBox) && n === ((s = this.master.control.viewContainerManager.mainView) == null ? void 0 : s.id)) {
        const S = (o = this.master.control.viewContainerManager.getView(n)) == null ? void 0 : o.displayer, v = (r = S.snapshotContainerRef) == null ? void 0 : r.current;
        if (S && v && d) {
          v.style.width = `${d.width}px`, v.style.height = `${d.height}px`;
          const I = {
            ...V.defaultLayerOpt,
            offscreen: !1,
            width: d.width,
            height: d.height
          }, y = {
            ...V.defaultScreenCanvasOpt,
            width: d.width,
            height: d.height
          };
          this.snapshotThread = this.createSnapshotThread(n, {
            displayer: S,
            container: v,
            layerOpt: I,
            master: this.master,
            canvasOpt: y,
            post: this.post.bind(this)
          }), this.snapshotThread.on(i).then(() => {
            this.snapshotThread = void 0, v.innerHTML = "", v.style.width = "", v.style.height = "";
          });
          continue;
        }
      }
      if (c === p.GetImageBitMap && w && this.snapshotThread) {
        this.snapshotThread.on(i);
        continue;
      }
      if (c === p.TasksQueue && (a != null && a.size)) {
        for (const [S, v] of this.mainThreadMap.entries()) {
          const I = a.get(S);
          I && (await v.on(I), h && this.post({ workerTasksqueueCount: h }));
        }
        continue;
      }
      if (n === ae) {
        for (const S of this.mainThreadMap.values())
          S.on(i), c === p.Destroy && this.mainThreadMap.delete(n);
        continue;
      }
      const k = this.mainThreadMap.get(n);
      k && (k.on(i), c === p.Destroy && this.mainThreadMap.delete(n));
    }
  }
}
export {
  xe as MainThreadManagerImpl
};
