@pooder/kit 5.3.1 → 5.4.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 (90) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.d.mts +243 -36
  3. package/dist/index.d.ts +243 -36
  4. package/dist/index.js +2278 -1041
  5. package/dist/index.mjs +2278 -1041
  6. package/package.json +1 -1
  7. package/src/coordinate.ts +106 -106
  8. package/src/extensions/background.ts +323 -230
  9. package/src/extensions/bridgeSelection.ts +17 -17
  10. package/src/extensions/constraints.ts +322 -322
  11. package/src/extensions/dieline.ts +1149 -1076
  12. package/src/extensions/dielineShape.ts +109 -0
  13. package/src/extensions/edgeScale.ts +19 -19
  14. package/src/extensions/feature.ts +1137 -1021
  15. package/src/extensions/featureComplete.ts +46 -46
  16. package/src/extensions/film.ts +266 -194
  17. package/src/extensions/geometry.ts +885 -752
  18. package/src/extensions/image.ts +2054 -1926
  19. package/src/extensions/index.ts +11 -11
  20. package/src/extensions/maskOps.ts +283 -283
  21. package/src/extensions/mirror.ts +128 -128
  22. package/src/extensions/ruler.ts +654 -451
  23. package/src/extensions/sceneLayout.ts +140 -140
  24. package/src/extensions/sceneLayoutModel.ts +364 -352
  25. package/src/extensions/sceneVisibility.ts +64 -71
  26. package/src/extensions/size.ts +389 -389
  27. package/src/extensions/tracer.ts +1019 -1019
  28. package/src/extensions/white-ink.ts +1567 -1514
  29. package/src/extensions/wrappedOffsets.ts +33 -33
  30. package/src/index.ts +2 -2
  31. package/src/services/CanvasService.ts +832 -300
  32. package/src/services/ViewportSystem.ts +95 -95
  33. package/src/services/index.ts +3 -3
  34. package/src/services/renderSpec.ts +53 -18
  35. package/src/units.ts +27 -27
  36. package/tests/run.ts +118 -118
  37. package/tsconfig.test.json +15 -15
  38. package/.test-dist/src/CanvasService.js +0 -249
  39. package/.test-dist/src/ViewportSystem.js +0 -75
  40. package/.test-dist/src/background.js +0 -203
  41. package/.test-dist/src/bridgeSelection.js +0 -20
  42. package/.test-dist/src/constraints.js +0 -237
  43. package/.test-dist/src/coordinate.js +0 -74
  44. package/.test-dist/src/dieline.js +0 -818
  45. package/.test-dist/src/edgeScale.js +0 -12
  46. package/.test-dist/src/extensions/background.js +0 -203
  47. package/.test-dist/src/extensions/bridgeSelection.js +0 -20
  48. package/.test-dist/src/extensions/constraints.js +0 -237
  49. package/.test-dist/src/extensions/dieline.js +0 -828
  50. package/.test-dist/src/extensions/edgeScale.js +0 -12
  51. package/.test-dist/src/extensions/feature.js +0 -825
  52. package/.test-dist/src/extensions/featureComplete.js +0 -32
  53. package/.test-dist/src/extensions/film.js +0 -167
  54. package/.test-dist/src/extensions/geometry.js +0 -545
  55. package/.test-dist/src/extensions/image.js +0 -1529
  56. package/.test-dist/src/extensions/index.js +0 -30
  57. package/.test-dist/src/extensions/maskOps.js +0 -279
  58. package/.test-dist/src/extensions/mirror.js +0 -104
  59. package/.test-dist/src/extensions/ruler.js +0 -345
  60. package/.test-dist/src/extensions/sceneLayout.js +0 -96
  61. package/.test-dist/src/extensions/sceneLayoutModel.js +0 -196
  62. package/.test-dist/src/extensions/sceneVisibility.js +0 -62
  63. package/.test-dist/src/extensions/size.js +0 -331
  64. package/.test-dist/src/extensions/tracer.js +0 -538
  65. package/.test-dist/src/extensions/white-ink.js +0 -1190
  66. package/.test-dist/src/extensions/wrappedOffsets.js +0 -33
  67. package/.test-dist/src/feature.js +0 -826
  68. package/.test-dist/src/featureComplete.js +0 -32
  69. package/.test-dist/src/film.js +0 -167
  70. package/.test-dist/src/geometry.js +0 -506
  71. package/.test-dist/src/image.js +0 -1250
  72. package/.test-dist/src/index.js +0 -18
  73. package/.test-dist/src/maskOps.js +0 -270
  74. package/.test-dist/src/mirror.js +0 -104
  75. package/.test-dist/src/renderSpec.js +0 -2
  76. package/.test-dist/src/ruler.js +0 -343
  77. package/.test-dist/src/sceneLayout.js +0 -99
  78. package/.test-dist/src/sceneLayoutModel.js +0 -196
  79. package/.test-dist/src/sceneView.js +0 -40
  80. package/.test-dist/src/sceneVisibility.js +0 -42
  81. package/.test-dist/src/services/CanvasService.js +0 -249
  82. package/.test-dist/src/services/ViewportSystem.js +0 -76
  83. package/.test-dist/src/services/index.js +0 -24
  84. package/.test-dist/src/services/renderSpec.js +0 -2
  85. package/.test-dist/src/size.js +0 -332
  86. package/.test-dist/src/tracer.js +0 -544
  87. package/.test-dist/src/units.js +0 -30
  88. package/.test-dist/src/white-ink.js +0 -829
  89. package/.test-dist/src/wrappedOffsets.js +0 -33
  90. package/.test-dist/tests/run.js +0 -94
@@ -1,300 +1,832 @@
1
- import { Canvas, Group, FabricObject, Rect, Path, Image } from "fabric";
2
- import { Service, EventBus } from "@pooder/core";
3
- import { ViewportSystem } from "./ViewportSystem";
4
- import type { RenderLayerSpec, RenderObjectSpec } from "./renderSpec";
5
-
6
- export default class CanvasService implements Service {
7
- public canvas: Canvas;
8
- public viewport: ViewportSystem;
9
- private eventBus?: EventBus;
10
-
11
- constructor(el: HTMLCanvasElement | string | Canvas, options?: any) {
12
- if (el instanceof Canvas) {
13
- this.canvas = el;
14
- } else {
15
- this.canvas = new Canvas(el, {
16
- preserveObjectStacking: true,
17
- ...options,
18
- });
19
- }
20
-
21
- this.viewport = new ViewportSystem();
22
- if (this.canvas.width !== undefined && this.canvas.height !== undefined) {
23
- this.viewport.updateContainer(this.canvas.width, this.canvas.height);
24
- }
25
-
26
- if (options?.eventBus) {
27
- this.setEventBus(options.eventBus);
28
- }
29
- }
30
-
31
- setEventBus(eventBus: EventBus) {
32
- this.eventBus = eventBus;
33
- this.setupEvents();
34
- }
35
-
36
- private setupEvents() {
37
- if (!this.eventBus) return;
38
- const bus = this.eventBus;
39
-
40
- const forward = (name: string) => (e: any) => bus.emit(name, e);
41
-
42
- this.canvas.on("selection:created", forward("selection:created"));
43
- this.canvas.on("selection:updated", forward("selection:updated"));
44
- this.canvas.on("selection:cleared", forward("selection:cleared"));
45
- this.canvas.on("object:modified", forward("object:modified"));
46
- this.canvas.on("object:added", forward("object:added"));
47
- this.canvas.on("object:removed", forward("object:removed"));
48
- }
49
-
50
- dispose() {
51
- this.canvas.dispose();
52
- }
53
-
54
- /**
55
- * Get a layer (Group) by its ID.
56
- * We assume layers are Groups directly on the canvas with a data.id property.
57
- */
58
- getLayer(id: string): Group | undefined {
59
- return this.canvas.getObjects().find((obj: any) => obj.data?.id === id) as
60
- | Group
61
- | undefined;
62
- }
63
-
64
- /**
65
- * Create a layer (Group) with the given ID if it doesn't exist.
66
- */
67
- createLayer(id: string, options: any = {}): Group {
68
- let layer = this.getLayer(id);
69
- if (!layer) {
70
- const defaultOptions = {
71
- selectable: false,
72
- evented: false,
73
- ...options,
74
- data: { ...options.data, id },
75
- };
76
- layer = new Group([], defaultOptions);
77
- this.canvas.add(layer);
78
- }
79
- return layer;
80
- }
81
-
82
- /**
83
- * Find an object by ID, optionally within a specific layer.
84
- */
85
- getObject(id: string, layerId?: string): FabricObject | undefined {
86
- if (layerId) {
87
- const layer = this.getLayer(layerId);
88
- if (!layer) return undefined;
89
- return layer.getObjects().find((obj: any) => obj.data?.id === id);
90
- }
91
- return this.canvas.getObjects().find((obj: any) => obj.data?.id === id);
92
- }
93
-
94
- requestRenderAll() {
95
- this.canvas.requestRenderAll();
96
- }
97
-
98
- resize(width: number, height: number) {
99
- this.canvas.setDimensions({ width, height });
100
- this.viewport.updateContainer(width, height);
101
- this.eventBus?.emit("canvas:resized", { width, height });
102
- this.requestRenderAll();
103
- }
104
-
105
- async applyLayerSpec(spec: RenderLayerSpec): Promise<void> {
106
- const layer = this.createLayer(spec.id, spec.props || {});
107
- await this.applyObjectSpecsToContainer(layer, spec.objects);
108
- }
109
-
110
- async applyObjectSpecsToLayer(
111
- layerId: string,
112
- objects: RenderObjectSpec[],
113
- ): Promise<void> {
114
- const layer = this.createLayer(layerId, {});
115
- await this.applyObjectSpecsToContainer(layer, objects);
116
- }
117
-
118
- getRootLayerObjects(layerId: string): FabricObject[] {
119
- return this.canvas
120
- .getObjects()
121
- .filter((obj: any) => obj?.data?.layerId === layerId);
122
- }
123
-
124
- async applyObjectSpecsToRootLayer(
125
- layerId: string,
126
- specs: RenderObjectSpec[],
127
- ): Promise<void> {
128
- const desiredIds = new Set(specs.map((s) => s.id));
129
- const existing = this.getRootLayerObjects(layerId) as any[];
130
- existing.forEach((obj) => {
131
- const id = obj?.data?.id;
132
- if (typeof id === "string" && !desiredIds.has(id)) {
133
- this.canvas.remove(obj);
134
- }
135
- });
136
-
137
- const byId = new Map<string, any>();
138
- this.getRootLayerObjects(layerId).forEach((obj: any) => {
139
- const id = obj?.data?.id;
140
- if (typeof id === "string") byId.set(id, obj);
141
- });
142
-
143
- for (let index = 0; index < specs.length; index += 1) {
144
- const spec = specs[index];
145
- let current = byId.get(spec.id);
146
- if (
147
- current &&
148
- spec.type === "image" &&
149
- spec.src &&
150
- current.getSrc &&
151
- current.getSrc() !== spec.src
152
- ) {
153
- this.canvas.remove(current);
154
- byId.delete(spec.id);
155
- current = undefined;
156
- }
157
-
158
- if (!current) {
159
- const created = await this.createFabricObject(spec);
160
- if (!created) continue;
161
- this.patchFabricObject(created as any, spec, { layerId });
162
- this.canvas.add(created as any);
163
- byId.set(spec.id, created);
164
- continue;
165
- }
166
-
167
- this.patchFabricObject(current, spec, { layerId });
168
- }
169
-
170
- this.requestRenderAll();
171
- }
172
-
173
- private async applyObjectSpecsToContainer(
174
- container: Group,
175
- specs: RenderObjectSpec[],
176
- ): Promise<void> {
177
- const desiredIds = new Set(specs.map((s) => s.id));
178
- const existing = container.getObjects() as any[];
179
- existing.forEach((obj) => {
180
- const id = obj?.data?.id;
181
- if (typeof id === "string" && !desiredIds.has(id)) {
182
- container.remove(obj);
183
- }
184
- });
185
-
186
- const byId = new Map<string, any>();
187
- (container.getObjects() as any[]).forEach((obj) => {
188
- const id = obj?.data?.id;
189
- if (typeof id === "string") byId.set(id, obj);
190
- });
191
-
192
- for (let index = 0; index < specs.length; index += 1) {
193
- const spec = specs[index];
194
- let current = byId.get(spec.id);
195
- if (
196
- current &&
197
- spec.type === "image" &&
198
- spec.src &&
199
- current.getSrc &&
200
- current.getSrc() !== spec.src
201
- ) {
202
- container.remove(current);
203
- byId.delete(spec.id);
204
- current = undefined;
205
- }
206
-
207
- if (!current) {
208
- const created = await this.createFabricObject(spec);
209
- if (!created) continue;
210
- container.add(created as any);
211
- current = created as any;
212
- byId.set(spec.id, current);
213
- } else {
214
- this.patchFabricObject(current, spec);
215
- }
216
-
217
- this.moveObjectInContainer(container, current, index);
218
- }
219
-
220
- container.dirty = true;
221
- this.requestRenderAll();
222
- }
223
-
224
- private patchFabricObject(
225
- obj: any,
226
- spec: RenderObjectSpec,
227
- extraData?: Record<string, any>,
228
- ) {
229
- const nextData = {
230
- ...(obj.data || {}),
231
- ...(spec.data || {}),
232
- ...(extraData || {}),
233
- id: spec.id,
234
- };
235
- obj.set({ ...(spec.props || {}), data: nextData });
236
- obj.setCoords();
237
- }
238
-
239
- private moveObjectInContainer(
240
- container: Group | Canvas,
241
- obj: any,
242
- index: number,
243
- ) {
244
- if (!obj) return;
245
-
246
- const moveObjectTo = (container as any).moveObjectTo;
247
- if (typeof moveObjectTo === "function") {
248
- moveObjectTo.call(container, obj, index);
249
- return;
250
- }
251
-
252
- const list = (container as any)._objects as any[] | undefined;
253
- if (!Array.isArray(list)) return;
254
- const from = list.indexOf(obj);
255
- if (from < 0 || from === index) return;
256
- list.splice(from, 1);
257
- const target = Math.max(0, Math.min(index, list.length));
258
- list.splice(target, 0, obj);
259
- if (typeof (container as any)._onStackOrderChanged === "function") {
260
- (container as any)._onStackOrderChanged();
261
- }
262
- }
263
-
264
- private async createFabricObject(
265
- spec: RenderObjectSpec,
266
- ): Promise<FabricObject | undefined> {
267
- if (spec.type === "rect") {
268
- const rect = new Rect({
269
- ...(spec.props || {}),
270
- data: { ...(spec.data || {}), id: spec.id },
271
- } as any);
272
- rect.setCoords();
273
- return rect;
274
- }
275
-
276
- if (spec.type === "path") {
277
- const pathData = (spec.props as any)?.path || (spec.props as any)?.pathData;
278
- if (!pathData) return undefined;
279
- const path = new Path(pathData, {
280
- ...(spec.props || {}),
281
- data: { ...(spec.data || {}), id: spec.id },
282
- } as any);
283
- path.setCoords();
284
- return path;
285
- }
286
-
287
- if (spec.type === "image") {
288
- if (!spec.src) return undefined;
289
- const image = await Image.fromURL(spec.src, { crossOrigin: "anonymous" });
290
- image.set({
291
- ...(spec.props || {}),
292
- data: { ...(spec.data || {}), id: spec.id },
293
- } as any);
294
- image.setCoords();
295
- return image as any;
296
- }
297
-
298
- return undefined;
299
- }
300
- }
1
+ import { Canvas, Group, FabricObject, Rect, Path, Image, Text } from "fabric";
2
+ import { Service, EventBus } from "@pooder/core";
3
+ import { ViewportSystem } from "./ViewportSystem";
4
+ import type {
5
+ RenderCoordinateSpace,
6
+ RenderLayerSpec,
7
+ RenderLayoutInsets,
8
+ RenderLayoutLength,
9
+ RenderObjectLayoutSpec,
10
+ RenderObjectSpec,
11
+ } from "./renderSpec";
12
+
13
+ export interface RenderProducerResult {
14
+ layerSpecs?: Record<string, RenderObjectSpec[]>;
15
+ rootLayerSpecs?: Record<string, RenderObjectSpec[]>;
16
+ replaceLayerIds?: string[];
17
+ replaceRootLayerIds?: string[];
18
+ }
19
+
20
+ export type RenderProducer = () =>
21
+ | RenderProducerResult
22
+ | undefined
23
+ | Promise<RenderProducerResult | undefined>;
24
+
25
+ export interface RegisterRenderProducerOptions {
26
+ priority?: number;
27
+ }
28
+
29
+ interface RenderProducerEntry {
30
+ toolId: string;
31
+ producer: RenderProducer;
32
+ priority: number;
33
+ order: number;
34
+ }
35
+
36
+ interface RectLike {
37
+ left: number;
38
+ top: number;
39
+ width: number;
40
+ height: number;
41
+ }
42
+
43
+ export default class CanvasService implements Service {
44
+ public canvas: Canvas;
45
+ public viewport: ViewportSystem;
46
+ private eventBus?: EventBus;
47
+ private renderProducers: Map<string, RenderProducerEntry> = new Map();
48
+ private producerOrder = 0;
49
+ private producerFlushRequested = false;
50
+ private producerLoopPending = false;
51
+ private producerLoopPromise: Promise<void> | null = null;
52
+ private managedProducerLayerIds: Set<string> = new Set();
53
+ private managedProducerRootLayerIds: Set<string> = new Set();
54
+
55
+ constructor(el: HTMLCanvasElement | string | Canvas, options?: any) {
56
+ if (el instanceof Canvas) {
57
+ this.canvas = el;
58
+ } else {
59
+ this.canvas = new Canvas(el, {
60
+ preserveObjectStacking: true,
61
+ ...options,
62
+ });
63
+ }
64
+
65
+ this.viewport = new ViewportSystem();
66
+ if (this.canvas.width !== undefined && this.canvas.height !== undefined) {
67
+ this.viewport.updateContainer(this.canvas.width, this.canvas.height);
68
+ }
69
+
70
+ if (options?.eventBus) {
71
+ this.setEventBus(options.eventBus);
72
+ }
73
+ }
74
+
75
+ setEventBus(eventBus: EventBus) {
76
+ this.eventBus = eventBus;
77
+ this.setupEvents();
78
+ }
79
+
80
+ private setupEvents() {
81
+ if (!this.eventBus) return;
82
+ const bus = this.eventBus;
83
+
84
+ const forward = (name: string) => (e: any) => bus.emit(name, e);
85
+
86
+ this.canvas.on("selection:created", forward("selection:created"));
87
+ this.canvas.on("selection:updated", forward("selection:updated"));
88
+ this.canvas.on("selection:cleared", forward("selection:cleared"));
89
+ this.canvas.on("object:modified", forward("object:modified"));
90
+ this.canvas.on("object:added", forward("object:added"));
91
+ this.canvas.on("object:removed", forward("object:removed"));
92
+ }
93
+
94
+ dispose() {
95
+ this.renderProducers.clear();
96
+ this.managedProducerLayerIds.clear();
97
+ this.managedProducerRootLayerIds.clear();
98
+ this.producerFlushRequested = false;
99
+ this.canvas.dispose();
100
+ }
101
+
102
+ registerRenderProducer(
103
+ toolId: string,
104
+ producer: RenderProducer,
105
+ options: RegisterRenderProducerOptions = {},
106
+ ): { dispose: () => void } {
107
+ const normalizedToolId = String(toolId || "").trim();
108
+ if (!normalizedToolId) {
109
+ throw new Error(
110
+ "[CanvasService] registerRenderProducer requires a toolId.",
111
+ );
112
+ }
113
+ if (typeof producer !== "function") {
114
+ throw new Error(
115
+ `[CanvasService] registerRenderProducer("${normalizedToolId}") requires a producer function.`,
116
+ );
117
+ }
118
+ const entry: RenderProducerEntry = {
119
+ toolId: normalizedToolId,
120
+ producer,
121
+ priority: Number.isFinite(options.priority)
122
+ ? Number(options.priority)
123
+ : 0,
124
+ order: this.producerOrder++,
125
+ };
126
+ this.renderProducers.set(normalizedToolId, entry);
127
+ this.requestRenderFromProducers();
128
+ return {
129
+ dispose: () => {
130
+ this.unregisterRenderProducer(normalizedToolId);
131
+ },
132
+ };
133
+ }
134
+
135
+ unregisterRenderProducer(toolId: string): boolean {
136
+ const normalizedToolId = String(toolId || "").trim();
137
+ if (!normalizedToolId) return false;
138
+ const removed = this.renderProducers.delete(normalizedToolId);
139
+ if (removed) {
140
+ this.requestRenderFromProducers();
141
+ }
142
+ return removed;
143
+ }
144
+
145
+ requestRenderFromProducers() {
146
+ this.producerFlushRequested = true;
147
+ this.scheduleProducerLoop();
148
+ }
149
+
150
+ async flushRenderFromProducers(): Promise<void> {
151
+ this.requestRenderFromProducers();
152
+ if (this.producerLoopPromise) {
153
+ await this.producerLoopPromise;
154
+ }
155
+ }
156
+
157
+ private scheduleProducerLoop() {
158
+ if (this.producerLoopPending) return;
159
+ this.producerLoopPending = true;
160
+ this.producerLoopPromise = Promise.resolve()
161
+ .then(() => this.runProducerLoop())
162
+ .catch((error) => {
163
+ console.error("[CanvasService] render producer loop failed.", error);
164
+ })
165
+ .finally(() => {
166
+ this.producerLoopPending = false;
167
+ if (this.producerFlushRequested) {
168
+ this.scheduleProducerLoop();
169
+ }
170
+ });
171
+ }
172
+
173
+ private async runProducerLoop(): Promise<void> {
174
+ while (this.producerFlushRequested) {
175
+ this.producerFlushRequested = false;
176
+ await this.collectAndApplyProducerSpecs();
177
+ }
178
+ }
179
+
180
+ private sortedRenderProducerEntries(): RenderProducerEntry[] {
181
+ return Array.from(this.renderProducers.values()).sort((a, b) => {
182
+ if (a.priority !== b.priority) {
183
+ return a.priority - b.priority;
184
+ }
185
+ if (a.order !== b.order) {
186
+ return a.order - b.order;
187
+ }
188
+ return a.toolId.localeCompare(b.toolId);
189
+ });
190
+ }
191
+
192
+ private appendLayerSpecMap(
193
+ map: Map<string, RenderObjectSpec[]>,
194
+ source?: Record<string, RenderObjectSpec[]>,
195
+ ) {
196
+ if (!source) return;
197
+ Object.entries(source).forEach(([layerId, specs]) => {
198
+ if (!Array.isArray(specs)) return;
199
+ const list = map.get(layerId) || [];
200
+ list.push(...specs);
201
+ map.set(layerId, list);
202
+ });
203
+ }
204
+
205
+ private async collectAndApplyProducerSpecs(): Promise<void> {
206
+ const groupLayerSpecs = new Map<string, RenderObjectSpec[]>();
207
+ const rootLayerSpecs = new Map<string, RenderObjectSpec[]>();
208
+ const replaceLayerIds = new Set<string>();
209
+ const replaceRootLayerIds = new Set<string>();
210
+ const entries = this.sortedRenderProducerEntries();
211
+
212
+ for (const entry of entries) {
213
+ try {
214
+ const result = await entry.producer();
215
+ if (!result) continue;
216
+ this.appendLayerSpecMap(groupLayerSpecs, result.layerSpecs);
217
+ this.appendLayerSpecMap(rootLayerSpecs, result.rootLayerSpecs);
218
+ if (Array.isArray(result.replaceLayerIds)) {
219
+ result.replaceLayerIds.forEach((layerId) => {
220
+ if (layerId) replaceLayerIds.add(layerId);
221
+ });
222
+ }
223
+ if (Array.isArray(result.replaceRootLayerIds)) {
224
+ result.replaceRootLayerIds.forEach((layerId) => {
225
+ if (layerId) replaceRootLayerIds.add(layerId);
226
+ });
227
+ }
228
+ } catch (error) {
229
+ console.error(
230
+ `[CanvasService] render producer "${entry.toolId}" failed.`,
231
+ error,
232
+ );
233
+ }
234
+ }
235
+
236
+ const nextLayerIds = new Set(groupLayerSpecs.keys());
237
+ const nextRootLayerIds = new Set(rootLayerSpecs.keys());
238
+
239
+ for (const [layerId, specs] of groupLayerSpecs.entries()) {
240
+ if (replaceLayerIds.has(layerId)) {
241
+ const layer = this.getLayer(layerId);
242
+ if (layer) {
243
+ (layer.getObjects() as any[]).forEach((obj) => layer.remove(obj));
244
+ }
245
+ }
246
+ await this.applyObjectSpecsToLayer(layerId, specs, { render: false });
247
+ }
248
+
249
+ for (const layerId of this.managedProducerLayerIds) {
250
+ if (nextLayerIds.has(layerId)) continue;
251
+ const layer = this.getLayer(layerId);
252
+ if (!layer) continue;
253
+ await this.applyObjectSpecsToContainer(layer, [], { render: false });
254
+ }
255
+
256
+ for (const [layerId, specs] of rootLayerSpecs.entries()) {
257
+ if (replaceRootLayerIds.has(layerId)) {
258
+ const existing = this.getRootLayerObjects(layerId) as any[];
259
+ existing.forEach((obj) => this.canvas.remove(obj));
260
+ }
261
+ await this.applyObjectSpecsToRootLayer(layerId, specs, { render: false });
262
+ }
263
+
264
+ for (const layerId of this.managedProducerRootLayerIds) {
265
+ if (nextRootLayerIds.has(layerId)) continue;
266
+ await this.applyObjectSpecsToRootLayer(layerId, [], { render: false });
267
+ }
268
+
269
+ this.managedProducerLayerIds = nextLayerIds;
270
+ this.managedProducerRootLayerIds = nextRootLayerIds;
271
+ this.requestRenderAll();
272
+ }
273
+
274
+ /**
275
+ * Get a layer (Group) by its ID.
276
+ * We assume layers are Groups directly on the canvas with a data.id property.
277
+ */
278
+ getLayer(id: string): Group | undefined {
279
+ return this.canvas.getObjects().find((obj: any) => obj.data?.id === id) as
280
+ | Group
281
+ | undefined;
282
+ }
283
+
284
+ /**
285
+ * Create a layer (Group) with the given ID if it doesn't exist.
286
+ */
287
+ createLayer(id: string, options: any = {}): Group {
288
+ let layer = this.getLayer(id);
289
+ if (!layer) {
290
+ const defaultOptions = {
291
+ selectable: false,
292
+ evented: false,
293
+ ...options,
294
+ data: { ...options.data, id },
295
+ };
296
+ layer = new Group([], defaultOptions);
297
+ this.canvas.add(layer);
298
+ }
299
+ return layer;
300
+ }
301
+
302
+ /**
303
+ * Find an object by ID, optionally within a specific layer.
304
+ */
305
+ getObject(id: string, layerId?: string): FabricObject | undefined {
306
+ if (layerId) {
307
+ const layer = this.getLayer(layerId);
308
+ if (!layer) return undefined;
309
+ return layer.getObjects().find((obj: any) => obj.data?.id === id);
310
+ }
311
+ return this.canvas.getObjects().find((obj: any) => obj.data?.id === id);
312
+ }
313
+
314
+ requestRenderAll() {
315
+ this.canvas.requestRenderAll();
316
+ }
317
+
318
+ resize(width: number, height: number) {
319
+ this.canvas.setDimensions({ width, height });
320
+ this.viewport.updateContainer(width, height);
321
+ this.eventBus?.emit("canvas:resized", { width, height });
322
+ this.requestRenderAll();
323
+ }
324
+
325
+ getSceneScale(): number {
326
+ const scale = Number(this.viewport.scale);
327
+ return Number.isFinite(scale) && scale > 0 ? scale : 1;
328
+ }
329
+
330
+ getSceneOffset(): { x: number; y: number } {
331
+ const offset = this.viewport.offset;
332
+ const x = Number(offset.x);
333
+ const y = Number(offset.y);
334
+ return {
335
+ x: Number.isFinite(x) ? x : 0,
336
+ y: Number.isFinite(y) ? y : 0,
337
+ };
338
+ }
339
+
340
+ toScreenPoint(point: { x: number; y: number }): { x: number; y: number } {
341
+ const scale = this.getSceneScale();
342
+ const offset = this.getSceneOffset();
343
+ return {
344
+ x: point.x * scale + offset.x,
345
+ y: point.y * scale + offset.y,
346
+ };
347
+ }
348
+
349
+ toScenePoint(point: { x: number; y: number }): { x: number; y: number } {
350
+ const scale = this.getSceneScale();
351
+ const offset = this.getSceneOffset();
352
+ return {
353
+ x: (point.x - offset.x) / scale,
354
+ y: (point.y - offset.y) / scale,
355
+ };
356
+ }
357
+
358
+ toScreenLength(value: number): number {
359
+ return value * this.getSceneScale();
360
+ }
361
+
362
+ toSceneLength(value: number): number {
363
+ return value / this.getSceneScale();
364
+ }
365
+
366
+ toScreenRect(rect: {
367
+ left: number;
368
+ top: number;
369
+ width: number;
370
+ height: number;
371
+ }): { left: number; top: number; width: number; height: number } {
372
+ const start = this.toScreenPoint({ x: rect.left, y: rect.top });
373
+ return {
374
+ left: start.x,
375
+ top: start.y,
376
+ width: this.toScreenLength(rect.width),
377
+ height: this.toScreenLength(rect.height),
378
+ };
379
+ }
380
+
381
+ toSceneRect(rect: {
382
+ left: number;
383
+ top: number;
384
+ width: number;
385
+ height: number;
386
+ }): { left: number; top: number; width: number; height: number } {
387
+ const start = this.toScenePoint({ x: rect.left, y: rect.top });
388
+ return {
389
+ left: start.x,
390
+ top: start.y,
391
+ width: this.toSceneLength(rect.width),
392
+ height: this.toSceneLength(rect.height),
393
+ };
394
+ }
395
+
396
+ getSceneViewportRect(): {
397
+ left: number;
398
+ top: number;
399
+ width: number;
400
+ height: number;
401
+ } {
402
+ const width = Number(this.canvas.width || 0);
403
+ const height = Number(this.canvas.height || 0);
404
+ return this.toSceneRect({ left: 0, top: 0, width, height });
405
+ }
406
+
407
+ getScreenViewportRect(): RectLike {
408
+ return {
409
+ left: 0,
410
+ top: 0,
411
+ width: Number(this.canvas.width || 0),
412
+ height: Number(this.canvas.height || 0),
413
+ };
414
+ }
415
+
416
+ private toSpaceRect(
417
+ rect: RectLike,
418
+ from: RenderCoordinateSpace,
419
+ to: RenderCoordinateSpace,
420
+ ): RectLike {
421
+ if (from === to) return { ...rect };
422
+ if (from === "scene") {
423
+ return this.toScreenRect(rect);
424
+ }
425
+ return this.toSceneRect(rect);
426
+ }
427
+
428
+ private resolveLayoutLength(
429
+ value: RenderLayoutLength | undefined,
430
+ base: number,
431
+ ): number | undefined {
432
+ if (typeof value === "number") {
433
+ return Number.isFinite(value) ? value : undefined;
434
+ }
435
+ if (typeof value !== "string") {
436
+ return undefined;
437
+ }
438
+ const raw = value.trim();
439
+ if (!raw) return undefined;
440
+ if (raw.endsWith("%")) {
441
+ const percent = parseFloat(raw.slice(0, -1));
442
+ if (!Number.isFinite(percent)) return undefined;
443
+ return (base * percent) / 100;
444
+ }
445
+ const parsed = parseFloat(raw);
446
+ return Number.isFinite(parsed) ? parsed : undefined;
447
+ }
448
+
449
+ private resolveLayoutInsets(
450
+ inset: RenderLayoutLength | RenderLayoutInsets | undefined,
451
+ reference: RectLike,
452
+ ): { top: number; right: number; bottom: number; left: number } {
453
+ if (typeof inset === "number" || typeof inset === "string") {
454
+ const all =
455
+ this.resolveLayoutLength(
456
+ inset,
457
+ Math.min(reference.width, reference.height),
458
+ ) ?? 0;
459
+ return { top: all, right: all, bottom: all, left: all };
460
+ }
461
+
462
+ const source = inset || {};
463
+ const top = this.resolveLayoutLength(source.top, reference.height) ?? 0;
464
+ const right = this.resolveLayoutLength(source.right, reference.width) ?? 0;
465
+ const bottom =
466
+ this.resolveLayoutLength(source.bottom, reference.height) ?? 0;
467
+ const left = this.resolveLayoutLength(source.left, reference.width) ?? 0;
468
+ return { top, right, bottom, left };
469
+ }
470
+
471
+ private resolveLayoutReferenceRect(
472
+ layout: RenderObjectLayoutSpec,
473
+ space: RenderCoordinateSpace,
474
+ ): RectLike {
475
+ if (layout.referenceRect) {
476
+ const sourceSpace: RenderCoordinateSpace =
477
+ layout.referenceRect.space || space;
478
+ return this.toSpaceRect(layout.referenceRect, sourceSpace, space);
479
+ }
480
+
481
+ const reference = layout.reference || "sceneViewport";
482
+ if (reference === "screenViewport") {
483
+ const screenRect = this.getScreenViewportRect();
484
+ return space === "screen" ? screenRect : this.toSceneRect(screenRect);
485
+ }
486
+
487
+ const sceneRect = this.getSceneViewportRect();
488
+ return space === "scene" ? sceneRect : this.toScreenRect(sceneRect);
489
+ }
490
+
491
+ private alignFactor(value: unknown): number {
492
+ if (value === "end") return 1;
493
+ if (value === "center") return 0.5;
494
+ return 0;
495
+ }
496
+
497
+ private normalizeOriginX(value: unknown): "left" | "center" | "right" {
498
+ if (value === "center") return "center";
499
+ if (value === "right") return "right";
500
+ return "left";
501
+ }
502
+
503
+ private normalizeOriginY(value: unknown): "top" | "center" | "bottom" {
504
+ if (value === "center") return "center";
505
+ if (value === "bottom") return "bottom";
506
+ return "top";
507
+ }
508
+
509
+ private originFactor(
510
+ value: "left" | "center" | "right" | "top" | "bottom",
511
+ ): number {
512
+ if (value === "center") return 0.5;
513
+ if (value === "right" || value === "bottom") return 1;
514
+ return 0;
515
+ }
516
+
517
+ private resolveLayoutProps(
518
+ spec: RenderObjectSpec,
519
+ props: Record<string, any>,
520
+ ): Record<string, any> {
521
+ const layout = spec.layout;
522
+ if (!layout) {
523
+ return { ...props };
524
+ }
525
+
526
+ const space: RenderCoordinateSpace = spec.space || "scene";
527
+ const reference = this.resolveLayoutReferenceRect(layout, space);
528
+ const inset = this.resolveLayoutInsets(layout.inset, reference);
529
+ const area: RectLike = {
530
+ left: reference.left + inset.left,
531
+ top: reference.top + inset.top,
532
+ width: Math.max(0, reference.width - inset.left - inset.right),
533
+ height: Math.max(0, reference.height - inset.top - inset.bottom),
534
+ };
535
+
536
+ const next = { ...props };
537
+ const width =
538
+ this.resolveLayoutLength(layout.width, area.width) ??
539
+ (Number.isFinite(next.width) ? Number(next.width) : undefined);
540
+ const height =
541
+ this.resolveLayoutLength(layout.height, area.height) ??
542
+ (Number.isFinite(next.height) ? Number(next.height) : undefined);
543
+
544
+ if (width !== undefined) next.width = width;
545
+ if (height !== undefined) next.height = height;
546
+
547
+ const alignX = this.alignFactor(layout.alignX);
548
+ const alignY = this.alignFactor(layout.alignY);
549
+ const offsetX = this.resolveLayoutLength(layout.offsetX, area.width) ?? 0;
550
+ const offsetY = this.resolveLayoutLength(layout.offsetY, area.height) ?? 0;
551
+ const objectWidth = Number.isFinite(next.width) ? Number(next.width) : 0;
552
+ const objectHeight = Number.isFinite(next.height) ? Number(next.height) : 0;
553
+
554
+ const objectLeft =
555
+ area.left + (area.width - objectWidth) * alignX + offsetX;
556
+ const objectTop =
557
+ area.top + (area.height - objectHeight) * alignY + offsetY;
558
+
559
+ const originX = this.normalizeOriginX(next.originX);
560
+ const originY = this.normalizeOriginY(next.originY);
561
+ next.left = objectLeft + objectWidth * this.originFactor(originX);
562
+ next.top = objectTop + objectHeight * this.originFactor(originY);
563
+ return next;
564
+ }
565
+
566
+ setLayerVisibility(layerId: string, visible: boolean) {
567
+ const layer = this.getLayer(layerId);
568
+ if (layer) {
569
+ layer.set({ visible });
570
+ }
571
+ const objects = this.getRootLayerObjects(layerId) as any[];
572
+ objects.forEach((obj) => {
573
+ obj.set?.({ visible });
574
+ obj.setCoords?.();
575
+ });
576
+ }
577
+
578
+ bringLayerToFront(layerId: string) {
579
+ const layer = this.getLayer(layerId);
580
+ if (layer) {
581
+ this.canvas.bringObjectToFront(layer);
582
+ }
583
+ const objects = this.getRootLayerObjects(layerId) as any[];
584
+ objects.forEach((obj) => this.canvas.bringObjectToFront(obj as any));
585
+ }
586
+
587
+ async applyLayerSpec(spec: RenderLayerSpec): Promise<void> {
588
+ const layer = this.createLayer(spec.id, spec.props || {});
589
+ await this.applyObjectSpecsToContainer(layer, spec.objects);
590
+ }
591
+
592
+ async applyObjectSpecsToLayer(
593
+ layerId: string,
594
+ objects: RenderObjectSpec[],
595
+ options: { render?: boolean } = {},
596
+ ): Promise<void> {
597
+ const layer = this.createLayer(layerId, {});
598
+ await this.applyObjectSpecsToContainer(layer, objects, options);
599
+ }
600
+
601
+ getRootLayerObjects(layerId: string): FabricObject[] {
602
+ return this.canvas
603
+ .getObjects()
604
+ .filter((obj: any) => obj?.data?.layerId === layerId);
605
+ }
606
+
607
+ async applyObjectSpecsToRootLayer(
608
+ layerId: string,
609
+ specs: RenderObjectSpec[],
610
+ options: { render?: boolean } = {},
611
+ ): Promise<void> {
612
+ const desiredIds = new Set(specs.map((s) => s.id));
613
+ const existing = this.getRootLayerObjects(layerId) as any[];
614
+ existing.forEach((obj) => {
615
+ const id = obj?.data?.id;
616
+ if (typeof id === "string" && !desiredIds.has(id)) {
617
+ this.canvas.remove(obj);
618
+ }
619
+ });
620
+
621
+ const byId = new Map<string, any>();
622
+ this.getRootLayerObjects(layerId).forEach((obj: any) => {
623
+ const id = obj?.data?.id;
624
+ if (typeof id === "string") byId.set(id, obj);
625
+ });
626
+
627
+ for (let index = 0; index < specs.length; index += 1) {
628
+ const spec = specs[index];
629
+ let current = byId.get(spec.id);
630
+ if (
631
+ current &&
632
+ spec.type === "image" &&
633
+ spec.src &&
634
+ current.getSrc &&
635
+ current.getSrc() !== spec.src
636
+ ) {
637
+ this.canvas.remove(current);
638
+ byId.delete(spec.id);
639
+ current = undefined;
640
+ }
641
+
642
+ if (!current) {
643
+ const created = await this.createFabricObject(spec);
644
+ if (!created) continue;
645
+ this.patchFabricObject(created as any, spec, { layerId });
646
+ this.canvas.add(created as any);
647
+ byId.set(spec.id, created);
648
+ continue;
649
+ }
650
+
651
+ this.patchFabricObject(current, spec, { layerId });
652
+ }
653
+
654
+ if (options.render !== false) {
655
+ this.requestRenderAll();
656
+ }
657
+ }
658
+
659
+ private async applyObjectSpecsToContainer(
660
+ container: Group,
661
+ specs: RenderObjectSpec[],
662
+ options: { render?: boolean } = {},
663
+ ): Promise<void> {
664
+ const desiredIds = new Set(specs.map((s) => s.id));
665
+ const existing = container.getObjects() as any[];
666
+ existing.forEach((obj) => {
667
+ const id = obj?.data?.id;
668
+ if (typeof id === "string" && !desiredIds.has(id)) {
669
+ container.remove(obj);
670
+ }
671
+ });
672
+
673
+ const byId = new Map<string, any>();
674
+ (container.getObjects() as any[]).forEach((obj) => {
675
+ const id = obj?.data?.id;
676
+ if (typeof id === "string") byId.set(id, obj);
677
+ });
678
+
679
+ for (let index = 0; index < specs.length; index += 1) {
680
+ const spec = specs[index];
681
+ let current = byId.get(spec.id);
682
+ if (
683
+ current &&
684
+ spec.type === "image" &&
685
+ spec.src &&
686
+ current.getSrc &&
687
+ current.getSrc() !== spec.src
688
+ ) {
689
+ container.remove(current);
690
+ byId.delete(spec.id);
691
+ current = undefined;
692
+ }
693
+
694
+ if (!current) {
695
+ const created = await this.createFabricObject(spec);
696
+ if (!created) continue;
697
+ container.add(created as any);
698
+ current = created as any;
699
+ byId.set(spec.id, current);
700
+ } else {
701
+ this.patchFabricObject(current, spec);
702
+ }
703
+
704
+ this.moveObjectInContainer(container, current, index);
705
+ }
706
+
707
+ container.dirty = true;
708
+ if (options.render !== false) {
709
+ this.requestRenderAll();
710
+ }
711
+ }
712
+
713
+ private patchFabricObject(
714
+ obj: any,
715
+ spec: RenderObjectSpec,
716
+ extraData?: Record<string, any>,
717
+ ) {
718
+ const nextData = {
719
+ ...(obj.data || {}),
720
+ ...(spec.data || {}),
721
+ ...(extraData || {}),
722
+ id: spec.id,
723
+ };
724
+ const props = this.resolveFabricProps(spec, spec.props || {});
725
+ obj.set({ ...props, data: nextData });
726
+ obj.setCoords();
727
+ }
728
+
729
+ private resolveFabricProps(
730
+ spec: RenderObjectSpec,
731
+ props: Record<string, any>,
732
+ ): Record<string, any> {
733
+ const space: RenderCoordinateSpace = spec.space || "scene";
734
+ const next = this.resolveLayoutProps(spec, props);
735
+ if (space === "screen") {
736
+ return next;
737
+ }
738
+ const hasLeft = Number.isFinite(next.left);
739
+ const hasTop = Number.isFinite(next.top);
740
+ if (hasLeft || hasTop) {
741
+ const mapped = this.toScreenPoint({
742
+ x: hasLeft ? Number(next.left) : 0,
743
+ y: hasTop ? Number(next.top) : 0,
744
+ });
745
+ if (hasLeft) next.left = mapped.x;
746
+ if (hasTop) next.top = mapped.y;
747
+ }
748
+ const rawScaleX = Number.isFinite(next.scaleX) ? Number(next.scaleX) : 1;
749
+ const rawScaleY = Number.isFinite(next.scaleY) ? Number(next.scaleY) : 1;
750
+ const sceneScale = this.getSceneScale();
751
+ next.scaleX = rawScaleX * sceneScale;
752
+ next.scaleY = rawScaleY * sceneScale;
753
+ return next;
754
+ }
755
+
756
+ private moveObjectInContainer(
757
+ container: Group | Canvas,
758
+ obj: any,
759
+ index: number,
760
+ ) {
761
+ if (!obj) return;
762
+
763
+ const moveObjectTo = (container as any).moveObjectTo;
764
+ if (typeof moveObjectTo === "function") {
765
+ moveObjectTo.call(container, obj, index);
766
+ return;
767
+ }
768
+
769
+ const list = (container as any)._objects as any[] | undefined;
770
+ if (!Array.isArray(list)) return;
771
+ const from = list.indexOf(obj);
772
+ if (from < 0 || from === index) return;
773
+ list.splice(from, 1);
774
+ const target = Math.max(0, Math.min(index, list.length));
775
+ list.splice(target, 0, obj);
776
+ if (typeof (container as any)._onStackOrderChanged === "function") {
777
+ (container as any)._onStackOrderChanged();
778
+ }
779
+ }
780
+
781
+ private async createFabricObject(
782
+ spec: RenderObjectSpec,
783
+ ): Promise<FabricObject | undefined> {
784
+ if (spec.type === "rect") {
785
+ const props = this.resolveFabricProps(spec, spec.props || {});
786
+ const rect = new Rect({
787
+ ...props,
788
+ data: { ...(spec.data || {}), id: spec.id },
789
+ } as any);
790
+ rect.setCoords();
791
+ return rect;
792
+ }
793
+
794
+ if (spec.type === "path") {
795
+ const pathData =
796
+ (spec.props as any)?.path || (spec.props as any)?.pathData;
797
+ if (!pathData) return undefined;
798
+ const props = this.resolveFabricProps(spec, spec.props || {});
799
+ const path = new Path(pathData, {
800
+ ...props,
801
+ data: { ...(spec.data || {}), id: spec.id },
802
+ } as any);
803
+ path.setCoords();
804
+ return path;
805
+ }
806
+
807
+ if (spec.type === "image") {
808
+ if (!spec.src) return undefined;
809
+ const image = await Image.fromURL(spec.src, { crossOrigin: "anonymous" });
810
+ const props = this.resolveFabricProps(spec, spec.props || {});
811
+ image.set({
812
+ ...props,
813
+ data: { ...(spec.data || {}), id: spec.id },
814
+ } as any);
815
+ image.setCoords();
816
+ return image as any;
817
+ }
818
+
819
+ if (spec.type === "text") {
820
+ const content = String((spec.props as any)?.text ?? "");
821
+ const props = this.resolveFabricProps(spec, spec.props || {});
822
+ const text = new Text(content, {
823
+ ...props,
824
+ data: { ...(spec.data || {}), id: spec.id },
825
+ } as any);
826
+ text.setCoords();
827
+ return text as any;
828
+ }
829
+
830
+ return undefined;
831
+ }
832
+ }