@widgetic/canvas 0.5.7 → 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
@@ -95,7 +99,7 @@
95
99
  const propsToRegister = [
96
100
  '_objectId', '_customType',
97
101
  '_cornerRoundness', '_cornerRoundnessPixels', '_fillOpacity',
98
- '_shapeKey', '_cornerRadiusMode',
102
+ '_shapeKey', '_cornerRadiusMode', '_iconFill',
99
103
  '_boxStroke', '_boxStrokeWidth', '_boxStrokeDashArray',
100
104
  '_boxCornerRadius', '_boxFill',
101
105
  '_textPadding', '_textStrokeColor', '_textStrokeWidth',
@@ -156,6 +160,12 @@
156
160
  // Extra canvas chrome (undo/redo/lock, frame, image, shape library).
157
161
  // Default off for the sketch MVP. Same pattern as wireframeMode: keep the code, hide the UI.
158
162
  export let advancedFeatures: boolean = false;
163
+ /** When true and advanced is on, Frame/Image/Video stay on the toolbar. Default true. */
164
+ export let mediaBtsOnBar: boolean = true;
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;
159
169
 
160
170
  // Callback fired once when Fabric canvas is fully initialized and ready
161
171
  export let onReady: (() => void) | null = null;
@@ -189,6 +199,9 @@
189
199
  // Fires frequently — implement lightweight (e.g. set a boolean flag only).
190
200
  export let onCanvasDirty: (() => void) | null = null;
191
201
 
202
+ // Callback fired when the user intentionally clears all canvas objects
203
+ export let onCanvasCleared: (() => void) | null = null;
204
+
192
205
  // Callback: fires when user clicks "Convert to Widget" on any object in PropsPanel.
193
206
  // Widget-creator handles the API call and links the resulting widget ID back.
194
207
  export let onConvertToWidget: ((data: WidgetConversionPayload) => void) | null = null;
@@ -282,7 +295,7 @@
282
295
  const GRID_COLOR = 'rgba(0, 0, 0, 0.1)'; // Light gray dots
283
296
 
284
297
  // Tools state
285
- type ToolName = 'select' | 'erase' | 'draw' | 'arrow' | 'text' | 'rect' | 'circle' | 'circle-true' | 'triangle' | 'frame' | 'pan' | 'image' | 'library-shape';
298
+ type ToolName = 'select' | 'erase' | 'draw' | 'arrow' | 'text' | 'rect' | 'circle' | 'circle-true' | 'triangle' | 'frame' | 'pan' | 'image' | 'video' | 'library-shape';
286
299
 
287
300
  // Minimum size for image placeholder to fit UI text
288
301
  const MIN_IMAGE_PLACEHOLDER_WIDTH = 120;
@@ -649,6 +662,30 @@
649
662
  { children: any[]; bounds: { left: number; top: number; width: number; height: number } }
650
663
  >();
651
664
 
665
+ const STROKE_PAINT_SHAPE_KEYS = new Set(['cross', 'plus', 'minus', 'check']);
666
+ function paintsFillOnStroke(obj: any): boolean {
667
+ return !!obj && (obj._cornerRadiusMode === 'strokeRound' || STROKE_PAINT_SHAPE_KEYS.has(obj._shapeKey));
668
+ }
669
+
670
+ let videoRenderRaf = 0;
671
+ let videoPointerDown: { x: number; y: number; target: ImageShape; scene: { x: number; y: number } } | null = null;
672
+
673
+ function startVideoRenderLoop() {
674
+ if (videoRenderRaf) return;
675
+ const tick = () => {
676
+ videoRenderRaf = 0;
677
+ if (!canvas) return;
678
+ const playing = canvas.getObjects().some((obj: any) => {
679
+ const video = obj?._videoElement as HTMLVideoElement | undefined;
680
+ return obj?._customType === 'video' && video && !video.paused && !video.ended;
681
+ });
682
+ if (!playing) return;
683
+ canvas.requestRenderAll();
684
+ videoRenderRaf = requestAnimationFrame(tick);
685
+ };
686
+ videoRenderRaf = requestAnimationFrame(tick);
687
+ }
688
+
652
689
  /**
653
690
  * HELPER FUNCTIONS
654
691
  */
@@ -789,7 +826,7 @@
789
826
  const obj = selectedObject;
790
827
  const isFrame = isFrameShape(obj);
791
828
  const children = isFrame ? getFrameChildren(obj) : [];
792
- const bounds = obj.getBoundingRect();
829
+ const bounds = obj.getBoundingRect(true);
793
830
  const isMultiSelection =
794
831
  obj.type === 'activeSelection' || obj.type === 'activeselection';
795
832
 
@@ -977,10 +1014,10 @@
977
1014
  const isFrame = obj ? isFrameShape(obj) : false;
978
1015
  const bounds = pendingConversion?.bounds ??
979
1016
  (obj
980
- ? obj.getBoundingRect()
1017
+ ? obj.getBoundingRect(true)
981
1018
  : (() => {
982
1019
  const a = canvas.getActiveObject() as any;
983
- 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 };
984
1021
  })());
985
1022
 
986
1023
  // Preserve original visual properties before removing
@@ -1119,6 +1156,66 @@
1119
1156
  return false;
1120
1157
  }
1121
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
+
1122
1219
  /**
1123
1220
  * Screen-space box of a widget shape plus the canvas element viewport.
1124
1221
  * Used to park Widget Details left/right of the shape.
@@ -1139,18 +1236,7 @@
1139
1236
  canvasLog('Canvas: getWidgetShapeScreenRect — no shape for', widgetId);
1140
1237
  return null;
1141
1238
  }
1142
- const bbox = obj.getBoundingRect();
1143
- const canvasRect = canvasEl.getBoundingClientRect();
1144
- return {
1145
- left: canvasRect.left + bbox.left,
1146
- top: canvasRect.top + bbox.top,
1147
- width: bbox.width,
1148
- height: bbox.height,
1149
- viewportLeft: canvasRect.left,
1150
- viewportTop: canvasRect.top,
1151
- viewportWidth: canvasRect.width,
1152
- viewportHeight: canvasRect.height,
1153
- };
1239
+ return objectSceneToScreenRect(obj);
1154
1240
  }
1155
1241
 
1156
1242
  /** Screen-space box for any canvas object id (convert drafts use the grouped sketch). */
@@ -1170,18 +1256,7 @@
1170
1256
  canvasLog('Canvas: getObjectScreenRect — no object for', objectId);
1171
1257
  return null;
1172
1258
  }
1173
- const bbox = obj.getBoundingRect();
1174
- const canvasRect = canvasEl.getBoundingClientRect();
1175
- return {
1176
- left: canvasRect.left + bbox.left,
1177
- top: canvasRect.top + bbox.top,
1178
- width: bbox.width,
1179
- height: bbox.height,
1180
- viewportLeft: canvasRect.left,
1181
- viewportTop: canvasRect.top,
1182
- viewportWidth: canvasRect.width,
1183
- viewportHeight: canvasRect.height,
1184
- };
1259
+ return objectSceneToScreenRect(obj);
1185
1260
  }
1186
1261
 
1187
1262
  /**
@@ -1457,7 +1532,7 @@
1457
1532
  * This section contains the lifecycle methods for the component.
1458
1533
  * They are used to initialize the canvas and the tools.
1459
1534
  * */
1460
- onMount(() => {
1535
+ onMount(async () => {
1461
1536
  const initializationLogContext = 'Canvas initialization';
1462
1537
  canvasLog(initializationLogContext, { MountedWidth: canvasEl?.clientWidth, MountedHeight: canvasEl?.clientHeight });
1463
1538
 
@@ -1528,16 +1603,20 @@
1528
1603
 
1529
1604
  // Inject a style element at runtime for retina-aware cursor using image-set.
1530
1605
  // Done via JS (not Svelte style block) to bypass PostCSS/Tailwind preprocessing.
1531
- var cursorStyleEl = document.createElement('style');
1532
- var cssUrl1x = "url('data:image/svg+xml," + rotSvgBase1x + "') 10 10, crosshair !important";
1533
- var cssImageSet = "-webkit-image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1534
- var cssImageSetStd = "image-set(url('data:image/svg+xml," + rotSvgBase2x + "') 2x) 10 10, crosshair !important";
1535
- cursorStyleEl.textContent = '.fabric-rotate-cursor { '
1536
- + 'cursor: ' + cssUrl1x + '; '
1537
- + 'cursor: ' + cssImageSet + '; '
1538
- + 'cursor: ' + cssImageSetStd + '; '
1539
- + '}';
1540
- 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
+ }
1541
1620
 
1542
1621
  // Track rotation state for cursor class management
1543
1622
  let isRotating = false;
@@ -2318,6 +2397,10 @@
2318
2397
  // Skip internal frame background rects
2319
2398
  if (obj._isFrameBackground) return;
2320
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
+
2321
2404
  // Re-apply frame custom render for frames arriving via JSON load.
2322
2405
  // Group.fromObject creates plain Groups — our custom render/hitTest must be
2323
2406
  // reapplied so the label and border-only click detection work correctly.
@@ -2377,7 +2460,7 @@
2377
2460
  ) {
2378
2461
  try {
2379
2462
  const fingerprint = (fabricUtil as any).joinPath((obj as any).path);
2380
- const matchedKey = _shapeLibraryFingerprints.get(fingerprint);
2463
+ const matchedKey = getShapeLibraryFingerprints().get(fingerprint);
2381
2464
  if (matchedKey) {
2382
2465
  const shapeDef = getShapeByKey(matchedKey);
2383
2466
  if (shapeDef) {
@@ -2421,6 +2504,20 @@
2421
2504
  (obj as any)._lockAspectRatio = true;
2422
2505
  (obj as any)._forceLockAspectRatio = true;
2423
2506
  }
2507
+ if (shapeDef.cornerRadiusMode === 'strokeRound') {
2508
+ const bg = (obj as any).backgroundColor;
2509
+ if (!bg || bg === 'transparent') {
2510
+ const fromFill = typeof obj.fill === 'string' && obj.fill && obj.fill !== 'transparent' ? obj.fill : '#ffffff';
2511
+ obj.set({ fill: '', backgroundColor: fromFill });
2512
+ (obj as any)._iconFill = fromFill;
2513
+ } else if (obj.fill && obj.fill !== '') {
2514
+ obj.set({ fill: '' });
2515
+ }
2516
+ if (!obj.stroke) {
2517
+ obj.set({ stroke: '#374151', strokeWidth: obj.strokeWidth || 3, strokeUniform: true });
2518
+ }
2519
+ obj.dirty = true;
2520
+ }
2424
2521
  }
2425
2522
  }
2426
2523
 
@@ -2861,7 +2958,12 @@
2861
2958
  // Override PencilBrush round-cap defaults so the Corner Roundness slider
2862
2959
  // has a visible effect. At 0% the drawing appears sharp (square caps, miter
2863
2960
  // joins); moving the slider progressively rounds caps and joins.
2864
- path.set({ strokeLineCap: 'square', strokeLineJoin: 'miter' });
2961
+ path.set({
2962
+ strokeLineCap: 'square',
2963
+ strokeLineJoin: 'miter',
2964
+ fill: 'transparent',
2965
+ _fillOpacity: 0,
2966
+ });
2865
2967
  checkAndAddNewShapeToFrame(path);
2866
2968
  takeHistorySnapshot();
2867
2969
  });
@@ -3472,7 +3574,7 @@
3472
3574
  // Fill opacity (percentage stored separately from the baked rgba fill value)
3473
3575
  '_fillOpacity',
3474
3576
  // Library shape metadata
3475
- '_shapeKey', '_cornerRadiusMode',
3577
+ '_shapeKey', '_cornerRadiusMode', '_iconFill',
3476
3578
  // Textbox box stroke and corner properties
3477
3579
  '_boxStroke', '_boxStrokeWidth', '_boxStrokeDashArray',
3478
3580
  '_boxCornerRadius', '_boxFill',
@@ -4703,9 +4805,47 @@
4703
4805
  openFilePickerForPlaceholder(target);
4704
4806
  return;
4705
4807
  }
4808
+ if ((target as any)._customType === 'video') {
4809
+ if ((target as ImageShape)._videoElement) {
4810
+ void (target as ImageShape).toggleVideoPlayback().then((ok) => {
4811
+ if (ok) startVideoRenderLoop();
4812
+ });
4813
+ } else {
4814
+ openFilePickerForPlaceholder(target);
4815
+ }
4816
+ return;
4817
+ }
4706
4818
  };
4707
4819
 
4708
4820
  canvas.on('mouse:dblclick', handleDoubleClick);
4821
+
4822
+ canvas.on('mouse:down', (opt: any) => {
4823
+ const target = opt?.target as ImageShape | undefined;
4824
+ if (target?._customType === 'video' && target._videoElement && canvas) {
4825
+ videoPointerDown = {
4826
+ x: opt.e?.clientX ?? 0,
4827
+ y: opt.e?.clientY ?? 0,
4828
+ target,
4829
+ scene: canvas.getPointer(opt.e),
4830
+ };
4831
+ } else {
4832
+ videoPointerDown = null;
4833
+ }
4834
+ });
4835
+ canvas.on('mouse:up', (opt: any) => {
4836
+ if (!videoPointerDown || !opt?.e) {
4837
+ videoPointerDown = null;
4838
+ return;
4839
+ }
4840
+ const dx = Math.abs((opt.e.clientX ?? 0) - videoPointerDown.x);
4841
+ const dy = Math.abs((opt.e.clientY ?? 0) - videoPointerDown.y);
4842
+ if (dx < 5 && dy < 5 && videoPointerDown.target.isVideoPlayBadgeHit(videoPointerDown.scene)) {
4843
+ void videoPointerDown.target.toggleVideoPlayback().then((ok) => {
4844
+ if (ok) startVideoRenderLoop();
4845
+ });
4846
+ }
4847
+ videoPointerDown = null;
4848
+ });
4709
4849
 
4710
4850
  // ─── Frame label drag & cursor handlers ───
4711
4851
  // Handles hover cursor and click-drag on frame labels (including nested frames).
@@ -5240,15 +5380,50 @@
5240
5380
  const files = e.dataTransfer?.files;
5241
5381
  if (!files || files.length === 0) return;
5242
5382
 
5243
- // Get drop position relative to canvas
5244
- const rect = canvasWrapper.getBoundingClientRect();
5245
- const dropX = e.clientX - rect.left;
5246
- 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;
5247
5387
 
5248
5388
  // Process each dropped file
5249
5389
  Array.from(files).forEach((file) => {
5250
- if (!file.type.startsWith('image/')) {
5251
- canvasLog('Skipped non-image file:', file.name);
5390
+ const isVideo = file.type.startsWith('video/');
5391
+ if (!file.type.startsWith('image/') && !isVideo) {
5392
+ canvasLog('Skipped non-media file:', file.name);
5393
+ return;
5394
+ }
5395
+
5396
+ if (isVideo) {
5397
+ const { video, objectUrl } = createVideoElementFromFile(file);
5398
+ capturePosterFromVideo(video).then((posterUrl) => {
5399
+ const maxWidth = canvas.width * 0.6;
5400
+ const maxHeight = canvas.height * 0.6;
5401
+ const tempImg = new Image();
5402
+ tempImg.onload = () => {
5403
+ let width = tempImg.width;
5404
+ let height = tempImg.height;
5405
+ if (width > maxWidth || height > maxHeight) {
5406
+ const scale = Math.min(maxWidth / width, maxHeight / height);
5407
+ width *= scale;
5408
+ height *= scale;
5409
+ }
5410
+ const videoShape = createImagePlaceholder({
5411
+ left: dropX - width / 2,
5412
+ top: dropY - height / 2,
5413
+ width,
5414
+ height,
5415
+ mediaKind: 'video'
5416
+ });
5417
+ canvas.add(videoShape);
5418
+ canvas.setActiveObject(videoShape);
5419
+ attachVideoElementToShape(videoShape, video, objectUrl);
5420
+ loadImageIntoShape(videoShape, posterUrl, file.name);
5421
+ canvasLog('Video dropped on canvas:', file.name);
5422
+ };
5423
+ tempImg.src = posterUrl;
5424
+ }).catch((err) => {
5425
+ console.error('Failed to load dropped video:', err);
5426
+ });
5252
5427
  return;
5253
5428
  }
5254
5429
 
@@ -5422,11 +5597,23 @@
5422
5597
  // only fires after real content modifications. A debounced timer there
5423
5598
  // calls onAutoSave after autosaveDelayMs of inactivity.
5424
5599
 
5425
- // Set canvas ready state
5426
- canvasLoadPhase = 'ready';
5427
- // Take the initial "empty canvas" snapshot so undo can return to it
5428
- // Use silent snapshot — don't mark dirty or trigger autosave for the initial state
5429
- 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
+ }
5430
5617
  onReady?.();
5431
5618
  } catch (fabricInitializationError) {
5432
5619
  console.error(`${initializationLogContext}: Failed to create Fabric canvas`, fabricInitializationError);
@@ -5440,6 +5627,10 @@
5440
5627
  });
5441
5628
 
5442
5629
  onDestroy(() => {
5630
+ if (videoRenderRaf) {
5631
+ cancelAnimationFrame(videoRenderRaf);
5632
+ videoRenderRaf = 0;
5633
+ }
5443
5634
  // CRITICAL: Notify the host to save canvas data BEFORE any cleanup.
5444
5635
  // This fires when Vite HMR rebuilds this component or the page navigates away.
5445
5636
  // At this point canvas is still valid — canvas.dispose() hasn't run yet.
@@ -5579,18 +5770,17 @@
5579
5770
  }
5580
5771
  });
5581
5772
 
5582
- function resizeObserver(node) {
5773
+ function resizeObserver(node: HTMLElement) {
5583
5774
  const observer = new ResizeObserver(entries => {
5775
+ if (!canvas) return;
5584
5776
  const entry = entries[0];
5777
+ if (!entry) return;
5585
5778
  const { width: w, height: h } = entry.contentRect;
5586
-
5587
- // Update component state
5588
- // width = w;
5589
- // height = h;
5779
+ if (w <= 0 || h <= 0) return;
5590
5780
 
5591
5781
  // Update canvas dimensions
5592
5782
  canvas.setDimensions({ width: w, height: h });
5593
- canvas.renderAll();
5783
+ canvas.requestRenderAll();
5594
5784
  });
5595
5785
  observer.observe(node);
5596
5786
 
@@ -6459,6 +6649,14 @@ function checkAndAddNewShapeToFrame(shape: any) {
6459
6649
  (shape as any)._shapeKey = shapeKey;
6460
6650
  (shape as any)._cornerRadiusMode = cornerRadiusMode;
6461
6651
  (shape as any)._cornerRoundness = 0;
6652
+ if (cornerRadiusMode === 'strokeRound') {
6653
+ const existingBg = (shape as any).backgroundColor;
6654
+ shape.set({
6655
+ fill: '',
6656
+ backgroundColor: existingBg || '#ffffff',
6657
+ });
6658
+ (shape as any)._iconFill = '#ffffff';
6659
+ }
6462
6660
  if (lockAspectRatio) {
6463
6661
  (shape as any)._lockAspectRatio = true;
6464
6662
  (shape as any)._forceLockAspectRatio = true;
@@ -6510,7 +6708,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
6510
6708
  top: pointer.y,
6511
6709
  originX: 'left',
6512
6710
  originY: 'top',
6513
- fill: '#ffffff',
6711
+ fill: getLibraryShapeMeta(pendingLibraryShapeKey).cornerRadiusMode === 'strokeRound' ? '' : '#ffffff',
6712
+ backgroundColor: getLibraryShapeMeta(pendingLibraryShapeKey).cornerRadiusMode === 'strokeRound' ? '#ffffff' : undefined,
6514
6713
  _fillOpacity: 1,
6515
6714
  stroke: '#374151',
6516
6715
  strokeWidth: 3,
@@ -7369,6 +7568,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
7369
7568
  top: number;
7370
7569
  width: number;
7371
7570
  height: number;
7571
+ mediaKind?: 'image' | 'video';
7372
7572
  }) {
7373
7573
  // Use ImageShape class for image placeholders. When converted to a widget,
7374
7574
  // the prototype is swapped to WidgetShape via upgradeToWidgetShape().
@@ -7391,7 +7591,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
7391
7591
  minScaleLimit: 0.01
7392
7592
  }) as any;
7393
7593
 
7394
- imageShape._customType = 'image';
7594
+ imageShape._customType = options.mediaKind === 'video' ? 'video' : 'image';
7395
7595
  imageShape._hasImage = false;
7396
7596
  imageShape._imageElement = null;
7397
7597
  imageShape._originalFilename = null;
@@ -7613,7 +7813,16 @@ function checkAndAddNewShapeToFrame(shape: any) {
7613
7813
  * Image Tool - Draw ImagePlaceholder on canvas
7614
7814
  */
7615
7815
  export function onSelectImageTool() {
7616
- setActiveTool('image', () => {
7816
+ startMediaPlaceholderTool('image');
7817
+ }
7818
+
7819
+ /** Video tool — same draw-to-place flow as Image, with a video placeholder and upload filter. */
7820
+ export function onSelectVideoTool() {
7821
+ startMediaPlaceholderTool('video');
7822
+ }
7823
+
7824
+ function startMediaPlaceholderTool(kind: 'image' | 'video') {
7825
+ setActiveTool(kind, () => {
7617
7826
  if (!canvas) {
7618
7827
  return;
7619
7828
  }
@@ -7714,7 +7923,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
7714
7923
  left: finalBounds.left,
7715
7924
  top: finalBounds.top,
7716
7925
  width: finalBounds.width,
7717
- height: finalBounds.height
7926
+ height: finalBounds.height,
7927
+ mediaKind: kind
7718
7928
  });
7719
7929
 
7720
7930
  canvas.add(placeholder);
@@ -7750,20 +7960,40 @@ function checkAndAddNewShapeToFrame(shape: any) {
7750
7960
  */
7751
7961
  function openFilePickerForPlaceholder(placeholder: any) {
7752
7962
  if (!canvas) return;
7963
+ const isVideo = placeholder._customType === 'video';
7753
7964
 
7754
7965
  const fileInput = document.createElement('input');
7755
7966
  fileInput.type = 'file';
7756
- fileInput.accept = 'image/*';
7967
+ fileInput.accept = isVideo ? 'video/*' : 'image/*';
7757
7968
  fileInput.style.display = 'none';
7758
7969
 
7759
7970
  fileInput.onchange = (event: Event) => {
7760
7971
  const target = event.target as HTMLInputElement;
7761
7972
  const file = target.files?.[0];
7762
7973
 
7763
- if (!file || !file.type.startsWith('image/')) {
7974
+ if (!file) {
7975
+ document.body.removeChild(fileInput);
7976
+ return;
7977
+ }
7978
+ if (isVideo && !file.type.startsWith('video/')) {
7764
7979
  document.body.removeChild(fileInput);
7765
7980
  return;
7766
7981
  }
7982
+ if (!isVideo && !file.type.startsWith('image/')) {
7983
+ document.body.removeChild(fileInput);
7984
+ return;
7985
+ }
7986
+
7987
+ if (isVideo) {
7988
+ bindVideoFileToShape(placeholder, file).then((posterUrl) => {
7989
+ replacePlaceholderWithImage(placeholder, posterUrl, file.name);
7990
+ }).catch((err) => {
7991
+ console.error('Video poster capture failed', err);
7992
+ }).finally(() => {
7993
+ if (fileInput.parentNode) document.body.removeChild(fileInput);
7994
+ });
7995
+ return;
7996
+ }
7767
7997
 
7768
7998
  const reader = new FileReader();
7769
7999
  reader.onload = (e) => {
@@ -7780,6 +8010,59 @@ function checkAndAddNewShapeToFrame(shape: any) {
7780
8010
  fileInput.click();
7781
8011
  }
7782
8012
 
8013
+ function createVideoElementFromFile(file: File): { video: HTMLVideoElement; objectUrl: string } {
8014
+ const objectUrl = URL.createObjectURL(file);
8015
+ const video = document.createElement('video');
8016
+ video.muted = true;
8017
+ video.loop = true;
8018
+ video.playsInline = true;
8019
+ video.preload = 'auto';
8020
+ video.src = objectUrl;
8021
+ return { video, objectUrl };
8022
+ }
8023
+
8024
+ function capturePosterFromVideo(video: HTMLVideoElement): Promise<string> {
8025
+ return new Promise((resolve, reject) => {
8026
+ const onSeeked = () => {
8027
+ try {
8028
+ const poster = document.createElement('canvas');
8029
+ poster.width = Math.max(1, video.videoWidth || 640);
8030
+ poster.height = Math.max(1, video.videoHeight || 360);
8031
+ poster.getContext('2d')?.drawImage(video, 0, 0, poster.width, poster.height);
8032
+ resolve(poster.toDataURL('image/jpeg', 0.85));
8033
+ } catch (err) {
8034
+ reject(err);
8035
+ }
8036
+ };
8037
+ video.onloadeddata = () => {
8038
+ try {
8039
+ video.currentTime = Math.min(0.15, Number.isFinite(video.duration) ? video.duration * 0.1 : 0.15);
8040
+ } catch (err) {
8041
+ reject(err);
8042
+ }
8043
+ };
8044
+ video.onseeked = onSeeked;
8045
+ video.onerror = () => reject(new Error('Could not load video'));
8046
+ });
8047
+ }
8048
+
8049
+ function attachVideoElementToShape(shape: any, video: HTMLVideoElement, objectUrl: string) {
8050
+ if (shape._videoObjectUrl && shape._videoObjectUrl !== objectUrl) {
8051
+ URL.revokeObjectURL(shape._videoObjectUrl);
8052
+ }
8053
+ shape._videoElement = video;
8054
+ shape._videoObjectUrl = objectUrl;
8055
+ video.addEventListener('play', () => startVideoRenderLoop());
8056
+ video.addEventListener('pause', () => canvas?.requestRenderAll());
8057
+ video.addEventListener('ended', () => canvas?.requestRenderAll());
8058
+ }
8059
+
8060
+ function bindVideoFileToShape(shape: any, file: File): Promise<string> {
8061
+ const { video, objectUrl } = createVideoElementFromFile(file);
8062
+ attachVideoElementToShape(shape, video, objectUrl);
8063
+ return capturePosterFromVideo(video);
8064
+ }
8065
+
7783
8066
  /**
7784
8067
  * Load image from URL into selected ImagePlaceholder (from PropsPanel)
7785
8068
  */
@@ -7800,20 +8083,32 @@ function checkAndAddNewShapeToFrame(shape: any) {
7800
8083
  // Works for both ImagePlaceholder and loaded Image
7801
8084
  const currentObject = selectedObject;
7802
8085
 
8086
+ const isVideo = (currentObject as any)._customType === 'video';
7803
8087
  const fileInput = document.createElement('input');
7804
8088
  fileInput.type = 'file';
7805
- fileInput.accept = 'image/*';
8089
+ fileInput.accept = isVideo ? 'video/*' : 'image/*';
7806
8090
  fileInput.style.display = 'none';
7807
8091
 
7808
8092
  fileInput.onchange = (event: Event) => {
7809
8093
  const target = event.target as HTMLInputElement;
7810
8094
  const file = target.files?.[0];
7811
8095
 
7812
- if (!file || !file.type.startsWith('image/')) {
8096
+ if (!file || (isVideo ? !file.type.startsWith('video/') : !file.type.startsWith('image/'))) {
7813
8097
  document.body.removeChild(fileInput);
7814
8098
  return;
7815
8099
  }
7816
-
8100
+
8101
+ if (isVideo) {
8102
+ bindVideoFileToShape(currentObject, file).then((posterUrl) => {
8103
+ replaceImageWithNewSource(currentObject, posterUrl, file.name);
8104
+ }).catch((err) => {
8105
+ console.error('Video poster capture failed', err);
8106
+ }).finally(() => {
8107
+ if (fileInput.parentNode) document.body.removeChild(fileInput);
8108
+ });
8109
+ return;
8110
+ }
8111
+
7817
8112
  const reader = new FileReader();
7818
8113
  reader.onload = (e) => {
7819
8114
  const dataUrl = e.target?.result as string;
@@ -8339,7 +8634,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8339
8634
  // Fill opacity (percentage stored separately from the baked rgba fill value)
8340
8635
  '_fillOpacity',
8341
8636
  // Library shape metadata
8342
- '_shapeKey', '_cornerRadiusMode',
8637
+ '_shapeKey', '_cornerRadiusMode', '_iconFill',
8343
8638
  '_boxStroke', '_boxStrokeWidth', '_boxStrokeDashArray',
8344
8639
  '_boxCornerRadius', '_boxFill',
8345
8640
  '_textPadding',
@@ -8358,6 +8653,37 @@ function checkAndAddNewShapeToFrame(shape: any) {
8358
8653
 
8359
8654
  // ── History: capture / restore ───────────────────────────────────────────
8360
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
+
8361
8687
  /**
8362
8688
  * Capture the current canvas object state as a JSON string.
8363
8689
  * Viewport (pan/zoom) is intentionally excluded — undo/redo only affects
@@ -8366,7 +8692,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8366
8692
  function captureHistorySnapshot(): string | null {
8367
8693
  if (!canvas) return null;
8368
8694
  try {
8369
- const json = canvas.toJSON(CANVAS_CUSTOM_PROPS);
8695
+ const json = safelySerializeCanvas(canvas, CANVAS_CUSTOM_PROPS);
8370
8696
  return JSON.stringify(json);
8371
8697
  } catch (err) {
8372
8698
  console.error('Canvas: captureHistorySnapshot failed', err);
@@ -8509,6 +8835,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8509
8835
  historyIndex--;
8510
8836
  canvasLog('Canvas: undo → history index', historyIndex);
8511
8837
  await restoreHistorySnapshot(historyStack[historyIndex]);
8838
+ _hasUnsavedChanges = true;
8839
+ onCanvasDirty?.();
8840
+ scheduleAutoSave();
8512
8841
  }
8513
8842
 
8514
8843
  /** Redo the previously undone action. No-op if at the newest state. */
@@ -8517,6 +8846,9 @@ function checkAndAddNewShapeToFrame(shape: any) {
8517
8846
  historyIndex++;
8518
8847
  canvasLog('Canvas: redo → history index', historyIndex);
8519
8848
  await restoreHistorySnapshot(historyStack[historyIndex]);
8849
+ _hasUnsavedChanges = true;
8850
+ onCanvasDirty?.();
8851
+ scheduleAutoSave();
8520
8852
  }
8521
8853
 
8522
8854
  /** Serialize the current canvas state to a JSON string */
@@ -8530,7 +8862,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8530
8862
  return null;
8531
8863
  }
8532
8864
  try {
8533
- const canvasJson = canvas.toJSON(CANVAS_CUSTOM_PROPS);
8865
+ const canvasJson = safelySerializeCanvas(canvas, CANVAS_CUSTOM_PROPS);
8534
8866
  // Diagnostic: log frame structure at save time to detect corruption
8535
8867
  (canvasJson.objects || []).forEach((obj: any) => {
8536
8868
  if (obj._isFrame || obj._customType === 'frame' || obj.type === 'FrameShape') {
@@ -8622,35 +8954,18 @@ function checkAndAddNewShapeToFrame(shape: any) {
8622
8954
 
8623
8955
  await canvas.loadFromJSON(canvasJson, reviver);
8624
8956
 
8625
- // Belt-and-suspenders: also walk all objects after load to catch any
8626
- // that the reviver may have missed (e.g. due to async timing).
8957
+ // Light pass: ensure any images without loaded elements are reloaded
8627
8958
  const allObjects = canvas.getObjects();
8628
- const restoreObject = (obj: any) => {
8629
- if (isFrameShape(obj)) {
8630
- reapplyFrameRender(obj);
8631
- getFrameChildren(obj).forEach(restoreObject);
8632
- } else if (obj._customType === 'image' || obj._hasImage || obj._imageUrl) {
8633
- upgradeToImageShape(obj);
8959
+ const checkUnloadedImages = (obj: any) => {
8960
+ if (obj._customType === 'image' || obj._hasImage || obj._imageUrl) {
8634
8961
  if (obj._imageUrl && !obj._imageElement) {
8635
- const img = new Image();
8636
- img.crossOrigin = 'anonymous';
8637
- img.onload = () => {
8638
- obj._imageElement = img;
8639
- obj._hasImage = true;
8640
- obj.dirty = true;
8641
- canvas?.requestRenderAll();
8642
- };
8643
- img.onerror = () => {
8644
- canvasWarn('Canvas: loadCanvas — failed to reload image (post-pass)', obj._imageUrl?.substring(0, 60));
8645
- };
8646
- img.src = obj._imageUrl;
8962
+ ImageShape.reloadImage(obj);
8647
8963
  }
8648
- } else if (String(obj.type || '').toLowerCase() === 'group') {
8649
- applyInteractiveGroupFlags(obj);
8650
- (obj.getObjects?.() || []).forEach(restoreObject);
8964
+ } else if (String(obj.type || '').toLowerCase() === 'group' || isFrameShape(obj)) {
8965
+ (obj.getObjects?.() || []).forEach(checkUnloadedImages);
8651
8966
  }
8652
8967
  };
8653
- allObjects.forEach(restoreObject);
8968
+ allObjects.forEach(checkUnloadedImages);
8654
8969
 
8655
8970
  // ── Orphan-repair pass ──────────────────────────────────────────────
8656
8971
  // Old/corrupted saves may have frame children at canvas level instead
@@ -8687,16 +9002,19 @@ function checkAndAddNewShapeToFrame(shape: any) {
8687
9002
  const spatialOrphans = canvas.getObjects().filter((obj: any) =>
8688
9003
  !isFrameShape(obj) &&
8689
9004
  !(obj as any)._isFrameBackground &&
9005
+ !(obj as any)._parentFrameId &&
8690
9006
  !obj.group && // not already inside any group
8691
9007
  String(obj.type || '').toLowerCase() !== 'group'
8692
9008
  );
8693
- for (const obj of spatialOrphans) {
8694
- const center = obj.getCenterPoint();
8695
- for (const frame of framesForSpatialRepair) {
8696
- if (isPointInsideFrame(frame, center)) {
8697
- canvasWarn('Canvas: loadCanvas — spatial repair: re-attaching', (obj as any).type, 'to frame', frame._labelText);
8698
- addObjectToFrame(frame, obj, canvas);
8699
- 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
+ }
8700
9018
  }
8701
9019
  }
8702
9020
  }
@@ -8724,11 +9042,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
8724
9042
 
8725
9043
  // Reset history after an external load so undo can't go back to
8726
9044
  // the previous canvas state and the loaded state becomes the new "initial".
8727
- historyStack = [];
8728
- 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;
8729
9049
  isRestoringHistory = false;
8730
9050
  canvasLoadPhase = 'ready';
8731
- takeHistorySnapshot(true);
8732
9051
  } catch (err) {
8733
9052
  console.error('Canvas: loadCanvas failed', err);
8734
9053
  isRestoringHistory = false;
@@ -8753,7 +9072,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
8753
9072
 
8754
9073
  // request a render all
8755
9074
  canvas.requestRenderAll();
8756
- takeHistorySnapshot(true);
9075
+ takeHistorySnapshot();
9076
+ onCanvasCleared?.();
8757
9077
 
8758
9078
  // log the clearing
8759
9079
  canvasLog('Clear all objects created');
@@ -9003,13 +9323,13 @@ function checkAndAddNewShapeToFrame(shape: any) {
9003
9323
  // Helper to apply fill color while preserving fill opacity
9004
9324
  const applyFillColor = (obj: any, clr: string) => {
9005
9325
  const fillOpacity = obj._fillOpacity ?? 1;
9006
- // If we have fill opacity < 1, convert to rgba
9007
- if (fillOpacity < 1) {
9008
- const rgbaColor = colorToRgba(clr, fillOpacity);
9009
- obj.set({ fill: rgbaColor });
9010
- } else {
9011
- obj.set({ fill: clr });
9326
+ const painted = fillOpacity < 1 ? colorToRgba(clr, fillOpacity) : clr;
9327
+ if (paintsFillOnStroke(obj)) {
9328
+ obj._iconFill = clr;
9329
+ obj.set({ fill: '', backgroundColor: painted });
9330
+ return;
9012
9331
  }
9332
+ obj.set({ fill: painted });
9013
9333
  };
9014
9334
 
9015
9335
  // If it's a Frame, update the background rect specifically (preserving fill opacity)
@@ -9045,8 +9365,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
9045
9365
  // Skip ImagePlaceholder — its fill background is hidden once an image is
9046
9366
  // loaded; only stroke properties are meaningful for this type.
9047
9367
  } else if ('fill' in obj) {
9048
- // For shapes: apply color at full opacity for uniformity
9049
- obj.set({ fill: color });
9368
+ if (paintsFillOnStroke(obj)) {
9369
+ obj._iconFill = color;
9370
+ obj.set({ fill: '', backgroundColor: color });
9371
+ } else {
9372
+ obj.set({ fill: color });
9373
+ }
9050
9374
  obj._fillOpacity = 1;
9051
9375
  }
9052
9376
  });
@@ -9209,6 +9533,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
9209
9533
  // Helper to apply fill opacity to a single shape object
9210
9534
  const applyFillOpacity = (obj: any) => {
9211
9535
  obj._fillOpacity = alpha;
9536
+ if (paintsFillOnStroke(obj)) {
9537
+ const base = obj._iconFill || obj.backgroundColor || '#FFFFFF';
9538
+ obj.set({ fill: '', backgroundColor: colorToRgba(base, alpha) });
9539
+ return;
9540
+ }
9212
9541
  const currentFill = obj.fill || '#FFFFFF';
9213
9542
  const rgbaFill = colorToRgba(currentFill, alpha);
9214
9543
  obj.set({ fill: rgbaFill });
@@ -11142,8 +11471,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11142
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>
11143
11472
 
11144
11473
  <!-- Pan/Zoom Panel: Position configurable via panZoomPosition prop -->
11145
- {#if !isCanvasLoading}
11146
- <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'}">
11147
11475
  <PanZoomPanel
11148
11476
  {zoomLevel}
11149
11477
  isPanActive={activeTool === 'pan'}
@@ -11163,13 +11491,12 @@ function checkAndAddNewShapeToFrame(shape: any) {
11163
11491
  onSave={saveNow}
11164
11492
  />
11165
11493
  </div>
11166
- {/if}
11167
11494
 
11168
11495
  <!-- Canvas -->
11169
11496
  <canvas class="canvas-el" bind:this={canvasEl}></canvas>
11170
11497
 
11171
11498
  {#if isCanvasLoading}
11172
- <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);">
11173
11500
  <div style="display:flex;flex-direction:column;align-items:center;gap:12px;">
11174
11501
  <div class="canvas-loader-spinner"></div>
11175
11502
  <span style="font-size:14px;font-weight:500;color:#6b7280;letter-spacing:0.02em;">Loading canvas…</span>
@@ -11185,8 +11512,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11185
11512
  {/if}
11186
11513
 
11187
11514
  <!-- Toolbar: Positioned at the bottom of the canvas -->
11188
- {#if !isCanvasLoading}
11189
- <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'}"
11190
11516
  {activeTool}
11191
11517
  {onSelectSelectTool}
11192
11518
  {onSelectEraseTool}
@@ -11196,6 +11522,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11196
11522
  {onSelectShapeTool}
11197
11523
  {onSelectFrameTool}
11198
11524
  {onSelectImageTool}
11525
+ onSelectVideoTool={onSelectVideoTool}
11199
11526
  {onGroupSelection}
11200
11527
  {onUngroupSelection}
11201
11528
  onDuplicateSelection={() => _duplicateSelected()}
@@ -11222,8 +11549,8 @@ function checkAndAddNewShapeToFrame(shape: any) {
11222
11549
  {onInsertLibraryShape}
11223
11550
  {onSelectLibraryShapeTool}
11224
11551
  {advancedFeatures}
11225
- />
11226
- {/if}
11552
+ {mediaBtsOnBar}
11553
+ />
11227
11554
 
11228
11555
  <!-- Props Panel: Only visible when an object is selected -->
11229
11556
  {#if selectedObject}