@widgetic/canvas 0.5.13 → 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.
@@ -28,10 +28,21 @@
28
28
  MIN_FRAME_WIDTH, MIN_FRAME_HEIGHT, DEFAULT_STROKE, FRAME_HOVER_STROKE
29
29
  } from './shapes/FrameShape';
30
30
  import { ImageShape, IMAGE_SHAPE_CUSTOM_PROPS, upgradeToImageShape } from './shapes/ImageShape';
31
- import { WidgetShape, WIDGET_SHAPE_CUSTOM_PROPS, upgradeToWidgetShape } from './shapes/WidgetShape';
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 ──
@@ -121,6 +130,8 @@
121
130
  '_widgetId',
122
131
  // Widget Image: marks an image shape as a converted widget placeholder
123
132
  '_isWidgetImage',
133
+ // Widget thumbnail held by the host store instead of inline in the JSON
134
+ '_imageRef',
124
135
  ];
125
136
  const existing = new Set((FabricObject as any).customProperties as string[]);
126
137
  for (const prop of propsToRegister) {
@@ -214,6 +225,11 @@
214
225
  // The host can use this to open WidgetDetails for the linked widget.
215
226
  export let onWidgetImageClick: ((widgetId: string) => void) | null = null;
216
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
+
217
233
  // Callback: fires when a non-widget shape is selected on canvas.
218
234
  // The host can use this to close WidgetDetails panel.
219
235
  export let onNonWidgetSelected: (() => void) | null = null;
@@ -265,6 +281,11 @@
265
281
 
266
282
  // Refferences
267
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
+ */
268
289
  let canvas: Canvas | null = null;
269
290
 
270
291
  // Canvas state & configuration
@@ -576,7 +597,7 @@
576
597
  stampTopLevelPaintOrder();
577
598
  canvasLog('Canvas: rebuilt group after edit', {
578
599
  children: children.length,
579
- objectId: newGroup._objectId,
600
+ objectId: (newGroup as any)._objectId,
580
601
  });
581
602
  return newGroup;
582
603
  }
@@ -638,7 +659,9 @@
638
659
  let shapeStrokeWidth = 1;
639
660
 
640
661
  type ShapeToolType = 'rect' | 'circle' | 'circle-true' | 'triangle' | 'arrow';
641
- 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';
642
665
 
643
666
  const SHAPE_CONSTRAINT_MAP: Record<ShapeToolType, ConstraintType> = {
644
667
  rect: 'square',
@@ -657,8 +680,10 @@
657
680
  let lastAppliedBounds: { left: number; top: number; width: number; height: number } | null = null;
658
681
  let shapeKeyboardListenersAttached = false;
659
682
  let canvasScalingHandlers: {
660
- scaling: fabric.IEventHandler<Event>;
661
- 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;
662
687
  } | null = null;
663
688
 
664
689
  /**
@@ -1025,7 +1050,7 @@
1025
1050
  const isFrame = obj ? isFrameShape(obj) : false;
1026
1051
  const bounds = pendingConversion?.bounds ??
1027
1052
  (obj
1028
- ? obj.getBoundingRect(true)
1053
+ ? obj.getBoundingRect()
1029
1054
  : (() => {
1030
1055
  const a = canvas.getActiveObject() as any;
1031
1056
  return a ? a.getBoundingRect(true) : { left: 0, top: 0, width: 200, height: 200 };
@@ -1098,7 +1123,7 @@
1098
1123
  widgetImage._imageElement = img;
1099
1124
  widgetImage._originalAspectRatio = img.width / img.height;
1100
1125
  widgetImage.dirty = true;
1101
- canvas.requestRenderAll();
1126
+ canvas!.requestRenderAll();
1102
1127
  takeHistorySnapshot();
1103
1128
  canvasLog('Canvas: Widget Image created', { WidgetId: widgetId, ObjectId: newObjectId });
1104
1129
  };
@@ -1139,7 +1164,7 @@
1139
1164
  (obj as any)._hasImage = true;
1140
1165
  (obj as any)._imageUrl = newScreenshotDataUrl;
1141
1166
  (obj as any).dirty = true;
1142
- canvas.requestRenderAll();
1167
+ canvas!.requestRenderAll();
1143
1168
  canvasLog('Canvas: Widget Image updated', { WidgetId: widgetId });
1144
1169
  };
1145
1170
  img.onerror = () => {
@@ -1698,13 +1723,14 @@
1698
1723
  canvasLog('Rotation cursor: configured with retina image-set CSS');
1699
1724
  }
1700
1725
 
1701
- // Also override the rotation cursor on the canvas itself
1702
- 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;
1703
1729
 
1704
1730
  // Set cursor class during active rotation
1705
1731
  canvas.on('object:rotating', () => {
1706
1732
  isRotating = true;
1707
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.add('fabric-rotate-cursor');
1733
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.add('fabric-rotate-cursor');
1708
1734
  });
1709
1735
 
1710
1736
  // Detect hover over the mtr control by checking oCoords distance.
@@ -1718,17 +1744,17 @@
1718
1744
  // Always track mouse position in canvas-absolute (scene) coords
1719
1745
  // for paste-at-cursor and frame detection
1720
1746
  try {
1721
- const pointer = canvas.getScenePoint(e.e);
1747
+ const pointer = canvas!.getScenePoint(e.e);
1722
1748
  lastCanvasMousePosition = { x: pointer.x, y: pointer.y };
1723
1749
  } catch { /* ignore errors during init */ }
1724
1750
 
1725
- const activeObj = canvas.getActiveObject();
1751
+ const activeObj = canvas!.getActiveObject();
1726
1752
  if (!activeObj || !activeObj.oCoords) return;
1727
1753
  const mtrCoord = (activeObj.oCoords as any).mtr;
1728
1754
  if (!mtrCoord) return;
1729
1755
 
1730
1756
  // Get pointer in viewport-space (same space as oCoords)
1731
- const rect = canvas.upperCanvasEl?.getBoundingClientRect();
1757
+ const rect = canvas!.upperCanvasEl?.getBoundingClientRect();
1732
1758
  if (!rect) return;
1733
1759
  const vpX = e.e.clientX - rect.left;
1734
1760
  const vpY = e.e.clientY - rect.top;
@@ -1740,9 +1766,9 @@
1740
1766
 
1741
1767
  // Add/remove rotation cursor class based on proximity to mtr or active rotation
1742
1768
  if (dist <= 12 || isRotating) {
1743
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.add('fabric-rotate-cursor');
1769
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.add('fabric-rotate-cursor');
1744
1770
  } else {
1745
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1771
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1746
1772
  }
1747
1773
  });
1748
1774
 
@@ -1750,7 +1776,7 @@
1750
1776
  canvas.on('mouse:up', () => {
1751
1777
  if (isRotating) {
1752
1778
  isRotating = false;
1753
- if (canvas.upperCanvasEl) canvas.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1779
+ if (canvas!.upperCanvasEl) canvas!.upperCanvasEl.classList.remove('fabric-rotate-cursor');
1754
1780
  }
1755
1781
  });
1756
1782
 
@@ -1915,7 +1941,7 @@
1915
1941
  }
1916
1942
 
1917
1943
  target.setCoords?.();
1918
- canvas.uniformScaling = false;
1944
+ canvas!.uniformScaling = false;
1919
1945
  return; // Skip the rest, we've handled textbox specially
1920
1946
  } else {
1921
1947
  // Other objects: maintain initial aspect ratio
@@ -2017,12 +2043,12 @@
2017
2043
  }
2018
2044
 
2019
2045
  // Disable Fabric's native uniform scaling since we're handling it manually
2020
- canvas.uniformScaling = false;
2046
+ canvas!.uniformScaling = false;
2021
2047
  } else {
2022
2048
  // No Shift held: ensure free resize for non-locked shapes.
2023
2049
  // _lockAspectRatio shapes keep uniformScaling=true from before:transform.
2024
2050
  if (!target._lockAspectRatio) {
2025
- canvas.uniformScaling = false;
2051
+ canvas!.uniformScaling = false;
2026
2052
  }
2027
2053
  }
2028
2054
 
@@ -2030,7 +2056,7 @@
2030
2056
  // regardless of Shift key. Re-assert uniformScaling AND correct any
2031
2057
  // scale divergence that Fabric's uniScaleKey toggle may have introduced.
2032
2058
  if (target._forceLockAspectRatio) {
2033
- canvas.uniformScaling = true;
2059
+ canvas!.uniformScaling = true;
2034
2060
  const sx = Math.abs(target.scaleX ?? 1);
2035
2061
  const sy = Math.abs(target.scaleY ?? 1);
2036
2062
  if (Math.abs(sx - sy) > 0.001) {
@@ -2137,7 +2163,7 @@
2137
2163
  }
2138
2164
 
2139
2165
  // Reset uniform scaling after scale operation completes
2140
- canvas.uniformScaling = false;
2166
+ canvas!.uniformScaling = false;
2141
2167
 
2142
2168
  // Reset skew locks after scale operation completes
2143
2169
  target.lockSkewingX = false;
@@ -2319,7 +2345,7 @@
2319
2345
  // in object:scaling after the position has already been computed by Fabric.
2320
2346
  // uniformScaling is reset in handleObjectScaled (object:modified) at drag end.
2321
2347
  if ((transform.target as any)?._lockAspectRatio) {
2322
- canvas.uniformScaling = true;
2348
+ canvas!.uniformScaling = true;
2323
2349
  canvasLog('Canvas: lockAspectRatio — enabled uniformScaling for', (transform.target as any)?._shapeKey ?? transform.target?.type);
2324
2350
  }
2325
2351
 
@@ -2437,7 +2463,10 @@
2437
2463
  }
2438
2464
  });
2439
2465
 
2440
- 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) => {
2441
2470
  handleObjectScaled(opt);
2442
2471
  if ((opt?.target as any)?._isWidgetImage || (scalingTarget as any)?._isWidgetImage) {
2443
2472
  try {
@@ -2724,7 +2753,7 @@
2724
2753
  }
2725
2754
  }
2726
2755
  };
2727
- collectFrames(canvas.getObjects());
2756
+ collectFrames(canvas!.getObjects());
2728
2757
  return allFrames;
2729
2758
  };
2730
2759
 
@@ -2779,7 +2808,7 @@
2779
2808
  // Capture absolute matrices BEFORE any group changes.
2780
2809
  // obj.calcTransformMatrix() chains through the activeSelection
2781
2810
  // to give the correct post-drag canvas-space position.
2782
- const absMatrices = new Map<any, number[]>();
2811
+ const absMatrices = new Map<any, [number, number, number, number, number, number]>();
2783
2812
  objectsToMove.forEach((obj: any) => {
2784
2813
  absMatrices.set(obj, obj.calcTransformMatrix());
2785
2814
  });
@@ -2795,7 +2824,7 @@
2795
2824
  if (obj.group && obj.group !== targetFrame) {
2796
2825
  obj.group.remove(obj);
2797
2826
  } else if ((canvas as any)._objects?.includes(obj)) {
2798
- canvas.remove(obj);
2827
+ canvas!.remove(obj);
2799
2828
  }
2800
2829
  (obj as any)._set('group', undefined);
2801
2830
  (obj as any)._set('parent', undefined);
@@ -2806,7 +2835,7 @@
2806
2835
  // addObjectToFrame converts it to frame-local coords.
2807
2836
  if (m) fabricUtil.applyTransformToObject(obj, m);
2808
2837
 
2809
- addObjectToFrame(targetFrame, obj, canvas);
2838
+ addObjectToFrame(targetFrame, obj, canvas!);
2810
2839
  });
2811
2840
  } finally {
2812
2841
  isHandlingContainment = false;
@@ -2858,7 +2887,7 @@
2858
2887
  // are found — otherwise regular canvas moves would lose the selection.
2859
2888
  const objects = target.getObjects().slice();
2860
2889
 
2861
- type FrameBound = { obj: any; parentFrame: any; absMatrix: number[] };
2890
+ type FrameBound = { obj: any; parentFrame: any; absMatrix: [number, number, number, number, number, number] };
2862
2891
  const frameBoundObjects: FrameBound[] = [];
2863
2892
  const allCanvasObjects: any[] = (canvas as any)._objects || [];
2864
2893
 
@@ -2911,10 +2940,10 @@
2911
2940
  parentFrame.dirty = true;
2912
2941
 
2913
2942
  // Apply the captured post-drag absolute position
2914
- fabricUtil.applyTransformToObject(obj, absMatrix);
2943
+ fabricUtil.applyTransformToObject(obj, absMatrix as [number, number, number, number, number, number]);
2915
2944
 
2916
2945
  if (!(canvas as any)._objects?.includes(obj)) {
2917
- canvas.add(obj);
2946
+ canvas!.add(obj);
2918
2947
  }
2919
2948
  obj.setCoords();
2920
2949
  });
@@ -3055,6 +3084,12 @@
3055
3084
  });
3056
3085
  checkAndAddNewShapeToFrame(path);
3057
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);
3058
3093
  });
3059
3094
 
3060
3095
  // ─── History: snapshot after each completed move/scale/rotate ───
@@ -3092,7 +3127,7 @@
3092
3127
  if (target && target === activeEditingTextbox) return;
3093
3128
  if (target && target.isEditing) {
3094
3129
  target.exitEditing();
3095
- canvas.requestRenderAll();
3130
+ canvas!.requestRenderAll();
3096
3131
  }
3097
3132
  });
3098
3133
 
@@ -3191,7 +3226,7 @@
3191
3226
  }
3192
3227
 
3193
3228
  target.setCoords();
3194
- canvas.requestRenderAll();
3229
+ canvas!.requestRenderAll();
3195
3230
  return; // Handled textbox specially
3196
3231
  }
3197
3232
  // For rect, ellipse, triangle, frame: targetAspectRatio stays 1 (square/circle)
@@ -3276,7 +3311,7 @@
3276
3311
  }
3277
3312
 
3278
3313
  target.setCoords();
3279
- canvas.requestRenderAll();
3314
+ canvas!.requestRenderAll();
3280
3315
  }
3281
3316
  }
3282
3317
  };
@@ -3284,7 +3319,7 @@
3284
3319
  const handleGlobalShiftKeyup = (e: KeyboardEvent) => {
3285
3320
  if (e.key === 'Shift') {
3286
3321
  isShiftHeld = false;
3287
- canvas.uniformScaling = false;
3322
+ canvas!.uniformScaling = false;
3288
3323
  }
3289
3324
  };
3290
3325
 
@@ -3306,7 +3341,7 @@
3306
3341
  if (isMiddleControl) {
3307
3342
  scalingTarget.set({ skewX: 0, skewY: 0 });
3308
3343
  scalingTarget.setCoords();
3309
- canvas.requestRenderAll();
3344
+ canvas!.requestRenderAll();
3310
3345
  }
3311
3346
  }
3312
3347
  };
@@ -3355,7 +3390,7 @@
3355
3390
  if (obj.group && isFrameShape(obj.group)) {
3356
3391
  obj.group.remove(obj);
3357
3392
  } else {
3358
- canvas.remove(obj);
3393
+ canvas!.remove(obj);
3359
3394
  }
3360
3395
  });
3361
3396
  selectedObject = null;
@@ -3477,16 +3512,16 @@
3477
3512
  const selectAllFrameChildren = (parentFrame: any, frameChildren: any[]) => {
3478
3513
  if (frameChildren.length === 0) return;
3479
3514
  if (frameChildren.length === 1) {
3480
- canvas.setActiveObject(frameChildren[0]);
3481
- canvas.requestRenderAll();
3515
+ canvas!.setActiveObject(frameChildren[0]);
3516
+ canvas!.requestRenderAll();
3482
3517
  return;
3483
3518
  }
3484
3519
  // Constructor with enterGroup(child,false) + INITIALIZATION layout is
3485
3520
  // the correct one-pass approach — no drift across repeated Ctrl+A.
3486
- const sel = new ActiveSelection(frameChildren, { canvas });
3521
+ const sel = new ActiveSelection(frameChildren, { canvas: canvas! });
3487
3522
  (sel as any)._parentFrame = parentFrame;
3488
- canvas.setActiveObject(sel);
3489
- canvas.requestRenderAll();
3523
+ canvas!.setActiveObject(sel);
3524
+ canvas!.requestRenderAll();
3490
3525
  };
3491
3526
 
3492
3527
  const handleSelectAllKeydown = (e: KeyboardEvent) => {
@@ -4058,7 +4093,7 @@
4058
4093
  left: (obj.left || 0) + (cloned.left || 0) + cloneWidth / 2,
4059
4094
  top: (obj.top || 0) + (cloned.top || 0) + cloneHeight / 2,
4060
4095
  });
4061
- addObjectToFrame(targetFrame, obj, canvas);
4096
+ addObjectToFrame(targetFrame, obj, canvas!);
4062
4097
  });
4063
4098
  if (!hasPendingWidgetPaste) {
4064
4099
  const frameChildren = targetFrame.getObjects().filter((o: any) => !o._isFrameBackground);
@@ -4069,7 +4104,7 @@
4069
4104
  } else {
4070
4105
  cloned.canvas = canvas;
4071
4106
  cloned.forEachObject((obj: any) => {
4072
- canvas.add(obj);
4107
+ canvas!.add(obj);
4073
4108
  });
4074
4109
  cloned.setCoords();
4075
4110
  if (!hasPendingWidgetPaste) canvas.setActiveObject(cloned);
@@ -4128,16 +4163,17 @@
4128
4163
 
4129
4164
  // Clone the active object
4130
4165
  const cloned = await activeObject.clone();
4131
-
4132
- // Copy custom properties from original to cloned
4133
- if (activeObject.type === 'activeSelection' || activeObject.type === 'activeselection') {
4134
- const sourceObjects = (activeObject as any).getObjects();
4135
- const clonedObjects = cloned.getObjects();
4136
- sourceObjects.forEach((srcObj: any, idx: number) => {
4137
- if (clonedObjects[idx]) {
4138
- copyCustomProperties(srcObj, clonedObjects[idx]);
4139
- }
4140
- });
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
+ });
4141
4177
  } else {
4142
4178
  copyCustomProperties(activeObject, cloned);
4143
4179
  }
@@ -4163,7 +4199,7 @@
4163
4199
  }
4164
4200
  };
4165
4201
  if (cloned.type === 'activeSelection' || cloned.type === 'activeselection') {
4166
- cloned.getObjects().forEach(handleWidgetDuplicate);
4202
+ clonedSrc.getObjects().forEach(handleWidgetDuplicate);
4167
4203
  } else {
4168
4204
  handleWidgetDuplicate(cloned);
4169
4205
  }
@@ -4178,9 +4214,9 @@
4178
4214
  // Handle ActiveSelection (multiple objects) - following Fabric.js demo approach
4179
4215
  if (cloned.type === 'activeSelection' || cloned.type === 'activeselection') {
4180
4216
  // Active selection needs a reference to the canvas
4181
- cloned.canvas = canvas;
4182
- cloned.forEachObject((obj: any) => {
4183
- canvas.add(obj);
4217
+ clonedSrc.canvas = canvas;
4218
+ clonedSrc.forEachObject((obj: any) => {
4219
+ canvas!.add(obj);
4184
4220
  });
4185
4221
  // This should solve the unselectability
4186
4222
  cloned.setCoords();
@@ -4207,7 +4243,7 @@
4207
4243
  });
4208
4244
 
4209
4245
  // 1. Restore Frame render override + interactive properties
4210
- reapplyFrameRender(cloned);
4246
+ reapplyFrameRender(cloned as unknown as Group);
4211
4247
 
4212
4248
  // 2. Patch setCoords to no-op during enterGroup
4213
4249
  // (_enterGroup calls setCoords before group/canvas are set → wrong coords)
@@ -4277,7 +4313,7 @@
4277
4313
  } else {
4278
4314
  // Canvas-level paste — restore Frame properties if cloning a Frame
4279
4315
  if (isFrameShape(cloned)) {
4280
- reapplyFrameRender(cloned);
4316
+ reapplyFrameRender(cloned as unknown as Group);
4281
4317
  canvasLog('Canvas: Restored Frame properties on canvas-level duplicate');
4282
4318
  }
4283
4319
  canvas.add(cloned);
@@ -4344,7 +4380,7 @@
4344
4380
  if (obj.group && isFrameShape(obj.group)) {
4345
4381
  obj.group.remove(obj);
4346
4382
  } else {
4347
- canvas.remove(obj);
4383
+ canvas!.remove(obj);
4348
4384
  }
4349
4385
  });
4350
4386
  } else {
@@ -4503,11 +4539,11 @@
4503
4539
  height: 200,
4504
4540
  });
4505
4541
  (placeholder as any)._objectId = `img_paste_${Date.now()}`;
4506
- canvas.add(placeholder);
4507
- canvas.setActiveObject(placeholder);
4542
+ canvas!.add(placeholder);
4543
+ canvas!.setActiveObject(placeholder);
4508
4544
  selectedObject = placeholder;
4509
4545
  replacePlaceholderWithImage(placeholder, dataUrl, 'pasted-image.png', false);
4510
- canvas.requestRenderAll();
4546
+ canvas!.requestRenderAll();
4511
4547
  takeHistorySnapshot();
4512
4548
  canvasLog('Canvas: Image pasted from OS clipboard at', { x: Math.round(mousePos.x), y: Math.round(mousePos.y) });
4513
4549
  };
@@ -4717,7 +4753,7 @@
4717
4753
  // Safety: if the background rect itself is somehow selected, select the parent frame
4718
4754
  if (activeObj._isFrameBackground && activeObj.group && isFrameShape(activeObj.group)) {
4719
4755
  // Switch the canvas selection to the parent frame
4720
- canvas.setActiveObject(activeObj.group);
4756
+ canvas!.setActiveObject(activeObj.group);
4721
4757
  return activeObj.group;
4722
4758
  }
4723
4759
 
@@ -4731,7 +4767,7 @@
4731
4767
  if (!isRedirectingGroupSelection) {
4732
4768
  isRedirectingGroupSelection = true;
4733
4769
  try {
4734
- canvas.setActiveObject(parent);
4770
+ canvas!.setActiveObject(parent);
4735
4771
  } finally {
4736
4772
  isRedirectingGroupSelection = false;
4737
4773
  }
@@ -4748,13 +4784,13 @@
4748
4784
 
4749
4785
  const handleSelectionCreated = (e: any) => {
4750
4786
  // Get the active object which could be a single object, group, or activeSelection
4751
- const activeObj = canvas.getActiveObject() as any;
4787
+ const activeObj = canvas!.getActiveObject() as any;
4752
4788
 
4753
4789
  // If it's a multi-selection, detect and set common properties
4754
4790
  if (activeObj && (activeObj.type === 'activeSelection' || activeObj.type === 'activeselection')) {
4755
4791
  setCommonPropertiesOnSelection(activeObj);
4756
4792
  // Disable caching if selection contains Frame/Image with custom render
4757
- const hasCustomRender = activeObj.getObjects().some((obj: any) =>
4793
+ const hasCustomRender = (activeObj as any).getObjects().some((obj: any) =>
4758
4794
  isFrameShape(obj) || obj._customType === 'image'
4759
4795
  );
4760
4796
  if (hasCustomRender) {
@@ -4766,7 +4802,7 @@
4766
4802
  const selItems: any[] = activeObj.getObjects ? activeObj.getObjects() : [];
4767
4803
  const frameId = selItems[0]?._parentFrameId;
4768
4804
  if (frameId && selItems.every((item: any) => item._parentFrameId === frameId)) {
4769
- const parentFrame = canvas.getObjects().find((o: any) => o._objectId === frameId);
4805
+ const parentFrame = canvas!.getObjects().find((o: any) => o._objectId === frameId);
4770
4806
  if (parentFrame && isFrameShape(parentFrame)) {
4771
4807
  activeObj._parentFrame = parentFrame;
4772
4808
  canvasLog('Canvas: selection:created — tagged with parent frame', (parentFrame as any)._labelText || frameId);
@@ -4776,6 +4812,7 @@
4776
4812
  }
4777
4813
 
4778
4814
  selectedObject = resolveSelectedObject(activeObj);
4815
+ if ((selectedObject as any)?._isWidgetImage) lockWidgetShapeBodyDrag(selectedObject);
4779
4816
  // Self-heal _customType and _cornerRadiusMode for any library shape on selection.
4780
4817
  // Covers old saves where _customType was missing and stale _cornerRadiusMode values.
4781
4818
  if ((selectedObject as any)?._shapeKey) {
@@ -4795,13 +4832,13 @@
4795
4832
 
4796
4833
  const handleSelectionUpdated = (e: any) => {
4797
4834
  // Get the active object which could be a single object, group, or activeSelection
4798
- const activeObj = canvas.getActiveObject();
4835
+ const activeObj = canvas!.getActiveObject();
4799
4836
 
4800
4837
  // If it's a multi-selection, detect and set common properties
4801
4838
  if (activeObj && (activeObj.type === 'activeSelection' || activeObj.type === 'activeselection')) {
4802
4839
  setCommonPropertiesOnSelection(activeObj);
4803
4840
  // Disable caching if selection contains Frame/Image with custom render
4804
- const hasCustomRender = activeObj.getObjects().some((obj: any) =>
4841
+ const hasCustomRender = (activeObj as any).getObjects().some((obj: any) =>
4805
4842
  isFrameShape(obj) || obj._customType === 'image'
4806
4843
  );
4807
4844
  if (hasCustomRender) {
@@ -4810,6 +4847,7 @@
4810
4847
  }
4811
4848
 
4812
4849
  selectedObject = resolveSelectedObject(activeObj);
4850
+ if ((selectedObject as any)?._isWidgetImage) lockWidgetShapeBodyDrag(selectedObject);
4813
4851
  // Self-heal _customType and _cornerRadiusMode for any library shape on selection.
4814
4852
  if ((selectedObject as any)?._shapeKey) {
4815
4853
  if ((selectedObject as any)._customType !== 'libraryShape') {
@@ -4870,7 +4908,7 @@
4870
4908
  // Defer selectAll to run after Fabric's internal dblclick word-selection
4871
4909
  requestAnimationFrame(() => {
4872
4910
  target.selectAll();
4873
- canvas.requestRenderAll();
4911
+ canvas!.requestRenderAll();
4874
4912
  });
4875
4913
  return;
4876
4914
  }
@@ -4886,9 +4924,9 @@
4886
4924
  enterGroupEdit(target);
4887
4925
  const sub = Array.isArray(e.subTargets) ? e.subTargets[0] : null;
4888
4926
  if (sub && sub !== target) {
4889
- canvas.setActiveObject(sub);
4927
+ canvas!.setActiveObject(sub);
4890
4928
  }
4891
- canvas.requestRenderAll();
4929
+ canvas!.requestRenderAll();
4892
4930
  canvasLog('Canvas: entered group via double-click', {
4893
4931
  children: target.getObjects?.()?.length,
4894
4932
  subType: sub?.type,
@@ -4973,7 +5011,7 @@
4973
5011
  }
4974
5012
  }
4975
5013
  };
4976
- recurse(canvas.getObjects());
5014
+ recurse(canvas!.getObjects());
4977
5015
  return frames;
4978
5016
  };
4979
5017
 
@@ -5128,16 +5166,17 @@
5128
5166
  */
5129
5167
  const getSelectableObjectsAtPoint = (point: any): any[] => {
5130
5168
  const result: any[] = [];
5131
- const canvasObjects = canvas.getObjects();
5169
+ const canvasObjects = canvas!.getObjects();
5132
5170
  for (const obj of canvasObjects) {
5133
5171
  // Skip non-selectable and background rects
5134
- if (obj.selectable === false || obj._isFrameBackground) continue;
5172
+ if (obj.selectable === false || (obj as any)._isFrameBackground) continue;
5135
5173
  if (obj.containsPoint(point)) {
5136
5174
  result.push(obj);
5137
5175
  }
5138
5176
  // Also check inside interactive frames (children are selectable directly)
5139
- if (isFrameShape(obj) && obj.interactive) {
5140
- 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?.() ?? [];
5141
5180
  for (const child of children) {
5142
5181
  if (child.selectable === false || child._isFrameBackground) continue;
5143
5182
  if (child.containsPoint(point)) {
@@ -5155,7 +5194,9 @@
5155
5194
  if (!isAlt) return;
5156
5195
 
5157
5196
  // Don't intercept if the click is on a control handle (resize/rotate)
5158
- 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;
5159
5200
 
5160
5201
  // Get click position in scene coordinates
5161
5202
  let point: any;
@@ -5213,7 +5254,7 @@
5213
5254
  return;
5214
5255
  }
5215
5256
 
5216
- const pointer = canvas.getScenePoint(opt.e);
5257
+ const pointer = canvas!.getScenePoint(opt.e);
5217
5258
 
5218
5259
  // Only intercept if click is strictly inside the frame (not on border/label)
5219
5260
  if (isPointOnFrameBorder(target, pointer)) return;
@@ -5225,7 +5266,7 @@
5225
5266
 
5226
5267
  // Clear the target — Fabric will proceed with rubber-band selection
5227
5268
  (canvas as any)._target = null;
5228
- canvas.setCursor(canvas.defaultCursor || 'default');
5269
+ canvas!.setCursor(canvas!.defaultCursor || 'default');
5229
5270
  canvasLog('Canvas: Frame interior — cleared target for rubber-band, lastInteractedFrame =', target._labelText || target._objectId || 'frame');
5230
5271
  };
5231
5272
  canvas.on('mouse:down:before', handleFrameInteriorMouseDownBefore);
@@ -5237,10 +5278,10 @@
5237
5278
  // We run AFTER Fabric's mouse:up to correct it.
5238
5279
  const handleFrameInteriorMouseUp = (opt: any) => {
5239
5280
  if (!opt.e) return;
5240
- const pointer = canvas.getScenePoint(opt.e);
5281
+ const pointer = canvas!.getScenePoint(opt.e);
5241
5282
  for (const frame of collectAllFrames()) {
5242
5283
  if (isPointInsideFrame(frame, pointer) && !isPointOnFrameBorder(frame, pointer) && !isPointInFrameLabel(frame, pointer)) {
5243
- canvas.setCursor(canvas.defaultCursor || 'default');
5284
+ canvas!.setCursor(canvas!.defaultCursor || 'default');
5244
5285
  return;
5245
5286
  }
5246
5287
  }
@@ -5321,13 +5362,13 @@
5321
5362
  (canvas as any)._groupSelector = null;
5322
5363
 
5323
5364
  if (matched.length === 1) {
5324
- canvas.setActiveObject(matched[0]);
5365
+ canvas!.setActiveObject(matched[0]);
5325
5366
  } else {
5326
- const sel = new ActiveSelection(matched, { canvas });
5367
+ const sel = new ActiveSelection(matched, { canvas: canvas! });
5327
5368
  (sel as any)._parentFrame = frame;
5328
- canvas.setActiveObject(sel);
5369
+ canvas!.setActiveObject(sel);
5329
5370
  }
5330
- canvas.requestRenderAll();
5371
+ canvas!.requestRenderAll();
5331
5372
  canvasLog('Canvas: rubber-band inside frame — selected', matched.length, 'children in', (frame as any)._labelText || 'frame');
5332
5373
  break;
5333
5374
  }
@@ -5337,7 +5378,7 @@
5337
5378
  console.error('Canvas: handleFrameRubberBandUpBefore error:', err);
5338
5379
  // Best-effort cleanup: clear the rubber-band indicator
5339
5380
  (canvas as any)._groupSelector = null;
5340
- canvas.renderTop();
5381
+ canvas!.renderTop();
5341
5382
  }
5342
5383
  };
5343
5384
  canvas.on('mouse:up:before', handleFrameRubberBandUpBefore);
@@ -5413,7 +5454,7 @@
5413
5454
  // If the AS was moved/resized, save the NEW absolute positions.
5414
5455
  // Otherwise restore canonical positions to counteract FP drift.
5415
5456
  canvas.on('selection:cleared', () => {
5416
- 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);
5417
5458
  if (_activeSelectionModified) {
5418
5459
  _activeSelectionModified = false;
5419
5460
  saveAbsolutePositions(allObjects);
@@ -5488,7 +5529,7 @@
5488
5529
  if (!files || files.length === 0) return;
5489
5530
 
5490
5531
  // Get drop position in canvas scene coordinates (handles pan & zoom)
5491
- const scenePoint = canvas.getScenePoint(e);
5532
+ const scenePoint = canvas!.getScenePoint(e);
5492
5533
  const dropX = scenePoint.x;
5493
5534
  const dropY = scenePoint.y;
5494
5535
 
@@ -5503,8 +5544,8 @@
5503
5544
  if (isVideo) {
5504
5545
  const { video, objectUrl } = createVideoElementFromFile(file);
5505
5546
  capturePosterFromVideo(video).then((posterUrl) => {
5506
- const maxWidth = canvas.width * 0.6;
5507
- const maxHeight = canvas.height * 0.6;
5547
+ const maxWidth = canvas!.width * 0.6;
5548
+ const maxHeight = canvas!.height * 0.6;
5508
5549
  const tempImg = new Image();
5509
5550
  tempImg.onload = () => {
5510
5551
  let width = tempImg.width;
@@ -5521,8 +5562,8 @@
5521
5562
  height,
5522
5563
  mediaKind: 'video'
5523
5564
  });
5524
- canvas.add(videoShape);
5525
- canvas.setActiveObject(videoShape);
5565
+ canvas!.add(videoShape);
5566
+ canvas!.setActiveObject(videoShape);
5526
5567
  attachVideoElementToShape(videoShape, video, objectUrl);
5527
5568
  loadImageIntoShape(videoShape, posterUrl, file.name);
5528
5569
  canvasLog('Video dropped on canvas:', file.name);
@@ -5543,8 +5584,8 @@
5543
5584
  const tempImg = new Image();
5544
5585
  tempImg.onload = () => {
5545
5586
  // Scale image to fit if too large
5546
- const maxWidth = canvas.width * 0.6;
5547
- const maxHeight = canvas.height * 0.6;
5587
+ const maxWidth = canvas!.width * 0.6;
5588
+ const maxHeight = canvas!.height * 0.6;
5548
5589
 
5549
5590
  let width = tempImg.width;
5550
5591
  let height = tempImg.height;
@@ -5563,8 +5604,8 @@
5563
5604
  height: height
5564
5605
  });
5565
5606
 
5566
- canvas.add(imageShape);
5567
- canvas.setActiveObject(imageShape);
5607
+ canvas!.add(imageShape);
5608
+ canvas!.setActiveObject(imageShape);
5568
5609
 
5569
5610
  // Load the image into the shape
5570
5611
  loadImageIntoShape(imageShape, dataUrl, file.name);
@@ -5666,9 +5707,9 @@
5666
5707
  };
5667
5708
 
5668
5709
  canvas.on('mouse:move', (hoverOpt: any) => {
5669
- const pointer = canvas.getScenePoint(hoverOpt.e);
5710
+ const pointer = canvas!.getScenePoint(hoverOpt.e);
5670
5711
  let needsRender = false;
5671
- for (const obj of canvas.getObjects()) {
5712
+ for (const obj of canvas!.getObjects()) {
5672
5713
  if (!isFrameShape(obj)) continue;
5673
5714
  const wasHovered = !!(obj as any)._borderHovered;
5674
5715
  const isNowHovered =
@@ -5679,7 +5720,7 @@
5679
5720
  needsRender = true;
5680
5721
  }
5681
5722
  }
5682
- if (needsRender) canvas.requestRenderAll();
5723
+ if (needsRender) canvas!.requestRenderAll();
5683
5724
  });
5684
5725
 
5685
5726
  // Clear all frame hover states when mouse leaves the canvas wrapper
@@ -5687,14 +5728,14 @@
5687
5728
  if (hoverWrapperEl) {
5688
5729
  hoverWrapperEl.addEventListener('mouseleave', () => {
5689
5730
  let needsRender = false;
5690
- for (const obj of canvas.getObjects()) {
5731
+ for (const obj of canvas!.getObjects()) {
5691
5732
  if (!isFrameShape(obj)) continue;
5692
5733
  if ((obj as any)._borderHovered) {
5693
5734
  applyFrameHoverStroke(obj, false);
5694
5735
  needsRender = true;
5695
5736
  }
5696
5737
  }
5697
- if (needsRender) canvas.requestRenderAll();
5738
+ if (needsRender) canvas!.requestRenderAll();
5698
5739
  // WidgetShape drag bar must also hide when the pointer leaves the canvas.
5699
5740
  setHoveredWidgetShape(null);
5700
5741
  });
@@ -5789,7 +5830,7 @@
5789
5830
 
5790
5831
  if (canvas && canvasScalingHandlers) {
5791
5832
  canvas.off('object:scaling', canvasScalingHandlers.scaling);
5792
- canvas.off('object:scaled', canvasScalingHandlers.scaled);
5833
+ (canvas as any).off('object:scaled', canvasScalingHandlers.scaled);
5793
5834
  canvasScalingHandlers = null;
5794
5835
  }
5795
5836
 
@@ -7029,6 +7070,207 @@ function checkAndAddNewShapeToFrame(shape: any) {
7029
7070
  });
7030
7071
  }
7031
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
+
7032
7274
  // Text object method
7033
7275
  export function onSelectTextTool() {
7034
7276
  setActiveTool('text', () => {
@@ -7370,7 +7612,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
7370
7612
  return;
7371
7613
  }
7372
7614
 
7373
- let finalizePointer = pointer;
7615
+ let finalizePointer: { x: number; y: number } = pointer;
7374
7616
  if (!lastAppliedBounds || Math.max(lastAppliedBounds.width, lastAppliedBounds.height) < MIN_DRAW_DISTANCE) {
7375
7617
  finalizePointer = {
7376
7618
  x: arrowStartPoint.x + DEFAULT_OBJECT_SIZE,
@@ -7716,11 +7958,19 @@ function checkAndAddNewShapeToFrame(shape: any) {
7716
7958
  if (!canvas || !widgetId) return false;
7717
7959
  const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId) as any;
7718
7960
  if (!obj) return false;
7719
- 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);
7720
7967
  // setXY accepts scene coordinates even while an ActiveSelection owns the object.
7721
7968
  // Movement locks only affect Fabric pointer transforms, not programmatic setters.
7722
7969
  const position = obj.getXY();
7723
- 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
+ ));
7724
7974
  obj.setXY(nextPosition);
7725
7975
  // selection:cleared restores this canonical cache. Update it before any
7726
7976
  // deselection/history serialization, otherwise the header move snaps back.
@@ -7782,6 +8032,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
7782
8032
  if (!canvas || !widgetId) return false;
7783
8033
  const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId);
7784
8034
  if (!obj) return false;
8035
+ lockWidgetShapeBodyDrag(obj);
7785
8036
  canvas.setActiveObject(obj);
7786
8037
  canvas.requestRenderAll();
7787
8038
  return true;
@@ -7794,6 +8045,18 @@ function checkAndAddNewShapeToFrame(shape: any) {
7794
8045
  return null;
7795
8046
  }
7796
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
+
7797
8060
  export function getHoveredWidgetShapeId(): string | null {
7798
8061
  return hoveredWidgetShapeId;
7799
8062
  }
@@ -8457,7 +8720,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8457
8720
  // Mark as dirty and re-render
8458
8721
  imageShape.dirty = true;
8459
8722
  imageShape.setCoords();
8460
- canvas.requestRenderAll();
8723
+ canvas!.requestRenderAll();
8461
8724
 
8462
8725
  // Update selectedObject reference
8463
8726
  selectedObject = imageShape;
@@ -8518,7 +8781,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8518
8781
  const deltaY = e.clientY - panStartPoint.y;
8519
8782
 
8520
8783
  // Use relativePan to move the viewport
8521
- canvas.relativePan({ x: deltaX, y: deltaY });
8784
+ canvas.relativePan(new FabricPoint(deltaX, deltaY));
8522
8785
 
8523
8786
  // Update start point for next move
8524
8787
  panStartPoint = { x: e.clientX, y: e.clientY };
@@ -8648,13 +8911,13 @@ function checkAndAddNewShapeToFrame(shape: any) {
8648
8911
  const contentCenterY = minY + contentHeight / 2;
8649
8912
 
8650
8913
  // Apply zoom
8651
- canvas.zoomToPoint({ x: canvasWidth / 2, y: canvasHeight / 2 }, newZoom);
8914
+ canvas.zoomToPoint(new FabricPoint(canvasWidth / 2, canvasHeight / 2), newZoom);
8652
8915
 
8653
8916
  // Pan to center content
8654
8917
  const currentCenter = canvas.getCenterPoint();
8655
8918
  const offsetX = (currentCenter.x - contentCenterX) * newZoom;
8656
8919
  const offsetY = (currentCenter.y - contentCenterY) * newZoom;
8657
- canvas.relativePan({ x: offsetX, y: offsetY });
8920
+ canvas.relativePan(new FabricPoint(offsetX, offsetY));
8658
8921
 
8659
8922
  canvas.requestRenderAll();
8660
8923
  updateZoomLevel();
@@ -8691,7 +8954,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8691
8954
 
8692
8955
  // Copy — getObjects() returns the live _objects array.
8693
8956
  // Sort by canvas paint order (bottom → top) so grouping does not reverse z-index.
8694
- const objects = [...activeObject.getObjects()].sort((a: any, b: any) => {
8957
+ const objects = [...(activeObject as any).getObjects()].sort((a: any, b: any) => {
8695
8958
  const ia = a._canvasPaintOrder;
8696
8959
  const ib = b._canvasPaintOrder;
8697
8960
  if (typeof ia === 'number' && typeof ib === 'number') return ia - ib;
@@ -8709,7 +8972,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8709
8972
  canvas.discardActiveObject();
8710
8973
 
8711
8974
  objects.forEach((obj: any) => {
8712
- canvas.remove(obj);
8975
+ canvas!.remove(obj);
8713
8976
  if (!obj._objectId) obj._objectId = generateObjectId();
8714
8977
  });
8715
8978
 
@@ -8782,7 +9045,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8782
9045
 
8783
9046
  // 3. Add all items back to canvas (they already have correct absolute positions)
8784
9047
  items.forEach((item: any) => {
8785
- canvas.add(item);
9048
+ canvas!.add(item);
8786
9049
  });
8787
9050
 
8788
9051
  // 4. Create a new selection with the ungrouped objects
@@ -8887,6 +9150,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
8887
9150
  '_widgetId',
8888
9151
  // Widget Image: converted widget placeholder on canvas
8889
9152
  '_isWidgetImage',
9153
+ // Widget thumbnail kept in the host store, referenced instead of inlined
9154
+ '_imageRef',
8890
9155
  '_groupFill', '_groupStroke', '_groupStrokeWidth',
8891
9156
  '_groupFillOpacity', '_groupStrokeDashArray',
8892
9157
  '_canvasPaintOrder',
@@ -8924,7 +9189,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8924
9189
 
8925
9190
  let json: any = null;
8926
9191
  try {
8927
- 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.
8928
9195
  } finally {
8929
9196
  if (isMultiSelection && selectedObjects && selectedObjects.length > 0) {
8930
9197
  const restoredSelection = new ActiveSelection(selectedObjects, { canvas: canvasInstance });
@@ -9043,6 +9310,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
9043
9310
  }
9044
9311
  }
9045
9312
  applyInteractiveGroupFlags(obj);
9313
+ if ((obj as any)._isWidgetImage) lockWidgetShapeBodyDrag(obj);
9046
9314
  } catch (reviverErr) {
9047
9315
  canvasWarn('Canvas: restoreHistorySnapshot reviver error', obj?.type, reviverErr);
9048
9316
  }
@@ -9198,6 +9466,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
9198
9466
  }
9199
9467
  }
9200
9468
  applyInteractiveGroupFlags(obj);
9469
+ if ((obj as any)._isWidgetImage) lockWidgetShapeBodyDrag(obj);
9201
9470
  } catch (reviverErr) {
9202
9471
  canvasWarn('Canvas: loadCanvas reviver error for object', obj?.type, reviverErr);
9203
9472
  }
@@ -9208,9 +9477,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
9208
9477
  // Light pass: ensure any images without loaded elements are reloaded
9209
9478
  const allObjects = canvas.getObjects();
9210
9479
  const checkUnloadedImages = (obj: any) => {
9211
- if (obj._customType === 'image' || obj._hasImage || obj._imageUrl) {
9480
+ if (obj._customType === 'image' || obj._hasImage || obj._imageUrl || obj._imageRef) {
9212
9481
  if (obj._imageUrl && !obj._imageElement) {
9213
9482
  ImageShape.reloadImage(obj);
9483
+ } else if (!obj._imageUrl && obj._imageRef) {
9484
+ // Thumbnail lives in the host store, not in the JSON
9485
+ void restoreThumbnailFromStore(obj);
9214
9486
  }
9215
9487
  } else if (String(obj.type || '').toLowerCase() === 'group' || isFrameShape(obj)) {
9216
9488
  (obj.getObjects?.() || []).forEach(checkUnloadedImages);
@@ -9273,7 +9545,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
9273
9545
 
9274
9546
  // Restore viewport (pan/zoom) if saved
9275
9547
  if (viewport && Array.isArray(viewport) && viewport.length === 6) {
9276
- canvas.setViewportTransform(viewport);
9548
+ canvas!.setViewportTransform(viewport as [number, number, number, number, number, number]);
9277
9549
  // Sync zoomLevel state for the PanZoomPanel
9278
9550
  zoomLevel = Math.round((canvas.getZoom() || 1) * 100);
9279
9551
  }
@@ -9334,8 +9606,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
9334
9606
  let textBoxWidth = 100;
9335
9607
  let text = new Textbox("Hello World!", {
9336
9608
  width: textBoxWidth,
9337
- top: Math.min(Math.random() * canvas.height, canvas.height - textBoxWidth),
9338
- 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),
9339
9611
  fill: shapeFillColor(),
9340
9612
  fontSize: 20,
9341
9613
  fontFamily: 'Arial',
@@ -9343,13 +9615,13 @@ function checkAndAddNewShapeToFrame(shape: any) {
9343
9615
  splitByGrapheme: true
9344
9616
  });
9345
9617
 
9346
- canvas.add(text);
9347
- canvas.setActiveObject(text);
9618
+ canvas!.add(text);
9619
+ canvas!.setActiveObject(text);
9348
9620
  activeEditingTextbox = text;
9349
9621
  text.enterEditing();
9350
9622
  text.selectAll();
9351
9623
  attachActiveTextListeners();
9352
- canvas.requestRenderAll();
9624
+ canvas!.requestRenderAll();
9353
9625
  }
9354
9626
 
9355
9627
  export function addTriangle() {
@@ -9359,8 +9631,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
9359
9631
  let triangle = new Path(createTrianglePathDefinition(triangleWidth, triangleHeight, 0), {
9360
9632
  width: triangleWidth,
9361
9633
  height: triangleHeight,
9362
- top: Math.min(Math.random() * canvas.height, canvas.height - triangleHeight),
9363
- 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),
9364
9636
  fill: shapeFillColor(),
9365
9637
  stroke: shapeStrokeColor,
9366
9638
  strokeWidth: shapeStrokeWidth,
@@ -9375,8 +9647,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
9375
9647
  (triangle as any)._baseHeight = triangleHeight;
9376
9648
  (triangle as any)._cornerRoundness = 0;
9377
9649
 
9378
- canvas.add(triangle);
9379
- canvas.setActiveObject(triangle);
9650
+ canvas!.add(triangle);
9651
+ canvas!.setActiveObject(triangle);
9380
9652
  }
9381
9653
 
9382
9654
  export function addRect() {
@@ -9386,16 +9658,16 @@ function checkAndAddNewShapeToFrame(shape: any) {
9386
9658
  let rect = new Rect({
9387
9659
  width: rectWidth,
9388
9660
  height: rectHeight,
9389
- top: Math.min(Math.random() * canvas.height, canvas.height - rectHeight),
9390
- 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),
9391
9663
  fill: shapeFillColor(),
9392
9664
  stroke: shapeStrokeColor,
9393
9665
  strokeWidth: shapeStrokeWidth,
9394
9666
  strokeUniform: true
9395
9667
  });
9396
9668
 
9397
- canvas.add(rect);
9398
- canvas.setActiveObject(rect);
9669
+ canvas!.add(rect);
9670
+ canvas!.setActiveObject(rect);
9399
9671
  }
9400
9672
 
9401
9673
  export function addCircle() {
@@ -9411,15 +9683,15 @@ function checkAndAddNewShapeToFrame(shape: any) {
9411
9683
  lockScalingFlip: true
9412
9684
  });
9413
9685
 
9414
- canvas.add(circle);
9415
- canvas.setActiveObject(circle);
9686
+ canvas!.add(circle);
9687
+ canvas!.setActiveObject(circle);
9416
9688
  }
9417
9689
 
9418
9690
  export function addFrame() {
9419
9691
  const frameWidth = 150;
9420
9692
  const frameHeight = 150;
9421
- const frameLeft = Math.min(Math.random() * canvas.width, canvas.width - frameWidth - 50);
9422
- 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);
9423
9695
 
9424
9696
  // Create FrameShape - Group-based container with label, clipPath, edit mode support
9425
9697
  const frame = createFrameShape({
@@ -9437,11 +9709,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
9437
9709
  strokeWidth: 3
9438
9710
  });
9439
9711
 
9440
- canvas.add(frame);
9712
+ canvas!.add(frame);
9441
9713
  // Frames always sit at the lowest z-index so all other objects render above them
9442
- canvas.sendObjectToBack(frame);
9443
- canvas.setActiveObject(frame);
9444
- canvas.requestRenderAll();
9714
+ canvas!.sendObjectToBack(frame);
9715
+ canvas!.setActiveObject(frame);
9716
+ canvas!.requestRenderAll();
9445
9717
 
9446
9718
  canvasLog('FrameShape added', { frame });
9447
9719
  }
@@ -11903,11 +12175,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
11903
12175
  width: 300, height: 200,
11904
12176
  });
11905
12177
  (placeholder as any)._objectId = `img_paste_${Date.now()}`;
11906
- canvas.add(placeholder);
11907
- canvas.setActiveObject(placeholder);
12178
+ canvas!.add(placeholder);
12179
+ canvas!.setActiveObject(placeholder);
11908
12180
  selectedObject = placeholder;
11909
12181
  replacePlaceholderWithImage(placeholder, dataUrl, 'pasted-image.png', false);
11910
- canvas.requestRenderAll();
12182
+ canvas!.requestRenderAll();
11911
12183
  takeHistorySnapshot();
11912
12184
  clipboard = null;
11913
12185
  clipboardSourceObject = null;
@@ -11940,6 +12212,31 @@ function checkAndAddNewShapeToFrame(shape: any) {
11940
12212
  max-w-[calc(100%-1rem)] w-11/12
11941
12213
  -->
11942
12214
 
11943
- <style>/*! tailwindcss v4.1.18 | MIT License | https://tailwindcss.com */
11944
- 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
+ }
11945
12242
  </style>