@widgetic/canvas 0.5.9 → 0.5.10

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.
@@ -38,17 +38,21 @@
38
38
  // normalizes it when creating a Path object — this ensures arc ('A') and other
39
39
  // complex commands that get converted to bezier curves still match after a
40
40
  // save/load round-trip.
41
- const _shapeLibraryFingerprints = (() => {
42
- const map = new Map<string, string>();
43
- SHAPE_LIBRARY.forEach((shapeDef) => {
44
- try {
45
- const parsed = (fabricUtil as any).parsePath(shapeDef.pathData);
46
- const simplified = (fabricUtil as any).makePathSimpler?.(parsed) ?? parsed;
47
- if (simplified) map.set((fabricUtil as any).joinPath(simplified), shapeDef.key);
48
- } catch { /* ignore */ }
49
- });
50
- return map;
51
- })();
41
+ // Lazily evaluated to avoid blocking the main thread during module load.
42
+ let _shapeLibraryFingerprints: Map<string, string> | null = null;
43
+ function getShapeLibraryFingerprints(): Map<string, string> {
44
+ if (!_shapeLibraryFingerprints) {
45
+ _shapeLibraryFingerprints = new Map<string, string>();
46
+ SHAPE_LIBRARY.forEach((shapeDef) => {
47
+ try {
48
+ const parsed = (fabricUtil as any).parsePath(shapeDef.pathData);
49
+ const simplified = (fabricUtil as any).makePathSimpler?.(parsed) ?? parsed;
50
+ if (simplified) _shapeLibraryFingerprints.set((fabricUtil as any).joinPath(simplified), shapeDef.key);
51
+ } catch { /* ignore */ }
52
+ });
53
+ }
54
+ return _shapeLibraryFingerprints;
55
+ }
52
56
 
53
57
  // ── Textbox prototype patch: fix drawBorders for text padding inside groups/frames ──
54
58
  // Fabric's drawBorders uses raw this.width/this.height in the group path
@@ -159,6 +163,10 @@
159
163
  /** When true and advanced is on, Frame/Image/Video stay on the toolbar. Default true. */
160
164
  export let mediaBtsOnBar: boolean = true;
161
165
 
166
+ // Initial canvas data to deserialize immediately upon Fabric initialization
167
+ // Avoids flashing empty canvas and double-mount cycles.
168
+ export let initialData: string | null = null;
169
+
162
170
  // Callback fired once when Fabric canvas is fully initialized and ready
163
171
  export let onReady: (() => void) | null = null;
164
172
 
@@ -191,6 +199,9 @@
191
199
  // Fires frequently — implement lightweight (e.g. set a boolean flag only).
192
200
  export let onCanvasDirty: (() => void) | null = null;
193
201
 
202
+ // Callback fired when the user intentionally clears all canvas objects
203
+ export let onCanvasCleared: (() => void) | null = null;
204
+
194
205
  // Callback: fires when user clicks "Convert to Widget" on any object in PropsPanel.
195
206
  // Widget-creator handles the API call and links the resulting widget ID back.
196
207
  export let onConvertToWidget: ((data: WidgetConversionPayload) => void) | null = null;
@@ -815,7 +826,7 @@
815
826
  const obj = selectedObject;
816
827
  const isFrame = isFrameShape(obj);
817
828
  const children = isFrame ? getFrameChildren(obj) : [];
818
- const bounds = obj.getBoundingRect();
829
+ const bounds = obj.getBoundingRect(true);
819
830
  const isMultiSelection =
820
831
  obj.type === 'activeSelection' || obj.type === 'activeselection';
821
832
 
@@ -1003,10 +1014,10 @@
1003
1014
  const isFrame = obj ? isFrameShape(obj) : false;
1004
1015
  const bounds = pendingConversion?.bounds ??
1005
1016
  (obj
1006
- ? obj.getBoundingRect()
1017
+ ? obj.getBoundingRect(true)
1007
1018
  : (() => {
1008
1019
  const a = canvas.getActiveObject() as any;
1009
- return a ? a.getBoundingRect() : { left: 0, top: 0, width: 200, height: 200 };
1020
+ return a ? a.getBoundingRect(true) : { left: 0, top: 0, width: 200, height: 200 };
1010
1021
  })());
1011
1022
 
1012
1023
  // Preserve original visual properties before removing
@@ -1145,6 +1156,66 @@
1145
1156
  return false;
1146
1157
  }
1147
1158
 
1159
+ function objectSceneToScreenRect(obj: any): {
1160
+ left: number;
1161
+ top: number;
1162
+ width: number;
1163
+ height: number;
1164
+ viewportLeft: number;
1165
+ viewportTop: number;
1166
+ viewportWidth: number;
1167
+ viewportHeight: number;
1168
+ } | null {
1169
+ if (!canvas || !canvasEl || !obj) return null;
1170
+ try {
1171
+ obj.setCoords?.();
1172
+ } catch { /* ignore */ }
1173
+ const canvasRect = canvasEl.getBoundingClientRect();
1174
+ const o = obj.oCoords;
1175
+ if (o?.tl && o?.tr && o?.br && o?.bl) {
1176
+ const xs = [o.tl.x, o.tr.x, o.br.x, o.bl.x];
1177
+ const ys = [o.tl.y, o.tr.y, o.br.y, o.bl.y];
1178
+ const vpLeft = Math.min(...xs);
1179
+ const vpTop = Math.min(...ys);
1180
+ return {
1181
+ left: canvasRect.left + vpLeft,
1182
+ top: canvasRect.top + vpTop,
1183
+ width: Math.max(...xs) - vpLeft,
1184
+ height: Math.max(...ys) - vpTop,
1185
+ viewportLeft: canvasRect.left,
1186
+ viewportTop: canvasRect.top,
1187
+ viewportWidth: canvasRect.width,
1188
+ viewportHeight: canvasRect.height,
1189
+ };
1190
+ }
1191
+ const bbox = obj.getBoundingRect();
1192
+ const vpt = canvas.viewportTransform;
1193
+ const transformScene = (x: number, y: number) => {
1194
+ if (!vpt) return { x, y };
1195
+ return fabricUtil.transformPoint(new FabricPoint(x, y), vpt);
1196
+ };
1197
+ const corners = [
1198
+ transformScene(bbox.left, bbox.top),
1199
+ transformScene(bbox.left + bbox.width, bbox.top),
1200
+ transformScene(bbox.left + bbox.width, bbox.top + bbox.height),
1201
+ transformScene(bbox.left, bbox.top + bbox.height),
1202
+ ];
1203
+ const xs = corners.map((p) => p.x);
1204
+ const ys = corners.map((p) => p.y);
1205
+ const vpLeft = Math.min(...xs);
1206
+ const vpTop = Math.min(...ys);
1207
+ return {
1208
+ left: canvasRect.left + vpLeft,
1209
+ top: canvasRect.top + vpTop,
1210
+ width: Math.max(...xs) - vpLeft,
1211
+ height: Math.max(...ys) - vpTop,
1212
+ viewportLeft: canvasRect.left,
1213
+ viewportTop: canvasRect.top,
1214
+ viewportWidth: canvasRect.width,
1215
+ viewportHeight: canvasRect.height,
1216
+ };
1217
+ }
1218
+
1148
1219
  /**
1149
1220
  * Screen-space box of a widget shape plus the canvas element viewport.
1150
1221
  * Used to park Widget Details left/right of the shape.
@@ -1165,18 +1236,7 @@
1165
1236
  canvasLog('Canvas: getWidgetShapeScreenRect — no shape for', widgetId);
1166
1237
  return null;
1167
1238
  }
1168
- const bbox = obj.getBoundingRect();
1169
- const canvasRect = canvasEl.getBoundingClientRect();
1170
- return {
1171
- left: canvasRect.left + bbox.left,
1172
- top: canvasRect.top + bbox.top,
1173
- width: bbox.width,
1174
- height: bbox.height,
1175
- viewportLeft: canvasRect.left,
1176
- viewportTop: canvasRect.top,
1177
- viewportWidth: canvasRect.width,
1178
- viewportHeight: canvasRect.height,
1179
- };
1239
+ return objectSceneToScreenRect(obj);
1180
1240
  }
1181
1241
 
1182
1242
  /** Screen-space box for any canvas object id (convert drafts use the grouped sketch). */
@@ -1196,18 +1256,7 @@
1196
1256
  canvasLog('Canvas: getObjectScreenRect — no object for', objectId);
1197
1257
  return null;
1198
1258
  }
1199
- const bbox = obj.getBoundingRect();
1200
- const canvasRect = canvasEl.getBoundingClientRect();
1201
- return {
1202
- left: canvasRect.left + bbox.left,
1203
- top: canvasRect.top + bbox.top,
1204
- width: bbox.width,
1205
- height: bbox.height,
1206
- viewportLeft: canvasRect.left,
1207
- viewportTop: canvasRect.top,
1208
- viewportWidth: canvasRect.width,
1209
- viewportHeight: canvasRect.height,
1210
- };
1259
+ return objectSceneToScreenRect(obj);
1211
1260
  }
1212
1261
 
1213
1262
  /**
@@ -1483,7 +1532,7 @@
1483
1532
  * This section contains the lifecycle methods for the component.
1484
1533
  * They are used to initialize the canvas and the tools.
1485
1534
  * */
1486
- onMount(() => {
1535
+ onMount(async () => {
1487
1536
  const initializationLogContext = 'Canvas initialization';
1488
1537
  canvasLog(initializationLogContext, { MountedWidth: canvasEl?.clientWidth, MountedHeight: canvasEl?.clientHeight });
1489
1538
 
@@ -1554,16 +1603,20 @@
1554
1603
 
1555
1604
  // Inject a style element at runtime for retina-aware cursor using image-set.
1556
1605
  // Done via JS (not Svelte style block) to bypass PostCSS/Tailwind preprocessing.
1557
- var cursorStyleEl = document.createElement('style');
1558
- var cssUrl1x = "url('data:image/svg+xml," + rotSvgBase1x + "') 10 10, crosshair !important";
1559
- var cssImageSet = "-webkit-image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1560
- var cssImageSetStd = "image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1561
- cursorStyleEl.textContent = '.fabric-rotate-cursor { '
1562
- + 'cursor: ' + cssUrl1x + '; '
1563
- + 'cursor: ' + cssImageSet + '; '
1564
- + 'cursor: ' + cssImageSetStd + '; '
1565
- + '}';
1566
- document.head.appendChild(cursorStyleEl);
1606
+ const ROTATE_CURSOR_STYLE_ID = 'fabric-rotate-cursor-style';
1607
+ if (!document.getElementById(ROTATE_CURSOR_STYLE_ID)) {
1608
+ var cursorStyleEl = document.createElement('style');
1609
+ cursorStyleEl.id = ROTATE_CURSOR_STYLE_ID;
1610
+ var cssUrl1x = "url('data:image/svg+xml," + rotSvgBase1x + "') 10 10, crosshair !important";
1611
+ var cssImageSet = "-webkit-image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1612
+ var cssImageSetStd = "image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1613
+ cursorStyleEl.textContent = '.fabric-rotate-cursor { '
1614
+ + 'cursor: ' + cssUrl1x + '; '
1615
+ + 'cursor: ' + cssImageSet + '; '
1616
+ + 'cursor: ' + cssImageSetStd + '; '
1617
+ + '}';
1618
+ document.head.appendChild(cursorStyleEl);
1619
+ }
1567
1620
 
1568
1621
  // Track rotation state for cursor class management
1569
1622
  let isRotating = false;
@@ -2344,6 +2397,10 @@
2344
2397
  // Skip internal frame background rects
2345
2398
  if (obj._isFrameBackground) return;
2346
2399
 
2400
+ // When restoring history or loading JSON, reviver handles restoration.
2401
+ // Avoid redundant re-checking of all objects during batch load.
2402
+ if (isRestoringHistory) return;
2403
+
2347
2404
  // Re-apply frame custom render for frames arriving via JSON load.
2348
2405
  // Group.fromObject creates plain Groups — our custom render/hitTest must be
2349
2406
  // reapplied so the label and border-only click detection work correctly.
@@ -2403,7 +2460,7 @@
2403
2460
  ) {
2404
2461
  try {
2405
2462
  const fingerprint = (fabricUtil as any).joinPath((obj as any).path);
2406
- const matchedKey = _shapeLibraryFingerprints.get(fingerprint);
2463
+ const matchedKey = getShapeLibraryFingerprints().get(fingerprint);
2407
2464
  if (matchedKey) {
2408
2465
  const shapeDef = getShapeByKey(matchedKey);
2409
2466
  if (shapeDef) {
@@ -5323,10 +5380,10 @@
5323
5380
  const files = e.dataTransfer?.files;
5324
5381
  if (!files || files.length === 0) return;
5325
5382
 
5326
- // Get drop position relative to canvas
5327
- const rect = canvasWrapper.getBoundingClientRect();
5328
- const dropX = e.clientX - rect.left;
5329
- const dropY = e.clientY - rect.top;
5383
+ // Get drop position in canvas scene coordinates (handles pan & zoom)
5384
+ const scenePoint = canvas.getScenePoint(e);
5385
+ const dropX = scenePoint.x;
5386
+ const dropY = scenePoint.y;
5330
5387
 
5331
5388
  // Process each dropped file
5332
5389
  Array.from(files).forEach((file) => {
@@ -5540,11 +5597,23 @@
5540
5597
  // only fires after real content modifications. A debounced timer there
5541
5598
  // calls onAutoSave after autosaveDelayMs of inactivity.
5542
5599
 
5543
- // Set canvas ready state
5544
- canvasLoadPhase = 'ready';
5545
- // Take the initial "empty canvas" snapshot so undo can return to it
5546
- // Use silent snapshot — don't mark dirty or trigger autosave for the initial state
5547
- takeHistorySnapshot(true);
5600
+ // Set canvas ready state and initialize history.
5601
+ // If initialData was provided by host, load it immediately to avoid flashing empty canvas.
5602
+ if (initialData) {
5603
+ try {
5604
+ await loadCanvas(initialData);
5605
+ canvasLog(`${initializationLogContext}: Initial data loaded directly on mount`);
5606
+ } catch (loadErr) {
5607
+ console.error(`${initializationLogContext}: Failed to load initialData on mount`, loadErr);
5608
+ canvasLoadPhase = 'ready';
5609
+ takeHistorySnapshot(true);
5610
+ }
5611
+ } else {
5612
+ canvasLoadPhase = 'ready';
5613
+ // Take the initial "empty canvas" snapshot so undo can return to it
5614
+ // Use silent snapshot — don't mark dirty or trigger autosave for the initial state
5615
+ takeHistorySnapshot(true);
5616
+ }
5548
5617
  onReady?.();
5549
5618
  } catch (fabricInitializationError) {
5550
5619
  console.error(`${initializationLogContext}: Failed to create Fabric canvas`, fabricInitializationError);
@@ -5701,18 +5770,17 @@
5701
5770
  }
5702
5771
  });
5703
5772
 
5704
- function resizeObserver(node) {
5773
+ function resizeObserver(node: HTMLElement) {
5705
5774
  const observer = new ResizeObserver(entries => {
5775
+ if (!canvas) return;
5706
5776
  const entry = entries[0];
5777
+ if (!entry) return;
5707
5778
  const { width: w, height: h } = entry.contentRect;
5708
-
5709
- // Update component state
5710
- // width = w;
5711
- // height = h;
5779
+ if (w <= 0 || h <= 0) return;
5712
5780
 
5713
5781
  // Update canvas dimensions
5714
5782
  canvas.setDimensions({ width: w, height: h });
5715
- canvas.renderAll();
5783
+ canvas.requestRenderAll();
5716
5784
  });
5717
5785
  observer.observe(node);
5718
5786
 
@@ -8585,6 +8653,37 @@ function checkAndAddNewShapeToFrame(shape: any) {
8585
8653
 
8586
8654
  // ── History: capture / restore ───────────────────────────────────────────
8587
8655
 
8656
+ /**
8657
+ * Safely serializes the canvas to a plain JS object via toJSON.
8658
+ * If an ActiveSelection exists, temporarily discards it so all child objects
8659
+ * have their true canvas-absolute scene coordinates restored before serialization,
8660
+ * then re-creates the ActiveSelection so the user's selection is not lost.
8661
+ */
8662
+ function safelySerializeCanvas(canvasInstance: Canvas, propertiesToInclude: string[]): any {
8663
+ const activeObj = canvasInstance.getActiveObject();
8664
+ const isMultiSelection = !!(activeObj && (
8665
+ activeObj.type === 'activeselection' ||
8666
+ activeObj.type === 'activeSelection'
8667
+ ));
8668
+ const selectedObjects = isMultiSelection ? (activeObj as any).getObjects().slice() : null;
8669
+
8670
+ if (isMultiSelection) {
8671
+ canvasInstance.discardActiveObject();
8672
+ }
8673
+
8674
+ let json: any = null;
8675
+ try {
8676
+ json = canvasInstance.toJSON(propertiesToInclude);
8677
+ } finally {
8678
+ if (isMultiSelection && selectedObjects && selectedObjects.length > 0) {
8679
+ const restoredSelection = new ActiveSelection(selectedObjects, { canvas: canvasInstance });
8680
+ canvasInstance.setActiveObject(restoredSelection);
8681
+ }
8682
+ }
8683
+
8684
+ return json;
8685
+ }
8686
+
8588
8687
  /**
8589
8688
  * Capture the current canvas object state as a JSON string.
8590
8689
  * Viewport (pan/zoom) is intentionally excluded — undo/redo only affects
@@ -8593,7 +8692,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8593
8692
  function captureHistorySnapshot(): string | null {
8594
8693
  if (!canvas) return null;
8595
8694
  try {
8596
- const json = canvas.toJSON(CANVAS_CUSTOM_PROPS);
8695
+ const json = safelySerializeCanvas(canvas, CANVAS_CUSTOM_PROPS);
8597
8696
  return JSON.stringify(json);
8598
8697
  } catch (err) {
8599
8698
  console.error('Canvas: captureHistorySnapshot failed', err);
@@ -8736,6 +8835,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8736
8835
  historyIndex--;
8737
8836
  canvasLog('Canvas: undo → history index', historyIndex);
8738
8837
  await restoreHistorySnapshot(historyStack[historyIndex]);
8838
+ _hasUnsavedChanges = true;
8839
+ onCanvasDirty?.();
8840
+ scheduleAutoSave();
8739
8841
  }
8740
8842
 
8741
8843
  /** Redo the previously undone action. No-op if at the newest state. */
@@ -8744,6 +8846,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8744
8846
  historyIndex++;
8745
8847
  canvasLog('Canvas: redo → history index', historyIndex);
8746
8848
  await restoreHistorySnapshot(historyStack[historyIndex]);
8849
+ _hasUnsavedChanges = true;
8850
+ onCanvasDirty?.();
8851
+ scheduleAutoSave();
8747
8852
  }
8748
8853
 
8749
8854
  /** Serialize the current canvas state to a JSON string */
@@ -8757,7 +8862,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8757
8862
  return null;
8758
8863
  }
8759
8864
  try {
8760
- const canvasJson = canvas.toJSON(CANVAS_CUSTOM_PROPS);
8865
+ const canvasJson = safelySerializeCanvas(canvas, CANVAS_CUSTOM_PROPS);
8761
8866
  // Diagnostic: log frame structure at save time to detect corruption
8762
8867
  (canvasJson.objects || []).forEach((obj: any) => {
8763
8868
  if (obj._isFrame || obj._customType === 'frame' || obj.type === 'FrameShape') {
@@ -8849,35 +8954,18 @@ function checkAndAddNewShapeToFrame(shape: any) {
8849
8954
 
8850
8955
  await canvas.loadFromJSON(canvasJson, reviver);
8851
8956
 
8852
- // Belt-and-suspenders: also walk all objects after load to catch any
8853
- // that the reviver may have missed (e.g. due to async timing).
8957
+ // Light pass: ensure any images without loaded elements are reloaded
8854
8958
  const allObjects = canvas.getObjects();
8855
- const restoreObject = (obj: any) => {
8856
- if (isFrameShape(obj)) {
8857
- reapplyFrameRender(obj);
8858
- getFrameChildren(obj).forEach(restoreObject);
8859
- } else if (obj._customType === 'image' || obj._hasImage || obj._imageUrl) {
8860
- upgradeToImageShape(obj);
8959
+ const checkUnloadedImages = (obj: any) => {
8960
+ if (obj._customType === 'image' || obj._hasImage || obj._imageUrl) {
8861
8961
  if (obj._imageUrl && !obj._imageElement) {
8862
- const img = new Image();
8863
- img.crossOrigin = 'anonymous';
8864
- img.onload = () => {
8865
- obj._imageElement = img;
8866
- obj._hasImage = true;
8867
- obj.dirty = true;
8868
- canvas?.requestRenderAll();
8869
- };
8870
- img.onerror = () => {
8871
- canvasWarn('Canvas: loadCanvas — failed to reload image (post-pass)', obj._imageUrl?.substring(0, 60));
8872
- };
8873
- img.src = obj._imageUrl;
8962
+ ImageShape.reloadImage(obj);
8874
8963
  }
8875
- } else if (String(obj.type || '').toLowerCase() === 'group') {
8876
- applyInteractiveGroupFlags(obj);
8877
- (obj.getObjects?.() || []).forEach(restoreObject);
8964
+ } else if (String(obj.type || '').toLowerCase() === 'group' || isFrameShape(obj)) {
8965
+ (obj.getObjects?.() || []).forEach(checkUnloadedImages);
8878
8966
  }
8879
8967
  };
8880
- allObjects.forEach(restoreObject);
8968
+ allObjects.forEach(checkUnloadedImages);
8881
8969
 
8882
8970
  // ── Orphan-repair pass ──────────────────────────────────────────────
8883
8971
  // Old/corrupted saves may have frame children at canvas level instead
@@ -8914,16 +9002,19 @@ function checkAndAddNewShapeToFrame(shape: any) {
8914
9002
  const spatialOrphans = canvas.getObjects().filter((obj: any) =>
8915
9003
  !isFrameShape(obj) &&
8916
9004
  !(obj as any)._isFrameBackground &&
9005
+ !(obj as any)._parentFrameId &&
8917
9006
  !obj.group && // not already inside any group
8918
9007
  String(obj.type || '').toLowerCase() !== 'group'
8919
9008
  );
8920
- for (const obj of spatialOrphans) {
8921
- const center = obj.getCenterPoint();
8922
- for (const frame of framesForSpatialRepair) {
8923
- if (isPointInsideFrame(frame, center)) {
8924
- canvasWarn('Canvas: loadCanvas — spatial repair: re-attaching', (obj as any).type, 'to frame', frame._labelText);
8925
- addObjectToFrame(frame, obj, canvas);
8926
- break;
9009
+ if (spatialOrphans.length > 0) {
9010
+ for (const obj of spatialOrphans) {
9011
+ const center = obj.getCenterPoint();
9012
+ for (const frame of framesForSpatialRepair) {
9013
+ if (isPointInsideFrame(frame, center)) {
9014
+ canvasWarn('Canvas: loadCanvas — spatial repair: re-attaching', (obj as any).type, 'to frame', frame._labelText);
9015
+ addObjectToFrame(frame, obj, canvas);
9016
+ break;
9017
+ }
8927
9018
  }
8928
9019
  }
8929
9020
  }
@@ -8951,11 +9042,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
8951
9042
 
8952
9043
  // Reset history after an external load so undo can't go back to
8953
9044
  // the previous canvas state and the loaded state becomes the new "initial".
8954
- historyStack = [];
8955
- historyIndex = -1;
9045
+ // Seed historyStack directly with the loaded state to avoid re-serializing via canvas.toJSON().
9046
+ const initialSnapshot = JSON.stringify(canvasJson);
9047
+ historyStack = [initialSnapshot];
9048
+ historyIndex = 0;
8956
9049
  isRestoringHistory = false;
8957
9050
  canvasLoadPhase = 'ready';
8958
- takeHistorySnapshot(true);
8959
9051
  } catch (err) {
8960
9052
  console.error('Canvas: loadCanvas failed', err);
8961
9053
  isRestoringHistory = false;
@@ -8980,7 +9072,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
8980
9072
 
8981
9073
  // request a render all
8982
9074
  canvas.requestRenderAll();
8983
- takeHistorySnapshot(true);
9075
+ takeHistorySnapshot();
9076
+ onCanvasCleared?.();
8984
9077
 
8985
9078
  // log the clearing
8986
9079
  canvasLog('Clear all objects created');
@@ -11378,8 +11471,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11378
11471
  <div class="{className ? className + ' ' : ''}canvas-container relative w-full h-full overflow-hidden {showContainerFrame ? 'border-2 border-gray-300 rounded-md' : 'border-0 rounded-none'}" style={style} use:resizeObserver>
11379
11472
 
11380
11473
  <!-- Pan/Zoom Panel: Position configurable via panZoomPosition prop -->
11381
- {#if !isCanvasLoading}
11382
- <div class="canvas-pan-zoom-overlay {getPanZoomPositionClass(panZoomPosition)}">
11474
+ <div class="canvas-pan-zoom-overlay {getPanZoomPositionClass(panZoomPosition)} {isCanvasLoading ? 'pointer-events-none opacity-60 transition-opacity duration-200' : 'transition-opacity duration-200'}">
11383
11475
  <PanZoomPanel
11384
11476
  {zoomLevel}
11385
11477
  isPanActive={activeTool === 'pan'}
@@ -11399,13 +11491,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
11399
11491
  onSave={saveNow}
11400
11492
  />
11401
11493
  </div>
11402
- {/if}
11403
11494
 
11404
11495
  <!-- Canvas -->
11405
11496
  <canvas class="canvas-el" bind:this={canvasEl}></canvas>
11406
11497
 
11407
11498
  {#if isCanvasLoading}
11408
- <div class="canvas-loader" style="position:absolute;inset:0;z-index:10;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.85);backdrop-filter:blur(4px);">
11499
+ <div class="canvas-loader" style="position:absolute;inset:0;z-index:30;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.85);backdrop-filter:blur(4px);">
11409
11500
  <div style="display:flex;flex-direction:column;align-items:center;gap:12px;">
11410
11501
  <div class="canvas-loader-spinner"></div>
11411
11502
  <span style="font-size:14px;font-weight:500;color:#6b7280;letter-spacing:0.02em;">Loading canvas…</span>
@@ -11421,8 +11512,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11421
11512
  {/if}
11422
11513
 
11423
11514
  <!-- Toolbar: Positioned at the bottom of the canvas -->
11424
- {#if !isCanvasLoading}
11425
- <CanvasToolbar class="absolute bottom-1 left-1/2 -translate-x-1/2 max-w-[calc(100%-1rem)]"
11515
+ <CanvasToolbar class="absolute bottom-1 left-1/2 -translate-x-1/2 max-w-[calc(100%-1rem)] {isCanvasLoading ? 'pointer-events-none opacity-60 transition-opacity duration-200' : 'transition-opacity duration-200'}"
11426
11516
  {activeTool}
11427
11517
  {onSelectSelectTool}
11428
11518
  {onSelectEraseTool}
@@ -11460,8 +11550,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11460
11550
  {onSelectLibraryShapeTool}
11461
11551
  {advancedFeatures}
11462
11552
  {mediaBtsOnBar}
11463
- />
11464
- {/if}
11553
+ />
11465
11554
 
11466
11555
  <!-- Props Panel: Only visible when an object is selected -->
11467
11556
  {#if selectedObject}
@@ -24,6 +24,7 @@ declare const __propDef: {
24
24
  wireframeMode?: boolean;
25
25
  advancedFeatures?: boolean;
26
26
  /** When true and advanced is on, Frame/Image/Video stay on the toolbar. Default true. */ mediaBtsOnBar?: boolean;
27
+ initialData?: string | null;
27
28
  onReady?: (() => void) | null;
28
29
  isExternalDataLoading?: boolean;
29
30
  onBeforeUnmount?: ((json: string | null) => void) | null;
@@ -31,6 +32,7 @@ declare const __propDef: {
31
32
  autosaveDelayMs?: number;
32
33
  showSaveButton?: boolean;
33
34
  onCanvasDirty?: (() => void) | null;
35
+ onCanvasCleared?: (() => void) | null;
34
36
  onConvertToWidget?: ((data: WidgetConversionPayload) => void) | null;
35
37
  onWidgetImageClick?: ((widgetId: string) => void) | null;
36
38
  onNonWidgetSelected?: (() => void) | null;
@@ -64,7 +64,7 @@
64
64
 
65
65
  function toggleMinimized() {
66
66
  isMinimized = !isMinimized;
67
- console.log('[PanZoomPanel] minimized:', isMinimized);
67
+ // console.log('[PanZoomPanel] minimized:', isMinimized);
68
68
  }
69
69
  </script>
70
70
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/canvas",
3
- "version": "0.5.9",
3
+ "version": "0.5.10",
4
4
  "type": "module",
5
5
  "svelte": "./dist/index.js",
6
6
  "module": "./dist/index.js",