@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.
@@ -1,5 +1,5 @@
1
1
  import { SvelteComponentTyped } from "svelte";
2
- import type { WidgetConversionPayload } from './types';
2
+ import type { WidgetConversionPayload, StrokeRecognizer } from './types';
3
3
  declare const __propDef: {
4
4
  props: {
5
5
  /**
@@ -36,6 +36,7 @@ declare const __propDef: {
36
36
  onCanvasCleared?: (() => void) | null;
37
37
  onConvertToWidget?: ((data: WidgetConversionPayload) => void) | null;
38
38
  onWidgetImageClick?: ((widgetId: string) => void) | null;
39
+ onRecognizeStroke?: StrokeRecognizer | null;
39
40
  onNonWidgetSelected?: (() => void) | null;
40
41
  onWidgetShapeDuplicated?: ((sourceWidgetId: string, clonedObject: any) => void) | null;
41
42
  onWidgetShapeDeleting?: ((widgetId: string) => Promise<boolean>) | null;
@@ -62,9 +63,9 @@ declare const __propDef: {
62
63
  top: number;
63
64
  width: number;
64
65
  height: number;
65
- localWidth: any;
66
- localHeight: any;
67
- matrix: any[];
66
+ localWidth: number;
67
+ localHeight: number;
68
+ matrix: number[];
68
69
  widgetId: string;
69
70
  hovered: boolean;
70
71
  }[];
@@ -113,6 +114,7 @@ declare const __propDef: {
113
114
  setWidgetShapeOverlayDragActive?: (active: boolean) => void;
114
115
  selectWidgetShapeById?: (widgetId: string) => boolean;
115
116
  getSelectedWidgetShapeId?: () => string | null;
117
+ getSelectedObject?: () => any;
116
118
  getHoveredWidgetShapeId?: () => string | null;
117
119
  onSelectImageTool?: () => void;
118
120
  onSelectVideoTool?: () => void;
@@ -163,9 +165,9 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
163
165
  top: number;
164
166
  width: number;
165
167
  height: number;
166
- localWidth: any;
167
- localHeight: any;
168
- matrix: any[];
168
+ localWidth: number;
169
+ localHeight: number;
170
+ matrix: number[];
169
171
  widgetId: string;
170
172
  hovered: boolean;
171
173
  }[];
@@ -214,6 +216,7 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
214
216
  get setWidgetShapeOverlayDragActive(): (active: boolean) => void;
215
217
  get selectWidgetShapeById(): (widgetId: string) => boolean;
216
218
  get getSelectedWidgetShapeId(): () => string | null;
219
+ get getSelectedObject(): () => any;
217
220
  get getHoveredWidgetShapeId(): () => string | null;
218
221
  get onSelectImageTool(): () => void;
219
222
  get onSelectVideoTool(): () => void;
@@ -9,7 +9,7 @@
9
9
  // Tool type definition
10
10
  type ToolName = 'select' | 'erase' | 'draw' | 'arrow' | 'text' | 'rect' | 'circle' | 'circle-true' | 'triangle' | 'frame' | 'pan' | 'image' | 'video' | 'library-shape';
11
11
  // Shape tool sub-type for the shapes dropdown (Arrow is a dedicated button, not in dropdown)
12
- type ShapeToolName = 'rect' | 'circle' | 'circle-true' | 'triangle';
12
+ type ShapeToolName = 'rect' | 'circle' | 'circle-true' | 'triangle' | 'arrow';
13
13
 
14
14
  // Class
15
15
  let className = '';
@@ -60,7 +60,9 @@
60
60
 
61
61
  // ── Shape library (special shapes: media, arrows, UI) ────────────────────
62
62
  /** Called when user clicks a library shape. Canvas inserts it as a Path. */
63
- export let onInsertLibraryShape: (shapeKey: string, pathData: string) => void = () => {};
63
+ /** Passed by Canvas.svelte but never read here — export const keeps the
64
+ * init-set contract without the unused-reactive warning. */
65
+ export const onInsertLibraryShape: (shapeKey: string, pathData: string) => void = () => {};
64
66
  /** Draw-to-place: activates library shape tool so user clicks-and-drags to size it. */
65
67
  export let onSelectLibraryShapeTool: (shapeKey: string, pathData: string) => void = () => {};
66
68
 
@@ -136,6 +138,12 @@
136
138
  label: 'Circle',
137
139
  key: '',
138
140
  },
141
+ arrow: {
142
+ icon: '↗',
143
+ iconSvg: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path d="M6 18C6 18 6.06617 12.5162 8.00001 10.5521C10.862 7.64522 19 9 19 9M19 9L15 5M19 9L15 13" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
144
+ label: 'Arrow',
145
+ key: 'A',
146
+ },
139
147
  };
140
148
 
141
149
  // Image dropdown entry — placed at the bottom of the shapes dropdown with a divider
@@ -1180,10 +1188,7 @@ button:disabled {
1180
1188
  flex-shrink: 0;
1181
1189
  }
1182
1190
 
1183
- /* Left: shape icon button — same size as other tool buttons */
1184
- .shapes-main-bt {
1185
- /* Inherits .wdg-tool-bt 48×48 */
1186
- }
1191
+ /* Left: shape icon button (.shapes-main-bt) — inherits .wdg-tool-bt 48×48 */
1187
1192
  /* When active, give all shape SVGs a semi-transparent fill for visual weight */
1188
1193
  .shapes-main-bt.wdg-tool-active :global(svg rect),
1189
1194
  .shapes-main-bt.wdg-tool-active :global(svg circle),
@@ -10,7 +10,7 @@ declare const __propDef: {
10
10
  onSelectSelectTool?: () => void;
11
11
  onSelectEraseTool?: () => void;
12
12
  onSelectDrawTool?: () => void;
13
- onSelectShapeTool?: (shapeType: "rect" | "circle" | "circle-true" | "triangle") => void;
13
+ onSelectShapeTool?: (shapeType: "rect" | "arrow" | "circle" | "circle-true" | "triangle") => void;
14
14
  onSelectFrameTool?: () => void;
15
15
  onSelectTextTool?: () => void;
16
16
  onSelectPanTool?: () => void;
@@ -31,7 +31,8 @@ declare const __propDef: {
31
31
  /** Disables the Redo button when there is no future state to redo to. */ canRedo?: boolean;
32
32
  /** When true, the drawing tool stays active after placing a shape. */ stickyToolEnabled?: boolean;
33
33
  onToggleStickyTool?: () => void;
34
- /** Called when user clicks a library shape. Canvas inserts it as a Path. */ onInsertLibraryShape?: (shapeKey: string, pathData: string) => void;
34
+ /** Passed by Canvas.svelte but never read here — export const keeps the
35
+ * init-set contract without the unused-reactive warning. */ onInsertLibraryShape?: (shapeKey: string, pathData: string) => void;
35
36
  /** Draw-to-place: activates library shape tool so user clicks-and-drags to size it. */ onSelectLibraryShapeTool?: (shapeKey: string, pathData: string) => void;
36
37
  /** Extra tools (undo/redo/lock). Code stays; UI is gated. */ advancedFeatures?: boolean;
37
38
  /**
@@ -56,5 +57,6 @@ export type CanvasToolbarProps = typeof __propDef.props;
56
57
  export type CanvasToolbarEvents = typeof __propDef.events;
57
58
  export type CanvasToolbarSlots = typeof __propDef.slots;
58
59
  export default class CanvasToolbar extends SvelteComponentTyped<CanvasToolbarProps, CanvasToolbarEvents, CanvasToolbarSlots> {
60
+ get onInsertLibraryShape(): (shapeKey: string, pathData: string) => void;
59
61
  }
60
62
  export {};
@@ -8,7 +8,9 @@
8
8
 
9
9
  // ── Context: what was right-clicked ───────────────────────────────────────
10
10
  export let hasSelection: boolean = false;
11
- export let selectionCount: number = 0;
11
+ // Passed by Canvas.svelte but never read here — export const keeps the
12
+ // init-set contract without the unused-reactive warning.
13
+ export const selectionCount: number = 0;
12
14
  export let canGroup: boolean = false;
13
15
  export let canUngroup: boolean = false;
14
16
  export let canPaste: boolean = false;
@@ -32,5 +32,6 @@ export type ContextMenuProps = typeof __propDef.props;
32
32
  export type ContextMenuEvents = typeof __propDef.events;
33
33
  export type ContextMenuSlots = typeof __propDef.slots;
34
34
  export default class ContextMenu extends SvelteComponentTyped<ContextMenuProps, ContextMenuEvents, ContextMenuSlots> {
35
+ get selectionCount(): number;
35
36
  }
36
37
  export {};
@@ -87,6 +87,7 @@
87
87
  <button
88
88
  class="panel-btn grid-btn {showGrid ? 'active' : ''}"
89
89
  onclick={onGridToggle}
90
+ aria-label="Toggle grid"
90
91
  >
91
92
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
92
93
  <rect x="3" y="3" width="7" height="7"/>
@@ -104,6 +105,7 @@
104
105
  <button
105
106
  class="panel-btn pan-btn {isPanActive ? 'active' : ''}"
106
107
  onclick={onPanToggle}
108
+ aria-label="Hand / pan tool"
107
109
  >
108
110
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
109
111
  <path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0"/>
@@ -123,6 +125,7 @@
123
125
  class="panel-btn"
124
126
  onclick={onZoomOut}
125
127
  disabled={zoomLevel <= 10}
128
+ aria-label="Zoom out"
126
129
  >
127
130
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
128
131
  <circle cx="11" cy="11" r="8"/>
@@ -165,6 +168,7 @@
165
168
  class="panel-btn"
166
169
  onclick={onZoomIn}
167
170
  disabled={zoomLevel >= 500}
171
+ aria-label="Zoom in"
168
172
  >
169
173
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
170
174
  <circle cx="11" cy="11" r="8"/>
@@ -193,6 +197,7 @@
193
197
  <button
194
198
  class="panel-btn"
195
199
  onclick={onZoomFit}
200
+ aria-label="Fit content to view"
196
201
  >
197
202
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
198
203
  <path d="M8 3H5a2 2 0 0 0-2 2v3"/>
@@ -1,22 +1,23 @@
1
- <script>
1
+ <script lang="ts">
2
2
  import { onMount } from 'svelte';
3
+ import type { Canvas } from 'fabric';
3
4
  import { Portal } from '@widgetic/design-system';
4
5
  import { canvasWarn } from './canvasLogger';
5
6
 
6
- let { fabricCanvas, target, class: className = '', style = '' } = $props();
7
- let drawingCanvas;
8
- function captureDrawingCanvas(node) {
7
+ let { fabricCanvas, target, class: className = '', style = '' }: { fabricCanvas: Canvas; target: string; class?: string; style?: string } = $props();
8
+ let drawingCanvas: HTMLCanvasElement | null = null;
9
+ function captureDrawingCanvas(node: HTMLCanvasElement) {
9
10
  drawingCanvas = node;
10
11
  return { destroy() { drawingCanvas = null; } };
11
12
  }
12
- let controls = $state([]);
13
+ let controls: { key: string; points: string; cursor: string }[] = $state([]);
13
14
  let viewport = $state({ left: 0, top: 0, width: 0, height: 0 });
14
- let activePointer = null;
15
- let lastPointerEvent = null;
15
+ let activePointer: number | null = null;
16
+ let lastPointerEvent: PointerEvent | null = null;
16
17
 
17
18
  // Route only control gestures through Fabric's existing DOM event handlers.
18
19
  // Pointer capture prevents neighboring iframes from stealing the gesture.
19
- function routeMouseEvent(type, event) {
20
+ function routeMouseEvent(type: 'mousedown' | 'mousemove' | 'mouseup', event: PointerEvent) {
20
21
  fabricCanvas.upperCanvasEl.dispatchEvent(new MouseEvent(type, {
21
22
  bubbles: true, cancelable: true, clientX: event.clientX, clientY: event.clientY,
22
23
  button: 0, buttons: type === 'mouseup' ? 0 : 1,
@@ -25,12 +26,12 @@
25
26
  }));
26
27
  }
27
28
 
28
- function startControl(event) {
29
+ function startControl(event: PointerEvent) {
29
30
  if (event.button !== 0 || activePointer !== null) return;
30
31
  event.preventDefault();
31
32
  event.stopPropagation();
32
33
  try {
33
- event.currentTarget.setPointerCapture(event.pointerId);
34
+ (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
34
35
  activePointer = event.pointerId;
35
36
  lastPointerEvent = event;
36
37
  routeMouseEvent('mousedown', event);
@@ -40,18 +41,19 @@
40
41
  }
41
42
  }
42
43
 
43
- function moveControl(event) {
44
+ function moveControl(event: PointerEvent) {
44
45
  if (activePointer !== event.pointerId) return;
45
46
  lastPointerEvent = event;
46
47
  routeMouseEvent('mousemove', event);
47
48
  }
48
49
 
49
- function finishControl(event) {
50
+ function finishControl(event: PointerEvent) {
50
51
  if (activePointer !== event.pointerId) return;
51
52
  activePointer = null;
52
53
  routeMouseEvent('mouseup', event);
53
- if (event.currentTarget?.hasPointerCapture?.(event.pointerId)) {
54
- event.currentTarget.releasePointerCapture(event.pointerId);
54
+ const target = event.currentTarget as HTMLElement | null;
55
+ if (target?.hasPointerCapture?.(event.pointerId)) {
56
+ target.releasePointerCapture(event.pointerId);
55
57
  }
56
58
  }
57
59
 
@@ -67,7 +69,7 @@
67
69
  context.setTransform(1, 0, 0, 1, 0, 0);
68
70
  context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height);
69
71
  const selected = fabricCanvas.getActiveObject();
70
- if (!selected?._isWidgetImage || fabricCanvas.skipTargetFind || fabricCanvas.isDrawingMode) {
72
+ if (!selected || !(selected as any)._isWidgetImage || fabricCanvas.skipTargetFind || fabricCanvas.isDrawingMode) {
71
73
  controls = [];
72
74
  return;
73
75
  }
@@ -75,11 +77,11 @@
75
77
  context.setTransform(retina, 0, 0, retina, 0, 0);
76
78
  // Red primary stroke is part of the object, not the selection border.
77
79
  // Paint it with the same viewport/object matrices above the HTML preview.
78
- if (selected._isPrimaryWidget && selected.strokeWidth) {
80
+ if ((selected as any)._isPrimaryWidget && selected.strokeWidth) {
79
81
  context.save();
80
82
  context.transform(...fabricCanvas.viewportTransform);
81
83
  context.transform(...selected.calcTransformMatrix());
82
- context.strokeStyle = selected.stroke;
84
+ context.strokeStyle = selected.stroke as string;
83
85
  context.lineWidth = selected.strokeWidth;
84
86
  context.strokeRect(-selected.width / 2, -selected.height / 2, selected.width, selected.height);
85
87
  context.restore();
@@ -88,11 +90,14 @@
88
90
  selected._renderControls(context);
89
91
  const scaleX = bounds.width / fabricCanvas.getWidth();
90
92
  const scaleY = bounds.height / fabricCanvas.getHeight();
91
- controls = Object.entries(selected.oCoords || {}).flatMap(([key, position]) => {
92
- const control = selected.controls[key];
93
- if (!selected.hasControls || !control?.getVisibility(selected, key)) return [];
93
+ // Fabric's internal control geometry (oCoords/controls) isn't on the
94
+ // public FabricObject type; this layer re-renders it as hit regions.
95
+ const sel = selected as any;
96
+ controls = Object.entries(sel.oCoords || {}).flatMap(([key, position]: [string, any]) => {
97
+ const control = sel.controls[key];
98
+ if (!sel.hasControls || !control?.getVisibility(sel, key)) return [];
94
99
  const points = position.corner;
95
- return [{ key, points: ['tl', 'tr', 'br', 'bl'].map(corner => `${points[corner].x * scaleX},${points[corner].y * scaleY}`).join(' '), cursor: control.cursorStyleHandler({}, control, selected) }];
100
+ return [{ key, points: ['tl', 'tr', 'br', 'bl'].map(corner => `${points[corner].x * scaleX},${points[corner].y * scaleY}`).join(' '), cursor: control.cursorStyleHandler({}, control, sel) }];
96
101
  });
97
102
  }
98
103
 
@@ -1,23 +1,14 @@
1
- /** @typedef {typeof __propDef.props} WidgetSelectionLayerProps */
2
- /** @typedef {typeof __propDef.events} WidgetSelectionLayerEvents */
3
- /** @typedef {typeof __propDef.slots} WidgetSelectionLayerSlots */
4
- export default class WidgetSelectionLayer extends SvelteComponentTyped<{
5
- [x: string]: never;
6
- }, {
7
- [evt: string]: CustomEvent<any>;
8
- }, {}> {
9
- }
10
- export type WidgetSelectionLayerProps = typeof __propDef.props;
11
- export type WidgetSelectionLayerEvents = typeof __propDef.events;
12
- export type WidgetSelectionLayerSlots = typeof __propDef.slots;
13
1
  import { SvelteComponentTyped } from "svelte";
14
2
  declare const __propDef: {
15
- props: {
16
- [x: string]: never;
17
- };
3
+ props: Record<string, never>;
18
4
  events: {
19
5
  [evt: string]: CustomEvent<any>;
20
6
  };
21
7
  slots: {};
22
8
  };
9
+ export type WidgetSelectionLayerProps = typeof __propDef.props;
10
+ export type WidgetSelectionLayerEvents = typeof __propDef.events;
11
+ export type WidgetSelectionLayerSlots = typeof __propDef.slots;
12
+ export default class WidgetSelectionLayer extends SvelteComponentTyped<WidgetSelectionLayerProps, WidgetSelectionLayerEvents, WidgetSelectionLayerSlots> {
13
+ }
23
14
  export {};
@@ -10,4 +10,8 @@ export { default as ContextMenu } from './ContextMenu.svelte';
10
10
  export { default as PanZoomPanel } from './PanZoomPanel.svelte';
11
11
  export { default as PropsPanel } from './props-panel/PropsPanel.svelte';
12
12
  export type { WidgetConversionPayload } from './types';
13
+ export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
14
+ export { CANVAS_SHAPE_SNAP_ENABLED } from './shapes/strokeShapeSnap';
13
15
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
16
+ export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
17
+ export type { ShapeImageStore } from './shapes/shapeImageStore';
@@ -9,4 +9,6 @@ export { default as CanvasToolbar } from './CanvasToolbar.svelte';
9
9
  export { default as ContextMenu } from './ContextMenu.svelte';
10
10
  export { default as PanZoomPanel } from './PanZoomPanel.svelte';
11
11
  export { default as PropsPanel } from './props-panel/PropsPanel.svelte';
12
+ export { CANVAS_SHAPE_SNAP_ENABLED } from './shapes/strokeShapeSnap';
12
13
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
14
+ export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
@@ -151,7 +151,10 @@
151
151
  $: isDuplicating = !!selectedObject?._isDuplicating;
152
152
  $: isConverting = !!selectedObject?._isConverting;
153
153
  $: showWidgetLoader = isPendingWidgetLink || isDuplicating || isConverting;
154
- $: resolvedWidgetName = (widgetNameRevision, widgetId && getWidgetName)
154
+ // Reading widgetNameRevision registers it as a dependency so renamed
155
+ // widgets re-resolve; the value itself is unused.
156
+ $: void widgetNameRevision;
157
+ $: resolvedWidgetName = widgetId && getWidgetName
155
158
  ? getWidgetName(widgetId)
156
159
  : null;
157
160
  $: isOrphanedWidgetShape = !!(
@@ -392,8 +395,9 @@
392
395
  }
393
396
 
394
397
  // Dismissal belongs to this selection, not to property-change notifications.
395
- let dismissedSelection = null;
396
- let previousSelection = null;
398
+ // selectedObject is `any`, so these mirror it.
399
+ let dismissedSelection: any = null;
400
+ let previousSelection: any = null;
397
401
  $: if (selectedObject !== previousSelection) {
398
402
  previousSelection = selectedObject;
399
403
  dismissedSelection = null;
@@ -1865,10 +1869,12 @@
1865
1869
  background: white;
1866
1870
  outline: none;
1867
1871
  -moz-appearance: textfield;
1872
+ appearance: textfield;
1868
1873
  }
1869
1874
  .dimension-input::-webkit-outer-spin-button,
1870
1875
  .dimension-input::-webkit-inner-spin-button {
1871
1876
  -webkit-appearance: none;
1877
+ appearance: none;
1872
1878
  margin: 0;
1873
1879
  }
1874
1880
  .dimension-input:focus {
@@ -1,6 +1,8 @@
1
1
  import { ImageShape } from './ImageShape';
2
2
  export declare const WIDGET_SHAPE_EXTRA_PROPS: string[];
3
3
  export declare const WIDGET_SHAPE_CUSTOM_PROPS: string[];
4
+ /** Pulls a shape's thumbnail back from the host store and repaints it. */
5
+ export declare function restoreThumbnailFromStore(shape: WidgetShape): Promise<void>;
4
6
  export declare class WidgetShape extends ImageShape {
5
7
  static type: string;
6
8
  _isWidgetImage: boolean;
@@ -8,6 +10,8 @@ export declare class WidgetShape extends ImageShape {
8
10
  _widgetName: string | null;
9
11
  /** True when _widgetId no longer exists in the host widget list (deleted or moved). */
10
12
  _widgetOrphaned: boolean;
13
+ /** Reference to the thumbnail bytes held by the host store, when externalized. */
14
+ _imageRef: string | null;
11
15
  /**
12
16
  * Runtime-only: when live HTML iframe overlays the shape, hide the screenshot
13
17
  * (draw a solid fill instead) so it does not ghost in the padding. Not serialized.
@@ -15,18 +15,69 @@
15
15
  import { Rect, classRegistry } from 'fabric';
16
16
  import { ImageShape, IMAGE_SHAPE_CUSTOM_PROPS } from './ImageShape';
17
17
  import { canvasLog, canvasWarn } from '../canvasLogger';
18
+ import { getShapeImageStore, isInlineImageData, shapeImageRef } from './shapeImageStore';
18
19
  // Widget-specific custom properties (on top of IMAGE_SHAPE_CUSTOM_PROPS)
19
20
  export const WIDGET_SHAPE_EXTRA_PROPS = [
20
21
  '_isWidgetImage',
21
22
  '_widgetId',
22
23
  '_widgetName',
23
24
  '_widgetOrphaned',
25
+ /** Stands in for the thumbnail bytes when a host store holds them. */
26
+ '_imageRef',
24
27
  ];
25
28
  // Full list: base image props + widget props
26
29
  export const WIDGET_SHAPE_CUSTOM_PROPS = [
27
30
  ...IMAGE_SHAPE_CUSTOM_PROPS,
28
31
  ...WIDGET_SHAPE_EXTRA_PROPS,
29
32
  ];
33
+ /** What the store already holds per reference, so repeat saves are skipped. */
34
+ const lastStoredThumbnailByRef = new Map();
35
+ /**
36
+ * Hands the thumbnail bytes to the host store and returns the fields that keep
37
+ * them out of the serialized shape. Returns nothing to change when there is no
38
+ * store, no inline bytes, or no stable reference to file them under — those
39
+ * shapes keep serializing as before.
40
+ */
41
+ function externalizeThumbnail(shape) {
42
+ const store = getShapeImageStore();
43
+ if (!store || !isInlineImageData(shape._imageUrl))
44
+ return {};
45
+ const ref = shapeImageRef(shape._widgetId, shape._objectId);
46
+ if (!ref)
47
+ return {};
48
+ try {
49
+ // Undo history serializes on every edit, so only a changed screenshot is
50
+ // worth another write.
51
+ if (lastStoredThumbnailByRef.get(ref) !== shape._imageUrl) {
52
+ store.save(ref, shape._imageUrl);
53
+ lastStoredThumbnailByRef.set(ref, shape._imageUrl);
54
+ }
55
+ }
56
+ catch (err) {
57
+ canvasWarn('WidgetShape: thumbnail store rejected the save, keeping it inline', err);
58
+ return {};
59
+ }
60
+ shape._imageRef = ref;
61
+ return { _imageUrl: undefined, _imageRef: ref };
62
+ }
63
+ /** Pulls a shape's thumbnail back from the host store and repaints it. */
64
+ export async function restoreThumbnailFromStore(shape) {
65
+ const store = getShapeImageStore();
66
+ if (!store || !shape._imageRef || shape._imageUrl)
67
+ return;
68
+ try {
69
+ const url = await store.load(shape._imageRef);
70
+ if (!url || shape._imageUrl)
71
+ return;
72
+ if (isInlineImageData(url))
73
+ lastStoredThumbnailByRef.set(shape._imageRef, url);
74
+ shape._imageUrl = url;
75
+ ImageShape.reloadImage(shape);
76
+ }
77
+ catch (err) {
78
+ canvasWarn('WidgetShape: could not restore thumbnail for', shape._imageRef, err);
79
+ }
80
+ }
30
81
  export class WidgetShape extends ImageShape {
31
82
  static type = 'WidgetShape';
32
83
  _isWidgetImage = false;
@@ -34,6 +85,8 @@ export class WidgetShape extends ImageShape {
34
85
  _widgetName = null;
35
86
  /** True when _widgetId no longer exists in the host widget list (deleted or moved). */
36
87
  _widgetOrphaned = false;
88
+ /** Reference to the thumbnail bytes held by the host store, when externalized. */
89
+ _imageRef = null;
37
90
  /**
38
91
  * Runtime-only: when live HTML iframe overlays the shape, hide the screenshot
39
92
  * (draw a solid fill instead) so it does not ghost in the padding. Not serialized.
@@ -90,6 +143,7 @@ export class WidgetShape extends ImageShape {
90
143
  const base = super.toObject(extras);
91
144
  return {
92
145
  ...base,
146
+ ...externalizeThumbnail(this),
93
147
  type: WidgetShape.type,
94
148
  _imageElement: undefined,
95
149
  };
@@ -107,6 +161,9 @@ export class WidgetShape extends ImageShape {
107
161
  if (shape._imageUrl) {
108
162
  ImageShape.reloadImage(shape);
109
163
  }
164
+ else if (shape._imageRef) {
165
+ void restoreThumbnailFromStore(shape);
166
+ }
110
167
  canvasLog('WidgetShape: fromObject — restored', shape._objectId || 'shape', 'hasImage:', shape._hasImage, 'isWidget:', shape._isWidgetImage, 'widgetId:', shape._widgetId);
111
168
  return shape;
112
169
  });
@@ -127,6 +184,9 @@ export function upgradeToWidgetShape(obj) {
127
184
  Object.setPrototypeOf(obj, WidgetShape.prototype);
128
185
  const shape = obj;
129
186
  shape._isWidgetImage = true;
187
+ if (shape._imageRef && !shape._imageUrl) {
188
+ void restoreThumbnailFromStore(shape);
189
+ }
130
190
  canvasLog('WidgetShape: upgraded ImageShape → WidgetShape for', shape._objectId || 'shape');
131
191
  return shape;
132
192
  }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Where a widget shape's thumbnail bytes live when they are not in the canvas
3
+ * JSON.
4
+ *
5
+ * A widget shape's image is a screenshot of the widget, and it was serialized
6
+ * inline as a `data:` URL on every save. Canvas JSON is stringified on each
7
+ * autosave and written three times over (durable store, legacy mirror, API), so
8
+ * a handful of shapes turned every save into megabytes of synchronous string
9
+ * work on the main thread — the freeze reports named it directly.
10
+ *
11
+ * The bytes are reproducible and already persisted per widget server-side, so
12
+ * the canvas only needs to record *which* image a shape had. The host supplies
13
+ * the store: it saves the bytes where it likes and resolves a reference back to
14
+ * something an `Image` can load (its own copy, or the widget's thumbnail URL).
15
+ *
16
+ * With no store installed nothing changes — shapes keep serializing inline, so
17
+ * a consumer that has not wired one up is never left with blank shapes.
18
+ */
19
+ export interface ShapeImageStore {
20
+ /**
21
+ * Persist the bytes for a reference. Called during serialization, so it must
22
+ * return immediately — write in the background and swallow failures.
23
+ */
24
+ save(ref: string, dataUrl: string): void;
25
+ /** Resolve a reference to a data URL or any URL an `Image` can load. */
26
+ load(ref: string): Promise<string | null>;
27
+ }
28
+ export declare function setShapeImageStore(store: ShapeImageStore | null): void;
29
+ export declare function getShapeImageStore(): ShapeImageStore | null;
30
+ /** Inline bytes — the thing that must not reach the canvas JSON. */
31
+ export declare function isInlineImageData(url: unknown): url is string;
32
+ /**
33
+ * Reference for a shape's thumbnail. Keyed on the widget when there is one, so
34
+ * the same reference resolves after a reload, a duplicate, or a fresh browser
35
+ * where only the server copy exists.
36
+ */
37
+ export declare function shapeImageRef(widgetId?: string | null, objectId?: string | null): string | null;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Where a widget shape's thumbnail bytes live when they are not in the canvas
3
+ * JSON.
4
+ *
5
+ * A widget shape's image is a screenshot of the widget, and it was serialized
6
+ * inline as a `data:` URL on every save. Canvas JSON is stringified on each
7
+ * autosave and written three times over (durable store, legacy mirror, API), so
8
+ * a handful of shapes turned every save into megabytes of synchronous string
9
+ * work on the main thread — the freeze reports named it directly.
10
+ *
11
+ * The bytes are reproducible and already persisted per widget server-side, so
12
+ * the canvas only needs to record *which* image a shape had. The host supplies
13
+ * the store: it saves the bytes where it likes and resolves a reference back to
14
+ * something an `Image` can load (its own copy, or the widget's thumbnail URL).
15
+ *
16
+ * With no store installed nothing changes — shapes keep serializing inline, so
17
+ * a consumer that has not wired one up is never left with blank shapes.
18
+ */
19
+ let installedStore = null;
20
+ export function setShapeImageStore(store) {
21
+ installedStore = store;
22
+ }
23
+ export function getShapeImageStore() {
24
+ return installedStore;
25
+ }
26
+ /** Inline bytes — the thing that must not reach the canvas JSON. */
27
+ export function isInlineImageData(url) {
28
+ return typeof url === 'string' && url.startsWith('data:');
29
+ }
30
+ /**
31
+ * Reference for a shape's thumbnail. Keyed on the widget when there is one, so
32
+ * the same reference resolves after a reload, a duplicate, or a fresh browser
33
+ * where only the server copy exists.
34
+ */
35
+ export function shapeImageRef(widgetId, objectId) {
36
+ if (widgetId)
37
+ return `widget:${widgetId}`;
38
+ if (objectId)
39
+ return `shape:${objectId}`;
40
+ return null;
41
+ }