customforge 0.1.0-alpha.1 → 0.1.0

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +79 -24
  2. package/LICENSES/NunitoSans-OFL.txt +93 -0
  3. package/LICENSES/plain-mug-CC-BY-4.0.txt +11 -0
  4. package/README.md +592 -290
  5. package/README.zh-CN.md +589 -290
  6. package/dist/NunitoSans-Variable.ttf +0 -0
  7. package/dist/ProductCustomizer-4ytA68eg.js +2350 -0
  8. package/dist/ProductCustomizer-4ytA68eg.js.map +1 -0
  9. package/dist/bridge/TextureBridge.d.ts +1 -1
  10. package/dist/core/api.d.ts +94 -0
  11. package/dist/core/api.d.ts.map +1 -0
  12. package/dist/core/config.d.ts +3 -12
  13. package/dist/core/config.d.ts.map +1 -1
  14. package/dist/core/design.d.ts.map +1 -1
  15. package/dist/core/types.d.ts +217 -8
  16. package/dist/core/types.d.ts.map +1 -1
  17. package/dist/core/uv.d.ts +8 -0
  18. package/dist/core/uv.d.ts.map +1 -0
  19. package/dist/cup_decal_small_margins.glb +0 -0
  20. package/dist/customizer/ProductCustomizer.d.ts +174 -7
  21. package/dist/customizer/ProductCustomizer.d.ts.map +1 -1
  22. package/dist/editor/DesignEditor.d.ts +224 -14
  23. package/dist/editor/DesignEditor.d.ts.map +1 -1
  24. package/dist/editor/DesignHistory.d.ts +27 -0
  25. package/dist/editor/DesignHistory.d.ts.map +1 -0
  26. package/dist/editor/uvBounds.d.ts +15 -0
  27. package/dist/editor/uvBounds.d.ts.map +1 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -1108
  31. package/dist/index.js.map +1 -1
  32. package/dist/style.css +2123 -11
  33. package/dist/viewer/ProductViewer.d.ts +37 -6
  34. package/dist/viewer/ProductViewer.d.ts.map +1 -1
  35. package/dist/viewer/uvLayout.d.ts +11 -0
  36. package/dist/viewer/uvLayout.d.ts.map +1 -0
  37. package/dist/workbench/CustomForgeWorkbench.d.ts +205 -0
  38. package/dist/workbench/CustomForgeWorkbench.d.ts.map +1 -0
  39. package/dist/workbench/assets/catalog.d.ts +8 -0
  40. package/dist/workbench/assets/catalog.d.ts.map +1 -0
  41. package/dist/workbench/config.d.ts +96 -0
  42. package/dist/workbench/config.d.ts.map +1 -0
  43. package/dist/workbench/icons.d.ts +4 -0
  44. package/dist/workbench/icons.d.ts.map +1 -0
  45. package/dist/workbench/index.d.ts +25 -0
  46. package/dist/workbench/index.d.ts.map +1 -0
  47. package/dist/workbench/template.d.ts +3 -0
  48. package/dist/workbench/template.d.ts.map +1 -0
  49. package/dist/workbench/types.d.ts +542 -0
  50. package/dist/workbench/types.d.ts.map +1 -0
  51. package/dist/workbench.js +3052 -0
  52. package/dist/workbench.js.map +1 -0
  53. package/package.json +77 -71
@@ -0,0 +1,2350 @@
1
+ import { ActiveSelection, Canvas, FabricImage, Point, Textbox } from "fabric";
2
+ import { ACESFilmicToneMapping, AmbientLight, Box3, CanvasTexture, DirectionalLight, MathUtils, Mesh, MeshStandardMaterial, PerspectiveCamera, SRGBColorSpace, Scene, Vector3, WebGLRenderer } from "three";
3
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
4
+ import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
5
+ /**
6
+ * 清理产品配置并补全运行所需的默认值
7
+ *
8
+ * 远程模型和随包提供的默认 GLB 模型均默认不翻转纹理
9
+ *
10
+ * @param product 外部传入的产品配置
11
+ * @returns 可以直接交给编辑器和查看器使用的完整配置
12
+ */
13
+ function normalizeProductConfiguration(product = {}) {
14
+ return {
15
+ modelUrl: product.modelUrl?.trim() || void 0,
16
+ textureUrl: product.textureUrl?.trim() || void 0,
17
+ surfaceMesh: product.surfaceMesh?.trim() || "PrintArea",
18
+ textureFlipY: product.textureFlipY ?? false
19
+ };
20
+ }
21
+ //#endregion
22
+ //#region src/core/dom.ts
23
+ /**
24
+ * 将 HTMLElement 或 CSS 选择器解析为挂载容器
25
+ *
26
+ * @param target DOM 元素或 CSS 选择器
27
+ * @param label 错误消息中使用的容器名称
28
+ * @returns 解析得到的 DOM 元素
29
+ * @throws CSS 选择器无法找到对应元素时抛出错误
30
+ */
31
+ function resolveElement(target, label) {
32
+ if (target instanceof HTMLElement) return target;
33
+ const element = document.querySelector(target);
34
+ if (!element) throw new Error(`${label} element was not found: ${target}`);
35
+ return element;
36
+ }
37
+ function isRecord(value) {
38
+ return typeof value === "object" && value !== null && !Array.isArray(value);
39
+ }
40
+ function readRecord(value, path) {
41
+ if (!isRecord(value)) throw new TypeError(`${path} must be an object`);
42
+ return value;
43
+ }
44
+ function readString(value, path, allowEmpty = false) {
45
+ if (typeof value !== "string" || !allowEmpty && value.trim().length === 0) throw new TypeError(`${path} must be ${allowEmpty ? "a string" : "a non-empty string"}`);
46
+ return value;
47
+ }
48
+ function readFiniteNumber(value, path) {
49
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError(`${path} must be a finite number`);
50
+ return value;
51
+ }
52
+ function readPositiveNumber(value, path) {
53
+ const number = readFiniteNumber(value, path);
54
+ if (number <= 0) throw new TypeError(`${path} must be greater than zero`);
55
+ return number;
56
+ }
57
+ function readBoolean(value, path) {
58
+ if (typeof value !== "boolean") throw new TypeError(`${path} must be a boolean`);
59
+ return value;
60
+ }
61
+ function readImageRole(value, path) {
62
+ if (value !== "element" && value !== "background") throw new TypeError(`${path} must be element or background`);
63
+ return value;
64
+ }
65
+ function readTextAlignment(value, path) {
66
+ if (value !== "left" && value !== "center" && value !== "right") throw new TypeError(`${path} must be left, center, or right`);
67
+ return value;
68
+ }
69
+ function readTextFontStyle(value, path) {
70
+ if (value !== "normal" && value !== "italic") throw new TypeError(`${path} must be normal or italic`);
71
+ return value;
72
+ }
73
+ function readTextFontWeight(value, path) {
74
+ if (value === "normal" || value === "bold") return value;
75
+ const weight = readFiniteNumber(value, path);
76
+ if (weight <= 0 || weight > 1e3) throw new TypeError(`${path} must be between 1 and 1000`);
77
+ return weight;
78
+ }
79
+ function parseObjectState(object, path) {
80
+ return {
81
+ ...object.name === void 0 ? {} : { name: readString(object.name, `${path}.name`).trim() },
82
+ visible: object.visible === void 0 ? true : readBoolean(object.visible, `${path}.visible`),
83
+ locked: object.locked === void 0 ? false : readBoolean(object.locked, `${path}.locked`)
84
+ };
85
+ }
86
+ function parseTransform(value, path) {
87
+ const transform = readRecord(value, path);
88
+ return {
89
+ x: readFiniteNumber(transform.x, `${path}.x`),
90
+ y: readFiniteNumber(transform.y, `${path}.y`),
91
+ scaleX: readPositiveNumber(transform.scaleX, `${path}.scaleX`),
92
+ scaleY: readPositiveNumber(transform.scaleY, `${path}.scaleY`),
93
+ rotation: readFiniteNumber(transform.rotation, `${path}.rotation`),
94
+ flipX: readBoolean(transform.flipX, `${path}.flipX`),
95
+ flipY: readBoolean(transform.flipY, `${path}.flipY`)
96
+ };
97
+ }
98
+ function parseObject(value, index) {
99
+ const path = `design.objects[${index}]`;
100
+ const object = readRecord(value, path);
101
+ const id = readString(object.id, `${path}.id`);
102
+ const transform = parseTransform(object.transform, `${path}.transform`);
103
+ const state = parseObjectState(object, path);
104
+ if (object.type === "text") return {
105
+ id,
106
+ type: "text",
107
+ ...state,
108
+ transform,
109
+ text: readString(object.text, `${path}.text`, true),
110
+ width: readPositiveNumber(object.width, `${path}.width`),
111
+ fontFamily: readString(object.fontFamily, `${path}.fontFamily`),
112
+ fontSize: readPositiveNumber(object.fontSize, `${path}.fontSize`),
113
+ color: readString(object.color, `${path}.color`),
114
+ ...object.fontWeight === void 0 ? {} : { fontWeight: readTextFontWeight(object.fontWeight, `${path}.fontWeight`) },
115
+ ...object.fontStyle === void 0 ? {} : { fontStyle: readTextFontStyle(object.fontStyle, `${path}.fontStyle`) },
116
+ ...object.underline === void 0 ? {} : { underline: readBoolean(object.underline, `${path}.underline`) },
117
+ ...object.textAlign === void 0 ? {} : { textAlign: readTextAlignment(object.textAlign, `${path}.textAlign`) },
118
+ ...object.lineHeight === void 0 ? {} : { lineHeight: readPositiveNumber(object.lineHeight, `${path}.lineHeight`) },
119
+ ...object.charSpacing === void 0 ? {} : { charSpacing: readFiniteNumber(object.charSpacing, `${path}.charSpacing`) },
120
+ ...object.backgroundColor === void 0 ? {} : { backgroundColor: readString(object.backgroundColor, `${path}.backgroundColor`) }
121
+ };
122
+ if (object.type === "image") {
123
+ const src = readString(object.src, `${path}.src`);
124
+ if (src.startsWith("blob:")) throw new TypeError(`${path}.src must not use a Blob URL`);
125
+ return {
126
+ id,
127
+ type: "image",
128
+ ...state,
129
+ transform,
130
+ src,
131
+ ...object.role === void 0 ? {} : { role: readImageRole(object.role, `${path}.role`) }
132
+ };
133
+ }
134
+ throw new TypeError(`${path}.type is not supported`);
135
+ }
136
+ /**
137
+ * 校验并净化外部 Design JSON
138
+ *
139
+ * @param value JSON.parse 结果或其他未知输入
140
+ * @returns 只包含当前 Schema 字段的新设计文档
141
+ * @throws 文档版本、字段类型、对象 ID 或图片来源不符合契约时抛出 TypeError
142
+ */
143
+ function parseDesignDocument(value) {
144
+ const design = readRecord(value, "design");
145
+ if (design.version !== 1) throw new TypeError(`design.version must be 1`);
146
+ const canvas = readRecord(design.canvas, "design.canvas");
147
+ if (!Array.isArray(design.objects)) throw new TypeError("design.objects must be an array");
148
+ const objects = design.objects.map(parseObject);
149
+ const ids = /* @__PURE__ */ new Set();
150
+ let backgroundCount = 0;
151
+ for (const object of objects) {
152
+ if (ids.has(object.id)) throw new TypeError(`design object id is duplicated: ${object.id}`);
153
+ ids.add(object.id);
154
+ if (object.type === "image" && object.role === "background") {
155
+ backgroundCount += 1;
156
+ if (backgroundCount > 1) throw new TypeError("design must not contain more than one background");
157
+ if (objects.indexOf(object) !== 0) throw new TypeError("design background must be the first object");
158
+ }
159
+ }
160
+ return {
161
+ version: 1,
162
+ canvas: {
163
+ width: readPositiveNumber(canvas.width, "design.canvas.width"),
164
+ height: readPositiveNumber(canvas.height, "design.canvas.height")
165
+ },
166
+ objects
167
+ };
168
+ }
169
+ //#endregion
170
+ //#region src/editor/DesignHistory.ts
171
+ /** 固定容量的设计快照历史 */
172
+ var DesignHistory = class {
173
+ limit;
174
+ entries;
175
+ index = 0;
176
+ /**
177
+ * @param initial 初始设计快照
178
+ * @param limit 最多保留的撤销步骤数量
179
+ */
180
+ constructor(initial, limit) {
181
+ this.limit = limit;
182
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError("History limit must be a positive integer");
183
+ this.entries = [initial];
184
+ }
185
+ /** 当前撤销与重做可用状态 */
186
+ get state() {
187
+ return {
188
+ canUndo: this.index > 0,
189
+ canRedo: this.index < this.entries.length - 1
190
+ };
191
+ }
192
+ /** 当前步骤之前的快照 */
193
+ peekUndo() {
194
+ return this.entries[this.index - 1];
195
+ }
196
+ /** 当前步骤之后的快照 */
197
+ peekRedo() {
198
+ return this.entries[this.index + 1];
199
+ }
200
+ /** 添加新快照并丢弃当前步骤之后的重做分支 */
201
+ push(snapshot) {
202
+ this.entries.splice(this.index + 1);
203
+ this.entries.push(snapshot);
204
+ if (this.entries.length > this.limit + 1) this.entries.splice(0, this.entries.length - this.limit - 1);
205
+ this.index = this.entries.length - 1;
206
+ }
207
+ /** 在目标快照成功恢复后确认一次撤销 */
208
+ confirmUndo() {
209
+ if (this.index > 0) this.index -= 1;
210
+ }
211
+ /** 在目标快照成功恢复后确认一次重做 */
212
+ confirmRedo() {
213
+ if (this.index < this.entries.length - 1) this.index += 1;
214
+ }
215
+ /** 以当前快照重新开始历史记录 */
216
+ reset(snapshot) {
217
+ this.entries = [snapshot];
218
+ this.index = 0;
219
+ }
220
+ };
221
+ //#endregion
222
+ //#region src/editor/objectBounds.ts
223
+ /**
224
+ * 计算对象完整进入画布所需的最大等比缩放系数
225
+ *
226
+ * @param bounds 对象当前的轴对齐包围盒
227
+ * @param canvasWidth 画布逻辑宽度
228
+ * @param canvasHeight 画布逻辑高度
229
+ * @returns 不大于 1 的缩放系数,对象已经可容纳时返回 1
230
+ */
231
+ function calculateContainmentScale(bounds, canvasWidth, canvasHeight) {
232
+ const widthScale = bounds.width > canvasWidth ? canvasWidth / bounds.width : 1;
233
+ const heightScale = bounds.height > canvasHeight ? canvasHeight / bounds.height : 1;
234
+ return Math.min(widthScale, heightScale, 1);
235
+ }
236
+ /**
237
+ * 计算可容纳对象移回画布所需的平移距离
238
+ *
239
+ * 调用前应先确保包围盒不大于画布,否则无法同时满足两侧边界
240
+ *
241
+ * @param bounds 对象当前的轴对齐包围盒
242
+ * @param canvasWidth 画布逻辑宽度
243
+ * @param canvasHeight 画布逻辑高度
244
+ * @returns 应叠加到对象位置的画布坐标偏移量
245
+ */
246
+ function calculateContainmentOffset(bounds, canvasWidth, canvasHeight) {
247
+ return {
248
+ x: bounds.left < 0 ? -bounds.left : Math.min(0, canvasWidth - bounds.left - bounds.width),
249
+ y: bounds.top < 0 ? -bounds.top : Math.min(0, canvasHeight - bounds.top - bounds.height)
250
+ };
251
+ }
252
+ //#endregion
253
+ //#region src/editor/uvBounds.ts
254
+ function fullCanvasBounds(width, height) {
255
+ return {
256
+ left: 0,
257
+ top: 0,
258
+ width,
259
+ height
260
+ };
261
+ }
262
+ /**
263
+ * 将 UV 三角形的坐标范围转换为逻辑画布包围框
264
+ *
265
+ * UV 坐标会限制在 0 到 1 之间;布局为空、无效或退化时回退到整张画布
266
+ *
267
+ * @param layout 当前可打印 Mesh 的 UV 布局
268
+ * @param flipY 是否按照垂直翻转后的纹理方向计算
269
+ * @param canvasWidth 逻辑画布宽度
270
+ * @param canvasHeight 逻辑画布高度
271
+ * @returns 当前 UV 可打印区域在逻辑画布中的轴对齐包围框
272
+ */
273
+ function calculateUvCanvasBounds(layout, flipY, canvasWidth, canvasHeight) {
274
+ const coordinates = layout.triangleCoordinates;
275
+ let minimumX = Number.POSITIVE_INFINITY;
276
+ let minimumY = Number.POSITIVE_INFINITY;
277
+ let maximumX = Number.NEGATIVE_INFINITY;
278
+ let maximumY = Number.NEGATIVE_INFINITY;
279
+ for (let index = 0; index + 1 < coordinates.length; index += 2) {
280
+ const u = coordinates[index];
281
+ const v = coordinates[index + 1];
282
+ if (!Number.isFinite(u) || !Number.isFinite(v)) continue;
283
+ const x = Math.min(Math.max(u, 0), 1) * canvasWidth;
284
+ const normalizedY = flipY ? 1 - v : v;
285
+ const y = Math.min(Math.max(normalizedY, 0), 1) * canvasHeight;
286
+ minimumX = Math.min(minimumX, x);
287
+ minimumY = Math.min(minimumY, y);
288
+ maximumX = Math.max(maximumX, x);
289
+ maximumY = Math.max(maximumY, y);
290
+ }
291
+ const width = maximumX - minimumX;
292
+ const height = maximumY - minimumY;
293
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return fullCanvasBounds(canvasWidth, canvasHeight);
294
+ return {
295
+ left: minimumX,
296
+ top: minimumY,
297
+ width,
298
+ height
299
+ };
300
+ }
301
+ //#endregion
302
+ //#region src/editor/imageSource.ts
303
+ function readBlobAsDataUrl(blob) {
304
+ return new Promise((resolve, reject) => {
305
+ const reader = new FileReader();
306
+ reader.addEventListener("load", () => {
307
+ if (typeof reader.result === "string") resolve(reader.result);
308
+ else reject(/* @__PURE__ */ new Error("Blob image could not be converted to a Data URL"));
309
+ });
310
+ reader.addEventListener("error", () => {
311
+ reject(reader.error ?? /* @__PURE__ */ new Error("Blob image could not be read"));
312
+ });
313
+ reader.readAsDataURL(blob);
314
+ });
315
+ }
316
+ /**
317
+ * 将短生命周期 Blob URL 转换为可写入 Design JSON 的 Data URL
318
+ *
319
+ * 远程 URL 和已有 Data URL 会保持不变
320
+ *
321
+ * @param src 图片来源
322
+ * @returns 可跨页面会话重新加载的图片来源
323
+ * @throws Blob URL 已失效或浏览器无法读取对应 Blob 时抛出错误
324
+ */
325
+ async function resolvePersistentImageSource(src) {
326
+ if (!src.startsWith("blob:")) return src;
327
+ const response = await fetch(src);
328
+ if (!response.ok) throw new Error(`Blob image could not be loaded: ${response.status}`);
329
+ return readBlobAsDataUrl(await response.blob());
330
+ }
331
+ //#endregion
332
+ //#region src/editor/DesignEditor.ts
333
+ var EDITOR_DISPLAY_GUTTER = 56;
334
+ function normalizeEditorAppearance(appearance = {}) {
335
+ const controlSize = appearance.controlSize ?? 8;
336
+ if (!Number.isFinite(controlSize) || controlSize <= 0) throw new RangeError("appearance.editor.controlSize must be greater than zero");
337
+ return {
338
+ selectionFill: appearance.selectionFill?.trim() || "rgba(19, 113, 125, 0.12)",
339
+ selectionBorder: appearance.selectionBorder?.trim() || "#13717d",
340
+ controlFill: appearance.controlFill?.trim() || "#ffffff",
341
+ controlBorder: appearance.controlBorder?.trim() || "#13717d",
342
+ objectBorder: appearance.objectBorder?.trim() || "#13717d",
343
+ controlSize,
344
+ uvFill: appearance.uvFill?.trim() || void 0,
345
+ uvBoundary: appearance.uvBoundary?.trim() || "#dc2626"
346
+ };
347
+ }
348
+ /** 将 Fabric 主画布重绘为不含选择框的实时纹理 */
349
+ var DesignCanvas = class extends Canvas {
350
+ /** 将纯设计内容绘制到稳定的纹理 Canvas */
351
+ renderTexture(context) {
352
+ const previousSkipControlsDrawing = this.skipControlsDrawing;
353
+ this.skipControlsDrawing = true;
354
+ try {
355
+ this.renderCanvas(context, this.getObjects());
356
+ } finally {
357
+ this.skipControlsDrawing = previousSkipControlsDrawing;
358
+ }
359
+ }
360
+ };
361
+ /**
362
+ * 基于 Fabric.js 的二维纹理编辑器
363
+ *
364
+ * 负责基础纹理、UV 区域辅助层、文字、图片、对象选择和 PNG 导出
365
+ * 显示尺寸可以响应容器变化,内部逻辑尺寸保持不变
366
+ */
367
+ var DesignEditor = class {
368
+ /** 当前实例使用的 Fabric Canvas */
369
+ canvas;
370
+ host;
371
+ width;
372
+ height;
373
+ defaultText;
374
+ textObjectName;
375
+ imageObjectName;
376
+ backgroundObjectName;
377
+ appearance;
378
+ editableBounds;
379
+ renderListeners = /* @__PURE__ */ new Set();
380
+ selectionListeners = /* @__PURE__ */ new Set();
381
+ historyListeners = /* @__PURE__ */ new Set();
382
+ objectIds = /* @__PURE__ */ new WeakMap();
383
+ objectsById = /* @__PURE__ */ new Map();
384
+ objectNames = /* @__PURE__ */ new WeakMap();
385
+ objectLocks = /* @__PURE__ */ new WeakMap();
386
+ usedObjectIds = /* @__PURE__ */ new Set();
387
+ imageSources = /* @__PURE__ */ new WeakMap();
388
+ imageRoles = /* @__PURE__ */ new WeakMap();
389
+ resizeObserver;
390
+ history;
391
+ uvOverlay;
392
+ textureRenderer;
393
+ textureCanvasElement;
394
+ textureContext;
395
+ historySignature;
396
+ historyTimer;
397
+ historyBusy = false;
398
+ renderingTexture = false;
399
+ objectIdSequence = 0;
400
+ /**
401
+ * @param host 二维编辑器挂载容器
402
+ * @param options 画布逻辑尺寸和历史容量
403
+ */
404
+ constructor(host, options) {
405
+ this.host = host;
406
+ this.width = options.width;
407
+ this.height = options.height;
408
+ this.defaultText = options.defaultText ?? "Edit this text";
409
+ this.textObjectName = options.textObjectName ?? "Text";
410
+ this.imageObjectName = options.imageObjectName ?? "Image";
411
+ this.backgroundObjectName = options.backgroundObjectName ?? "Background";
412
+ this.appearance = normalizeEditorAppearance(options.appearance);
413
+ this.editableBounds = {
414
+ left: 0,
415
+ top: 0,
416
+ width: this.width,
417
+ height: this.height
418
+ };
419
+ const element = document.createElement("canvas");
420
+ element.setAttribute("aria-label", options.ariaLabel ?? "UV texture editor");
421
+ host.replaceChildren(element);
422
+ const canvas = new DesignCanvas(element, {
423
+ width: this.width,
424
+ height: this.height,
425
+ preserveObjectStacking: true,
426
+ selectionColor: this.appearance.selectionFill,
427
+ selectionBorderColor: this.appearance.selectionBorder
428
+ });
429
+ this.canvas = canvas;
430
+ this.textureRenderer = canvas;
431
+ this.textureCanvasElement = document.createElement("canvas");
432
+ this.textureCanvasElement.width = this.width;
433
+ this.textureCanvasElement.height = this.height;
434
+ const textureContext = this.textureCanvasElement.getContext("2d");
435
+ if (!textureContext) {
436
+ canvas.dispose();
437
+ throw new Error("Unable to create the live texture canvas");
438
+ }
439
+ this.textureContext = textureContext;
440
+ const initialDesign = this.saveDesign();
441
+ this.history = new DesignHistory(initialDesign, options.historyLimit);
442
+ this.historySignature = JSON.stringify(initialDesign);
443
+ this.canvas.wrapperEl.classList.add("customforge-design-canvas");
444
+ this.uvOverlay = document.createElement("canvas");
445
+ this.uvOverlay.width = this.width;
446
+ this.uvOverlay.height = this.height;
447
+ this.uvOverlay.className = "customforge-uv-layout";
448
+ this.uvOverlay.setAttribute("aria-hidden", "true");
449
+ this.uvOverlay.hidden = true;
450
+ this.canvas.wrapperEl.insertBefore(this.uvOverlay, this.canvas.upperCanvasEl);
451
+ this.host.dataset.renderState = "pending";
452
+ this.canvas.on("after:render", () => {
453
+ if (this.renderingTexture) return;
454
+ this.renderTextureCanvas();
455
+ this.markRenderState();
456
+ this.renderListeners.forEach((listener) => listener());
457
+ });
458
+ const notifySelection = () => this.notifySelectionChange();
459
+ this.canvas.on("selection:created", notifySelection);
460
+ this.canvas.on("selection:updated", notifySelection);
461
+ this.canvas.on("selection:cleared", notifySelection);
462
+ const constrainTarget = ({ target }) => {
463
+ this.constrainObjectToCanvas(target);
464
+ };
465
+ this.canvas.on("object:moving", constrainTarget);
466
+ this.canvas.on("object:scaling", constrainTarget);
467
+ this.canvas.on("object:rotating", constrainTarget);
468
+ this.canvas.on("object:skewing", constrainTarget);
469
+ this.canvas.on("object:resizing", constrainTarget);
470
+ this.canvas.on("object:modified", ({ target }) => {
471
+ this.constrainObjectToCanvas(target);
472
+ this.commitHistory();
473
+ });
474
+ this.canvas.on("text:changed", ({ target }) => {
475
+ this.constrainObjectToCanvas(target);
476
+ this.scheduleHistoryCommit();
477
+ });
478
+ this.resizeObserver = new ResizeObserver(() => this.resizeDisplay());
479
+ this.resizeObserver.observe(host);
480
+ this.resizeDisplay();
481
+ }
482
+ /** 供 Three.js 创建 CanvasTexture 的纯设计画布,不包含选择框和变换控件 */
483
+ get textureCanvas() {
484
+ return this.textureCanvasElement;
485
+ }
486
+ /**
487
+ * 在交互画布上显示目标 Mesh 的 UV 可打印区域,但不写入实时纹理或导出图片
488
+ *
489
+ * @param layout 从当前目标 Mesh 提取的 UV 布局
490
+ * @param flipY 是否按照垂直翻转后的纹理方向显示
491
+ */
492
+ setUvLayout(layout, flipY) {
493
+ this.editableBounds = calculateUvCanvasBounds(layout, flipY, this.width, this.height);
494
+ const context = this.uvOverlay.getContext("2d");
495
+ if (!context) return;
496
+ context.clearRect(0, 0, this.width, this.height);
497
+ const { triangleCoordinates, boundaryCoordinates } = layout;
498
+ if (triangleCoordinates.length === 0) {
499
+ this.uvOverlay.hidden = true;
500
+ return;
501
+ }
502
+ this.uvOverlay.hidden = false;
503
+ const accent = this.appearance.uvFill ?? (getComputedStyle(this.canvas.wrapperEl).getPropertyValue("--cfw-accent").trim() || "#268a4b");
504
+ const canvasX = (u) => Math.min(Math.max(u * this.width, 1), this.width - 1);
505
+ const canvasY = (v) => Math.min(Math.max((flipY ? 1 - v : v) * this.height, 1), this.height - 1);
506
+ context.save();
507
+ context.beginPath();
508
+ for (let index = 0; index < triangleCoordinates.length; index += 6) {
509
+ context.moveTo(canvasX(triangleCoordinates[index]), canvasY(triangleCoordinates[index + 1]));
510
+ context.lineTo(canvasX(triangleCoordinates[index + 2]), canvasY(triangleCoordinates[index + 3]));
511
+ context.lineTo(canvasX(triangleCoordinates[index + 4]), canvasY(triangleCoordinates[index + 5]));
512
+ context.closePath();
513
+ }
514
+ context.fillStyle = accent;
515
+ context.globalAlpha = .012;
516
+ context.fill();
517
+ context.beginPath();
518
+ for (let index = 0; index < boundaryCoordinates.length; index += 4) {
519
+ context.moveTo(canvasX(boundaryCoordinates[index]), canvasY(boundaryCoordinates[index + 1]));
520
+ context.lineTo(canvasX(boundaryCoordinates[index + 2]), canvasY(boundaryCoordinates[index + 3]));
521
+ }
522
+ context.globalAlpha = .28;
523
+ context.strokeStyle = this.appearance.uvBoundary;
524
+ context.lineWidth = 1;
525
+ context.lineCap = "round";
526
+ context.lineJoin = "round";
527
+ context.setLineDash([6, 6]);
528
+ context.stroke();
529
+ context.restore();
530
+ }
531
+ /** 当前画布中设计对象的数量,不包含产品基础纹理 */
532
+ get objectCount() {
533
+ return this.canvas.getObjects().length;
534
+ }
535
+ /**
536
+ * 订阅 Fabric Canvas 完成渲染事件
537
+ *
538
+ * @param listener 每次画布完成渲染后调用的函数
539
+ * @returns 用于取消本次订阅的函数
540
+ */
541
+ onRender(listener) {
542
+ this.renderListeners.add(listener);
543
+ return () => this.renderListeners.delete(listener);
544
+ }
545
+ /**
546
+ * 订阅画布选中状态变化
547
+ *
548
+ * @param listener 接收当前选中对象 ID 的函数
549
+ * @returns 用于取消本次订阅的函数
550
+ */
551
+ onSelectionChange(listener) {
552
+ this.selectionListeners.add(listener);
553
+ return () => this.selectionListeners.delete(listener);
554
+ }
555
+ /**
556
+ * 订阅撤销与重做可用状态变化
557
+ *
558
+ * @param listener 接收最新历史状态的函数
559
+ * @returns 用于取消本次订阅的函数
560
+ */
561
+ onHistoryChange(listener) {
562
+ this.historyListeners.add(listener);
563
+ return () => this.historyListeners.delete(listener);
564
+ }
565
+ /** 当前是否存在可以撤销的设计快照 */
566
+ get canUndo() {
567
+ return this.history.state.canUndo;
568
+ }
569
+ /** 当前是否存在可以重做的设计快照 */
570
+ get canRedo() {
571
+ return this.history.state.canRedo;
572
+ }
573
+ /**
574
+ * 返回当前对象的独立 Design JSON 快照
575
+ *
576
+ * @returns 按画布层级从后到前排列的对象数组
577
+ */
578
+ getObjects() {
579
+ return this.canvas.getObjects().map((object) => this.serializeObject(object));
580
+ }
581
+ /** 返回当前逻辑画布尺寸 */
582
+ getCanvasSize() {
583
+ return {
584
+ width: this.width,
585
+ height: this.height
586
+ };
587
+ }
588
+ /** 返回当前 UV 可打印区域的独立包围框 */
589
+ getPrintableBounds() {
590
+ return { ...this.editableBounds };
591
+ }
592
+ /** 当前选中对象的 ID,按画布层级从后到前排列 */
593
+ getSelectedObjectIds() {
594
+ return this.canvas.getActiveObjects().map((object) => this.objectIds.get(object)).filter((id) => Boolean(id));
595
+ }
596
+ /**
597
+ * 按稳定 ID 选中一个可见对象
598
+ *
599
+ * @param id Design JSON 中的对象 ID
600
+ * @returns 是否找到并选中了对象
601
+ */
602
+ selectObject(id) {
603
+ return this.selectObjects([id]);
604
+ }
605
+ /**
606
+ * 按稳定 ID 同时选中多个可见对象
607
+ *
608
+ * 所有 ID 都必须有效且对象可见,否则保持原选区不变
609
+ *
610
+ * @param ids 对象 ID,空数组表示清除选区
611
+ * @returns 是否应用了请求的选区
612
+ */
613
+ selectObjects(ids) {
614
+ const uniqueIds = [...new Set(ids)];
615
+ if (uniqueIds.length === 0) return this.clearSelection();
616
+ const objects = uniqueIds.map((id) => this.objectsById.get(id));
617
+ if (objects.some((object) => !object || !object.visible)) return false;
618
+ this.applySelection(objects);
619
+ this.canvas.requestRenderAll();
620
+ this.notifySelectionChange();
621
+ return true;
622
+ }
623
+ /**
624
+ * 清除当前画布选区,不修改设计内容或历史记录
625
+ *
626
+ * @returns 清除前是否存在选中对象
627
+ */
628
+ clearSelection() {
629
+ if (!this.canvas.getActiveObject()) return false;
630
+ this.canvas.discardActiveObject();
631
+ this.canvas.requestRenderAll();
632
+ this.notifySelectionChange();
633
+ return true;
634
+ }
635
+ /**
636
+ * 按稳定 ID 删除一个对象
637
+ *
638
+ * @param id Design JSON 中的对象 ID
639
+ * @returns 是否找到并删除了对象
640
+ */
641
+ removeObject(id) {
642
+ this.flushHistoryCommit();
643
+ const object = this.objectsById.get(id);
644
+ if (!object) return false;
645
+ if (this.canvas.getActiveObjects().includes(object)) this.canvas.discardActiveObject();
646
+ this.canvas.remove(object);
647
+ this.unregisterObject(object);
648
+ object.dispose();
649
+ this.canvas.requestRenderAll();
650
+ this.notifySelectionChange();
651
+ this.commitHistory();
652
+ return true;
653
+ }
654
+ /**
655
+ * 将对象移动到指定图层索引
656
+ *
657
+ * @param id Design JSON 中的对象 ID
658
+ * @param index 从 0 开始的索引,0 表示最底层
659
+ * @returns 对象层级是否发生变化
660
+ */
661
+ moveObject(id, index) {
662
+ this.flushHistoryCommit();
663
+ const object = this.objectsById.get(id);
664
+ const objects = this.canvas.getObjects();
665
+ if (!object || !Number.isInteger(index) || objects.length === 0) return false;
666
+ const currentIndex = objects.indexOf(object);
667
+ const role = object instanceof FabricImage ? this.imageRoles.get(object) ?? "element" : "element";
668
+ const backgroundCount = objects.filter((entry) => entry instanceof FabricImage && this.imageRoles.get(entry) === "background").length;
669
+ const minimumIndex = role === "background" ? 0 : backgroundCount;
670
+ const maximumIndex = role === "background" ? 0 : objects.length - 1;
671
+ const nextIndex = Math.min(Math.max(index, minimumIndex), maximumIndex);
672
+ if (currentIndex === nextIndex) return false;
673
+ this.canvas.moveObjectTo(object, nextIndex);
674
+ this.canvas.requestRenderAll();
675
+ this.commitHistory();
676
+ return true;
677
+ }
678
+ /**
679
+ * 将现有图片转换为铺满当前 UV 可打印区域的设计背景
680
+ *
681
+ * 转换会替换已有设计背景、重置旋转、锁定对象并移动到最底层
682
+ *
683
+ * @param id Design JSON 中的图片对象 ID
684
+ * @returns 是否找到普通图片并完成转换
685
+ */
686
+ setImageAsBackground(id) {
687
+ this.flushHistoryCommit();
688
+ const object = this.objectsById.get(id);
689
+ if (!(object instanceof FabricImage) || this.imageRoles.get(object) === "background") return false;
690
+ this.removeDesignBackgrounds();
691
+ this.imageRoles.set(object, "background");
692
+ this.fitImageToEditableBounds(object);
693
+ this.applyObjectLock(object, true);
694
+ this.canvas.moveObjectTo(object, 0);
695
+ this.canvas.setActiveObject(object);
696
+ this.canvas.requestRenderAll();
697
+ this.notifySelectionChange();
698
+ this.commitHistory();
699
+ return true;
700
+ }
701
+ /**
702
+ * 修改对象在图层面板中的名称
703
+ *
704
+ * @param id Design JSON 中的对象 ID
705
+ * @param name 非空图层名称
706
+ * @returns 是否找到并更新了对象
707
+ */
708
+ renameObject(id, name) {
709
+ this.flushHistoryCommit();
710
+ const object = this.objectsById.get(id);
711
+ const normalizedName = name.trim();
712
+ if (!object || !normalizedName) return false;
713
+ this.objectNames.set(object, normalizedName);
714
+ this.canvas.requestRenderAll();
715
+ this.commitHistory();
716
+ return true;
717
+ }
718
+ /**
719
+ * 修改对象是否参与渲染
720
+ *
721
+ * @param id Design JSON 中的对象 ID
722
+ * @param visible 是否参与二维画布、三维纹理和 PNG 渲染
723
+ * @returns 是否找到并更新了对象
724
+ */
725
+ setObjectVisibility(id, visible) {
726
+ this.flushHistoryCommit();
727
+ const object = this.objectsById.get(id);
728
+ if (!object || object.visible === visible) return Boolean(object);
729
+ if (!visible && this.canvas.getActiveObjects().includes(object)) this.canvas.discardActiveObject();
730
+ object.set({ visible });
731
+ this.canvas.requestRenderAll();
732
+ this.notifySelectionChange();
733
+ this.commitHistory();
734
+ return true;
735
+ }
736
+ /**
737
+ * 修改对象是否允许通过画布控件变换
738
+ *
739
+ * @param id Design JSON 中的对象 ID
740
+ * @param locked 是否锁定移动、缩放、旋转、倾斜和文字编辑
741
+ * @returns 是否找到并更新了对象
742
+ */
743
+ setObjectLocked(id, locked) {
744
+ this.flushHistoryCommit();
745
+ const object = this.objectsById.get(id);
746
+ if (!object) return false;
747
+ this.applyObjectLock(object, locked);
748
+ this.canvas.requestRenderAll();
749
+ this.commitHistory();
750
+ return true;
751
+ }
752
+ /**
753
+ * 更新对象中心位置、缩放、旋转和翻转
754
+ *
755
+ * 对象最终仍会约束在逻辑画布内,连续调用会合并为一个历史步骤
756
+ *
757
+ * @param id Design JSON 中的对象 ID
758
+ * @param options 要更新的变换字段
759
+ * @returns 约束后的对象快照,找不到对象时返回 undefined
760
+ * @throws 数值无效或缩放倍数不大于零时抛出错误
761
+ */
762
+ updateObjectTransform(id, options) {
763
+ const object = this.objectsById.get(id);
764
+ if (!object) return;
765
+ this.validateTransformOptions(options);
766
+ const selectedIds = this.getSelectedObjectIds();
767
+ if (object.group instanceof ActiveSelection) this.canvas.discardActiveObject();
768
+ const current = this.serializeTransform(object);
769
+ const x = options.x ?? current.x;
770
+ const y = options.y ?? current.y;
771
+ object.set({
772
+ scaleX: options.scaleX ?? current.scaleX,
773
+ scaleY: options.scaleY ?? current.scaleY,
774
+ angle: options.rotation ?? current.rotation,
775
+ flipX: options.flipX ?? current.flipX,
776
+ flipY: options.flipY ?? current.flipY
777
+ });
778
+ object.setPositionByOrigin(new Point(x, y), "center", "center");
779
+ this.constrainObjectToCanvas(object);
780
+ const selectedObjects = selectedIds.map((selectedId) => this.objectsById.get(selectedId)).filter((selected) => Boolean(selected?.visible));
781
+ if (selectedObjects.length > 0) this.applySelection(selectedObjects);
782
+ this.canvas.requestRenderAll();
783
+ this.notifySelectionChange();
784
+ this.scheduleHistoryCommit();
785
+ return this.serializeObject(object);
786
+ }
787
+ /**
788
+ * 修改已有文字对象的内容和排版样式
789
+ *
790
+ * 连续调用会在短暂空闲后合并为一个历史步骤
791
+ * 字体必须由消费页面提前加载,否则浏览器会使用回退字体
792
+ *
793
+ * @param id Design JSON 中的对象 ID
794
+ * @param options 要修改的文字属性,未传字段保持不变
795
+ * @returns 是否找到并更新了文字对象
796
+ * @throws 字号、行高、字距、字重或 CSS 颜色不符合约束时抛出错误
797
+ */
798
+ updateText(id, options) {
799
+ const object = this.objectsById.get(id);
800
+ if (!(object instanceof Textbox)) return false;
801
+ if (options.text !== void 0) object.set({ text: options.text });
802
+ if (options.fontFamily !== void 0) {
803
+ const fontFamily = options.fontFamily.trim();
804
+ if (!fontFamily) throw new TypeError("fontFamily must be a non-empty string");
805
+ object.set({ fontFamily });
806
+ }
807
+ if (options.fontSize !== void 0) {
808
+ if (!Number.isFinite(options.fontSize) || options.fontSize <= 0) throw new RangeError("fontSize must be greater than zero");
809
+ object.set({ fontSize: options.fontSize });
810
+ }
811
+ if (options.color !== void 0) {
812
+ if (!options.color.trim()) throw new TypeError("color must be a non-empty CSS color");
813
+ object.set({ fill: options.color });
814
+ }
815
+ if (options.fontWeight !== void 0) {
816
+ if (!(options.fontWeight === "normal" || options.fontWeight === "bold" || typeof options.fontWeight === "number" && Number.isFinite(options.fontWeight) && options.fontWeight > 0 && options.fontWeight <= 1e3)) throw new RangeError("fontWeight must be normal, bold, or between 1 and 1000");
817
+ object.set({ fontWeight: options.fontWeight });
818
+ }
819
+ if (options.fontStyle !== void 0) {
820
+ if (options.fontStyle !== "normal" && options.fontStyle !== "italic") throw new TypeError("fontStyle must be normal or italic");
821
+ object.set({ fontStyle: options.fontStyle });
822
+ }
823
+ if (options.underline !== void 0) object.set({ underline: options.underline });
824
+ if (options.textAlign !== void 0) {
825
+ if (![
826
+ "left",
827
+ "center",
828
+ "right"
829
+ ].includes(options.textAlign)) throw new TypeError("textAlign must be left, center, or right");
830
+ object.set({ textAlign: options.textAlign });
831
+ }
832
+ if (options.lineHeight !== void 0) {
833
+ if (!Number.isFinite(options.lineHeight) || options.lineHeight <= 0) throw new RangeError("lineHeight must be greater than zero");
834
+ object.set({ lineHeight: options.lineHeight });
835
+ }
836
+ if (options.charSpacing !== void 0) {
837
+ if (!Number.isFinite(options.charSpacing)) throw new TypeError("charSpacing must be a finite number");
838
+ object.set({ charSpacing: options.charSpacing });
839
+ }
840
+ if (options.backgroundColor !== void 0) {
841
+ if (options.backgroundColor !== null && !options.backgroundColor.trim()) throw new TypeError("backgroundColor must be a non-empty CSS color or null");
842
+ object.set({ backgroundColor: options.backgroundColor ?? "" });
843
+ }
844
+ object.initDimensions();
845
+ if (object.group instanceof ActiveSelection) {
846
+ object.group.triggerLayout();
847
+ this.constrainObjectToCanvas(object.group);
848
+ } else this.constrainObjectToCanvas(object);
849
+ this.canvas.requestRenderAll();
850
+ this.scheduleHistoryCommit();
851
+ return true;
852
+ }
853
+ /**
854
+ * 让一个未锁定文字对象进入画布内联编辑状态
855
+ *
856
+ * @param id Design JSON 中的对象 ID
857
+ * @returns 是否找到文字对象并进入编辑状态
858
+ */
859
+ editText(id) {
860
+ this.flushHistoryCommit();
861
+ const object = this.objectsById.get(id);
862
+ if (!(object instanceof Textbox) || !object.visible || (this.objectLocks.get(object) ?? false)) return false;
863
+ this.canvas.setActiveObject(object);
864
+ object.enterEditing();
865
+ object.hiddenTextarea?.focus();
866
+ this.canvas.requestRenderAll();
867
+ this.notifySelectionChange();
868
+ return true;
869
+ }
870
+ /**
871
+ * 设置铺满画布的基础纹理,不传地址时恢复透明背景
872
+ *
873
+ * 背景纹理不参与对象选择,但会包含在实时纹理和 PNG 导出中
874
+ *
875
+ * @param url 基础纹理地址
876
+ * @throws 图片加载失败或被 CORS 策略阻止时抛出错误
877
+ */
878
+ async setBackgroundTexture(url) {
879
+ if (!url) {
880
+ this.canvas.backgroundImage = void 0;
881
+ this.canvas.backgroundColor = "";
882
+ this.canvas.requestRenderAll();
883
+ return;
884
+ }
885
+ const image = await FabricImage.fromURL(url, { crossOrigin: "anonymous" });
886
+ const scaleX = this.width / Math.max(image.width, 1);
887
+ const scaleY = this.height / Math.max(image.height, 1);
888
+ image.set({
889
+ left: 0,
890
+ top: 0,
891
+ originX: "left",
892
+ originY: "top",
893
+ scaleX,
894
+ scaleY,
895
+ selectable: false,
896
+ evented: false
897
+ });
898
+ this.canvas.backgroundImage = image;
899
+ this.canvas.requestRenderAll();
900
+ }
901
+ /**
902
+ * 添加并选中一个可编辑文字对象
903
+ *
904
+ * 文字位置使用画布像素坐标,原点位于对象左上角
905
+ * 对象过大时会等比缩小,越界时会自动移回画布
906
+ *
907
+ * @param options 文字内容、位置和样式
908
+ * @returns 创建后的可持久化文字对象快照
909
+ */
910
+ addText(options = {}) {
911
+ this.flushHistoryCommit();
912
+ const text = new Textbox(options.text ?? this.defaultText, {
913
+ left: options.x ?? this.width * .18,
914
+ top: options.y ?? this.height * .36,
915
+ width: options.width ?? this.width * .42,
916
+ fontFamily: options.fontFamily ?? "Arial",
917
+ fontSize: options.fontSize ?? 22,
918
+ fontWeight: options.fontWeight ?? 700,
919
+ fontStyle: options.fontStyle ?? "normal",
920
+ underline: options.underline ?? false,
921
+ fill: options.color ?? "#172126",
922
+ backgroundColor: options.backgroundColor ?? "",
923
+ originX: "left",
924
+ originY: "top",
925
+ textAlign: options.textAlign ?? "center",
926
+ lineHeight: options.lineHeight ?? 1.16,
927
+ charSpacing: options.charSpacing ?? 0,
928
+ editable: true,
929
+ ...this.objectControlAppearance()
930
+ });
931
+ this.addAndSelect(text, options.name);
932
+ return this.serializeObject(text);
933
+ }
934
+ /**
935
+ * 加载、添加并选中一个图片对象
936
+ *
937
+ * role 为 background 时替换已有设计背景、铺满当前 UV 可打印区域并默认锁定在最底层
938
+ * 图片位置使用画布像素坐标,原点位于图片中心
939
+ * 对象过大时会等比缩小,越界时会自动移回画布
940
+ * 远程图片必须提供正确的 CORS 响应头才能安全导出 PNG
941
+ *
942
+ * @param options 图片地址、中心位置和显示宽度
943
+ * @returns 创建后的可持久化图片对象快照
944
+ * @throws 图片加载失败或被 CORS 策略阻止时抛出错误
945
+ */
946
+ async addImage(options) {
947
+ this.flushHistoryCommit();
948
+ const source = await resolvePersistentImageSource(options.src);
949
+ const image = await this.loadImage(source);
950
+ const role = options.role ?? "element";
951
+ const scale = (options.width ?? this.width * .22) / Math.max(image.width, 1);
952
+ image.set({
953
+ left: options.x ?? this.width * .62,
954
+ top: options.y ?? this.height * .29,
955
+ originX: "center",
956
+ originY: "center",
957
+ scaleX: scale,
958
+ scaleY: scale,
959
+ ...this.objectControlAppearance()
960
+ });
961
+ if (role === "background") {
962
+ this.removeDesignBackgrounds();
963
+ this.fitImageToEditableBounds(image);
964
+ }
965
+ this.imageSources.set(image, source);
966
+ this.addAndSelect(image, options.name, role === "background", role);
967
+ return this.serializeObject(image);
968
+ }
969
+ /**
970
+ * 返回与 Fabric.js 无关的当前设计快照
971
+ *
972
+ * 文档包含设计背景等设计对象和逻辑画布尺寸,不包含产品基础纹理或模型配置
973
+ *
974
+ * @returns 可以安全传给 JSON.stringify 的 Design JSON 文档
975
+ * @throws 画布包含不支持的对象或非字符串文字填充时抛出错误
976
+ */
977
+ saveDesign() {
978
+ return {
979
+ version: 1,
980
+ canvas: {
981
+ width: this.width,
982
+ height: this.height
983
+ },
984
+ objects: this.getObjects()
985
+ };
986
+ }
987
+ /**
988
+ * 校验并恢复 Design JSON,图片全部加载成功后才替换当前对象
989
+ *
990
+ * 背景纹理和当前产品保持不变,恢复后不选中任何对象
991
+ *
992
+ * @param value JSON.parse 结果或符合 DesignDocument 的对象
993
+ * @throws Schema 无效、画布尺寸不匹配或图片无法加载时抛出错误
994
+ */
995
+ async loadDesign(value) {
996
+ this.flushHistoryCommit();
997
+ await this.replaceDesign(value);
998
+ this.commitHistory();
999
+ }
1000
+ async replaceDesign(value) {
1001
+ const design = parseDesignDocument(value);
1002
+ if (design.canvas.width !== this.width || design.canvas.height !== this.height) throw new RangeError(`Design canvas ${design.canvas.width}x${design.canvas.height} does not match editor canvas ${this.width}x${this.height}`);
1003
+ const entries = [];
1004
+ try {
1005
+ for (const object of design.objects) entries.push({
1006
+ id: object.id,
1007
+ object: await this.createObjectFromDesign(object),
1008
+ source: object.type === "image" ? object.src : void 0,
1009
+ name: object.name,
1010
+ locked: object.locked ?? false,
1011
+ role: object.type === "image" ? object.role ?? "element" : "element"
1012
+ });
1013
+ } catch (error) {
1014
+ entries.forEach(({ object }) => object.dispose());
1015
+ throw error;
1016
+ }
1017
+ const previousObjects = this.canvas.getObjects();
1018
+ this.canvas.discardActiveObject();
1019
+ this.canvas.remove(...previousObjects);
1020
+ previousObjects.forEach((object) => object.dispose());
1021
+ this.usedObjectIds.clear();
1022
+ this.objectsById.clear();
1023
+ for (const entry of entries) {
1024
+ this.registerObject(entry.object, entry.id, entry.name, entry.locked, entry.role);
1025
+ if (entry.object instanceof FabricImage && entry.source) this.imageSources.set(entry.object, entry.source);
1026
+ this.canvas.add(entry.object);
1027
+ this.constrainObjectToCanvas(entry.object);
1028
+ }
1029
+ this.canvas.requestRenderAll();
1030
+ this.notifySelectionChange();
1031
+ }
1032
+ /**
1033
+ * 恢复上一个设计快照
1034
+ *
1035
+ * @returns 是否成功恢复了一个历史步骤
1036
+ */
1037
+ async undo() {
1038
+ this.flushHistoryCommit();
1039
+ const target = this.history.peekUndo();
1040
+ if (!target || this.historyBusy) return false;
1041
+ this.historyBusy = true;
1042
+ try {
1043
+ await this.replaceDesign(target);
1044
+ this.history.confirmUndo();
1045
+ this.historySignature = JSON.stringify(this.saveDesign());
1046
+ this.notifyHistoryChange();
1047
+ return true;
1048
+ } finally {
1049
+ this.historyBusy = false;
1050
+ }
1051
+ }
1052
+ /**
1053
+ * 恢复下一个设计快照
1054
+ *
1055
+ * @returns 是否成功恢复了一个历史步骤
1056
+ */
1057
+ async redo() {
1058
+ this.flushHistoryCommit();
1059
+ const target = this.history.peekRedo();
1060
+ if (!target || this.historyBusy) return false;
1061
+ this.historyBusy = true;
1062
+ try {
1063
+ await this.replaceDesign(target);
1064
+ this.history.confirmRedo();
1065
+ this.historySignature = JSON.stringify(this.saveDesign());
1066
+ this.notifyHistoryChange();
1067
+ return true;
1068
+ } finally {
1069
+ this.historyBusy = false;
1070
+ }
1071
+ }
1072
+ /** 以当前设计为起点清空撤销与重做历史 */
1073
+ clearHistory() {
1074
+ this.flushHistoryCommit();
1075
+ const current = this.saveDesign();
1076
+ this.history.reset(current);
1077
+ this.historySignature = JSON.stringify(current);
1078
+ this.notifyHistoryChange();
1079
+ }
1080
+ /**
1081
+ * 删除当前对象或多选选区
1082
+ *
1083
+ * @returns 是否删除了至少一个对象
1084
+ */
1085
+ deleteSelected() {
1086
+ this.flushHistoryCommit();
1087
+ const selection = this.canvas.getActiveObjects();
1088
+ if (selection.length === 0) return false;
1089
+ this.canvas.remove(...selection);
1090
+ selection.forEach((object) => {
1091
+ this.unregisterObject(object);
1092
+ object.dispose();
1093
+ });
1094
+ this.canvas.discardActiveObject();
1095
+ this.canvas.requestRenderAll();
1096
+ this.notifySelectionChange();
1097
+ this.commitHistory();
1098
+ return true;
1099
+ }
1100
+ /**
1101
+ * 将当前画布内容导出为 PNG 并触发浏览器下载
1102
+ *
1103
+ * @param filename 下载文件名
1104
+ * @throws 画布被无 CORS 授权的远程图片污染时抛出安全错误
1105
+ */
1106
+ exportTexture(filename = "custom-texture.png") {
1107
+ const anchor = document.createElement("a");
1108
+ anchor.download = filename;
1109
+ anchor.href = this.getTextureDataUrl();
1110
+ anchor.click();
1111
+ }
1112
+ /**
1113
+ * 返回不含选择框和 UV 辅助层的 PNG Data URL
1114
+ *
1115
+ * @returns 与逻辑画布同尺寸的 PNG Data URL
1116
+ * @throws 远程图片污染 Canvas 时抛出安全错误
1117
+ */
1118
+ getTextureDataUrl() {
1119
+ this.renderTextureCanvas();
1120
+ return this.textureCanvasElement.toDataURL("image/png");
1121
+ }
1122
+ /**
1123
+ * 异步返回不含选择框和 UV 辅助层的 PNG Blob
1124
+ *
1125
+ * @returns 与逻辑画布同尺寸的 PNG Blob
1126
+ * @throws 远程图片污染 Canvas 或浏览器无法编码时抛出错误
1127
+ */
1128
+ getTextureBlob() {
1129
+ this.renderTextureCanvas();
1130
+ return new Promise((resolve, reject) => {
1131
+ this.textureCanvasElement.toBlob((blob) => {
1132
+ if (blob) resolve(blob);
1133
+ else reject(/* @__PURE__ */ new Error("The texture canvas could not be encoded as PNG"));
1134
+ }, "image/png");
1135
+ });
1136
+ }
1137
+ /** 释放 ResizeObserver、事件监听和 Fabric Canvas */
1138
+ destroy() {
1139
+ if (this.historyTimer !== void 0) {
1140
+ clearTimeout(this.historyTimer);
1141
+ this.historyTimer = void 0;
1142
+ }
1143
+ this.resizeObserver.disconnect();
1144
+ this.renderListeners.clear();
1145
+ this.selectionListeners.clear();
1146
+ this.historyListeners.clear();
1147
+ this.objectsById.clear();
1148
+ this.usedObjectIds.clear();
1149
+ this.canvas.dispose();
1150
+ this.host.replaceChildren();
1151
+ }
1152
+ addAndSelect(object, name, locked = false, role = "element") {
1153
+ this.registerObject(object, void 0, name, locked, role);
1154
+ this.canvas.add(object);
1155
+ if (object instanceof FabricImage && role === "background") this.canvas.moveObjectTo(object, 0);
1156
+ this.constrainObjectToCanvas(object);
1157
+ this.canvas.setActiveObject(object);
1158
+ this.canvas.requestRenderAll();
1159
+ this.notifySelectionChange();
1160
+ this.commitHistory();
1161
+ }
1162
+ registerObject(object, id = this.createObjectId(), name, locked = false, role = "element") {
1163
+ if (this.usedObjectIds.has(id)) throw new Error(`Design object id is already in use: ${id}`);
1164
+ this.usedObjectIds.add(id);
1165
+ this.objectIds.set(object, id);
1166
+ this.objectsById.set(id, object);
1167
+ if (name) this.objectNames.set(object, name);
1168
+ if (object instanceof FabricImage) this.imageRoles.set(object, role);
1169
+ this.applyObjectLock(object, locked);
1170
+ }
1171
+ unregisterObject(object) {
1172
+ const id = this.objectIds.get(object);
1173
+ if (id) this.objectsById.delete(id);
1174
+ }
1175
+ createObjectId() {
1176
+ let id;
1177
+ do {
1178
+ this.objectIdSequence += 1;
1179
+ id = `object-${this.objectIdSequence}`;
1180
+ } while (this.usedObjectIds.has(id));
1181
+ return id;
1182
+ }
1183
+ serializeObject(object) {
1184
+ const id = this.objectIds.get(object);
1185
+ if (!id) throw new Error("Design object is missing its stable id");
1186
+ const transform = this.serializeTransform(object);
1187
+ const state = {
1188
+ name: this.objectNames.get(object) ?? this.createObjectName(object),
1189
+ visible: object.visible,
1190
+ locked: this.objectLocks.get(object) ?? false
1191
+ };
1192
+ if (object instanceof Textbox) {
1193
+ if (typeof object.fill !== "string") throw new Error(`Text object ${id} uses an unsupported non-string fill`);
1194
+ return {
1195
+ id,
1196
+ type: "text",
1197
+ ...state,
1198
+ transform,
1199
+ text: object.text,
1200
+ width: object.width,
1201
+ fontFamily: object.fontFamily,
1202
+ fontSize: object.fontSize,
1203
+ color: object.fill,
1204
+ fontWeight: object.fontWeight,
1205
+ fontStyle: object.fontStyle,
1206
+ underline: object.underline,
1207
+ textAlign: object.textAlign,
1208
+ lineHeight: object.lineHeight,
1209
+ charSpacing: object.charSpacing,
1210
+ ...object.backgroundColor ? { backgroundColor: object.backgroundColor } : {}
1211
+ };
1212
+ }
1213
+ if (object instanceof FabricImage) {
1214
+ const src = this.imageSources.get(object) ?? object.getSrc();
1215
+ if (!src || src.startsWith("blob:")) throw new Error(`Image object ${id} does not have a persistent source`);
1216
+ return {
1217
+ id,
1218
+ type: "image",
1219
+ ...state,
1220
+ transform,
1221
+ src,
1222
+ role: this.imageRoles.get(object) ?? "element"
1223
+ };
1224
+ }
1225
+ throw new Error(`Design object ${id} has an unsupported type`);
1226
+ }
1227
+ serializeTransform(object) {
1228
+ const center = object.getCenterPoint();
1229
+ return {
1230
+ x: center.x,
1231
+ y: center.y,
1232
+ scaleX: Math.abs(object.scaleX),
1233
+ scaleY: Math.abs(object.scaleY),
1234
+ rotation: object.angle,
1235
+ flipX: object.scaleX < 0 ? !object.flipX : object.flipX,
1236
+ flipY: object.scaleY < 0 ? !object.flipY : object.flipY
1237
+ };
1238
+ }
1239
+ async createObjectFromDesign(design) {
1240
+ const common = {
1241
+ left: design.transform.x,
1242
+ top: design.transform.y,
1243
+ originX: "center",
1244
+ originY: "center",
1245
+ scaleX: design.transform.scaleX,
1246
+ scaleY: design.transform.scaleY,
1247
+ angle: design.transform.rotation,
1248
+ flipX: design.transform.flipX,
1249
+ flipY: design.transform.flipY,
1250
+ visible: design.visible ?? true,
1251
+ ...this.objectControlAppearance()
1252
+ };
1253
+ if (design.type === "text") return new Textbox(design.text, {
1254
+ ...common,
1255
+ width: design.width,
1256
+ fontFamily: design.fontFamily,
1257
+ fontSize: design.fontSize,
1258
+ fontWeight: design.fontWeight ?? 700,
1259
+ fontStyle: design.fontStyle ?? "normal",
1260
+ underline: design.underline ?? false,
1261
+ fill: design.color,
1262
+ backgroundColor: design.backgroundColor ?? "",
1263
+ textAlign: design.textAlign ?? "center",
1264
+ lineHeight: design.lineHeight ?? 1.16,
1265
+ charSpacing: design.charSpacing ?? 0,
1266
+ editable: true
1267
+ });
1268
+ const image = await this.loadImage(design.src);
1269
+ image.set(common);
1270
+ return image;
1271
+ }
1272
+ loadImage(source) {
1273
+ return FabricImage.fromURL(source, source.startsWith("data:") ? void 0 : { crossOrigin: "anonymous" });
1274
+ }
1275
+ createObjectName(object) {
1276
+ if (object instanceof Textbox) return object.text.trim().slice(0, 48) || this.textObjectName;
1277
+ if (object instanceof FabricImage) return this.imageRoles.get(object) === "background" ? this.backgroundObjectName : this.imageObjectName;
1278
+ return "Object";
1279
+ }
1280
+ applyObjectLock(object, locked) {
1281
+ this.objectLocks.set(object, locked);
1282
+ object.set({
1283
+ hasBorders: !locked,
1284
+ hasControls: !locked,
1285
+ lockMovementX: locked,
1286
+ lockMovementY: locked,
1287
+ lockRotation: locked,
1288
+ lockScalingX: locked,
1289
+ lockScalingY: locked,
1290
+ lockSkewingX: locked,
1291
+ lockSkewingY: locked
1292
+ });
1293
+ if (object instanceof Textbox) object.set({ editable: !locked });
1294
+ }
1295
+ notifySelectionChange() {
1296
+ const objectIds = this.getSelectedObjectIds();
1297
+ this.selectionListeners.forEach((listener) => listener(objectIds));
1298
+ }
1299
+ removeDesignBackgrounds() {
1300
+ const backgrounds = this.canvas.getObjects().filter((object) => object instanceof FabricImage && this.imageRoles.get(object) === "background");
1301
+ if (backgrounds.length === 0) return;
1302
+ if (backgrounds.some((object) => this.canvas.getActiveObjects().includes(object))) this.canvas.discardActiveObject();
1303
+ this.canvas.remove(...backgrounds);
1304
+ backgrounds.forEach((object) => {
1305
+ this.unregisterObject(object);
1306
+ object.dispose();
1307
+ });
1308
+ }
1309
+ scheduleHistoryCommit() {
1310
+ if (this.historyBusy) return;
1311
+ if (this.historyTimer !== void 0) clearTimeout(this.historyTimer);
1312
+ this.historyTimer = setTimeout(() => {
1313
+ this.historyTimer = void 0;
1314
+ this.commitHistory();
1315
+ }, 320);
1316
+ }
1317
+ flushHistoryCommit() {
1318
+ if (this.historyTimer === void 0) return;
1319
+ clearTimeout(this.historyTimer);
1320
+ this.historyTimer = void 0;
1321
+ this.commitHistory();
1322
+ }
1323
+ commitHistory() {
1324
+ if (this.historyBusy) return;
1325
+ if (this.historyTimer !== void 0) {
1326
+ clearTimeout(this.historyTimer);
1327
+ this.historyTimer = void 0;
1328
+ }
1329
+ const snapshot = this.saveDesign();
1330
+ const signature = JSON.stringify(snapshot);
1331
+ if (signature === this.historySignature) return;
1332
+ this.history.push(snapshot);
1333
+ this.historySignature = signature;
1334
+ this.notifyHistoryChange();
1335
+ }
1336
+ notifyHistoryChange() {
1337
+ const state = this.history.state;
1338
+ this.historyListeners.forEach((listener) => listener(state));
1339
+ }
1340
+ constrainObjectToCanvas(object) {
1341
+ object.setCoords();
1342
+ let bounds = object.getBoundingRect();
1343
+ const scale = calculateContainmentScale(bounds, this.width, this.height);
1344
+ if (scale < 1) {
1345
+ object.set({
1346
+ scaleX: object.scaleX * scale,
1347
+ scaleY: object.scaleY * scale
1348
+ });
1349
+ object.setCoords();
1350
+ bounds = object.getBoundingRect();
1351
+ }
1352
+ const offset = calculateContainmentOffset(bounds, this.width, this.height);
1353
+ if (offset.x !== 0 || offset.y !== 0) {
1354
+ object.set({
1355
+ left: object.left + offset.x,
1356
+ top: object.top + offset.y
1357
+ });
1358
+ object.setCoords();
1359
+ }
1360
+ }
1361
+ resizeDisplay() {
1362
+ const availableWidth = Math.max(this.host.clientWidth - EDITOR_DISPLAY_GUTTER, 1);
1363
+ const availableHeight = Math.max(this.host.clientHeight - EDITOR_DISPLAY_GUTTER, 1);
1364
+ const scale = Math.min(availableWidth / this.width, availableHeight / this.height, 1);
1365
+ this.canvas.setDimensions({
1366
+ width: `${Math.floor(this.width * scale)}px`,
1367
+ height: `${Math.floor(this.height * scale)}px`
1368
+ }, { cssOnly: true });
1369
+ }
1370
+ applySelection(objects) {
1371
+ this.canvas.discardActiveObject();
1372
+ this.canvas.setActiveObject(objects.length === 1 ? objects[0] : new ActiveSelection(objects, { canvas: this.canvas }));
1373
+ }
1374
+ objectControlAppearance() {
1375
+ return {
1376
+ transparentCorners: false,
1377
+ cornerColor: this.appearance.controlFill,
1378
+ cornerStrokeColor: this.appearance.controlBorder,
1379
+ borderColor: this.appearance.objectBorder,
1380
+ cornerSize: this.appearance.controlSize
1381
+ };
1382
+ }
1383
+ validateTransformOptions(options) {
1384
+ for (const [name, value] of [
1385
+ ["x", options.x],
1386
+ ["y", options.y],
1387
+ ["rotation", options.rotation]
1388
+ ]) if (value !== void 0 && !Number.isFinite(value)) throw new TypeError(`${name} must be a finite number`);
1389
+ for (const [name, value] of [["scaleX", options.scaleX], ["scaleY", options.scaleY]]) if (value !== void 0 && (!Number.isFinite(value) || value <= 0)) throw new RangeError(`${name} must be greater than zero`);
1390
+ for (const [name, value] of [["flipX", options.flipX], ["flipY", options.flipY]]) if (value !== void 0 && typeof value !== "boolean") throw new TypeError(`${name} must be a boolean`);
1391
+ }
1392
+ fitImageToEditableBounds(image) {
1393
+ const bounds = this.editableBounds;
1394
+ image.set({
1395
+ left: bounds.left + bounds.width / 2,
1396
+ top: bounds.top + bounds.height / 2,
1397
+ angle: 0,
1398
+ scaleX: bounds.width / Math.max(image.width, 1),
1399
+ scaleY: bounds.height / Math.max(image.height, 1)
1400
+ });
1401
+ image.setCoords();
1402
+ }
1403
+ renderTextureCanvas() {
1404
+ this.renderingTexture = true;
1405
+ try {
1406
+ this.textureRenderer.renderTexture(this.textureContext);
1407
+ } finally {
1408
+ this.renderingTexture = false;
1409
+ }
1410
+ }
1411
+ markRenderState() {
1412
+ if (this.host.dataset.renderState === "nonblank") return;
1413
+ const context = this.canvas.getContext();
1414
+ let minimum = 255;
1415
+ let maximum = 0;
1416
+ let opaqueSamples = 0;
1417
+ for (let row = 1; row < 8; row += 1) for (let column = 1; column < 16; column += 1) {
1418
+ const x = Math.floor(column / 16 * this.width);
1419
+ const y = Math.floor(row / 8 * this.height);
1420
+ const pixel = context.getImageData(x, y, 1, 1).data;
1421
+ const luminance = (pixel[0] + pixel[1] + pixel[2]) / 3;
1422
+ minimum = Math.min(minimum, luminance);
1423
+ maximum = Math.max(maximum, luminance);
1424
+ if (pixel[3] > 0) opaqueSamples += 1;
1425
+ }
1426
+ if (opaqueSamples > 0 && maximum - minimum > 8) this.host.dataset.renderState = "nonblank";
1427
+ }
1428
+ };
1429
+ //#endregion
1430
+ //#region src/bridge/TextureBridge.ts
1431
+ /**
1432
+ * 将二维编辑画布转换为 Three.js 实时纹理
1433
+ *
1434
+ * 多次画布渲染会合并到下一个动画帧,避免重复标记纹理更新
1435
+ */
1436
+ var TextureBridge = class {
1437
+ /** 绑定到三维产品材质的实时 CanvasTexture */
1438
+ texture;
1439
+ stopListening;
1440
+ updateFrame = 0;
1441
+ /**
1442
+ * @param editor 提供不含交互控件的纹理 Canvas 和渲染事件的二维编辑器
1443
+ * @param viewer 接收实时纹理的三维查看器
1444
+ * @param flipY 是否垂直翻转纹理
1445
+ */
1446
+ constructor(editor, viewer, flipY) {
1447
+ this.texture = new CanvasTexture(editor.textureCanvas);
1448
+ this.texture.colorSpace = SRGBColorSpace;
1449
+ this.texture.flipY = flipY;
1450
+ this.texture.anisotropy = 4;
1451
+ viewer.setTexture(this.texture);
1452
+ this.stopListening = editor.onRender(() => this.scheduleUpdate());
1453
+ this.scheduleUpdate();
1454
+ }
1455
+ /**
1456
+ * 更新纹理垂直翻转状态并立即标记刷新
1457
+ *
1458
+ * @param flipY 是否垂直翻转纹理
1459
+ */
1460
+ setFlipY(flipY) {
1461
+ this.texture.flipY = flipY;
1462
+ this.texture.needsUpdate = true;
1463
+ }
1464
+ /** 取消编辑器订阅、动画帧并释放 CanvasTexture */
1465
+ destroy() {
1466
+ this.stopListening();
1467
+ cancelAnimationFrame(this.updateFrame);
1468
+ this.texture.dispose();
1469
+ }
1470
+ /** 将同一帧内的多次画布渲染合并为一次纹理更新 */
1471
+ scheduleUpdate() {
1472
+ if (this.updateFrame) return;
1473
+ this.updateFrame = requestAnimationFrame(() => {
1474
+ this.updateFrame = 0;
1475
+ this.texture.needsUpdate = true;
1476
+ });
1477
+ }
1478
+ };
1479
+ //#endregion
1480
+ //#region src/viewer/assets/cup_decal_small_margins.glb?url&no-inline
1481
+ var cup_decal_small_margins_default = "" + new URL("cup_decal_small_margins.glb", import.meta.url).href;
1482
+ //#endregion
1483
+ //#region src/viewer/uvLayout.ts
1484
+ var UV_EDGE_PRECISION = 1e6;
1485
+ function createPointKey(u, v) {
1486
+ return `${Math.round(u * UV_EDGE_PRECISION)},${Math.round(v * UV_EDGE_PRECISION)}`;
1487
+ }
1488
+ function extractBoundaryCoordinates(triangleCoordinates) {
1489
+ const edges = /* @__PURE__ */ new Map();
1490
+ for (let index = 0; index < triangleCoordinates.length; index += 6) {
1491
+ const points = [
1492
+ [triangleCoordinates[index], triangleCoordinates[index + 1]],
1493
+ [triangleCoordinates[index + 2], triangleCoordinates[index + 3]],
1494
+ [triangleCoordinates[index + 4], triangleCoordinates[index + 5]]
1495
+ ];
1496
+ for (const [startIndex, endIndex] of [
1497
+ [0, 1],
1498
+ [1, 2],
1499
+ [2, 0]
1500
+ ]) {
1501
+ const start = points[startIndex];
1502
+ const end = points[endIndex];
1503
+ const startKey = createPointKey(start[0], start[1]);
1504
+ const endKey = createPointKey(end[0], end[1]);
1505
+ const edgeKey = startKey < endKey ? `${startKey}|${endKey}` : `${endKey}|${startKey}`;
1506
+ const edge = edges.get(edgeKey);
1507
+ if (edge) edge.occurrences += 1;
1508
+ else edges.set(edgeKey, {
1509
+ coordinates: [
1510
+ start[0],
1511
+ start[1],
1512
+ end[0],
1513
+ end[1]
1514
+ ],
1515
+ occurrences: 1
1516
+ });
1517
+ }
1518
+ }
1519
+ return new Float32Array([...edges.values()].filter((edge) => edge.occurrences === 1).flatMap((edge) => edge.coordinates));
1520
+ }
1521
+ /**
1522
+ * 提取目标 Mesh 第一个材质槽使用的 UV 三角形
1523
+ *
1524
+ * @param mesh 接收实时纹理的目标 Mesh
1525
+ * @returns 保持模型原始 V 方向的 UV 三角形和外边界布局
1526
+ * @throws Mesh 缺少 UV、面数据无效或第一个材质槽没有三角形时抛出错误
1527
+ */
1528
+ function extractUvLayout(mesh) {
1529
+ const geometry = mesh.geometry;
1530
+ const uv = geometry.getAttribute("uv");
1531
+ if (!uv) throw new Error(`Customizable mesh does not contain UV coordinates: ${mesh.name}`);
1532
+ const index = geometry.getIndex();
1533
+ const elementCount = index?.count ?? uv.count;
1534
+ const ranges = Array.isArray(mesh.material) && geometry.groups.length > 0 ? geometry.groups.filter((group) => (group.materialIndex ?? 0) === 0).map(({ start, count }) => ({
1535
+ start,
1536
+ count
1537
+ })) : [{
1538
+ start: 0,
1539
+ count: elementCount
1540
+ }];
1541
+ const coordinateCount = ranges.reduce((total, range) => {
1542
+ if (!Number.isInteger(range.start) || !Number.isInteger(range.count) || range.start < 0 || range.count < 0 || range.start + range.count > elementCount || range.count % 3 !== 0) throw new Error(`Customizable mesh has invalid triangle groups: ${mesh.name}`);
1543
+ return total + range.count * 2;
1544
+ }, 0);
1545
+ if (coordinateCount === 0) throw new Error(`Customizable mesh has no triangles in its first material slot: ${mesh.name}`);
1546
+ const triangleCoordinates = new Float32Array(coordinateCount);
1547
+ let targetIndex = 0;
1548
+ for (const range of ranges) for (let offset = range.start; offset < range.start + range.count; offset += 1) {
1549
+ const vertexIndex = index ? index.getX(offset) : offset;
1550
+ const u = uv.getX(vertexIndex);
1551
+ const v = uv.getY(vertexIndex);
1552
+ if (!Number.isFinite(u) || !Number.isFinite(v)) throw new Error(`Customizable mesh has invalid UV coordinates: ${mesh.name}`);
1553
+ triangleCoordinates[targetIndex] = u;
1554
+ triangleCoordinates[targetIndex + 1] = v;
1555
+ targetIndex += 2;
1556
+ }
1557
+ return {
1558
+ triangleCoordinates,
1559
+ boundaryCoordinates: extractBoundaryCoordinates(triangleCoordinates)
1560
+ };
1561
+ }
1562
+ //#endregion
1563
+ //#region src/viewer/ProductViewer.ts
1564
+ var DEFAULT_PRODUCT_HEIGHT = 2.35;
1565
+ var DEFAULT_PRODUCT_BASE_Y = -1.17;
1566
+ var DEFAULT_PRODUCT_ROTATION = MathUtils.degToRad(-72);
1567
+ var DEFAULT_CAMERA_AZIMUTH = MathUtils.degToRad(18);
1568
+ var DEFAULT_CAMERA_ELEVATION = MathUtils.degToRad(10);
1569
+ var CAMERA_VIEWPORT_FILL = .7;
1570
+ /**
1571
+ * 基于 Three.js 的三维产品查看器
1572
+ *
1573
+ * 负责模型加载、目标 Mesh 查找、实时纹理绑定、相机控制和资源释放
1574
+ * 当前只将纹理应用到目标 Mesh 的第一个材质槽
1575
+ */
1576
+ var ProductViewer = class {
1577
+ host;
1578
+ scene = new Scene();
1579
+ camera = new PerspectiveCamera(35, 1, .05, 100);
1580
+ renderer;
1581
+ controls;
1582
+ loader = new GLTFLoader();
1583
+ resizeObserver;
1584
+ productRoot;
1585
+ surface;
1586
+ texture;
1587
+ animationFrame = 0;
1588
+ viewChangeListeners = /* @__PURE__ */ new Set();
1589
+ handleControlsChange = () => {
1590
+ const state = this.getViewState();
1591
+ this.viewChangeListeners.forEach((listener) => listener(state));
1592
+ };
1593
+ /**
1594
+ * @param host 三维查看器挂载容器
1595
+ * @param ariaLabel 三维产品画布的无障碍名称
1596
+ * @param appearance WebGL 画布清屏颜色等外观配置
1597
+ */
1598
+ constructor(host, ariaLabel = "Interactive 3D product preview", appearance = {}) {
1599
+ this.host = host;
1600
+ host.replaceChildren();
1601
+ this.renderer = new WebGLRenderer({
1602
+ antialias: true,
1603
+ alpha: true
1604
+ });
1605
+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
1606
+ this.renderer.outputColorSpace = SRGBColorSpace;
1607
+ this.renderer.toneMapping = ACESFilmicToneMapping;
1608
+ this.renderer.toneMappingExposure = 1.05;
1609
+ if (appearance.backgroundColor?.trim()) this.renderer.setClearColor(appearance.backgroundColor.trim(), 1);
1610
+ this.renderer.domElement.setAttribute("aria-label", ariaLabel);
1611
+ this.renderer.domElement.classList.add("customforge-viewer-canvas");
1612
+ host.append(this.renderer.domElement);
1613
+ host.dataset.renderState = "pending";
1614
+ this.camera.position.set(4.6, 2.8, 5.8);
1615
+ this.controls = new OrbitControls(this.camera, this.renderer.domElement);
1616
+ this.controls.enableDamping = true;
1617
+ this.controls.minDistance = 3.2;
1618
+ this.controls.maxDistance = 11;
1619
+ this.controls.target.set(0, 0, 0);
1620
+ this.controls.addEventListener("change", this.handleControlsChange);
1621
+ this.addStudioLighting();
1622
+ this.resizeObserver = new ResizeObserver(() => this.resize());
1623
+ this.resizeObserver.observe(host);
1624
+ this.resize();
1625
+ this.render();
1626
+ }
1627
+ /**
1628
+ * 加载远程模型或随包提供的默认 GLB 模型
1629
+ *
1630
+ * @param product 已完成默认值补全的产品配置
1631
+ * @returns 目标 Mesh 第一个材质槽使用的 UV 三角形布局
1632
+ * @throws 模型加载失败、找不到目标 Mesh 或目标 Mesh 缺少有效 UV 时抛出错误
1633
+ */
1634
+ async loadProduct(product) {
1635
+ this.removeProduct();
1636
+ if (product.modelUrl) {
1637
+ const gltf = await this.loader.loadAsync(product.modelUrl);
1638
+ this.productRoot = gltf.scene;
1639
+ this.surface = this.findSurface(gltf.scene, product.surfaceMesh);
1640
+ } else {
1641
+ const gltf = await this.loader.loadAsync(cup_decal_small_margins_default);
1642
+ this.productRoot = gltf.scene;
1643
+ this.surface = this.findSurface(gltf.scene, product.surfaceMesh);
1644
+ this.prepareBundledProduct(gltf.scene, this.surface);
1645
+ }
1646
+ const surface = this.surface;
1647
+ if (!surface) throw new Error("Customizable mesh was not initialized");
1648
+ const uvLayout = extractUvLayout(surface);
1649
+ this.scene.add(this.productRoot);
1650
+ if (this.texture) this.attachTexture(this.texture);
1651
+ this.fitCamera(this.productRoot);
1652
+ return uvLayout;
1653
+ }
1654
+ /**
1655
+ * 保存并绑定二维编辑器生成的实时纹理
1656
+ *
1657
+ * 如果模型尚未加载,纹理会在模型加载完成后自动绑定
1658
+ *
1659
+ * @param texture 由二维画布创建的 CanvasTexture
1660
+ */
1661
+ setTexture(texture) {
1662
+ this.texture = texture;
1663
+ if (this.surface) this.attachTexture(texture);
1664
+ }
1665
+ /** 根据当前模型包围盒恢复默认相机位置 */
1666
+ resetView() {
1667
+ if (this.productRoot) this.fitCamera(this.productRoot);
1668
+ }
1669
+ /** 返回当前相机位置和轨道控制目标点的独立快照 */
1670
+ getViewState() {
1671
+ return {
1672
+ position: this.vectorToValue(this.camera.position),
1673
+ target: this.vectorToValue(this.controls.target)
1674
+ };
1675
+ }
1676
+ /**
1677
+ * 恢复相机位置和轨道控制目标点
1678
+ *
1679
+ * @param state 要恢复的三维观察视角
1680
+ * @returns 应用后的独立视角快照
1681
+ * @throws 坐标不是有限数值或相机与目标点重合时抛出错误
1682
+ */
1683
+ setViewState(state) {
1684
+ this.validateViewState(state);
1685
+ this.camera.position.set(state.position.x, state.position.y, state.position.z);
1686
+ this.controls.target.set(state.target.x, state.target.y, state.target.z);
1687
+ this.camera.updateProjectionMatrix();
1688
+ this.controls.update();
1689
+ return this.getViewState();
1690
+ }
1691
+ /**
1692
+ * 订阅三维视角变化
1693
+ *
1694
+ * 用户旋转、缩放、平移以及 API 恢复视角时都会触发
1695
+ *
1696
+ * @param listener 接收独立视角快照的监听函数
1697
+ * @returns 用于取消本次订阅的函数
1698
+ */
1699
+ onViewChange(listener) {
1700
+ this.viewChangeListeners.add(listener);
1701
+ return () => this.viewChangeListeners.delete(listener);
1702
+ }
1703
+ /** 释放动画帧、相机控制、模型材质和 WebGLRenderer */
1704
+ destroy() {
1705
+ cancelAnimationFrame(this.animationFrame);
1706
+ this.resizeObserver.disconnect();
1707
+ this.controls.removeEventListener("change", this.handleControlsChange);
1708
+ this.controls.dispose();
1709
+ this.viewChangeListeners.clear();
1710
+ this.removeProduct();
1711
+ this.renderer.dispose();
1712
+ this.renderer.domElement.remove();
1713
+ }
1714
+ addStudioLighting() {
1715
+ this.scene.add(new AmbientLight("#ffffff", .9));
1716
+ const key = new DirectionalLight("#ffffff", 2.1);
1717
+ key.position.set(4, 5, 6);
1718
+ this.scene.add(key);
1719
+ const fill = new DirectionalLight("#e8f0f2", 1.15);
1720
+ fill.position.set(-5, 2, 4);
1721
+ this.scene.add(fill);
1722
+ const rim = new DirectionalLight("#ffffff", .8);
1723
+ rim.position.set(1, 4, -5);
1724
+ this.scene.add(rim);
1725
+ }
1726
+ prepareBundledProduct(root, surface) {
1727
+ surface.renderOrder = 1;
1728
+ (Array.isArray(surface.material) ? surface.material : [surface.material]).forEach((material) => {
1729
+ material.depthWrite = false;
1730
+ material.polygonOffset = true;
1731
+ material.polygonOffsetFactor = -1;
1732
+ material.polygonOffsetUnits = -1;
1733
+ });
1734
+ const initialHeight = new Box3().setFromObject(root).getSize(new Vector3()).y;
1735
+ if (!Number.isFinite(initialHeight) || initialHeight <= 0) throw new Error("The bundled product has invalid bounds");
1736
+ root.scale.multiplyScalar(DEFAULT_PRODUCT_HEIGHT / initialHeight);
1737
+ root.rotation.y = DEFAULT_PRODUCT_ROTATION;
1738
+ root.updateMatrixWorld(true);
1739
+ const bounds = new Box3().setFromObject(root);
1740
+ const center = bounds.getCenter(new Vector3());
1741
+ root.position.x -= center.x;
1742
+ root.position.y += DEFAULT_PRODUCT_BASE_Y - bounds.min.y;
1743
+ root.position.z -= center.z;
1744
+ root.updateMatrixWorld(true);
1745
+ }
1746
+ /**
1747
+ * 按名称查找接收实时纹理的 Mesh
1748
+ *
1749
+ * @throws 找不到对象或同名对象不是 Mesh 时抛出错误
1750
+ */
1751
+ findSurface(root, meshName) {
1752
+ const object = root.getObjectByName(meshName);
1753
+ if (!(object instanceof Mesh)) throw new Error(`Customizable mesh was not found: ${meshName}`);
1754
+ return object;
1755
+ }
1756
+ /**
1757
+ * 将纹理应用到目标 Mesh 的第一个材质槽
1758
+ *
1759
+ * 非 MeshStandardMaterial 会被替换为基础标准材质
1760
+ */
1761
+ attachTexture(texture) {
1762
+ if (!this.surface) return;
1763
+ const material = (Array.isArray(this.surface.material) ? this.surface.material : [this.surface.material])[0];
1764
+ if (!(material instanceof MeshStandardMaterial)) {
1765
+ const replacement = new MeshStandardMaterial({
1766
+ color: "#ffffff",
1767
+ roughness: .45,
1768
+ map: texture
1769
+ });
1770
+ this.surface.material = replacement;
1771
+ return;
1772
+ }
1773
+ material.map = texture;
1774
+ material.color.set("#ffffff");
1775
+ material.needsUpdate = true;
1776
+ }
1777
+ fitCamera(root, direction) {
1778
+ const bounds = new Box3().setFromObject(root);
1779
+ const size = bounds.getSize(new Vector3());
1780
+ const center = bounds.getCenter(new Vector3());
1781
+ const diagonal = size.length();
1782
+ if (!Number.isFinite(diagonal) || diagonal <= 0) throw new Error("The product has invalid bounds");
1783
+ const viewDirection = direction?.clone() ?? this.defaultCameraDirection();
1784
+ if (viewDirection.lengthSq() === 0) viewDirection.copy(this.defaultCameraDirection());
1785
+ viewDirection.normalize();
1786
+ const right = new Vector3().crossVectors(this.camera.up, viewDirection);
1787
+ if (right.lengthSq() < 1e-8) right.set(1, 0, 0);
1788
+ else right.normalize();
1789
+ const up = new Vector3().crossVectors(viewDirection, right).normalize();
1790
+ const verticalSlope = Math.tan(MathUtils.degToRad(this.camera.fov / 2)) * CAMERA_VIEWPORT_FILL;
1791
+ const horizontalSlope = verticalSlope * Math.max(this.camera.aspect, .1);
1792
+ let distance = 0;
1793
+ for (const x of [bounds.min.x, bounds.max.x]) for (const y of [bounds.min.y, bounds.max.y]) for (const z of [bounds.min.z, bounds.max.z]) {
1794
+ const offset = new Vector3(x, y, z).sub(center);
1795
+ const depth = offset.dot(viewDirection);
1796
+ distance = Math.max(distance, depth + Math.abs(offset.dot(right)) / horizontalSlope, depth + Math.abs(offset.dot(up)) / verticalSlope);
1797
+ }
1798
+ distance = Math.max(distance, diagonal * .55, .1);
1799
+ this.controls.target.copy(center);
1800
+ this.camera.position.copy(center).addScaledVector(viewDirection, distance);
1801
+ this.camera.near = Math.max(Math.min(distance * .02, diagonal * .01), .01);
1802
+ this.camera.far = Math.max(distance + diagonal * 2, 10);
1803
+ this.camera.updateProjectionMatrix();
1804
+ this.controls.minDistance = Math.max(diagonal * .45, distance * .3, .05);
1805
+ this.controls.maxDistance = Math.max(distance * 4, diagonal * 4);
1806
+ this.controls.update();
1807
+ }
1808
+ defaultCameraDirection() {
1809
+ const horizontal = Math.cos(DEFAULT_CAMERA_ELEVATION);
1810
+ return new Vector3(horizontal * Math.sin(DEFAULT_CAMERA_AZIMUTH), Math.sin(DEFAULT_CAMERA_ELEVATION), horizontal * Math.cos(DEFAULT_CAMERA_AZIMUTH));
1811
+ }
1812
+ vectorToValue(vector) {
1813
+ return {
1814
+ x: vector.x,
1815
+ y: vector.y,
1816
+ z: vector.z
1817
+ };
1818
+ }
1819
+ validateViewState(state) {
1820
+ if (![
1821
+ state.position.x,
1822
+ state.position.y,
1823
+ state.position.z,
1824
+ state.target.x,
1825
+ state.target.y,
1826
+ state.target.z
1827
+ ].every(Number.isFinite)) throw new TypeError("View position and target must contain finite numbers");
1828
+ if ((state.position.x - state.target.x) ** 2 + (state.position.y - state.target.y) ** 2 + (state.position.z - state.target.z) ** 2 <= Number.EPSILON) throw new RangeError("View position and target must not be identical");
1829
+ }
1830
+ removeProduct() {
1831
+ if (!this.productRoot) return;
1832
+ this.scene.remove(this.productRoot);
1833
+ this.productRoot.traverse((object) => {
1834
+ if (!(object instanceof Mesh)) return;
1835
+ object.geometry.dispose();
1836
+ (Array.isArray(object.material) ? object.material : [object.material]).forEach((material) => material.dispose());
1837
+ });
1838
+ this.productRoot = void 0;
1839
+ this.surface = void 0;
1840
+ }
1841
+ resize() {
1842
+ const width = Math.max(this.host.clientWidth, 1);
1843
+ const height = Math.max(this.host.clientHeight, 1);
1844
+ const direction = this.camera.position.clone().sub(this.controls.target);
1845
+ this.renderer.setSize(width, height, false);
1846
+ this.camera.aspect = width / height;
1847
+ if (this.productRoot && direction.lengthSq() > 0) this.fitCamera(this.productRoot, direction);
1848
+ else this.camera.updateProjectionMatrix();
1849
+ }
1850
+ render = () => {
1851
+ this.animationFrame = requestAnimationFrame(this.render);
1852
+ this.controls.update();
1853
+ this.renderer.render(this.scene, this.camera);
1854
+ this.markRenderState();
1855
+ };
1856
+ markRenderState() {
1857
+ if (this.host.dataset.renderState === "nonblank") return;
1858
+ const context = this.renderer.getContext();
1859
+ const width = context.drawingBufferWidth;
1860
+ const height = context.drawingBufferHeight;
1861
+ if (width < 2 || height < 2) return;
1862
+ const pixel = /* @__PURE__ */ new Uint8Array(4);
1863
+ let minimum = 255;
1864
+ let maximum = 0;
1865
+ for (const xRatio of [
1866
+ .25,
1867
+ .5,
1868
+ .75
1869
+ ]) for (const yRatio of [
1870
+ .25,
1871
+ .5,
1872
+ .75
1873
+ ]) {
1874
+ context.readPixels(Math.floor(width * xRatio), Math.floor(height * yRatio), 1, 1, context.RGBA, context.UNSIGNED_BYTE, pixel);
1875
+ const luminance = (pixel[0] + pixel[1] + pixel[2]) / 3;
1876
+ minimum = Math.min(minimum, luminance);
1877
+ maximum = Math.max(maximum, luminance);
1878
+ }
1879
+ if (maximum - minimum > 8) this.host.dataset.renderState = "nonblank";
1880
+ }
1881
+ };
1882
+ //#endregion
1883
+ //#region src/customizer/ProductCustomizer.ts
1884
+ /**
1885
+ * 统一管理二维编辑器、三维查看器和实时纹理同步
1886
+ *
1887
+ * 仅支持具有 DOM、Canvas、WebGL 和 ResizeObserver 的浏览器环境
1888
+ * 每个实例独立持有 DOM 事件、Fabric 状态和 WebGL 资源
1889
+ * 不再使用实例时必须调用 `destroy()`
1890
+ */
1891
+ var ProductCustomizer = class ProductCustomizer {
1892
+ events = new EventTarget();
1893
+ textureBridge;
1894
+ editor;
1895
+ viewer;
1896
+ product;
1897
+ stopSelectionListener;
1898
+ stopRenderListener;
1899
+ stopHistoryListener;
1900
+ stopViewListener;
1901
+ destroyed = false;
1902
+ constructor(options) {
1903
+ const editorHost = resolveElement(options.editor, "Editor");
1904
+ const viewerHost = resolveElement(options.viewer, "Viewer");
1905
+ if (editorHost === viewerHost) throw new Error("Editor and viewer must use different elements");
1906
+ const historyLimit = options.historyLimit ?? 50;
1907
+ if (!Number.isInteger(historyLimit) || historyLimit < 1) throw new RangeError("historyLimit must be a positive integer");
1908
+ this.product = normalizeProductConfiguration(options.product);
1909
+ this.editor = new DesignEditor(editorHost, {
1910
+ width: options.editorWidth ?? 1024,
1911
+ height: options.editorHeight ?? 512,
1912
+ historyLimit,
1913
+ ariaLabel: options.editorAriaLabel,
1914
+ defaultText: options.defaultText,
1915
+ textObjectName: options.textObjectName,
1916
+ imageObjectName: options.imageObjectName,
1917
+ backgroundObjectName: options.backgroundObjectName,
1918
+ appearance: options.appearance?.editor
1919
+ });
1920
+ this.viewer = new ProductViewer(viewerHost, options.viewerAriaLabel, options.appearance?.viewer);
1921
+ this.textureBridge = new TextureBridge(this.editor, this.viewer, this.product.textureFlipY);
1922
+ this.stopSelectionListener = this.editor.onSelectionChange((objectIds) => {
1923
+ this.emit("selectionchange", {
1924
+ hasSelection: objectIds.length > 0,
1925
+ objectIds
1926
+ });
1927
+ });
1928
+ this.stopRenderListener = this.editor.onRender(() => {
1929
+ this.emit("change", { objectCount: this.editor.objectCount });
1930
+ });
1931
+ this.stopHistoryListener = this.editor.onHistoryChange((state) => {
1932
+ this.emit("historychange", state);
1933
+ });
1934
+ this.stopViewListener = this.viewer.onViewChange((state) => {
1935
+ this.emit("viewchange", state);
1936
+ });
1937
+ }
1938
+ /**
1939
+ * 创建实例并完成初始产品加载
1940
+ *
1941
+ * @param options 产品定制器初始化配置
1942
+ * @returns 初始化完成的产品定制器实例
1943
+ * @throws DOM 容器无效或初始化失败时释放已创建资源并继续抛出原始错误
1944
+ */
1945
+ static async create(options) {
1946
+ const customizer = new ProductCustomizer(options);
1947
+ try {
1948
+ await customizer.initialize();
1949
+ return customizer;
1950
+ } catch (error) {
1951
+ customizer.destroy();
1952
+ throw error;
1953
+ }
1954
+ }
1955
+ /**
1956
+ * 订阅产品定制器事件
1957
+ *
1958
+ * @param event 事件名称
1959
+ * @param listener 接收对应事件载荷的监听函数
1960
+ * @returns 用于取消本次订阅的函数
1961
+ */
1962
+ on(event, listener) {
1963
+ const wrapped = (browserEvent) => {
1964
+ listener(browserEvent.detail);
1965
+ };
1966
+ this.events.addEventListener(event, wrapped);
1967
+ return () => this.events.removeEventListener(event, wrapped);
1968
+ }
1969
+ /**
1970
+ * 在二维画布中添加并选中一个文字对象
1971
+ *
1972
+ * 创建后和用户变换期间,对象会自动缩放或平移以保持完整可见
1973
+ *
1974
+ * @param options 文字内容、位置和样式配置
1975
+ * @returns 创建后的可持久化文字对象快照
1976
+ */
1977
+ addText(options) {
1978
+ return this.editor.addText(options);
1979
+ }
1980
+ /**
1981
+ * 加载图片并将其添加到二维画布
1982
+ *
1983
+ * role 为 background 时会替换已有设计背景、铺满当前 UV 可打印区域并默认锁定在最底层
1984
+ * 创建后和用户变换期间,对象会自动缩放或平移以保持完整可见
1985
+ *
1986
+ * @param options 图片地址、位置和显示宽度
1987
+ * @returns 创建后的可持久化图片对象快照
1988
+ * @throws 图片无法访问、加载失败或被 CORS 策略阻止时抛出错误
1989
+ */
1990
+ async addImage(options) {
1991
+ try {
1992
+ return await this.editor.addImage(options);
1993
+ } catch (error) {
1994
+ this.reportError(error);
1995
+ throw error;
1996
+ }
1997
+ }
1998
+ /** 返回产品、画布、对象、选区、历史和视角的独立状态快照 */
1999
+ getState() {
2000
+ return {
2001
+ product: this.getProduct(),
2002
+ canvas: this.getCanvasSize(),
2003
+ printableBounds: this.getPrintableBounds(),
2004
+ objects: this.getObjects(),
2005
+ selectedObjectIds: this.getSelectedObjectIds(),
2006
+ history: {
2007
+ canUndo: this.canUndo(),
2008
+ canRedo: this.canRedo()
2009
+ },
2010
+ view: this.getViewState()
2011
+ };
2012
+ }
2013
+ /** 返回当前补全默认值后的产品配置独立快照 */
2014
+ getProduct() {
2015
+ return { ...this.product };
2016
+ }
2017
+ /** 返回当前二维逻辑画布尺寸 */
2018
+ getCanvasSize() {
2019
+ return this.editor.getCanvasSize();
2020
+ }
2021
+ /** 返回当前产品 UV 在逻辑画布中的可打印包围框 */
2022
+ getPrintableBounds() {
2023
+ return this.editor.getPrintableBounds();
2024
+ }
2025
+ /**
2026
+ * 返回当前可编辑对象的独立快照
2027
+ *
2028
+ * @returns 按画布层级从后到前排列的 Design JSON 对象
2029
+ */
2030
+ getObjects() {
2031
+ return this.editor.getObjects();
2032
+ }
2033
+ /** 当前选中对象的 ID,按画布层级从后到前排列 */
2034
+ getSelectedObjectIds() {
2035
+ return this.editor.getSelectedObjectIds();
2036
+ }
2037
+ /**
2038
+ * 按稳定 ID 选中一个可见对象
2039
+ *
2040
+ * @param id Design JSON 中的对象 ID
2041
+ * @returns 是否找到并选中了对象
2042
+ */
2043
+ selectObject(id) {
2044
+ return this.editor.selectObject(id);
2045
+ }
2046
+ /**
2047
+ * 按稳定 ID 同时选中多个可见对象
2048
+ *
2049
+ * 所有 ID 都必须有效且可见,否则保持原选区不变;空数组清除选区
2050
+ *
2051
+ * @param ids Design JSON 中的对象 ID
2052
+ * @returns 是否应用了请求的选区
2053
+ */
2054
+ selectObjects(ids) {
2055
+ return this.editor.selectObjects(ids);
2056
+ }
2057
+ /**
2058
+ * 清除当前画布选区,不修改设计内容或历史记录
2059
+ *
2060
+ * @returns 清除前是否存在选中对象
2061
+ */
2062
+ clearSelection() {
2063
+ return this.editor.clearSelection();
2064
+ }
2065
+ /**
2066
+ * 按稳定 ID 删除一个对象
2067
+ *
2068
+ * @param id Design JSON 中的对象 ID
2069
+ * @returns 是否找到并删除了对象
2070
+ */
2071
+ removeObject(id) {
2072
+ return this.editor.removeObject(id);
2073
+ }
2074
+ /**
2075
+ * 将对象移动到指定图层索引
2076
+ *
2077
+ * @param id Design JSON 中的对象 ID
2078
+ * @param index 从 0 开始的索引,0 表示最底层
2079
+ * @returns 对象层级是否发生变化
2080
+ */
2081
+ moveObject(id, index) {
2082
+ return this.editor.moveObject(id, index);
2083
+ }
2084
+ /**
2085
+ * 将现有图片转换为铺满当前 UV 可打印区域的设计背景
2086
+ *
2087
+ * 转换会替换已有设计背景、重置旋转、锁定对象并移动到最底层
2088
+ *
2089
+ * @param id Design JSON 中的图片对象 ID
2090
+ * @returns 是否找到普通图片并完成转换
2091
+ */
2092
+ setImageAsBackground(id) {
2093
+ return this.editor.setImageAsBackground(id);
2094
+ }
2095
+ /**
2096
+ * 修改对象在图层面板中的名称
2097
+ *
2098
+ * @param id Design JSON 中的对象 ID
2099
+ * @param name 非空图层名称
2100
+ * @returns 是否找到并更新了对象
2101
+ */
2102
+ renameObject(id, name) {
2103
+ return this.editor.renameObject(id, name);
2104
+ }
2105
+ /**
2106
+ * 修改对象是否参与渲染
2107
+ *
2108
+ * @param id Design JSON 中的对象 ID
2109
+ * @param visible 是否参与二维画布、三维纹理和 PNG 渲染
2110
+ * @returns 是否找到并更新了对象
2111
+ */
2112
+ setObjectVisibility(id, visible) {
2113
+ return this.editor.setObjectVisibility(id, visible);
2114
+ }
2115
+ /**
2116
+ * 修改对象是否允许通过画布控件变换
2117
+ *
2118
+ * @param id Design JSON 中的对象 ID
2119
+ * @param locked 是否锁定移动、缩放、旋转、倾斜和文字编辑
2120
+ * @returns 是否找到并更新了对象
2121
+ */
2122
+ setObjectLocked(id, locked) {
2123
+ return this.editor.setObjectLocked(id, locked);
2124
+ }
2125
+ /**
2126
+ * 更新对象中心位置、缩放、旋转和翻转
2127
+ *
2128
+ * @param id Design JSON 中的对象 ID
2129
+ * @param options 要更新的变换字段
2130
+ * @returns 约束后的对象快照,找不到对象时返回 undefined
2131
+ * @throws 数值无效或缩放倍数不大于零时抛出错误
2132
+ */
2133
+ updateObjectTransform(id, options) {
2134
+ return this.editor.updateObjectTransform(id, options);
2135
+ }
2136
+ /**
2137
+ * 修改已有文字对象的内容和排版样式
2138
+ *
2139
+ * 连续调用会在短暂空闲后合并为一个撤销步骤
2140
+ *
2141
+ * @param id Design JSON 中的对象 ID
2142
+ * @param options 要修改的文字属性,未传字段保持不变
2143
+ * @returns 是否找到并更新了文字对象
2144
+ * @throws 字号、行高、字距、字重或 CSS 颜色不符合约束时抛出错误
2145
+ */
2146
+ updateText(id, options) {
2147
+ return this.editor.updateText(id, options);
2148
+ }
2149
+ /**
2150
+ * 让一个未锁定文字对象进入画布内联编辑状态
2151
+ *
2152
+ * @param id Design JSON 中的对象 ID
2153
+ * @returns 是否找到文字对象并进入编辑状态
2154
+ */
2155
+ editText(id) {
2156
+ return this.editor.editText(id);
2157
+ }
2158
+ /**
2159
+ * 删除二维编辑器中的当前对象或选区
2160
+ *
2161
+ * @returns 是否删除了至少一个对象
2162
+ */
2163
+ deleteSelected() {
2164
+ return this.editor.deleteSelected();
2165
+ }
2166
+ /**
2167
+ * 创建当前二维设计的版本化 JSON 快照
2168
+ *
2169
+ * 快照不包含产品模型、目标 Mesh 或基础纹理配置
2170
+ * Blob URL 图片会在添加时转换为 Data URL,因此返回值可以跨页面会话保存
2171
+ *
2172
+ * @returns 可以安全传给 JSON.stringify 的 DesignDocument
2173
+ * @throws 设计中存在不支持的对象或文字填充时抛出错误
2174
+ */
2175
+ saveDesign() {
2176
+ return this.editor.saveDesign();
2177
+ }
2178
+ /**
2179
+ * 校验并恢复版本化 Design JSON
2180
+ *
2181
+ * 图片全部加载成功后才替换当前二维对象,产品和基础纹理保持不变
2182
+ * 输入画布尺寸必须与当前编辑器的逻辑尺寸完全一致
2183
+ *
2184
+ * @param value JSON.parse 结果或符合 DesignDocument 的对象
2185
+ * @throws Schema 无效、画布尺寸不匹配或图片加载失败时抛出错误
2186
+ */
2187
+ async loadDesign(value) {
2188
+ this.emit("status", { message: "Loading design" });
2189
+ try {
2190
+ await this.editor.loadDesign(value);
2191
+ this.emit("status", { message: "Design loaded" });
2192
+ } catch (error) {
2193
+ this.reportError(error);
2194
+ throw error;
2195
+ }
2196
+ }
2197
+ /** 当前是否存在可以撤销的设计快照 */
2198
+ canUndo() {
2199
+ return this.editor.canUndo;
2200
+ }
2201
+ /** 当前是否存在可以重做的设计快照 */
2202
+ canRedo() {
2203
+ return this.editor.canRedo;
2204
+ }
2205
+ /**
2206
+ * 恢复上一个设计快照
2207
+ *
2208
+ * @returns 是否成功恢复了一个历史步骤
2209
+ * @throws 历史中的图片无法恢复时抛出错误
2210
+ */
2211
+ async undo() {
2212
+ try {
2213
+ const changed = await this.editor.undo();
2214
+ if (changed) this.emit("status", { message: "Undo complete" });
2215
+ return changed;
2216
+ } catch (error) {
2217
+ this.reportError(error);
2218
+ throw error;
2219
+ }
2220
+ }
2221
+ /**
2222
+ * 恢复下一个设计快照
2223
+ *
2224
+ * @returns 是否成功恢复了一个历史步骤
2225
+ * @throws 历史中的图片无法恢复时抛出错误
2226
+ */
2227
+ async redo() {
2228
+ try {
2229
+ const changed = await this.editor.redo();
2230
+ if (changed) this.emit("status", { message: "Redo complete" });
2231
+ return changed;
2232
+ } catch (error) {
2233
+ this.reportError(error);
2234
+ throw error;
2235
+ }
2236
+ }
2237
+ /** 以当前设计为起点清空撤销与重做历史 */
2238
+ clearHistory() {
2239
+ this.editor.clearHistory();
2240
+ }
2241
+ /**
2242
+ * 返回当前合成纹理的 PNG Data URL
2243
+ *
2244
+ * 结果与逻辑画布同尺寸,不包含选择框和 UV 辅助层
2245
+ *
2246
+ * @returns PNG Data URL
2247
+ * @throws 远程图片污染 Canvas 时抛出安全错误
2248
+ */
2249
+ getTextureDataUrl() {
2250
+ return this.editor.getTextureDataUrl();
2251
+ }
2252
+ /**
2253
+ * 异步返回当前合成纹理的 PNG Blob
2254
+ *
2255
+ * 结果与逻辑画布同尺寸,不包含选择框和 UV 辅助层
2256
+ *
2257
+ * @returns PNG Blob
2258
+ * @throws 远程图片污染 Canvas 或浏览器无法编码时抛出错误
2259
+ */
2260
+ getTextureBlob() {
2261
+ return this.editor.getTextureBlob();
2262
+ }
2263
+ /**
2264
+ * 将当前二维设计合成为 PNG 并触发浏览器下载
2265
+ *
2266
+ * @param filename 下载文件名,默认为 `custom-texture.png`
2267
+ * @throws 远程图片污染 Canvas 时可能抛出安全错误
2268
+ */
2269
+ exportTexture(filename) {
2270
+ this.editor.exportTexture(filename);
2271
+ }
2272
+ /** 恢复三维产品的默认相机位置 */
2273
+ resetView() {
2274
+ this.viewer.resetView();
2275
+ }
2276
+ /** 返回当前三维相机位置和观察目标点 */
2277
+ getViewState() {
2278
+ return this.viewer.getViewState();
2279
+ }
2280
+ /**
2281
+ * 恢复三维观察视角
2282
+ *
2283
+ * @param state 要恢复的相机位置和观察目标点
2284
+ * @returns 应用后的独立视角快照
2285
+ * @throws 坐标不是有限数值或相机与目标点重合时抛出错误
2286
+ */
2287
+ setViewState(state) {
2288
+ return this.viewer.setViewState(state);
2289
+ }
2290
+ /**
2291
+ * 更换模型、基础纹理和接收纹理的目标 Mesh
2292
+ *
2293
+ * 成功后保留当前设计对象,并将当前设计设为新的历史起点
2294
+ *
2295
+ * @param product 新的产品配置
2296
+ * @throws 模型或纹理加载失败、目标 Mesh 不存在时抛出错误
2297
+ */
2298
+ async loadProduct(product) {
2299
+ const nextProduct = normalizeProductConfiguration(product);
2300
+ this.emit("status", { message: "Loading product" });
2301
+ try {
2302
+ const uvLayout = await this.viewer.loadProduct(nextProduct);
2303
+ await this.editor.setBackgroundTexture(nextProduct.textureUrl);
2304
+ this.textureBridge.setFlipY(nextProduct.textureFlipY);
2305
+ this.editor.setUvLayout(uvLayout, nextProduct.textureFlipY);
2306
+ this.product = nextProduct;
2307
+ this.editor.clearHistory();
2308
+ this.emit("ready", { product: this.getProduct() });
2309
+ this.emit("status", { message: nextProduct.modelUrl ? "Remote product ready" : "Demo product ready" });
2310
+ } catch (error) {
2311
+ this.reportError(error);
2312
+ throw error;
2313
+ }
2314
+ }
2315
+ /**
2316
+ * 释放事件监听、Fabric Canvas、纹理和 WebGL 资源
2317
+ *
2318
+ * 重复调用不会再次释放资源,首次调用后不得继续使用其他实例方法
2319
+ */
2320
+ destroy() {
2321
+ if (this.destroyed) return;
2322
+ this.destroyed = true;
2323
+ this.stopSelectionListener?.();
2324
+ this.stopRenderListener?.();
2325
+ this.stopHistoryListener?.();
2326
+ this.stopViewListener?.();
2327
+ this.textureBridge.destroy();
2328
+ this.editor.destroy();
2329
+ this.viewer.destroy();
2330
+ }
2331
+ async initialize() {
2332
+ const uvLayout = await this.viewer.loadProduct(this.product);
2333
+ await this.editor.setBackgroundTexture(this.product.textureUrl);
2334
+ this.textureBridge.setFlipY(this.product.textureFlipY);
2335
+ this.editor.setUvLayout(uvLayout, this.product.textureFlipY);
2336
+ this.emit("ready", { product: this.getProduct() });
2337
+ }
2338
+ emit(event, detail) {
2339
+ this.events.dispatchEvent(new CustomEvent(event, { detail }));
2340
+ }
2341
+ reportError(error) {
2342
+ const normalized = error instanceof Error ? error : new Error(String(error));
2343
+ this.emit("error", { error: normalized });
2344
+ this.emit("status", { message: normalized.message });
2345
+ }
2346
+ };
2347
+ //#endregion
2348
+ export { resolveElement as n, ProductCustomizer as t };
2349
+
2350
+ //# sourceMappingURL=ProductCustomizer-4ytA68eg.js.map