@widgetic/canvas 0.5.11 → 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: {
@@ -239,6 +243,8 @@
239
243
  // Widget name resolver: given a widgetId, returns the widget name (or null).
240
244
  // Used by PropsPanel to display the linked widget's name.
241
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;
242
248
  /** Returns true when widgetId still exists in the host widget list. */
243
249
  export let isWidgetKnown: ((widgetId: string) => boolean) | null = null;
244
250
 
@@ -305,6 +311,8 @@
305
311
  const MIN_IMAGE_PLACEHOLDER_HEIGHT = 100;
306
312
  // Minimum size for image with loaded content (much smaller, just needs to be visible)
307
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;
308
316
  let activeTool: ToolName = 'select';
309
317
  /**
310
318
  * The pointer handlers belonging to the currently active tool session.
@@ -1224,31 +1232,17 @@
1224
1232
  * Screen-space boxes for every WidgetShape currently on the canvas.
1225
1233
  * Used by the host to sync live iframe overlays (W3).
1226
1234
  */
1227
- export function listWidgetShapeScreenRects(): Array<{
1228
- widgetId: string;
1229
- left: number;
1230
- top: number;
1231
- width: number;
1232
- height: number;
1233
- }> {
1235
+ export function listWidgetShapeScreenRects() {
1234
1236
  if (!canvas || !canvasEl) return [];
1235
- const results: Array<{
1236
- widgetId: string;
1237
- left: number;
1238
- top: number;
1239
- width: number;
1240
- height: number;
1241
- }> = [];
1237
+ const results = [];
1242
1238
  for (const obj of canvas.getObjects() as any[]) {
1243
- if (!obj?._isWidgetImage || !obj?._widgetId || obj._widgetOrphaned) continue;
1244
- const rect = objectSceneToScreenRect(obj);
1245
- if (!rect || rect.width < 4 || rect.height < 4) continue;
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;
1246
1242
  results.push({
1247
1243
  widgetId: String(obj._widgetId),
1248
- left: rect.left,
1249
- top: rect.top,
1250
- width: rect.width,
1251
- height: rect.height,
1244
+ hovered: String(obj._widgetId) === hoveredWidgetShapeId,
1245
+ ...geometry,
1252
1246
  });
1253
1247
  }
1254
1248
  return results;
@@ -1304,7 +1298,9 @@
1304
1298
  export function getWidgetShapeDataUrl(widgetId: string): string | null {
1305
1299
  if (!canvas) return null;
1306
1300
  const obj = canvas.getObjects().find(
1307
- (o: any) => o._widgetId === widgetId && o._isWidgetImage
1301
+ (o: any) =>
1302
+ o._widgetId === widgetId &&
1303
+ (o._isWidgetImage || o.type === 'WidgetShape' || o.type === 'ImageShape')
1308
1304
  );
1309
1305
  if (!obj) {
1310
1306
  canvasLog('Canvas: getWidgetShapeDataUrl — no widget shape found for', widgetId);
@@ -1318,6 +1314,26 @@
1318
1314
  }
1319
1315
  }
1320
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
+
1321
1337
  /**
1322
1338
  * Add a new WidgetShape placeholder on the canvas for a widget that has no shape yet.
1323
1339
  * Places it in the visible viewport center. Returns the new object ID or null.
@@ -1593,6 +1609,9 @@
1593
1609
  preserveObjectStacking: true
1594
1610
  });
1595
1611
 
1612
+ // Programmatic focus return from the reusable properties panel.
1613
+ canvas.upperCanvasEl.tabIndex = -1;
1614
+
1596
1615
  // Let Fabric handle Shift+corner = proportional resize natively.
1597
1616
  // For _lockAspectRatio shapes, before:transform sets uniformScaling=true.
1598
1617
  (canvas as any).uniScaleKey = 'shiftKey';
@@ -2033,7 +2052,11 @@
2033
2052
  // Use smaller minimum when image is loaded (just needs to be visible)
2034
2053
  // Use larger minimum for placeholder (needs to fit UI text)
2035
2054
  const hasImage = target._hasImage && target._imageElement;
2036
- 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);
2037
2060
 
2038
2061
  let needsClamp = false;
2039
2062
  let clampedScaleX = target.scaleX;
@@ -2131,7 +2154,11 @@
2131
2154
 
2132
2155
  // Use smaller minimum when image is loaded
2133
2156
  const hasImage = target._hasImage && target._imageElement;
2134
- 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);
2135
2162
 
2136
2163
  // Enforce minimum size
2137
2164
  if (currentWidth < minSize || currentHeight < minSize) {
@@ -2276,6 +2303,14 @@
2276
2303
  isCurrentlyScaling = true;
2277
2304
  scalingTarget = transform.target;
2278
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
+ }
2279
2314
 
2280
2315
  // ── Proportional resize lock: enable uniformScaling for the drag duration ──
2281
2316
  // For _lockAspectRatio shapes (icon symbols), set canvas.uniformScaling=true
@@ -2404,6 +2439,13 @@
2404
2439
 
2405
2440
  canvas.on('object:scaled', (opt: any) => {
2406
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
+ }
2407
2449
  isCurrentlyScaling = false;
2408
2450
  scalingTarget = null;
2409
2451
  currentScalingCorner = null;
@@ -2418,6 +2460,13 @@
2418
2460
  if (scalingTarget?._originalCorners) {
2419
2461
  delete scalingTarget._originalCorners;
2420
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
+ }
2421
2470
  isCurrentlyScaling = false;
2422
2471
  scalingTarget = null;
2423
2472
  currentScalingCorner = null;
@@ -5328,8 +5377,11 @@
5328
5377
  // cumulative floating-point drift from ActiveSelection create/discard cycles.
5329
5378
  const saveAbsolutePositions = (objects: any[]) => {
5330
5379
  for (const obj of objects) {
5331
- obj._absLeft = obj.left;
5332
- 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;
5333
5385
  }
5334
5386
  };
5335
5387
  const restoreAbsolutePositions = (objects: any[]) => {
@@ -5643,9 +5695,42 @@
5643
5695
  }
5644
5696
  }
5645
5697
  if (needsRender) canvas.requestRenderAll();
5698
+ // WidgetShape drag bar must also hide when the pointer leaves the canvas.
5699
+ setHoveredWidgetShape(null);
5646
5700
  });
5647
5701
  }
5648
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
+
5649
5734
  // NOTE: Autosave is NOT triggered by after:render — that event fires on
5650
5735
  // every redraw (pan, zoom, hover, selection) and would spam the API.
5651
5736
  // Instead, _hasUnsavedChanges is set inside takeHistorySnapshot() which
@@ -7630,21 +7715,51 @@ function checkAndAddNewShapeToFrame(shape: any) {
7630
7715
  const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId) as any;
7631
7716
  if (!obj) return false;
7632
7717
  const zoom = canvas.getZoom?.() || 1;
7633
- const dx = dxScreen / zoom;
7634
- const dy = dyScreen / zoom;
7635
- // Temporarily unlock so Fabric applies left/top without fighting locks
7636
- obj.set({
7637
- lockMovementX: false,
7638
- lockMovementY: false,
7639
- left: (obj.left ?? 0) + dx,
7640
- top: (obj.top ?? 0) + dy,
7641
- });
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;
7642
7727
  obj.setCoords?.();
7643
7728
  lockWidgetShapeBodyDrag(obj);
7644
7729
  canvas.requestRenderAll();
7645
7730
  return true;
7646
7731
  }
7647
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
+
7648
7763
  export function selectWidgetShapeById(widgetId: string): boolean {
7649
7764
  if (!canvas || !widgetId) return false;
7650
7765
  const obj = canvas.getObjects().find((o: any) => o._isWidgetImage && o._widgetId === widgetId);
@@ -7661,6 +7776,10 @@ function checkAndAddNewShapeToFrame(shape: any) {
7661
7776
  return null;
7662
7777
  }
7663
7778
 
7779
+ export function getHoveredWidgetShapeId(): string | null {
7780
+ return hoveredWidgetShapeId;
7781
+ }
7782
+
7664
7783
  /**
7665
7784
  * Create an WidgetShape object (unified Rect that can display placeholder UI OR an image)
7666
7785
  * This is a custom Rect that:
@@ -8765,6 +8884,15 @@ function checkAndAddNewShapeToFrame(shape: any) {
8765
8884
  * then re-creates the ActiveSelection so the user's selection is not lost.
8766
8885
  */
8767
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
+ }
8768
8896
  const activeObj = canvasInstance.getActiveObject();
8769
8897
  const isMultiSelection = !!(activeObj && (
8770
8898
  activeObj.type === 'activeselection' ||
@@ -11657,8 +11785,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
11657
11785
  {mediaBtsOnBar}
11658
11786
  />
11659
11787
 
11660
- <!-- Props Panel: Only visible when an object is selected -->
11661
- {#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. -->
11662
11793
  <PropsPanel
11663
11794
  {selectedObject}
11664
11795
  {wireframeMode}
@@ -11708,6 +11839,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
11708
11839
  {onRefreshScreenshot}
11709
11840
  onSetAsPrimary={handleSetPrimaryFromPanel}
11710
11841
  {getWidgetName}
11842
+ widgetNameRevision={widgetNameRevision}
11711
11843
  {isWidgetKnown}
11712
11844
  onRemoveOrphanedShape={() => { _deleteActiveObjects(); }}
11713
11845
  onBringToFront={bringToFront}
@@ -11723,7 +11855,6 @@ function checkAndAddNewShapeToFrame(shape: any) {
11723
11855
  onWidthChange={updateSelectedWidth}
11724
11856
  onHeightChange={updateSelectedHeight}
11725
11857
  />
11726
- {/if}
11727
11858
 
11728
11859
  <!-- Custom Context Menu (shown on right-click) -->
11729
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;
@@ -43,6 +44,7 @@ declare const __propDef: {
43
44
  /** Host persists canvases.primary_widget_id after Canvas paints the red stroke. */ onSetPrimaryWidget?: ((widgetId: string) => void) | null;
44
45
  /** Throttled paint hook for HTML overlays (e.g. live WidgetShape iframes). */ onAfterRender?: (() => void) | null;
45
46
  getWidgetName?: ((widgetId: string) => string | null) | null;
47
+ /** Bumped when names change so PropsPanel re-resolves getWidgetName. */ widgetNameRevision?: number;
46
48
  /** Returns true when widgetId still exists in the host widget list. */ isWidgetKnown?: ((widgetId: string) => boolean) | null;
47
49
  showLogs?: boolean;
48
50
  shapeFillColor?: () => string;
@@ -55,13 +57,17 @@ declare const __propDef: {
55
57
  replaceObjectWithWidgetImage?: (objectId: string, widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
56
58
  updateWidgetImage?: (widgetId: string, newScreenshotDataUrl: string) => void;
57
59
  selectWidgetShape?: (widgetId: string) => boolean;
58
- listWidgetShapeScreenRects?: () => Array<{
59
- widgetId: string;
60
+ listWidgetShapeScreenRects?: () => {
60
61
  left: number;
61
62
  top: number;
62
63
  width: number;
63
64
  height: number;
64
- }>;
65
+ localWidth: any;
66
+ localHeight: any;
67
+ matrix: any[];
68
+ widgetId: string;
69
+ hovered: boolean;
70
+ }[];
65
71
  getWidgetShapeScreenRect?: (widgetId: string) => {
66
72
  left: number;
67
73
  top: number;
@@ -83,6 +89,7 @@ declare const __propDef: {
83
89
  viewportHeight: number;
84
90
  } | null;
85
91
  getWidgetShapeDataUrl?: (widgetId: string) => string | null;
92
+ setWidgetShapeLivePreviewHiddenImage?: (widgetId: string, hidden: boolean) => void;
86
93
  addWidgetShape?: (widgetId: string, widgetName?: string, gridIndex?: number, totalCount?: number, previewImageUrl?: string | null) => string | null;
87
94
  getLinkedWidgetIds?: () => Set<string>;
88
95
  hydrateWidgetShapeMetadata?: (widgetsById: Map<string, {
@@ -102,8 +109,10 @@ declare const __propDef: {
102
109
  setPrimaryWidgetShape?: (widgetId: string) => boolean;
103
110
  getPrimaryWidgetId?: () => string | null;
104
111
  translateWidgetShapeByScreen?: (widgetId: string, dxScreen: number, dyScreen: number) => boolean;
112
+ commitWidgetShapeTranslate?: (widgetId?: string | null) => void;
105
113
  selectWidgetShapeById?: (widgetId: string) => boolean;
106
114
  getSelectedWidgetShapeId?: () => string | null;
115
+ getHoveredWidgetShapeId?: () => string | null;
107
116
  onSelectImageTool?: () => void;
108
117
  onSelectVideoTool?: () => void;
109
118
  onSelectPanTool?: () => void;
@@ -148,13 +157,17 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
148
157
  get replaceObjectWithWidgetImage(): (objectId: string, widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
149
158
  get updateWidgetImage(): (widgetId: string, newScreenshotDataUrl: string) => void;
150
159
  get selectWidgetShape(): (widgetId: string) => boolean;
151
- get listWidgetShapeScreenRects(): () => Array<{
152
- widgetId: string;
160
+ get listWidgetShapeScreenRects(): () => {
153
161
  left: number;
154
162
  top: number;
155
163
  width: number;
156
164
  height: number;
157
- }>;
165
+ localWidth: any;
166
+ localHeight: any;
167
+ matrix: any[];
168
+ widgetId: string;
169
+ hovered: boolean;
170
+ }[];
158
171
  get getWidgetShapeScreenRect(): (widgetId: string) => {
159
172
  left: number;
160
173
  top: number;
@@ -176,6 +189,7 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
176
189
  viewportHeight: number;
177
190
  } | null;
178
191
  get getWidgetShapeDataUrl(): (widgetId: string) => string | null;
192
+ get setWidgetShapeLivePreviewHiddenImage(): (widgetId: string, hidden: boolean) => void;
179
193
  get addWidgetShape(): (widgetId: string, widgetName?: string, gridIndex?: number, totalCount?: number, previewImageUrl?: string | null) => string | null;
180
194
  get getLinkedWidgetIds(): () => Set<string>;
181
195
  get hydrateWidgetShapeMetadata(): (widgetsById: Map<string, {
@@ -195,8 +209,10 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
195
209
  get setPrimaryWidgetShape(): (widgetId: string) => boolean;
196
210
  get getPrimaryWidgetId(): () => string | null;
197
211
  get translateWidgetShapeByScreen(): (widgetId: string, dxScreen: number, dyScreen: number) => boolean;
212
+ get commitWidgetShapeTranslate(): (widgetId?: string | null) => void;
198
213
  get selectWidgetShapeById(): (widgetId: string) => boolean;
199
214
  get getSelectedWidgetShapeId(): () => string | null;
215
+ get getHoveredWidgetShapeId(): () => string | null;
200
216
  get onSelectImageTool(): () => void;
201
217
  get onSelectVideoTool(): () => void;
202
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.11",
3
+ "version": "0.5.12",
4
4
  "type": "module",
5
5
  "svelte": "./dist/index.js",
6
6
  "module": "./dist/index.js",