@printine/pod-editor 0.1.21 → 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.
@@ -1,1422 +0,0 @@
1
- import { jsxs as Ae, jsx as H } from "react/jsx-runtime";
2
- import { forwardRef as Ge, useRef as S, useState as Z, useCallback as N, useEffect as ie, useImperativeHandle as Je } from "react";
3
- import { LAYER_BLACK_LIST as Oe, BLEND_MODES_MAP as Ke } from "./engine/constants.js";
4
- import { P as Ye, h as Qe, r as Ze, i as pe, M as $e, a as je } from "./pixel-map-CSpWvUYE.js";
5
- import "./engine/fabric.js";
6
- import { v4 as et } from "uuid";
7
- import { cloneObject as G, urlToDataURL as tt } from "./engine/utils/common.js";
8
- import { ImageProcessor as rt } from "./engine/processors/image.js";
9
- import { TemplateProcessor as it } from "./engine/processors/template.js";
10
- import { TextProcessor as st } from "./engine/processors/text.js";
11
- import { ResizeManager as nt } from "./engine/managers/resize.js";
12
- import { loadOverlaySvgImage as at, loadImage as ct } from "./engine/utils/image.js";
13
- import { WorkspaceManager as ot } from "./engine/managers/workspace.js";
14
- import { HistoryManager as lt } from "./engine/history.js";
15
- import ht from "./engine/events.js";
16
- import { fabric as L } from "fabric";
17
- import { setDefaultControls as ut } from "./engine/utils/setting.js";
18
- class Ie {
19
- constructor(e, i, r, t = 0.85) {
20
- this.imageCache = /* @__PURE__ */ new Map(), this.overlayCache = /* @__PURE__ */ new Map(), this.destroyed = !1, this.deleteObject = (s) => {
21
- if (s) {
22
- const a = this.canvas._objects.find((n) => n.id === s);
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 L.Canvas(e, {
32
- enableRetinaScaling: !0,
33
- width: i.width,
34
- height: i.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 rt(this), this.templateProcessor = new it(this), this.textProcessor = new st(this), this.resizeManager = new nt(this, r), this.workspaceManager = new ot(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, i = !1) {
69
- const { image: r, clipPath: t } = await this.getOverlayImage(e.image), s = Math.min(this.canvas.width, this.canvas.height) * this.overlayScale, a = s / r.width, n = s / 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
- }), i && 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 i = this.overlayCache.get(e);
99
- if (i) {
100
- const a = await G(i.image), n = i.clipPath ? await G(i.clipPath) : void 0;
101
- return { image: a, clipPath: n };
102
- }
103
- const r = await at(e);
104
- this.overlayCache.set(e, r);
105
- const t = await G(r.image), s = r.clipPath ? await G(r.clipPath) : void 0;
106
- return { image: t, clipPath: s };
107
- }
108
- /**
109
- * 绘制可设计区域边框,优先使用 clipPath 的真实形状
110
- */
111
- setupOverlayBorders(e, i) {
112
- this.overlayBorderHandler && this.canvas.off("after:render", this.overlayBorderHandler);
113
- const r = i ?? e;
114
- this.overlayBorderHandler = () => {
115
- const t = this.canvas.getContext(), s = this.canvas.viewportTransform || [1, 0, 0, 1, 0, 0];
116
- t.save(), t.transform(s[0], s[1], s[2], s[3], s[4], s[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, g = r.top ?? 0, P = r.scaleX ?? 1, h = 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: h * o,
140
- left: m - n,
141
- top: g - 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: h,
150
- left: m,
151
- top: g
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 i = document.querySelector(".lower-canvas");
186
- if (i && !e)
187
- return i.style.backgroundImage = "", Promise.resolve();
188
- const r = await ct(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
- i && (i.style.backgroundImage = `url(${t})`, i.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: i = 0, top: r = 0, width: t = 0, height: s = 0 } = e.getBoundingRect(), a = e.getCenterPoint(), n = this.canvas.viewportTransform;
214
- return {
215
- left: i * n[0] + n[4],
216
- top: r * n[3] + n[5],
217
- width: t * n[0],
218
- height: s * 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, i = !0) {
228
- e.set({
229
- id: et()
230
- }), this.canvas.add(e), i && this.canvas.setActiveObject(e);
231
- }
232
- /**
233
- * 恢复对象
234
- */
235
- async restoreObject(e) {
236
- return new Promise((i) => {
237
- L.util.enlivenObjects([e], (r) => i(r), "");
238
- });
239
- }
240
- /**
241
- * 半定制文本更新:如果存在 originalWidth / originalHeight,则按固定框重新计算 fitScale;
242
- * 否则只更新文本内容/字体等基础属性。
243
- */
244
- async updateText(e, i) {
245
- if (!(typeof e?.type == "string" && (e.type.includes("i-text") || e.type === "text"))) return null;
246
- await this.textProcessor.ensureFontLoaded(i);
247
- const [t] = await this.restoreObject(e);
248
- if (!t) return null;
249
- const s = 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 y = o ? t.getCenterPoint() : null;
267
- t.set(i), o && (t.__restoredGeometry = !1);
268
- try {
269
- t.initDimensions?.();
270
- } catch {
271
- }
272
- return y && t.setPositionByOrigin(y, "center", "center"), t.setCoords(), {
273
- ...i,
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 g = e?.__semiTargetInfo, P = !!g && typeof g.width == "number" && g.width > 0 && typeof g.height == "number" && g.height > 0 && typeof g.centerX == "number" && typeof g.centerY == "number";
289
- let h;
290
- if (P) {
291
- const y = t.getCenterPoint();
292
- h = {
293
- width: n.originalWidth,
294
- height: n.originalHeight,
295
- centerX: typeof g.centerX == "number" ? g.centerX : y.x,
296
- centerY: typeof g.centerY == "number" ? g.centerY : y.y,
297
- signX: typeof g.signX == "number" && g.signX !== 0 ? Math.sign(g.signX) : Math.sign(s) || 1,
298
- signY: typeof g.signY == "number" && g.signY !== 0 ? Math.sign(g.signY) : Math.sign(a) || 1
299
- };
300
- } else {
301
- const y = t.getCenterPoint();
302
- h = {
303
- width: n.originalWidth,
304
- height: n.originalHeight,
305
- centerX: y.x,
306
- centerY: y.y,
307
- signX: Math.sign(s) || 1,
308
- signY: Math.sign(a) || 1
309
- };
310
- }
311
- t.set({
312
- ...i,
313
- scaleX: h.signX,
314
- scaleY: h.signY
315
- }), o && (t.__restoredGeometry = !1);
316
- try {
317
- t.initDimensions?.();
318
- } catch {
319
- }
320
- t.setCoords();
321
- const X = t.getBoundingRect(!0, !0), x = Math.max(1, X.width || 1), A = Math.max(1, X.height || 1);
322
- let M = Math.min(h.width / x, h.height / A);
323
- return (!Number.isFinite(M) || M <= 0) && (M = 1), t.set({
324
- scaleX: M * h.signX,
325
- scaleY: M * h.signY
326
- }), t.setPositionByOrigin(new L.Point(h.centerX, h.centerY), "center", "center"), t.setCoords(), {
327
- ...i,
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: h,
340
- ...m()
341
- };
342
- }
343
- /**
344
- * 半定制图片替换:使用 cover 模式重新计算缩放,保持原始占位框中心不变。
345
- */
346
- async updateImage(e, i) {
347
- if (e?.type !== "image") return null;
348
- const r = i.src;
349
- if (!r) return null;
350
- const [t] = await this.restoreObject(e);
351
- if (!t) return null;
352
- const s = t, a = e.scaleX || 1, n = e.scaleY || 1, c = e.width || 1, o = e.height || 1, m = c * Math.abs(a), g = o * Math.abs(n), P = t.getCenterPoint();
353
- return new Promise((h) => {
354
- s.setSrc(r, () => {
355
- const X = s.width || 1, x = s.height || 1, A = Math.max(m / X, g / x);
356
- s.set({
357
- ...i,
358
- scaleX: A * Math.sign(a),
359
- scaleY: A * Math.sign(n)
360
- }), s.setPositionByOrigin(P, "center", "center"), s.setCoords(), h({
361
- ...i,
362
- width: X,
363
- height: x,
364
- left: s.left,
365
- top: s.top,
366
- scaleX: s.scaleX,
367
- scaleY: s.scaleY,
368
- angle: s.angle,
369
- originX: s.originX,
370
- originY: s.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 i = e, r = i.getSrc(), t = i.originSrc || r;
383
- if (r && r.startsWith("blob:")) {
384
- const s = this.imageCache.get(t);
385
- if (!s || s.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, i) {
399
- const r = this.canvas._objects.find((t) => t.id === e);
400
- if (r) {
401
- if (i.hasOwnProperty("angle"))
402
- r.rotate(i.angle);
403
- else if (i.hasOwnProperty("align")) {
404
- const { left: t, right: s, top: a, bottom: n, center: c } = this.workspaceManager.dimension, o = r.getBoundingRect(!0, !0);
405
- switch (i.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 + (s - (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 (i.hasOwnProperty("zIndex"))
438
- this.canvas.moveTo(r, i.zIndex);
439
- else if (i.hasOwnProperty("scale"))
440
- this.updateObjectScale(r, i.scale);
441
- else if (i.hasOwnProperty("width") || i.hasOwnProperty("height")) {
442
- const t = i.hasOwnProperty("width") ? r.width : r.height, a = (i.width || i.height) / t * this.workspaceManager.scale;
443
- this.updateObjectScale(r, a);
444
- } else
445
- r.set(i);
446
- r.setCoords(), this.canvas.requestRenderAll(), i.hasOwnProperty("selectable") || this.canvas.fire("object:modified", {
447
- target: r
448
- });
449
- }
450
- }
451
- /**
452
- * 对象缩放
453
- */
454
- updateObjectScale(e, i) {
455
- const r = e.getCenterPoint(), t = this.workspaceManager.dimension.width * 0.01 / e.width;
456
- e.scale(i < t ? t : i), e.setPositionByOrigin(r, "center", "center");
457
- }
458
- /**
459
- * 修改画布上的对象的选中状态和事件状态
460
- * @param status
461
- */
462
- updateObjectsEvents(e) {
463
- this.canvas.forEachObject((i) => {
464
- i.set({
465
- selectable: e,
466
- evented: e
467
- });
468
- });
469
- }
470
- /**
471
- * 获取当前可选择的对象,不包括背景图、裁剪区域
472
- */
473
- getLayerList() {
474
- return this.canvas._objects.filter((e) => !Oe.includes(e.id || ""));
475
- }
476
- /**
477
- * 设置当前选中的对象
478
- */
479
- setActiveObject(e) {
480
- const i = this.canvas.getActiveObjects(), r = i.some((s) => s.id === e), t = this.getLayerList().find((s) => s.id === e);
481
- t && (this.canvas.discardActiveObject(), (!r || i.length > 1) && this.canvas.setActiveObject(t), this.canvas.requestRenderAll());
482
- }
483
- /**
484
- * 同时选中多个对象
485
- */
486
- setActiveObjects(e) {
487
- const i = new L.ActiveSelection(e, { canvas: this.canvas });
488
- this.canvas.setActiveObject(i), 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 i = this.canvas.viewportTransform, r = i[0], t = i[4], s = i[5], a = this.canvas.width / 2, n = this.canvas.height / 2, c = e - r, o = t - a * c, m = s - 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(lt.DEFAULT_SAVE_PROPERTIES), i = this.workspaceManager.dimension;
507
- return {
508
- objects: e.filter((r) => !Oe.includes(r.id || "")),
509
- workspaceMetadata: {
510
- width: i.width,
511
- height: i.height,
512
- centerX: i.center.x,
513
- centerY: i.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(), i = this.canvas.getObjects(), r = (s) => {
528
- const a = s.id;
529
- a && e.set(String(a), s), s.type === "group" && s._objects?.forEach(r);
530
- };
531
- i.forEach(r);
532
- const t = (s) => {
533
- const n = s.clipPath?.id;
534
- if (n && e.has(String(n))) {
535
- const c = e.get(String(n));
536
- c.set({ absolutePositioned: !0 }), s.set("clipPath", c), s.dirty = !0;
537
- }
538
- s.type === "group" && s._objects?.forEach(t);
539
- };
540
- i.forEach(t);
541
- }
542
- /**
543
- * 切换视图,重新渲染画布
544
- */
545
- async switchView(e, i, 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(i), r.workspaceMetadata && this._scaleObjectsToWorkspace(r.workspaceMetadata);
552
- const s = this.canvas.getObjects().filter((a) => a.type === "image");
553
- s.length > 0 && await Promise.all(
554
- s.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(), ht.emit("design:layerChange"), t();
567
- },
568
- (s, a) => {
569
- s.clipPath && !r.objects.some((n) => n.id === s.clipPath.id) && (delete a.clipPath, L.util.enlivenObjects(
570
- [s.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(i), 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 i = this.workspaceManager.dimension, r = Math.min(
591
- i.width / e.width,
592
- i.height / e.height
593
- ), t = e.centerX, s = e.centerY, a = i.center.x, n = i.center.y, c = Math.abs(a - t), o = Math.abs(n - s), m = Math.abs(r - 1) >= 1e-3, g = c >= 0.1 || o >= 0.1;
594
- if (!m && !g) return;
595
- const P = this.canvas.getObjects(), h = new Set(P), X = /* @__PURE__ */ new Set(), x = (f) => {
596
- const u = f.clipPath;
597
- u && h.has(u) && X.add(u);
598
- };
599
- P.forEach(x);
600
- const A = (f) => {
601
- const u = (f.left || 0) - t, T = (f.top || 0) - s, W = a + u * r, l = n + T * r;
602
- f.set({
603
- left: W,
604
- top: l,
605
- scaleX: (f.scaleX || 1) * r,
606
- scaleY: (f.scaleY || 1) * r
607
- }), f.setCoords(), f.dirty = !0;
608
- }, M = /* @__PURE__ */ new Set(), y = (f) => {
609
- !f.selectable && !X.has(f) || (A(f), M.add(f));
610
- };
611
- P.forEach(y);
612
- const B = (f) => {
613
- const u = f.clipPath;
614
- u && u.absolutePositioned && !h.has(u) && !M.has(u) && (A(u), M.add(u));
615
- };
616
- P.forEach(B);
617
- }
618
- /**
619
- * 计算对象相对于画布的全局变换矩阵(包括父组的影响)
620
- */
621
- getGlobalTransformMatrix(e) {
622
- return e.calcTransformMatrix();
623
- }
624
- /**
625
- * 判断对象是否位于 activeSelection 中
626
- */
627
- isInActiveSelection(e) {
628
- let i = e.group;
629
- for (; i; ) {
630
- if (i.type === "activeSelection") return !0;
631
- i = i.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, i, r) {
642
- if (!e || e.startsWith("data:")) return;
643
- const t = i.getElement(), s = this.imageCache.get(e);
644
- this.imageCache.set(e, {
645
- element: t,
646
- blobUrl: r || s?.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 i = this.imageCache.get(e);
678
- if (i?.element && i.element.complete) {
679
- const r = document.createElement("canvas");
680
- r.width = i.element.naturalWidth || i.element.width, r.height = i.element.naturalHeight || i.element.height;
681
- const t = r.getContext("2d");
682
- if (t) {
683
- t.drawImage(i.element, 0, 0);
684
- const s = r.toDataURL("image/png");
685
- return r.width = 0, r.height = 0, s;
686
- }
687
- return "";
688
- }
689
- return await tt(e);
690
- }
691
- /**
692
- * 从缓存克隆图片,避免重复下载
693
- */
694
- async cloneImageFromCache(e, i) {
695
- const r = e.getSrc() || "", t = e.originSrc || "", s = e.isCropped, a = t || r;
696
- if (a.startsWith("data:"))
697
- return new Promise((c) => {
698
- e.clone(
699
- (o) => {
700
- o.set(i), 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 L.Image(n.element, {
708
- width: e.width,
709
- height: e.height,
710
- ...i
711
- });
712
- if (e.clipPath)
713
- try {
714
- const m = await G(e.clipPath, ["absolutePositioned"]);
715
- o.set({ clipPath: m });
716
- } catch {
717
- }
718
- s && (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(i), s && (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, i) {
737
- if (this.destroyed) throw new Error("Canvas is not ready");
738
- const r = this.workspaceManager.dimension, t = this.workspaceManager.printAreaSize?.width ?? r.width, s = this.workspaceManager.printAreaSize?.height ?? r.height;
739
- if (!r.width || !r.height || !t || !s)
740
- throw new Error("Printable workspace has no dimensions");
741
- const a = Math.max(t, s), n = Math.max(1, e) / a, c = Math.max(1, Math.round(t * n)), o = Math.max(1, Math.round(s * n)), m = this.canvas.viewportTransform?.slice(), g = this.canvas.overlayImage?.visible, P = this.canvas.backgroundColor, h = this.canvas.getActiveObject(), X = h ? { hasBorders: h.hasBorders, hasControls: h.hasControls } : null;
742
- try {
743
- this.canvas.overlayImage && (this.canvas.overlayImage.visible = !1), h?.set({ hasBorders: !1, hasControls: !1 }), this.canvas.backgroundColor = i || "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 A = x.getContext("2d", { alpha: !0 });
747
- if (!A) throw new Error("Could not create preview canvas context");
748
- const M = this.canvas, y = M.getRetinaScaling?.() ?? window.devicePixelRatio ?? 1;
749
- A.drawImage(
750
- M.lowerCanvasEl,
751
- r.left * y,
752
- r.top * y,
753
- r.width * y,
754
- r.height * y,
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 && g !== void 0 && (this.canvas.overlayImage.visible = g), h && X && h.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, i, r) {
776
- const t = this.workspaceManager.dimension, s = this.workspaceManager.printAreaSize?.width ?? t.width, a = this.workspaceManager.printAreaSize?.height ?? t.height, n = window.devicePixelRatio || 1, c = Math.max(s / t.width, a / t.height), o = r?.objectCloneMultiplierCap ?? 8, m = Math.max(1, Math.min(r?.minObjectCloneMultiplier ?? 2, o)), g = Math.max(m, Math.min(o, Math.ceil(c * n)));
777
- let P = new L.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 G(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 h = new L.StaticCanvas(null, {
791
- width: t.width,
792
- height: t.height,
793
- enableRetinaScaling: !1,
794
- backgroundColor: i || "transparent",
795
- preserveObjectStacking: !0,
796
- clipPath: P
797
- }), X = this.getLayerList();
798
- (await Promise.all(
799
- X.map(
800
- (l) => new Promise((_) => {
801
- try {
802
- const O = l.sourceType === "svg";
803
- if (l.type === "image") {
804
- const R = l;
805
- let p = {
806
- selectable: !1,
807
- evented: !1,
808
- flipX: l.flipX || !1,
809
- flipY: l.flipY || !1
810
- };
811
- if (this.isInActiveSelection(l)) {
812
- const C = this.getGlobalTransformMatrix(l), v = L.util.qrDecompose(C);
813
- p = {
814
- ...p,
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
- p = {
825
- ...p,
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(R, p).then(async (C) => {
835
- if (C.clipPath) {
836
- const v = C.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 && C.type === "image")
843
- try {
844
- const v = C, I = v.getSrc() || v.originSrc || "";
845
- if (I) {
846
- const q = await this.getCachedDataURL(I);
847
- v.setSrc(q, () => _(C));
848
- return;
849
- }
850
- } catch {
851
- }
852
- _(C);
853
- }).catch(() => {
854
- _(l);
855
- });
856
- } else O ? G(l, ["absolutePositioned"]).then((R) => {
857
- if (this.isInActiveSelection(l)) {
858
- const C = this.getGlobalTransformMatrix(l), v = L.util.qrDecompose(C);
859
- R.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
- R.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 p = R.clipPath;
887
- p && p.absolutePositioned && p.set({
888
- left: (p.left || 0) - t.left,
889
- top: (p.top || 0) - t.top
890
- }), R.setCoords(), R.dirty = !0, _(R);
891
- }).catch(() => _(l)) : l.cloneAsImage(
892
- (R) => {
893
- if (this.isInActiveSelection(l)) {
894
- const p = this.getGlobalTransformMatrix(l), C = L.util.qrDecompose(p);
895
- R.set({
896
- left: (C.translateX || 0) - (t.left || 0),
897
- top: (C.translateY || 0) - (t.top || 0),
898
- angle: C.angle || 0,
899
- scaleX: (C.scaleX || 1) / g,
900
- scaleY: (C.scaleY || 1) / g,
901
- selectable: !1,
902
- hasControls: !1,
903
- hasBorders: !1,
904
- originX: "center",
905
- originY: "center"
906
- });
907
- } else {
908
- const p = l.getBoundingRect(!0, !0);
909
- R.set({
910
- left: p.left - t.left,
911
- top: p.top - t.top,
912
- scaleX: 1 / g,
913
- scaleY: 1 / g,
914
- angle: 0,
915
- selectable: !1,
916
- hasControls: !1,
917
- hasBorders: !1,
918
- originX: "left",
919
- originY: "top"
920
- });
921
- }
922
- _(R);
923
- },
924
- { multiplier: g }
925
- );
926
- } catch {
927
- _(l);
928
- }
929
- })
930
- )
931
- )).forEach((l) => h.add(l));
932
- const A = s / t.width, M = a / t.height;
933
- h.setViewportTransform([A, 0, 0, M, 0, 0]), h.renderAll();
934
- const y = r?.minOutputSize ?? 1024;
935
- let B = 1;
936
- (s > y || a > y) && (B = Math.max(1, y / Math.max(s, a))), typeof r?.outputMultiplierCap == "number" && (B = Math.min(B, r.outputMultiplierCap));
937
- let f = "";
938
- const u = () => h.toDataURL({
939
- format: "webp",
940
- quality: r?.quality ?? 0.5,
941
- width: s,
942
- height: a,
943
- multiplier: B
944
- }), T = r?.preferImageBitmap ?? !0, W = r?.returnBlobUrl ?? !1;
945
- if (T && window.createImageBitmap && typeof h.toCanvasElement == "function") {
946
- const l = h.toCanvasElement(B, { width: s, height: a });
947
- try {
948
- f = await createImageBitmap(l);
949
- } finally {
950
- l.width = 0, l.height = 0;
951
- }
952
- } else if (W && typeof h.toCanvasElement == "function") {
953
- const l = h.toCanvasElement(B, { width: s, height: a }), _ = await new Promise((O) => l.toBlob(O, "image/webp", r?.quality ?? 0.5));
954
- l.width = 0, l.height = 0, f = _ ? URL.createObjectURL(_) : u();
955
- } else
956
- f = u();
957
- return h.dispose(), f;
958
- }
959
- }
960
- class dt {
961
- constructor(e, i) {
962
- this.onBusy = e, this.onIdle = i, 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 ft {
986
- constructor(e = 32 * 1024 * 1024, i = 4, r) {
987
- this.budget = e, this.concurrency = i, 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((i) => {
991
- i.foreground = this.pinned.has(i.source);
992
- }), this.waiting.sort((i, r) => Number(r.foreground) - Number(i.foreground)), this.trim();
993
- }
994
- trim() {
995
- for (const [e, i] of this.entries) {
996
- if (this.bytes <= this.budget) break;
997
- !i.bytes || this.pinned.has(e) || (this.entries.delete(e), this.bytes -= i.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 i = this.waiting.findIndex((s) => s.source === e && !s.foreground);
1007
- if (i < 0) return;
1008
- const [r] = this.waiting.splice(i, 1);
1009
- r.foreground = !0;
1010
- const t = this.waiting.findIndex((s) => !s.foreground);
1011
- this.waiting.splice(t < 0 ? this.waiting.length : t, 0, r);
1012
- }
1013
- async fetchBlob(e, i) {
1014
- await new Promise((r, t) => {
1015
- const s = () => {
1016
- this.active += 1, r();
1017
- };
1018
- this.active < this.concurrency ? s() : (this.waiting.push({ source: e, foreground: !1, start: s, cancel: () => t(new Error("Resource cache was released")) }), i && 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, i = !0) {
1029
- const r = this.entries.get(e);
1030
- if (r)
1031
- return this.entries.delete(e), this.entries.set(e, r), i && this.promote(e), r.ready;
1032
- const t = { ready: this.fetchBlob(e, i), bytes: 0 };
1033
- return this.entries.set(e, t), t.ready.then((s) => {
1034
- this.entries.get(e) === t && (t.bytes = s.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 Be {
1041
- constructor() {
1042
- this.urls = /* @__PURE__ */ new Map(), this.disposed = !1, this.current = /* @__PURE__ */ new Set(), this.holds = /* @__PURE__ */ new Map(), this.cache = new ft(32 * 1024 * 1024, 4, (e) => {
1043
- const i = this.urls.get(e);
1044
- i && URL.revokeObjectURL(i), 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((i) => i && !i.startsWith("data:") && !i.startsWith("blob:")).map((i) => this.key(i));
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 i = new Set(this.sources(e));
1061
- return i.forEach((r) => this.holds.set(r, (this.holds.get(r) ?? 0) + 1)), this.updatePins(), () => {
1062
- i.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, i = !1) {
1069
- await Promise.all([...new Set(this.sources(e))].map((r) => this.cache.load(r, i)));
1070
- }
1071
- async url(e) {
1072
- if (!e || e.startsWith("data:") || e.startsWith("blob:")) return e;
1073
- const i = this.key(e), r = await this.cache.load(i, !0);
1074
- if (this.disposed) throw new Error("Resource session was released");
1075
- let t = this.urls.get(i);
1076
- return t || (t = URL.createObjectURL(r), this.urls.set(i, t)), t;
1077
- }
1078
- async acquire(e) {
1079
- const i = 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: i };
1082
- } catch (r) {
1083
- throw i(), r;
1084
- }
1085
- }
1086
- dispose() {
1087
- this.disposed = !0, this.cache.clear();
1088
- }
1089
- }
1090
- function ve(d) {
1091
- const e = /* @__PURE__ */ new Set(), i = (r) => {
1092
- if (!r || typeof r != "object") return;
1093
- if (Array.isArray(r)) {
1094
- r.forEach(i);
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(i);
1099
- };
1100
- return i(d), [...e];
1101
- }
1102
- async function Ee(d, e) {
1103
- const i = JSON.parse(JSON.stringify(d)), r = new Map(await Promise.all(ve(i).map(async (s) => [s, await e.url(s)]))), t = (s) => {
1104
- if (!s || typeof s != "object") return;
1105
- if (Array.isArray(s)) {
1106
- s.forEach(t);
1107
- return;
1108
- }
1109
- const a = s;
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(i), i;
1113
- }
1114
- function gt(d, e, i) {
1115
- const r = JSON.parse(JSON.stringify(d)), t = new Map(Object.entries(e.urls).map(([n, c]) => [c, n])), s = /* @__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(i, (n) => {
1125
- n.id !== void 0 && s.set(String(n.id), n);
1126
- }), a(r, (n) => {
1127
- const c = n.id !== void 0 ? s.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 $(d) {
1133
- return d.designKey || d.area?.name || d.name;
1134
- }
1135
- function me(d, e, i) {
1136
- const r = e[$(d)]?.color;
1137
- return i ?? (typeof r == "string" ? r : void 0);
1138
- }
1139
- function Ue(d, e, i) {
1140
- return i ?? d.render_areas.filter((r) => r.design).map((r) => e[$(r)]?.color).find((r) => typeof r == "string");
1141
- }
1142
- function we(d, e, i, r = !0, t = "global") {
1143
- if (!r) return d.render_areas;
1144
- const s = t === "global" ? Ue(d, e, i) : void 0;
1145
- return d.render_areas.filter((a) => {
1146
- const n = e[$(a)], c = t === "placement" ? me(a, e, i) : s;
1147
- return je({ design: a.design, defaultPrintColor: pe(a.defaultPrintColor, a.area?.defaultPrintColor, d.defaultPrintColor) }, c, !!(a.area && Array.isArray(n?.objects) && n.objects.length));
1148
- });
1149
- }
1150
- function Xe(d, e, i, r = !0, t = "global") {
1151
- return we(d, e, i, r, t).flatMap((s) => {
1152
- const a = e[$(s)];
1153
- return [s.image, ...s.design && s.area && Array.isArray(a?.objects) && a.objects.length ? [s.area.image, ...ve(a)] : []];
1154
- }).filter(Boolean);
1155
- }
1156
- function pt(d) {
1157
- return d.render_areas.find((e) => e.name === "bg")?.image || d.image || "";
1158
- }
1159
- function mt(d, e) {
1160
- const i = d.render_areas.find((t) => t.name === "bg") ?? d.render_areas.find((t) => !t.design), r = Math.max(i?.width ?? 0, i?.height ?? 0);
1161
- return Math.max(1, Math.min(768, Math.round(r ? r * e : 600)));
1162
- }
1163
- function ge(d) {
1164
- if (typeof d != "string") {
1165
- d.close();
1166
- return;
1167
- }
1168
- d.startsWith("blob:") && URL.revokeObjectURL(d);
1169
- }
1170
- const Bt = Ge(
1171
- function({
1172
- render: e,
1173
- designData: i,
1174
- enabled: r = !0,
1175
- preloadSources: t,
1176
- preloadDesignData: s,
1177
- onAssetReady: a,
1178
- backgroundColor: n,
1179
- colorMode: c = "global",
1180
- scale: o = 0.8,
1181
- renderer: m = "pixel-map",
1182
- className: g,
1183
- style: P,
1184
- alt: h = "Product preview",
1185
- onLoadingChange: X,
1186
- onRendered: x,
1187
- onError: A
1188
- }, M) {
1189
- const y = S(null), B = S(null), f = S(null), u = S(null), T = S(null), W = S(void 0), l = S(null), _ = S(null), O = S(0), R = S(/* @__PURE__ */ new Map()), p = S(null), C = S(0), v = S(!1), I = S(!1), q = S({ onLoadingChange: X, onRendered: x, onError: A, onAssetReady: a });
1190
- q.current = { onLoadingChange: X, onRendered: x, onError: A, onAssetReady: a };
1191
- const Y = m === "pixel-map" && Ye.isSupported(), se = S(Y);
1192
- se.current = Y;
1193
- const [j, k] = Z(""), [ne, Te] = Z(!1), [Le, We] = Z(""), [qe, he] = Z(!1), ue = Qe(Ze(e).render_areas), J = N(() => (T.current ??= new Be(), T.current), []), ee = N((w) => {
1194
- Te(w), q.current.onLoadingChange?.(w);
1195
- }, []), ae = N(() => {
1196
- if (f.current) return f.current;
1197
- if (!y.current || !B.current) return null;
1198
- const w = 800;
1199
- return y.current.width = w, y.current.height = w, f.current = new Ie(
1200
- y.current,
1201
- { width: w, height: w },
1202
- B.current,
1203
- 0.85
1204
- ), f.current;
1205
- }, []), ye = N(async () => {
1206
- if (u.current) return u.current;
1207
- if (Y) u.current = new Ye();
1208
- else {
1209
- const { StickerPlugin: w } = await import("./renderer/sticker.js");
1210
- if (I.current || se.current !== Y) return null;
1211
- if (u.current) return u.current;
1212
- u.current = new w({ width: 1, height: 1 }, !0, { subdiv: 8 });
1213
- }
1214
- return u.current;
1215
- }, [Y]), ce = N(() => {
1216
- f.current?.destroy(), f.current = null, u.current?.destroy(), u.current = null, T.current?.dispose(), T.current = null, W.current = void 0, R.current.forEach(({ texture: w }) => ge(w)), R.current.clear(), _.current && URL.revokeObjectURL(_.current), _.current = null, l.current = null;
1217
- }, []), be = N(() => (p.current || (p.current = new dt(
1218
- () => ee(!0),
1219
- () => {
1220
- I.current ? ce() : ee(!1);
1221
- }
1222
- )), p.current), [ce, ee]), te = N(() => {
1223
- const w = ++O.current, K = C.current;
1224
- be().enqueue(async () => {
1225
- let F;
1226
- try {
1227
- if (I.current || w !== O.current) return;
1228
- he(!1);
1229
- const U = ae();
1230
- v.current && (u.current?.destroy(), u.current = null, v.current = !1);
1231
- const V = await ye();
1232
- if (!U || !V || I.current || w !== O.current) return;
1233
- const z = J();
1234
- F = z.hold(Xe(e, i, n, Y, c));
1235
- const Ce = we(e, i, n, Y, c), Se = c === "global" ? Ue(e, i, n) : n, ze = e.render_areas.filter((b) => !!b.design), oe = mt(e, o), Re = Promise.all(Ce.map(async (b) => [b.image, await z.url(b.image)]));
1236
- Re.catch(() => {
1237
- });
1238
- for (const b of ze) {
1239
- const D = $(b), E = i[D], Q = c === "placement" ? me(b, i, n) ?? "" : typeof E?.color == "string" ? E.color : "", fe = pe(b.defaultPrintColor, b.area?.defaultPrintColor, e.defaultPrintColor), _e = fe ? "" : Q, De = !fe && c === "placement" && !Y && n === void 0 && !!Q;
1240
- if (!b.area || (!Array.isArray(E?.objects) || !E.objects.length) && !De) {
1241
- const re = R.current.get(D);
1242
- re && (ge(re.texture), R.current.delete(D));
1243
- continue;
1244
- }
1245
- const Me = JSON.stringify([
1246
- K,
1247
- oe,
1248
- b.area.id,
1249
- b.area.image,
1250
- E,
1251
- c,
1252
- Q,
1253
- fe
1254
- ]);
1255
- if (R.current.get(D)?.fingerprint === Me) continue;
1256
- const [Ne, Ve] = await Promise.all([
1257
- z.url(b.area.image),
1258
- Ee(E, z)
1259
- ]);
1260
- if (I.current || w !== O.current || (await U.switchView({ ...b.area, image: Ne }, Q, Ve), I.current || w !== O.current)) return;
1261
- const xe = typeof createImageBitmap == "function" ? await U.exportPreviewBitmap(oe, _e) : await U.export(!1, _e, {
1262
- minOutputSize: oe,
1263
- preferImageBitmap: !1,
1264
- returnBlobUrl: !1,
1265
- outputMultiplierCap: 1,
1266
- quality: 0.72
1267
- });
1268
- if (xe) {
1269
- const re = R.current.get(D);
1270
- re && ge(re.texture), R.current.set(D, { fingerprint: Me, texture: xe });
1271
- }
1272
- if (I.current || w !== O.current) return;
1273
- }
1274
- const Fe = new Map(await Re);
1275
- if (I.current || w !== O.current) return;
1276
- const ke = Ce.map((b) => {
1277
- const D = b.design ? R.current.get($(b))?.texture : void 0, E = b.texture_transform, Q = typeof E?.blendMode == "number" ? E.blendMode : typeof E?.blendMode == "string" ? Ke[E.blendMode.toLowerCase()] : void 0;
1278
- return {
1279
- ...b,
1280
- defaultPrintColor: pe(b.defaultPrintColor, b.area?.defaultPrintColor, e.defaultPrintColor),
1281
- image: Fe.get(b.image) ?? b.image,
1282
- texture: D,
1283
- color: c === "placement" && b.design ? me(b, i) : void 0,
1284
- // PixelMapRenderer consumes the source blend-mode string; Pixi
1285
- // still receives its enum value exactly as before.
1286
- config: E ? Y ? { ...E } : { ...E, blendMode: Q } : void 0
1287
- };
1288
- }), le = Y ? await V.onOffscreenRender(ke, {
1289
- color: Se,
1290
- targetSize: oe,
1291
- quality: 0.85,
1292
- format: "image/png",
1293
- cacheKey: e.id
1294
- }) : await (await import("./pixi-print-base-DIvtSF7v.js")).renderPixiWithPrintBase(V, ke, {
1295
- color: Se,
1296
- cleanCache: !1,
1297
- scale: o,
1298
- quality: 0.85
1299
- });
1300
- if (I.current || w !== O.current) return;
1301
- if (!le) throw new Error("Could not render the product preview");
1302
- const de = URL.createObjectURL(le);
1303
- _.current && URL.revokeObjectURL(_.current), l.current = le, _.current = de, k(de), q.current.onRendered?.({ renderId: e.id, blob: le, url: de });
1304
- } catch (U) {
1305
- !I.current && w === O.current && (he(!0), q.current.onError?.(U instanceof Error ? U : new Error("Could not render the product preview")));
1306
- } finally {
1307
- F?.();
1308
- }
1309
- });
1310
- }, [n, c, i, ae, be, ye, J, e, o, Y]);
1311
- ie(() => (I.current = !1, () => {
1312
- I.current = !0, O.current += 1, p.current?.clear(), p.current?.active || ce();
1313
- }), [ce]), ie(() => {
1314
- u.current?.destroy(), u.current = null;
1315
- }, [m, Y]), ie(() => {
1316
- const w = J(), K = s ?? i, F = Xe(e, K, n, Y, c);
1317
- w.pin(F);
1318
- let U = !0;
1319
- return w.preload(F, !0).then(async () => {
1320
- if (U)
1321
- for (const V of we(e, K, n, Y, c).map((z) => z.image).filter(Boolean)) {
1322
- const z = await w.url(V);
1323
- if (!U) return;
1324
- q.current.onAssetReady?.(V, z), V === pt(e) && We(z);
1325
- }
1326
- }).catch(() => {
1327
- }).finally(() => {
1328
- U && t?.length && W.current !== t && (W.current = t, w.preload(t).catch(() => {
1329
- }));
1330
- }), () => {
1331
- U = !1;
1332
- };
1333
- }, [n, c, i, s, J, t, e, Y]), ie(() => (r ? te() : ee(!1), () => {
1334
- O.current += 1, p.current?.clear();
1335
- }), [r, te, ee]), Je(M, () => ({
1336
- acquireResources: (w) => J().acquire(w),
1337
- getPreviewBlob: async () => l.current,
1338
- getPreviewUrl: async () => l.current ? URL.createObjectURL(l.current) : null,
1339
- refresh: () => {
1340
- C.current += 1, v.current = !0, r && te();
1341
- },
1342
- updateText: async (w, K) => {
1343
- const F = ae();
1344
- return F ? F.updateText(w, K) : null;
1345
- }
1346
- }), [r, ae, J, te]);
1347
- const He = () => {
1348
- C.current += 1, v.current = !0, he(!1), r && te();
1349
- }, Pe = j || (ue ? "" : Le);
1350
- return /* @__PURE__ */ Ae("div", { className: g, style: { position: "relative", ...P }, children: [
1351
- ue ? /* @__PURE__ */ H($e, { image: j, alt: h, loading: ne, failed: qe, onRetry: He }) : Pe && /* @__PURE__ */ H("img", { src: Pe, alt: h, style: { display: "block", width: "100%", height: "100%", objectFit: "contain" } }),
1352
- !ue && ne && /* @__PURE__ */ H("div", { "aria-live": "polite", "aria-label": "Rendering product preview", style: { position: "absolute", inset: 0 } }),
1353
- /* @__PURE__ */ H("div", { "aria-hidden": "true", style: { position: "absolute", width: 1, height: 1, overflow: "hidden", opacity: 0, pointerEvents: "none" }, children: /* @__PURE__ */ H("div", { ref: B, style: { width: 800, height: 800 }, children: /* @__PURE__ */ H("canvas", { ref: y, width: 800, height: 800 }) }) })
1354
- ] });
1355
- }
1356
- );
1357
- function Et({
1358
- viewArea: d,
1359
- viewState: e,
1360
- activeObjectId: i,
1361
- onChange: r,
1362
- acquireResources: t,
1363
- onLoadingChange: s,
1364
- className: a,
1365
- style: n
1366
- }) {
1367
- const c = S(null), o = S(null), m = S(null), g = S(r), P = S(s), h = S(null), X = S(e), [x, A] = Z(!1), [M, y] = Z("");
1368
- g.current = r, P.current = s;
1369
- const B = N(() => {
1370
- const f = m.current;
1371
- if (!f) return;
1372
- const u = f.getRenderedObjects();
1373
- g.current(h.current ? gt(u, h.current, X.current) : u);
1374
- }, []);
1375
- return ie(() => {
1376
- let f = !1, u = null, T = !1, W = !1, l = null, _ = null;
1377
- const O = () => {
1378
- T || (T = !0, u?.destroy(), m.current === u && (m.current = null), l?.release(), h.current === l && (h.current = null), _?.dispose());
1379
- };
1380
- return (async () => {
1381
- if (P.current?.(!0), await new Promise((k) => requestAnimationFrame(() => k())), f) return;
1382
- const p = c.current, C = o.current;
1383
- if (!p || !C) return;
1384
- const v = p.clientWidth || 400, I = p.clientHeight || 400, q = [d.image, ...ve(e)];
1385
- if (t ? l = await t(q) : (_ = new Be(), l = await _.acquire(q)), f) return;
1386
- h.current = l;
1387
- const Y = await Ee(e, { url: async (k) => l.urls[k] ?? k });
1388
- if (f) return;
1389
- u = new Ie(C, { width: v, height: I }, p, 0.85), m.current = u, ut(typeof window < "u" && window.innerWidth < 768 ? 16 : 8);
1390
- const se = {
1391
- ...Y,
1392
- objects: (Array.isArray(Y.objects) ? Y.objects : []).map(
1393
- (k) => k?.selectable === !1 ? { ...k, selectable: !0 } : k
1394
- )
1395
- };
1396
- if (await u.switchView({ ...d, image: l.urls[d.image] ?? d.image }, typeof e.color == "string" ? e.color : "", se), f) return;
1397
- const j = new Set(
1398
- (Array.isArray(e.objects) ? e.objects : []).filter((k) => k?.customConfig?.moveable === !0).map((k) => String(k.id ?? ""))
1399
- );
1400
- if (u.canvas.forEachObject((k) => {
1401
- j.has(String(k.id ?? "")) || k.set({ selectable: !1, evented: !1 });
1402
- }), i) {
1403
- const k = u.canvas.getObjects().find((ne) => String(ne.id ?? "") === String(i));
1404
- k && j.has(String(i)) && u.canvas.setActiveObject(k);
1405
- }
1406
- u.canvas.on("object:modified", () => B()), u.canvas.requestRenderAll(), await new Promise((k) => requestAnimationFrame(() => k())), f || A(!0);
1407
- })().catch((p) => {
1408
- f || y(p instanceof Error ? p.message : "Could not load the editor.");
1409
- }).finally(() => {
1410
- W = !0, f && O(), P.current?.(!1);
1411
- }), () => {
1412
- f = !0, A(!1), W && O();
1413
- };
1414
- }, []), /* @__PURE__ */ Ae("div", { className: a, style: { position: "relative", width: "100%", height: "100%", ...n }, children: [
1415
- /* @__PURE__ */ H("div", { ref: c, style: { position: "absolute", inset: 0, overflow: "hidden" }, children: /* @__PURE__ */ H("canvas", { ref: o }) }),
1416
- !x && /* @__PURE__ */ H("div", { style: { position: "absolute", inset: 0, background: "#f2f2f2" }, "aria-label": M ? "Editor failed to load" : "Loading editor", children: M && /* @__PURE__ */ H("span", { role: "alert", children: M }) })
1417
- ] });
1418
- }
1419
- export {
1420
- Et as P,
1421
- Bt as a
1422
- };