@printine/pod-editor 0.1.20 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1469 @@
1
+ import { jsxs as Le, jsx as H } from "react/jsx-runtime";
2
+ import { forwardRef as et, useRef as b, useState as j, useCallback as G, useEffect as re, useImperativeHandle as tt } from "react";
3
+ import { LAYER_BLACK_LIST as Ie, BLEND_MODES_MAP as rt } from "./engine/constants.js";
4
+ import { P as Ue, h as st, r as it, i as ye, M as nt, a as at } from "./pixel-map-CSpWvUYE.js";
5
+ import "./engine/fabric.js";
6
+ import { v4 as ct } from "uuid";
7
+ import { cloneObject as K, urlToDataURL as ot } from "./engine/utils/common.js";
8
+ import { ImageProcessor as lt } from "./engine/processors/image.js";
9
+ import { TemplateProcessor as ht } from "./engine/processors/template.js";
10
+ import { TextProcessor as ut } from "./engine/processors/text.js";
11
+ import { ResizeManager as dt } from "./engine/managers/resize.js";
12
+ import { loadOverlaySvgImage as ft, loadImage as gt } from "./engine/utils/image.js";
13
+ import { WorkspaceManager as pt } from "./engine/managers/workspace.js";
14
+ import { HistoryManager as mt } from "./engine/history.js";
15
+ import wt from "./engine/events.js";
16
+ import { fabric as z } from "fabric";
17
+ import { setDefaultControls as vt } from "./engine/utils/setting.js";
18
+ class We {
19
+ constructor(e, s, r, t = 0.85) {
20
+ this.imageCache = /* @__PURE__ */ new Map(), this.overlayCache = /* @__PURE__ */ new Map(), this.destroyed = !1, this.deleteObject = (i) => {
21
+ if (i) {
22
+ const a = this.canvas._objects.find((n) => n.id === i);
23
+ a && (this.canvas.remove(a), this.revokeImgBlobLink(a));
24
+ } else {
25
+ const a = this.canvas.getActiveObjects();
26
+ a.length > 0 && (a.forEach((n) => {
27
+ this.canvas.remove(n), this.revokeImgBlobLink(n);
28
+ }), this.canvas.discardActiveObject());
29
+ }
30
+ this.canvas.requestRenderAll();
31
+ }, this.canvas = new z.Canvas(e, {
32
+ enableRetinaScaling: !0,
33
+ width: s.width,
34
+ height: s.height,
35
+ preserveObjectStacking: !0,
36
+ stopContextMenu: !1,
37
+ centeredRotation: !0,
38
+ hoverCursor: "grab",
39
+ moveCursor: "grabbing",
40
+ allowTouchScrolling: !0,
41
+ selection: !0,
42
+ interactive: !0,
43
+ controlsAboveOverlay: !0,
44
+ fireRightClick: !0
45
+ // 允许识别右键点击
46
+ }), this.overlayScale = t, this.imageProcessor = new lt(this), this.templateProcessor = new ht(this), this.textProcessor = new ut(this), this.resizeManager = new dt(this, r), this.workspaceManager = new pt(this);
47
+ }
48
+ /**
49
+ * ImageProcessor/TextProcessor are shared with the interactive editor and
50
+ * expect a loading-overlay factory. SemiExportEditor renders on a hidden
51
+ * canvas, so drawing a spinner would only add work and could leak into the
52
+ * exported texture. Keep the shared processor contract with a no-op handle.
53
+ */
54
+ createLoading() {
55
+ return {
56
+ addLoadingGroup() {
57
+ },
58
+ removeLoadingGroup() {
59
+ }
60
+ };
61
+ }
62
+ /**
63
+ * 渲染 overlayImage(SVG)
64
+ * @param mockup 模板信息
65
+ * @param changeView 是否切换视图,如果为true,则需要重新设置画布和背景图
66
+
67
+ */
68
+ async renderOverlayImage(e, s = !1) {
69
+ const { image: r, clipPath: t } = await this.getOverlayImage(e.image), i = Math.min(this.canvas.width, this.canvas.height) * this.overlayScale, a = i / r.width, n = i / r.height, c = Math.min(a, n);
70
+ return r.set({
71
+ scaleX: c,
72
+ scaleY: c,
73
+ left: (this.canvas.width - r.width * c) / 2,
74
+ top: (this.canvas.height - r.height * c) / 2,
75
+ selectable: !1
76
+ }), t && t.set({
77
+ scaleX: c,
78
+ scaleY: c,
79
+ left: (this.canvas.width - t.width * c) / 2,
80
+ top: (this.canvas.height - t.height * c) / 2,
81
+ absolutePositioned: !0,
82
+ selectable: !1,
83
+ evented: !1
84
+ }), s && this.canvas.setViewportTransform([1, 0, 0, 1, 0, 0]), new Promise((o) => {
85
+ this.canvas.setOverlayImage(r, async () => {
86
+ this.workspaceManager.setClipPath(t ?? r, {
87
+ width: r.width,
88
+ height: r.height
89
+ }), this.setupOverlayBorders(r, t), this.canvas.renderAll(), o();
90
+ });
91
+ });
92
+ }
93
+ /**
94
+ * 获取 overlay 图:优先使用会话级缓存,避免重复网络请求
95
+ * 会返回深拷贝,确保不同视图间互不影响
96
+ */
97
+ async getOverlayImage(e) {
98
+ const s = this.overlayCache.get(e);
99
+ if (s) {
100
+ const a = await K(s.image), n = s.clipPath ? await K(s.clipPath) : void 0;
101
+ return { image: a, clipPath: n };
102
+ }
103
+ const r = await ft(e);
104
+ this.overlayCache.set(e, r);
105
+ const t = await K(r.image), i = r.clipPath ? await K(r.clipPath) : void 0;
106
+ return { image: t, clipPath: i };
107
+ }
108
+ /**
109
+ * 绘制可设计区域边框,优先使用 clipPath 的真实形状
110
+ */
111
+ setupOverlayBorders(e, s) {
112
+ this.overlayBorderHandler && this.canvas.off("after:render", this.overlayBorderHandler);
113
+ const r = s ?? e;
114
+ this.overlayBorderHandler = () => {
115
+ const t = this.canvas.getContext(), i = this.canvas.viewportTransform || [1, 0, 0, 1, 0, 0];
116
+ t.save(), t.transform(i[0], i[1], i[2], i[3], i[4], i[5]);
117
+ const a = {
118
+ stroke: r.stroke,
119
+ strokeWidth: r.strokeWidth,
120
+ strokeDashArray: r.strokeDashArray,
121
+ fill: r.fill,
122
+ strokeUniform: r.strokeUniform
123
+ };
124
+ r.set({
125
+ stroke: "#C3C3CC",
126
+ strokeWidth: 1,
127
+ strokeDashArray: [],
128
+ fill: "transparent",
129
+ strokeUniform: !0,
130
+ objectCaching: !1
131
+ }), r.render(t);
132
+ const n = 6, c = (r.getScaledWidth() + n * 2) / r.getScaledWidth(), o = (r.getScaledHeight() + n * 2) / r.getScaledHeight(), m = r.left ?? 0, d = r.top ?? 0, P = r.scaleX ?? 1, u = r.scaleY ?? 1;
133
+ r.set({
134
+ strokeDashArray: [4, 4],
135
+ stroke: "#C3C3CC",
136
+ strokeWidth: 1,
137
+ strokeUniform: !0,
138
+ scaleX: P * c,
139
+ scaleY: u * o,
140
+ left: m - n,
141
+ top: d - n
142
+ }), r.render(t), r.set({
143
+ stroke: a.stroke,
144
+ strokeWidth: a.strokeWidth,
145
+ strokeDashArray: a.strokeDashArray,
146
+ fill: a.fill,
147
+ strokeUniform: a.strokeUniform,
148
+ scaleX: P,
149
+ scaleY: u,
150
+ left: m,
151
+ top: d
152
+ }), t.restore();
153
+ }, this.canvas.on("after:render", this.overlayBorderHandler);
154
+ }
155
+ /**
156
+ * 渲染背景图(Bitmap)png、webp 等位图
157
+ * @param mockup 模板信息
158
+ * @param color 背景颜色
159
+ * @param changeView 是否切换视图,如果为true,则需要重新设置画布和背景图
160
+ */
161
+ // async renderBitmapBackground(mockup: Mockup, color: string, changeView: boolean = false) {
162
+ // const renderImage = await loadImage(mockup.generateImageUrl);
163
+ // renderImage.set({
164
+ // scaleX: this.canvas.width! / renderImage.width!,
165
+ // scaleY: this.canvas.height! / renderImage.height!,
166
+ // });
167
+ // if (changeView) {
168
+ // this.canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
169
+ // }
170
+ // return new Promise((resolve) => {
171
+ // this.canvas.setOverlayImage(renderImage, async () => {
172
+ // this.workspaceManager.setClipPath(mockup);
173
+ // // 渲染背景遮罩
174
+ // this.setBackgroundColor(color);
175
+ // await this.setBackgroundMask(mockup.maskImageUrl);
176
+ // this.canvas.renderAll();
177
+ // resolve(null);
178
+ // });
179
+ // });
180
+ // }
181
+ /**
182
+ * 设置背景遮罩
183
+ */
184
+ async setBackgroundMask(e) {
185
+ const s = document.querySelector(".lower-canvas");
186
+ if (s && !e)
187
+ return s.style.backgroundImage = "", Promise.resolve();
188
+ const r = await gt(e);
189
+ if (r == null) return Promise.resolve();
190
+ r.set({
191
+ scaleX: this.canvas.width / r.width,
192
+ scaleY: this.canvas.height / r.height
193
+ });
194
+ const t = r.toDataURL({ format: "png" });
195
+ s && (s.style.backgroundImage = `url(${t})`, s.style.backgroundSize = "100% 100%");
196
+ }
197
+ /**
198
+ * 设置背景颜色、透明图案
199
+ */
200
+ async setBackground(e) {
201
+ e ? await this.workspaceManager.setFillColor(e) : await this.workspaceManager.setTransparentPattern(), this.canvas.requestRenderAll();
202
+ }
203
+ /**
204
+ * 获取当前选中的对象
205
+ */
206
+ get activeObject() {
207
+ return this.canvas.getActiveObject();
208
+ }
209
+ /**
210
+ * 获取对象经过画布转换后的实际尺寸
211
+ */
212
+ getObjectActualSize(e) {
213
+ const { left: s = 0, top: r = 0, width: t = 0, height: i = 0 } = e.getBoundingRect(), a = e.getCenterPoint(), n = this.canvas.viewportTransform;
214
+ return {
215
+ left: s * n[0] + n[4],
216
+ top: r * n[3] + n[5],
217
+ width: t * n[0],
218
+ height: i * n[3],
219
+ centerX: a.x * n[0] + n[4],
220
+ centerY: a.y * n[3] + n[5]
221
+ };
222
+ }
223
+ /**
224
+ * 添加对象
225
+ *
226
+ */
227
+ addObject(e, s = !0) {
228
+ e.set({
229
+ id: ct()
230
+ }), this.canvas.add(e), s && this.canvas.setActiveObject(e);
231
+ }
232
+ /**
233
+ * 恢复对象
234
+ */
235
+ async restoreObject(e) {
236
+ return new Promise((s) => {
237
+ z.util.enlivenObjects([e], (r) => s(r), "");
238
+ });
239
+ }
240
+ /**
241
+ * 半定制文本更新:如果存在 originalWidth / originalHeight,则按固定框重新计算 fitScale;
242
+ * 否则只更新文本内容/字体等基础属性。
243
+ */
244
+ async updateText(e, s) {
245
+ if (!(typeof e?.type == "string" && (e.type.includes("i-text") || e.type === "text"))) return null;
246
+ await this.textProcessor.ensureFontLoaded(s);
247
+ const [t] = await this.restoreObject(e);
248
+ if (!t) return null;
249
+ const i = e.scaleX || 1, a = e.scaleY || 1, n = e?.customConfig, c = typeof n?.originalWidth == "number" && n.originalWidth > 0 && typeof n?.originalHeight == "number" && n.originalHeight > 0 && !n.moveable, o = t.type === "advanced-i-text" && t.radius, m = () => ({
250
+ ...typeof t.__baseWidth < "u" ? { __baseWidth: t.__baseWidth } : {},
251
+ ...typeof t.__baseHeight < "u" ? { __baseHeight: t.__baseHeight } : {},
252
+ ...typeof t.__basePadding < "u" ? { __basePadding: t.__basePadding } : {},
253
+ ...typeof t.__baseObjectCaching < "u" ? { __baseObjectCaching: t.__baseObjectCaching } : {},
254
+ ...typeof t.__curvedCenterX < "u" ? { __curvedCenterX: t.__curvedCenterX } : {},
255
+ ...typeof t.__curvedCenterY < "u" ? { __curvedCenterY: t.__curvedCenterY } : {},
256
+ ...typeof t.__lastCurvedWidth < "u" ? { __lastCurvedWidth: t.__lastCurvedWidth } : {},
257
+ ...typeof t.__lastCurvedHeight < "u" ? { __lastCurvedHeight: t.__lastCurvedHeight } : {},
258
+ ...typeof t.__lastCurvedCenterX < "u" ? { __lastCurvedCenterX: t.__lastCurvedCenterX } : {},
259
+ ...typeof t.__lastCurvedCenterY < "u" ? { __lastCurvedCenterY: t.__lastCurvedCenterY } : {},
260
+ ...typeof t.__rawText < "u" ? { __rawText: t.__rawText } : {},
261
+ ...typeof t.orientation < "u" ? { orientation: t.orientation } : {},
262
+ ...typeof t.radius < "u" ? { radius: t.radius } : {},
263
+ ...typeof t.spacing < "u" ? { spacing: t.spacing } : {}
264
+ });
265
+ if (!c) {
266
+ const C = o ? t.getCenterPoint() : null;
267
+ t.set(s), o && (t.__restoredGeometry = !1);
268
+ try {
269
+ t.initDimensions?.();
270
+ } catch {
271
+ }
272
+ return C && t.setPositionByOrigin(C, "center", "center"), t.setCoords(), {
273
+ ...s,
274
+ text: t.text,
275
+ left: t.left,
276
+ top: t.top,
277
+ width: t.width,
278
+ height: t.height,
279
+ scaleX: t.scaleX,
280
+ scaleY: t.scaleY,
281
+ angle: t.angle,
282
+ originX: t.originX,
283
+ originY: t.originY,
284
+ selectable: e.selectable,
285
+ ...m()
286
+ };
287
+ }
288
+ const d = e?.__semiTargetInfo, P = !!d && typeof d.width == "number" && d.width > 0 && typeof d.height == "number" && d.height > 0 && typeof d.centerX == "number" && typeof d.centerY == "number";
289
+ let u;
290
+ if (P) {
291
+ const C = t.getCenterPoint();
292
+ u = {
293
+ width: n.originalWidth,
294
+ height: n.originalHeight,
295
+ centerX: typeof d.centerX == "number" ? d.centerX : C.x,
296
+ centerY: typeof d.centerY == "number" ? d.centerY : C.y,
297
+ signX: typeof d.signX == "number" && d.signX !== 0 ? Math.sign(d.signX) : Math.sign(i) || 1,
298
+ signY: typeof d.signY == "number" && d.signY !== 0 ? Math.sign(d.signY) : Math.sign(a) || 1
299
+ };
300
+ } else {
301
+ const C = t.getCenterPoint();
302
+ u = {
303
+ width: n.originalWidth,
304
+ height: n.originalHeight,
305
+ centerX: C.x,
306
+ centerY: C.y,
307
+ signX: Math.sign(i) || 1,
308
+ signY: Math.sign(a) || 1
309
+ };
310
+ }
311
+ t.set({
312
+ ...s,
313
+ scaleX: u.signX,
314
+ scaleY: u.signY
315
+ }), o && (t.__restoredGeometry = !1);
316
+ try {
317
+ t.initDimensions?.();
318
+ } catch {
319
+ }
320
+ t.setCoords();
321
+ const X = Math.max(1, t.width || 1), x = Math.max(1, t.height || 1);
322
+ let _ = Math.min(u.width / X, u.height / x);
323
+ return (!Number.isFinite(_) || _ <= 0) && (_ = 1), t.set({
324
+ scaleX: _ * u.signX,
325
+ scaleY: _ * u.signY
326
+ }), t.setPositionByOrigin(new z.Point(u.centerX, u.centerY), "center", "center"), t.setCoords(), {
327
+ ...s,
328
+ text: t.text,
329
+ left: t.left,
330
+ top: t.top,
331
+ width: t.width,
332
+ height: t.height,
333
+ scaleX: t.scaleX,
334
+ scaleY: t.scaleY,
335
+ angle: t.angle,
336
+ originX: t.originX,
337
+ originY: t.originY,
338
+ selectable: e.selectable,
339
+ __semiTargetInfo: u,
340
+ ...m()
341
+ };
342
+ }
343
+ /**
344
+ * 半定制图片替换:使用 cover 模式重新计算缩放,保持原始占位框中心不变。
345
+ */
346
+ async updateImage(e, s) {
347
+ if (e?.type !== "image") return null;
348
+ const r = s.src;
349
+ if (!r) return null;
350
+ const [t] = await this.restoreObject(e);
351
+ if (!t) return null;
352
+ const i = t, a = e.scaleX || 1, n = e.scaleY || 1, c = e.width || 1, o = e.height || 1, m = c * Math.abs(a), d = o * Math.abs(n), P = t.getCenterPoint();
353
+ return new Promise((u) => {
354
+ i.setSrc(r, () => {
355
+ const X = i.width || 1, x = i.height || 1, _ = Math.max(m / X, d / x);
356
+ i.set({
357
+ ...s,
358
+ scaleX: _ * Math.sign(a),
359
+ scaleY: _ * Math.sign(n)
360
+ }), i.setPositionByOrigin(P, "center", "center"), i.setCoords(), u({
361
+ ...s,
362
+ width: X,
363
+ height: x,
364
+ left: i.left,
365
+ top: i.top,
366
+ scaleX: i.scaleX,
367
+ scaleY: i.scaleY,
368
+ angle: i.angle,
369
+ originX: i.originX,
370
+ originY: i.originY,
371
+ selectable: e.selectable
372
+ });
373
+ });
374
+ });
375
+ }
376
+ /**
377
+ * 清理图片 blob URL(只清理不在缓存中的临时 blob)
378
+ * @param obj 对象
379
+ */
380
+ revokeImgBlobLink(e) {
381
+ if (e.type === "image" && e.getSrc) {
382
+ const s = e, r = s.getSrc(), t = s.originSrc || r;
383
+ if (r && r.startsWith("blob:")) {
384
+ const i = this.imageCache.get(t);
385
+ if (!i || i.blobUrl !== r)
386
+ try {
387
+ URL.revokeObjectURL(r);
388
+ } catch {
389
+ }
390
+ }
391
+ }
392
+ }
393
+ /**
394
+ * 修改对象的属性
395
+ * @param {String} id 对象id
396
+ * @param {Record<string, any>} obj 对象属性集合
397
+ */
398
+ updateObject(e, s) {
399
+ const r = this.canvas._objects.find((t) => t.id === e);
400
+ if (r) {
401
+ if (s.hasOwnProperty("angle"))
402
+ r.rotate(s.angle);
403
+ else if (s.hasOwnProperty("align")) {
404
+ const { left: t, right: i, top: a, bottom: n, center: c } = this.workspaceManager.dimension, o = r.getBoundingRect(!0, !0);
405
+ switch (s.align) {
406
+ case "top":
407
+ r.set({
408
+ top: r.top + (a - o.top)
409
+ });
410
+ break;
411
+ case "left":
412
+ r.set({
413
+ left: r.left + (t - o.left)
414
+ });
415
+ break;
416
+ case "horizontal-center":
417
+ r.set({
418
+ left: r.left + (c.x - (o.left + o.width / 2))
419
+ });
420
+ break;
421
+ case "right":
422
+ r.set({
423
+ left: r.left + (i - (o.left + o.width))
424
+ });
425
+ break;
426
+ case "vertical-center":
427
+ r.set({
428
+ top: r.top + (c.y - (o.top + o.height / 2))
429
+ });
430
+ break;
431
+ case "bottom":
432
+ r.set({
433
+ top: r.top + (n - (o.top + o.height))
434
+ });
435
+ break;
436
+ }
437
+ } else if (s.hasOwnProperty("zIndex"))
438
+ this.canvas.moveTo(r, s.zIndex);
439
+ else if (s.hasOwnProperty("scale"))
440
+ this.updateObjectScale(r, s.scale);
441
+ else if (s.hasOwnProperty("width") || s.hasOwnProperty("height")) {
442
+ const t = s.hasOwnProperty("width") ? r.width : r.height, a = (s.width || s.height) / t * this.workspaceManager.scale;
443
+ this.updateObjectScale(r, a);
444
+ } else
445
+ r.set(s);
446
+ r.setCoords(), this.canvas.requestRenderAll(), s.hasOwnProperty("selectable") || this.canvas.fire("object:modified", {
447
+ target: r
448
+ });
449
+ }
450
+ }
451
+ /**
452
+ * 对象缩放
453
+ */
454
+ updateObjectScale(e, s) {
455
+ const r = e.getCenterPoint(), t = this.workspaceManager.dimension.width * 0.01 / e.width;
456
+ e.scale(s < t ? t : s), e.setPositionByOrigin(r, "center", "center");
457
+ }
458
+ /**
459
+ * 修改画布上的对象的选中状态和事件状态
460
+ * @param status
461
+ */
462
+ updateObjectsEvents(e) {
463
+ this.canvas.forEachObject((s) => {
464
+ s.set({
465
+ selectable: e,
466
+ evented: e
467
+ });
468
+ });
469
+ }
470
+ /**
471
+ * 获取当前可选择的对象,不包括背景图、裁剪区域
472
+ */
473
+ getLayerList() {
474
+ return this.canvas._objects.filter((e) => !Ie.includes(e.id || ""));
475
+ }
476
+ /**
477
+ * 设置当前选中的对象
478
+ */
479
+ setActiveObject(e) {
480
+ const s = this.canvas.getActiveObjects(), r = s.some((i) => i.id === e), t = this.getLayerList().find((i) => i.id === e);
481
+ t && (this.canvas.discardActiveObject(), (!r || s.length > 1) && this.canvas.setActiveObject(t), this.canvas.requestRenderAll());
482
+ }
483
+ /**
484
+ * 同时选中多个对象
485
+ */
486
+ setActiveObjects(e) {
487
+ const s = new z.ActiveSelection(e, { canvas: this.canvas });
488
+ this.canvas.setActiveObject(s), this.canvas.requestRenderAll();
489
+ }
490
+ /**
491
+ * 以画布中心点缩放画布
492
+ */
493
+ zoomToCenter(e) {
494
+ if (e === 1)
495
+ this.canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
496
+ else {
497
+ const s = this.canvas.viewportTransform, r = s[0], t = s[4], i = s[5], a = this.canvas.width / 2, n = this.canvas.height / 2, c = e - r, o = t - a * c, m = i - n * c;
498
+ this.canvas.setViewportTransform([e, 0, 0, e, o, m]);
499
+ }
500
+ this.canvas.requestRenderAll();
501
+ }
502
+ /**
503
+ * 获取当前画布上渲染的对象
504
+ */
505
+ getRenderedObjects() {
506
+ const { objects: e } = this.canvas.toJSON(mt.DEFAULT_SAVE_PROPERTIES), s = this.workspaceManager.dimension;
507
+ return {
508
+ objects: e.filter((r) => !Ie.includes(r.id || "")),
509
+ workspaceMetadata: {
510
+ width: s.width,
511
+ height: s.height,
512
+ centerX: s.center.x,
513
+ centerY: s.center.y
514
+ }
515
+ };
516
+ }
517
+ /**
518
+ * 清空当前画布
519
+ */
520
+ clearCanvas() {
521
+ this.canvas._objects.length && (this.canvas.clear(), this.canvas.requestRenderAll());
522
+ }
523
+ /**
524
+ * 将图片对象的 clipPath 重新关联到画布上的对象
525
+ */
526
+ relinkClipPaths() {
527
+ const e = /* @__PURE__ */ new Map(), s = this.canvas.getObjects(), r = (i) => {
528
+ const a = i.id;
529
+ a && e.set(String(a), i), i.type === "group" && i._objects?.forEach(r);
530
+ };
531
+ s.forEach(r);
532
+ const t = (i) => {
533
+ const n = i.clipPath?.id;
534
+ if (n && e.has(String(n))) {
535
+ const c = e.get(String(n));
536
+ c.set({ absolutePositioned: !0 }), i.set("clipPath", c), i.dirty = !0;
537
+ }
538
+ i.type === "group" && i._objects?.forEach(t);
539
+ };
540
+ s.forEach(t);
541
+ }
542
+ /**
543
+ * 切换视图,重新渲染画布
544
+ */
545
+ async switchView(e, s, r) {
546
+ if (this.canvas.clear(), r && r.objects && r.objects.length)
547
+ return await this.textProcessor.preloadFontsFromState(r), new Promise((t) => {
548
+ this.canvas.loadFromJSON(
549
+ r,
550
+ async () => {
551
+ this.relinkClipPaths(), await this.renderOverlayImage(e, !0), await this.setBackground(s), r.workspaceMetadata && this._scaleObjectsToWorkspace(r.workspaceMetadata);
552
+ const i = this.canvas.getObjects().filter((a) => a.type === "image");
553
+ i.length > 0 && await Promise.all(
554
+ i.map((a) => new Promise((n) => {
555
+ const c = a.getElement(), o = a.getSrc() || a.originSrc;
556
+ if (!o) {
557
+ n();
558
+ return;
559
+ }
560
+ c && c.complete && c.naturalWidth > 0 ? (this.registerImageCache(o, a), n()) : c ? (c.onload = () => {
561
+ this.registerImageCache(o, a), n();
562
+ }, c.onerror = () => {
563
+ n();
564
+ }) : n();
565
+ }))
566
+ ), this.canvas.renderAll(), wt.emit("design:layerChange"), t();
567
+ },
568
+ (i, a) => {
569
+ i.clipPath && !r.objects.some((n) => n.id === i.clipPath.id) && (delete a.clipPath, z.util.enlivenObjects(
570
+ [i.clipPath],
571
+ (n) => {
572
+ const c = n[0];
573
+ c && (a.set("clipPath", c), a.dirty = !0, this.canvas.requestRenderAll());
574
+ },
575
+ ""
576
+ ));
577
+ }
578
+ );
579
+ });
580
+ await this.renderOverlayImage(e, !0), await this.setBackground(s), r && r.object && await this.imageProcessor.addBitmapImage(r.object);
581
+ }
582
+ /**
583
+ * 半定制固定文本在修改内容/字体后,按 originalWidth/originalHeight 重新计算自适应缩放。
584
+ * 仅供半定制 Pixi 链路使用,不影响通用编辑器。
585
+ */
586
+ /**
587
+ * 根据 workspace 尺寸变化,按比例缩放所有对象
588
+ */
589
+ _scaleObjectsToWorkspace(e) {
590
+ const s = this.workspaceManager.dimension, r = Math.min(
591
+ s.width / e.width,
592
+ s.height / e.height
593
+ ), t = e.centerX, i = e.centerY, a = s.center.x, n = s.center.y, c = Math.abs(a - t), o = Math.abs(n - i), m = Math.abs(r - 1) >= 1e-3, d = c >= 0.1 || o >= 0.1;
594
+ if (!m && !d) return;
595
+ const P = this.canvas.getObjects(), u = new Set(P), X = /* @__PURE__ */ new Set(), x = (f) => {
596
+ const p = f.clipPath;
597
+ p && u.has(p) && X.add(p);
598
+ };
599
+ P.forEach(x);
600
+ const _ = (f) => {
601
+ const p = (f.left || 0) - t, E = (f.top || 0) - i, k = a + p * r, l = n + E * r;
602
+ f.set({
603
+ left: k,
604
+ top: l,
605
+ scaleX: (f.scaleX || 1) * r,
606
+ scaleY: (f.scaleY || 1) * r
607
+ }), f.setCoords(), f.dirty = !0;
608
+ }, C = /* @__PURE__ */ new Set(), B = (f) => {
609
+ !f.selectable && !X.has(f) || (_(f), C.add(f));
610
+ };
611
+ P.forEach(B);
612
+ const T = (f) => {
613
+ const p = f.clipPath;
614
+ p && p.absolutePositioned && !u.has(p) && !C.has(p) && (_(p), C.add(p));
615
+ };
616
+ P.forEach(T);
617
+ }
618
+ /**
619
+ * 计算对象相对于画布的全局变换矩阵(包括父组的影响)
620
+ */
621
+ getGlobalTransformMatrix(e) {
622
+ return e.calcTransformMatrix();
623
+ }
624
+ /**
625
+ * 判断对象是否位于 activeSelection 中
626
+ */
627
+ isInActiveSelection(e) {
628
+ let s = e.group;
629
+ for (; s; ) {
630
+ if (s.type === "activeSelection") return !0;
631
+ s = s.group;
632
+ }
633
+ return !1;
634
+ }
635
+ /**
636
+ * 注册图片到缓存(会话级缓存,整个编辑期间保持)
637
+ * @param src 图片源地址(originSrc)
638
+ * @param img fabric.Image 对象
639
+ * @param blobUrl 可选的 blob URL(用于撤销/重做)
640
+ */
641
+ registerImageCache(e, s, r) {
642
+ if (!e || e.startsWith("data:")) return;
643
+ const t = s.getElement(), i = this.imageCache.get(e);
644
+ this.imageCache.set(e, {
645
+ element: t,
646
+ blobUrl: r || i?.blobUrl,
647
+ lastUsed: Date.now()
648
+ });
649
+ }
650
+ /**
651
+ * 清除整个图片缓存(在关闭编辑器时调用)
652
+ */
653
+ clearImageCache() {
654
+ this.imageCache.forEach((e) => {
655
+ if (e.blobUrl)
656
+ try {
657
+ URL.revokeObjectURL(e.blobUrl);
658
+ } catch {
659
+ }
660
+ }), this.imageCache.clear();
661
+ }
662
+ /**
663
+ * 销毁编辑器,释放所有资源
664
+ */
665
+ destroy() {
666
+ if (this.destroyed) return;
667
+ this.destroyed = !0, this.resizeManager.destroy(), this.clearImageCache();
668
+ const e = this.canvas;
669
+ e.contextContainer && e.contextTop && (e.cancelRequestedRender?.(), e.dispose());
670
+ }
671
+ /**
672
+ * 按需生成图片 dataURL(不缓存,减少内存占用)
673
+ */
674
+ async getCachedDataURL(e) {
675
+ if (!e)
676
+ return "";
677
+ const s = this.imageCache.get(e);
678
+ if (s?.element && s.element.complete) {
679
+ const r = document.createElement("canvas");
680
+ r.width = s.element.naturalWidth || s.element.width, r.height = s.element.naturalHeight || s.element.height;
681
+ const t = r.getContext("2d");
682
+ if (t) {
683
+ t.drawImage(s.element, 0, 0);
684
+ const i = r.toDataURL("image/png");
685
+ return r.width = 0, r.height = 0, i;
686
+ }
687
+ return "";
688
+ }
689
+ return await ot(e);
690
+ }
691
+ /**
692
+ * 从缓存克隆图片,避免重复下载
693
+ */
694
+ async cloneImageFromCache(e, s) {
695
+ const r = e.getSrc() || "", t = e.originSrc || "", i = e.isCropped, a = t || r;
696
+ if (a.startsWith("data:"))
697
+ return new Promise((c) => {
698
+ e.clone(
699
+ (o) => {
700
+ o.set(s), c(o);
701
+ },
702
+ ["absolutePositioned"]
703
+ );
704
+ });
705
+ const n = this.imageCache.get(a);
706
+ return n?.element && n.element.complete ? new Promise(async (c) => {
707
+ const o = new z.Image(n.element, {
708
+ width: e.width,
709
+ height: e.height,
710
+ ...s
711
+ });
712
+ if (e.clipPath)
713
+ try {
714
+ const m = await K(e.clipPath, ["absolutePositioned"]);
715
+ o.set({ clipPath: m });
716
+ } catch {
717
+ }
718
+ i && (o.isCropped = !0, o.cropBlob = e.cropBlob), c(o);
719
+ }) : new Promise((c) => {
720
+ e.clone(
721
+ (o) => {
722
+ this.registerImageCache(a, o), o.set(s), i && (o.isCropped = !0, o.cropBlob = e.cropBlob), c(o);
723
+ },
724
+ ["absolutePositioned"]
725
+ );
726
+ });
727
+ }
728
+ /**
729
+ * Rasterize the current printable area for a live product preview without
730
+ * cloning every Fabric object into a second canvas.
731
+ *
732
+ * This mirrors the full designer's fast preview path: hide the mockup
733
+ * overlay and selection controls, capture the existing lower canvas, and
734
+ * scale only the printable workspace to the requested longest edge.
735
+ */
736
+ async exportPreviewBitmap(e = 600, s) {
737
+ if (this.destroyed) throw new Error("Canvas is not ready");
738
+ const r = this.workspaceManager.dimension, t = this.workspaceManager.printAreaSize?.width ?? r.width, i = this.workspaceManager.printAreaSize?.height ?? r.height;
739
+ if (!r.width || !r.height || !t || !i)
740
+ throw new Error("Printable workspace has no dimensions");
741
+ const a = Math.max(t, i), n = Math.max(1, e) / a, c = Math.max(1, Math.round(t * n)), o = Math.max(1, Math.round(i * n)), m = this.canvas.viewportTransform?.slice(), d = this.canvas.overlayImage?.visible, P = this.canvas.backgroundColor, u = this.canvas.getActiveObject(), X = u ? { hasBorders: u.hasBorders, hasControls: u.hasControls } : null;
742
+ try {
743
+ this.canvas.overlayImage && (this.canvas.overlayImage.visible = !1), u?.set({ hasBorders: !1, hasControls: !1 }), this.canvas.backgroundColor = s || "transparent", this.canvas.viewportTransform = [1, 0, 0, 1, 0, 0], this.canvas.renderAll();
744
+ const x = document.createElement("canvas");
745
+ x.width = c, x.height = o;
746
+ const _ = x.getContext("2d", { alpha: !0 });
747
+ if (!_) throw new Error("Could not create preview canvas context");
748
+ const C = this.canvas, B = C.getRetinaScaling?.() ?? window.devicePixelRatio ?? 1;
749
+ _.drawImage(
750
+ C.lowerCanvasEl,
751
+ r.left * B,
752
+ r.top * B,
753
+ r.width * B,
754
+ r.height * B,
755
+ 0,
756
+ 0,
757
+ c,
758
+ o
759
+ );
760
+ try {
761
+ return await createImageBitmap(x);
762
+ } finally {
763
+ x.width = 0, x.height = 0;
764
+ }
765
+ } finally {
766
+ this.canvas.backgroundColor = P, this.canvas.overlayImage && d !== void 0 && (this.canvas.overlayImage.visible = d), u && X && u.set(X), m && (this.canvas.viewportTransform = m), this.destroyed || this.canvas.requestRenderAll();
767
+ }
768
+ }
769
+ /**
770
+ * 导出 clipPath 区域的 SVG(按 overlay 原始尺寸)
771
+ * @param {boolean} embedImages 是否将图片转为 dataURL 内嵌
772
+ * @param {String?} color 背景颜色
773
+ * @returns {Promise<string[]>} SVG 字符串
774
+ */
775
+ async export(e = !1, s, r) {
776
+ const t = this.workspaceManager.dimension, i = this.workspaceManager.printAreaSize?.width ?? t.width, a = this.workspaceManager.printAreaSize?.height ?? t.height, n = window.devicePixelRatio || 1, c = Math.max(i / t.width, a / t.height), o = r?.objectCloneMultiplierCap ?? 8, m = Math.max(1, Math.min(r?.minObjectCloneMultiplier ?? 2, o)), d = Math.max(m, Math.min(o, Math.ceil(c * n)));
777
+ let P = new z.Rect({
778
+ left: 0,
779
+ top: 0,
780
+ width: t.width,
781
+ height: t.height,
782
+ absolutePositioned: !0,
783
+ strokeWidth: 0
784
+ });
785
+ this.canvas.clipPath && (P = await K(this.canvas.clipPath, ["absolutePositioned"]), P.set({
786
+ left: this.canvas.clipPath.left - t.left,
787
+ top: this.canvas.clipPath.top - t.top,
788
+ absolutePositioned: !0
789
+ }));
790
+ const u = new z.StaticCanvas(null, {
791
+ width: t.width,
792
+ height: t.height,
793
+ enableRetinaScaling: !1,
794
+ backgroundColor: s || "transparent",
795
+ preserveObjectStacking: !0,
796
+ clipPath: P
797
+ }), X = this.getLayerList();
798
+ (await Promise.all(
799
+ X.map(
800
+ (l) => new Promise((O) => {
801
+ try {
802
+ const I = l.sourceType === "svg";
803
+ if (l.type === "image") {
804
+ const M = l;
805
+ let g = {
806
+ selectable: !1,
807
+ evented: !1,
808
+ flipX: l.flipX || !1,
809
+ flipY: l.flipY || !1
810
+ };
811
+ if (this.isInActiveSelection(l)) {
812
+ const R = this.getGlobalTransformMatrix(l), v = z.util.qrDecompose(R);
813
+ g = {
814
+ ...g,
815
+ left: (v.translateX || 0) - (t.left || 0),
816
+ top: (v.translateY || 0) - (t.top || 0),
817
+ angle: v.angle || 0,
818
+ scaleX: v.scaleX || 1,
819
+ scaleY: v.scaleY || 1,
820
+ originX: "center",
821
+ originY: "center"
822
+ };
823
+ } else
824
+ g = {
825
+ ...g,
826
+ left: l.left - t.left,
827
+ top: l.top - t.top,
828
+ angle: l.angle || 0,
829
+ scaleX: l.scaleX || 1,
830
+ scaleY: l.scaleY || 1,
831
+ originX: "left",
832
+ originY: "top"
833
+ };
834
+ this.cloneImageFromCache(M, g).then(async (R) => {
835
+ if (R.clipPath) {
836
+ const v = R.clipPath;
837
+ v.absolutePositioned && v.set({
838
+ left: (v.left || 0) - t.left,
839
+ top: (v.top || 0) - t.top
840
+ });
841
+ }
842
+ if (e && R.type === "image")
843
+ try {
844
+ const v = R, V = v.getSrc() || v.originSrc || "";
845
+ if (V) {
846
+ const L = await this.getCachedDataURL(V);
847
+ v.setSrc(L, () => O(R));
848
+ return;
849
+ }
850
+ } catch {
851
+ }
852
+ O(R);
853
+ }).catch(() => {
854
+ O(l);
855
+ });
856
+ } else I ? K(l, ["absolutePositioned"]).then((M) => {
857
+ if (this.isInActiveSelection(l)) {
858
+ const R = this.getGlobalTransformMatrix(l), v = z.util.qrDecompose(R);
859
+ M.set({
860
+ left: (v.translateX || 0) - (t.left || 0),
861
+ top: (v.translateY || 0) - (t.top || 0),
862
+ angle: v.angle || 0,
863
+ scaleX: v.scaleX || 1,
864
+ scaleY: v.scaleY || 1,
865
+ flipX: l.flipX || !1,
866
+ flipY: l.flipY || !1,
867
+ selectable: !1,
868
+ evented: !1,
869
+ originX: "center",
870
+ originY: "center"
871
+ });
872
+ } else
873
+ M.set({
874
+ left: (l.left || 0) - t.left,
875
+ top: (l.top || 0) - t.top,
876
+ angle: l.angle || 0,
877
+ scaleX: l.scaleX || 1,
878
+ scaleY: l.scaleY || 1,
879
+ flipX: l.flipX || !1,
880
+ flipY: l.flipY || !1,
881
+ selectable: !1,
882
+ evented: !1,
883
+ originX: l.originX || "left",
884
+ originY: l.originY || "top"
885
+ });
886
+ const g = M.clipPath;
887
+ g && g.absolutePositioned && g.set({
888
+ left: (g.left || 0) - t.left,
889
+ top: (g.top || 0) - t.top
890
+ }), M.setCoords(), M.dirty = !0, O(M);
891
+ }).catch(() => O(l)) : l.cloneAsImage(
892
+ (M) => {
893
+ if (this.isInActiveSelection(l)) {
894
+ const g = this.getGlobalTransformMatrix(l), R = z.util.qrDecompose(g);
895
+ M.set({
896
+ left: (R.translateX || 0) - (t.left || 0),
897
+ top: (R.translateY || 0) - (t.top || 0),
898
+ angle: R.angle || 0,
899
+ scaleX: (R.scaleX || 1) / d,
900
+ scaleY: (R.scaleY || 1) / d,
901
+ selectable: !1,
902
+ hasControls: !1,
903
+ hasBorders: !1,
904
+ originX: "center",
905
+ originY: "center"
906
+ });
907
+ } else {
908
+ const g = l.getBoundingRect(!0, !0);
909
+ M.set({
910
+ left: g.left - t.left,
911
+ top: g.top - t.top,
912
+ scaleX: 1 / d,
913
+ scaleY: 1 / d,
914
+ angle: 0,
915
+ selectable: !1,
916
+ hasControls: !1,
917
+ hasBorders: !1,
918
+ originX: "left",
919
+ originY: "top"
920
+ });
921
+ }
922
+ O(M);
923
+ },
924
+ { multiplier: d }
925
+ );
926
+ } catch {
927
+ O(l);
928
+ }
929
+ })
930
+ )
931
+ )).forEach((l) => u.add(l));
932
+ const _ = i / t.width, C = a / t.height;
933
+ u.setViewportTransform([_, 0, 0, C, 0, 0]), u.renderAll();
934
+ const B = r?.minOutputSize ?? 1024;
935
+ let T = 1;
936
+ (i > B || a > B) && (T = Math.max(1, B / Math.max(i, a))), typeof r?.outputMultiplierCap == "number" && (T = Math.min(T, r.outputMultiplierCap));
937
+ let f = "";
938
+ const p = () => u.toDataURL({
939
+ format: "webp",
940
+ quality: r?.quality ?? 0.5,
941
+ width: i,
942
+ height: a,
943
+ multiplier: T
944
+ }), E = r?.preferImageBitmap ?? !0, k = r?.returnBlobUrl ?? !1;
945
+ if (E && window.createImageBitmap && typeof u.toCanvasElement == "function") {
946
+ const l = u.toCanvasElement(T, { width: i, height: a });
947
+ try {
948
+ f = await createImageBitmap(l);
949
+ } finally {
950
+ l.width = 0, l.height = 0;
951
+ }
952
+ } else if (k && typeof u.toCanvasElement == "function") {
953
+ const l = u.toCanvasElement(T, { width: i, height: a }), O = await new Promise((I) => l.toBlob(I, "image/webp", r?.quality ?? 0.5));
954
+ l.width = 0, l.height = 0, f = O ? URL.createObjectURL(O) : p();
955
+ } else
956
+ f = p();
957
+ return u.dispose(), f;
958
+ }
959
+ }
960
+ class yt {
961
+ constructor(e, s) {
962
+ this.onBusy = e, this.onIdle = s, this.pending = null, this.running = !1;
963
+ }
964
+ get active() {
965
+ return this.running;
966
+ }
967
+ enqueue(e) {
968
+ this.pending = e, this.running || this.drain();
969
+ }
970
+ clear() {
971
+ this.pending = null;
972
+ }
973
+ async drain() {
974
+ this.running = !0, this.onBusy();
975
+ try {
976
+ for (; this.pending; ) {
977
+ const e = this.pending;
978
+ this.pending = null, await e();
979
+ }
980
+ } finally {
981
+ this.running = !1, this.onIdle(), this.pending && this.drain();
982
+ }
983
+ }
984
+ }
985
+ class bt {
986
+ constructor(e = 32 * 1024 * 1024, s = 4, r) {
987
+ this.budget = e, this.concurrency = s, this.onEvict = r, this.entries = /* @__PURE__ */ new Map(), this.bytes = 0, this.active = 0, this.waiting = [], this.pinned = /* @__PURE__ */ new Set();
988
+ }
989
+ setPinnedSources(e) {
990
+ this.pinned = new Set(e), this.waiting.forEach((s) => {
991
+ s.foreground = this.pinned.has(s.source);
992
+ }), this.waiting.sort((s, r) => Number(r.foreground) - Number(s.foreground)), this.trim();
993
+ }
994
+ trim() {
995
+ for (const [e, s] of this.entries) {
996
+ if (this.bytes <= this.budget) break;
997
+ !s.bytes || this.pinned.has(e) || (this.entries.delete(e), this.bytes -= s.bytes, this.onEvict?.(e));
998
+ }
999
+ }
1000
+ clear() {
1001
+ for (const e of this.waiting.splice(0)) e.cancel();
1002
+ for (const e of this.entries.keys()) this.onEvict?.(e);
1003
+ this.entries.clear(), this.pinned.clear(), this.bytes = 0;
1004
+ }
1005
+ promote(e) {
1006
+ const s = this.waiting.findIndex((i) => i.source === e && !i.foreground);
1007
+ if (s < 0) return;
1008
+ const [r] = this.waiting.splice(s, 1);
1009
+ r.foreground = !0;
1010
+ const t = this.waiting.findIndex((i) => !i.foreground);
1011
+ this.waiting.splice(t < 0 ? this.waiting.length : t, 0, r);
1012
+ }
1013
+ async fetchBlob(e, s) {
1014
+ await new Promise((r, t) => {
1015
+ const i = () => {
1016
+ this.active += 1, r();
1017
+ };
1018
+ this.active < this.concurrency ? i() : (this.waiting.push({ source: e, foreground: !1, start: i, cancel: () => t(new Error("Resource cache was released")) }), s && this.promote(e));
1019
+ });
1020
+ try {
1021
+ const r = await fetch(e);
1022
+ if (!r.ok) throw new Error(`Could not load render asset (${r.status})`);
1023
+ return await r.blob();
1024
+ } finally {
1025
+ this.active -= 1, this.waiting.shift()?.start();
1026
+ }
1027
+ }
1028
+ load(e, s = !0) {
1029
+ const r = this.entries.get(e);
1030
+ if (r)
1031
+ return this.entries.delete(e), this.entries.set(e, r), s && this.promote(e), r.ready;
1032
+ const t = { ready: this.fetchBlob(e, s), bytes: 0 };
1033
+ return this.entries.set(e, t), t.ready.then((i) => {
1034
+ this.entries.get(e) === t && (t.bytes = i.size, this.bytes += t.bytes, this.trim());
1035
+ }).catch(() => {
1036
+ this.entries.get(e) === t && this.entries.delete(e);
1037
+ }), t.ready;
1038
+ }
1039
+ }
1040
+ class qe {
1041
+ constructor() {
1042
+ this.urls = /* @__PURE__ */ new Map(), this.disposed = !1, this.current = /* @__PURE__ */ new Set(), this.holds = /* @__PURE__ */ new Map(), this.cache = new bt(32 * 1024 * 1024, 4, (e) => {
1043
+ const s = this.urls.get(e);
1044
+ s && URL.revokeObjectURL(s), this.urls.delete(e);
1045
+ });
1046
+ }
1047
+ key(e) {
1048
+ return new URL(e, document.baseURI).href;
1049
+ }
1050
+ sources(e) {
1051
+ return e.filter((s) => s && !s.startsWith("data:") && !s.startsWith("blob:")).map((s) => this.key(s));
1052
+ }
1053
+ updatePins() {
1054
+ this.cache.setPinnedSources([...this.current, ...this.holds.keys()]);
1055
+ }
1056
+ pin(e) {
1057
+ this.current = new Set(this.sources(e)), this.updatePins();
1058
+ }
1059
+ hold(e) {
1060
+ const s = new Set(this.sources(e));
1061
+ return s.forEach((r) => this.holds.set(r, (this.holds.get(r) ?? 0) + 1)), this.updatePins(), () => {
1062
+ s.forEach((r) => {
1063
+ const t = (this.holds.get(r) ?? 1) - 1;
1064
+ t ? this.holds.set(r, t) : this.holds.delete(r);
1065
+ }), this.updatePins();
1066
+ };
1067
+ }
1068
+ async preload(e, s = !1) {
1069
+ await Promise.all([...new Set(this.sources(e))].map((r) => this.cache.load(r, s)));
1070
+ }
1071
+ async url(e) {
1072
+ if (!e || e.startsWith("data:") || e.startsWith("blob:")) return e;
1073
+ const s = this.key(e), r = await this.cache.load(s, !0);
1074
+ if (this.disposed) throw new Error("Resource session was released");
1075
+ let t = this.urls.get(s);
1076
+ return t || (t = URL.createObjectURL(r), this.urls.set(s, t)), t;
1077
+ }
1078
+ async acquire(e) {
1079
+ const s = this.hold(e);
1080
+ try {
1081
+ return { urls: Object.fromEntries(await Promise.all([...new Set(e.filter(Boolean))].map(async (t) => [t, await this.url(t)]))), release: s };
1082
+ } catch (r) {
1083
+ throw s(), r;
1084
+ }
1085
+ }
1086
+ dispose() {
1087
+ this.disposed = !0, this.cache.clear();
1088
+ }
1089
+ }
1090
+ function Ce(h) {
1091
+ const e = /* @__PURE__ */ new Set(), s = (r) => {
1092
+ if (!r || typeof r != "object") return;
1093
+ if (Array.isArray(r)) {
1094
+ r.forEach(s);
1095
+ return;
1096
+ }
1097
+ const t = r;
1098
+ typeof t.src == "string" && t.src && e.add(t.src), typeof t.sourcePath == "string" && /^(https?:|\/)/.test(t.sourcePath) && e.add(t.sourcePath), Object.values(t).forEach(s);
1099
+ };
1100
+ return s(h), [...e];
1101
+ }
1102
+ async function ze(h, e) {
1103
+ const s = JSON.parse(JSON.stringify(h)), r = new Map(await Promise.all(Ce(s).map(async (i) => [i, await e.url(i)]))), t = (i) => {
1104
+ if (!i || typeof i != "object") return;
1105
+ if (Array.isArray(i)) {
1106
+ i.forEach(t);
1107
+ return;
1108
+ }
1109
+ const a = i;
1110
+ typeof a.src == "string" && (a.src = r.get(a.src) ?? a.src, a.originSrc && (a.originSrc = a.src)), typeof a.sourcePath == "string" && (a.sourcePath = r.get(a.sourcePath) ?? a.sourcePath), Object.values(a).forEach(t);
1111
+ };
1112
+ return t(s), s;
1113
+ }
1114
+ function Pt(h, e, s) {
1115
+ const r = JSON.parse(JSON.stringify(h)), t = new Map(Object.entries(e.urls).map(([n, c]) => [c, n])), i = /* @__PURE__ */ new Map(), a = (n, c) => {
1116
+ if (!n || typeof n != "object") return;
1117
+ if (Array.isArray(n)) {
1118
+ n.forEach((m) => a(m, c));
1119
+ return;
1120
+ }
1121
+ const o = n;
1122
+ c(o), Object.values(o).forEach((m) => a(m, c));
1123
+ };
1124
+ return a(s, (n) => {
1125
+ n.id !== void 0 && i.set(String(n.id), n);
1126
+ }), a(r, (n) => {
1127
+ const c = n.id !== void 0 ? i.get(String(n.id)) : void 0;
1128
+ for (const o of ["src", "originSrc", "sourcePath"])
1129
+ typeof n[o] == "string" && (c && typeof c[o] == "string" ? n[o] = c[o] : n[o] = t.get(n[o]) ?? n[o]);
1130
+ }), r;
1131
+ }
1132
+ function de(h) {
1133
+ typeof h != "string" ? h.close() : h.startsWith("blob:") && URL.revokeObjectURL(h);
1134
+ }
1135
+ function Ct(h) {
1136
+ return typeof h == "string" ? h.length * 2 : h.width * h.height * 4;
1137
+ }
1138
+ class St {
1139
+ constructor(e = 12, s = 32 * 1024 * 1024) {
1140
+ this.maxEntries = e, this.maxBytes = s, this.entries = /* @__PURE__ */ new Map(), this.pinned = /* @__PURE__ */ new Set(), this.bytes = 0;
1141
+ }
1142
+ get size() {
1143
+ return this.entries.size;
1144
+ }
1145
+ get estimatedBytes() {
1146
+ return this.bytes;
1147
+ }
1148
+ /** Keep every texture used by the current composition alive until it settles. */
1149
+ pin(e) {
1150
+ this.pinned.add(e);
1151
+ }
1152
+ get(e) {
1153
+ const s = this.entries.get(e);
1154
+ if (s)
1155
+ return this.entries.delete(e), this.entries.set(e, s), s.texture;
1156
+ }
1157
+ set(e, s) {
1158
+ const r = this.entries.get(e);
1159
+ r && (this.bytes -= r.bytes, r.texture !== s && de(r.texture), this.entries.delete(e));
1160
+ const t = e.length * 2 + Ct(s);
1161
+ this.entries.set(e, { texture: s, bytes: t }), this.bytes += t, this.trim();
1162
+ }
1163
+ releaseFrame() {
1164
+ this.pinned.clear(), this.trim();
1165
+ }
1166
+ clear() {
1167
+ this.entries.forEach(({ texture: e }) => de(e)), this.entries.clear(), this.pinned.clear(), this.bytes = 0;
1168
+ }
1169
+ trim() {
1170
+ for (const [e, s] of this.entries) {
1171
+ if (this.entries.size <= this.maxEntries && this.bytes <= this.maxBytes) break;
1172
+ this.pinned.has(e) || (this.entries.delete(e), this.bytes -= s.bytes, de(s.texture));
1173
+ }
1174
+ }
1175
+ }
1176
+ function se(h) {
1177
+ return h.designKey || h.area?.name || h.name;
1178
+ }
1179
+ function be(h, e, s) {
1180
+ const r = e[se(h)]?.color;
1181
+ return s ?? (typeof r == "string" ? r : void 0);
1182
+ }
1183
+ function He(h, e, s) {
1184
+ return s ?? h.render_areas.filter((r) => r.design).map((r) => e[se(r)]?.color).find((r) => typeof r == "string");
1185
+ }
1186
+ function Pe(h, e, s, r = !0, t = "global") {
1187
+ if (!r) return h.render_areas;
1188
+ const i = t === "global" ? He(h, e, s) : void 0;
1189
+ return h.render_areas.filter((a) => {
1190
+ const n = e[se(a)], c = t === "placement" ? be(a, e, s) : i;
1191
+ return at({ design: a.design, defaultPrintColor: ye(a.defaultPrintColor, a.area?.defaultPrintColor, h.defaultPrintColor) }, c, !!(a.area && Array.isArray(n?.objects) && n.objects.length));
1192
+ });
1193
+ }
1194
+ function Te(h, e, s, r = !0, t = "global") {
1195
+ return Pe(h, e, s, r, t).flatMap((i) => {
1196
+ const a = e[se(i)];
1197
+ return [i.image, ...i.design && i.area && Array.isArray(a?.objects) && a.objects.length ? [i.area.image, ...Ce(a)] : []];
1198
+ }).filter(Boolean);
1199
+ }
1200
+ function Rt(h) {
1201
+ return h.render_areas.find((e) => e.name === "bg")?.image || h.image || "";
1202
+ }
1203
+ function _t(h, e) {
1204
+ const s = h.render_areas.find((t) => t.name === "bg") ?? h.render_areas.find((t) => !t.design), r = Math.max(s?.width ?? 0, s?.height ?? 0);
1205
+ return Math.max(1, Math.min(768, Math.round(r ? r * e : 600)));
1206
+ }
1207
+ const Ft = et(
1208
+ function({
1209
+ render: e,
1210
+ designData: s,
1211
+ enabled: r = !0,
1212
+ preloadSources: t,
1213
+ preloadDesignData: i,
1214
+ onAssetReady: a,
1215
+ backgroundColor: n,
1216
+ colorMode: c = "global",
1217
+ scale: o = 0.8,
1218
+ reusePlacementTextures: m = !0,
1219
+ textureCacheScope: d,
1220
+ renderer: P = "pixel-map",
1221
+ className: u,
1222
+ style: X,
1223
+ alt: x = "Product preview",
1224
+ onLoadingChange: _,
1225
+ onRendered: C,
1226
+ onError: B
1227
+ }, T) {
1228
+ const f = b(null), p = b(null), E = b(null), k = b(null), l = b(null), O = b(void 0), I = b(null), M = b(null), g = b(0), R = b(null);
1229
+ R.current ??= new St();
1230
+ const v = b(d), V = b(0), L = b(null), J = b(0), Q = b(!1), A = b(!1), y = b({ onLoadingChange: _, onRendered: C, onError: B, onAssetReady: a });
1231
+ y.current = { onLoadingChange: _, onRendered: C, onError: B, onAssetReady: a };
1232
+ const Y = P === "pixel-map" && Ue.isSupported(), Se = b(Y);
1233
+ Se.current = Y;
1234
+ const [Re, Fe] = j(""), [_e, De] = j(!1), [Ne, Ge] = j(""), [Ve, fe] = j(!1), ge = st(it(e).render_areas), Z = G(() => (l.current ??= new qe(), l.current), []), ee = G((w) => {
1235
+ De(w), y.current.onLoadingChange?.(w);
1236
+ }, []), ie = G(() => {
1237
+ if (E.current) return E.current;
1238
+ if (!f.current || !p.current) return null;
1239
+ const w = 800;
1240
+ return f.current.width = w, f.current.height = w, E.current = new We(
1241
+ f.current,
1242
+ { width: w, height: w },
1243
+ p.current,
1244
+ 0.85
1245
+ ), E.current;
1246
+ }, []), ke = G(async () => {
1247
+ if (k.current) return k.current;
1248
+ if (Y) k.current = new Ue();
1249
+ else {
1250
+ const { StickerPlugin: w } = await import("./renderer/sticker.js");
1251
+ if (A.current || Se.current !== Y) return null;
1252
+ if (k.current) return k.current;
1253
+ k.current = new w({ width: 1, height: 1 }, !0, { subdiv: 8 });
1254
+ }
1255
+ return k.current;
1256
+ }, [Y]), ne = G(() => {
1257
+ E.current?.destroy(), E.current = null, k.current?.destroy(), k.current = null, l.current?.dispose(), l.current = null, O.current = void 0, R.current.clear(), M.current && URL.revokeObjectURL(M.current), M.current = null, I.current = null;
1258
+ }, []), Me = G(() => (L.current || (L.current = new yt(
1259
+ () => ee(!0),
1260
+ () => {
1261
+ A.current ? ne() : ee(!1);
1262
+ }
1263
+ )), L.current), [ne, ee]), te = G(() => {
1264
+ const w = ++g.current, F = J.current;
1265
+ Me().enqueue(async () => {
1266
+ let D;
1267
+ const W = R.current;
1268
+ try {
1269
+ if (A.current || w !== g.current) return;
1270
+ (!m || v.current !== d || V.current !== F) && (W.clear(), v.current = d, V.current = F), fe(!1);
1271
+ const q = ie();
1272
+ Q.current && (k.current?.destroy(), k.current = null, Q.current = !1);
1273
+ const N = await ke();
1274
+ if (!q || !N || A.current || w !== g.current) return;
1275
+ const ae = Z();
1276
+ D = ae.hold(Te(e, s, n, Y, c));
1277
+ const Oe = Pe(e, s, n, Y, c), Ye = c === "global" ? He(e, s, n) : n, Ke = e.render_areas.filter((S) => !!S.design), ce = _t(e, o), pe = /* @__PURE__ */ new Map(), Xe = Promise.all(Oe.map(async (S) => [S.image, await ae.url(S.image)]));
1278
+ Xe.catch(() => {
1279
+ });
1280
+ for (const S of Ke) {
1281
+ const le = se(S), U = s[le], $ = c === "placement" ? be(S, s, n) ?? "" : typeof U?.color == "string" ? U.color : "", we = ye(S.defaultPrintColor, S.area?.defaultPrintColor, e.defaultPrintColor), Be = we ? "" : $, Ze = !we && c === "placement" && !Y && n === void 0 && !!$;
1282
+ if (!S.area || (!Array.isArray(U?.objects) || !U.objects.length) && !Ze)
1283
+ continue;
1284
+ const he = JSON.stringify({
1285
+ designKey: le,
1286
+ refreshGeneration: F,
1287
+ targetSize: ce,
1288
+ placement: S.area,
1289
+ document: U,
1290
+ colorMode: c,
1291
+ color: $,
1292
+ printMaterial: we
1293
+ });
1294
+ W.pin(he);
1295
+ const Ee = W.get(he);
1296
+ if (Ee) {
1297
+ pe.set(S, Ee);
1298
+ continue;
1299
+ }
1300
+ const ve = JSON.parse(he), [$e, je] = await Promise.all([
1301
+ ae.url(ve.placement.image),
1302
+ ze(ve.document, ae)
1303
+ ]);
1304
+ if (A.current || w !== g.current || (await q.switchView({ ...ve.placement, image: $e }, $, je), A.current || w !== g.current)) return;
1305
+ const ue = typeof createImageBitmap == "function" ? await q.exportPreviewBitmap(ce, Be) : await q.export(!1, Be, {
1306
+ minOutputSize: ce,
1307
+ preferImageBitmap: !1,
1308
+ returnBlobUrl: !1,
1309
+ outputMultiplierCap: 1,
1310
+ quality: 0.72
1311
+ });
1312
+ if (ue) {
1313
+ if (A.current || w !== g.current) {
1314
+ de(ue);
1315
+ return;
1316
+ }
1317
+ W.set(he, ue), pe.set(S, ue);
1318
+ }
1319
+ if (A.current || w !== g.current) return;
1320
+ }
1321
+ const Qe = new Map(await Xe);
1322
+ if (A.current || w !== g.current) return;
1323
+ const Ae = Oe.map((S) => {
1324
+ const le = S.design ? pe.get(S) : void 0, U = S.texture_transform, $ = typeof U?.blendMode == "number" ? U.blendMode : typeof U?.blendMode == "string" ? rt[U.blendMode.toLowerCase()] : void 0;
1325
+ return {
1326
+ ...S,
1327
+ defaultPrintColor: ye(S.defaultPrintColor, S.area?.defaultPrintColor, e.defaultPrintColor),
1328
+ image: Qe.get(S.image) ?? S.image,
1329
+ texture: le,
1330
+ color: c === "placement" && S.design ? be(S, s) : void 0,
1331
+ // PixelMapRenderer consumes the source blend-mode string; Pixi
1332
+ // still receives its enum value exactly as before.
1333
+ config: U ? Y ? { ...U } : { ...U, blendMode: $ } : void 0
1334
+ };
1335
+ }), oe = Y ? await N.onOffscreenRender(Ae, {
1336
+ color: Ye,
1337
+ targetSize: ce,
1338
+ quality: 0.85,
1339
+ format: "image/png",
1340
+ cacheKey: e.id
1341
+ }) : await (await import("./pixi-print-base-DIvtSF7v.js")).renderPixiWithPrintBase(N, Ae, {
1342
+ color: Ye,
1343
+ cleanCache: !1,
1344
+ scale: o,
1345
+ quality: 0.85
1346
+ });
1347
+ if (A.current || w !== g.current) return;
1348
+ if (!oe) throw new Error("Could not render the product preview");
1349
+ const me = URL.createObjectURL(oe);
1350
+ M.current && URL.revokeObjectURL(M.current), I.current = oe, M.current = me, Fe(me), y.current.onRendered?.({ renderId: e.id, blob: oe, url: me });
1351
+ } catch (q) {
1352
+ !A.current && w === g.current && (fe(!0), y.current.onError?.(q instanceof Error ? q : new Error("Could not render the product preview")));
1353
+ } finally {
1354
+ D?.(), W.releaseFrame(), m || W.clear();
1355
+ }
1356
+ });
1357
+ }, [n, c, s, ie, Me, ke, Z, e, o, Y, m, d]);
1358
+ re(() => (A.current = !1, () => {
1359
+ A.current = !0, g.current += 1, L.current?.clear(), L.current?.active || ne();
1360
+ }), [ne]), re(() => {
1361
+ k.current?.destroy(), k.current = null;
1362
+ }, [P, Y]), re(() => {
1363
+ const w = Z(), F = i ?? s, D = Te(e, F, n, Y, c);
1364
+ w.pin(D);
1365
+ let W = !0;
1366
+ return w.preload(D, !0).then(async () => {
1367
+ if (W)
1368
+ for (const q of Pe(e, F, n, Y, c).map((N) => N.image).filter(Boolean)) {
1369
+ const N = await w.url(q);
1370
+ if (!W) return;
1371
+ y.current.onAssetReady?.(q, N), q === Rt(e) && Ge(N);
1372
+ }
1373
+ }).catch(() => {
1374
+ }).finally(() => {
1375
+ W && t?.length && O.current !== t && (O.current = t, w.preload(t).catch(() => {
1376
+ }));
1377
+ }), () => {
1378
+ W = !1;
1379
+ };
1380
+ }, [n, c, s, i, Z, t, e, Y]), re(() => (r ? te() : ee(!1), () => {
1381
+ g.current += 1, L.current?.clear();
1382
+ }), [r, te, ee]), tt(T, () => ({
1383
+ acquireResources: (w) => Z().acquire(w),
1384
+ getPreviewBlob: async () => I.current,
1385
+ getPreviewUrl: async () => I.current ? URL.createObjectURL(I.current) : null,
1386
+ refresh: () => {
1387
+ J.current += 1, Q.current = !0, r && te();
1388
+ },
1389
+ updateText: async (w, F) => {
1390
+ const D = ie();
1391
+ return D ? D.updateText(w, F) : null;
1392
+ }
1393
+ }), [r, ie, Z, te]);
1394
+ const Je = () => {
1395
+ J.current += 1, Q.current = !0, fe(!1), r && te();
1396
+ }, xe = Re || (ge ? "" : Ne);
1397
+ return /* @__PURE__ */ Le("div", { className: u, style: { position: "relative", ...X }, children: [
1398
+ ge ? /* @__PURE__ */ H(nt, { image: Re, alt: x, loading: _e, failed: Ve, onRetry: Je }) : xe && /* @__PURE__ */ H("img", { src: xe, alt: x, style: { display: "block", width: "100%", height: "100%", objectFit: "contain" } }),
1399
+ !ge && _e && /* @__PURE__ */ H("div", { "aria-live": "polite", "aria-label": "Rendering product preview", style: { position: "absolute", inset: 0 } }),
1400
+ /* @__PURE__ */ H("div", { "aria-hidden": "true", style: { position: "absolute", width: 1, height: 1, overflow: "hidden", opacity: 0, pointerEvents: "none" }, children: /* @__PURE__ */ H("div", { ref: p, style: { width: 800, height: 800 }, children: /* @__PURE__ */ H("canvas", { ref: f, width: 800, height: 800 }) }) })
1401
+ ] });
1402
+ }
1403
+ );
1404
+ function Dt({
1405
+ viewArea: h,
1406
+ viewState: e,
1407
+ activeObjectId: s,
1408
+ onChange: r,
1409
+ acquireResources: t,
1410
+ onLoadingChange: i,
1411
+ className: a,
1412
+ style: n
1413
+ }) {
1414
+ const c = b(null), o = b(null), m = b(null), d = b(r), P = b(i), u = b(null), X = b(e), [x, _] = j(!1), [C, B] = j("");
1415
+ d.current = r, P.current = i;
1416
+ const T = G(() => {
1417
+ const f = m.current;
1418
+ if (!f) return;
1419
+ const p = f.getRenderedObjects();
1420
+ d.current(u.current ? Pt(p, u.current, X.current) : p);
1421
+ }, []);
1422
+ return re(() => {
1423
+ let f = !1, p = null, E = !1, k = !1, l = null, O = null;
1424
+ const I = () => {
1425
+ E || (E = !0, p?.destroy(), m.current === p && (m.current = null), l?.release(), u.current === l && (u.current = null), O?.dispose());
1426
+ };
1427
+ return (async () => {
1428
+ if (P.current?.(!0), await new Promise((y) => requestAnimationFrame(() => y())), f) return;
1429
+ const g = c.current, R = o.current;
1430
+ if (!g || !R) return;
1431
+ const v = g.clientWidth || 400, V = g.clientHeight || 400, L = [h.image, ...Ce(e)];
1432
+ if (t ? l = await t(L) : (O = new qe(), l = await O.acquire(L)), f) return;
1433
+ u.current = l;
1434
+ const J = await ze(e, { url: async (y) => l.urls[y] ?? y });
1435
+ if (f) return;
1436
+ p = new We(R, { width: v, height: V }, g, 0.85), m.current = p, vt(typeof window < "u" && window.innerWidth < 768 ? 16 : 8);
1437
+ const Q = {
1438
+ ...J,
1439
+ objects: (Array.isArray(J.objects) ? J.objects : []).map(
1440
+ (y) => y?.selectable === !1 ? { ...y, selectable: !0 } : y
1441
+ )
1442
+ };
1443
+ if (await p.switchView({ ...h, image: l.urls[h.image] ?? h.image }, typeof e.color == "string" ? e.color : "", Q), f) return;
1444
+ const A = new Set(
1445
+ (Array.isArray(e.objects) ? e.objects : []).filter((y) => y?.customConfig?.moveable === !0).map((y) => String(y.id ?? ""))
1446
+ );
1447
+ if (p.canvas.forEachObject((y) => {
1448
+ A.has(String(y.id ?? "")) || y.set({ selectable: !1, evented: !1 });
1449
+ }), s) {
1450
+ const y = p.canvas.getObjects().find((Y) => String(Y.id ?? "") === String(s));
1451
+ y && A.has(String(s)) && p.canvas.setActiveObject(y);
1452
+ }
1453
+ p.canvas.on("object:modified", () => T()), p.canvas.requestRenderAll(), await new Promise((y) => requestAnimationFrame(() => y())), f || _(!0);
1454
+ })().catch((g) => {
1455
+ f || B(g instanceof Error ? g.message : "Could not load the editor.");
1456
+ }).finally(() => {
1457
+ k = !0, f && I(), P.current?.(!1);
1458
+ }), () => {
1459
+ f = !0, _(!1), k && I();
1460
+ };
1461
+ }, []), /* @__PURE__ */ Le("div", { className: a, style: { position: "relative", width: "100%", height: "100%", ...n }, children: [
1462
+ /* @__PURE__ */ H("div", { ref: c, style: { position: "absolute", inset: 0, overflow: "hidden" }, children: /* @__PURE__ */ H("canvas", { ref: o }) }),
1463
+ !x && /* @__PURE__ */ H("div", { style: { position: "absolute", inset: 0, background: "#f2f2f2" }, "aria-label": C ? "Editor failed to load" : "Loading editor", children: C && /* @__PURE__ */ H("span", { role: "alert", children: C }) })
1464
+ ] });
1465
+ }
1466
+ export {
1467
+ Dt as P,
1468
+ Ft as a
1469
+ };