@widgetic/canvas 0.5.9 → 0.5.11

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;
@@ -222,6 +233,9 @@
222
233
  /** Host persists canvases.primary_widget_id after Canvas paints the red stroke. */
223
234
  export let onSetPrimaryWidget: ((widgetId: string) => void) | null = null;
224
235
 
236
+ /** Throttled paint hook for HTML overlays (e.g. live WidgetShape iframes). */
237
+ export let onAfterRender: (() => void) | null = null;
238
+
225
239
  // Widget name resolver: given a widgetId, returns the widget name (or null).
226
240
  // Used by PropsPanel to display the linked widget's name.
227
241
  export let getWidgetName: ((widgetId: string) => string | null) | null = null;
@@ -815,7 +829,7 @@
815
829
  const obj = selectedObject;
816
830
  const isFrame = isFrameShape(obj);
817
831
  const children = isFrame ? getFrameChildren(obj) : [];
818
- const bounds = obj.getBoundingRect();
832
+ const bounds = obj.getBoundingRect(true);
819
833
  const isMultiSelection =
820
834
  obj.type === 'activeSelection' || obj.type === 'activeselection';
821
835
 
@@ -1003,10 +1017,10 @@
1003
1017
  const isFrame = obj ? isFrameShape(obj) : false;
1004
1018
  const bounds = pendingConversion?.bounds ??
1005
1019
  (obj
1006
- ? obj.getBoundingRect()
1020
+ ? obj.getBoundingRect(true)
1007
1021
  : (() => {
1008
1022
  const a = canvas.getActiveObject() as any;
1009
- return a ? a.getBoundingRect() : { left: 0, top: 0, width: 200, height: 200 };
1023
+ return a ? a.getBoundingRect(true) : { left: 0, top: 0, width: 200, height: 200 };
1010
1024
  })());
1011
1025
 
1012
1026
  // Preserve original visual properties before removing
@@ -1055,6 +1069,7 @@
1055
1069
  // Upgrade ImageShape → WidgetShape (swaps prototype, sets _isWidgetImage)
1056
1070
  upgradeToWidgetShape(widgetImage);
1057
1071
  clearWidgetShapeDefaultBorder(widgetImage);
1072
+ lockWidgetShapeBodyDrag(widgetImage);
1058
1073
 
1059
1074
  const newObjectId = `widget_img_${Date.now()}`;
1060
1075
  widgetImage._objectId = newObjectId;
@@ -1145,6 +1160,100 @@
1145
1160
  return false;
1146
1161
  }
1147
1162
 
1163
+ function objectSceneToScreenRect(obj: any): {
1164
+ left: number;
1165
+ top: number;
1166
+ width: number;
1167
+ height: number;
1168
+ viewportLeft: number;
1169
+ viewportTop: number;
1170
+ viewportWidth: number;
1171
+ viewportHeight: number;
1172
+ } | null {
1173
+ if (!canvas || !canvasEl || !obj) return null;
1174
+ try {
1175
+ obj.setCoords?.();
1176
+ } catch { /* ignore */ }
1177
+ const canvasRect = canvasEl.getBoundingClientRect();
1178
+ const o = obj.oCoords;
1179
+ if (o?.tl && o?.tr && o?.br && o?.bl) {
1180
+ const xs = [o.tl.x, o.tr.x, o.br.x, o.bl.x];
1181
+ const ys = [o.tl.y, o.tr.y, o.br.y, o.bl.y];
1182
+ const vpLeft = Math.min(...xs);
1183
+ const vpTop = Math.min(...ys);
1184
+ return {
1185
+ left: canvasRect.left + vpLeft,
1186
+ top: canvasRect.top + vpTop,
1187
+ width: Math.max(...xs) - vpLeft,
1188
+ height: Math.max(...ys) - vpTop,
1189
+ viewportLeft: canvasRect.left,
1190
+ viewportTop: canvasRect.top,
1191
+ viewportWidth: canvasRect.width,
1192
+ viewportHeight: canvasRect.height,
1193
+ };
1194
+ }
1195
+ const bbox = obj.getBoundingRect();
1196
+ const vpt = canvas.viewportTransform;
1197
+ const transformScene = (x: number, y: number) => {
1198
+ if (!vpt) return { x, y };
1199
+ return fabricUtil.transformPoint(new FabricPoint(x, y), vpt);
1200
+ };
1201
+ const corners = [
1202
+ transformScene(bbox.left, bbox.top),
1203
+ transformScene(bbox.left + bbox.width, bbox.top),
1204
+ transformScene(bbox.left + bbox.width, bbox.top + bbox.height),
1205
+ transformScene(bbox.left, bbox.top + bbox.height),
1206
+ ];
1207
+ const xs = corners.map((p) => p.x);
1208
+ const ys = corners.map((p) => p.y);
1209
+ const vpLeft = Math.min(...xs);
1210
+ const vpTop = Math.min(...ys);
1211
+ return {
1212
+ left: canvasRect.left + vpLeft,
1213
+ top: canvasRect.top + vpTop,
1214
+ width: Math.max(...xs) - vpLeft,
1215
+ height: Math.max(...ys) - vpTop,
1216
+ viewportLeft: canvasRect.left,
1217
+ viewportTop: canvasRect.top,
1218
+ viewportWidth: canvasRect.width,
1219
+ viewportHeight: canvasRect.height,
1220
+ };
1221
+ }
1222
+
1223
+ /**
1224
+ * Screen-space boxes for every WidgetShape currently on the canvas.
1225
+ * Used by the host to sync live iframe overlays (W3).
1226
+ */
1227
+ export function listWidgetShapeScreenRects(): Array<{
1228
+ widgetId: string;
1229
+ left: number;
1230
+ top: number;
1231
+ width: number;
1232
+ height: number;
1233
+ }> {
1234
+ if (!canvas || !canvasEl) return [];
1235
+ const results: Array<{
1236
+ widgetId: string;
1237
+ left: number;
1238
+ top: number;
1239
+ width: number;
1240
+ height: number;
1241
+ }> = [];
1242
+ for (const obj of canvas.getObjects() as any[]) {
1243
+ if (!obj?._isWidgetImage || !obj?._widgetId || obj._widgetOrphaned) continue;
1244
+ const rect = objectSceneToScreenRect(obj);
1245
+ if (!rect || rect.width < 4 || rect.height < 4) continue;
1246
+ results.push({
1247
+ widgetId: String(obj._widgetId),
1248
+ left: rect.left,
1249
+ top: rect.top,
1250
+ width: rect.width,
1251
+ height: rect.height,
1252
+ });
1253
+ }
1254
+ return results;
1255
+ }
1256
+
1148
1257
  /**
1149
1258
  * Screen-space box of a widget shape plus the canvas element viewport.
1150
1259
  * Used to park Widget Details left/right of the shape.
@@ -1165,18 +1274,7 @@
1165
1274
  canvasLog('Canvas: getWidgetShapeScreenRect — no shape for', widgetId);
1166
1275
  return null;
1167
1276
  }
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
- };
1277
+ return objectSceneToScreenRect(obj);
1180
1278
  }
1181
1279
 
1182
1280
  /** Screen-space box for any canvas object id (convert drafts use the grouped sketch). */
@@ -1196,18 +1294,7 @@
1196
1294
  canvasLog('Canvas: getObjectScreenRect — no object for', objectId);
1197
1295
  return null;
1198
1296
  }
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
- };
1297
+ return objectSceneToScreenRect(obj);
1211
1298
  }
1212
1299
 
1213
1300
  /**
@@ -1269,6 +1356,7 @@
1269
1356
 
1270
1357
  upgradeToWidgetShape(placeholder);
1271
1358
  clearWidgetShapeDefaultBorder(placeholder);
1359
+ lockWidgetShapeBodyDrag(placeholder);
1272
1360
 
1273
1361
  const newObjectId = `widget_img_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1274
1362
  placeholder._objectId = newObjectId;
@@ -1483,7 +1571,7 @@
1483
1571
  * This section contains the lifecycle methods for the component.
1484
1572
  * They are used to initialize the canvas and the tools.
1485
1573
  * */
1486
- onMount(() => {
1574
+ onMount(async () => {
1487
1575
  const initializationLogContext = 'Canvas initialization';
1488
1576
  canvasLog(initializationLogContext, { MountedWidth: canvasEl?.clientWidth, MountedHeight: canvasEl?.clientHeight });
1489
1577
 
@@ -1554,16 +1642,20 @@
1554
1642
 
1555
1643
  // Inject a style element at runtime for retina-aware cursor using image-set.
1556
1644
  // 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);
1645
+ const ROTATE_CURSOR_STYLE_ID = 'fabric-rotate-cursor-style';
1646
+ if (!document.getElementById(ROTATE_CURSOR_STYLE_ID)) {
1647
+ var cursorStyleEl = document.createElement('style');
1648
+ cursorStyleEl.id = ROTATE_CURSOR_STYLE_ID;
1649
+ var cssUrl1x = "url('data:image/svg+xml," + rotSvgBase1x + "') 10 10, crosshair !important";
1650
+ var cssImageSet = "-webkit-image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1651
+ var cssImageSetStd = "image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1652
+ cursorStyleEl.textContent = '.fabric-rotate-cursor { '
1653
+ + 'cursor: ' + cssUrl1x + '; '
1654
+ + 'cursor: ' + cssImageSet + '; '
1655
+ + 'cursor: ' + cssImageSetStd + '; '
1656
+ + '}';
1657
+ document.head.appendChild(cursorStyleEl);
1658
+ }
1567
1659
 
1568
1660
  // Track rotation state for cursor class management
1569
1661
  let isRotating = false;
@@ -2344,6 +2436,10 @@
2344
2436
  // Skip internal frame background rects
2345
2437
  if (obj._isFrameBackground) return;
2346
2438
 
2439
+ // When restoring history or loading JSON, reviver handles restoration.
2440
+ // Avoid redundant re-checking of all objects during batch load.
2441
+ if (isRestoringHistory) return;
2442
+
2347
2443
  // Re-apply frame custom render for frames arriving via JSON load.
2348
2444
  // Group.fromObject creates plain Groups — our custom render/hitTest must be
2349
2445
  // reapplied so the label and border-only click detection work correctly.
@@ -2359,6 +2455,7 @@
2359
2455
  // Upgrade old Rect-based image placeholders to ImageShape (backward compat)
2360
2456
  upgradeToImageShape(obj);
2361
2457
  if ((obj as any)._isWidgetImage) {
2458
+ lockWidgetShapeBodyDrag(obj);
2362
2459
  if ((obj as any)._isPrimaryWidget) {
2363
2460
  obj.set({
2364
2461
  stroke: PRIMARY_WIDGET_STROKE,
@@ -2403,7 +2500,7 @@
2403
2500
  ) {
2404
2501
  try {
2405
2502
  const fingerprint = (fabricUtil as any).joinPath((obj as any).path);
2406
- const matchedKey = _shapeLibraryFingerprints.get(fingerprint);
2503
+ const matchedKey = getShapeLibraryFingerprints().get(fingerprint);
2407
2504
  if (matchedKey) {
2408
2505
  const shapeDef = getShapeByKey(matchedKey);
2409
2506
  if (shapeDef) {
@@ -4693,6 +4790,21 @@
4693
4790
  canvas.on('selection:created', handleSelectionCreated);
4694
4791
  canvas.on('selection:updated', handleSelectionUpdated);
4695
4792
  canvas.on('selection:cleared', handleSelectionCleared);
4793
+
4794
+ // Live HTML overlays (WidgetShape iframes) — one callback per animation frame max
4795
+ let afterRenderRaf = 0;
4796
+ canvas.on('after:render', () => {
4797
+ if (!onAfterRender) return;
4798
+ if (afterRenderRaf) return;
4799
+ afterRenderRaf = requestAnimationFrame(() => {
4800
+ afterRenderRaf = 0;
4801
+ try {
4802
+ onAfterRender?.();
4803
+ } catch (err) {
4804
+ canvasWarn('Canvas: onAfterRender failed', err);
4805
+ }
4806
+ });
4807
+ });
4696
4808
 
4697
4809
  // Double-click handler:
4698
4810
  // - Textbox: enter editing mode with all text selected
@@ -5323,10 +5435,10 @@
5323
5435
  const files = e.dataTransfer?.files;
5324
5436
  if (!files || files.length === 0) return;
5325
5437
 
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;
5438
+ // Get drop position in canvas scene coordinates (handles pan & zoom)
5439
+ const scenePoint = canvas.getScenePoint(e);
5440
+ const dropX = scenePoint.x;
5441
+ const dropY = scenePoint.y;
5330
5442
 
5331
5443
  // Process each dropped file
5332
5444
  Array.from(files).forEach((file) => {
@@ -5540,11 +5652,23 @@
5540
5652
  // only fires after real content modifications. A debounced timer there
5541
5653
  // calls onAutoSave after autosaveDelayMs of inactivity.
5542
5654
 
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);
5655
+ // Set canvas ready state and initialize history.
5656
+ // If initialData was provided by host, load it immediately to avoid flashing empty canvas.
5657
+ if (initialData) {
5658
+ try {
5659
+ await loadCanvas(initialData);
5660
+ canvasLog(`${initializationLogContext}: Initial data loaded directly on mount`);
5661
+ } catch (loadErr) {
5662
+ console.error(`${initializationLogContext}: Failed to load initialData on mount`, loadErr);
5663
+ canvasLoadPhase = 'ready';
5664
+ takeHistorySnapshot(true);
5665
+ }
5666
+ } else {
5667
+ canvasLoadPhase = 'ready';
5668
+ // Take the initial "empty canvas" snapshot so undo can return to it
5669
+ // Use silent snapshot — don't mark dirty or trigger autosave for the initial state
5670
+ takeHistorySnapshot(true);
5671
+ }
5548
5672
  onReady?.();
5549
5673
  } catch (fabricInitializationError) {
5550
5674
  console.error(`${initializationLogContext}: Failed to create Fabric canvas`, fabricInitializationError);
@@ -5701,18 +5825,17 @@
5701
5825
  }
5702
5826
  });
5703
5827
 
5704
- function resizeObserver(node) {
5828
+ function resizeObserver(node: HTMLElement) {
5705
5829
  const observer = new ResizeObserver(entries => {
5830
+ if (!canvas) return;
5706
5831
  const entry = entries[0];
5832
+ if (!entry) return;
5707
5833
  const { width: w, height: h } = entry.contentRect;
5708
-
5709
- // Update component state
5710
- // width = w;
5711
- // height = h;
5834
+ if (w <= 0 || h <= 0) return;
5712
5835
 
5713
5836
  // Update canvas dimensions
5714
5837
  canvas.setDimensions({ width: w, height: h });
5715
- canvas.renderAll();
5838
+ canvas.requestRenderAll();
5716
5839
  });
5717
5840
  observer.observe(node);
5718
5841
 
@@ -7488,6 +7611,56 @@ function checkAndAddNewShapeToFrame(shape: any) {
7488
7611
  obj.dirty = true;
7489
7612
  }
7490
7613
 
7614
+ /**
7615
+ * WidgetShapes move only via the HTML chrome drag bar (live iframe stays interactive).
7616
+ * Other shapes keep normal Fabric body-drag.
7617
+ */
7618
+ function lockWidgetShapeBodyDrag(obj: any): void {
7619
+ if (!obj?._isWidgetImage) return;
7620
+ obj.set({
7621
+ lockMovementX: true,
7622
+ lockMovementY: true,
7623
+ });
7624
+ obj.dirty = true;
7625
+ }
7626
+
7627
+ /** Translate a WidgetShape by screen-pixel delta (accounts for canvas zoom). */
7628
+ export function translateWidgetShapeByScreen(widgetId: string, dxScreen: number, dyScreen: number): boolean {
7629
+ if (!canvas || !widgetId) return false;
7630
+ const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId) as any;
7631
+ if (!obj) return false;
7632
+ const zoom = canvas.getZoom?.() || 1;
7633
+ const dx = dxScreen / zoom;
7634
+ const dy = dyScreen / zoom;
7635
+ // Temporarily unlock so Fabric applies left/top without fighting locks
7636
+ obj.set({
7637
+ lockMovementX: false,
7638
+ lockMovementY: false,
7639
+ left: (obj.left ?? 0) + dx,
7640
+ top: (obj.top ?? 0) + dy,
7641
+ });
7642
+ obj.setCoords?.();
7643
+ lockWidgetShapeBodyDrag(obj);
7644
+ canvas.requestRenderAll();
7645
+ return true;
7646
+ }
7647
+
7648
+ export function selectWidgetShapeById(widgetId: string): boolean {
7649
+ if (!canvas || !widgetId) return false;
7650
+ const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId);
7651
+ if (!obj) return false;
7652
+ canvas.setActiveObject(obj);
7653
+ canvas.requestRenderAll();
7654
+ return true;
7655
+ }
7656
+
7657
+ export function getSelectedWidgetShapeId(): string | null {
7658
+ if (!canvas) return null;
7659
+ const active = canvas.getActiveObject() as any;
7660
+ if (active?._isWidgetImage && active?._widgetId) return String(active._widgetId);
7661
+ return null;
7662
+ }
7663
+
7491
7664
  /**
7492
7665
  * Create an WidgetShape object (unified Rect that can display placeholder UI OR an image)
7493
7666
  * This is a custom Rect that:
@@ -8585,6 +8758,37 @@ function checkAndAddNewShapeToFrame(shape: any) {
8585
8758
 
8586
8759
  // ── History: capture / restore ───────────────────────────────────────────
8587
8760
 
8761
+ /**
8762
+ * Safely serializes the canvas to a plain JS object via toJSON.
8763
+ * If an ActiveSelection exists, temporarily discards it so all child objects
8764
+ * have their true canvas-absolute scene coordinates restored before serialization,
8765
+ * then re-creates the ActiveSelection so the user's selection is not lost.
8766
+ */
8767
+ function safelySerializeCanvas(canvasInstance: Canvas, propertiesToInclude: string[]): any {
8768
+ const activeObj = canvasInstance.getActiveObject();
8769
+ const isMultiSelection = !!(activeObj && (
8770
+ activeObj.type === 'activeselection' ||
8771
+ activeObj.type === 'activeSelection'
8772
+ ));
8773
+ const selectedObjects = isMultiSelection ? (activeObj as any).getObjects().slice() : null;
8774
+
8775
+ if (isMultiSelection) {
8776
+ canvasInstance.discardActiveObject();
8777
+ }
8778
+
8779
+ let json: any = null;
8780
+ try {
8781
+ json = canvasInstance.toJSON(propertiesToInclude);
8782
+ } finally {
8783
+ if (isMultiSelection && selectedObjects && selectedObjects.length > 0) {
8784
+ const restoredSelection = new ActiveSelection(selectedObjects, { canvas: canvasInstance });
8785
+ canvasInstance.setActiveObject(restoredSelection);
8786
+ }
8787
+ }
8788
+
8789
+ return json;
8790
+ }
8791
+
8588
8792
  /**
8589
8793
  * Capture the current canvas object state as a JSON string.
8590
8794
  * Viewport (pan/zoom) is intentionally excluded — undo/redo only affects
@@ -8593,7 +8797,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8593
8797
  function captureHistorySnapshot(): string | null {
8594
8798
  if (!canvas) return null;
8595
8799
  try {
8596
- const json = canvas.toJSON(CANVAS_CUSTOM_PROPS);
8800
+ const json = safelySerializeCanvas(canvas, CANVAS_CUSTOM_PROPS);
8597
8801
  return JSON.stringify(json);
8598
8802
  } catch (err) {
8599
8803
  console.error('Canvas: captureHistorySnapshot failed', err);
@@ -8736,6 +8940,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8736
8940
  historyIndex--;
8737
8941
  canvasLog('Canvas: undo → history index', historyIndex);
8738
8942
  await restoreHistorySnapshot(historyStack[historyIndex]);
8943
+ _hasUnsavedChanges = true;
8944
+ onCanvasDirty?.();
8945
+ scheduleAutoSave();
8739
8946
  }
8740
8947
 
8741
8948
  /** Redo the previously undone action. No-op if at the newest state. */
@@ -8744,6 +8951,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8744
8951
  historyIndex++;
8745
8952
  canvasLog('Canvas: redo → history index', historyIndex);
8746
8953
  await restoreHistorySnapshot(historyStack[historyIndex]);
8954
+ _hasUnsavedChanges = true;
8955
+ onCanvasDirty?.();
8956
+ scheduleAutoSave();
8747
8957
  }
8748
8958
 
8749
8959
  /** Serialize the current canvas state to a JSON string */
@@ -8757,7 +8967,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8757
8967
  return null;
8758
8968
  }
8759
8969
  try {
8760
- const canvasJson = canvas.toJSON(CANVAS_CUSTOM_PROPS);
8970
+ const canvasJson = safelySerializeCanvas(canvas, CANVAS_CUSTOM_PROPS);
8761
8971
  // Diagnostic: log frame structure at save time to detect corruption
8762
8972
  (canvasJson.objects || []).forEach((obj: any) => {
8763
8973
  if (obj._isFrame || obj._customType === 'frame' || obj.type === 'FrameShape') {
@@ -8849,35 +9059,18 @@ function checkAndAddNewShapeToFrame(shape: any) {
8849
9059
 
8850
9060
  await canvas.loadFromJSON(canvasJson, reviver);
8851
9061
 
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).
9062
+ // Light pass: ensure any images without loaded elements are reloaded
8854
9063
  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);
9064
+ const checkUnloadedImages = (obj: any) => {
9065
+ if (obj._customType === 'image' || obj._hasImage || obj._imageUrl) {
8861
9066
  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;
9067
+ ImageShape.reloadImage(obj);
8874
9068
  }
8875
- } else if (String(obj.type || '').toLowerCase() === 'group') {
8876
- applyInteractiveGroupFlags(obj);
8877
- (obj.getObjects?.() || []).forEach(restoreObject);
9069
+ } else if (String(obj.type || '').toLowerCase() === 'group' || isFrameShape(obj)) {
9070
+ (obj.getObjects?.() || []).forEach(checkUnloadedImages);
8878
9071
  }
8879
9072
  };
8880
- allObjects.forEach(restoreObject);
9073
+ allObjects.forEach(checkUnloadedImages);
8881
9074
 
8882
9075
  // ── Orphan-repair pass ──────────────────────────────────────────────
8883
9076
  // Old/corrupted saves may have frame children at canvas level instead
@@ -8914,16 +9107,19 @@ function checkAndAddNewShapeToFrame(shape: any) {
8914
9107
  const spatialOrphans = canvas.getObjects().filter((obj: any) =>
8915
9108
  !isFrameShape(obj) &&
8916
9109
  !(obj as any)._isFrameBackground &&
9110
+ !(obj as any)._parentFrameId &&
8917
9111
  !obj.group && // not already inside any group
8918
9112
  String(obj.type || '').toLowerCase() !== 'group'
8919
9113
  );
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;
9114
+ if (spatialOrphans.length > 0) {
9115
+ for (const obj of spatialOrphans) {
9116
+ const center = obj.getCenterPoint();
9117
+ for (const frame of framesForSpatialRepair) {
9118
+ if (isPointInsideFrame(frame, center)) {
9119
+ canvasWarn('Canvas: loadCanvas — spatial repair: re-attaching', (obj as any).type, 'to frame', frame._labelText);
9120
+ addObjectToFrame(frame, obj, canvas);
9121
+ break;
9122
+ }
8927
9123
  }
8928
9124
  }
8929
9125
  }
@@ -8951,11 +9147,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
8951
9147
 
8952
9148
  // Reset history after an external load so undo can't go back to
8953
9149
  // the previous canvas state and the loaded state becomes the new "initial".
8954
- historyStack = [];
8955
- historyIndex = -1;
9150
+ // Seed historyStack directly with the loaded state to avoid re-serializing via canvas.toJSON().
9151
+ const initialSnapshot = JSON.stringify(canvasJson);
9152
+ historyStack = [initialSnapshot];
9153
+ historyIndex = 0;
8956
9154
  isRestoringHistory = false;
8957
9155
  canvasLoadPhase = 'ready';
8958
- takeHistorySnapshot(true);
8959
9156
  } catch (err) {
8960
9157
  console.error('Canvas: loadCanvas failed', err);
8961
9158
  isRestoringHistory = false;
@@ -8980,7 +9177,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
8980
9177
 
8981
9178
  // request a render all
8982
9179
  canvas.requestRenderAll();
8983
- takeHistorySnapshot(true);
9180
+ takeHistorySnapshot();
9181
+ onCanvasCleared?.();
8984
9182
 
8985
9183
  // log the clearing
8986
9184
  canvasLog('Clear all objects created');
@@ -11378,8 +11576,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11378
11576
  <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
11577
 
11380
11578
  <!-- Pan/Zoom Panel: Position configurable via panZoomPosition prop -->
11381
- {#if !isCanvasLoading}
11382
- <div class="canvas-pan-zoom-overlay {getPanZoomPositionClass(panZoomPosition)}">
11579
+ <div class="canvas-pan-zoom-overlay {getPanZoomPositionClass(panZoomPosition)} {isCanvasLoading ? 'pointer-events-none opacity-60 transition-opacity duration-200' : 'transition-opacity duration-200'}">
11383
11580
  <PanZoomPanel
11384
11581
  {zoomLevel}
11385
11582
  isPanActive={activeTool === 'pan'}
@@ -11399,13 +11596,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
11399
11596
  onSave={saveNow}
11400
11597
  />
11401
11598
  </div>
11402
- {/if}
11403
11599
 
11404
11600
  <!-- Canvas -->
11405
11601
  <canvas class="canvas-el" bind:this={canvasEl}></canvas>
11406
11602
 
11407
11603
  {#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);">
11604
+ <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
11605
  <div style="display:flex;flex-direction:column;align-items:center;gap:12px;">
11410
11606
  <div class="canvas-loader-spinner"></div>
11411
11607
  <span style="font-size:14px;font-weight:500;color:#6b7280;letter-spacing:0.02em;">Loading canvas…</span>
@@ -11421,8 +11617,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11421
11617
  {/if}
11422
11618
 
11423
11619
  <!-- 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)]"
11620
+ <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
11621
  {activeTool}
11427
11622
  {onSelectSelectTool}
11428
11623
  {onSelectEraseTool}
@@ -11460,8 +11655,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11460
11655
  {onSelectLibraryShapeTool}
11461
11656
  {advancedFeatures}
11462
11657
  {mediaBtsOnBar}
11463
- />
11464
- {/if}
11658
+ />
11465
11659
 
11466
11660
  <!-- Props Panel: Only visible when an object is selected -->
11467
11661
  {#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;
@@ -39,6 +41,7 @@ declare const __propDef: {
39
41
  onWidgetRename?: ((widgetId: string, newName: string) => void) | null;
40
42
  onRefreshScreenshot?: ((widgetId: string) => void) | null;
41
43
  /** Host persists canvases.primary_widget_id after Canvas paints the red stroke. */ onSetPrimaryWidget?: ((widgetId: string) => void) | null;
44
+ /** Throttled paint hook for HTML overlays (e.g. live WidgetShape iframes). */ onAfterRender?: (() => void) | null;
42
45
  getWidgetName?: ((widgetId: string) => string | null) | null;
43
46
  /** Returns true when widgetId still exists in the host widget list. */ isWidgetKnown?: ((widgetId: string) => boolean) | null;
44
47
  showLogs?: boolean;
@@ -52,6 +55,13 @@ declare const __propDef: {
52
55
  replaceObjectWithWidgetImage?: (objectId: string, widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
53
56
  updateWidgetImage?: (widgetId: string, newScreenshotDataUrl: string) => void;
54
57
  selectWidgetShape?: (widgetId: string) => boolean;
58
+ listWidgetShapeScreenRects?: () => Array<{
59
+ widgetId: string;
60
+ left: number;
61
+ top: number;
62
+ width: number;
63
+ height: number;
64
+ }>;
55
65
  getWidgetShapeScreenRect?: (widgetId: string) => {
56
66
  left: number;
57
67
  top: number;
@@ -91,6 +101,9 @@ declare const __propDef: {
91
101
  onSelectFrameTool?: () => void;
92
102
  setPrimaryWidgetShape?: (widgetId: string) => boolean;
93
103
  getPrimaryWidgetId?: () => string | null;
104
+ translateWidgetShapeByScreen?: (widgetId: string, dxScreen: number, dyScreen: number) => boolean;
105
+ selectWidgetShapeById?: (widgetId: string) => boolean;
106
+ getSelectedWidgetShapeId?: () => string | null;
94
107
  onSelectImageTool?: () => void;
95
108
  onSelectVideoTool?: () => void;
96
109
  onSelectPanTool?: () => void;
@@ -135,6 +148,13 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
135
148
  get replaceObjectWithWidgetImage(): (objectId: string, widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
136
149
  get updateWidgetImage(): (widgetId: string, newScreenshotDataUrl: string) => void;
137
150
  get selectWidgetShape(): (widgetId: string) => boolean;
151
+ get listWidgetShapeScreenRects(): () => Array<{
152
+ widgetId: string;
153
+ left: number;
154
+ top: number;
155
+ width: number;
156
+ height: number;
157
+ }>;
138
158
  get getWidgetShapeScreenRect(): (widgetId: string) => {
139
159
  left: number;
140
160
  top: number;
@@ -174,6 +194,9 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
174
194
  get onSelectFrameTool(): () => void;
175
195
  get setPrimaryWidgetShape(): (widgetId: string) => boolean;
176
196
  get getPrimaryWidgetId(): () => string | null;
197
+ get translateWidgetShapeByScreen(): (widgetId: string, dxScreen: number, dyScreen: number) => boolean;
198
+ get selectWidgetShapeById(): (widgetId: string) => boolean;
199
+ get getSelectedWidgetShapeId(): () => string | null;
177
200
  get onSelectImageTool(): () => void;
178
201
  get onSelectVideoTool(): () => void;
179
202
  get onSelectPanTool(): () => void;
@@ -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.11",
4
4
  "type": "module",
5
5
  "svelte": "./dist/index.js",
6
6
  "module": "./dist/index.js",