@widgetic/canvas 0.5.14 → 0.5.15

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.
@@ -30,8 +30,19 @@
30
30
  import { ImageShape, IMAGE_SHAPE_CUSTOM_PROPS, upgradeToImageShape } from './shapes/ImageShape';
31
31
  import { WidgetShape, WIDGET_SHAPE_CUSTOM_PROPS, upgradeToWidgetShape, restoreThumbnailFromStore } from './shapes/WidgetShape';
32
32
  import { SHAPE_LIBRARY, getShapeByKey, generatePathForShape } from './shapes/ShapeLibrary';
33
+ import {
34
+ CANVAS_SHAPE_SNAP_ENABLED,
35
+ CANVAS_SNAP_SHAPE_LABELS,
36
+ confidentSnapShape,
37
+ flattenPathCommands,
38
+ measureStroke,
39
+ planSnapPlacement,
40
+ rankSnapShapes,
41
+ type CanvasSnapShape,
42
+ type PathCommand
43
+ } from './shapes/strokeShapeSnap';
33
44
  import { canvasLog, canvasWarn, setCanvasLogsEnabled } from './canvasLogger';
34
- import type { WidgetConversionPayload } from './types';
45
+ import type { WidgetConversionPayload, StrokeRecognizer } from './types';
35
46
 
36
47
  // ── Library shape path fingerprints (migration for old saves) ──────────────
37
48
  // Maps a normalized path string → shape key. Used to identify library shapes
@@ -43,17 +54,15 @@
43
54
  // Lazily evaluated to avoid blocking the main thread during module load.
44
55
  let _shapeLibraryFingerprints: Map<string, string> | null = null;
45
56
  function getShapeLibraryFingerprints(): Map<string, string> {
46
- if (!_shapeLibraryFingerprints) {
47
- _shapeLibraryFingerprints = new Map<string, string>();
48
- SHAPE_LIBRARY.forEach((shapeDef) => {
49
- try {
50
- const parsed = (fabricUtil as any).parsePath(shapeDef.pathData);
51
- const simplified = (fabricUtil as any).makePathSimpler?.(parsed) ?? parsed;
52
- if (simplified) _shapeLibraryFingerprints.set((fabricUtil as any).joinPath(simplified), shapeDef.key);
53
- } catch { /* ignore */ }
54
- });
55
- }
56
- return _shapeLibraryFingerprints;
57
+ const fingerprints = _shapeLibraryFingerprints ?? (_shapeLibraryFingerprints = new Map<string, string>());
58
+ SHAPE_LIBRARY.forEach((shapeDef) => {
59
+ try {
60
+ const parsed = (fabricUtil as any).parsePath(shapeDef.pathData);
61
+ const simplified = (fabricUtil as any).makePathSimpler?.(parsed) ?? parsed;
62
+ if (simplified) fingerprints.set((fabricUtil as any).joinPath(simplified), shapeDef.key);
63
+ } catch { /* ignore */ }
64
+ });
65
+ return fingerprints;
57
66
  }
58
67
 
59
68
  // ── Textbox prototype patch: fix drawBorders for text padding inside groups/frames ──
@@ -216,6 +225,11 @@
216
225
  // The host can use this to open WidgetDetails for the linked widget.
217
226
  export let onWidgetImageClick: ((widgetId: string) => void) | null = null;
218
227
 
228
+ // Callback: classify a freehand stroke the geometry engine could not decide
229
+ // on its own. The host owns the model call; returning null — or a shape the
230
+ // geometry ruled out — leaves the stroke exactly as drawn.
231
+ export let onRecognizeStroke: StrokeRecognizer | null = null;
232
+
219
233
  // Callback: fires when a non-widget shape is selected on canvas.
220
234
  // The host can use this to close WidgetDetails panel.
221
235
  export let onNonWidgetSelected: (() => void) | null = null;
@@ -267,6 +281,11 @@
267
281
 
268
282
  // Refferences
269
283
  let canvasEl: HTMLCanvasElement | null = null;
284
+ /**
285
+ * The live fabric instance. Assigned once in onMount and nulled in
286
+ * onDestroy, so every handler in between can rely on it — the `canvas!`
287
+ * suffixes below encode that lifecycle contract (init → teardown).
288
+ */
270
289
  let canvas: Canvas | null = null;
271
290
 
272
291
  // Canvas state & configuration
@@ -578,7 +597,7 @@
578
597
  stampTopLevelPaintOrder();
579
598
  canvasLog('Canvas: rebuilt group after edit', {
580
599
  children: children.length,
581
- objectId: newGroup._objectId,
600
+ objectId: (newGroup as any)._objectId,
582
601
  });
583
602
  return newGroup;
584
603
  }
@@ -640,7 +659,9 @@
640
659
  let shapeStrokeWidth = 1;
641
660
 
642
661
  type ShapeToolType = 'rect' | 'circle' | 'circle-true' | 'triangle' | 'arrow';
643
- type ConstraintType = 'none' | 'square' | 'equilateral';
662
+ // 'circle' is the 1:1 constraint used by circle-true (and reachable for
663
+ // other shapes via getConstrainedPointer).
664
+ type ConstraintType = 'none' | 'square' | 'equilateral' | 'circle';
644
665
 
645
666
  const SHAPE_CONSTRAINT_MAP: Record<ShapeToolType, ConstraintType> = {
646
667
  rect: 'square',
@@ -659,8 +680,10 @@
659
680
  let lastAppliedBounds: { left: number; top: number; width: number; height: number } | null = null;
660
681
  let shapeKeyboardListenersAttached = false;
661
682
  let canvasScalingHandlers: {
662
- scaling: fabric.IEventHandler<Event>;
663
- scaled: fabric.IEventHandler<Event>;
683
+ // fabric v6's generic event map lost these custom names; the handlers
684
+ // still compile to plain (e: IEvent<Event>) => void at runtime.
685
+ scaling: (e: { e: Event }) => void;
686
+ scaled: (e: { e: Event }) => void;
664
687
  } | null = null;
665
688
 
666
689
  /**
@@ -1027,7 +1050,7 @@
1027
1050
  const isFrame = obj ? isFrameShape(obj) : false;
1028
1051
  const bounds = pendingConversion?.bounds ??
1029
1052
  (obj
1030
- ? obj.getBoundingRect(true)
1053
+ ? obj.getBoundingRect()
1031
1054
  : (() => {
1032
1055
  const a = canvas.getActiveObject() as any;
1033
1056
  return a ? a.getBoundingRect(true) : { left: 0, top: 0, width: 200, height: 200 };
@@ -1100,7 +1123,7 @@
1100
1123
  widgetImage._imageElement = img;
1101
1124
  widgetImage._originalAspectRatio = img.width / img.height;
1102
1125
  widgetImage.dirty = true;
1103
- canvas.requestRenderAll();
1126
+ canvas!.requestRenderAll();
1104
1127
  takeHistorySnapshot();
1105
1128
  canvasLog('Canvas: Widget Image created', { WidgetId: widgetId, ObjectId: newObjectId });
1106
1129
  };
@@ -1141,7 +1164,7 @@
1141
1164
  (obj as any)._hasImage = true;
1142
1165
  (obj as any)._imageUrl = newScreenshotDataUrl;
1143
1166
  (obj as any).dirty = true;
1144
- canvas.requestRenderAll();
1167
+ canvas!.requestRenderAll();
1145
1168
  canvasLog('Canvas: Widget Image updated', { WidgetId: widgetId });
1146
1169
  };
1147
1170
  img.onerror = () => {
@@ -1700,13 +1723,14 @@
1700
1723
  canvasLog('Rotation cursor: configured with retina image-set CSS');
1701
1724
  }
1702
1725
 
1703
- // Also override the rotation cursor on the canvas itself
1704
- canvas.rotationCursor = rotationCursorFallback;
1726
+ // Also override the rotation cursor on the canvas itself — a legacy
1727
+ // property the typings dropped but the runtime cursor logic still reads.
1728
+ (canvas as any).rotationCursor = rotationCursorFallback;
1705
1729
 
1706
1730
  // Set cursor class during active rotation
1707
1731
  canvas.on('object:rotating', () => {
1708
1732
  isRotating = true;
1709
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.add('fabric-rotate-cursor');
1733
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.add('fabric-rotate-cursor');
1710
1734
  });
1711
1735
 
1712
1736
  // Detect hover over the mtr control by checking oCoords distance.
@@ -1720,17 +1744,17 @@
1720
1744
  // Always track mouse position in canvas-absolute (scene) coords
1721
1745
  // for paste-at-cursor and frame detection
1722
1746
  try {
1723
- const pointer = canvas.getScenePoint(e.e);
1747
+ const pointer = canvas!.getScenePoint(e.e);
1724
1748
  lastCanvasMousePosition = { x: pointer.x, y: pointer.y };
1725
1749
  } catch { /* ignore errors during init */ }
1726
1750
 
1727
- const activeObj = canvas.getActiveObject();
1751
+ const activeObj = canvas!.getActiveObject();
1728
1752
  if (!activeObj || !activeObj.oCoords) return;
1729
1753
  const mtrCoord = (activeObj.oCoords as any).mtr;
1730
1754
  if (!mtrCoord) return;
1731
1755
 
1732
1756
  // Get pointer in viewport-space (same space as oCoords)
1733
- const rect = canvas.upperCanvasEl?.getBoundingClientRect();
1757
+ const rect = canvas!.upperCanvasEl?.getBoundingClientRect();
1734
1758
  if (!rect) return;
1735
1759
  const vpX = e.e.clientX - rect.left;
1736
1760
  const vpY = e.e.clientY - rect.top;
@@ -1742,9 +1766,9 @@
1742
1766
 
1743
1767
  // Add/remove rotation cursor class based on proximity to mtr or active rotation
1744
1768
  if (dist <= 12 || isRotating) {
1745
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.add('fabric-rotate-cursor');
1769
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.add('fabric-rotate-cursor');
1746
1770
  } else {
1747
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1771
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1748
1772
  }
1749
1773
  });
1750
1774
 
@@ -1752,7 +1776,7 @@
1752
1776
  canvas.on('mouse:up', () => {
1753
1777
  if (isRotating) {
1754
1778
  isRotating = false;
1755
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1779
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1756
1780
  }
1757
1781
  });
1758
1782
 
@@ -1917,7 +1941,7 @@
1917
1941
  }
1918
1942
 
1919
1943
  target.setCoords?.();
1920
- canvas.uniformScaling = false;
1944
+ canvas!.uniformScaling = false;
1921
1945
  return; // Skip the rest, we've handled textbox specially
1922
1946
  } else {
1923
1947
  // Other objects: maintain initial aspect ratio
@@ -2019,12 +2043,12 @@
2019
2043
  }
2020
2044
 
2021
2045
  // Disable Fabric's native uniform scaling since we're handling it manually
2022
- canvas.uniformScaling = false;
2046
+ canvas!.uniformScaling = false;
2023
2047
  } else {
2024
2048
  // No Shift held: ensure free resize for non-locked shapes.
2025
2049
  // _lockAspectRatio shapes keep uniformScaling=true from before:transform.
2026
2050
  if (!target._lockAspectRatio) {
2027
- canvas.uniformScaling = false;
2051
+ canvas!.uniformScaling = false;
2028
2052
  }
2029
2053
  }
2030
2054
 
@@ -2032,7 +2056,7 @@
2032
2056
  // regardless of Shift key. Re-assert uniformScaling AND correct any
2033
2057
  // scale divergence that Fabric's uniScaleKey toggle may have introduced.
2034
2058
  if (target._forceLockAspectRatio) {
2035
- canvas.uniformScaling = true;
2059
+ canvas!.uniformScaling = true;
2036
2060
  const sx = Math.abs(target.scaleX ?? 1);
2037
2061
  const sy = Math.abs(target.scaleY ?? 1);
2038
2062
  if (Math.abs(sx - sy) > 0.001) {
@@ -2139,7 +2163,7 @@
2139
2163
  }
2140
2164
 
2141
2165
  // Reset uniform scaling after scale operation completes
2142
- canvas.uniformScaling = false;
2166
+ canvas!.uniformScaling = false;
2143
2167
 
2144
2168
  // Reset skew locks after scale operation completes
2145
2169
  target.lockSkewingX = false;
@@ -2321,7 +2345,7 @@
2321
2345
  // in object:scaling after the position has already been computed by Fabric.
2322
2346
  // uniformScaling is reset in handleObjectScaled (object:modified) at drag end.
2323
2347
  if ((transform.target as any)?._lockAspectRatio) {
2324
- canvas.uniformScaling = true;
2348
+ canvas!.uniformScaling = true;
2325
2349
  canvasLog('Canvas: lockAspectRatio — enabled uniformScaling for', (transform.target as any)?._shapeKey ?? transform.target?.type);
2326
2350
  }
2327
2351
 
@@ -2439,7 +2463,10 @@
2439
2463
  }
2440
2464
  });
2441
2465
 
2442
- canvas.on('object:scaled', (opt: any) => {
2466
+ // fabric v6's runtime never fires 'object:scaled' (merged into
2467
+ // 'scaling'), but the pairing is kept for back-compat with saved
2468
+ // handler registries.
2469
+ (canvas as any).on('object:scaled', (opt: any) => {
2443
2470
  handleObjectScaled(opt);
2444
2471
  if ((opt?.target as any)?._isWidgetImage || (scalingTarget as any)?._isWidgetImage) {
2445
2472
  try {
@@ -2726,7 +2753,7 @@
2726
2753
  }
2727
2754
  }
2728
2755
  };
2729
- collectFrames(canvas.getObjects());
2756
+ collectFrames(canvas!.getObjects());
2730
2757
  return allFrames;
2731
2758
  };
2732
2759
 
@@ -2781,7 +2808,7 @@
2781
2808
  // Capture absolute matrices BEFORE any group changes.
2782
2809
  // obj.calcTransformMatrix() chains through the activeSelection
2783
2810
  // to give the correct post-drag canvas-space position.
2784
- const absMatrices = new Map<any, number[]>();
2811
+ const absMatrices = new Map<any, [number, number, number, number, number, number]>();
2785
2812
  objectsToMove.forEach((obj: any) => {
2786
2813
  absMatrices.set(obj, obj.calcTransformMatrix());
2787
2814
  });
@@ -2797,7 +2824,7 @@
2797
2824
  if (obj.group && obj.group !== targetFrame) {
2798
2825
  obj.group.remove(obj);
2799
2826
  } else if ((canvas as any)._objects?.includes(obj)) {
2800
- canvas.remove(obj);
2827
+ canvas!.remove(obj);
2801
2828
  }
2802
2829
  (obj as any)._set('group', undefined);
2803
2830
  (obj as any)._set('parent', undefined);
@@ -2808,7 +2835,7 @@
2808
2835
  // addObjectToFrame converts it to frame-local coords.
2809
2836
  if (m) fabricUtil.applyTransformToObject(obj, m);
2810
2837
 
2811
- addObjectToFrame(targetFrame, obj, canvas);
2838
+ addObjectToFrame(targetFrame, obj, canvas!);
2812
2839
  });
2813
2840
  } finally {
2814
2841
  isHandlingContainment = false;
@@ -2860,7 +2887,7 @@
2860
2887
  // are found — otherwise regular canvas moves would lose the selection.
2861
2888
  const objects = target.getObjects().slice();
2862
2889
 
2863
- type FrameBound = { obj: any; parentFrame: any; absMatrix: number[] };
2890
+ type FrameBound = { obj: any; parentFrame: any; absMatrix: [number, number, number, number, number, number] };
2864
2891
  const frameBoundObjects: FrameBound[] = [];
2865
2892
  const allCanvasObjects: any[] = (canvas as any)._objects || [];
2866
2893
 
@@ -2913,10 +2940,10 @@
2913
2940
  parentFrame.dirty = true;
2914
2941
 
2915
2942
  // Apply the captured post-drag absolute position
2916
- fabricUtil.applyTransformToObject(obj, absMatrix);
2943
+ fabricUtil.applyTransformToObject(obj, absMatrix as [number, number, number, number, number, number]);
2917
2944
 
2918
2945
  if (!(canvas as any)._objects?.includes(obj)) {
2919
- canvas.add(obj);
2946
+ canvas!.add(obj);
2920
2947
  }
2921
2948
  obj.setCoords();
2922
2949
  });
@@ -3057,6 +3084,12 @@
3057
3084
  });
3058
3085
  checkAndAddNewShapeToFrame(path);
3059
3086
  takeHistorySnapshot();
3087
+
3088
+ // Shape snap: if the stroke is a shape the canvas can build, swap
3089
+ // it for the clean one. Async (the ambiguous cases ask the host's
3090
+ // recognizer), so it re-checks that the stroke is still on the
3091
+ // canvas before touching it.
3092
+ void maybeSnapDrawnStroke(path);
3060
3093
  });
3061
3094
 
3062
3095
  // ─── History: snapshot after each completed move/scale/rotate ───
@@ -3094,7 +3127,7 @@
3094
3127
  if (target && target === activeEditingTextbox) return;
3095
3128
  if (target && target.isEditing) {
3096
3129
  target.exitEditing();
3097
- canvas.requestRenderAll();
3130
+ canvas!.requestRenderAll();
3098
3131
  }
3099
3132
  });
3100
3133
 
@@ -3193,7 +3226,7 @@
3193
3226
  }
3194
3227
 
3195
3228
  target.setCoords();
3196
- canvas.requestRenderAll();
3229
+ canvas!.requestRenderAll();
3197
3230
  return; // Handled textbox specially
3198
3231
  }
3199
3232
  // For rect, ellipse, triangle, frame: targetAspectRatio stays 1 (square/circle)
@@ -3278,7 +3311,7 @@
3278
3311
  }
3279
3312
 
3280
3313
  target.setCoords();
3281
- canvas.requestRenderAll();
3314
+ canvas!.requestRenderAll();
3282
3315
  }
3283
3316
  }
3284
3317
  };
@@ -3286,7 +3319,7 @@
3286
3319
  const handleGlobalShiftKeyup = (e: KeyboardEvent) => {
3287
3320
  if (e.key === 'Shift') {
3288
3321
  isShiftHeld = false;
3289
- canvas.uniformScaling = false;
3322
+ canvas!.uniformScaling = false;
3290
3323
  }
3291
3324
  };
3292
3325
 
@@ -3308,7 +3341,7 @@
3308
3341
  if (isMiddleControl) {
3309
3342
  scalingTarget.set({ skewX: 0, skewY: 0 });
3310
3343
  scalingTarget.setCoords();
3311
- canvas.requestRenderAll();
3344
+ canvas!.requestRenderAll();
3312
3345
  }
3313
3346
  }
3314
3347
  };
@@ -3357,7 +3390,7 @@
3357
3390
  if (obj.group && isFrameShape(obj.group)) {
3358
3391
  obj.group.remove(obj);
3359
3392
  } else {
3360
- canvas.remove(obj);
3393
+ canvas!.remove(obj);
3361
3394
  }
3362
3395
  });
3363
3396
  selectedObject = null;
@@ -3479,16 +3512,16 @@
3479
3512
  const selectAllFrameChildren = (parentFrame: any, frameChildren: any[]) => {
3480
3513
  if (frameChildren.length === 0) return;
3481
3514
  if (frameChildren.length === 1) {
3482
- canvas.setActiveObject(frameChildren[0]);
3483
- canvas.requestRenderAll();
3515
+ canvas!.setActiveObject(frameChildren[0]);
3516
+ canvas!.requestRenderAll();
3484
3517
  return;
3485
3518
  }
3486
3519
  // Constructor with enterGroup(child,false) + INITIALIZATION layout is
3487
3520
  // the correct one-pass approach — no drift across repeated Ctrl+A.
3488
- const sel = new ActiveSelection(frameChildren, { canvas });
3521
+ const sel = new ActiveSelection(frameChildren, { canvas: canvas! });
3489
3522
  (sel as any)._parentFrame = parentFrame;
3490
- canvas.setActiveObject(sel);
3491
- canvas.requestRenderAll();
3523
+ canvas!.setActiveObject(sel);
3524
+ canvas!.requestRenderAll();
3492
3525
  };
3493
3526
 
3494
3527
  const handleSelectAllKeydown = (e: KeyboardEvent) => {
@@ -4060,7 +4093,7 @@
4060
4093
  left: (obj.left || 0) + (cloned.left || 0) + cloneWidth / 2,
4061
4094
  top: (obj.top || 0) + (cloned.top || 0) + cloneHeight / 2,
4062
4095
  });
4063
- addObjectToFrame(targetFrame, obj, canvas);
4096
+ addObjectToFrame(targetFrame, obj, canvas!);
4064
4097
  });
4065
4098
  if (!hasPendingWidgetPaste) {
4066
4099
  const frameChildren = targetFrame.getObjects().filter((o: any) => !o._isFrameBackground);
@@ -4071,7 +4104,7 @@
4071
4104
  } else {
4072
4105
  cloned.canvas = canvas;
4073
4106
  cloned.forEachObject((obj: any) => {
4074
- canvas.add(obj);
4107
+ canvas!.add(obj);
4075
4108
  });
4076
4109
  cloned.setCoords();
4077
4110
  if (!hasPendingWidgetPaste) canvas.setActiveObject(cloned);
@@ -4130,16 +4163,17 @@
4130
4163
 
4131
4164
  // Clone the active object
4132
4165
  const cloned = await activeObject.clone();
4133
-
4134
- // Copy custom properties from original to cloned
4135
- if (activeObject.type === 'activeSelection' || activeObject.type === 'activeselection') {
4136
- const sourceObjects = (activeObject as any).getObjects();
4137
- const clonedObjects = cloned.getObjects();
4138
- sourceObjects.forEach((srcObj: any, idx: number) => {
4139
- if (clonedObjects[idx]) {
4140
- copyCustomProperties(srcObj, clonedObjects[idx]);
4141
- }
4142
- });
4166
+ const clonedSrc = cloned as any;
4167
+
4168
+ // Copy custom properties from original to cloned
4169
+ if (activeObject.type === 'activeSelection' || activeObject.type === 'activeselection') {
4170
+ const sourceObjects = (activeObject as any).getObjects();
4171
+ const clonedObjects = clonedSrc.getObjects();
4172
+ sourceObjects.forEach((srcObj: any, idx: number) => {
4173
+ if (clonedObjects[idx]) {
4174
+ copyCustomProperties(srcObj, clonedObjects[idx]);
4175
+ }
4176
+ });
4143
4177
  } else {
4144
4178
  copyCustomProperties(activeObject, cloned);
4145
4179
  }
@@ -4165,7 +4199,7 @@
4165
4199
  }
4166
4200
  };
4167
4201
  if (cloned.type === 'activeSelection' || cloned.type === 'activeselection') {
4168
- cloned.getObjects().forEach(handleWidgetDuplicate);
4202
+ clonedSrc.getObjects().forEach(handleWidgetDuplicate);
4169
4203
  } else {
4170
4204
  handleWidgetDuplicate(cloned);
4171
4205
  }
@@ -4180,9 +4214,9 @@
4180
4214
  // Handle ActiveSelection (multiple objects) - following Fabric.js demo approach
4181
4215
  if (cloned.type === 'activeSelection' || cloned.type === 'activeselection') {
4182
4216
  // Active selection needs a reference to the canvas
4183
- cloned.canvas = canvas;
4184
- cloned.forEachObject((obj: any) => {
4185
- canvas.add(obj);
4217
+ clonedSrc.canvas = canvas;
4218
+ clonedSrc.forEachObject((obj: any) => {
4219
+ canvas!.add(obj);
4186
4220
  });
4187
4221
  // This should solve the unselectability
4188
4222
  cloned.setCoords();
@@ -4209,7 +4243,7 @@
4209
4243
  });
4210
4244
 
4211
4245
  // 1. Restore Frame render override + interactive properties
4212
- reapplyFrameRender(cloned);
4246
+ reapplyFrameRender(cloned as unknown as Group);
4213
4247
 
4214
4248
  // 2. Patch setCoords to no-op during enterGroup
4215
4249
  // (_enterGroup calls setCoords before group/canvas are set → wrong coords)
@@ -4279,7 +4313,7 @@
4279
4313
  } else {
4280
4314
  // Canvas-level paste — restore Frame properties if cloning a Frame
4281
4315
  if (isFrameShape(cloned)) {
4282
- reapplyFrameRender(cloned);
4316
+ reapplyFrameRender(cloned as unknown as Group);
4283
4317
  canvasLog('Canvas: Restored Frame properties on canvas-level duplicate');
4284
4318
  }
4285
4319
  canvas.add(cloned);
@@ -4346,7 +4380,7 @@
4346
4380
  if (obj.group && isFrameShape(obj.group)) {
4347
4381
  obj.group.remove(obj);
4348
4382
  } else {
4349
- canvas.remove(obj);
4383
+ canvas!.remove(obj);
4350
4384
  }
4351
4385
  });
4352
4386
  } else {
@@ -4505,11 +4539,11 @@
4505
4539
  height: 200,
4506
4540
  });
4507
4541
  (placeholder as any)._objectId = `img_paste_${Date.now()}`;
4508
- canvas.add(placeholder);
4509
- canvas.setActiveObject(placeholder);
4542
+ canvas!.add(placeholder);
4543
+ canvas!.setActiveObject(placeholder);
4510
4544
  selectedObject = placeholder;
4511
4545
  replacePlaceholderWithImage(placeholder, dataUrl, 'pasted-image.png', false);
4512
- canvas.requestRenderAll();
4546
+ canvas!.requestRenderAll();
4513
4547
  takeHistorySnapshot();
4514
4548
  canvasLog('Canvas: Image pasted from OS clipboard at', { x: Math.round(mousePos.x), y: Math.round(mousePos.y) });
4515
4549
  };
@@ -4719,7 +4753,7 @@
4719
4753
  // Safety: if the background rect itself is somehow selected, select the parent frame
4720
4754
  if (activeObj._isFrameBackground && activeObj.group && isFrameShape(activeObj.group)) {
4721
4755
  // Switch the canvas selection to the parent frame
4722
- canvas.setActiveObject(activeObj.group);
4756
+ canvas!.setActiveObject(activeObj.group);
4723
4757
  return activeObj.group;
4724
4758
  }
4725
4759
 
@@ -4733,7 +4767,7 @@
4733
4767
  if (!isRedirectingGroupSelection) {
4734
4768
  isRedirectingGroupSelection = true;
4735
4769
  try {
4736
- canvas.setActiveObject(parent);
4770
+ canvas!.setActiveObject(parent);
4737
4771
  } finally {
4738
4772
  isRedirectingGroupSelection = false;
4739
4773
  }
@@ -4750,13 +4784,13 @@
4750
4784
 
4751
4785
  const handleSelectionCreated = (e: any) => {
4752
4786
  // Get the active object which could be a single object, group, or activeSelection
4753
- const activeObj = canvas.getActiveObject() as any;
4787
+ const activeObj = canvas!.getActiveObject() as any;
4754
4788
 
4755
4789
  // If it's a multi-selection, detect and set common properties
4756
4790
  if (activeObj && (activeObj.type === 'activeSelection' || activeObj.type === 'activeselection')) {
4757
4791
  setCommonPropertiesOnSelection(activeObj);
4758
4792
  // Disable caching if selection contains Frame/Image with custom render
4759
- const hasCustomRender = activeObj.getObjects().some((obj: any) =>
4793
+ const hasCustomRender = (activeObj as any).getObjects().some((obj: any) =>
4760
4794
  isFrameShape(obj) || obj._customType === 'image'
4761
4795
  );
4762
4796
  if (hasCustomRender) {
@@ -4768,7 +4802,7 @@
4768
4802
  const selItems: any[] = activeObj.getObjects ? activeObj.getObjects() : [];
4769
4803
  const frameId = selItems[0]?._parentFrameId;
4770
4804
  if (frameId && selItems.every((item: any) => item._parentFrameId === frameId)) {
4771
- const parentFrame = canvas.getObjects().find((o: any) => o._objectId === frameId);
4805
+ const parentFrame = canvas!.getObjects().find((o: any) => o._objectId === frameId);
4772
4806
  if (parentFrame && isFrameShape(parentFrame)) {
4773
4807
  activeObj._parentFrame = parentFrame;
4774
4808
  canvasLog('Canvas: selection:created — tagged with parent frame', (parentFrame as any)._labelText || frameId);
@@ -4778,6 +4812,7 @@
4778
4812
  }
4779
4813
 
4780
4814
  selectedObject = resolveSelectedObject(activeObj);
4815
+ if ((selectedObject as any)?._isWidgetImage) lockWidgetShapeBodyDrag(selectedObject);
4781
4816
  // Self-heal _customType and _cornerRadiusMode for any library shape on selection.
4782
4817
  // Covers old saves where _customType was missing and stale _cornerRadiusMode values.
4783
4818
  if ((selectedObject as any)?._shapeKey) {
@@ -4797,13 +4832,13 @@
4797
4832
 
4798
4833
  const handleSelectionUpdated = (e: any) => {
4799
4834
  // Get the active object which could be a single object, group, or activeSelection
4800
- const activeObj = canvas.getActiveObject();
4835
+ const activeObj = canvas!.getActiveObject();
4801
4836
 
4802
4837
  // If it's a multi-selection, detect and set common properties
4803
4838
  if (activeObj && (activeObj.type === 'activeSelection' || activeObj.type === 'activeselection')) {
4804
4839
  setCommonPropertiesOnSelection(activeObj);
4805
4840
  // Disable caching if selection contains Frame/Image with custom render
4806
- const hasCustomRender = activeObj.getObjects().some((obj: any) =>
4841
+ const hasCustomRender = (activeObj as any).getObjects().some((obj: any) =>
4807
4842
  isFrameShape(obj) || obj._customType === 'image'
4808
4843
  );
4809
4844
  if (hasCustomRender) {
@@ -4812,6 +4847,7 @@
4812
4847
  }
4813
4848
 
4814
4849
  selectedObject = resolveSelectedObject(activeObj);
4850
+ if ((selectedObject as any)?._isWidgetImage) lockWidgetShapeBodyDrag(selectedObject);
4815
4851
  // Self-heal _customType and _cornerRadiusMode for any library shape on selection.
4816
4852
  if ((selectedObject as any)?._shapeKey) {
4817
4853
  if ((selectedObject as any)._customType !== 'libraryShape') {
@@ -4872,7 +4908,7 @@
4872
4908
  // Defer selectAll to run after Fabric's internal dblclick word-selection
4873
4909
  requestAnimationFrame(() => {
4874
4910
  target.selectAll();
4875
- canvas.requestRenderAll();
4911
+ canvas!.requestRenderAll();
4876
4912
  });
4877
4913
  return;
4878
4914
  }
@@ -4888,9 +4924,9 @@
4888
4924
  enterGroupEdit(target);
4889
4925
  const sub = Array.isArray(e.subTargets) ? e.subTargets[0] : null;
4890
4926
  if (sub && sub !== target) {
4891
- canvas.setActiveObject(sub);
4927
+ canvas!.setActiveObject(sub);
4892
4928
  }
4893
- canvas.requestRenderAll();
4929
+ canvas!.requestRenderAll();
4894
4930
  canvasLog('Canvas: entered group via double-click', {
4895
4931
  children: target.getObjects?.()?.length,
4896
4932
  subType: sub?.type,
@@ -4975,7 +5011,7 @@
4975
5011
  }
4976
5012
  }
4977
5013
  };
4978
- recurse(canvas.getObjects());
5014
+ recurse(canvas!.getObjects());
4979
5015
  return frames;
4980
5016
  };
4981
5017
 
@@ -5130,16 +5166,17 @@
5130
5166
  */
5131
5167
  const getSelectableObjectsAtPoint = (point: any): any[] => {
5132
5168
  const result: any[] = [];
5133
- const canvasObjects = canvas.getObjects();
5169
+ const canvasObjects = canvas!.getObjects();
5134
5170
  for (const obj of canvasObjects) {
5135
5171
  // Skip non-selectable and background rects
5136
- if (obj.selectable === false || obj._isFrameBackground) continue;
5172
+ if (obj.selectable === false || (obj as any)._isFrameBackground) continue;
5137
5173
  if (obj.containsPoint(point)) {
5138
5174
  result.push(obj);
5139
5175
  }
5140
5176
  // Also check inside interactive frames (children are selectable directly)
5141
- if (isFrameShape(obj) && obj.interactive) {
5142
- const children = obj.getObjects ? obj.getObjects() : [];
5177
+ // (obj is typed FabricObject; only frames answer getObjects)
5178
+ if (isFrameShape(obj) && (obj as any).interactive) {
5179
+ const children = (obj as any).getObjects?.() ?? [];
5143
5180
  for (const child of children) {
5144
5181
  if (child.selectable === false || child._isFrameBackground) continue;
5145
5182
  if (child.containsPoint(point)) {
@@ -5157,7 +5194,9 @@
5157
5194
  if (!isAlt) return;
5158
5195
 
5159
5196
  // Don't intercept if the click is on a control handle (resize/rotate)
5160
- if (canvas.__targetTransform) return;
5197
+ // The internal paint-order marker this module attaches to canvas objects;
5198
+ // fabric's Canvas type doesn't know about it.
5199
+ if ((canvas as any).__targetTransform) return;
5161
5200
 
5162
5201
  // Get click position in scene coordinates
5163
5202
  let point: any;
@@ -5215,7 +5254,7 @@
5215
5254
  return;
5216
5255
  }
5217
5256
 
5218
- const pointer = canvas.getScenePoint(opt.e);
5257
+ const pointer = canvas!.getScenePoint(opt.e);
5219
5258
 
5220
5259
  // Only intercept if click is strictly inside the frame (not on border/label)
5221
5260
  if (isPointOnFrameBorder(target, pointer)) return;
@@ -5227,7 +5266,7 @@
5227
5266
 
5228
5267
  // Clear the target — Fabric will proceed with rubber-band selection
5229
5268
  (canvas as any)._target = null;
5230
- canvas.setCursor(canvas.defaultCursor || 'default');
5269
+ canvas!.setCursor(canvas!.defaultCursor || 'default');
5231
5270
  canvasLog('Canvas: Frame interior — cleared target for rubber-band, lastInteractedFrame =', target._labelText || target._objectId || 'frame');
5232
5271
  };
5233
5272
  canvas.on('mouse:down:before', handleFrameInteriorMouseDownBefore);
@@ -5239,10 +5278,10 @@
5239
5278
  // We run AFTER Fabric's mouse:up to correct it.
5240
5279
  const handleFrameInteriorMouseUp = (opt: any) => {
5241
5280
  if (!opt.e) return;
5242
- const pointer = canvas.getScenePoint(opt.e);
5281
+ const pointer = canvas!.getScenePoint(opt.e);
5243
5282
  for (const frame of collectAllFrames()) {
5244
5283
  if (isPointInsideFrame(frame, pointer) && !isPointOnFrameBorder(frame, pointer) && !isPointInFrameLabel(frame, pointer)) {
5245
- canvas.setCursor(canvas.defaultCursor || 'default');
5284
+ canvas!.setCursor(canvas!.defaultCursor || 'default');
5246
5285
  return;
5247
5286
  }
5248
5287
  }
@@ -5323,13 +5362,13 @@
5323
5362
  (canvas as any)._groupSelector = null;
5324
5363
 
5325
5364
  if (matched.length === 1) {
5326
- canvas.setActiveObject(matched[0]);
5365
+ canvas!.setActiveObject(matched[0]);
5327
5366
  } else {
5328
- const sel = new ActiveSelection(matched, { canvas });
5367
+ const sel = new ActiveSelection(matched, { canvas: canvas! });
5329
5368
  (sel as any)._parentFrame = frame;
5330
- canvas.setActiveObject(sel);
5369
+ canvas!.setActiveObject(sel);
5331
5370
  }
5332
- canvas.requestRenderAll();
5371
+ canvas!.requestRenderAll();
5333
5372
  canvasLog('Canvas: rubber-band inside frame — selected', matched.length, 'children in', (frame as any)._labelText || 'frame');
5334
5373
  break;
5335
5374
  }
@@ -5339,7 +5378,7 @@
5339
5378
  console.error('Canvas: handleFrameRubberBandUpBefore error:', err);
5340
5379
  // Best-effort cleanup: clear the rubber-band indicator
5341
5380
  (canvas as any)._groupSelector = null;
5342
- canvas.renderTop();
5381
+ canvas!.renderTop();
5343
5382
  }
5344
5383
  };
5345
5384
  canvas.on('mouse:up:before', handleFrameRubberBandUpBefore);
@@ -5415,7 +5454,7 @@
5415
5454
  // If the AS was moved/resized, save the NEW absolute positions.
5416
5455
  // Otherwise restore canonical positions to counteract FP drift.
5417
5456
  canvas.on('selection:cleared', () => {
5418
- const allObjects = canvas.getObjects().filter((o: any) => !o._isFrameBackground && o.selectable !== false);
5457
+ const allObjects = canvas!.getObjects().filter((o: any) => !o._isFrameBackground && o.selectable !== false);
5419
5458
  if (_activeSelectionModified) {
5420
5459
  _activeSelectionModified = false;
5421
5460
  saveAbsolutePositions(allObjects);
@@ -5490,7 +5529,7 @@
5490
5529
  if (!files || files.length === 0) return;
5491
5530
 
5492
5531
  // Get drop position in canvas scene coordinates (handles pan & zoom)
5493
- const scenePoint = canvas.getScenePoint(e);
5532
+ const scenePoint = canvas!.getScenePoint(e);
5494
5533
  const dropX = scenePoint.x;
5495
5534
  const dropY = scenePoint.y;
5496
5535
 
@@ -5505,8 +5544,8 @@
5505
5544
  if (isVideo) {
5506
5545
  const { video, objectUrl } = createVideoElementFromFile(file);
5507
5546
  capturePosterFromVideo(video).then((posterUrl) => {
5508
- const maxWidth = canvas.width * 0.6;
5509
- const maxHeight = canvas.height * 0.6;
5547
+ const maxWidth = canvas!.width * 0.6;
5548
+ const maxHeight = canvas!.height * 0.6;
5510
5549
  const tempImg = new Image();
5511
5550
  tempImg.onload = () => {
5512
5551
  let width = tempImg.width;
@@ -5523,8 +5562,8 @@
5523
5562
  height,
5524
5563
  mediaKind: 'video'
5525
5564
  });
5526
- canvas.add(videoShape);
5527
- canvas.setActiveObject(videoShape);
5565
+ canvas!.add(videoShape);
5566
+ canvas!.setActiveObject(videoShape);
5528
5567
  attachVideoElementToShape(videoShape, video, objectUrl);
5529
5568
  loadImageIntoShape(videoShape, posterUrl, file.name);
5530
5569
  canvasLog('Video dropped on canvas:', file.name);
@@ -5545,8 +5584,8 @@
5545
5584
  const tempImg = new Image();
5546
5585
  tempImg.onload = () => {
5547
5586
  // Scale image to fit if too large
5548
- const maxWidth = canvas.width * 0.6;
5549
- const maxHeight = canvas.height * 0.6;
5587
+ const maxWidth = canvas!.width * 0.6;
5588
+ const maxHeight = canvas!.height * 0.6;
5550
5589
 
5551
5590
  let width = tempImg.width;
5552
5591
  let height = tempImg.height;
@@ -5565,8 +5604,8 @@
5565
5604
  height: height
5566
5605
  });
5567
5606
 
5568
- canvas.add(imageShape);
5569
- canvas.setActiveObject(imageShape);
5607
+ canvas!.add(imageShape);
5608
+ canvas!.setActiveObject(imageShape);
5570
5609
 
5571
5610
  // Load the image into the shape
5572
5611
  loadImageIntoShape(imageShape, dataUrl, file.name);
@@ -5668,9 +5707,9 @@
5668
5707
  };
5669
5708
 
5670
5709
  canvas.on('mouse:move', (hoverOpt: any) => {
5671
- const pointer = canvas.getScenePoint(hoverOpt.e);
5710
+ const pointer = canvas!.getScenePoint(hoverOpt.e);
5672
5711
  let needsRender = false;
5673
- for (const obj of canvas.getObjects()) {
5712
+ for (const obj of canvas!.getObjects()) {
5674
5713
  if (!isFrameShape(obj)) continue;
5675
5714
  const wasHovered = !!(obj as any)._borderHovered;
5676
5715
  const isNowHovered =
@@ -5681,7 +5720,7 @@
5681
5720
  needsRender = true;
5682
5721
  }
5683
5722
  }
5684
- if (needsRender) canvas.requestRenderAll();
5723
+ if (needsRender) canvas!.requestRenderAll();
5685
5724
  });
5686
5725
 
5687
5726
  // Clear all frame hover states when mouse leaves the canvas wrapper
@@ -5689,14 +5728,14 @@
5689
5728
  if (hoverWrapperEl) {
5690
5729
  hoverWrapperEl.addEventListener('mouseleave', () => {
5691
5730
  let needsRender = false;
5692
- for (const obj of canvas.getObjects()) {
5731
+ for (const obj of canvas!.getObjects()) {
5693
5732
  if (!isFrameShape(obj)) continue;
5694
5733
  if ((obj as any)._borderHovered) {
5695
5734
  applyFrameHoverStroke(obj, false);
5696
5735
  needsRender = true;
5697
5736
  }
5698
5737
  }
5699
- if (needsRender) canvas.requestRenderAll();
5738
+ if (needsRender) canvas!.requestRenderAll();
5700
5739
  // WidgetShape drag bar must also hide when the pointer leaves the canvas.
5701
5740
  setHoveredWidgetShape(null);
5702
5741
  });
@@ -5791,7 +5830,7 @@
5791
5830
 
5792
5831
  if (canvas && canvasScalingHandlers) {
5793
5832
  canvas.off('object:scaling', canvasScalingHandlers.scaling);
5794
- canvas.off('object:scaled', canvasScalingHandlers.scaled);
5833
+ (canvas as any).off('object:scaled', canvasScalingHandlers.scaled);
5795
5834
  canvasScalingHandlers = null;
5796
5835
  }
5797
5836
 
@@ -7031,6 +7070,207 @@ function checkAndAddNewShapeToFrame(shape: any) {
7031
7070
  });
7032
7071
  }
7033
7072
 
7073
+ // ── Shape snap: replace a recognized freehand stroke with the clean shape ──
7074
+ // Geometry is decided here (see `shapes/strokeShapeSnap.ts`); only a stroke
7075
+ // whose measurements are genuinely ambiguous is handed to the host's
7076
+ // recognizer, and only shapes the geometry allowed can ever be applied.
7077
+
7078
+ /** Is this object still on the canvas, either free-standing or inside a frame? */
7079
+ function isStrokeStillOnCanvas(path: any): boolean {
7080
+ if (!canvas || !path) return false;
7081
+ if (canvas.getObjects().includes(path)) return true;
7082
+ const parentFrame = path.group;
7083
+ return Boolean(parentFrame && canvas.getObjects().includes(parentFrame));
7084
+ }
7085
+
7086
+ /**
7087
+ * Snap a freshly drawn stroke, if it is a shape the canvas can build.
7088
+ *
7089
+ * Deliberately fatal-free: any failure — no flag, no recognizer, a cancelled
7090
+ * request, an answer the geometry ruled out, an object that left the canvas
7091
+ * while we waited — leaves the drawing exactly as the user made it.
7092
+ */
7093
+ async function maybeSnapDrawnStroke(path: any) {
7094
+ if (!CANVAS_SHAPE_SNAP_ENABLED || !canvas) return;
7095
+
7096
+ const commands = (path?.path ?? null) as PathCommand[] | null;
7097
+ if (!Array.isArray(commands) || commands.length < 2) return;
7098
+
7099
+ const measurements = measureStroke(flattenPathCommands(commands));
7100
+ if (!measurements) return;
7101
+
7102
+ // Only shapes the measurements cannot rule out are ever considered, and
7103
+ // the same list is the only roster the host may choose from.
7104
+ const rankings = rankSnapShapes(measurements);
7105
+ if (rankings.length === 0) return;
7106
+
7107
+ const candidates = rankings.map((ranking) => ({
7108
+ ...ranking,
7109
+ label: CANVAS_SNAP_SHAPE_LABELS[ranking.shape]
7110
+ }));
7111
+
7112
+ const decisive = confidentSnapShape(rankings);
7113
+ let chosen: CanvasSnapShape | null = decisive?.shape ?? null;
7114
+ let source: 'geometry' | 'recognizer' = 'geometry';
7115
+
7116
+ if (!chosen) {
7117
+ if (!onRecognizeStroke) {
7118
+ canvasLog('Shape snap: ambiguous and no recognizer configured — leaving stroke as drawn', {
7119
+ candidates: candidates.map((candidate) => candidate.shape)
7120
+ });
7121
+ return;
7122
+ }
7123
+ const answer = await onRecognizeStroke({
7124
+ measurements,
7125
+ candidates,
7126
+ best: candidates[0] ?? null
7127
+ });
7128
+ const shape = answer?.shape ?? null;
7129
+ if (!shape || !candidates.some((candidate) => candidate.shape === shape)) {
7130
+ canvasLog('Shape snap: recognizer declined or named a shape the geometry ruled out', {
7131
+ shape,
7132
+ reason: answer?.reason ?? 'no_answer'
7133
+ });
7134
+ return;
7135
+ }
7136
+ chosen = shape as CanvasSnapShape;
7137
+ source = 'recognizer';
7138
+ }
7139
+
7140
+ if (!canvas || !isStrokeStillOnCanvas(path)) return;
7141
+ replaceStrokeWithShape(path, chosen, source, measurements.axisTilt);
7142
+ }
7143
+
7144
+ /**
7145
+ * Swap the drawn stroke for the clean shape, keeping its place, its size and
7146
+ * its stroke colour — the same object the user would have got from the
7147
+ * toolbar, so every property panel and every export keeps working.
7148
+ */
7149
+ function replaceStrokeWithShape(path: any, shape: CanvasSnapShape, source: string, axisTilt: number) {
7150
+ if (!canvas) return;
7151
+
7152
+ // Placement comes from the stroke's *rendered* bounds, so the clean shape
7153
+ // lands exactly where the drawing was.
7154
+ const sceneBounds = path.getBoundingRect(true);
7155
+ const placement = planSnapPlacement(shape, {
7156
+ left: sceneBounds.left,
7157
+ top: sceneBounds.top,
7158
+ width: sceneBounds.width,
7159
+ height: sceneBounds.height
7160
+ });
7161
+
7162
+ const stroke = (path.stroke as string) || '#1f2937';
7163
+ const strokeWidth = typeof path.strokeWidth === 'number' ? path.strokeWidth : 3;
7164
+ const base = {
7165
+ left: placement.bounds.left,
7166
+ top: placement.bounds.top,
7167
+ originX: 'left' as const,
7168
+ originY: 'top' as const,
7169
+ // Freehand strokes are never filled, so the replacement is not either.
7170
+ fill: 'transparent',
7171
+ _fillOpacity: 0,
7172
+ stroke,
7173
+ strokeWidth,
7174
+ strokeUniform: true,
7175
+ selectable: true,
7176
+ evented: true
7177
+ };
7178
+
7179
+ let replacement: any = null;
7180
+
7181
+ try {
7182
+ if (shape === 'rect') {
7183
+ replacement = new Rect({ ...base, width: placement.bounds.width, height: placement.bounds.height });
7184
+ } else if (shape === 'oval') {
7185
+ replacement = new Ellipse({
7186
+ ...base,
7187
+ rx: Math.max(1, placement.bounds.width / 2),
7188
+ ry: Math.max(1, placement.bounds.height / 2)
7189
+ });
7190
+ } else if (shape === 'circle') {
7191
+ replacement = new Circle({ ...base, radius: Math.max(1, placement.bounds.width / 2) });
7192
+ (replacement as any)._lockAspectRatio = true;
7193
+ (replacement as any)._forceLockAspectRatio = true;
7194
+ replacement.setControlsVisibility({ ml: false, mr: false, mt: false, mb: false });
7195
+ } else if (shape === 'triangle') {
7196
+ const width = placement.bounds.width;
7197
+ const height = placement.bounds.height;
7198
+ replacement = new Path(createTrianglePathDefinition(width, height, 0), {
7199
+ ...base,
7200
+ strokeLineJoin: 'round'
7201
+ });
7202
+ updatePathWithDefinition(replacement as Path, createTrianglePathDefinition(width, height, 0), {
7203
+ left: placement.bounds.left,
7204
+ top: placement.bounds.top,
7205
+ originX: 'left',
7206
+ originY: 'top'
7207
+ });
7208
+ }
7209
+ } catch (error) {
7210
+ console.error('Shape snap: could not build the replacement shape', error);
7211
+ return;
7212
+ }
7213
+
7214
+ if (!replacement) return;
7215
+
7216
+ // Free the stroke first — from its frame as well, so nothing is left
7217
+ // behind and the replacement can be re-contained the same way.
7218
+ const parentFrame = path.group;
7219
+ if (parentFrame && isFrameShape(parentFrame)) {
7220
+ removeObjectFromFrame(parentFrame, path, canvas);
7221
+ }
7222
+ canvas.remove(path);
7223
+
7224
+ if (shape === 'diamond' || shape === 'hexagon') {
7225
+ // Library shapes carry their own normalized path data and bookkeeping,
7226
+ // so they go through the same finalizer the toolbar uses.
7227
+ const shapeDef = getShapeByKey(shape);
7228
+ if (!shapeDef) {
7229
+ canvas.add(path);
7230
+ return;
7231
+ }
7232
+ replacement = new Path(shapeDef.pathData, {
7233
+ ...base,
7234
+ strokeUniform: true,
7235
+ scaleX: 0.01,
7236
+ scaleY: 0.01
7237
+ });
7238
+ const naturalWidth = (replacement as any).width || 1;
7239
+ const naturalHeight = (replacement as any).height || 1;
7240
+ replacement.set({
7241
+ scaleX: placement.bounds.width / naturalWidth,
7242
+ scaleY: placement.bounds.height / naturalHeight
7243
+ });
7244
+ canvas.add(replacement);
7245
+ const { lockAspectRatio, cornerRadiusMode } = getLibraryShapeMeta(shape);
7246
+ finalizeLibraryShape(replacement as Path, shape, lockAspectRatio, cornerRadiusMode);
7247
+ } else {
7248
+ canvas.add(replacement);
7249
+ if (shape === 'triangle') {
7250
+ (replacement as any)._customType = 'triangle';
7251
+ (replacement as any)._baseWidth = placement.bounds.width;
7252
+ (replacement as any)._baseHeight = placement.bounds.height;
7253
+ (replacement as any)._cornerRoundness = 0;
7254
+ }
7255
+ replacement.setCoords?.();
7256
+ (replacement as any)._absLeft = replacement.left;
7257
+ (replacement as any)._absTop = replacement.top;
7258
+ checkAndAddNewShapeToFrame(replacement);
7259
+ takeHistorySnapshot();
7260
+ }
7261
+
7262
+ canvas.requestRenderAll();
7263
+ canvasLog('Shape snap: stroke replaced with clean shape', {
7264
+ shape,
7265
+ decidedBy: source,
7266
+ axisTilt,
7267
+ left: Math.round(placement.bounds.left),
7268
+ top: Math.round(placement.bounds.top),
7269
+ width: Math.round(placement.bounds.width),
7270
+ height: Math.round(placement.bounds.height)
7271
+ });
7272
+ }
7273
+
7034
7274
  // Text object method
7035
7275
  export function onSelectTextTool() {
7036
7276
  setActiveTool('text', () => {
@@ -7372,7 +7612,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
7372
7612
  return;
7373
7613
  }
7374
7614
 
7375
- let finalizePointer = pointer;
7615
+ let finalizePointer: { x: number; y: number } = pointer;
7376
7616
  if (!lastAppliedBounds || Math.max(lastAppliedBounds.width, lastAppliedBounds.height) < MIN_DRAW_DISTANCE) {
7377
7617
  finalizePointer = {
7378
7618
  x: arrowStartPoint.x + DEFAULT_OBJECT_SIZE,
@@ -7718,11 +7958,19 @@ function checkAndAddNewShapeToFrame(shape: any) {
7718
7958
  if (!canvas || !widgetId) return false;
7719
7959
  const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId) as any;
7720
7960
  if (!obj) return false;
7721
- const zoom = canvas.getZoom?.() || 1;
7961
+ const viewport = canvas.viewportTransform || [1, 0, 0, 1, 0, 0];
7962
+ const bounds = canvasEl?.getBoundingClientRect();
7963
+ const canvasWidth = canvas.getWidth?.() || bounds?.width || 1;
7964
+ const canvasHeight = canvas.getHeight?.() || bounds?.height || 1;
7965
+ const screenPerSceneX = ((bounds?.width || canvasWidth) / canvasWidth) * (viewport[0] || 1);
7966
+ const screenPerSceneY = ((bounds?.height || canvasHeight) / canvasHeight) * (viewport[3] || 1);
7722
7967
  // setXY accepts scene coordinates even while an ActiveSelection owns the object.
7723
7968
  // Movement locks only affect Fabric pointer transforms, not programmatic setters.
7724
7969
  const position = obj.getXY();
7725
- const nextPosition = position.add(new FabricPoint(dxScreen / zoom, dyScreen / zoom));
7970
+ const nextPosition = position.add(new FabricPoint(
7971
+ dxScreen / (screenPerSceneX || 1),
7972
+ dyScreen / (screenPerSceneY || 1),
7973
+ ));
7726
7974
  obj.setXY(nextPosition);
7727
7975
  // selection:cleared restores this canonical cache. Update it before any
7728
7976
  // deselection/history serialization, otherwise the header move snaps back.
@@ -7784,6 +8032,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
7784
8032
  if (!canvas || !widgetId) return false;
7785
8033
  const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId);
7786
8034
  if (!obj) return false;
8035
+ lockWidgetShapeBodyDrag(obj);
7787
8036
  canvas.setActiveObject(obj);
7788
8037
  canvas.requestRenderAll();
7789
8038
  return true;
@@ -7796,6 +8045,18 @@ function checkAndAddNewShapeToFrame(shape: any) {
7796
8045
  return null;
7797
8046
  }
7798
8047
 
8048
+ /**
8049
+ * The currently selected fabric object, if any — the read-side accessor
8050
+ * matching the internal selection state. Consumers outside the canvas
8051
+ * (CreatorApp's non-widget-selection guard) used to reach for this through
8052
+ * a property probe on the instance ref, which could never resolve because
8053
+ * the state was not exported; exported now so the guard checks the real
8054
+ * object instead of silently seeing `undefined`.
8055
+ */
8056
+ export function getSelectedObject(): any {
8057
+ return selectedObject;
8058
+ }
8059
+
7799
8060
  export function getHoveredWidgetShapeId(): string | null {
7800
8061
  return hoveredWidgetShapeId;
7801
8062
  }
@@ -8459,7 +8720,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8459
8720
  // Mark as dirty and re-render
8460
8721
  imageShape.dirty = true;
8461
8722
  imageShape.setCoords();
8462
- canvas.requestRenderAll();
8723
+ canvas!.requestRenderAll();
8463
8724
 
8464
8725
  // Update selectedObject reference
8465
8726
  selectedObject = imageShape;
@@ -8520,7 +8781,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8520
8781
  const deltaY = e.clientY - panStartPoint.y;
8521
8782
 
8522
8783
  // Use relativePan to move the viewport
8523
- canvas.relativePan({ x: deltaX, y: deltaY });
8784
+ canvas.relativePan(new FabricPoint(deltaX, deltaY));
8524
8785
 
8525
8786
  // Update start point for next move
8526
8787
  panStartPoint = { x: e.clientX, y: e.clientY };
@@ -8650,13 +8911,13 @@ function checkAndAddNewShapeToFrame(shape: any) {
8650
8911
  const contentCenterY = minY + contentHeight / 2;
8651
8912
 
8652
8913
  // Apply zoom
8653
- canvas.zoomToPoint({ x: canvasWidth / 2, y: canvasHeight / 2 }, newZoom);
8914
+ canvas.zoomToPoint(new FabricPoint(canvasWidth / 2, canvasHeight / 2), newZoom);
8654
8915
 
8655
8916
  // Pan to center content
8656
8917
  const currentCenter = canvas.getCenterPoint();
8657
8918
  const offsetX = (currentCenter.x - contentCenterX) * newZoom;
8658
8919
  const offsetY = (currentCenter.y - contentCenterY) * newZoom;
8659
- canvas.relativePan({ x: offsetX, y: offsetY });
8920
+ canvas.relativePan(new FabricPoint(offsetX, offsetY));
8660
8921
 
8661
8922
  canvas.requestRenderAll();
8662
8923
  updateZoomLevel();
@@ -8693,7 +8954,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8693
8954
 
8694
8955
  // Copy — getObjects() returns the live _objects array.
8695
8956
  // Sort by canvas paint order (bottom → top) so grouping does not reverse z-index.
8696
- const objects = [...activeObject.getObjects()].sort((a: any, b: any) => {
8957
+ const objects = [...(activeObject as any).getObjects()].sort((a: any, b: any) => {
8697
8958
  const ia = a._canvasPaintOrder;
8698
8959
  const ib = b._canvasPaintOrder;
8699
8960
  if (typeof ia === 'number' && typeof ib === 'number') return ia - ib;
@@ -8711,7 +8972,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8711
8972
  canvas.discardActiveObject();
8712
8973
 
8713
8974
  objects.forEach((obj: any) => {
8714
- canvas.remove(obj);
8975
+ canvas!.remove(obj);
8715
8976
  if (!obj._objectId) obj._objectId = generateObjectId();
8716
8977
  });
8717
8978
 
@@ -8784,7 +9045,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8784
9045
 
8785
9046
  // 3. Add all items back to canvas (they already have correct absolute positions)
8786
9047
  items.forEach((item: any) => {
8787
- canvas.add(item);
9048
+ canvas!.add(item);
8788
9049
  });
8789
9050
 
8790
9051
  // 4. Create a new selection with the ungrouped objects
@@ -8928,7 +9189,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8928
9189
 
8929
9190
  let json: any = null;
8930
9191
  try {
8931
- json = canvasInstance.toJSON(propertiesToInclude);
9192
+ json = canvasInstance.toObject(propertiesToInclude);
9193
+ // fabric v6: toJSON() is the no-arg convenience alias; toObject()
9194
+ // is the form that carries propertiesToInclude.
8932
9195
  } finally {
8933
9196
  if (isMultiSelection && selectedObjects && selectedObjects.length > 0) {
8934
9197
  const restoredSelection = new ActiveSelection(selectedObjects, { canvas: canvasInstance });
@@ -9047,6 +9310,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
9047
9310
  }
9048
9311
  }
9049
9312
  applyInteractiveGroupFlags(obj);
9313
+ if ((obj as any)._isWidgetImage) lockWidgetShapeBodyDrag(obj);
9050
9314
  } catch (reviverErr) {
9051
9315
  canvasWarn('Canvas: restoreHistorySnapshot reviver error', obj?.type, reviverErr);
9052
9316
  }
@@ -9202,6 +9466,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
9202
9466
  }
9203
9467
  }
9204
9468
  applyInteractiveGroupFlags(obj);
9469
+ if ((obj as any)._isWidgetImage) lockWidgetShapeBodyDrag(obj);
9205
9470
  } catch (reviverErr) {
9206
9471
  canvasWarn('Canvas: loadCanvas reviver error for object', obj?.type, reviverErr);
9207
9472
  }
@@ -9280,7 +9545,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
9280
9545
 
9281
9546
  // Restore viewport (pan/zoom) if saved
9282
9547
  if (viewport && Array.isArray(viewport) && viewport.length === 6) {
9283
- canvas.setViewportTransform(viewport);
9548
+ canvas!.setViewportTransform(viewport as [number, number, number, number, number, number]);
9284
9549
  // Sync zoomLevel state for the PanZoomPanel
9285
9550
  zoomLevel = Math.round((canvas.getZoom() || 1) * 100);
9286
9551
  }
@@ -9341,8 +9606,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
9341
9606
  let textBoxWidth = 100;
9342
9607
  let text = new Textbox("Hello World!", {
9343
9608
  width: textBoxWidth,
9344
- top: Math.min(Math.random() * canvas.height, canvas.height - textBoxWidth),
9345
- left: Math.min(Math.random() * canvas.width, canvas.width - textBoxWidth),
9609
+ top: Math.min(Math.random() * canvas!.height, canvas!.height - textBoxWidth),
9610
+ left: Math.min(Math.random() * canvas!.width, canvas!.width - textBoxWidth),
9346
9611
  fill: shapeFillColor(),
9347
9612
  fontSize: 20,
9348
9613
  fontFamily: 'Arial',
@@ -9350,13 +9615,13 @@ function checkAndAddNewShapeToFrame(shape: any) {
9350
9615
  splitByGrapheme: true
9351
9616
  });
9352
9617
 
9353
- canvas.add(text);
9354
- canvas.setActiveObject(text);
9618
+ canvas!.add(text);
9619
+ canvas!.setActiveObject(text);
9355
9620
  activeEditingTextbox = text;
9356
9621
  text.enterEditing();
9357
9622
  text.selectAll();
9358
9623
  attachActiveTextListeners();
9359
- canvas.requestRenderAll();
9624
+ canvas!.requestRenderAll();
9360
9625
  }
9361
9626
 
9362
9627
  export function addTriangle() {
@@ -9366,8 +9631,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
9366
9631
  let triangle = new Path(createTrianglePathDefinition(triangleWidth, triangleHeight, 0), {
9367
9632
  width: triangleWidth,
9368
9633
  height: triangleHeight,
9369
- top: Math.min(Math.random() * canvas.height, canvas.height - triangleHeight),
9370
- left: Math.min(Math.random() * canvas.width, canvas.width - triangleWidth),
9634
+ top: Math.min(Math.random() * canvas!.height, canvas!.height - triangleHeight),
9635
+ left: Math.min(Math.random() * canvas!.width, canvas!.width - triangleWidth),
9371
9636
  fill: shapeFillColor(),
9372
9637
  stroke: shapeStrokeColor,
9373
9638
  strokeWidth: shapeStrokeWidth,
@@ -9382,8 +9647,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
9382
9647
  (triangle as any)._baseHeight = triangleHeight;
9383
9648
  (triangle as any)._cornerRoundness = 0;
9384
9649
 
9385
- canvas.add(triangle);
9386
- canvas.setActiveObject(triangle);
9650
+ canvas!.add(triangle);
9651
+ canvas!.setActiveObject(triangle);
9387
9652
  }
9388
9653
 
9389
9654
  export function addRect() {
@@ -9393,16 +9658,16 @@ function checkAndAddNewShapeToFrame(shape: any) {
9393
9658
  let rect = new Rect({
9394
9659
  width: rectWidth,
9395
9660
  height: rectHeight,
9396
- top: Math.min(Math.random() * canvas.height, canvas.height - rectHeight),
9397
- left: Math.min(Math.random() * canvas.width, canvas.width - rectWidth),
9661
+ top: Math.min(Math.random() * canvas!.height, canvas!.height - rectHeight),
9662
+ left: Math.min(Math.random() * canvas!.width, canvas!.width - rectWidth),
9398
9663
  fill: shapeFillColor(),
9399
9664
  stroke: shapeStrokeColor,
9400
9665
  strokeWidth: shapeStrokeWidth,
9401
9666
  strokeUniform: true
9402
9667
  });
9403
9668
 
9404
- canvas.add(rect);
9405
- canvas.setActiveObject(rect);
9669
+ canvas!.add(rect);
9670
+ canvas!.setActiveObject(rect);
9406
9671
  }
9407
9672
 
9408
9673
  export function addCircle() {
@@ -9418,15 +9683,15 @@ function checkAndAddNewShapeToFrame(shape: any) {
9418
9683
  lockScalingFlip: true
9419
9684
  });
9420
9685
 
9421
- canvas.add(circle);
9422
- canvas.setActiveObject(circle);
9686
+ canvas!.add(circle);
9687
+ canvas!.setActiveObject(circle);
9423
9688
  }
9424
9689
 
9425
9690
  export function addFrame() {
9426
9691
  const frameWidth = 150;
9427
9692
  const frameHeight = 150;
9428
- const frameLeft = Math.min(Math.random() * canvas.width, canvas.width - frameWidth - 50);
9429
- const frameTop = Math.min(Math.random() * canvas.height, canvas.height - frameHeight - 50);
9693
+ const frameLeft = Math.min(Math.random() * canvas!.width, canvas!.width - frameWidth - 50);
9694
+ const frameTop = Math.min(Math.random() * canvas!.height, canvas!.height - frameHeight - 50);
9430
9695
 
9431
9696
  // Create FrameShape - Group-based container with label, clipPath, edit mode support
9432
9697
  const frame = createFrameShape({
@@ -9444,11 +9709,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
9444
9709
  strokeWidth: 3
9445
9710
  });
9446
9711
 
9447
- canvas.add(frame);
9712
+ canvas!.add(frame);
9448
9713
  // Frames always sit at the lowest z-index so all other objects render above them
9449
- canvas.sendObjectToBack(frame);
9450
- canvas.setActiveObject(frame);
9451
- canvas.requestRenderAll();
9714
+ canvas!.sendObjectToBack(frame);
9715
+ canvas!.setActiveObject(frame);
9716
+ canvas!.requestRenderAll();
9452
9717
 
9453
9718
  canvasLog('FrameShape added', { frame });
9454
9719
  }
@@ -11910,11 +12175,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
11910
12175
  width: 300, height: 200,
11911
12176
  });
11912
12177
  (placeholder as any)._objectId = `img_paste_${Date.now()}`;
11913
- canvas.add(placeholder);
11914
- canvas.setActiveObject(placeholder);
12178
+ canvas!.add(placeholder);
12179
+ canvas!.setActiveObject(placeholder);
11915
12180
  selectedObject = placeholder;
11916
12181
  replacePlaceholderWithImage(placeholder, dataUrl, 'pasted-image.png', false);
11917
- canvas.requestRenderAll();
12182
+ canvas!.requestRenderAll();
11918
12183
  takeHistorySnapshot();
11919
12184
  clipboard = null;
11920
12185
  clipboardSourceObject = null;
@@ -11947,6 +12212,31 @@ function checkAndAddNewShapeToFrame(shape: any) {
11947
12212
  max-w-[calc(100%-1rem)] w-11/12
11948
12213
  -->
11949
12214
 
11950
- <style>/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */
11951
- button{cursor:pointer}.canvas-container{-webkit-user-select:none;user-select:none}.canvas-container input,.canvas-container textarea{-webkit-user-select:text;user-select:text}.canvas-loader-spinner{border:3px solid #e5e7eb;border-top-color:#374151;border-radius:50%;width:36px;height:36px;animation:.8s linear infinite canvas-spin}@keyframes canvas-spin{to{transform:rotate(360deg)}}.canvas-pan-zoom-overlay{width:max-content;max-width:calc(100% - 2rem);overflow:visible}
12215
+ <style>
12216
+ /* Prevent text selection in UI when using CMD+A */
12217
+ .canvas-container {
12218
+ user-select: none;
12219
+ -webkit-user-select: none;
12220
+ -moz-user-select: none;
12221
+ -ms-user-select: none;
12222
+ }
12223
+
12224
+ .canvas-loader-spinner {
12225
+ width: 36px;
12226
+ height: 36px;
12227
+ border: 3px solid #e5e7eb;
12228
+ border-top-color: #374151;
12229
+ border-radius: 50%;
12230
+ animation: canvas-spin 0.8s linear infinite;
12231
+ }
12232
+
12233
+ @keyframes canvas-spin {
12234
+ to { transform: rotate(360deg); }
12235
+ }
12236
+
12237
+ .canvas-pan-zoom-overlay {
12238
+ width: max-content;
12239
+ max-width: calc(100% - 2rem);
12240
+ overflow: visible;
12241
+ }
11952
12242
  </style>