@pooder/kit 4.3.1 → 5.0.1

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 +818 -0
  8. package/.test-dist/src/edgeScale.js +12 -0
  9. package/.test-dist/src/feature.js +754 -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 +342 -37
  31. package/dist/index.d.ts +342 -37
  32. package/dist/index.js +3679 -865
  33. package/dist/index.mjs +3673 -868
  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 +1005 -973
  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 +242 -84
  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,754 @@
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
+ // Keep feature markers above dieline overlay after config-driven redraw.
286
+ this.redraw();
287
+ return { ok: true };
288
+ }
289
+ addFeature(type) {
290
+ if (!this.canvasService)
291
+ return false;
292
+ // Default to top edge center
293
+ const newFeature = {
294
+ id: Date.now().toString(),
295
+ operation: type,
296
+ shape: "rect",
297
+ x: 0.5,
298
+ y: 0, // Top edge
299
+ width: 10,
300
+ height: 10,
301
+ rotation: 0,
302
+ renderBehavior: "edge",
303
+ // Default constraint: path (snap to edge)
304
+ constraints: [{ type: "path" }],
305
+ };
306
+ this.setWorkingFeatures([...(this.workingFeatures || []), newFeature]);
307
+ this.hasWorkingChanges = true;
308
+ this.redraw();
309
+ this.emitWorkingChange();
310
+ return true;
311
+ }
312
+ addDoubleLayerHole() {
313
+ if (!this.canvasService)
314
+ return false;
315
+ const groupId = Date.now().toString();
316
+ const timestamp = Date.now();
317
+ // 1. Lug (Outer) - Add
318
+ const lug = {
319
+ id: `${timestamp}-lug`,
320
+ groupId,
321
+ operation: "add",
322
+ shape: "circle",
323
+ x: 0.5,
324
+ y: 0,
325
+ radius: 20,
326
+ rotation: 0,
327
+ renderBehavior: "edge",
328
+ constraints: [{ type: "path" }],
329
+ };
330
+ // 2. Hole (Inner) - Subtract
331
+ const hole = {
332
+ id: `${timestamp}-hole`,
333
+ groupId,
334
+ operation: "subtract",
335
+ shape: "circle",
336
+ x: 0.5,
337
+ y: 0,
338
+ radius: 15,
339
+ rotation: 0,
340
+ renderBehavior: "edge",
341
+ constraints: [{ type: "path" }],
342
+ };
343
+ this.setWorkingFeatures([...(this.workingFeatures || []), lug, hole]);
344
+ this.hasWorkingChanges = true;
345
+ this.redraw();
346
+ this.emitWorkingChange();
347
+ return true;
348
+ }
349
+ getGeometryForFeature(geometry, feature) {
350
+ // Legacy support or specialized scaling can go here if needed
351
+ // Currently all features operate on the base geometry (or scaled version of it)
352
+ return geometry;
353
+ }
354
+ setup() {
355
+ if (!this.canvasService || !this.context)
356
+ return;
357
+ const canvas = this.canvasService.canvas;
358
+ // 1. Listen for Scene Geometry Changes
359
+ if (!this.handleSceneGeometryChange) {
360
+ this.handleSceneGeometryChange = (geometry) => {
361
+ this.currentGeometry = geometry;
362
+ this.redraw();
363
+ this.enforceConstraints();
364
+ };
365
+ this.context.eventBus.on("scene:geometry:change", this.handleSceneGeometryChange);
366
+ }
367
+ // 2. Initial Fetch of Geometry
368
+ const commandService = this.context.services.get("CommandService");
369
+ if (commandService) {
370
+ try {
371
+ Promise.resolve(commandService.executeCommand("getSceneGeometry")).then((g) => {
372
+ if (g) {
373
+ this.currentGeometry = g;
374
+ this.redraw();
375
+ }
376
+ });
377
+ }
378
+ catch (e) { }
379
+ }
380
+ // 3. Setup Canvas Interaction
381
+ if (!this.handleMoving) {
382
+ this.handleMoving = (e) => {
383
+ const target = e.target;
384
+ if (!target || target.data?.type !== "feature-marker")
385
+ return;
386
+ if (!this.currentGeometry)
387
+ return;
388
+ // Determine feature to use for snapping context
389
+ let feature;
390
+ if (target.data?.isGroup) {
391
+ const indices = target.data?.indices;
392
+ if (indices && indices.length > 0) {
393
+ feature = this.workingFeatures[indices[0]];
394
+ }
395
+ }
396
+ else {
397
+ const index = target.data?.index;
398
+ if (index !== undefined) {
399
+ feature = this.workingFeatures[index];
400
+ }
401
+ }
402
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
403
+ // Snap to edge during move
404
+ // For Group, target.left/top is group center (or top-left depending on origin)
405
+ // We snap the target position itself.
406
+ const p = new fabric_1.Point(target.left, target.top);
407
+ // Calculate limit based on target size (min dimension / 2 ensures overlap)
408
+ // Also subtract stroke width to ensure visual overlap (not just tangent)
409
+ // target.strokeWidth for group is usually 0, need a safe default (e.g. 2 for markers)
410
+ const markerStrokeWidth = (target.strokeWidth || 2) * (target.scaleX || 1);
411
+ const minDim = Math.min(target.getScaledWidth(), target.getScaledHeight());
412
+ const limit = Math.max(0, minDim / 2 - markerStrokeWidth);
413
+ const snapped = this.constrainPosition(p, geometry, limit, feature);
414
+ target.set({
415
+ left: snapped.x,
416
+ top: snapped.y,
417
+ });
418
+ };
419
+ canvas.on("object:moving", this.handleMoving);
420
+ }
421
+ if (!this.handleModified) {
422
+ this.handleModified = (e) => {
423
+ const target = e.target;
424
+ if (!target || target.data?.type !== "feature-marker")
425
+ return;
426
+ if (target.data?.isGroup) {
427
+ // It's a Group object
428
+ const groupObj = target;
429
+ // @ts-ignore
430
+ const indices = groupObj.data?.indices;
431
+ if (!indices)
432
+ return;
433
+ // We need to update all features in the group based on their new absolute positions.
434
+ // Fabric Group children positions are relative to group center.
435
+ // We need to calculate absolute position for each child.
436
+ // Note: groupObj has already been moved to new position (target.left, target.top)
437
+ const groupCenter = new fabric_1.Point(groupObj.left, groupObj.top);
438
+ // Get group matrix to transform children
439
+ // Simplified: just add relative coordinates if no rotation/scaling on group
440
+ // We locked rotation/scaling, so it's safe.
441
+ const newFeatures = [...this.workingFeatures];
442
+ const { x, y } = this.currentGeometry; // Center is same
443
+ // Fabric Group objects have .getObjects() which returns children
444
+ // But children inside group have coordinates relative to group center.
445
+ // center is (0,0) inside the group local coordinate system.
446
+ groupObj.getObjects().forEach((child, i) => {
447
+ const originalIndex = indices[i];
448
+ const feature = this.workingFeatures[originalIndex];
449
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
450
+ const { width, height } = geometry;
451
+ const layoutLeft = x - width / 2;
452
+ const layoutTop = y - height / 2;
453
+ // Calculate absolute position
454
+ // child.left/top are relative to group center
455
+ const absX = groupCenter.x + (child.left || 0);
456
+ const absY = groupCenter.y + (child.top || 0);
457
+ // Normalize
458
+ const normalizedX = width > 0 ? (absX - layoutLeft) / width : 0.5;
459
+ const normalizedY = height > 0 ? (absY - layoutTop) / height : 0.5;
460
+ newFeatures[originalIndex] = {
461
+ ...newFeatures[originalIndex],
462
+ x: normalizedX,
463
+ y: normalizedY,
464
+ };
465
+ });
466
+ this.setWorkingFeatures(newFeatures);
467
+ this.hasWorkingChanges = true;
468
+ this.emitWorkingChange();
469
+ }
470
+ else {
471
+ // Single object
472
+ this.syncFeatureFromCanvas(target);
473
+ }
474
+ };
475
+ canvas.on("object:modified", this.handleModified);
476
+ }
477
+ }
478
+ teardown() {
479
+ if (!this.canvasService)
480
+ return;
481
+ const canvas = this.canvasService.canvas;
482
+ if (this.handleMoving) {
483
+ canvas.off("object:moving", this.handleMoving);
484
+ this.handleMoving = null;
485
+ }
486
+ if (this.handleModified) {
487
+ canvas.off("object:modified", this.handleModified);
488
+ this.handleModified = null;
489
+ }
490
+ if (this.handleSceneGeometryChange && this.context) {
491
+ this.context.eventBus.off("scene:geometry:change", this.handleSceneGeometryChange);
492
+ this.handleSceneGeometryChange = null;
493
+ }
494
+ const objects = canvas
495
+ .getObjects()
496
+ .filter((obj) => obj.data?.type === "feature-marker");
497
+ objects.forEach((obj) => canvas.remove(obj));
498
+ this.canvasService.requestRenderAll();
499
+ }
500
+ constrainPosition(p, geometry, limit, feature) {
501
+ if (!feature) {
502
+ return { x: p.x, y: p.y };
503
+ }
504
+ const minX = geometry.x - geometry.width / 2;
505
+ const minY = geometry.y - geometry.height / 2;
506
+ // Normalize
507
+ const nx = geometry.width > 0 ? (p.x - minX) / geometry.width : 0.5;
508
+ const ny = geometry.height > 0 ? (p.y - minY) / geometry.height : 0.5;
509
+ const scale = geometry.scale || 1;
510
+ const dielineWidth = geometry.width / scale;
511
+ const dielineHeight = geometry.height / scale;
512
+ // Filter constraints: only apply those that are NOT validateOnly
513
+ const activeConstraints = feature.constraints?.filter((c) => !c.validateOnly);
514
+ const constrained = constraints_1.ConstraintRegistry.apply(nx, ny, feature, {
515
+ dielineWidth,
516
+ dielineHeight,
517
+ geometry,
518
+ }, activeConstraints);
519
+ // Denormalize
520
+ return {
521
+ x: minX + constrained.x * geometry.width,
522
+ y: minY + constrained.y * geometry.height,
523
+ };
524
+ }
525
+ syncFeatureFromCanvas(target) {
526
+ if (!this.currentGeometry || !this.context)
527
+ return;
528
+ const index = target.data?.index;
529
+ if (index === undefined ||
530
+ index < 0 ||
531
+ index >= this.workingFeatures.length)
532
+ return;
533
+ const feature = this.workingFeatures[index];
534
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
535
+ const { width, height, x, y } = geometry;
536
+ // Calculate Normalized Position
537
+ // The geometry x/y is the CENTER.
538
+ const left = x - width / 2;
539
+ const top = y - height / 2;
540
+ const normalizedX = width > 0 ? (target.left - left) / width : 0.5;
541
+ const normalizedY = height > 0 ? (target.top - top) / height : 0.5;
542
+ // Update feature
543
+ const updatedFeature = {
544
+ ...feature,
545
+ x: normalizedX,
546
+ y: normalizedY,
547
+ // Could also update rotation if we allowed rotating markers
548
+ };
549
+ const newFeatures = [...this.workingFeatures];
550
+ newFeatures[index] = updatedFeature;
551
+ this.setWorkingFeatures(newFeatures);
552
+ this.hasWorkingChanges = true;
553
+ this.emitWorkingChange();
554
+ }
555
+ redraw() {
556
+ if (!this.canvasService || !this.currentGeometry)
557
+ return;
558
+ const canvas = this.canvasService.canvas;
559
+ const geometry = this.currentGeometry;
560
+ // Remove existing markers
561
+ const existing = canvas
562
+ .getObjects()
563
+ .filter((obj) => obj.data?.type === "feature-marker");
564
+ existing.forEach((obj) => canvas.remove(obj));
565
+ if (!this.workingFeatures || this.workingFeatures.length === 0) {
566
+ this.canvasService.requestRenderAll();
567
+ return;
568
+ }
569
+ const scale = geometry.scale || 1;
570
+ const finalScale = scale;
571
+ // Group features by groupId
572
+ const groups = {};
573
+ const singles = [];
574
+ this.workingFeatures.forEach((f, i) => {
575
+ if (f.groupId) {
576
+ if (!groups[f.groupId])
577
+ groups[f.groupId] = [];
578
+ groups[f.groupId].push({ feature: f, index: i });
579
+ }
580
+ else {
581
+ singles.push({ feature: f, index: i });
582
+ }
583
+ });
584
+ // Helper to create marker shape
585
+ const createMarkerShape = (feature, pos) => {
586
+ const featureScale = scale;
587
+ const visualWidth = (feature.width || 10) * featureScale;
588
+ const visualHeight = (feature.height || 10) * featureScale;
589
+ const visualRadius = (feature.radius || 0) * featureScale;
590
+ const color = feature.color ||
591
+ (feature.operation === "add" ? "#00FF00" : "#FF0000");
592
+ const strokeDash = feature.strokeDash ||
593
+ (feature.operation === "subtract" ? [4, 4] : undefined);
594
+ let shape;
595
+ if (feature.shape === "rect") {
596
+ shape = new fabric_1.Rect({
597
+ width: visualWidth,
598
+ height: visualHeight,
599
+ rx: visualRadius,
600
+ ry: visualRadius,
601
+ fill: "transparent",
602
+ stroke: color,
603
+ strokeWidth: 2,
604
+ strokeDashArray: strokeDash,
605
+ originX: "center",
606
+ originY: "center",
607
+ left: pos.x,
608
+ top: pos.y,
609
+ });
610
+ }
611
+ else {
612
+ shape = new fabric_1.Circle({
613
+ radius: visualRadius || 5 * finalScale,
614
+ fill: "transparent",
615
+ stroke: color,
616
+ strokeWidth: 2,
617
+ strokeDashArray: strokeDash,
618
+ originX: "center",
619
+ originY: "center",
620
+ left: pos.x,
621
+ top: pos.y,
622
+ });
623
+ }
624
+ if (feature.rotation) {
625
+ shape.rotate(feature.rotation);
626
+ }
627
+ // Handle Indicator for Bridge
628
+ if (feature.bridge && feature.bridge.type === "vertical") {
629
+ // Create a visual indicator for the bridge
630
+ // A dashed rectangle extending upwards
631
+ const bridgeIndicator = new fabric_1.Rect({
632
+ width: visualWidth,
633
+ height: 100 * featureScale, // Arbitrary long length to show direction
634
+ fill: "transparent",
635
+ stroke: "#888",
636
+ strokeWidth: 1,
637
+ strokeDashArray: [2, 2],
638
+ originX: "center",
639
+ originY: "bottom", // Anchor at bottom so it extends up
640
+ left: pos.x,
641
+ top: pos.y - visualHeight / 2, // Start from top of feature
642
+ opacity: 0.5,
643
+ selectable: false,
644
+ evented: false
645
+ });
646
+ // We need to return a group containing both shape and indicator
647
+ // But createMarkerShape is expected to return one object.
648
+ // If we return a Group, Fabric handles it.
649
+ // But the caller might wrap this in another Group if it's part of a feature group.
650
+ // Fabric supports nested groups.
651
+ const group = new fabric_1.Group([bridgeIndicator, shape], {
652
+ originX: "center",
653
+ originY: "center",
654
+ left: pos.x,
655
+ top: pos.y
656
+ });
657
+ return group;
658
+ }
659
+ return shape;
660
+ };
661
+ // Render Singles
662
+ singles.forEach(({ feature, index }) => {
663
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
664
+ const pos = (0, geometry_1.resolveFeaturePosition)(feature, geometry);
665
+ const marker = createMarkerShape(feature, pos);
666
+ marker.set({
667
+ visible: this.isToolActive,
668
+ selectable: this.isToolActive,
669
+ evented: this.isToolActive,
670
+ hasControls: false,
671
+ hasBorders: false,
672
+ hoverCursor: "move",
673
+ lockRotation: true,
674
+ lockScalingX: true,
675
+ lockScalingY: true,
676
+ data: { type: "feature-marker", index, isGroup: false },
677
+ });
678
+ canvas.add(marker);
679
+ canvas.bringObjectToFront(marker);
680
+ });
681
+ // Render Groups
682
+ Object.keys(groups).forEach((groupId) => {
683
+ const members = groups[groupId];
684
+ if (members.length === 0)
685
+ return;
686
+ // Calculate group center (average position) to position the group correctly
687
+ // But Fabric Group uses relative coordinates.
688
+ // Easiest way: Create shapes at absolute positions, then Group them.
689
+ // Fabric will auto-calculate group center and adjust children.
690
+ const shapes = members.map(({ feature }) => {
691
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
692
+ const pos = (0, geometry_1.resolveFeaturePosition)(feature, geometry);
693
+ return createMarkerShape(feature, pos);
694
+ });
695
+ const groupObj = new fabric_1.Group(shapes, {
696
+ visible: this.isToolActive,
697
+ selectable: this.isToolActive,
698
+ evented: this.isToolActive,
699
+ hasControls: false,
700
+ hasBorders: false,
701
+ hoverCursor: "move",
702
+ lockRotation: true,
703
+ lockScalingX: true,
704
+ lockScalingY: true,
705
+ subTargetCheck: true, // Allow events to pass through if needed, but we treat as one
706
+ interactive: false, // Children not interactive
707
+ // @ts-ignore
708
+ data: {
709
+ type: "feature-marker",
710
+ isGroup: true,
711
+ groupId,
712
+ indices: members.map((m) => m.index),
713
+ },
714
+ });
715
+ canvas.add(groupObj);
716
+ canvas.bringObjectToFront(groupObj);
717
+ });
718
+ this.canvasService.requestRenderAll();
719
+ }
720
+ enforceConstraints() {
721
+ if (!this.canvasService || !this.currentGeometry)
722
+ return;
723
+ // Iterate markers and snap them if geometry changed
724
+ const canvas = this.canvasService.canvas;
725
+ const markers = canvas
726
+ .getObjects()
727
+ .filter((obj) => obj.data?.type === "feature-marker");
728
+ markers.forEach((marker) => {
729
+ // Find associated feature
730
+ let feature;
731
+ if (marker.data?.isGroup) {
732
+ const indices = marker.data?.indices;
733
+ if (indices && indices.length > 0) {
734
+ feature = this.workingFeatures[indices[0]];
735
+ }
736
+ }
737
+ else {
738
+ const index = marker.data?.index;
739
+ if (index !== undefined) {
740
+ feature = this.workingFeatures[index];
741
+ }
742
+ }
743
+ const geometry = this.getGeometryForFeature(this.currentGeometry, feature);
744
+ const markerStrokeWidth = (marker.strokeWidth || 2) * (marker.scaleX || 1);
745
+ const minDim = Math.min(marker.getScaledWidth(), marker.getScaledHeight());
746
+ const limit = Math.max(0, minDim / 2 - markerStrokeWidth);
747
+ const snapped = this.constrainPosition(new fabric_1.Point(marker.left, marker.top), geometry, limit, feature);
748
+ marker.set({ left: snapped.x, top: snapped.y });
749
+ marker.setCoords();
750
+ });
751
+ canvas.requestRenderAll();
752
+ }
753
+ }
754
+ exports.FeatureTool = FeatureTool;