@widgetic/canvas 0.5.10 → 0.5.12

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.
@@ -15,6 +15,8 @@
15
15
  import CanvasToolbar from './CanvasToolbar.svelte';
16
16
  import ContextMenu from './ContextMenu.svelte';
17
17
  import PropsPanel from './props-panel/PropsPanel.svelte';
18
+ import WidgetSelectionLayer from './WidgetSelectionLayer.svelte';
19
+ import { getWidgetPreviewGeometry } from './widgetPreviewGeometry.js';
18
20
  import PanZoomPanel from './PanZoomPanel.svelte';
19
21
  import {
20
22
  createFrameShape, isFrameShape, reapplyFrameRender,
@@ -139,6 +141,8 @@
139
141
  export let style = '';
140
142
  /** Site /canvas embed sits flush under AppHeader — skip the 2px frame (double stroke). */
141
143
  export let showContainerFrame = true;
144
+ /** Mount native widget controls alongside host HTML previews, never over their entire body. */
145
+ export let widgetSelectionLayerTarget = '';
142
146
 
143
147
  // Callback: fires when user clicks/selects an object with screenshot
144
148
  export let onObjectClick: ((data: {
@@ -233,9 +237,14 @@
233
237
  /** Host persists canvases.primary_widget_id after Canvas paints the red stroke. */
234
238
  export let onSetPrimaryWidget: ((widgetId: string) => void) | null = null;
235
239
 
240
+ /** Throttled paint hook for HTML overlays (e.g. live WidgetShape iframes). */
241
+ export let onAfterRender: (() => void) | null = null;
242
+
236
243
  // Widget name resolver: given a widgetId, returns the widget name (or null).
237
244
  // Used by PropsPanel to display the linked widget's name.
238
245
  export let getWidgetName: ((widgetId: string) => string | null) | null = null;
246
+ /** Bumped when names change so PropsPanel re-resolves getWidgetName. */
247
+ export let widgetNameRevision: number = 0;
239
248
  /** Returns true when widgetId still exists in the host widget list. */
240
249
  export let isWidgetKnown: ((widgetId: string) => boolean) | null = null;
241
250
 
@@ -302,6 +311,8 @@
302
311
  const MIN_IMAGE_PLACEHOLDER_HEIGHT = 100;
303
312
  // Minimum size for image with loaded content (much smaller, just needs to be visible)
304
313
  const MIN_IMAGE_WITH_CONTENT_SIZE = 20;
314
+ // WidgetShapes (live iframe chrome) — keep a usable footprint when resizing
315
+ const MIN_WIDGET_SHAPE_SIZE = 50;
305
316
  let activeTool: ToolName = 'select';
306
317
  /**
307
318
  * The pointer handlers belonging to the currently active tool session.
@@ -1066,6 +1077,7 @@
1066
1077
  // Upgrade ImageShape → WidgetShape (swaps prototype, sets _isWidgetImage)
1067
1078
  upgradeToWidgetShape(widgetImage);
1068
1079
  clearWidgetShapeDefaultBorder(widgetImage);
1080
+ lockWidgetShapeBodyDrag(widgetImage);
1069
1081
 
1070
1082
  const newObjectId = `widget_img_${Date.now()}`;
1071
1083
  widgetImage._objectId = newObjectId;
@@ -1216,6 +1228,26 @@
1216
1228
  };
1217
1229
  }
1218
1230
 
1231
+ /**
1232
+ * Screen-space boxes for every WidgetShape currently on the canvas.
1233
+ * Used by the host to sync live iframe overlays (W3).
1234
+ */
1235
+ export function listWidgetShapeScreenRects() {
1236
+ if (!canvas || !canvasEl) return [];
1237
+ const results = [];
1238
+ for (const obj of canvas.getObjects() as any[]) {
1239
+ if (!obj?._isWidgetImage || !obj?._widgetId || obj._widgetOrphaned || !obj.visible) continue;
1240
+ const geometry = getWidgetPreviewGeometry(obj, canvas, canvasEl);
1241
+ if (!geometry || !geometry.matrix.every(Number.isFinite) || geometry.width < 4 || geometry.height < 4) continue;
1242
+ results.push({
1243
+ widgetId: String(obj._widgetId),
1244
+ hovered: String(obj._widgetId) === hoveredWidgetShapeId,
1245
+ ...geometry,
1246
+ });
1247
+ }
1248
+ return results;
1249
+ }
1250
+
1219
1251
  /**
1220
1252
  * Screen-space box of a widget shape plus the canvas element viewport.
1221
1253
  * Used to park Widget Details left/right of the shape.
@@ -1266,7 +1298,9 @@
1266
1298
  export function getWidgetShapeDataUrl(widgetId: string): string | null {
1267
1299
  if (!canvas) return null;
1268
1300
  const obj = canvas.getObjects().find(
1269
- (o: any) => o._widgetId === widgetId && o._isWidgetImage
1301
+ (o: any) =>
1302
+ o._widgetId === widgetId &&
1303
+ (o._isWidgetImage || o.type === 'WidgetShape' || o.type === 'ImageShape')
1270
1304
  );
1271
1305
  if (!obj) {
1272
1306
  canvasLog('Canvas: getWidgetShapeDataUrl — no widget shape found for', widgetId);
@@ -1280,6 +1314,26 @@
1280
1314
  }
1281
1315
  }
1282
1316
 
1317
+ /**
1318
+ * Hide (or restore) the Fabric screenshot under a live HTML WidgetShape overlay
1319
+ * so the old image does not ghost in the iframe padding.
1320
+ */
1321
+ export function setWidgetShapeLivePreviewHiddenImage(widgetId: string, hidden: boolean): void {
1322
+ if (!canvas || !widgetId) return;
1323
+ const obj = canvas.getObjects().find(
1324
+ (o: any) => o._widgetId === widgetId && o._isWidgetImage
1325
+ );
1326
+ if (!obj) {
1327
+ canvasLog('Canvas: setWidgetShapeLivePreviewHiddenImage — no shape for', widgetId);
1328
+ return;
1329
+ }
1330
+ const nextHidden = !!hidden;
1331
+ if ((obj as any)._hideImageForLivePreview === nextHidden) return;
1332
+ (obj as any)._hideImageForLivePreview = nextHidden;
1333
+ canvas.requestRenderAll();
1334
+ canvasLog('Canvas: setWidgetShapeLivePreviewHiddenImage', widgetId.substring(0, 8), nextHidden);
1335
+ }
1336
+
1283
1337
  /**
1284
1338
  * Add a new WidgetShape placeholder on the canvas for a widget that has no shape yet.
1285
1339
  * Places it in the visible viewport center. Returns the new object ID or null.
@@ -1318,6 +1372,7 @@
1318
1372
 
1319
1373
  upgradeToWidgetShape(placeholder);
1320
1374
  clearWidgetShapeDefaultBorder(placeholder);
1375
+ lockWidgetShapeBodyDrag(placeholder);
1321
1376
 
1322
1377
  const newObjectId = `widget_img_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1323
1378
  placeholder._objectId = newObjectId;
@@ -1554,6 +1609,9 @@
1554
1609
  preserveObjectStacking: true
1555
1610
  });
1556
1611
 
1612
+ // Programmatic focus return from the reusable properties panel.
1613
+ canvas.upperCanvasEl.tabIndex = -1;
1614
+
1557
1615
  // Let Fabric handle Shift+corner = proportional resize natively.
1558
1616
  // For _lockAspectRatio shapes, before:transform sets uniformScaling=true.
1559
1617
  (canvas as any).uniScaleKey = 'shiftKey';
@@ -1994,7 +2052,11 @@
1994
2052
  // Use smaller minimum when image is loaded (just needs to be visible)
1995
2053
  // Use larger minimum for placeholder (needs to fit UI text)
1996
2054
  const hasImage = target._hasImage && target._imageElement;
1997
- const minSize = hasImage ? MIN_IMAGE_WITH_CONTENT_SIZE : Math.min(MIN_IMAGE_PLACEHOLDER_WIDTH, MIN_IMAGE_PLACEHOLDER_HEIGHT);
2055
+ const minSize = target._isWidgetImage
2056
+ ? MIN_WIDGET_SHAPE_SIZE
2057
+ : hasImage
2058
+ ? MIN_IMAGE_WITH_CONTENT_SIZE
2059
+ : Math.min(MIN_IMAGE_PLACEHOLDER_WIDTH, MIN_IMAGE_PLACEHOLDER_HEIGHT);
1998
2060
 
1999
2061
  let needsClamp = false;
2000
2062
  let clampedScaleX = target.scaleX;
@@ -2092,7 +2154,11 @@
2092
2154
 
2093
2155
  // Use smaller minimum when image is loaded
2094
2156
  const hasImage = target._hasImage && target._imageElement;
2095
- const minSize = hasImage ? MIN_IMAGE_WITH_CONTENT_SIZE : Math.min(MIN_IMAGE_PLACEHOLDER_WIDTH, MIN_IMAGE_PLACEHOLDER_HEIGHT);
2157
+ const minSize = target._isWidgetImage
2158
+ ? MIN_WIDGET_SHAPE_SIZE
2159
+ : hasImage
2160
+ ? MIN_IMAGE_WITH_CONTENT_SIZE
2161
+ : Math.min(MIN_IMAGE_PLACEHOLDER_WIDTH, MIN_IMAGE_PLACEHOLDER_HEIGHT);
2096
2162
 
2097
2163
  // Enforce minimum size
2098
2164
  if (currentWidth < minSize || currentHeight < minSize) {
@@ -2237,6 +2303,14 @@
2237
2303
  isCurrentlyScaling = true;
2238
2304
  scalingTarget = transform.target;
2239
2305
  currentScalingCorner = transform.corner || null;
2306
+ // Block iframe pointer capture while resizing a WidgetShape
2307
+ if ((transform.target as any)?._isWidgetImage && (transform.target as any)?._widgetId) {
2308
+ try {
2309
+ window.dispatchEvent(new CustomEvent('widgetic:widget-shape-pointer-block', {
2310
+ detail: { widgetId: String((transform.target as any)._widgetId), active: true }
2311
+ }));
2312
+ } catch { /* ignore */ }
2313
+ }
2240
2314
 
2241
2315
  // ── Proportional resize lock: enable uniformScaling for the drag duration ──
2242
2316
  // For _lockAspectRatio shapes (icon symbols), set canvas.uniformScaling=true
@@ -2365,6 +2439,13 @@
2365
2439
 
2366
2440
  canvas.on('object:scaled', (opt: any) => {
2367
2441
  handleObjectScaled(opt);
2442
+ if ((opt?.target as any)?._isWidgetImage || (scalingTarget as any)?._isWidgetImage) {
2443
+ try {
2444
+ window.dispatchEvent(new CustomEvent('widgetic:widget-shape-pointer-block', {
2445
+ detail: { widgetId: null, active: false }
2446
+ }));
2447
+ } catch { /* ignore */ }
2448
+ }
2368
2449
  isCurrentlyScaling = false;
2369
2450
  scalingTarget = null;
2370
2451
  currentScalingCorner = null;
@@ -2379,6 +2460,13 @@
2379
2460
  if (scalingTarget?._originalCorners) {
2380
2461
  delete scalingTarget._originalCorners;
2381
2462
  }
2463
+ if ((scalingTarget as any)?._isWidgetImage) {
2464
+ try {
2465
+ window.dispatchEvent(new CustomEvent('widgetic:widget-shape-pointer-block', {
2466
+ detail: { widgetId: null, active: false }
2467
+ }));
2468
+ } catch { /* ignore */ }
2469
+ }
2382
2470
  isCurrentlyScaling = false;
2383
2471
  scalingTarget = null;
2384
2472
  currentScalingCorner = null;
@@ -2416,6 +2504,7 @@
2416
2504
  // Upgrade old Rect-based image placeholders to ImageShape (backward compat)
2417
2505
  upgradeToImageShape(obj);
2418
2506
  if ((obj as any)._isWidgetImage) {
2507
+ lockWidgetShapeBodyDrag(obj);
2419
2508
  if ((obj as any)._isPrimaryWidget) {
2420
2509
  obj.set({
2421
2510
  stroke: PRIMARY_WIDGET_STROKE,
@@ -4750,6 +4839,21 @@
4750
4839
  canvas.on('selection:created', handleSelectionCreated);
4751
4840
  canvas.on('selection:updated', handleSelectionUpdated);
4752
4841
  canvas.on('selection:cleared', handleSelectionCleared);
4842
+
4843
+ // Live HTML overlays (WidgetShape iframes) — one callback per animation frame max
4844
+ let afterRenderRaf = 0;
4845
+ canvas.on('after:render', () => {
4846
+ if (!onAfterRender) return;
4847
+ if (afterRenderRaf) return;
4848
+ afterRenderRaf = requestAnimationFrame(() => {
4849
+ afterRenderRaf = 0;
4850
+ try {
4851
+ onAfterRender?.();
4852
+ } catch (err) {
4853
+ canvasWarn('Canvas: onAfterRender failed', err);
4854
+ }
4855
+ });
4856
+ });
4753
4857
 
4754
4858
  // Double-click handler:
4755
4859
  // - Textbox: enter editing mode with all text selected
@@ -5273,8 +5377,11 @@
5273
5377
  // cumulative floating-point drift from ActiveSelection create/discard cycles.
5274
5378
  const saveAbsolutePositions = (objects: any[]) => {
5275
5379
  for (const obj of objects) {
5276
- obj._absLeft = obj.left;
5277
- obj._absTop = obj.top;
5380
+ // A serialized ActiveSelection may already have been recreated by
5381
+ // the history listener. Never cache its child-local coordinates.
5382
+ const position = obj.getXY();
5383
+ obj._absLeft = position.x;
5384
+ obj._absTop = position.y;
5278
5385
  }
5279
5386
  };
5280
5387
  const restoreAbsolutePositions = (objects: any[]) => {
@@ -5588,9 +5695,42 @@
5588
5695
  }
5589
5696
  }
5590
5697
  if (needsRender) canvas.requestRenderAll();
5698
+ // WidgetShape drag bar must also hide when the pointer leaves the canvas.
5699
+ setHoveredWidgetShape(null);
5591
5700
  });
5592
5701
  }
5593
5702
 
5703
+ // ── WidgetShape hover tracking + hover-select (W3 drag bar) ──
5704
+ // Tracks _isWidgetImage objects only. Fabric emits mouse:over/out per
5705
+ // object; the host overlay layer reads getHoveredWidgetShapeId() to
5706
+ // decide drag-bar visibility. Hover also selects a WidgetShape that
5707
+ // has no live iframe yet (same selection path as click) — pointer
5708
+ // then selects the iframe itself via the overlay's focus bridge.
5709
+ canvas.on('mouse:over', (hoverEvt: any) => {
5710
+ const target = hoverEvt?.target as any;
5711
+ if (!target?._isWidgetImage || !target._widgetId || target._widgetOrphaned) return;
5712
+ setHoveredWidgetShape(String(target._widgetId));
5713
+ if (!isWidgetShapeHoverSelectBlocked() && canvas) {
5714
+ const active = canvas.getActiveObject() as any;
5715
+ const alreadyActive = active === target
5716
+ || (String(active?.type || '').toLowerCase() === 'activeselection'
5717
+ && typeof active.getObjects === 'function'
5718
+ && active.getObjects().includes(target));
5719
+ if (!alreadyActive) {
5720
+ canvas.setActiveObject(target);
5721
+ canvas.requestRenderAll();
5722
+ canvasLog('Canvas: WidgetShape hover-selected (no iframe click path)', target._widgetId);
5723
+ }
5724
+ }
5725
+ });
5726
+ canvas.on('mouse:out', (hoverEvt: any) => {
5727
+ const target = hoverEvt?.target as any;
5728
+ if (!target?._isWidgetImage) return;
5729
+ if (hoveredWidgetShapeId === String(target._widgetId)) {
5730
+ setHoveredWidgetShape(null);
5731
+ }
5732
+ });
5733
+
5594
5734
  // NOTE: Autosave is NOT triggered by after:render — that event fires on
5595
5735
  // every redraw (pan, zoom, hover, selection) and would spam the API.
5596
5736
  // Instead, _hasUnsavedChanges is set inside takeHistorySnapshot() which
@@ -7556,6 +7696,90 @@ function checkAndAddNewShapeToFrame(shape: any) {
7556
7696
  obj.dirty = true;
7557
7697
  }
7558
7698
 
7699
+ /**
7700
+ * WidgetShapes move only via the HTML chrome drag bar (live iframe stays interactive).
7701
+ * Other shapes keep normal Fabric body-drag.
7702
+ */
7703
+ function lockWidgetShapeBodyDrag(obj: any): void {
7704
+ if (!obj?._isWidgetImage) return;
7705
+ obj.set({
7706
+ lockMovementX: true,
7707
+ lockMovementY: true,
7708
+ });
7709
+ obj.dirty = true;
7710
+ }
7711
+
7712
+ /** Translate a WidgetShape by screen-pixel delta (accounts for canvas zoom). */
7713
+ export function translateWidgetShapeByScreen(widgetId: string, dxScreen: number, dyScreen: number): boolean {
7714
+ if (!canvas || !widgetId) return false;
7715
+ const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId) as any;
7716
+ if (!obj) return false;
7717
+ const zoom = canvas.getZoom?.() || 1;
7718
+ // setXY accepts scene coordinates even while an ActiveSelection owns the object.
7719
+ // Movement locks only affect Fabric pointer transforms, not programmatic setters.
7720
+ const position = obj.getXY();
7721
+ const nextPosition = position.add(new FabricPoint(dxScreen / zoom, dyScreen / zoom));
7722
+ obj.setXY(nextPosition);
7723
+ // selection:cleared restores this canonical cache. Update it before any
7724
+ // deselection/history serialization, otherwise the header move snaps back.
7725
+ obj._absLeft = nextPosition.x;
7726
+ obj._absTop = nextPosition.y;
7727
+ obj.setCoords?.();
7728
+ lockWidgetShapeBodyDrag(obj);
7729
+ canvas.requestRenderAll();
7730
+ return true;
7731
+ }
7732
+
7733
+ /** Mark dirty + history after a chrome-bar drag ends (translateWidgetShapeByScreen alone skips this). */
7734
+ export function commitWidgetShapeTranslate(widgetId?: string | null): void {
7735
+ if (!canvas) return;
7736
+ if (widgetId) {
7737
+ const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId) as any;
7738
+ if (obj) obj.setCoords?.();
7739
+ }
7740
+ takeHistorySnapshot();
7741
+ canvasLog('Canvas: commitWidgetShapeTranslate', widgetId?.substring?.(0, 8) || 'unknown');
7742
+ }
7743
+
7744
+ /** Hover tracking for WidgetShape overlays (W3 drag bar) + hover-select. */
7745
+ let hoveredWidgetShapeId: string | null = null;
7746
+ /** Suppress hover-select while a Fabric transform (drag/resize/rotate) is active. */
7747
+ function isWidgetShapeHoverSelectBlocked(): boolean {
7748
+ if (!canvas) return true;
7749
+ if (activeTool !== 'select') return true;
7750
+ if ((canvas as any)._currentTransform) return true;
7751
+ if (activeEditingTextbox?.isEditing) return true;
7752
+ return false;
7753
+ }
7754
+
7755
+ /** Apply hover state change + notify the host overlay layer. */
7756
+ function setHoveredWidgetShape(widgetId: string | null): void {
7757
+ if (hoveredWidgetShapeId === widgetId) return;
7758
+ hoveredWidgetShapeId = widgetId;
7759
+ // Overlays sync on Fabric after:render; hover does not repaint, so force one.
7760
+ canvas?.requestRenderAll();
7761
+ }
7762
+
7763
+ export function selectWidgetShapeById(widgetId: string): boolean {
7764
+ if (!canvas || !widgetId) return false;
7765
+ const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId);
7766
+ if (!obj) return false;
7767
+ canvas.setActiveObject(obj);
7768
+ canvas.requestRenderAll();
7769
+ return true;
7770
+ }
7771
+
7772
+ export function getSelectedWidgetShapeId(): string | null {
7773
+ if (!canvas) return null;
7774
+ const active = canvas.getActiveObject() as any;
7775
+ if (active?._isWidgetImage && active?._widgetId) return String(active._widgetId);
7776
+ return null;
7777
+ }
7778
+
7779
+ export function getHoveredWidgetShapeId(): string | null {
7780
+ return hoveredWidgetShapeId;
7781
+ }
7782
+
7559
7783
  /**
7560
7784
  * Create an WidgetShape object (unified Rect that can display placeholder UI OR an image)
7561
7785
  * This is a custom Rect that:
@@ -8660,6 +8884,15 @@ function checkAndAddNewShapeToFrame(shape: any) {
8660
8884
  * then re-creates the ActiveSelection so the user's selection is not lost.
8661
8885
  */
8662
8886
  function safelySerializeCanvas(canvasInstance: Canvas, propertiesToInclude: string[]): any {
8887
+ // Commit current scene positions BEFORE discardActiveObject fires selection:cleared.
8888
+ // Header/property edits don't emit object:modified; native multi-selection history
8889
+ // also runs before that event's canonical-position listener. In either case the
8890
+ // old cache would otherwise overwrite the edit before toJSON can persist it.
8891
+ for (const obj of canvasInstance.getObjects()) {
8892
+ const position = obj.getXY();
8893
+ (obj as any)._absLeft = position.x;
8894
+ (obj as any)._absTop = position.y;
8895
+ }
8663
8896
  const activeObj = canvasInstance.getActiveObject();
8664
8897
  const isMultiSelection = !!(activeObj && (
8665
8898
  activeObj.type === 'activeselection' ||
@@ -11552,8 +11785,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
11552
11785
  {mediaBtsOnBar}
11553
11786
  />
11554
11787
 
11555
- <!-- Props Panel: Only visible when an object is selected -->
11556
- {#if selectedObject}
11788
+ {#if canvas && widgetSelectionLayerTarget}
11789
+ <WidgetSelectionLayer fabricCanvas={canvas} target={widgetSelectionLayerTarget} />
11790
+ {/if}
11791
+
11792
+ <!-- Preserve the panel wrapper and dismissal state throughout selection changes. -->
11557
11793
  <PropsPanel
11558
11794
  {selectedObject}
11559
11795
  {wireframeMode}
@@ -11603,6 +11839,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11603
11839
  {onRefreshScreenshot}
11604
11840
  onSetAsPrimary={handleSetPrimaryFromPanel}
11605
11841
  {getWidgetName}
11842
+ widgetNameRevision={widgetNameRevision}
11606
11843
  {isWidgetKnown}
11607
11844
  onRemoveOrphanedShape={() => { _deleteActiveObjects(); }}
11608
11845
  onBringToFront={bringToFront}
@@ -11618,7 +11855,6 @@ function checkAndAddNewShapeToFrame(shape: any) {
11618
11855
  onWidthChange={updateSelectedWidth}
11619
11856
  onHeightChange={updateSelectedHeight}
11620
11857
  />
11621
- {/if}
11622
11858
 
11623
11859
  <!-- Custom Context Menu (shown on right-click) -->
11624
11860
  <ContextMenu
@@ -7,6 +7,7 @@ declare const __propDef: {
7
7
  */ class?: string;
8
8
  style?: string;
9
9
  /** Site /canvas embed sits flush under AppHeader — skip the 2px frame (double stroke). */ showContainerFrame?: boolean;
10
+ /** Mount native widget controls alongside host HTML previews, never over their entire body. */ widgetSelectionLayerTarget?: string;
10
11
  onObjectClick?: ((data: {
11
12
  screenshot: string;
12
13
  objectType: string;
@@ -41,7 +42,9 @@ declare const __propDef: {
41
42
  onWidgetRename?: ((widgetId: string, newName: string) => void) | null;
42
43
  onRefreshScreenshot?: ((widgetId: string) => void) | null;
43
44
  /** Host persists canvases.primary_widget_id after Canvas paints the red stroke. */ onSetPrimaryWidget?: ((widgetId: string) => void) | null;
45
+ /** Throttled paint hook for HTML overlays (e.g. live WidgetShape iframes). */ onAfterRender?: (() => void) | null;
44
46
  getWidgetName?: ((widgetId: string) => string | null) | null;
47
+ /** Bumped when names change so PropsPanel re-resolves getWidgetName. */ widgetNameRevision?: number;
45
48
  /** Returns true when widgetId still exists in the host widget list. */ isWidgetKnown?: ((widgetId: string) => boolean) | null;
46
49
  showLogs?: boolean;
47
50
  shapeFillColor?: () => string;
@@ -54,6 +57,17 @@ declare const __propDef: {
54
57
  replaceObjectWithWidgetImage?: (objectId: string, widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
55
58
  updateWidgetImage?: (widgetId: string, newScreenshotDataUrl: string) => void;
56
59
  selectWidgetShape?: (widgetId: string) => boolean;
60
+ listWidgetShapeScreenRects?: () => {
61
+ left: number;
62
+ top: number;
63
+ width: number;
64
+ height: number;
65
+ localWidth: any;
66
+ localHeight: any;
67
+ matrix: any[];
68
+ widgetId: string;
69
+ hovered: boolean;
70
+ }[];
57
71
  getWidgetShapeScreenRect?: (widgetId: string) => {
58
72
  left: number;
59
73
  top: number;
@@ -75,6 +89,7 @@ declare const __propDef: {
75
89
  viewportHeight: number;
76
90
  } | null;
77
91
  getWidgetShapeDataUrl?: (widgetId: string) => string | null;
92
+ setWidgetShapeLivePreviewHiddenImage?: (widgetId: string, hidden: boolean) => void;
78
93
  addWidgetShape?: (widgetId: string, widgetName?: string, gridIndex?: number, totalCount?: number, previewImageUrl?: string | null) => string | null;
79
94
  getLinkedWidgetIds?: () => Set<string>;
80
95
  hydrateWidgetShapeMetadata?: (widgetsById: Map<string, {
@@ -93,6 +108,11 @@ declare const __propDef: {
93
108
  onSelectFrameTool?: () => void;
94
109
  setPrimaryWidgetShape?: (widgetId: string) => boolean;
95
110
  getPrimaryWidgetId?: () => string | null;
111
+ translateWidgetShapeByScreen?: (widgetId: string, dxScreen: number, dyScreen: number) => boolean;
112
+ commitWidgetShapeTranslate?: (widgetId?: string | null) => void;
113
+ selectWidgetShapeById?: (widgetId: string) => boolean;
114
+ getSelectedWidgetShapeId?: () => string | null;
115
+ getHoveredWidgetShapeId?: () => string | null;
96
116
  onSelectImageTool?: () => void;
97
117
  onSelectVideoTool?: () => void;
98
118
  onSelectPanTool?: () => void;
@@ -137,6 +157,17 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
137
157
  get replaceObjectWithWidgetImage(): (objectId: string, widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
138
158
  get updateWidgetImage(): (widgetId: string, newScreenshotDataUrl: string) => void;
139
159
  get selectWidgetShape(): (widgetId: string) => boolean;
160
+ get listWidgetShapeScreenRects(): () => {
161
+ left: number;
162
+ top: number;
163
+ width: number;
164
+ height: number;
165
+ localWidth: any;
166
+ localHeight: any;
167
+ matrix: any[];
168
+ widgetId: string;
169
+ hovered: boolean;
170
+ }[];
140
171
  get getWidgetShapeScreenRect(): (widgetId: string) => {
141
172
  left: number;
142
173
  top: number;
@@ -158,6 +189,7 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
158
189
  viewportHeight: number;
159
190
  } | null;
160
191
  get getWidgetShapeDataUrl(): (widgetId: string) => string | null;
192
+ get setWidgetShapeLivePreviewHiddenImage(): (widgetId: string, hidden: boolean) => void;
161
193
  get addWidgetShape(): (widgetId: string, widgetName?: string, gridIndex?: number, totalCount?: number, previewImageUrl?: string | null) => string | null;
162
194
  get getLinkedWidgetIds(): () => Set<string>;
163
195
  get hydrateWidgetShapeMetadata(): (widgetsById: Map<string, {
@@ -176,6 +208,11 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
176
208
  get onSelectFrameTool(): () => void;
177
209
  get setPrimaryWidgetShape(): (widgetId: string) => boolean;
178
210
  get getPrimaryWidgetId(): () => string | null;
211
+ get translateWidgetShapeByScreen(): (widgetId: string, dxScreen: number, dyScreen: number) => boolean;
212
+ get commitWidgetShapeTranslate(): (widgetId?: string | null) => void;
213
+ get selectWidgetShapeById(): (widgetId: string) => boolean;
214
+ get getSelectedWidgetShapeId(): () => string | null;
215
+ get getHoveredWidgetShapeId(): () => string | null;
179
216
  get onSelectImageTool(): () => void;
180
217
  get onSelectVideoTool(): () => void;
181
218
  get onSelectPanTool(): () => void;
@@ -0,0 +1,136 @@
1
+ <script>
2
+ import { onMount } from 'svelte';
3
+ import { Portal } from '@widgetic/design-system';
4
+ import { canvasWarn } from './canvasLogger';
5
+
6
+ let { fabricCanvas, target, class: className = '', style = '' } = $props();
7
+ let drawingCanvas;
8
+ function captureDrawingCanvas(node) {
9
+ drawingCanvas = node;
10
+ return { destroy() { drawingCanvas = null; } };
11
+ }
12
+ let controls = $state([]);
13
+ let viewport = $state({ left: 0, top: 0, width: 0, height: 0 });
14
+ let activePointer = null;
15
+ let lastPointerEvent = null;
16
+
17
+ // Route only control gestures through Fabric's existing DOM event handlers.
18
+ // Pointer capture prevents neighboring iframes from stealing the gesture.
19
+ function routeMouseEvent(type, event) {
20
+ fabricCanvas.upperCanvasEl.dispatchEvent(new MouseEvent(type, {
21
+ bubbles: true, cancelable: true, clientX: event.clientX, clientY: event.clientY,
22
+ button: 0, buttons: type === 'mouseup' ? 0 : 1,
23
+ shiftKey: event.shiftKey, altKey: event.altKey,
24
+ ctrlKey: event.ctrlKey, metaKey: event.metaKey,
25
+ }));
26
+ }
27
+
28
+ function startControl(event) {
29
+ if (event.button !== 0 || activePointer !== null) return;
30
+ event.preventDefault();
31
+ event.stopPropagation();
32
+ try {
33
+ event.currentTarget.setPointerCapture(event.pointerId);
34
+ activePointer = event.pointerId;
35
+ lastPointerEvent = event;
36
+ routeMouseEvent('mousedown', event);
37
+ } catch (error) {
38
+ activePointer = null;
39
+ canvasWarn('Canvas: could not start widget control gesture', error);
40
+ }
41
+ }
42
+
43
+ function moveControl(event) {
44
+ if (activePointer !== event.pointerId) return;
45
+ lastPointerEvent = event;
46
+ routeMouseEvent('mousemove', event);
47
+ }
48
+
49
+ function finishControl(event) {
50
+ if (activePointer !== event.pointerId) return;
51
+ activePointer = null;
52
+ routeMouseEvent('mouseup', event);
53
+ if (event.currentTarget?.hasPointerCapture?.(event.pointerId)) {
54
+ event.currentTarget.releasePointerCapture(event.pointerId);
55
+ }
56
+ }
57
+
58
+ function redraw() {
59
+ if (!drawingCanvas || fabricCanvas.disposed) return;
60
+ const upper = fabricCanvas.upperCanvasEl;
61
+ const bounds = upper.getBoundingClientRect();
62
+ viewport = { left: bounds.left, top: bounds.top, width: bounds.width, height: bounds.height };
63
+ if (drawingCanvas.width !== upper.width) drawingCanvas.width = upper.width;
64
+ if (drawingCanvas.height !== upper.height) drawingCanvas.height = upper.height;
65
+ const context = drawingCanvas.getContext('2d');
66
+ if (!context) return;
67
+ context.setTransform(1, 0, 0, 1, 0, 0);
68
+ context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height);
69
+ const selected = fabricCanvas.getActiveObject();
70
+ if (!selected?._isWidgetImage || fabricCanvas.skipTargetFind || fabricCanvas.isDrawingMode) {
71
+ controls = [];
72
+ return;
73
+ }
74
+ const retina = fabricCanvas.getRetinaScaling();
75
+ context.setTransform(retina, 0, 0, retina, 0, 0);
76
+ // Red primary stroke is part of the object, not the selection border.
77
+ // Paint it with the same viewport/object matrices above the HTML preview.
78
+ if (selected._isPrimaryWidget && selected.strokeWidth) {
79
+ context.save();
80
+ context.transform(...fabricCanvas.viewportTransform);
81
+ context.transform(...selected.calcTransformMatrix());
82
+ context.strokeStyle = selected.stroke;
83
+ context.lineWidth = selected.strokeWidth;
84
+ context.strokeRect(-selected.width / 2, -selected.height / 2, selected.width, selected.height);
85
+ context.restore();
86
+ }
87
+ selected.setCoords();
88
+ selected._renderControls(context);
89
+ const scaleX = bounds.width / fabricCanvas.getWidth();
90
+ 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 [];
94
+ 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) }];
96
+ });
97
+ }
98
+
99
+ onMount(() => {
100
+ let animationFrame = 0;
101
+ function scheduleRedraw() {
102
+ if (animationFrame) return;
103
+ animationFrame = requestAnimationFrame(() => {
104
+ animationFrame = 0;
105
+ redraw();
106
+ });
107
+ }
108
+ const disposeRender = fabricCanvas.on('after:render', scheduleRedraw);
109
+ const observer = new ResizeObserver(scheduleRedraw);
110
+ observer.observe(fabricCanvas.upperCanvasEl);
111
+ window.addEventListener('scroll', scheduleRedraw, true);
112
+ window.addEventListener('resize', scheduleRedraw);
113
+ scheduleRedraw();
114
+ return () => {
115
+ if (activePointer !== null && lastPointerEvent && !fabricCanvas.disposed) finishControl(lastPointerEvent);
116
+ disposeRender();
117
+ observer.disconnect();
118
+ window.removeEventListener('scroll', scheduleRedraw, true);
119
+ window.removeEventListener('resize', scheduleRedraw);
120
+ cancelAnimationFrame(animationFrame);
121
+ };
122
+ });
123
+ </script>
124
+
125
+ <Portal {target} style="z-index: 70; pointer-events: none;">
126
+ <div class="canvas-widget-selection-layer fixed pointer-events-none overflow-hidden {className}" style="left: {viewport.left}px; top: {viewport.top}px; width: {viewport.width}px; height: {viewport.height}px; pointer-events: none; {style}">
127
+ <canvas class="canvas-widget-selection-paint h-full w-full pointer-events-none" use:captureDrawingCanvas aria-hidden="true"></canvas>
128
+ <svg class="canvas-widget-control-hit-regions absolute inset-0 h-full w-full pointer-events-none" aria-hidden="true">
129
+ {#each controls as control (control.key)}
130
+ <!-- Fabric controls are pointer affordances; equivalent numeric dimensions remain in PropsPanel. -->
131
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
132
+ <polygon class="canvas-widget-control-hit-region pointer-events-auto touch-none" data-control={control.key} points={control.points} fill="transparent" style="cursor: {control.cursor};" onpointerdown={startControl} onpointermove={moveControl} onpointerup={finishControl} onpointercancel={finishControl} onlostpointercapture={finishControl} />
133
+ {/each}
134
+ </svg>
135
+ </div>
136
+ </Portal>
@@ -0,0 +1,23 @@
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
+ import { SvelteComponentTyped } from "svelte";
14
+ declare const __propDef: {
15
+ props: {
16
+ [x: string]: never;
17
+ };
18
+ events: {
19
+ [evt: string]: CustomEvent<any>;
20
+ };
21
+ slots: {};
22
+ };
23
+ export {};
@@ -90,6 +90,8 @@
90
90
 
91
91
  // Widget name resolver: given a widgetId, returns the widget name (or null)
92
92
  export let getWidgetName: ((widgetId: string) => string | null) | null = null;
93
+ /** Bumped when names change so PropsPanel re-reads getWidgetName. */
94
+ export let widgetNameRevision: number = 0;
93
95
  /** Returns false when the linked widget was deleted or moved off this canvas. */
94
96
  export let isWidgetKnown: ((widgetId: string) => boolean) | null = null;
95
97
  /** Remove the selected orphaned widget shape from the canvas. */
@@ -149,7 +151,9 @@
149
151
  $: isDuplicating = !!selectedObject?._isDuplicating;
150
152
  $: isConverting = !!selectedObject?._isConverting;
151
153
  $: showWidgetLoader = isPendingWidgetLink || isDuplicating || isConverting;
152
- $: resolvedWidgetName = (widgetId && getWidgetName) ? getWidgetName(widgetId) : null;
154
+ $: resolvedWidgetName = (widgetNameRevision, widgetId && getWidgetName)
155
+ ? getWidgetName(widgetId)
156
+ : null;
153
157
  $: isOrphanedWidgetShape = !!(
154
158
  widgetId
155
159
  && hasWidgetId
@@ -387,6 +391,21 @@
387
391
  }
388
392
  }
389
393
 
394
+ // Dismissal belongs to this selection, not to property-change notifications.
395
+ let dismissedSelection = null;
396
+ let previousSelection = null;
397
+ $: if (selectedObject !== previousSelection) {
398
+ previousSelection = selectedObject;
399
+ dismissedSelection = null;
400
+ }
401
+ $: panelHidden = !selectedObject || dismissedSelection === selectedObject;
402
+
403
+ function dismissPanel() {
404
+ dismissedSelection = selectedObject;
405
+ // Return keyboard focus to the canvas without discarding its selection.
406
+ selectedObject?.canvas?.upperCanvasEl?.focus({ preventScroll: true });
407
+ }
408
+
390
409
  // Panel minimize/maximize state: minimized shows only essential props
391
410
  let isMinimized = true;
392
411
 
@@ -415,7 +434,7 @@
415
434
  $: selectedObject, isMinimized, setTimeout(checkOverflow, 50);
416
435
  </script>
417
436
 
418
- <div class="{className ? className + ' ' : ''}props-panel-el px-3 py-3" style={style}>
437
+ <div class="{className ? className + ' ' : ''}props-panel-el relative px-3 py-3 {panelHidden ? 'invisible pointer-events-none' : ''}" aria-hidden={panelHidden} inert={panelHidden} style={style}>
419
438
 
420
439
  <!-- Sticky Header: Selected Object Type + Children count + minimize toggle -->
421
440
  <div class="props-panel-sticky-header">
@@ -439,7 +458,17 @@
439
458
  </button>
440
459
  </Tooltip>
441
460
  </div>
442
-
461
+
462
+ <button
463
+ type="button"
464
+ class="props-panel-close-button absolute right-0 top-0 flex h-5 w-5 items-center justify-center rounded text-grey5 hover:bg-grey2 hover:text-dark focus:outline-none focus:shadow-none focus-visible:bg-grey2 focus-visible:text-dark focus-visible:outline-none focus-visible:shadow-none"
465
+ aria-label="Close properties panel"
466
+ title="Close properties panel"
467
+ onclick={dismissPanel}
468
+ >
469
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18" /></svg>
470
+ </button>
471
+
443
472
  <!-- Children count: shown for frames, groups, and multi-selections -->
444
473
  {#if childrenCount !== null}
445
474
  <div class="children-count-row">
@@ -1364,16 +1393,19 @@
1364
1393
  display: flex;
1365
1394
  gap: 4px;
1366
1395
  padding-bottom: 8px;
1367
- align-items: baseline;
1396
+ align-items: flex-end;
1368
1397
  }
1369
1398
 
1370
1399
  .minimize-toggle-bt {
1371
1400
  margin-left: auto;
1401
+ /* Clear the corner close button parked beside the panel edge. */
1402
+ margin-right: 0px;
1403
+ margin-bottom: -2px;
1372
1404
  display: flex;
1373
1405
  align-items: center;
1374
1406
  justify-content: center;
1375
- width: 22px;
1376
- height: 22px;
1407
+ width: 18px;
1408
+ height: 18px;
1377
1409
  background: transparent;
1378
1410
  border: 1px solid transparent;
1379
1411
  border-radius: 4px;
@@ -1382,7 +1414,6 @@
1382
1414
  padding: 0;
1383
1415
  flex-shrink: 0;
1384
1416
  transition: all 0.15s ease;
1385
- align-self: center;
1386
1417
  }
1387
1418
  .minimize-toggle-bt:hover {
1388
1419
  background: #f3f4f6;
@@ -51,6 +51,7 @@ declare const __propDef: {
51
51
  onRefreshScreenshot?: ((widgetId: string) => void) | null;
52
52
  onSetAsPrimary?: ((widgetId: string) => void) | null;
53
53
  getWidgetName?: ((widgetId: string) => string | null) | null;
54
+ /** Bumped when names change so PropsPanel re-reads getWidgetName. */ widgetNameRevision?: number;
54
55
  /** Returns false when the linked widget was deleted or moved off this canvas. */ isWidgetKnown?: ((widgetId: string) => boolean) | null;
55
56
  /** Remove the selected orphaned widget shape from the canvas. */ onRemoveOrphanedShape?: (() => void) | null;
56
57
  onBringToFront?: () => void;
@@ -85,7 +85,12 @@ export class ImageShape extends Rect {
85
85
  const useVideo = !!(video && video.readyState >= 2);
86
86
  const source = useVideo ? video : (img && img.complete && img.naturalWidth > 0 ? img : null);
87
87
  const imgReady = !!source;
88
- if (source) {
88
+ // Live HTML overlay active: paint solid fill so the old screenshot does not ghost in the padding.
89
+ if (this._isWidgetImage && this._hideImageForLivePreview) {
90
+ ctx.fillStyle = '#f3f4f6';
91
+ ctx.fillRect(-w / 2, -h / 2, w, h);
92
+ }
93
+ else if (source) {
89
94
  if (this._isWidgetImage && img && img.complete && img.naturalWidth > 0 && !useVideo) {
90
95
  const imgW = img.naturalWidth;
91
96
  const imgH = img.naturalHeight;
@@ -8,6 +8,11 @@ export declare class WidgetShape extends ImageShape {
8
8
  _widgetName: string | null;
9
9
  /** True when _widgetId no longer exists in the host widget list (deleted or moved). */
10
10
  _widgetOrphaned: boolean;
11
+ /**
12
+ * Runtime-only: when live HTML iframe overlays the shape, hide the screenshot
13
+ * (draw a solid fill instead) so it does not ghost in the padding. Not serialized.
14
+ */
15
+ _hideImageForLivePreview: boolean;
11
16
  /** Custom placeholder overlay: replace generic "Drop image" text with the widget name. */
12
17
  _render(ctx: CanvasRenderingContext2D): void;
13
18
  private _renderWidgetPlaceholder;
@@ -34,6 +34,11 @@ export class WidgetShape extends ImageShape {
34
34
  _widgetName = null;
35
35
  /** True when _widgetId no longer exists in the host widget list (deleted or moved). */
36
36
  _widgetOrphaned = false;
37
+ /**
38
+ * Runtime-only: when live HTML iframe overlays the shape, hide the screenshot
39
+ * (draw a solid fill instead) so it does not ghost in the padding. Not serialized.
40
+ */
41
+ _hideImageForLivePreview = false;
37
42
  /** Custom placeholder overlay: replace generic "Drop image" text with the widget name. */
38
43
  _render(ctx) {
39
44
  const hasImage = this._hasImage && this._imageElement;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Local widget pixels -> CSS viewport pixels (no selection padding/stroke).
3
+ * Fabric matrices include rotation, skew, flips and owning groups. CSS starts
4
+ * at the top-left, while Fabric transforms around the object's center.
5
+ */
6
+ export function getWidgetPreviewGeometry(object: any, canvas: any, canvasElement: any): {
7
+ left: number;
8
+ top: number;
9
+ width: number;
10
+ height: number;
11
+ localWidth: any;
12
+ localHeight: any;
13
+ matrix: any[];
14
+ } | null;
@@ -0,0 +1,33 @@
1
+ import { util } from 'fabric';
2
+
3
+ /**
4
+ * Local widget pixels -> CSS viewport pixels (no selection padding/stroke).
5
+ * Fabric matrices include rotation, skew, flips and owning groups. CSS starts
6
+ * at the top-left, while Fabric transforms around the object's center.
7
+ */
8
+ export function getWidgetPreviewGeometry(object, canvas, canvasElement) {
9
+ if (!canvas || !canvasElement) return null;
10
+ const bounds = canvasElement.getBoundingClientRect();
11
+ const viewport = canvas.viewportTransform || [1, 0, 0, 1, 0, 0];
12
+ const [a, b, c, d, centerX, centerY] = util.multiplyTransformMatrices(viewport, object.calcTransformMatrix());
13
+ const cssScaleX = bounds.width / canvas.getWidth();
14
+ const cssScaleY = bounds.height / canvas.getHeight();
15
+ const localWidth = object.width;
16
+ const localHeight = object.height;
17
+ const matrix = [
18
+ a * cssScaleX, b * cssScaleY, c * cssScaleX, d * cssScaleY,
19
+ bounds.left + (centerX - a * localWidth / 2 - c * localHeight / 2) * cssScaleX,
20
+ bounds.top + (centerY - b * localWidth / 2 - d * localHeight / 2) * cssScaleY,
21
+ ];
22
+ const corners = [[0, 0], [localWidth, 0], [localWidth, localHeight], [0, localHeight]]
23
+ .map(([x, y]) => ({ x: matrix[0] * x + matrix[2] * y + matrix[4], y: matrix[1] * x + matrix[3] * y + matrix[5] }));
24
+ const left = Math.min(...corners.map(point => point.x));
25
+ const top = Math.min(...corners.map(point => point.y));
26
+ // Chrome attaches to these body bounds; selection controls do not add clearance.
27
+ return {
28
+ left, top,
29
+ width: Math.max(...corners.map(point => point.x)) - left,
30
+ height: Math.max(...corners.map(point => point.y)) - top,
31
+ localWidth, localHeight, matrix,
32
+ };
33
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/canvas",
3
- "version": "0.5.10",
3
+ "version": "0.5.12",
4
4
  "type": "module",
5
5
  "svelte": "./dist/index.js",
6
6
  "module": "./dist/index.js",