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