@r2digisolutions/components 0.20.0 → 0.21.1

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.
@@ -332,7 +332,7 @@
332
332
  <div class={['min-w-0', className]}>
333
333
  {#if selectionCount > 1}
334
334
  <p class="px-3 py-6 text-xs text-muted text-center">
335
- {selectionCount} layers selected — use the bulk dock
335
+ {selectionCount} layers selected — resize together on the canvas, or use the bottom dock
336
336
  </p>
337
337
  {:else if !layer}
338
338
  <p class="px-3 py-6 text-xs text-muted text-center">Select a layer to edit</p>
@@ -681,6 +681,20 @@
681
681
  size="sm"
682
682
  />
683
683
  </PropertyField>
684
+ {#if isContainerKind(layer.kind) || layer.kind === 'widget'}
685
+ <PropertyField
686
+ label="Auto size children"
687
+ modified={fieldModified('autoSizeChildren')}
688
+ onreset={() => resetField('autoSizeChildren')}
689
+ valueAlign="end"
690
+ >
691
+ <Toggle
692
+ checked={layer.autoSizeChildren ?? layer.kind === 'group'}
693
+ onchange={(v) => patch({ autoSizeChildren: v })}
694
+ size="sm"
695
+ />
696
+ </PropertyField>
697
+ {/if}
684
698
  {#if layer.kind === 'hBox' || layer.kind === 'vBox' || layer.kind === 'wrapBox' || layer.kind === 'uniformGrid'}
685
699
  <PropertyField
686
700
  label="Gap"
@@ -4,6 +4,7 @@
4
4
  import type { CanvasLayer, CanvasLayerRect } from '../../../utils/canvasDocument.js';
5
5
  import type { WidgetRect } from '../WidgetCanvas/widgetCanvasContext.js';
6
6
  import { isContainerKind } from '../../../utils/canvasHierarchy.js';
7
+ import { CANVAS_SVG_SHAPES } from '../../../utils/canvasShapes.js';
7
8
 
8
9
  interface MediaLayerItemProps {
9
10
  layer: CanvasLayer;
@@ -20,6 +21,8 @@
20
21
  /** Composed CSS transform (own + ancestor rotations) for flat-stage paint. */
21
22
  paintTransform?: string;
22
23
  selected?: boolean;
24
+ /** When false, hide resize handles (multi-select uses a shared AABB). */
25
+ showHandles?: boolean;
23
26
  /** Let clicks pass through (layer sits above the selection). */
24
27
  passthrough?: boolean;
25
28
  /** Synthetic resolved widget child — not directly editable. */
@@ -45,6 +48,7 @@
45
48
  stackIndex,
46
49
  paintTransform,
47
50
  selected = false,
51
+ showHandles,
48
52
  passthrough = false,
49
53
  readOnly = false,
50
54
  layoutPositionLocked = false,
@@ -96,9 +100,11 @@
96
100
  : undefined
97
101
  );
98
102
 
103
+ const handlesOn = $derived((showHandles ?? selected) && !readOnly);
104
+ const svgShape = $derived(CANVAS_SVG_SHAPES[layer.kind]);
99
105
  const isPanel = $derived(isContainerKind(layer.kind) || layer.kind === 'widget');
100
106
  const clip = $derived(
101
- layer.clipChildren ||
107
+ !!layer.clipChildren ||
102
108
  layer.kind === 'image' ||
103
109
  layer.kind === 'video' ||
104
110
  layer.kind === 'sticky' ||
@@ -108,6 +114,9 @@
108
114
  layer.kind === 'scrollBox' ||
109
115
  layer.kind === 'namedSlot'
110
116
  );
117
+ const panelClip = $derived(
118
+ !!layer.clipChildren || layer.kind === 'scrollBox' || layer.kind === 'namedSlot'
119
+ );
111
120
  </script>
112
121
 
113
122
  {#if layer.visible}
@@ -132,19 +141,18 @@
132
141
  showChrome={false}
133
142
  flush
134
143
  handleStyle="canva"
135
- handlesVisible={selected && !readOnly}
144
+ handlesVisible={handlesOn}
136
145
  raiseOnSelect={false}
137
146
  stackIndex={stackIndex ?? layer.zIndex}
138
147
  transform={paintTransform}
139
148
  draggable={!layer.locked && !readOnly && !noDrag}
140
- resizable={!layer.locked && !readOnly && !noResize}
149
+ resizable={!layer.locked && !readOnly && !noResize && handlesOn}
141
150
  bind:rect
142
151
  minW={layer.kind === 'line' || layer.kind === 'arrow' || layer.kind === 'path' ? 16 : 40}
143
152
  minH={layer.kind === 'line' ? 4 : layer.kind === 'arrow' || layer.kind === 'path' ? 16 : 24}
144
- class={[
145
- 'bg-transparent',
146
- passthrough || readOnly ? 'pointer-events-none' : ''
147
- ].filter(Boolean).join(' ')}
153
+ class={['bg-transparent', passthrough || readOnly ? 'pointer-events-none' : '']
154
+ .filter(Boolean)
155
+ .join(' ')}
148
156
  onchange={(r) => {
149
157
  rect = r;
150
158
  onchange?.(r);
@@ -175,12 +183,12 @@
175
183
  <video src={layer.src} class={['h-full w-full', fitClass]} muted playsinline></video>
176
184
  {:else if layer.kind === 'text' || layer.kind === 'sticky'}
177
185
  <div
178
- class="flex h-full w-full px-2 py-1"
186
+ class="px-2 py-1 flex h-full w-full"
179
187
  style:background={layer.kind === 'sticky'
180
188
  ? (layer.fill ?? '#fef08a')
181
189
  : layer.textBackground}
182
190
  style:color={layer.color ?? (layer.kind === 'sticky' ? '#713f12' : '#0f172a')}
183
- style:font-size="{(layer.fontSize ?? (layer.kind === 'sticky' ? 20 : 32))}px"
191
+ style:font-size="{layer.fontSize ?? (layer.kind === 'sticky' ? 20 : 32)}px"
184
192
  style:font-weight={layer.fontWeight ?? 600}
185
193
  style:font-family={layer.fontFamily}
186
194
  style:font-style={layer.fontStyle ?? 'normal'}
@@ -220,58 +228,19 @@
220
228
  ? `${layer.strokeWidth ?? 2}px solid ${layer.stroke}`
221
229
  : undefined}
222
230
  ></div>
223
- {:else if layer.kind === 'triangle'}
224
- <svg class="h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="none">
225
- <polygon
226
- points="50,4 96,96 4,96"
227
- fill={layer.fill ?? '#f59e0b'}
228
- stroke={layer.stroke}
229
- stroke-width={layer.strokeWidth ?? 0}
230
- />
231
- </svg>
232
- {:else if layer.kind === 'star'}
233
- <svg class="h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
234
- <polygon
235
- points="50,5 61,38 96,38 68,59 79,92 50,72 21,92 32,59 4,38 39,38"
236
- fill={layer.fill ?? '#ef4444'}
237
- stroke={layer.stroke}
238
- stroke-width={layer.strokeWidth ?? 0}
239
- />
240
- </svg>
241
- {:else if layer.kind === 'hexagon'}
242
- <svg class="h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="none">
243
- <polygon
244
- points="25,5 75,5 95,50 75,95 25,95 5,50"
245
- fill={layer.fill ?? '#06b6d4'}
246
- stroke={layer.stroke}
247
- stroke-width={layer.strokeWidth ?? 0}
248
- />
249
- </svg>
250
- {:else if layer.kind === 'pentagon'}
251
- <svg class="h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
252
- <polygon
253
- points="50,5 95,38 78,95 22,95 5,38"
254
- fill={layer.fill ?? '#a855f7'}
255
- stroke={layer.stroke}
256
- stroke-width={layer.strokeWidth ?? 0}
257
- />
258
- </svg>
259
- {:else if layer.kind === 'diamond'}
260
- <svg class="h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="none">
261
- <polygon
262
- points="50,4 96,50 50,96 4,50"
263
- fill={layer.fill ?? '#f43f5e'}
231
+ {:else if svgShape}
232
+ <svg
233
+ class="h-full w-full"
234
+ viewBox={`0 0 ${svgShape.viewBox.w} ${svgShape.viewBox.h}`}
235
+ preserveAspectRatio={svgShape.meet ? 'xMidYMid meet' : 'none'}
236
+ >
237
+ <path
238
+ d={svgShape.d}
239
+ fill={layer.fill ?? svgShape.fill}
264
240
  stroke={layer.stroke}
265
241
  stroke-width={layer.strokeWidth ?? 0}
266
242
  />
267
243
  </svg>
268
- {:else if layer.kind === 'heart'}
269
- <svg class="h-full w-full" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet">
270
- <path
271
- fill={layer.fill ?? '#ec4899'}
272
- d="M12 21s-6.7-4.35-9.33-7.6C.5 10.8 1.1 7.1 3.9 5.5 6.1 4.25 8.55 5 12 8.1c3.45-3.1 5.9-3.85 8.1-2.6 2.8 1.6 3.4 5.3 1.23 7.9C18.7 16.65 12 21 12 21z"
273
- />
274
- </svg>
275
244
  {:else if layer.kind === 'line'}
276
245
  {@const vertical = pos.h > pos.w}
277
246
  {@const sw = Math.max(2, layer.strokeWidth ?? 4)}
@@ -279,7 +248,7 @@
279
248
  class={[
280
249
  'absolute rounded-full',
281
250
  vertical
282
- ? 'left-1/2 top-0 h-full -translate-x-1/2'
251
+ ? 'top-0 left-1/2 h-full -translate-x-1/2'
283
252
  : 'left-0 top-1/2 w-full -translate-y-1/2'
284
253
  ]}
285
254
  style:background={layer.fill ?? '#94a3b8'}
@@ -294,7 +263,11 @@
294
263
  {@const len = vertical ? bh : bw}
295
264
  {@const thick = vertical ? bw : bh}
296
265
  {@const head = Math.min(Math.max(14, thick * 0.9), len * 0.35, 40)}
297
- <svg class="h-full w-full overflow-visible" viewBox={`0 0 ${bw} ${bh}`} aria-hidden="true">
266
+ <svg
267
+ class="h-full w-full overflow-visible"
268
+ viewBox={`0 0 ${bw} ${bh}`}
269
+ aria-hidden="true"
270
+ >
298
271
  {#if vertical}
299
272
  {@const cx = bw / 2}
300
273
  <line
@@ -333,7 +306,11 @@
333
306
  {@const d = layer.points
334
307
  .map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x * bw} ${p.y * bh}`)
335
308
  .join(' ')}
336
- <svg class="h-full w-full overflow-visible" viewBox={`0 0 ${bw} ${bh}`} aria-hidden="true">
309
+ <svg
310
+ class="h-full w-full overflow-visible"
311
+ viewBox={`0 0 ${bw} ${bh}`}
312
+ aria-hidden="true"
313
+ >
337
314
  <path
338
315
  d={layer.closed ? `${d} Z` : d}
339
316
  fill={layer.closed ? (layer.fill ?? '#0f172a') : 'none'}
@@ -346,8 +323,11 @@
346
323
  </svg>
347
324
  {:else if isPanel}
348
325
  <div
349
- class="relative h-full w-full overflow-hidden"
350
- style:background={layer.fill && layer.fill !== 'transparent' ? layer.fill : 'transparent'}
326
+ class="relative h-full w-full"
327
+ style:overflow={panelClip ? 'hidden' : 'visible'}
328
+ style:background={layer.fill && layer.fill !== 'transparent'
329
+ ? layer.fill
330
+ : 'transparent'}
351
331
  style:border={layer.kind === 'namedSlot'
352
332
  ? '1px dashed color-mix(in oklab, #3b82f6 50%, transparent)'
353
333
  : layer.kind === 'scrollBox'
@@ -361,14 +341,14 @@
361
341
  >
362
342
  {#if layer.kind === 'namedSlot'}
363
343
  <span
364
- class="pointer-events-none absolute left-1.5 top-1.5 rounded bg-brand-500/15 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-brand-600"
344
+ class="left-1.5 top-1.5 rounded bg-brand-500/15 px-1.5 py-0.5 font-semibold tracking-wide text-brand-600 pointer-events-none absolute text-[9px] uppercase"
365
345
  >
366
346
  {layer.slotName || layer.name || 'Slot'}
367
347
  </span>
368
348
  {/if}
369
349
  {#if layer.kind === 'scrollBox'}
370
350
  <span
371
- class="pointer-events-none absolute left-1.5 top-1.5 rounded bg-surface-overlay/90 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted"
351
+ class="left-1.5 top-1.5 rounded bg-surface-overlay/90 px-1.5 py-0.5 font-semibold tracking-wide text-muted pointer-events-none absolute text-[9px] uppercase"
372
352
  >
373
353
  Scroll
374
354
  </span>
@@ -376,7 +356,7 @@
376
356
  </div>
377
357
  {:else}
378
358
  <div
379
- class="flex h-full w-full items-center justify-center gap-2 bg-surface-overlay/80 text-secondary"
359
+ class="gap-2 bg-surface-overlay/80 text-secondary flex h-full w-full items-center justify-center"
380
360
  >
381
361
  <MediaKindIcon kind={layer.kind === 'audio' ? 'audio' : 'image'} />
382
362
  <span class="text-xs">{layer.name}</span>
@@ -15,6 +15,8 @@ interface MediaLayerItemProps {
15
15
  /** Composed CSS transform (own + ancestor rotations) for flat-stage paint. */
16
16
  paintTransform?: string;
17
17
  selected?: boolean;
18
+ /** When false, hide resize handles (multi-select uses a shared AABB). */
19
+ showHandles?: boolean;
18
20
  /** Let clicks pass through (layer sits above the selection). */
19
21
  passthrough?: boolean;
20
22
  /** Synthetic resolved widget child — not directly editable. */
@@ -2,6 +2,7 @@
2
2
  import { onMount, setContext } from 'svelte';
3
3
  import MediaLayerItem from '../MediaLayerItem/MediaLayerItem.svelte';
4
4
  import MarqueeRect from '../../atoms/MarqueeRect/MarqueeRect.svelte';
5
+ import WidgetFrame from '../WidgetFrame/WidgetFrame.svelte';
5
6
  import {
6
7
  WIDGET_CANVAS_CONTEXT,
7
8
  snapToGrid,
@@ -40,6 +41,10 @@
40
41
  layerFromAbsoluteRect,
41
42
  paintTransformForLayer,
42
43
  scaleSubtreeAbsolute,
44
+ scaleSelectionAbsolute,
45
+ shouldAutoSizeChildren,
46
+ unionAbsRect,
47
+ isContainerKind,
43
48
  scrollBoxOverflow,
44
49
  scrollBarMetrics,
45
50
  selectionAncestorIds,
@@ -180,6 +185,15 @@
180
185
  : null
181
186
  );
182
187
 
188
+ const selectionBounds = $derived.by(() => {
189
+ if (selectedIds.length < 2) return null;
190
+ return unionAbsRect(paintAbsMap, selectedIds);
191
+ });
192
+ let selectionLive = $state<{ x: number; y: number; w: number; h: number } | null>(null);
193
+ let selectionBaseLayers = $state<CanvasLayer[] | null>(null);
194
+ let selectionBaseBox = $state<{ x: number; y: number; w: number; h: number } | null>(null);
195
+ const selectionFrame = $derived(selectionLive ?? selectionBounds);
196
+
183
197
  const fitScale = $derived.by(() => {
184
198
  if (vw <= 0 || vh <= 0) return 1;
185
199
  const sx = (vw - PAD * 2) / doc.width;
@@ -343,6 +357,9 @@
343
357
  function cancelLayerDraft() {
344
358
  draftLayers = null;
345
359
  interactCount = 0;
360
+ selectionBaseLayers = null;
361
+ selectionBaseBox = null;
362
+ selectionLive = null;
346
363
  }
347
364
 
348
365
  function isLayoutLocked(layer: CanvasLayer): boolean {
@@ -421,8 +438,12 @@
421
438
  const sizeChanged = !moving;
422
439
  const rootSize = { width: doc.width, height: doc.height };
423
440
  let nextLayers = layers;
424
- if (source.kind === 'group' && sizeChanged) {
441
+ if (sizeChanged && shouldAutoSizeChildren(source)) {
425
442
  nextLayers = scaleSubtreeAbsolute(layers, source.id, prevAbs, nextAbs, rootSize);
443
+ } else if (sizeChanged && isContainerKind(source.kind)) {
444
+ nextLayers = scaleSubtreeAbsolute(layers, source.id, prevAbs, nextAbs, rootSize, {
445
+ scaleDescendants: false
446
+ });
426
447
  } else {
427
448
  const updated = applyTextAutoSize(
428
449
  source,
@@ -435,6 +456,33 @@
435
456
  commitGroupGeometry(nextLayers);
436
457
  }
437
458
 
459
+ function handleSelectionInteract(active: boolean) {
460
+ handleLayerInteract(active);
461
+ if (active && selectionBounds) {
462
+ selectionBaseLayers = workingLayers;
463
+ selectionBaseBox = { ...selectionBounds };
464
+ selectionLive = { ...selectionBounds };
465
+ return;
466
+ }
467
+ selectionBaseLayers = null;
468
+ selectionBaseBox = null;
469
+ selectionLive = null;
470
+ }
471
+
472
+ function handleSelectionRect(rect: { x: number; y: number; w: number; h: number }) {
473
+ selectionLive = rect;
474
+ if (!selectionBaseLayers || !selectionBaseBox) return;
475
+ commitGroupGeometry(
476
+ scaleSelectionAbsolute(
477
+ selectionBaseLayers,
478
+ selectedIds,
479
+ selectionBaseBox,
480
+ rect,
481
+ { width: doc.width, height: doc.height }
482
+ )
483
+ );
484
+ }
485
+
438
486
  function groupedChildPassthrough(layer: CanvasLayer): boolean {
439
487
  if (selectedSet.has(layer.id)) return false;
440
488
  return !!enclosingGroupId(workingLayers, layer.id);
@@ -1289,6 +1337,7 @@
1289
1337
  layerById
1290
1338
  )}
1291
1339
  selected={isSelected}
1340
+ showHandles={isSelected && selectedIds.length === 1}
1292
1341
  passthrough={lockedPass || groupedChildPassthrough(layer)}
1293
1342
  readOnly={isSynthetic}
1294
1343
  layoutPositionLocked={positionLocked || (marqueeBg && !dragOk)}
@@ -1328,6 +1377,43 @@
1328
1377
  {/if}
1329
1378
  {/each}
1330
1379
 
1380
+ {#if selectedIds.length > 1}
1381
+ {#each selectedIds as sid (sid)}
1382
+ {@const outline = paintAbsMap.get(sid)}
1383
+ {#if outline}
1384
+ <div
1385
+ class="pointer-events-none absolute z-[999985] outline outline-2 outline-[#3b82f6]"
1386
+ style:left="{outline.x}px"
1387
+ style:top="{outline.y}px"
1388
+ style:width="{outline.w}px"
1389
+ style:height="{outline.h}px"
1390
+ aria-hidden="true"
1391
+ ></div>
1392
+ {/if}
1393
+ {/each}
1394
+ {#if selectionFrame}
1395
+ <div data-marquee-ignore class="contents">
1396
+ <WidgetFrame
1397
+ freeform
1398
+ showChrome={false}
1399
+ flush
1400
+ handleStyle="canva"
1401
+ handlesVisible={true}
1402
+ raiseOnSelect={false}
1403
+ stackIndex={999999}
1404
+ draggable={false}
1405
+ resizable={true}
1406
+ rect={selectionFrame}
1407
+ minW={16}
1408
+ minH={16}
1409
+ class="pointer-events-none bg-transparent"
1410
+ onchange={handleSelectionRect}
1411
+ oninteract={handleSelectionInteract}
1412
+ />
1413
+ </div>
1414
+ {/if}
1415
+ {/if}
1416
+
1331
1417
  <!-- ScrollBox chrome above nested layer content -->
1332
1418
  {#each displayLayers.filter((l) => l.kind === 'scrollBox') as box (box.id + ':scroll')}
1333
1419
  {#if effectivelyVisible.has(box.id)}
@@ -448,7 +448,7 @@
448
448
  const edgeAccent = $derived.by(() => {
449
449
  if (isCanva) {
450
450
  const visible =
451
- mode === 'resize'
451
+ mode === 'resize' || handlesVisible === true
452
452
  ? 'pointer-events-auto opacity-100'
453
453
  : handlesVisible === false
454
454
  ? 'pointer-events-none opacity-0'
@@ -10,6 +10,8 @@
10
10
  import ContextMenu from '../../molecules/ContextMenu/ContextMenu.svelte';
11
11
  import type { ContextMenuItem } from '../../molecules/ContextMenu/ContextMenu.svelte';
12
12
  import BulkActionBar from '../../molecules/BulkActionBar/BulkActionBar.svelte';
13
+ import Dock from '../../molecules/Dock/Dock.svelte';
14
+ import DockItem from '../../molecules/Dock/DockItem.svelte';
13
15
  import Panel from '../../molecules/Panel/Panel.svelte';
14
16
  import SplitPane from '../../molecules/SplitPane/SplitPane.svelte';
15
17
  import IconButton from '../../atoms/IconButton/IconButton.svelte';
@@ -47,6 +49,7 @@
47
49
  reorderSiblings,
48
50
  resolveSlotRect,
49
51
  scaleSubtreeAbsolute,
52
+ shouldAutoSizeChildren,
50
53
  stepAxis,
51
54
  syncSlotFromRect,
52
55
  ungroupLayers,
@@ -293,6 +296,11 @@
293
296
  { id: 'full', label: 'Fill canvas', icon: Maximize2 }
294
297
  ];
295
298
 
299
+ const selectionAlignDock = alignItems.filter(
300
+ (item): item is DropdownItem & { icon: typeof AlignStartVertical } =>
301
+ !item.separator && Boolean(item.icon) && item.id !== 'full'
302
+ );
303
+
296
304
  const exportItems: DropdownItem[] = [
297
305
  { id: 'png', label: 'PNG image', icon: ImageIcon, description: 'Lossless · transparent ok' },
298
306
  { id: 'jpeg', label: 'JPEG image', icon: FileImage, description: 'Smaller file size' },
@@ -448,11 +456,16 @@
448
456
  const rootSize = { width: stageDoc.width, height: stageDoc.height };
449
457
  const prev = stageDoc.layers.find((l) => l.id === layer.id);
450
458
  let layers = stageDoc.layers.map((l) => (l.id === layer.id ? layer : l));
451
- if (prev && layer.kind === 'group') {
459
+ if (
460
+ prev &&
461
+ (shouldAutoSizeChildren(layer) || isContainerKind(layer.kind))
462
+ ) {
452
463
  const prevAbs = computeAbsoluteRects(stageDoc.layers, rootSize).get(prev.id) ?? prev.rect;
453
464
  const nextAbs = computeAbsoluteRects(layers, rootSize).get(layer.id) ?? layer.rect;
454
465
  if (Math.abs(nextAbs.w - prevAbs.w) > 0.5 || Math.abs(nextAbs.h - prevAbs.h) > 0.5) {
455
- layers = scaleSubtreeAbsolute(stageDoc.layers, layer.id, prevAbs, nextAbs, rootSize);
466
+ layers = scaleSubtreeAbsolute(stageDoc.layers, layer.id, prevAbs, nextAbs, rootSize, {
467
+ scaleDescendants: shouldAutoSizeChildren(layer)
468
+ });
456
469
  }
457
470
  }
458
471
  emitStageLayers(layers);
@@ -1659,7 +1672,9 @@
1659
1672
  compact
1660
1673
  showSelectAll={false}
1661
1674
  maxPrimary={5}
1675
+ hint="⌘G group · Shift+click add · Esc clears"
1662
1676
  actions={[
1677
+ { id: 'group', label: 'Group', icon: Group, variant: 'ghost' },
1663
1678
  { id: 'duplicate', label: 'Duplicate', icon: Copy, variant: 'ghost' },
1664
1679
  { id: 'front', label: 'Bring to front', icon: BringToFront, variant: 'ghost' },
1665
1680
  { id: 'back', label: 'Send to back', icon: ArrowDownToLine, variant: 'ghost' },
@@ -1679,6 +1694,20 @@
1679
1694
  onclear={() => (selectedIds = [])}
1680
1695
  >
1681
1696
  {#snippet extra()}
1697
+ <Dock size="mini">
1698
+ {#each selectionAlignDock as action (action.id)}
1699
+ {@const Icon = action.icon}
1700
+ <Tooltip content={action.label} side="top">
1701
+ <DockItem
1702
+ size="mini"
1703
+ ariaLabel={action.label}
1704
+ onclick={() => alignSelected(action.id as CanvasAlign)}
1705
+ >
1706
+ <Icon class="h-3.5 w-3.5" />
1707
+ </DockItem>
1708
+ </Tooltip>
1709
+ {/each}
1710
+ </Dock>
1682
1711
  <DropdownMenu
1683
1712
  size="sm"
1684
1713
  align="start"
package/dist/index.d.ts CHANGED
@@ -865,12 +865,14 @@ export type { MediaAsset, MediaAssetKind, MediaClip, MediaClipAlign, MediaClipRe
865
865
  export { uid, createMediaClip, createMediaTrack, createMediaAsset, clipDurationMs, moveClip, trimClipStart, trimClipEnd, isClipActiveAt, findClipAt, updateClipInTracks, removeClipFromTracks, removeClipsFromTracks, splitClipAt, splitClipsAt, duplicateClipInTracks, mergeClipsInTracks, canMergeMediaClips, moveClipsByDelta, findClipById, nextTrackName, reorderTracks, moveTrack, removeTrack, removeTracks, defaultOverlayRect, defaultMediaClipRect, resolveClipRect, alignClipRect, alignMediaRect, clipHasSpatialRect, isMediaClipFieldModified, resetMediaClipField, findTransitionAt, transitionLayerStyle, transitionDipOverlay, resolvePreviewOpacity, resolveClipOpacity, MEDIA_CLIP_DEFAULTS, kindFromFile, probeMediaSrc } from './utils/mediaTracks.js';
866
866
  export { emptyCanvasDocument, createCanvasLayer, createCanvasGuide, createPathFromDocPoints, rebakePathLayer, pathPointsToDoc, reorderCanvasLayers, updateCanvasLayer, updateCanvasLayers, alignLayerRect, snapLayerRect, snapRectToGuides, migrateCanvasDocument, defaultSlotFromRect, rectFromSlot, ensureLayerSlot, canvasLayerFieldDefault, isCanvasFieldModified, resetCanvasField, applyTextAutoSize, CANVAS_PRESETS, presetIdForSize } from './utils/canvasDocument.js';
867
867
  export type { CanvasDocument, CanvasLayer, CanvasLayerKind, CanvasLayerRect, CanvasPoint, CanvasObjectFit, CanvasTextAlign, CanvasResettableField, CanvasAlign, CanvasFontStyle, CanvasTextDecoration, CanvasGuide, CanvasGuideOrientation, CanvasAnchors, CanvasSlot, CanvasExposedProp, CanvasWidgetDefinition } from './utils/canvasDocument.js';
868
- export { isContainerKind, canHaveChildren, getChildren, getDescendantIds, getSubtreeIds, getAncestors, enclosingGroupId, isEffectivelyVisible, isEffectivelyLocked, isLayoutPositionLocked, isLayoutSizeLocked, selectionAncestorIds, LAYOUT_POSITION_KINDS, LAYOUT_SIZE_KINDS, paintTransformForLayer, isDescendant, canReparent, ANCHOR_PRESETS, resolveSlotRect, slotFromLocalRect, translateSlot, stepAxis, computeAbsoluteRects, absoluteRectFor, reparentLayer, wrapSelection, groupLayers, ungroupLayers, layerFromAbsoluteRect, fitGroupsToChildren, scaleSubtreeAbsolute, deleteSubtree, duplicateSubtree, reorderSiblings, clipPathForLayer, scrollBoxOverflow, scrollBarMetrics, applyScrollBoxOffsets } from './utils/canvasHierarchy.js';
868
+ export { isContainerKind, canHaveChildren, getChildren, getDescendantIds, getSubtreeIds, getAncestors, enclosingGroupId, isEffectivelyVisible, isEffectivelyLocked, isLayoutPositionLocked, isLayoutSizeLocked, selectionAncestorIds, LAYOUT_POSITION_KINDS, LAYOUT_SIZE_KINDS, paintTransformForLayer, isDescendant, canReparent, ANCHOR_PRESETS, resolveSlotRect, slotFromLocalRect, translateSlot, stepAxis, computeAbsoluteRects, absoluteRectFor, reparentLayer, wrapSelection, groupLayers, ungroupLayers, layerFromAbsoluteRect, fitGroupsToChildren, scaleSubtreeAbsolute, scaleSelectionAbsolute, shouldAutoSizeChildren, topLevelSelectedIds, unionAbsRect, deleteSubtree, duplicateSubtree, reorderSiblings, clipPathForLayer, scrollBoxOverflow, scrollBarMetrics, applyScrollBoxOffsets } from './utils/canvasHierarchy.js';
869
869
  export { createWidgetDefinition, createWidgetFromSelection, placeWidgetInstance, resolveWidgetInstance, flattenLayersWithWidgets, breakWidgetInstance, updateWidgetDefinition, deleteWidgetDefinition, renameWidgetDefinition, duplicateWidgetDefinition, syncInstanceSizesToDefinition, setExposedProp, isPropExposed, getExposedProp, getExposedFieldDefault, resolveExposedPropValue, groupExposedPropsByLayer, setInstanceOverride, getNamedSlotsFromDefinition, listFillableSlotsForInstance } from './utils/canvasWidget.js';
870
870
  export { createCanvasHistory, pushCanvasHistory, undoCanvasHistory, redoCanvasHistory, serializeCanvasDoc, parseCanvasDoc } from './utils/canvasHistory.js';
871
871
  export type { CanvasHistoryState } from './utils/canvasHistory.js';
872
872
  export { renderCanvasDocument, exportCanvasBlob, downloadBlob, backgroundAlpha } from './utils/canvasExport.js';
873
873
  export type { CanvasExportFormat } from './utils/canvasExport.js';
874
+ export { CANVAS_SVG_SHAPES, svgShapeFit, drawCanvasSvgShape } from './utils/canvasShapes.js';
875
+ export type { CanvasSvgShape } from './utils/canvasShapes.js';
874
876
  export { emptyVideoSequence, createDemoVideoSequence } from './utils/videoSequence.js';
875
877
  export type { VideoSequence } from './utils/videoSequence.js';
876
878
  export { emptyAudioProject, createDemoAudioProject } from './utils/audioProject.js';
package/dist/index.js CHANGED
@@ -587,10 +587,11 @@ export { emptyBlogDocument, createBlock, createComponentBlock, serializeBlogDocu
587
587
  export { msToPx, pxToMs, pxPerMsFromZoom, snapMs, clampMs, formatTimecode, ticksForDuration, snapStepForZoom } from './utils/mediaTime.js';
588
588
  export { uid, createMediaClip, createMediaTrack, createMediaAsset, clipDurationMs, moveClip, trimClipStart, trimClipEnd, isClipActiveAt, findClipAt, updateClipInTracks, removeClipFromTracks, removeClipsFromTracks, splitClipAt, splitClipsAt, duplicateClipInTracks, mergeClipsInTracks, canMergeMediaClips, moveClipsByDelta, findClipById, nextTrackName, reorderTracks, moveTrack, removeTrack, removeTracks, defaultOverlayRect, defaultMediaClipRect, resolveClipRect, alignClipRect, alignMediaRect, clipHasSpatialRect, isMediaClipFieldModified, resetMediaClipField, findTransitionAt, transitionLayerStyle, transitionDipOverlay, resolvePreviewOpacity, resolveClipOpacity, MEDIA_CLIP_DEFAULTS, kindFromFile, probeMediaSrc } from './utils/mediaTracks.js';
589
589
  export { emptyCanvasDocument, createCanvasLayer, createCanvasGuide, createPathFromDocPoints, rebakePathLayer, pathPointsToDoc, reorderCanvasLayers, updateCanvasLayer, updateCanvasLayers, alignLayerRect, snapLayerRect, snapRectToGuides, migrateCanvasDocument, defaultSlotFromRect, rectFromSlot, ensureLayerSlot, canvasLayerFieldDefault, isCanvasFieldModified, resetCanvasField, applyTextAutoSize, CANVAS_PRESETS, presetIdForSize } from './utils/canvasDocument.js';
590
- export { isContainerKind, canHaveChildren, getChildren, getDescendantIds, getSubtreeIds, getAncestors, enclosingGroupId, isEffectivelyVisible, isEffectivelyLocked, isLayoutPositionLocked, isLayoutSizeLocked, selectionAncestorIds, LAYOUT_POSITION_KINDS, LAYOUT_SIZE_KINDS, paintTransformForLayer, isDescendant, canReparent, ANCHOR_PRESETS, resolveSlotRect, slotFromLocalRect, translateSlot, stepAxis, computeAbsoluteRects, absoluteRectFor, reparentLayer, wrapSelection, groupLayers, ungroupLayers, layerFromAbsoluteRect, fitGroupsToChildren, scaleSubtreeAbsolute, deleteSubtree, duplicateSubtree, reorderSiblings, clipPathForLayer, scrollBoxOverflow, scrollBarMetrics, applyScrollBoxOffsets } from './utils/canvasHierarchy.js';
590
+ export { isContainerKind, canHaveChildren, getChildren, getDescendantIds, getSubtreeIds, getAncestors, enclosingGroupId, isEffectivelyVisible, isEffectivelyLocked, isLayoutPositionLocked, isLayoutSizeLocked, selectionAncestorIds, LAYOUT_POSITION_KINDS, LAYOUT_SIZE_KINDS, paintTransformForLayer, isDescendant, canReparent, ANCHOR_PRESETS, resolveSlotRect, slotFromLocalRect, translateSlot, stepAxis, computeAbsoluteRects, absoluteRectFor, reparentLayer, wrapSelection, groupLayers, ungroupLayers, layerFromAbsoluteRect, fitGroupsToChildren, scaleSubtreeAbsolute, scaleSelectionAbsolute, shouldAutoSizeChildren, topLevelSelectedIds, unionAbsRect, deleteSubtree, duplicateSubtree, reorderSiblings, clipPathForLayer, scrollBoxOverflow, scrollBarMetrics, applyScrollBoxOffsets } from './utils/canvasHierarchy.js';
591
591
  export { createWidgetDefinition, createWidgetFromSelection, placeWidgetInstance, resolveWidgetInstance, flattenLayersWithWidgets, breakWidgetInstance, updateWidgetDefinition, deleteWidgetDefinition, renameWidgetDefinition, duplicateWidgetDefinition, syncInstanceSizesToDefinition, setExposedProp, isPropExposed, getExposedProp, getExposedFieldDefault, resolveExposedPropValue, groupExposedPropsByLayer, setInstanceOverride, getNamedSlotsFromDefinition, listFillableSlotsForInstance } from './utils/canvasWidget.js';
592
592
  export { createCanvasHistory, pushCanvasHistory, undoCanvasHistory, redoCanvasHistory, serializeCanvasDoc, parseCanvasDoc } from './utils/canvasHistory.js';
593
593
  export { renderCanvasDocument, exportCanvasBlob, downloadBlob, backgroundAlpha } from './utils/canvasExport.js';
594
+ export { CANVAS_SVG_SHAPES, svgShapeFit, drawCanvasSvgShape } from './utils/canvasShapes.js';
594
595
  export { emptyVideoSequence, createDemoVideoSequence } from './utils/videoSequence.js';
595
596
  export { emptyAudioProject, createDemoAudioProject } from './utils/audioProject.js';
596
597
  export { emptyGraphDocument, createGraphNode, createGraphEdge, createVarGetNode, createVarSetNode, duplicateGraphSelection, cloneGraphDocument, extractGraphSelection, encodeGraphClipboard, decodeGraphClipboard, pasteGraphSelection, alignGraphNodes, distributeGraphNodes, selectionBounds, createCommentFromSelection, createRerouteNode, insertRerouteOnEdge, breakLinksAtHandle, collapseSelectionToFunction, expandCollapsedGraph, GRAPH_CLIPBOARD_MIME, serializeGraphDocument, parseGraphDocument, removeNode, removeEdge, updateNodePosition, nodeCenter, nodeSize, portPosition, findPort, edgeEndpoints, edgePathFromPoints, edgePathForPorts, snap, fitView, defaultPortsForType, resolveNodeType, pinsCompatible, pinColor, variablePinColor, defaultValueForPinType, variablePlaceItems, filterNodeTypesForGraph, nodeTypeAllowedInContext, formatPortLiteral, parsePortLiteral, isDataPort, wiredInputIdsByNode, validateGraph, groupNodeTypesByCategory, emptyBlueprintDocument, DEFAULT_NODE_TYPES, DEFAULT_BLUEPRINT_NODE_TYPES, DEFAULT_NODE_WIDTH, DEFAULT_NODE_HEIGHT, PORT_SIZE, EDGE_PORT_PAD, PIN_TYPE_COLORS } from './utils/nodeGraph.js';
@@ -83,6 +83,11 @@ export interface CanvasLayer {
83
83
  * (geometric mean of width/height scale — Unreal/Canva-style).
84
84
  */
85
85
  autoSize?: boolean;
86
+ /**
87
+ * When true, resizing this container scales children (position + size + text)
88
+ * relative to the parent — same idea as text `autoSize`. Groups default on.
89
+ */
90
+ autoSizeChildren?: boolean;
86
91
  color?: string;
87
92
  /** Text box background */
88
93
  textBackground?: string;
@@ -161,7 +166,7 @@ export declare function ensureLayerSlot(layer: CanvasLayer): CanvasLayer;
161
166
  export declare function createCanvasGuide(orientation: CanvasGuideOrientation, position: number, partial?: Partial<Omit<CanvasGuide, 'id' | 'orientation' | 'position'>>): CanvasGuide;
162
167
  export declare function createCanvasLayer(kind: CanvasLayerKind, partial?: Partial<Omit<CanvasLayer, 'id' | 'kind'>>): CanvasLayer;
163
168
  /** Scalar fields that can reset to createCanvasLayer defaults (UE-style details). */
164
- export type CanvasResettableField = 'opacity' | 'rotation' | 'visible' | 'locked' | 'flipX' | 'flipY' | 'blur' | 'shadowBlur' | 'shadowColor' | 'fill' | 'stroke' | 'strokeWidth' | 'fontSize' | 'fontWeight' | 'fontFamily' | 'fontStyle' | 'textDecoration' | 'letterSpacing' | 'lineHeight' | 'textAlign' | 'autoSize' | 'color' | 'textBackground' | 'objectFit' | 'borderRadius' | 'gap' | 'columns' | 'clipChildren' | 'text' | 'name';
169
+ export type CanvasResettableField = 'opacity' | 'rotation' | 'visible' | 'locked' | 'flipX' | 'flipY' | 'blur' | 'shadowBlur' | 'shadowColor' | 'fill' | 'stroke' | 'strokeWidth' | 'fontSize' | 'fontWeight' | 'fontFamily' | 'fontStyle' | 'textDecoration' | 'letterSpacing' | 'lineHeight' | 'textAlign' | 'autoSize' | 'color' | 'textBackground' | 'objectFit' | 'borderRadius' | 'gap' | 'columns' | 'clipChildren' | 'autoSizeChildren' | 'text' | 'name';
165
170
  /** Default value for a layer field (same as createCanvasLayer would use). */
166
171
  export declare function canvasLayerFieldDefault(kind: CanvasLayerKind, field: CanvasResettableField): unknown;
167
172
  export declare function isCanvasFieldModified(layer: CanvasLayer, field: CanvasResettableField): boolean;
@@ -73,7 +73,7 @@ const LAYER_DEFAULTS = {
73
73
  vBox: { w: 200, h: 240, name: 'Vertical Box', fill: 'transparent', gap: 8 },
74
74
  sizeBox: { w: 200, h: 200, name: 'Size Box', fill: 'transparent', clipChildren: true },
75
75
  scaleBox: { w: 240, h: 240, name: 'Scale Box', fill: 'transparent', clipChildren: true },
76
- group: { w: 280, h: 200, name: 'Group', fill: 'transparent' },
76
+ group: { w: 280, h: 200, name: 'Group', fill: 'transparent', autoSizeChildren: true },
77
77
  widget: { w: 280, h: 160, name: 'Widget' },
78
78
  namedSlot: { w: 200, h: 120, name: 'Named Slot', fill: 'rgba(59,130,246,0.08)' },
79
79
  scrollBox: { w: 280, h: 320, name: 'Scroll Box', fill: 'transparent', clipChildren: true },
@@ -174,6 +174,7 @@ export function createCanvasLayer(kind, partial) {
174
174
  parentId: partial?.parentId ?? null,
175
175
  slot: partial?.slot,
176
176
  clipChildren: partial?.clipChildren ?? d.clipChildren ?? false,
177
+ autoSizeChildren: partial?.autoSizeChildren ?? d.autoSizeChildren ?? (kind === 'group' ? true : undefined),
177
178
  gap: partial?.gap ?? d.gap,
178
179
  slotName: partial?.slotName ?? (kind === 'namedSlot' ? partial?.name ?? d.name : undefined),
179
180
  fillSlot: partial?.fillSlot,
@@ -250,6 +251,8 @@ export function canvasLayerFieldDefault(kind, field) {
250
251
  return kind === 'uniformGrid' ? 2 : undefined;
251
252
  case 'clipChildren':
252
253
  return d.clipChildren ?? false;
254
+ case 'autoSizeChildren':
255
+ return d.autoSizeChildren ?? kind === 'group';
253
256
  case 'text':
254
257
  return d.text;
255
258
  case 'name':
@@ -261,8 +264,8 @@ export function canvasLayerFieldDefault(kind, field) {
261
264
  export function isCanvasFieldModified(layer, field) {
262
265
  const def = canvasLayerFieldDefault(layer.kind, field);
263
266
  const raw = layer[field];
264
- // Missing autoSize on older docs → treat as the kind default (text=true).
265
- const cur = field === 'autoSize' && raw === undefined ? def : raw;
267
+ // Missing autoSize / autoSizeChildren on older docs → kind default.
268
+ const cur = (field === 'autoSize' || field === 'autoSizeChildren') && raw === undefined ? def : raw;
266
269
  return !canvasValuesEqual(cur, def);
267
270
  }
268
271
  export function resetCanvasField(layer, field) {
@@ -1,5 +1,6 @@
1
1
  import { computeAbsoluteRects, isEffectivelyVisible } from './canvasHierarchy.js';
2
2
  import { flattenLayersWithWidgets } from './canvasWidget.js';
3
+ import { CANVAS_SVG_SHAPES, drawCanvasSvgShape } from './canvasShapes.js';
3
4
  function loadImage(src) {
4
5
  return new Promise((resolve, reject) => {
5
6
  const img = new Image();
@@ -57,75 +58,17 @@ function drawShapePath(ctx, layer) {
57
58
  ctx.ellipse(x + w / 2, y + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
58
59
  break;
59
60
  case 'triangle':
60
- ctx.moveTo(x + w / 2, y);
61
- ctx.lineTo(x + w, y + h);
62
- ctx.lineTo(x, y + h);
63
- ctx.closePath();
64
- break;
65
61
  case 'diamond':
66
- ctx.moveTo(x + w / 2, y);
67
- ctx.lineTo(x + w, y + h / 2);
68
- ctx.lineTo(x + w / 2, y + h);
69
- ctx.lineTo(x, y + h / 2);
70
- ctx.closePath();
71
- break;
72
- case 'star': {
73
- const cx = x + w / 2;
74
- const cy = y + h / 2;
75
- const spikes = 5;
76
- const outer = Math.min(w, h) / 2;
77
- const inner = outer * 0.4;
78
- for (let i = 0; i < spikes * 2; i++) {
79
- const radius = i % 2 === 0 ? outer : inner;
80
- const angle = (i * Math.PI) / spikes - Math.PI / 2;
81
- const px = cx + Math.cos(angle) * radius;
82
- const py = cy + Math.sin(angle) * radius;
83
- if (i === 0)
84
- ctx.moveTo(px, py);
85
- else
86
- ctx.lineTo(px, py);
87
- }
88
- ctx.closePath();
89
- break;
90
- }
91
- case 'hexagon': {
92
- const cx = x + w / 2;
93
- const cy = y + h / 2;
94
- for (let i = 0; i < 6; i++) {
95
- const angle = (Math.PI / 3) * i - Math.PI / 6;
96
- const px = cx + (w / 2) * Math.cos(angle);
97
- const py = cy + (h / 2) * Math.sin(angle);
98
- if (i === 0)
99
- ctx.moveTo(px, py);
100
- else
101
- ctx.lineTo(px, py);
102
- }
103
- ctx.closePath();
104
- break;
105
- }
106
- case 'pentagon': {
107
- const cx = x + w / 2;
108
- const cy = y + h / 2;
109
- const r = Math.min(w, h) / 2;
110
- for (let i = 0; i < 5; i++) {
111
- const angle = (i * 2 * Math.PI) / 5 - Math.PI / 2;
112
- const px = cx + r * Math.cos(angle);
113
- const py = cy + r * Math.sin(angle);
114
- if (i === 0)
115
- ctx.moveTo(px, py);
116
- else
117
- ctx.lineTo(px, py);
118
- }
119
- ctx.closePath();
120
- break;
121
- }
62
+ case 'star':
63
+ case 'hexagon':
64
+ case 'pentagon':
122
65
  case 'heart': {
123
- const cx = x + w / 2;
124
- const top = y + h * 0.3;
125
- ctx.moveTo(cx, y + h * 0.9);
126
- ctx.bezierCurveTo(x, y + h * 0.6, x, top, cx, y + h * 0.35);
127
- ctx.bezierCurveTo(x + w, top, x + w, y + h * 0.6, cx, y + h * 0.9);
128
- ctx.closePath();
66
+ const svg = CANVAS_SVG_SHAPES[layer.kind];
67
+ if (svg) {
68
+ drawCanvasSvgShape(ctx, { x, y, w, h }, svg, layer.fill ?? svg.fill, layer.stroke, layer.strokeWidth);
69
+ return;
70
+ }
71
+ ctx.rect(x, y, w, h);
129
72
  break;
130
73
  }
131
74
  case 'line': {
@@ -234,11 +234,27 @@ export declare function fitGroupsToChildren(layers: CanvasLayer[], rootSize: {
234
234
  width: number;
235
235
  height: number;
236
236
  }): CanvasLayer[];
237
+ /** Groups default on; other containers opt in via `autoSizeChildren`. */
238
+ export declare function shouldAutoSizeChildren(layer: CanvasLayer): boolean;
239
+ export declare function topLevelSelectedIds(layers: CanvasLayer[], ids: string[]): string[];
240
+ export declare function unionAbsRect(absMap: Map<string, CanvasLayerRect>, ids: string[]): CanvasLayerRect | null;
237
241
  /**
238
242
  * Scale a group (or any subtree) from `prevAbs` to `nextAbs`.
239
- * Descendants keep their relative placement inside the box.
243
+ * Descendants keep their relative placement inside the box unless
244
+ * `scaleDescendants` is false (then they keep world position).
240
245
  */
241
246
  export declare function scaleSubtreeAbsolute(layers: CanvasLayer[], rootId: string, prevAbs: CanvasLayerRect, nextAbs: CanvasLayerRect, rootSize: {
242
247
  width: number;
243
248
  height: number;
249
+ }, opts?: {
250
+ scaleDescendants?: boolean;
251
+ }): CanvasLayer[];
252
+ /**
253
+ * Scale (or move) a multi-selection as one AABB — Figma/Canva transform box.
254
+ * Top-level selected layers map into `nextBox`; nested children follow if the
255
+ * parent has auto-size children (groups default on).
256
+ */
257
+ export declare function scaleSelectionAbsolute(layers: CanvasLayer[], selectedIds: string[], prevBox: CanvasLayerRect, nextBox: CanvasLayerRect, rootSize: {
258
+ width: number;
259
+ height: number;
244
260
  }): CanvasLayer[];
@@ -1,4 +1,4 @@
1
- import { createCanvasLayer, defaultSlotFromRect, rectFromSlot } from './canvasDocument.js';
1
+ import { applyTextAutoSize, createCanvasLayer, defaultSlotFromRect, rectFromSlot } from './canvasDocument.js';
2
2
  import { uid } from './mediaTracks.js';
3
3
  export const CONTAINER_KINDS = new Set([
4
4
  'canvasPanel',
@@ -654,6 +654,7 @@ export function wrapSelection(doc, selectedIds, wrapKind = 'group') {
654
654
  slot: slotFromLocalRect({ width: contentW, height: contentH }, wrapperLocal),
655
655
  zIndex,
656
656
  clipChildren: wrapKind === 'border' || wrapKind === 'canvasPanel' || wrapKind === 'scrollBox',
657
+ autoSizeChildren: wrapKind === 'group',
657
658
  fill: wrapKind === 'border' || wrapKind === 'roundRect'
658
659
  ? '#ffffff'
659
660
  : wrapKind === 'group'
@@ -867,16 +868,60 @@ function fitOneGroup(layers, groupId, rootSize) {
867
868
  }
868
869
  return layers.map((l) => updated.get(l.id) ?? l);
869
870
  }
871
+ /** Groups default on; other containers opt in via `autoSizeChildren`. */
872
+ export function shouldAutoSizeChildren(layer) {
873
+ if (layer.autoSizeChildren != null)
874
+ return layer.autoSizeChildren;
875
+ return layer.kind === 'group';
876
+ }
877
+ export function topLevelSelectedIds(layers, ids) {
878
+ const set = new Set(ids);
879
+ return ids.filter((id) => !getAncestors(layers, id).some((a) => set.has(a.id)));
880
+ }
881
+ export function unionAbsRect(absMap, ids) {
882
+ let minX = Infinity;
883
+ let minY = Infinity;
884
+ let maxX = -Infinity;
885
+ let maxY = -Infinity;
886
+ for (const id of ids) {
887
+ const r = absMap.get(id);
888
+ if (!r)
889
+ continue;
890
+ minX = Math.min(minX, r.x);
891
+ minY = Math.min(minY, r.y);
892
+ maxX = Math.max(maxX, r.x + r.w);
893
+ maxY = Math.max(maxY, r.y + r.h);
894
+ }
895
+ if (!Number.isFinite(minX))
896
+ return null;
897
+ return { x: minX, y: minY, w: Math.max(1, maxX - minX), h: Math.max(1, maxY - minY) };
898
+ }
899
+ function applyAbsoluteRects(layers, nextAbsMap, prevAbsMap, rootSize) {
900
+ const byId = new Map(layers.map((l) => [l.id, l]));
901
+ return layers.map((l) => {
902
+ const abs = nextAbsMap.get(l.id);
903
+ if (!abs)
904
+ return l;
905
+ const prev = prevAbsMap.get(l.id);
906
+ const parent = l.parentId ? (byId.get(l.parentId) ?? null) : null;
907
+ const parentAbs = l.parentId
908
+ ? (nextAbsMap.get(l.parentId) ?? prevAbsMap.get(l.parentId) ?? null)
909
+ : rootFrame(rootSize);
910
+ const updated = layerFromAbsoluteRect(l, abs, parentAbs, parent, rootSize);
911
+ return prev ? applyTextAutoSize(l, updated, prev, abs) : updated;
912
+ });
913
+ }
870
914
  /**
871
915
  * Scale a group (or any subtree) from `prevAbs` to `nextAbs`.
872
- * Descendants keep their relative placement inside the box.
916
+ * Descendants keep their relative placement inside the box unless
917
+ * `scaleDescendants` is false (then they keep world position).
873
918
  */
874
- export function scaleSubtreeAbsolute(layers, rootId, prevAbs, nextAbs, rootSize) {
919
+ export function scaleSubtreeAbsolute(layers, rootId, prevAbs, nextAbs, rootSize, opts) {
920
+ const scaleDescendants = opts?.scaleDescendants ?? true;
875
921
  const sx = prevAbs.w > 0 ? nextAbs.w / prevAbs.w : 1;
876
922
  const sy = prevAbs.h > 0 ? nextAbs.h / prevAbs.h : 1;
877
923
  const absMap = computeAbsoluteRects(layers, rootSize);
878
924
  const ids = new Set(getSubtreeIds(layers, rootId));
879
- const byId = new Map(layers.map((l) => [l.id, l]));
880
925
  const nextAbsMap = new Map();
881
926
  for (const id of ids) {
882
927
  const r = absMap.get(id);
@@ -886,6 +931,10 @@ export function scaleSubtreeAbsolute(layers, rootId, prevAbs, nextAbs, rootSize)
886
931
  nextAbsMap.set(id, { ...nextAbs });
887
932
  continue;
888
933
  }
934
+ if (!scaleDescendants) {
935
+ nextAbsMap.set(id, r);
936
+ continue;
937
+ }
889
938
  nextAbsMap.set(id, {
890
939
  x: nextAbs.x + (r.x - prevAbs.x) * sx,
891
940
  y: nextAbs.y + (r.y - prevAbs.y) * sy,
@@ -893,14 +942,38 @@ export function scaleSubtreeAbsolute(layers, rootId, prevAbs, nextAbs, rootSize)
893
942
  h: Math.max(1, r.h * sy)
894
943
  });
895
944
  }
896
- return layers.map((l) => {
897
- const abs = nextAbsMap.get(l.id);
898
- if (!abs)
899
- return l;
900
- const parent = l.parentId ? (byId.get(l.parentId) ?? null) : null;
901
- const parentAbs = l.parentId
902
- ? (nextAbsMap.get(l.parentId) ?? absMap.get(l.parentId) ?? null)
903
- : rootFrame(rootSize);
904
- return layerFromAbsoluteRect(l, abs, parentAbs, parent, rootSize);
945
+ return applyAbsoluteRects(layers, nextAbsMap, absMap, rootSize);
946
+ }
947
+ /**
948
+ * Scale (or move) a multi-selection as one AABB — Figma/Canva transform box.
949
+ * Top-level selected layers map into `nextBox`; nested children follow if the
950
+ * parent has auto-size children (groups default on).
951
+ */
952
+ export function scaleSelectionAbsolute(layers, selectedIds, prevBox, nextBox, rootSize) {
953
+ const sx = prevBox.w > 0 ? nextBox.w / prevBox.w : 1;
954
+ const sy = prevBox.h > 0 ? nextBox.h / prevBox.h : 1;
955
+ const absMap = computeAbsoluteRects(layers, rootSize);
956
+ const byId = new Map(layers.map((l) => [l.id, l]));
957
+ const nextAbsMap = new Map();
958
+ const mapRect = (r) => ({
959
+ x: nextBox.x + (r.x - prevBox.x) * sx,
960
+ y: nextBox.y + (r.y - prevBox.y) * sy,
961
+ w: Math.max(1, r.w * sx),
962
+ h: Math.max(1, r.h * sy)
905
963
  });
964
+ for (const id of topLevelSelectedIds(layers, selectedIds)) {
965
+ const layer = byId.get(id);
966
+ const r = absMap.get(id);
967
+ if (!layer || !r)
968
+ continue;
969
+ nextAbsMap.set(id, mapRect(r));
970
+ const scaleKids = shouldAutoSizeChildren(layer);
971
+ for (const did of getDescendantIds(layers, id)) {
972
+ const dr = absMap.get(did);
973
+ if (!dr)
974
+ continue;
975
+ nextAbsMap.set(did, scaleKids ? mapRect(dr) : dr);
976
+ }
977
+ }
978
+ return applyAbsoluteRects(layers, nextAbsMap, absMap, rootSize);
906
979
  }
@@ -0,0 +1,31 @@
1
+ import type { CanvasLayerKind } from './canvasDocument.js';
2
+ export interface CanvasSvgShape {
3
+ viewBox: {
4
+ w: number;
5
+ h: number;
6
+ };
7
+ d: string;
8
+ /** SVG preserveAspectRatio meet (uniform) vs none (stretch). */
9
+ meet: boolean;
10
+ fill: string;
11
+ }
12
+ /** Stage + export share the same SVG paths so PNG matches the canvas. */
13
+ export declare const CANVAS_SVG_SHAPES: Partial<Record<CanvasLayerKind, CanvasSvgShape>>;
14
+ export declare function svgShapeFit(box: {
15
+ w: number;
16
+ h: number;
17
+ }, viewBox: {
18
+ w: number;
19
+ h: number;
20
+ }, meet: boolean): {
21
+ tx: number;
22
+ ty: number;
23
+ sx: number;
24
+ sy: number;
25
+ };
26
+ export declare function drawCanvasSvgShape(ctx: CanvasRenderingContext2D, rect: {
27
+ x: number;
28
+ y: number;
29
+ w: number;
30
+ h: number;
31
+ }, shape: CanvasSvgShape, fill: string | undefined, stroke: string | undefined, strokeWidth: number | undefined): void;
@@ -0,0 +1,82 @@
1
+ function polygonPath(points) {
2
+ const nums = points
3
+ .trim()
4
+ .split(/[\s,]+/)
5
+ .map(Number)
6
+ .filter((n) => Number.isFinite(n));
7
+ const cmds = [];
8
+ for (let i = 0; i + 1 < nums.length; i += 2) {
9
+ cmds.push(`${i === 0 ? 'M' : 'L'}${nums[i]} ${nums[i + 1]}`);
10
+ }
11
+ return `${cmds.join(' ')} Z`;
12
+ }
13
+ /** Stage + export share the same SVG paths so PNG matches the canvas. */
14
+ export const CANVAS_SVG_SHAPES = {
15
+ triangle: {
16
+ viewBox: { w: 100, h: 100 },
17
+ d: polygonPath('50,4 96,96 4,96'),
18
+ meet: false,
19
+ fill: '#f59e0b'
20
+ },
21
+ star: {
22
+ viewBox: { w: 100, h: 100 },
23
+ d: polygonPath('50,5 61,38 96,38 68,59 79,92 50,72 21,92 32,59 4,38 39,38'),
24
+ meet: true,
25
+ fill: '#ef4444'
26
+ },
27
+ hexagon: {
28
+ viewBox: { w: 100, h: 100 },
29
+ d: polygonPath('25,5 75,5 95,50 75,95 25,95 5,50'),
30
+ meet: false,
31
+ fill: '#06b6d4'
32
+ },
33
+ pentagon: {
34
+ viewBox: { w: 100, h: 100 },
35
+ d: polygonPath('50,5 95,38 78,95 22,95 5,38'),
36
+ meet: true,
37
+ fill: '#a855f7'
38
+ },
39
+ diamond: {
40
+ viewBox: { w: 100, h: 100 },
41
+ d: polygonPath('50,4 96,50 50,96 4,50'),
42
+ meet: false,
43
+ fill: '#f43f5e'
44
+ },
45
+ heart: {
46
+ viewBox: { w: 24, h: 24 },
47
+ d: 'M12 21s-6.7-4.35-9.33-7.6C.5 10.8 1.1 7.1 3.9 5.5 6.1 4.25 8.55 5 12 8.1c3.45-3.1 5.9-3.85 8.1-2.6 2.8 1.6 3.4 5.3 1.23 7.9C18.7 16.65 12 21 12 21z',
48
+ meet: true,
49
+ fill: '#ec4899'
50
+ }
51
+ };
52
+ export function svgShapeFit(box, viewBox, meet) {
53
+ const sx = box.w / Math.max(1, viewBox.w);
54
+ const sy = box.h / Math.max(1, viewBox.h);
55
+ if (!meet)
56
+ return { tx: 0, ty: 0, sx, sy };
57
+ const s = Math.min(sx, sy);
58
+ return {
59
+ tx: (box.w - viewBox.w * s) / 2,
60
+ ty: (box.h - viewBox.h * s) / 2,
61
+ sx: s,
62
+ sy: s
63
+ };
64
+ }
65
+ export function drawCanvasSvgShape(ctx, rect, shape, fill, stroke, strokeWidth) {
66
+ const fit = svgShapeFit(rect, shape.viewBox, shape.meet);
67
+ const path = new Path2D(shape.d);
68
+ ctx.save();
69
+ ctx.translate(rect.x + fit.tx, rect.y + fit.ty);
70
+ ctx.scale(fit.sx, fit.sy);
71
+ const paint = fill ?? shape.fill;
72
+ if (paint) {
73
+ ctx.fillStyle = paint;
74
+ ctx.fill(path);
75
+ }
76
+ if (stroke && (strokeWidth ?? 0) > 0) {
77
+ ctx.strokeStyle = stroke;
78
+ ctx.lineWidth = strokeWidth ?? 0;
79
+ ctx.stroke(path);
80
+ }
81
+ ctx.restore();
82
+ }
@@ -1,5 +1,5 @@
1
1
  import { createCanvasLayer, defaultSlotFromRect, ensureLayerSlot } from './canvasDocument.js';
2
- import { computeAbsoluteRects, contentPadding, deleteSubtree, getChildren, getSubtreeIds, slotFromLocalRect } from './canvasHierarchy.js';
2
+ import { computeAbsoluteRects, contentPadding, deleteSubtree, getChildren, getSubtreeIds, scaleSubtreeAbsolute, slotFromLocalRect } from './canvasHierarchy.js';
3
3
  import { uid } from './mediaTracks.js';
4
4
  const EXPOSEABLE_FIELDS = [
5
5
  'text',
@@ -91,9 +91,7 @@ export function createWidgetFromSelection(doc, selectedIds, name = 'Widget') {
91
91
  const wasRoot = oldId ? selectedIds.includes(oldId) : false;
92
92
  if (wasRoot) {
93
93
  const abs = oldId ? absMap.get(oldId) : null;
94
- const local = abs
95
- ? { x: abs.x - minX, y: abs.y - minY, w: abs.w, h: abs.h }
96
- : l.rect;
94
+ const local = abs ? { x: abs.x - minX, y: abs.y - minY, w: abs.w, h: abs.h } : l.rect;
97
95
  return {
98
96
  ...l,
99
97
  parentId: null,
@@ -168,9 +166,7 @@ export function placeWidgetInstance(doc, definitionId, opts) {
168
166
  const parentAbs = parentId
169
167
  ? (absMap.get(parentId) ?? { x: 0, y: 0, w: doc.width, h: doc.height })
170
168
  : { x: 0, y: 0, w: doc.width, h: doc.height };
171
- const pad = parentLayer
172
- ? contentPadding(parentLayer)
173
- : { left: 0, top: 0, right: 0, bottom: 0 };
169
+ const pad = parentLayer ? contentPadding(parentLayer) : { left: 0, top: 0, right: 0, bottom: 0 };
174
170
  const contentW = Math.max(1, parentAbs.w - pad.left - pad.right);
175
171
  const contentH = Math.max(1, parentAbs.h - pad.top - pad.bottom);
176
172
  const x = opts?.x ?? (parentId ? Math.round((contentW - def.width) / 2) : 80);
@@ -334,7 +330,26 @@ export function flattenLayersWithWidgets(layers, widgets, depth = 0) {
334
330
  continue;
335
331
  }
336
332
  const resolved = resolveWidgetInstance(layer, def);
337
- const nested = resolved.map((l) => l.parentId === null ? { ...l, parentId: layer.id } : l);
333
+ let nested = resolved.map((l) => (l.parentId === null ? { ...l, parentId: layer.id } : l));
334
+ const defW = Math.max(1, def.width);
335
+ const defH = Math.max(1, def.height);
336
+ const instW = Math.max(1, layer.rect.w);
337
+ const instH = Math.max(1, layer.rect.h);
338
+ const sx = instW / defW;
339
+ const sy = instH / defH;
340
+ const needsScale = Math.abs(sx - 1) > 0.001 || Math.abs(sy - 1) > 0.001;
341
+ if (needsScale) {
342
+ const defHost = {
343
+ ...layer,
344
+ parentId: null,
345
+ kind: 'group',
346
+ clipChildren: false,
347
+ rect: { x: 0, y: 0, w: defW, h: defH },
348
+ slot: defaultSlotFromRect({ x: 0, y: 0, w: defW, h: defH })
349
+ };
350
+ const scaled = scaleSubtreeAbsolute([defHost, ...nested], layer.id, { x: 0, y: 0, w: defW, h: defH }, { x: 0, y: 0, w: instW, h: instH }, { width: instW, height: instH });
351
+ nested = scaled.filter((l) => l.id !== layer.id);
352
+ }
338
353
  const slotByName = new Map();
339
354
  for (const l of nested) {
340
355
  if (l.kind === 'namedSlot') {
@@ -349,27 +364,45 @@ export function flattenLayersWithWidgets(layers, widgets, depth = 0) {
349
364
  parentId: null,
350
365
  kind: 'group',
351
366
  clipChildren: false,
352
- rect: { x: 0, y: 0, w: layer.rect.w, h: layer.rect.h },
353
- slot: defaultSlotFromRect({ x: 0, y: 0, w: layer.rect.w, h: layer.rect.h })
367
+ rect: { x: 0, y: 0, w: instW, h: instH },
368
+ slot: defaultSlotFromRect({ x: 0, y: 0, w: instW, h: instH })
354
369
  };
355
370
  const layoutProbe = computeAbsoluteRects([hostLocal, ...nested], {
356
- width: layer.rect.w,
357
- height: layer.rect.h
371
+ width: instW,
372
+ height: instH
358
373
  });
359
374
  const injected = sceneKids.map((kid) => {
375
+ const kidRect = needsScale
376
+ ? {
377
+ x: kid.rect.x * sx,
378
+ y: kid.rect.y * sy,
379
+ w: kid.rect.w * sx,
380
+ h: kid.rect.h * sy
381
+ }
382
+ : kid.rect;
360
383
  const target = kid.fillSlot?.trim();
361
384
  const slotId = target ? slotByName.get(target) : undefined;
362
385
  if (!slotId) {
363
- return { ...kid, parentId: layer.id };
386
+ return {
387
+ ...kid,
388
+ parentId: layer.id,
389
+ rect: kidRect,
390
+ slot: kid.slot
391
+ ? {
392
+ ...kid.slot,
393
+ ...slotFromLocalRect({ width: instW, height: instH }, kidRect, kid.slot.anchors)
394
+ }
395
+ : defaultSlotFromRect(kidRect)
396
+ };
364
397
  }
365
398
  // Scene stores widget-local rects (parentId = instance). Convert to
366
399
  // slot-local so paint/hit-test match the named slot coordinate space.
367
400
  const slotAbs = layoutProbe.get(slotId) ?? { x: 0, y: 0, w: 0, h: 0 };
368
401
  const local = {
369
- x: kid.rect.x - slotAbs.x,
370
- y: kid.rect.y - slotAbs.y,
371
- w: kid.rect.w,
372
- h: kid.rect.h
402
+ x: kidRect.x - slotAbs.x,
403
+ y: kidRect.y - slotAbs.y,
404
+ w: kidRect.w,
405
+ h: kidRect.h
373
406
  };
374
407
  return {
375
408
  ...kid,
@@ -385,7 +418,7 @@ export function flattenLayersWithWidgets(layers, widgets, depth = 0) {
385
418
  });
386
419
  out.push({
387
420
  ...layer,
388
- clipChildren: true,
421
+ clipChildren: !!layer.clipChildren,
389
422
  kind: 'group',
390
423
  name: layer.name
391
424
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r2digisolutions/components",
3
- "version": "0.20.0",
3
+ "version": "0.21.1",
4
4
  "private": false,
5
5
  "description": "R2DigiSolutions Svelte 5 component library — Atomic Design, Tailwind 4, Light/Dark mode",
6
6
  "license": "MIT",