@pooder/kit 4.3.0 → 5.0.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 (60) hide show
  1. package/.test-dist/src/CanvasService.js +249 -0
  2. package/.test-dist/src/ViewportSystem.js +75 -0
  3. package/.test-dist/src/background.js +203 -0
  4. package/.test-dist/src/bridgeSelection.js +20 -0
  5. package/.test-dist/src/constraints.js +237 -0
  6. package/.test-dist/src/coordinate.js +74 -0
  7. package/.test-dist/src/dieline.js +723 -0
  8. package/.test-dist/src/edgeScale.js +12 -0
  9. package/.test-dist/src/feature.js +752 -0
  10. package/.test-dist/src/featureComplete.js +32 -0
  11. package/.test-dist/src/film.js +167 -0
  12. package/.test-dist/src/geometry.js +506 -0
  13. package/.test-dist/src/image.js +1234 -0
  14. package/.test-dist/src/index.js +35 -0
  15. package/.test-dist/src/maskOps.js +270 -0
  16. package/.test-dist/src/mirror.js +104 -0
  17. package/.test-dist/src/renderSpec.js +2 -0
  18. package/.test-dist/src/ruler.js +343 -0
  19. package/.test-dist/src/sceneLayout.js +99 -0
  20. package/.test-dist/src/sceneLayoutModel.js +196 -0
  21. package/.test-dist/src/sceneView.js +40 -0
  22. package/.test-dist/src/sceneVisibility.js +42 -0
  23. package/.test-dist/src/size.js +332 -0
  24. package/.test-dist/src/tracer.js +544 -0
  25. package/.test-dist/src/units.js +30 -0
  26. package/.test-dist/src/white-ink.js +829 -0
  27. package/.test-dist/src/wrappedOffsets.js +33 -0
  28. package/.test-dist/tests/run.js +94 -0
  29. package/CHANGELOG.md +17 -0
  30. package/dist/index.d.mts +339 -36
  31. package/dist/index.d.ts +339 -36
  32. package/dist/index.js +3587 -854
  33. package/dist/index.mjs +3580 -856
  34. package/package.json +2 -2
  35. package/src/CanvasService.ts +300 -96
  36. package/src/ViewportSystem.ts +92 -92
  37. package/src/background.ts +230 -230
  38. package/src/bridgeSelection.ts +17 -0
  39. package/src/coordinate.ts +106 -106
  40. package/src/dieline.ts +897 -955
  41. package/src/edgeScale.ts +19 -0
  42. package/src/feature.ts +83 -30
  43. package/src/film.ts +194 -194
  44. package/src/geometry.ts +234 -80
  45. package/src/image.ts +1582 -512
  46. package/src/index.ts +14 -10
  47. package/src/maskOps.ts +326 -0
  48. package/src/mirror.ts +128 -128
  49. package/src/renderSpec.ts +18 -0
  50. package/src/ruler.ts +449 -508
  51. package/src/sceneLayout.ts +121 -0
  52. package/src/sceneLayoutModel.ts +335 -0
  53. package/src/sceneVisibility.ts +49 -0
  54. package/src/size.ts +379 -0
  55. package/src/tracer.ts +719 -570
  56. package/src/units.ts +27 -27
  57. package/src/white-ink.ts +1018 -373
  58. package/src/wrappedOffsets.ts +33 -0
  59. package/tests/run.ts +118 -0
  60. package/tsconfig.test.json +15 -15
@@ -0,0 +1,752 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FeatureTool = void 0;
4
+ const core_1 = require("@pooder/core");
5
+ const fabric_1 = require("fabric");
6
+ const geometry_1 = require("./geometry");
7
+ const constraints_1 = require("./constraints");
8
+ const featureComplete_1 = require("./featureComplete");
9
+ const sceneLayoutModel_1 = require("./sceneLayoutModel");
10
+ class FeatureTool {
11
+ constructor(options) {
12
+ this.id = "pooder.kit.feature";
13
+ this.metadata = {
14
+ name: "FeatureTool",
15
+ };
16
+ this.workingFeatures = [];
17
+ this.isUpdatingConfig = false;
18
+ this.isToolActive = false;
19
+ this.hasWorkingChanges = false;
20
+ this.handleMoving = null;
21
+ this.handleModified = null;
22
+ this.handleSceneGeometryChange = null;
23
+ this.currentGeometry = null;
24
+ this.onToolActivated = (event) => {
25
+ this.isToolActive = event.id === this.id;
26
+ this.updateVisibility();
27
+ };
28
+ if (options) {
29
+ Object.assign(this, options);
30
+ }
31
+ }
32
+ activate(context) {
33
+ this.context = context;
34
+ this.canvasService = context.services.get("CanvasService");
35
+ if (!this.canvasService) {
36
+ console.warn("CanvasService not found for FeatureTool");
37
+ return;
38
+ }
39
+ const configService = context.services.get("ConfigurationService");
40
+ if (configService) {
41
+ const features = (configService.get("dieline.features", []) ||
42
+ []);
43
+ this.workingFeatures = this.cloneFeatures(features);
44
+ this.hasWorkingChanges = false;
45
+ configService.onAnyChange((e) => {
46
+ if (this.isUpdatingConfig)
47
+ return;
48
+ if (e.key === "dieline.features") {
49
+ const next = (e.value || []);
50
+ this.workingFeatures = this.cloneFeatures(next);
51
+ this.hasWorkingChanges = false;
52
+ this.redraw();
53
+ this.emitWorkingChange();
54
+ }
55
+ });
56
+ }
57
+ const toolSessionService = context.services.get("ToolSessionService");
58
+ this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(this.id, () => this.hasWorkingChanges);
59
+ // Listen to tool activation
60
+ context.eventBus.on("tool:activated", this.onToolActivated);
61
+ this.setup();
62
+ }
63
+ deactivate(context) {
64
+ context.eventBus.off("tool:activated", this.onToolActivated);
65
+ this.dirtyTrackerDisposable?.dispose();
66
+ this.dirtyTrackerDisposable = undefined;
67
+ this.teardown();
68
+ this.canvasService = undefined;
69
+ this.context = undefined;
70
+ }
71
+ updateVisibility() {
72
+ if (!this.canvasService)
73
+ return;
74
+ const canvas = this.canvasService.canvas;
75
+ const markers = canvas
76
+ .getObjects()
77
+ .filter((obj) => obj.data?.type === "feature-marker");
78
+ markers.forEach((marker) => {
79
+ // If tool active, allow selection. If not, disable selection.
80
+ // Also might want to hide them entirely or just disable interaction.
81
+ // Assuming we only want to see/edit holes when tool is active.
82
+ marker.set({
83
+ visible: this.isToolActive, // Or just selectable: false if we want them visible but locked
84
+ selectable: this.isToolActive,
85
+ evented: this.isToolActive
86
+ });
87
+ });
88
+ canvas.requestRenderAll();
89
+ }
90
+ contribute() {
91
+ return {
92
+ [core_1.ContributionPointIds.TOOLS]: [
93
+ {
94
+ id: this.id,
95
+ name: "Feature",
96
+ interaction: "session",
97
+ commands: {
98
+ begin: "resetWorkingFeatures",
99
+ commit: "completeFeatures",
100
+ rollback: "resetWorkingFeatures",
101
+ },
102
+ session: {
103
+ autoBegin: false,
104
+ leavePolicy: "block",
105
+ },
106
+ },
107
+ ],
108
+ [core_1.ContributionPointIds.COMMANDS]: [
109
+ {
110
+ command: "addFeature",
111
+ title: "Add Edge Feature",
112
+ handler: (type = "subtract") => {
113
+ return this.addFeature(type);
114
+ },
115
+ },
116
+ {
117
+ command: "addHole",
118
+ title: "Add Hole",
119
+ handler: () => {
120
+ return this.addFeature("subtract");
121
+ },
122
+ },
123
+ {
124
+ command: "addDoubleLayerHole",
125
+ title: "Add Double Layer Hole",
126
+ handler: () => {
127
+ return this.addDoubleLayerHole();
128
+ },
129
+ },
130
+ {
131
+ command: "clearFeatures",
132
+ title: "Clear Features",
133
+ handler: () => {
134
+ this.setWorkingFeatures([]);
135
+ this.hasWorkingChanges = true;
136
+ this.redraw();
137
+ this.emitWorkingChange();
138
+ return true;
139
+ },
140
+ },
141
+ {
142
+ command: "getWorkingFeatures",
143
+ title: "Get Working Features",
144
+ handler: () => {
145
+ return this.cloneFeatures(this.workingFeatures);
146
+ },
147
+ },
148
+ {
149
+ command: "setWorkingFeatures",
150
+ title: "Set Working Features",
151
+ handler: async (features) => {
152
+ await this.refreshGeometry();
153
+ this.setWorkingFeatures(this.cloneFeatures(features || []));
154
+ this.hasWorkingChanges = true;
155
+ this.redraw();
156
+ this.emitWorkingChange();
157
+ return { ok: true };
158
+ },
159
+ },
160
+ {
161
+ command: "resetWorkingFeatures",
162
+ title: "Reset Working Features",
163
+ handler: async () => {
164
+ const configService = this.context?.services.get("ConfigurationService");
165
+ const next = (configService?.get("dieline.features", []) ||
166
+ []);
167
+ await this.refreshGeometry();
168
+ this.setWorkingFeatures(this.cloneFeatures(next));
169
+ this.hasWorkingChanges = false;
170
+ this.redraw();
171
+ this.emitWorkingChange();
172
+ return { ok: true };
173
+ },
174
+ },
175
+ {
176
+ command: "updateWorkingGroupPosition",
177
+ title: "Update Working Group Position",
178
+ handler: (groupId, x, y) => {
179
+ return this.updateWorkingGroupPosition(groupId, x, y);
180
+ },
181
+ },
182
+ {
183
+ command: "completeFeatures",
184
+ title: "Complete Features",
185
+ handler: () => {
186
+ return this.completeFeatures();
187
+ },
188
+ },
189
+ ],
190
+ };
191
+ }
192
+ cloneFeatures(features) {
193
+ return JSON.parse(JSON.stringify(features || []));
194
+ }
195
+ emitWorkingChange() {
196
+ this.context?.eventBus.emit("feature:working:change", {
197
+ features: this.cloneFeatures(this.workingFeatures),
198
+ });
199
+ }
200
+ async refreshGeometry() {
201
+ if (!this.context)
202
+ return;
203
+ const commandService = this.context.services.get("CommandService");
204
+ if (!commandService)
205
+ return;
206
+ try {
207
+ const g = await Promise.resolve(commandService.executeCommand("getSceneGeometry"));
208
+ if (g)
209
+ this.currentGeometry = g;
210
+ }
211
+ catch (e) { }
212
+ }
213
+ setWorkingFeatures(next) {
214
+ this.workingFeatures = next;
215
+ }
216
+ updateWorkingGroupPosition(groupId, x, y) {
217
+ if (!groupId)
218
+ return { ok: false };
219
+ const configService = this.context?.services.get("ConfigurationService");
220
+ if (!configService)
221
+ return { ok: false };
222
+ const sizeState = (0, sceneLayoutModel_1.readSizeState)(configService);
223
+ const dielineWidth = sizeState.actualWidthMm;
224
+ const dielineHeight = sizeState.actualHeightMm;
225
+ let changed = false;
226
+ const next = this.workingFeatures.map((f) => {
227
+ if (f.groupId !== groupId)
228
+ return f;
229
+ let nx = x;
230
+ let ny = y;
231
+ if (f.constraints && dielineWidth > 0 && dielineHeight > 0) {
232
+ const constrained = constraints_1.ConstraintRegistry.apply(nx, ny, f, {
233
+ dielineWidth,
234
+ dielineHeight,
235
+ });
236
+ nx = constrained.x;
237
+ ny = constrained.y;
238
+ }
239
+ if (f.x !== nx || f.y !== ny) {
240
+ changed = true;
241
+ return { ...f, x: nx, y: ny };
242
+ }
243
+ return f;
244
+ });
245
+ if (!changed)
246
+ return { ok: true };
247
+ this.setWorkingFeatures(next);
248
+ this.hasWorkingChanges = true;
249
+ this.redraw();
250
+ this.enforceConstraints();
251
+ this.emitWorkingChange();
252
+ return { ok: true };
253
+ }
254
+ completeFeatures() {
255
+ const configService = this.context?.services.get("ConfigurationService");
256
+ if (!configService) {
257
+ return {
258
+ ok: false,
259
+ issues: [
260
+ { featureId: "unknown", reason: "ConfigurationService not found" },
261
+ ],
262
+ };
263
+ }
264
+ const sizeState = (0, sceneLayoutModel_1.readSizeState)(configService);
265
+ const dielineWidth = sizeState.actualWidthMm;
266
+ const dielineHeight = sizeState.actualHeightMm;
267
+ const result = (0, featureComplete_1.completeFeaturesStrict)(this.workingFeatures, { dielineWidth, dielineHeight }, (next) => {
268
+ this.isUpdatingConfig = true;
269
+ try {
270
+ configService.update("dieline.features", next);
271
+ }
272
+ finally {
273
+ this.isUpdatingConfig = false;
274
+ }
275
+ this.workingFeatures = this.cloneFeatures(next);
276
+ this.emitWorkingChange();
277
+ });
278
+ if (!result.ok) {
279
+ return {
280
+ ok: false,
281
+ issues: result.issues,
282
+ };
283
+ }
284
+ this.hasWorkingChanges = false;
285
+ return { ok: true };
286
+ }
287
+ addFeature(type) {
288
+ if (!this.canvasService)
289
+ return false;
290
+ // Default to top edge center
291
+ const newFeature = {
292
+ id: Date.now().toString(),
293
+ operation: type,
294
+ shape: "rect",
295
+ x: 0.5,
296
+ y: 0, // Top edge
297
+ width: 10,
298
+ height: 10,
299
+ rotation: 0,
300
+ renderBehavior: "edge",
301
+ // Default constraint: path (snap to edge)
302
+ constraints: [{ type: "path" }],
303
+ };
304
+ this.setWorkingFeatures([...(this.workingFeatures || []), newFeature]);
305
+ this.hasWorkingChanges = true;
306
+ this.redraw();
307
+ this.emitWorkingChange();
308
+ return true;
309
+ }
310
+ addDoubleLayerHole() {
311
+ if (!this.canvasService)
312
+ return false;
313
+ const groupId = Date.now().toString();
314
+ const timestamp = Date.now();
315
+ // 1. Lug (Outer) - Add
316
+ const lug = {
317
+ id: `${timestamp}-lug`,
318
+ groupId,
319
+ operation: "add",
320
+ shape: "circle",
321
+ x: 0.5,
322
+ y: 0,
323
+ radius: 20,
324
+ rotation: 0,
325
+ renderBehavior: "edge",
326
+ constraints: [{ type: "path" }],
327
+ };
328
+ // 2. Hole (Inner) - Subtract
329
+ const hole = {
330
+ id: `${timestamp}-hole`,
331
+ groupId,
332
+ operation: "subtract",
333
+ shape: "circle",
334
+ x: 0.5,
335
+ y: 0,
336
+ radius: 15,
337
+ rotation: 0,
338
+ renderBehavior: "edge",
339
+ constraints: [{ type: "path" }],
340
+ };
341
+ this.setWorkingFeatures([...(this.workingFeatures || []), lug, hole]);
342
+ this.hasWorkingChanges = true;
343
+ this.redraw();
344
+ this.emitWorkingChange();
345
+ return true;
346
+ }
347
+ getGeometryForFeature(geometry, feature) {
348
+ // Legacy support or specialized scaling can go here if needed
349
+ // Currently all features operate on the base geometry (or scaled version of it)
350
+ return geometry;
351
+ }
352
+ setup() {
353
+ if (!this.canvasService || !this.context)
354
+ return;
355
+ const canvas = this.canvasService.canvas;
356
+ // 1. Listen for Scene Geometry Changes
357
+ if (!this.handleSceneGeometryChange) {
358
+ this.handleSceneGeometryChange = (geometry) => {
359
+ this.currentGeometry = geometry;
360
+ this.redraw();
361
+ this.enforceConstraints();
362
+ };
363
+ this.context.eventBus.on("scene:geometry:change", this.handleSceneGeometryChange);
364
+ }
365
+ // 2. Initial Fetch of Geometry
366
+ const commandService = this.context.services.get("CommandService");
367
+ if (commandService) {
368
+ try {
369
+ Promise.resolve(commandService.executeCommand("getSceneGeometry")).then((g) => {
370
+ if (g) {
371
+ this.currentGeometry = g;
372
+ this.redraw();
373
+ }
374
+ });
375
+ }
376
+ catch (e) { }
377
+ }
378
+ // 3. Setup Canvas Interaction
379
+ if (!this.handleMoving) {
380
+ this.handleMoving = (e) => {
381
+ const target = e.target;
382
+ if (!target || target.data?.type !== "feature-marker")
383
+ return;
384
+ if (!this.currentGeometry)
385
+ return;
386
+ // Determine feature to use for snapping context
387
+ let feature;
388
+ if (target.data?.isGroup) {
389
+ const indices = target.data?.indices;
390
+ if (indices && indices.length > 0) {
391
+ feature = this.workingFeatures[indices[0]];
392
+ }
393
+ }
394
+ else {
395
+ const index = target.data?.index;
396
+ if (index !== undefined) {
397
+ feature = this.workingFeatures[index];
398
+ }
399
+ }
400
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
401
+ // Snap to edge during move
402
+ // For Group, target.left/top is group center (or top-left depending on origin)
403
+ // We snap the target position itself.
404
+ const p = new fabric_1.Point(target.left, target.top);
405
+ // Calculate limit based on target size (min dimension / 2 ensures overlap)
406
+ // Also subtract stroke width to ensure visual overlap (not just tangent)
407
+ // target.strokeWidth for group is usually 0, need a safe default (e.g. 2 for markers)
408
+ const markerStrokeWidth = (target.strokeWidth || 2) * (target.scaleX || 1);
409
+ const minDim = Math.min(target.getScaledWidth(), target.getScaledHeight());
410
+ const limit = Math.max(0, minDim / 2 - markerStrokeWidth);
411
+ const snapped = this.constrainPosition(p, geometry, limit, feature);
412
+ target.set({
413
+ left: snapped.x,
414
+ top: snapped.y,
415
+ });
416
+ };
417
+ canvas.on("object:moving", this.handleMoving);
418
+ }
419
+ if (!this.handleModified) {
420
+ this.handleModified = (e) => {
421
+ const target = e.target;
422
+ if (!target || target.data?.type !== "feature-marker")
423
+ return;
424
+ if (target.data?.isGroup) {
425
+ // It's a Group object
426
+ const groupObj = target;
427
+ // @ts-ignore
428
+ const indices = groupObj.data?.indices;
429
+ if (!indices)
430
+ return;
431
+ // We need to update all features in the group based on their new absolute positions.
432
+ // Fabric Group children positions are relative to group center.
433
+ // We need to calculate absolute position for each child.
434
+ // Note: groupObj has already been moved to new position (target.left, target.top)
435
+ const groupCenter = new fabric_1.Point(groupObj.left, groupObj.top);
436
+ // Get group matrix to transform children
437
+ // Simplified: just add relative coordinates if no rotation/scaling on group
438
+ // We locked rotation/scaling, so it's safe.
439
+ const newFeatures = [...this.workingFeatures];
440
+ const { x, y } = this.currentGeometry; // Center is same
441
+ // Fabric Group objects have .getObjects() which returns children
442
+ // But children inside group have coordinates relative to group center.
443
+ // center is (0,0) inside the group local coordinate system.
444
+ groupObj.getObjects().forEach((child, i) => {
445
+ const originalIndex = indices[i];
446
+ const feature = this.workingFeatures[originalIndex];
447
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
448
+ const { width, height } = geometry;
449
+ const layoutLeft = x - width / 2;
450
+ const layoutTop = y - height / 2;
451
+ // Calculate absolute position
452
+ // child.left/top are relative to group center
453
+ const absX = groupCenter.x + (child.left || 0);
454
+ const absY = groupCenter.y + (child.top || 0);
455
+ // Normalize
456
+ const normalizedX = width > 0 ? (absX - layoutLeft) / width : 0.5;
457
+ const normalizedY = height > 0 ? (absY - layoutTop) / height : 0.5;
458
+ newFeatures[originalIndex] = {
459
+ ...newFeatures[originalIndex],
460
+ x: normalizedX,
461
+ y: normalizedY,
462
+ };
463
+ });
464
+ this.setWorkingFeatures(newFeatures);
465
+ this.hasWorkingChanges = true;
466
+ this.emitWorkingChange();
467
+ }
468
+ else {
469
+ // Single object
470
+ this.syncFeatureFromCanvas(target);
471
+ }
472
+ };
473
+ canvas.on("object:modified", this.handleModified);
474
+ }
475
+ }
476
+ teardown() {
477
+ if (!this.canvasService)
478
+ return;
479
+ const canvas = this.canvasService.canvas;
480
+ if (this.handleMoving) {
481
+ canvas.off("object:moving", this.handleMoving);
482
+ this.handleMoving = null;
483
+ }
484
+ if (this.handleModified) {
485
+ canvas.off("object:modified", this.handleModified);
486
+ this.handleModified = null;
487
+ }
488
+ if (this.handleSceneGeometryChange && this.context) {
489
+ this.context.eventBus.off("scene:geometry:change", this.handleSceneGeometryChange);
490
+ this.handleSceneGeometryChange = null;
491
+ }
492
+ const objects = canvas
493
+ .getObjects()
494
+ .filter((obj) => obj.data?.type === "feature-marker");
495
+ objects.forEach((obj) => canvas.remove(obj));
496
+ this.canvasService.requestRenderAll();
497
+ }
498
+ constrainPosition(p, geometry, limit, feature) {
499
+ if (!feature) {
500
+ return { x: p.x, y: p.y };
501
+ }
502
+ const minX = geometry.x - geometry.width / 2;
503
+ const minY = geometry.y - geometry.height / 2;
504
+ // Normalize
505
+ const nx = geometry.width > 0 ? (p.x - minX) / geometry.width : 0.5;
506
+ const ny = geometry.height > 0 ? (p.y - minY) / geometry.height : 0.5;
507
+ const scale = geometry.scale || 1;
508
+ const dielineWidth = geometry.width / scale;
509
+ const dielineHeight = geometry.height / scale;
510
+ // Filter constraints: only apply those that are NOT validateOnly
511
+ const activeConstraints = feature.constraints?.filter((c) => !c.validateOnly);
512
+ const constrained = constraints_1.ConstraintRegistry.apply(nx, ny, feature, {
513
+ dielineWidth,
514
+ dielineHeight,
515
+ geometry,
516
+ }, activeConstraints);
517
+ // Denormalize
518
+ return {
519
+ x: minX + constrained.x * geometry.width,
520
+ y: minY + constrained.y * geometry.height,
521
+ };
522
+ }
523
+ syncFeatureFromCanvas(target) {
524
+ if (!this.currentGeometry || !this.context)
525
+ return;
526
+ const index = target.data?.index;
527
+ if (index === undefined ||
528
+ index < 0 ||
529
+ index >= this.workingFeatures.length)
530
+ return;
531
+ const feature = this.workingFeatures[index];
532
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
533
+ const { width, height, x, y } = geometry;
534
+ // Calculate Normalized Position
535
+ // The geometry x/y is the CENTER.
536
+ const left = x - width / 2;
537
+ const top = y - height / 2;
538
+ const normalizedX = width > 0 ? (target.left - left) / width : 0.5;
539
+ const normalizedY = height > 0 ? (target.top - top) / height : 0.5;
540
+ // Update feature
541
+ const updatedFeature = {
542
+ ...feature,
543
+ x: normalizedX,
544
+ y: normalizedY,
545
+ // Could also update rotation if we allowed rotating markers
546
+ };
547
+ const newFeatures = [...this.workingFeatures];
548
+ newFeatures[index] = updatedFeature;
549
+ this.setWorkingFeatures(newFeatures);
550
+ this.hasWorkingChanges = true;
551
+ this.emitWorkingChange();
552
+ }
553
+ redraw() {
554
+ if (!this.canvasService || !this.currentGeometry)
555
+ return;
556
+ const canvas = this.canvasService.canvas;
557
+ const geometry = this.currentGeometry;
558
+ // Remove existing markers
559
+ const existing = canvas
560
+ .getObjects()
561
+ .filter((obj) => obj.data?.type === "feature-marker");
562
+ existing.forEach((obj) => canvas.remove(obj));
563
+ if (!this.workingFeatures || this.workingFeatures.length === 0) {
564
+ this.canvasService.requestRenderAll();
565
+ return;
566
+ }
567
+ const scale = geometry.scale || 1;
568
+ const finalScale = scale;
569
+ // Group features by groupId
570
+ const groups = {};
571
+ const singles = [];
572
+ this.workingFeatures.forEach((f, i) => {
573
+ if (f.groupId) {
574
+ if (!groups[f.groupId])
575
+ groups[f.groupId] = [];
576
+ groups[f.groupId].push({ feature: f, index: i });
577
+ }
578
+ else {
579
+ singles.push({ feature: f, index: i });
580
+ }
581
+ });
582
+ // Helper to create marker shape
583
+ const createMarkerShape = (feature, pos) => {
584
+ const featureScale = scale;
585
+ const visualWidth = (feature.width || 10) * featureScale;
586
+ const visualHeight = (feature.height || 10) * featureScale;
587
+ const visualRadius = (feature.radius || 0) * featureScale;
588
+ const color = feature.color ||
589
+ (feature.operation === "add" ? "#00FF00" : "#FF0000");
590
+ const strokeDash = feature.strokeDash ||
591
+ (feature.operation === "subtract" ? [4, 4] : undefined);
592
+ let shape;
593
+ if (feature.shape === "rect") {
594
+ shape = new fabric_1.Rect({
595
+ width: visualWidth,
596
+ height: visualHeight,
597
+ rx: visualRadius,
598
+ ry: visualRadius,
599
+ fill: "transparent",
600
+ stroke: color,
601
+ strokeWidth: 2,
602
+ strokeDashArray: strokeDash,
603
+ originX: "center",
604
+ originY: "center",
605
+ left: pos.x,
606
+ top: pos.y,
607
+ });
608
+ }
609
+ else {
610
+ shape = new fabric_1.Circle({
611
+ radius: visualRadius || 5 * finalScale,
612
+ fill: "transparent",
613
+ stroke: color,
614
+ strokeWidth: 2,
615
+ strokeDashArray: strokeDash,
616
+ originX: "center",
617
+ originY: "center",
618
+ left: pos.x,
619
+ top: pos.y,
620
+ });
621
+ }
622
+ if (feature.rotation) {
623
+ shape.rotate(feature.rotation);
624
+ }
625
+ // Handle Indicator for Bridge
626
+ if (feature.bridge && feature.bridge.type === "vertical") {
627
+ // Create a visual indicator for the bridge
628
+ // A dashed rectangle extending upwards
629
+ const bridgeIndicator = new fabric_1.Rect({
630
+ width: visualWidth,
631
+ height: 100 * featureScale, // Arbitrary long length to show direction
632
+ fill: "transparent",
633
+ stroke: "#888",
634
+ strokeWidth: 1,
635
+ strokeDashArray: [2, 2],
636
+ originX: "center",
637
+ originY: "bottom", // Anchor at bottom so it extends up
638
+ left: pos.x,
639
+ top: pos.y - visualHeight / 2, // Start from top of feature
640
+ opacity: 0.5,
641
+ selectable: false,
642
+ evented: false
643
+ });
644
+ // We need to return a group containing both shape and indicator
645
+ // But createMarkerShape is expected to return one object.
646
+ // If we return a Group, Fabric handles it.
647
+ // But the caller might wrap this in another Group if it's part of a feature group.
648
+ // Fabric supports nested groups.
649
+ const group = new fabric_1.Group([bridgeIndicator, shape], {
650
+ originX: "center",
651
+ originY: "center",
652
+ left: pos.x,
653
+ top: pos.y
654
+ });
655
+ return group;
656
+ }
657
+ return shape;
658
+ };
659
+ // Render Singles
660
+ singles.forEach(({ feature, index }) => {
661
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
662
+ const pos = (0, geometry_1.resolveFeaturePosition)(feature, geometry);
663
+ const marker = createMarkerShape(feature, pos);
664
+ marker.set({
665
+ visible: this.isToolActive,
666
+ selectable: this.isToolActive,
667
+ evented: this.isToolActive,
668
+ hasControls: false,
669
+ hasBorders: false,
670
+ hoverCursor: "move",
671
+ lockRotation: true,
672
+ lockScalingX: true,
673
+ lockScalingY: true,
674
+ data: { type: "feature-marker", index, isGroup: false },
675
+ });
676
+ canvas.add(marker);
677
+ canvas.bringObjectToFront(marker);
678
+ });
679
+ // Render Groups
680
+ Object.keys(groups).forEach((groupId) => {
681
+ const members = groups[groupId];
682
+ if (members.length === 0)
683
+ return;
684
+ // Calculate group center (average position) to position the group correctly
685
+ // But Fabric Group uses relative coordinates.
686
+ // Easiest way: Create shapes at absolute positions, then Group them.
687
+ // Fabric will auto-calculate group center and adjust children.
688
+ const shapes = members.map(({ feature }) => {
689
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
690
+ const pos = (0, geometry_1.resolveFeaturePosition)(feature, geometry);
691
+ return createMarkerShape(feature, pos);
692
+ });
693
+ const groupObj = new fabric_1.Group(shapes, {
694
+ visible: this.isToolActive,
695
+ selectable: this.isToolActive,
696
+ evented: this.isToolActive,
697
+ hasControls: false,
698
+ hasBorders: false,
699
+ hoverCursor: "move",
700
+ lockRotation: true,
701
+ lockScalingX: true,
702
+ lockScalingY: true,
703
+ subTargetCheck: true, // Allow events to pass through if needed, but we treat as one
704
+ interactive: false, // Children not interactive
705
+ // @ts-ignore
706
+ data: {
707
+ type: "feature-marker",
708
+ isGroup: true,
709
+ groupId,
710
+ indices: members.map((m) => m.index),
711
+ },
712
+ });
713
+ canvas.add(groupObj);
714
+ canvas.bringObjectToFront(groupObj);
715
+ });
716
+ this.canvasService.requestRenderAll();
717
+ }
718
+ enforceConstraints() {
719
+ if (!this.canvasService || !this.currentGeometry)
720
+ return;
721
+ // Iterate markers and snap them if geometry changed
722
+ const canvas = this.canvasService.canvas;
723
+ const markers = canvas
724
+ .getObjects()
725
+ .filter((obj) => obj.data?.type === "feature-marker");
726
+ markers.forEach((marker) => {
727
+ // Find associated feature
728
+ let feature;
729
+ if (marker.data?.isGroup) {
730
+ const indices = marker.data?.indices;
731
+ if (indices && indices.length > 0) {
732
+ feature = this.workingFeatures[indices[0]];
733
+ }
734
+ }
735
+ else {
736
+ const index = marker.data?.index;
737
+ if (index !== undefined) {
738
+ feature = this.workingFeatures[index];
739
+ }
740
+ }
741
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
742
+ const markerStrokeWidth = (marker.strokeWidth || 2) * (marker.scaleX || 1);
743
+ const minDim = Math.min(marker.getScaledWidth(), marker.getScaledHeight());
744
+ const limit = Math.max(0, minDim / 2 - markerStrokeWidth);
745
+ const snapped = this.constrainPosition(new fabric_1.Point(marker.left, marker.top), geometry, limit, feature);
746
+ marker.set({ left: snapped.x, top: snapped.y });
747
+ marker.setCoords();
748
+ });
749
+ canvas.requestRenderAll();
750
+ }
751
+ }
752
+ exports.FeatureTool = FeatureTool;