Skip to content

AI-native design editor. Open-source Figma alternative.

fix(layout): size each axis on its own and lay out before geometry reads (#942)

Danila Poyarkov11e708de3922
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c1070eee..0ebd7e202 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,7 @@
- `fractionalPosition`, `orderKeyBetween`, and `siblingOrderKeys` moved from `@open-pencil/fig/node-change` to `@open-pencil/scene-graph/order-keys`; the `@open-pencil/core` root still exports `fractionalPosition`. `orderKeyBetween` now always returns a key: when no printable key sorts between its bounds it returns a key above `lo`, which `hasOrderKeyBetween` detects, and it takes an optional suffix that `siblingOrderKeys` can request through `{ suffix }`.
- Shared rooms record the layer tree in a new format, so people on this version and on earlier versions can no longer join each other's rooms. A room this browser saved with an earlier version converts when you open it again.
- `SceneGraph.hitTestFrame` is now `hitTestDropTarget`, which returns only layers that take a drop, as in Figma: it skips groups, boolean operations, component sets, and locked layers, follows rotation, and respects clipping. The editor's `adoptNodesIntoSection` is now `adoptCoveredLayers`, which also takes a frame, and leaves locked layers out.
+- `SceneNode.primaryAxisSizing` and `counterAxisSizing` are `AxisSizingMode` (`'FIXED' | 'HUG'`) instead of `LayoutSizing`: fill is stored only on the child, as `layoutGrow` along its parent's primary axis and `layoutAlignSelf: 'STRETCH'` across it, as Figma stores it. Read and change a node's per-axis sizing with `layoutSizing`, `layoutSizingOptions`, and `layoutSizingUpdates` from `@open-pencil/scene-graph`. A frame that an earlier version stored as filling through its own sizing, which `.fig` files never kept, is fixed until it is set to fill again.
- `buildDerivedTextDataV4` is removed from `@open-pencil/core`, and `sceneNodeToKiwi` no longer writes glyph outlines by itself: pass the `runtime` that `withFigExportRuntime(graph, canvasKit, write)` hands its callback. In `@open-pencil/fig/node-change`, `FigNodeChangeExportRuntime` takes `shapeText(node)` instead of `getGlyphOutlineMetrics`, `buildDerivedTextData` takes the `baselines` it writes, and `convertFigmaDerivedTextGlyphs` takes the text's characters.
- The `updates` messages from `@open-pencil/vue` no longer include `availableTitle`, `installPrompt`, `installedTitle`, and `downloading`, which only the system update dialogs and download toast used; `installed` now takes only `{ version }`, and `install` reads "Install Update". The Software Update window uses the new `windowTitle`, `currentVersion`, `whatsNew`, `installAndRestart`, `restartNow`, and related messages.
@@ -79,6 +80,7 @@
### Changed
+- The width and height menus in the properties panel offer Hug only for auto-layout frames and text, as in Figma; on a frame without auto layout it had no effect.
- Confirm deleting an AI conversation in the standard confirmation dialog, which names the conversation, instead of a prompt inside the chat panel.
- Run Pi with the providers you signed in to in the Pi CLI and Pi's default model, so an AI Gateway key and a model ID are optional. The Pi model editor shows whether the Harness companion and MCP server are installed and match the app, and a chat whose Harness companion is missing, or whose companion or MCP server does not match the app, says what to fix and offers guided setup instead of failing with a generic error, and the message and its attachments stay in the composer.
- Point Codex install instructions at `@agentclientprotocol/codex-acp`, which replaces `@zed-industries/codex-acp` and provides the same `codex-acp` command.
@@ -117,6 +119,10 @@
### Fixed
+- Fill one axis of a grid cell: a grid child set to fill its width or its height no longer fills both, and an auto-layout child of a grid keeps its own size unless it fills, as in Figma. Design JSX renders and exports `w="fill"` and `h="fill"` in grids, and HTML and Tailwind export leave out the size a child fills, so it stretches in the browser too.
+- Resize auto-layout frames that fill across their parent with it: one with a fixed size on that axis kept its old size. A filling child still counts toward a hugging parent's size, as in Figma.
+- Set `layoutSizingHorizontal` and `layoutSizingVertical` in scripts as Figma does: Fill is recorded on the child for that axis instead of on the frame's own sizing, which `.fig` export dropped, text switches its `textAutoResize`, and sizing Figma refuses, such as Hug on a frame without auto layout, throws Figma's error.
+- Read geometry in scripts after an edit without waiting for the script to finish: `x`, `y`, `width`, `height`, `relativeTransform`, `absoluteTransform`, `absoluteBoundingBox`, and `absoluteRenderBounds` lay out what the script changed first, as in Figma, so a hugging parent reports its new size right after a child is added.
- Draw segmented controls in the properties panel at the height of the fields beside them.
- Keep saving AI chat history in Safari Private Browsing after a message with an image or a reply that changed the document. Safari cannot store image data that way in a private window, so the conversation stopped saving from that point and showed "Chat history could not be saved".
- `figma.combineAsVariants` derives variant properties from components named as Figma names variants, such as `State=On, Size=Large`, as Combine as variants in the editor now does too; before, only slash-separated names gave the set any properties.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 0648cce1b..7fff2a026 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -94,5 +94,6 @@ Pixel-affecting features need committed visual coverage, not only mock or geomet
- **Shape follows Figma.** Match `@figma/plugin-typings` at the version pinned in the root `package.json`. `packages/core/src/figma-api/compatibility.ts` type-checks the supported surface against `PluginAPI`; add every new member to `SupportedPluginAPI` there. Model unsupported members explicitly rather than approximating them.
- **Behavior follows Figma.** Read the Plugin API documentation for the member, and for anything observable (geometry, ordering, defaults, errors) run the same script in live Figma and record the observed result in the test. `figma-use` and `tests/figma/` are the live oracle; `tests/fixtures/figma-oracles/` holds recorded values.
- **User actions are shared code.** When an editor command does the same thing (group, ungroup, boolean, flatten, instance creation, component sync), call the implementation under `packages/core/src/editor/` or its shared helper. Do not reimplement geometry, placement, or propagation here; new geometry helpers belong in Scene Graph.
+- Geometry getters lay out what the graph's edits touched since the last read, as Figma does, through `flushPendingLayout` in `packages/core/src/figma-api/pending-layout.ts`; a new geometry getter calls it first (`packages/core/tests/figma-api/pending-layout.test.ts`).
- Node proxies live in `packages/core/src/figma-api/proxy.ts` and `packages/core/src/figma-api/accessors/`; `packages/core/src/figma-api/render-bounds.ts` implements Figma's `absoluteRenderBounds` semantics and is the only geometry that is Figma-specific.
- `packages/core/src/figma-api/index.ts` stays under the 600-line limit by moving whole domains into sibling modules such as `components.ts` and `text.ts`, not by extracting generic helpers into this folder.
diff --git a/packages/core/src/editor/shapes/frame-presets.ts b/packages/core/src/editor/shapes/frame-presets.ts
index 814447a5d..eca1ac1dd 100644
--- a/packages/core/src/editor/shapes/frame-presets.ts
+++ b/packages/core/src/editor/shapes/frame-presets.ts
@@ -34,10 +34,11 @@ function fixedSizePatch(
preset: FramePresetDimensions
): FrameResizePatch {
const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined
+ // A flex parent set to stretch its children stretches this one too unless it opts out.
const inheritsStretch =
node.layoutPositioning !== 'ABSOLUTE' &&
- parent?.layoutMode !== 'NONE' &&
- (parent?.layoutMode === 'GRID' || parent?.counterAxisAlign === 'STRETCH')
+ (parent?.layoutMode === 'HORIZONTAL' || parent?.layoutMode === 'VERTICAL') &&
+ parent.counterAxisAlign === 'STRETCH'
return {
width: preset.width,
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index c3a734c8a..157c6e54b 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -24,6 +24,7 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
+import { flushPendingLayout } from '#core/figma-api/pending-layout'
import type { NodeProxyHost } from '#core/figma-api/proxy'
import { computeAbsoluteRenderBounds } from '#core/figma-api/render-bounds'
import {
@@ -116,6 +117,7 @@ export function installBasicNodeProxyAccessors(
// Figma places a node by its top-left corner in its container, wherever rotation takes it.
x: {
get(this: ProxyThis): number {
+ flushPendingLayout(graph(this, internals))
return containerTransform(raw(this, internals), graph(this, internals))[2]
},
set(this: ProxyThis, value: number) {
@@ -124,6 +126,7 @@ export function installBasicNodeProxyAccessors(
},
y: {
get(this: ProxyThis): number {
+ flushPendingLayout(graph(this, internals))
return containerTransform(raw(this, internals), graph(this, internals))[5]
},
set(this: ProxyThis, value: number) {
@@ -132,11 +135,13 @@ export function installBasicNodeProxyAccessors(
},
width: {
get(this: ProxyThis): number {
+ flushPendingLayout(graph(this, internals))
return raw(this, internals).width
}
},
height: {
get(this: ProxyThis): number {
+ flushPendingLayout(graph(this, internals))
return raw(this, internals).height
}
},
@@ -156,8 +161,9 @@ export function installBasicNodeProxyAccessors(
},
relativeTransform: {
get(this: ProxyThis): FigmaTransform {
- const node = raw(this, internals)
const scene = graph(this, internals)
+ flushPendingLayout(scene)
+ const node = raw(this, internals)
// Children of groups report a transform into the container, as Figma does.
if (inGroup(node, scene)) return figmaTransform(containerTransform(node, scene))
const sourceTransform = node.source.fig.rawTransform
@@ -180,16 +186,19 @@ export function installBasicNodeProxyAccessors(
},
absoluteTransform: {
get(this: ProxyThis): FigmaTransform {
+ flushPendingLayout(graph(this, internals))
return figmaTransform(getWorldMatrix(raw(this, internals), graph(this, internals)))
}
},
absoluteBoundingBox: {
get(this: ProxyThis): Rect {
+ flushPendingLayout(graph(this, internals))
return getAxisAlignedWorldBounds(raw(this, internals), graph(this, internals))
}
},
absoluteRenderBounds: {
get(this: ProxyThis): Rect | null {
+ flushPendingLayout(graph(this, internals))
return computeAbsoluteRenderBounds(graph(this, internals), raw(this, internals))
}
}
diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.ts
index 7c299f013..ad5f73779 100644
--- a/packages/core/src/figma-api/accessors/layout.ts
+++ b/packages/core/src/figma-api/accessors/layout.ts
@@ -1,45 +1,21 @@
-import type { LayoutMode, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ layoutSizing,
+ layoutSizingError,
+ layoutSizingUpdates,
+ type LayoutMode,
+ type LayoutSizing,
+ type LayoutSizingAxis,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import {
+ graph,
raw,
updateNode,
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {
- return target[internals.graph] as SceneGraph
-}
-
-function parentLayout(
- target: ProxyThis,
- internals: NodeProxyInternals
-): 'HORIZONTAL' | 'VERTICAL' | 'NONE' {
- const node = raw(target, internals)
- if (!node.parentId) return 'NONE'
- const parent = graph(target, internals).getNode(node.parentId)
- if (!parent) return 'NONE'
- const mode = parent.layoutMode
- return mode === 'HORIZONTAL' || mode === 'VERTICAL' ? mode : 'NONE'
-}
-
-function setLayoutSizing(
- target: ProxyThis,
- internals: NodeProxyInternals,
- axis: 'HORIZONTAL' | 'VERTICAL',
- value: string
-): void {
- const node = raw(target, internals)
- const layout = node.layoutMode !== 'NONE' ? node.layoutMode : parentLayout(target, internals)
- const isHorizontal = axis === 'HORIZONTAL'
- const usesCounterAxis = isHorizontal ? layout === 'VERTICAL' : layout === 'HORIZONTAL'
- const updates: Partial<SceneNode> = usesCounterAxis
- ? { counterAxisSizing: value as SceneNode['counterAxisSizing'] }
- : { primaryAxisSizing: value as SceneNode['primaryAxisSizing'] }
- if (parentLayout(target, internals) === axis) updates.layoutGrow = value === 'FILL' ? 1 : 0
- updateNode(target, internals, updates)
-}
-
export function installLayoutNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals
@@ -112,25 +88,36 @@ function axisSizingModeAccessor(
return value === 'HUG' ? 'AUTO' : value
},
set(this: ProxyThis, value: string) {
- const mapped = value === 'AUTO' ? 'HUG' : value
- updateNode(this, internals, { [field]: mapped } as Partial<SceneNode>)
+ if (value !== 'FIXED' && value !== 'AUTO') {
+ throw new TypeError(`Invalid ${field}Mode: ${String(value)}`)
+ }
+ updateNode(this, internals, { [field]: value === 'AUTO' ? 'HUG' : 'FIXED' })
}
}
}
+const LAYOUT_SIZINGS = new Set<unknown>(['FIXED', 'HUG', 'FILL'] satisfies LayoutSizing[])
+
+function isLayoutSizing(value: unknown): value is LayoutSizing {
+ return LAYOUT_SIZINGS.has(value)
+}
+
function layoutSizingAccessor(
internals: NodeProxyInternals,
- axis: 'HORIZONTAL' | 'VERTICAL'
+ axis: LayoutSizingAxis
): PropertyDescriptor {
+ const property = axis === 'HORIZONTAL' ? 'layoutSizingHorizontal' : 'layoutSizingVertical'
return {
- get(this: ProxyThis): string {
- const node = raw(this, internals)
- const layout = node.layoutMode !== 'NONE' ? node.layoutMode : parentLayout(this, internals)
- if (layout === 'NONE') return 'FIXED'
- return layout === axis ? node.primaryAxisSizing : node.counterAxisSizing
+ get(this: ProxyThis): LayoutSizing {
+ return layoutSizing(graph(this, internals), raw(this, internals), axis)
},
- set(this: ProxyThis, value: string) {
- setLayoutSizing(this, internals, axis, value)
+ set(this: ProxyThis, value: unknown) {
+ if (!isLayoutSizing(value)) throw new TypeError(`Invalid ${property}: ${String(value)}`)
+ const sceneGraph = graph(this, internals)
+ const node = raw(this, internals)
+ const error = layoutSizingError(sceneGraph, node, value)
+ if (error) throw new Error(`in set_${property}: ${error}`)
+ updateNode(this, internals, layoutSizingUpdates(sceneGraph, node, axis, value))
}
}
}
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 6afda76e0..f584306e5 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -44,6 +44,7 @@ import type {
FigmaTextNode,
FigmaVectorNode
} from './node-types'
+import { startPendingLayout } from './pending-layout'
import {
FigmaNodeProxy,
INTERNAL_ID,
@@ -96,6 +97,7 @@ export class FigmaAPI implements NodeProxyHost {
constructor(graph: SceneGraph) {
this.graph = graph
+ startPendingLayout(graph)
const pages = graph.getPages()
this._currentPageId = pages[0]?.id ?? graph.rootId
}
diff --git a/packages/core/src/figma-api/pending-layout.ts b/packages/core/src/figma-api/pending-layout.ts
new file mode 100644
index 000000000..99a0f3d88
--- /dev/null
+++ b/packages/core/src/figma-api/pending-layout.ts
@@ -0,0 +1,57 @@
+import {
+ createSceneMutationImpact,
+ recordSceneMutations,
+ type SceneGraph,
+ type SceneMutationImpact
+} from '@open-pencil/scene-graph'
+
+import { createLayoutRunner } from '#core/layout/mutations'
+
+interface PendingLayout {
+ impact: SceneMutationImpact
+ flushing: boolean
+}
+
+const pendingByGraph = new WeakMap<SceneGraph, PendingLayout>()
+
+function clearImpact(impact: SceneMutationImpact): void {
+ for (const ids of Object.values(impact)) ids.clear()
+}
+
+function mergeImpact(into: SceneMutationImpact, from: SceneMutationImpact): void {
+ for (const key of Object.keys(into) as (keyof SceneMutationImpact)[]) {
+ for (const id of from[key]) into[key].add(id)
+ }
+}
+
+/**
+ * Records the graph's edits so that reading geometry lays out what they touched first, as Figma
+ * does: a script that fills a child and then reads its width sees the filled width. A graph has
+ * one recorder for its lifetime, kept across APIs: a script that failed before its tool laid
+ * out its edits leaves them for the next read to lay out.
+ */
+export function startPendingLayout(graph: SceneGraph): void {
+ if (pendingByGraph.has(graph)) return
+ const pending: PendingLayout = { impact: createSceneMutationImpact(), flushing: false }
+ pendingByGraph.set(graph, pending)
+ // Layout's own writes are its result, not new edits.
+ recordSceneMutations(graph, pending.impact, () => !pending.flushing && !graph.isApplyingLayout)
+}
+
+/** Lays out the edits recorded since the last geometry read. */
+export function flushPendingLayout(graph: SceneGraph): void {
+ const pending = pendingByGraph.get(graph)
+ if (!pending || pending.flushing || pending.impact.changedNodeIds.size === 0) return
+ const impact = structuredClone(pending.impact)
+ clearImpact(pending.impact)
+ pending.flushing = true
+ try {
+ createLayoutRunner(() => graph).runLayoutForImpact(impact)
+ } catch (error) {
+ // The edits are still unlaid out, so the next read tries again.
+ mergeImpact(pending.impact, impact)
+ throw error
+ } finally {
+ pending.flushing = false
+ }
+}
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 2ca178bbf..e194b2ce0 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -14,6 +14,12 @@ import {
import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direction'
import { applyYogaLayout } from './layout/apply'
+import {
+ fillKeepsSizeInHuggingParent,
+ ownAxisSizing,
+ setCrossAxisSizing,
+ setMainAxisSizing
+} from './layout/axis-sizing'
import { usesDetachedDerivedLayout } from './layout/derived'
import { applyEffectiveGeneratedTextLayout } from './layout/effective-generated-text'
import { buildGridTree, createGridChildNode } from './layout/grid'
@@ -24,7 +30,12 @@ export {
setTextMeasurer,
type TextMeasurer
} from './layout/text-measurement'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ layoutSizing,
+ type LayoutSizing,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { estimateTextSize, getTextMeasurer } from './layout/text-measurement'
import {
@@ -234,12 +245,11 @@ function configureChildAsGrid(
configureAbsoluteChild(yogaGC, gc)
yogaChild.insertChild(yogaGC, yogaChild.getChildCount())
} else {
- yogaChild.insertChild(createGridChildNode(gc), yogaChild.getChildCount())
+ yogaChild.insertChild(createGridChildNode(graph, gc), yogaChild.getChildCount())
}
}
}
-type AxisSizing = SceneNode['primaryAxisSizing']
function sizesFitParent(
parent: SceneNode,
childCount: number,
@@ -278,46 +288,29 @@ function derivedMainAxisFitsParent(
)
}
-function usesAuthoritativeGeneratedStretch(parent: SceneNode, child: SceneNode): boolean {
- if (
- child.layoutAlignSelf !== 'STRETCH' ||
- parent.source.format === 'fig' ||
- !parent.derivedLayout
- ) {
- return false
- }
- const derivedCrossSize =
- parent.layoutMode === 'HORIZONTAL' ? parent.derivedLayout.height : parent.derivedLayout.width
- const parentCrossSize = parent.layoutMode === 'HORIZONTAL' ? parent.height : parent.width
- return derivedCrossSize !== undefined && Math.abs(derivedCrossSize - parentCrossSize) < 0.001
-}
-
function configureAutoLayoutChildSizing(
yogaChild: YogaNode,
child: SceneNode,
parent: SceneNode,
graph: SceneGraph,
- widthSizing: AxisSizing,
- heightSizing: AxisSizing
+ widthSizing: LayoutSizing,
+ heightSizing: LayoutSizing
): void {
const isParentRow = parent.layoutMode === 'HORIZONTAL'
const fixedDerivedMainAxis = isParentRow
? derivedMainAxisFitsParent(graph, parent, child, 'width')
: derivedMainAxisFitsParent(graph, parent, child, 'height')
- const stretchesAuthoritativeCrossAxis = usesAuthoritativeGeneratedStretch(parent, child)
if (isParentRow) {
if (fixedDerivedMainAxis) yogaChild.setWidth(child.derivedLayout?.width ?? child.width)
else setMainAxisSizing(yogaChild, 'width', widthSizing, child.width, child.layoutGrow)
- if (!stretchesAuthoritativeCrossAxis) {
- setCrossAxisSizing(yogaChild, 'height', heightSizing, child.height)
- }
+ const keepsSize = fillKeepsSizeInHuggingParent(child, parent, 'height')
+ setCrossAxisSizing(yogaChild, 'height', heightSizing, child.height, keepsSize)
return
}
- if (!stretchesAuthoritativeCrossAxis) {
- setCrossAxisSizing(yogaChild, 'width', widthSizing, child.width)
- }
+ const keepsSize = fillKeepsSizeInHuggingParent(child, parent, 'width')
+ setCrossAxisSizing(yogaChild, 'width', widthSizing, child.width, keepsSize)
if (fixedDerivedMainAxis) yogaChild.setHeight(child.derivedLayout?.height ?? child.height)
else setMainAxisSizing(yogaChild, 'height', heightSizing, child.height, child.layoutGrow)
}
@@ -330,9 +323,8 @@ function configureChildAsAutoLayout(
inheritedDirection: 'LTR' | 'RTL'
): void {
const direction = resolveNodeLayoutDirection(child, inheritedDirection)
- const isChildRow = child.layoutMode === 'HORIZONTAL'
- const widthSizing = isChildRow ? child.primaryAxisSizing : child.counterAxisSizing
- const heightSizing = isChildRow ? child.counterAxisSizing : child.primaryAxisSizing
+ const widthSizing = layoutSizing(graph, child, 'HORIZONTAL')
+ const heightSizing = layoutSizing(graph, child, 'VERTICAL')
configureAutoLayoutChildSizing(yogaChild, child, parent, graph, widthSizing, heightSizing)
@@ -340,9 +332,12 @@ function configureChildAsAutoLayout(
if (selfAlign != null) yogaChild.setAlignSelf(selfAlign)
if (usesDetachedDerivedLayout(child)) {
+ // The imported size is what the child's own hug produced, whether or not it also fills.
const derived = child.derivedLayout
- if (widthSizing === 'HUG') yogaChild.setWidth(derived?.width ?? child.width)
- if (heightSizing === 'HUG') yogaChild.setHeight(derived?.height ?? child.height)
+ if (ownAxisSizing(child, 'width') === 'HUG') yogaChild.setWidth(derived?.width ?? child.width)
+ if (ownAxisSizing(child, 'height') === 'HUG') {
+ yogaChild.setHeight(derived?.height ?? child.height)
+ }
applyMinMaxConstraints(yogaChild, child)
return
}
@@ -554,51 +549,3 @@ function configureTextLeaf(
})
}
}
-
-function setMainAxisSizing(
- yogaNode: YogaNode,
- axis: 'width' | 'height',
- sizing: AxisSizing,
- fixedValue: number,
- grow: number
-): void {
- if (grow > 0) {
- yogaNode.setFlexGrow(grow)
- yogaNode.setFlexShrink(1)
- yogaNode.setFlexBasis(0)
- return
- }
-
- switch (sizing) {
- case 'FIXED':
- if (axis === 'width') yogaNode.setWidth(fixedValue)
- else yogaNode.setHeight(fixedValue)
- break
- case 'HUG':
- break
- case 'FILL':
- yogaNode.setFlexGrow(1)
- yogaNode.setFlexShrink(1)
- yogaNode.setFlexBasis(0)
- break
- }
-}
-
-function setCrossAxisSizing(
- yogaNode: YogaNode,
- axis: 'width' | 'height',
- sizing: AxisSizing,
- fixedValue: number
-): void {
- switch (sizing) {
- case 'FIXED':
- if (axis === 'width') yogaNode.setWidth(fixedValue)
- else yogaNode.setHeight(fixedValue)
- break
- case 'HUG':
- break
- case 'FILL':
- yogaNode.setAlignSelf(Align.Stretch)
- break
- }
-}
diff --git a/packages/core/src/layout/axis-sizing.ts b/packages/core/src/layout/axis-sizing.ts
new file mode 100644
index 000000000..a1e3f9ce9
--- /dev/null
+++ b/packages/core/src/layout/axis-sizing.ts
@@ -0,0 +1,76 @@
+import { Align, type Node as YogaNode } from 'yoga-layout'
+
+import type { LayoutSizing, SceneNode } from '@open-pencil/scene-graph'
+
+type Axis = 'width' | 'height'
+
+/**
+ * A fixed-size child that fills across a hugging parent still counts toward the hug, as in
+ * Figma: the parent is at least as wide as the child was, and the child stretches beyond that.
+ */
+export function fillKeepsSizeInHuggingParent(
+ child: SceneNode,
+ parent: SceneNode,
+ axis: Axis
+): boolean {
+ return parent.counterAxisSizing === 'HUG' && ownAxisSizing(child, axis) === 'FIXED'
+}
+
+/** An auto-layout frame's own sizing along a screen axis, before any fill from its parent. */
+export function ownAxisSizing(child: SceneNode, axis: Axis): SceneNode['primaryAxisSizing'] {
+ const childPrimary = child.layoutMode === 'VERTICAL' ? 'height' : 'width'
+ return axis === childPrimary ? child.primaryAxisSizing : child.counterAxisSizing
+}
+
+export function setMainAxisSizing(
+ yogaNode: YogaNode,
+ axis: Axis,
+ sizing: LayoutSizing,
+ fixedValue: number,
+ grow: number
+): void {
+ if (grow > 0) {
+ yogaNode.setFlexGrow(grow)
+ yogaNode.setFlexShrink(1)
+ yogaNode.setFlexBasis(0)
+ return
+ }
+
+ switch (sizing) {
+ case 'FIXED':
+ if (axis === 'width') yogaNode.setWidth(fixedValue)
+ else yogaNode.setHeight(fixedValue)
+ break
+ case 'HUG':
+ break
+ case 'FILL':
+ yogaNode.setFlexGrow(1)
+ yogaNode.setFlexShrink(1)
+ yogaNode.setFlexBasis(0)
+ break
+ }
+}
+
+export function setCrossAxisSizing(
+ yogaNode: YogaNode,
+ axis: Axis,
+ sizing: LayoutSizing,
+ fixedValue: number,
+ fillKeepsSize = false
+): void {
+ switch (sizing) {
+ case 'FIXED':
+ if (axis === 'width') yogaNode.setWidth(fixedValue)
+ else yogaNode.setHeight(fixedValue)
+ break
+ case 'HUG':
+ break
+ case 'FILL':
+ yogaNode.setAlignSelf(Align.Stretch)
+ if (fillKeepsSize) {
+ if (axis === 'width') yogaNode.setMinWidth(fixedValue)
+ else yogaNode.setMinHeight(fixedValue)
+ }
+ break
+ }
+}
diff --git a/packages/core/src/layout/grid.ts b/packages/core/src/layout/grid.ts
index 5f240feb8..2e9733d30 100644
--- a/packages/core/src/layout/grid.ts
+++ b/packages/core/src/layout/grid.ts
@@ -1,6 +1,6 @@
import { Direction, Display, Gutter, Edge, type Node as YogaNode } from 'yoga-layout'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { layoutSizing, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direction'
import { configureAbsoluteChild, createYogaNode, mapGridTrack } from './yoga-helpers'
@@ -33,7 +33,7 @@ function configureAsGrid(
yogaNode.setPadding(Edge.Left, node.paddingLeft)
}
-export function createGridChildNode(child: SceneNode): YogaNode {
+export function createGridChildNode(graph: SceneGraph, child: SceneNode): YogaNode {
const yogaChild = createYogaNode()
if (!child.visible) {
yogaChild.setDisplay(Display.None)
@@ -45,20 +45,11 @@ export function createGridChildNode(child: SceneNode): YogaNode {
yogaChild.setGridRowStart(pos.row)
yogaChild.setGridRowEndSpan(pos.rowSpan)
}
- const hasLayout = child.layoutMode !== 'NONE'
- const explicitStretch = child.layoutGrow > 0 || child.layoutAlignSelf === 'STRETCH'
- const inheritsContainerStretch = hasLayout && child.layoutAlignSelf === 'AUTO'
-
- if (explicitStretch || inheritsContainerStretch) {
- yogaChild.setWidthStretch()
- } else {
- yogaChild.setWidth(child.width)
- }
- if (explicitStretch) {
- yogaChild.setHeightStretch()
- } else {
- yogaChild.setHeight(child.height)
- }
+ // Each axis fills its cell on its own, as in Figma: grow for width, stretch for height.
+ if (layoutSizing(graph, child, 'HORIZONTAL') === 'FILL') yogaChild.setWidthStretch()
+ else yogaChild.setWidth(child.width)
+ if (layoutSizing(graph, child, 'VERTICAL') === 'FILL') yogaChild.setHeightStretch()
+ else yogaChild.setHeight(child.height)
}
return yogaChild
}
@@ -79,7 +70,7 @@ export function buildGridTree(
configureAbsoluteChild(yogaChild, child)
root.insertChild(yogaChild, root.getChildCount())
} else {
- const yogaChild = createGridChildNode(child)
+ const yogaChild = createGridChildNode(graph, child)
if (
child.layoutMode === 'GRID' ||
child.layoutMode === 'HORIZONTAL' ||
diff --git a/packages/core/src/layout/mutations.ts b/packages/core/src/layout/mutations.ts
index f4496eeba..6519e30b1 100644
--- a/packages/core/src/layout/mutations.ts
+++ b/packages/core/src/layout/mutations.ts
@@ -45,14 +45,16 @@ export function createLayoutRunner(getGraph: () => SceneGraph) {
const graph = getGraph()
const { result, impact } = await collectSceneMutation(graph, operation)
await beforeLayout?.(result)
- const scopeIds = compactLayoutScope(impact)
- if (scopeIds.length > 0) {
- for (const id of scopeIds) runLayoutForNode(id)
- } else if (fallbackId) {
- computeAllLayouts(graph, fallbackId)
- }
+ if (!runLayoutForImpact(impact) && fallbackId) computeAllLayouts(graph, fallbackId)
return result
}
- return { runLayoutForNode, runMutationWithLayout }
+ /** Lays out what an edit touched; returns whether there was anything to lay out. */
+ function runLayoutForImpact(impact: SceneMutationImpact): boolean {
+ const scopeIds = compactLayoutScope(impact)
+ for (const id of scopeIds) runLayoutForNode(id)
+ return scopeIds.length > 0
+ }
+
+ return { runLayoutForNode, runLayoutForImpact, runMutationWithLayout }
}
diff --git a/packages/core/src/tools/describe/layout-issues.ts b/packages/core/src/tools/describe/layout-issues.ts
index 3fa3a63ea..2920003ef 100644
--- a/packages/core/src/tools/describe/layout-issues.ts
+++ b/packages/core/src/tools/describe/layout-issues.ts
@@ -143,8 +143,6 @@ function checkGrowInHug(ctx: LayoutContext): void {
function checkGrowSizeConflict(ctx: LayoutContext): void {
for (const child of ctx.children) {
if (child.layoutGrow > 0 && child.layoutMode === 'NONE') {
- const mainSizing = ctx.isRow ? child.primaryAxisSizing : child.counterAxisSizing
- if (mainSizing === 'FILL') continue
const fixedDim = ctx.isRow ? child.width : child.height
if (fixedDim > 0 && fixedDim !== 100) {
ctx.issues.push({
@@ -338,7 +336,7 @@ function checkFillWithoutFlex(ctx: LayoutContext): void {
if (node.layoutMode !== 'NONE') return
for (const child of visibleChildren(node, graph)) {
if (!CONTAINER_TYPES.has(child.type)) continue
- if (child.primaryAxisSizing === 'FILL' || child.counterAxisSizing === 'FILL') {
+ if (child.layoutGrow > 0 || child.layoutAlignSelf === 'STRETCH') {
issues.push({
message: `"${child.name}" uses fill sizing but parent "${node.name}" has no auto-layout`,
suggestion: 'Add flex="col" or flex="row" to the parent'
@@ -362,33 +360,19 @@ function effectivelyFillsCrossAxis(child: SceneNode, parent: SceneNode, isRow: b
function childNeedsFill(child: SceneNode, parent: SceneNode, isRow: boolean): boolean {
if (child.layoutMode === 'NONE') return false
- const crossDim = isRow ? child.width : child.height
- const crossSizing = isRow ? child.counterAxisSizing : child.primaryAxisSizing
- if (crossDim <= 0 && crossSizing !== 'FILL') return false
+ // Along the parent's main axis, fill is grow.
+ if (child.layoutGrow > 0) return false
+ const mainDim = isRow ? child.width : child.height
+ if (mainDim <= 0) return false
const mainSizing = isRow ? child.primaryAxisSizing : child.counterAxisSizing
if (mainSizing === 'FIXED') return false
if (effectivelyFillsCrossAxis(child, parent, isRow)) return false
if (child.childIds.length === 0) return false
- return isRow
- ? child.width < parent.width * 0.3 &&
- child.counterAxisSizing !== 'FILL' &&
- child.layoutGrow <= 0
- : child.height < parent.height * 0.3 &&
- child.primaryAxisSizing !== 'FILL' &&
- child.layoutGrow <= 0
+ return isRow ? child.width < parent.width * 0.3 : child.height < parent.height * 0.3
}
-function hasSiblingWithGrowOrFill(
- children: SceneNode[],
- exclude: SceneNode,
- isRow: boolean
-): boolean {
- return children.some((c) => {
- if (c === exclude) return false
- if (c.layoutGrow > 0) return true
- const sizing = isRow ? c.counterAxisSizing : c.primaryAxisSizing
- return sizing === 'FILL'
- })
+function hasGrowingSibling(children: SceneNode[], exclude: SceneNode): boolean {
+ return children.some((c) => c !== exclude && c.layoutGrow > 0)
}
function checkNestedFlexWithoutFill(ctx: LayoutContext): void {
@@ -398,7 +382,7 @@ function checkNestedFlexWithoutFill(ctx: LayoutContext): void {
if (node.layoutWrap === 'WRAP') return
for (const child of children) {
if (!childNeedsFill(child, node, isRow)) continue
- if (hasSiblingWithGrowOrFill(children, child, isRow)) continue
+ if (hasGrowingSibling(children, child)) continue
issues.push({
message: `Nested flex "${child.name}" may collapse — no fill or grow in "${node.name}"`,
suggestion: 'Add w="fill" or grow={1}'
diff --git a/packages/core/src/tools/prompts/codegen.md b/packages/core/src/tools/prompts/codegen.md
index d666878be..9515dde8b 100644
--- a/packages/core/src/tools/prompts/codegen.md
+++ b/packages/core/src/tools/prompts/codegen.md
@@ -203,9 +203,7 @@ assets/
- `primaryAxisAlign: CENTER` → `justify-content: center`
- `counterAxisAlign: CENTER` → `align-items: center`
- `layoutWrap: WRAP` → `flex-wrap: wrap`
-- `primaryAxisSizing: HUG` → no explicit size on primary axis (content-sized)
-- `primaryAxisSizing: FILL` → `flex: 1` or `width: 100%` depending on context
-- `counterAxisSizing: FILL` → `align-self: stretch` or explicit `width/height: 100%`
+- `primaryAxisSizing: HUG` / `counterAxisSizing: HUG` → no explicit size on that axis (content-sized)
**Grid layout**
@@ -216,9 +214,8 @@ assets/
**Sizing**
-- `layoutGrow > 0` → `flex-grow: 1`
-- `layoutAlignSelf: STRETCH` → cross-axis fill
-- Fixed width/height only when sizing mode is `FIXED`
+- Fill lives on the child: `layoutGrow > 0` fills the parent's primary axis (`flex-grow: 1`), `layoutAlignSelf: STRETCH` fills the cross axis (`align-self: stretch`, no fixed size on that axis). In a grid, `layoutGrow` fills the cell's width and `STRETCH` its height.
+- Fixed width/height only on axes that neither hug nor fill
**Corner radius**
diff --git a/packages/core/tests/design-jsx/fill-sizing.test.ts b/packages/core/tests/design-jsx/fill-sizing.test.ts
new file mode 100644
index 000000000..7b4db5833
--- /dev/null
+++ b/packages/core/tests/design-jsx/fill-sizing.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { renderJSX } from '@open-pencil/core/design-jsx'
+import { computeAllLayouts } from '@open-pencil/core/layout'
+import { sceneNodeToJSX } from '@open-pencil/design-jsx'
+import { layoutSizing, SceneGraph } from '@open-pencil/scene-graph'
+
+const makeSceneGraph = () => new SceneGraph()
+
+const PARENTS = {
+ row: 'flex="row" w={300} h={200}',
+ column: 'flex="col" w={300} h={200}',
+ grid: 'grid columns="1fr 1fr" rows="1fr" w={300} h={200}'
+}
+
+async function renderChild(parent: string, size: string) {
+ const graph = makeSceneGraph()
+ const [frame] = await renderJSX(
+ graph,
+ `<Frame name="Parent" ${parent}><Rectangle name="Child" ${size} bg="#000" /></Frame>`
+ )
+ computeAllLayouts(graph)
+ const [childId] = getNodeOrThrow(graph, frame.id).childIds
+ return { graph, frameId: frame.id, child: getNodeOrThrow(graph, childId) }
+}
+
+function sizing(graph: SceneGraph, id: string) {
+ const node = getNodeOrThrow(graph, id)
+ return [layoutSizing(graph, node, 'HORIZONTAL'), layoutSizing(graph, node, 'VERTICAL')]
+}
+
+describe('fill sizing round-trip', () => {
+ for (const [parentName, parent] of Object.entries(PARENTS)) {
+ for (const [size, expected] of [
+ ['w="fill" h={40}', ['FILL', 'FIXED']],
+ ['w={40} h="fill"', ['FIXED', 'FILL']],
+ ['w="fill" h="fill"', ['FILL', 'FILL']]
+ ] as const) {
+ it(`${size} in a ${parentName} fills only that axis and exports it`, async () => {
+ const { graph, frameId, child } = await renderChild(parent, size)
+ expect(sizing(graph, child.id)).toEqual([...expected])
+ expect(child.width).toBe(expected[0] === 'FILL' ? (parentName === 'grid' ? 150 : 300) : 40)
+ expect(child.height).toBe(expected[1] === 'FILL' ? 200 : 40)
+
+ const exported = sceneNodeToJSX(frameId, graph)
+ const again = makeSceneGraph()
+ const [frame] = await renderJSX(again, exported)
+ computeAllLayouts(again)
+ const [copyId] = getNodeOrThrow(again, frame.id).childIds
+ expect(sizing(again, copyId)).toEqual([...expected])
+ const copy = getNodeOrThrow(again, copyId)
+ expect([copy.width, copy.height]).toEqual([child.width, child.height])
+ })
+ }
+ }
+})
diff --git a/packages/core/tests/editor/frame-presets.test.ts b/packages/core/tests/editor/frame-presets.test.ts
index 7f0982b74..aff742ec6 100644
--- a/packages/core/tests/editor/frame-presets.test.ts
+++ b/packages/core/tests/editor/frame-presets.test.ts
@@ -159,23 +159,26 @@ describe('frame presets', () => {
width: 100,
height: 100,
layoutMode: 'HORIZONTAL',
- layoutAlignSelf: 'AUTO'
+ layoutGrow: 1,
+ layoutAlignSelf: 'STRETCH'
}).id
computeLayout(editor.graph, parentId)
- expect(getNodeOrThrow(editor.graph, id).width).toBe(500)
+ expect(getNodeOrThrow(editor.graph, id)).toMatchObject({ width: 500, height: 500 })
editor.resizeFrameToPreset(id, { name: 'Custom', width: 200, height: 300 })
expect(getNodeOrThrow(editor.graph, id)).toMatchObject({
width: 200,
height: 300,
+ layoutGrow: 0,
layoutAlignSelf: 'MIN'
})
editor.undo.undo()
expect(getNodeOrThrow(editor.graph, id)).toMatchObject({
width: 500,
- height: 100,
- layoutAlignSelf: 'AUTO'
+ height: 500,
+ layoutGrow: 1,
+ layoutAlignSelf: 'STRETCH'
})
editor.undo.redo()
diff --git a/packages/core/tests/figma-api/pending-layout.test.ts b/packages/core/tests/figma-api/pending-layout.test.ts
new file mode 100644
index 000000000..a8b070de9
--- /dev/null
+++ b/packages/core/tests/figma-api/pending-layout.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function createAPI(): FigmaAPI {
+ return new FigmaAPI(new SceneGraph())
+}
+
+function hugRow(api: ReturnType<typeof createAPI>) {
+ const row = api.createFrame()
+ row.layoutMode = 'HORIZONTAL'
+ row.primaryAxisSizingMode = 'AUTO'
+ row.counterAxisSizingMode = 'AUTO'
+ row.itemSpacing = 10
+ return row
+}
+
+describe('geometry reads after edits', () => {
+ test('a hugging parent reports its new size as soon as a child is added or resized', () => {
+ const api = createAPI()
+ const row = hugRow(api)
+ const first = api.createRectangle()
+ first.resize(40, 20)
+ row.appendChild(first)
+ expect([row.width, row.height]).toEqual([40, 20])
+
+ const second = api.createRectangle()
+ second.resize(60, 30)
+ row.appendChild(second)
+ expect([row.width, row.height]).toEqual([110, 30])
+ expect(second.x).toBe(50)
+
+ first.resize(80, 20)
+ expect(second.x).toBe(90)
+ expect(second.absoluteBoundingBox.x).toBe(row.absoluteBoundingBox.x + 90)
+ expect(row.width).toBe(150)
+ })
+
+ test('removing a child and changing spacing reflow the rest before the next read', () => {
+ const api = createAPI()
+ const row = hugRow(api)
+ const children = [40, 50, 60].map((width) => {
+ const child = api.createRectangle()
+ child.resize(width, 20)
+ row.appendChild(child)
+ return child
+ })
+ children[0].remove()
+ expect(children[1].x).toBe(0)
+ row.itemSpacing = 0
+ expect(children[2].x).toBe(50)
+ expect(row.width).toBe(110)
+ })
+
+ test('edits stay recorded when another API opens the same graph before a read', () => {
+ const api = createAPI()
+ const row = hugRow(api)
+ const child = api.createRectangle()
+ child.resize(40, 20)
+ row.appendChild(child)
+ expect(row.width).toBe(40)
+
+ // A script resizes the child and fails before its tool lays the edit out.
+ child.resize(90, 20)
+ const next = new FigmaAPI(api.graph)
+ expect(next.getNodeById(row.id)?.width).toBe(90)
+ })
+
+ test('reading again without edits does no layout work', () => {
+ const api = createAPI()
+ const row = hugRow(api)
+ const child = api.createRectangle()
+ row.appendChild(child)
+ expect(row.width).toBe(child.width)
+
+ let updates = 0
+ const unbind = api.graph.onNodeEvents({ updated: () => updates++ })
+ void row.width
+ void child.x
+ void row.absoluteTransform
+ unbind()
+ expect(updates).toBe(0)
+ })
+})
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
index 42dadd5dd..9a160855d 100644
--- a/packages/design-jsx/src/export/props.ts
+++ b/packages/design-jsx/src/export/props.ts
@@ -1,4 +1,9 @@
-import type { SceneGraph, SceneNode, NodeType } from '@open-pencil/scene-graph'
+import {
+ layoutSizing,
+ type SceneGraph,
+ type SceneNode,
+ type NodeType
+} from '@open-pencil/scene-graph'
import { DEFAULT_FONT_FAMILY } from '@open-pencil/scene-graph/constants'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
@@ -50,13 +55,12 @@ function collectFlexSizingProps(node: SceneNode, props: JSXProp[]): void {
const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'
- if (node.primaryAxisSizing === 'FILL') props.push([primaryAxis === 'width' ? 'w' : 'h', 'fill'])
- else if (node.primaryAxisSizing !== 'HUG')
+ if (node.primaryAxisSizing !== 'HUG') {
props.push([primaryAxis === 'width' ? 'w' : 'h', node[primaryAxis]])
-
- if (node.counterAxisSizing === 'FILL') props.push([crossAxis === 'width' ? 'w' : 'h', 'fill'])
- else if (node.counterAxisSizing !== 'HUG')
+ }
+ if (node.counterAxisSizing !== 'HUG') {
props.push([crossAxis === 'width' ? 'w' : 'h', node[crossAxis]])
+ }
}
function collectGridPositionProps(node: SceneNode, props: JSXProp[]): void {
@@ -168,13 +172,23 @@ function collectSizingProps(
}
if (!ctx.parentIsAutoLayout) return
- if (node.layoutGrow > 0) props.push(['grow', node.layoutGrow])
- if (node.layoutAlignSelf === 'STRETCH') {
- const parent = node.parentId ? graph.getNode(node.parentId) : null
- if (parent && (parent.layoutMode === 'HORIZONTAL' || parent.layoutMode === 'VERTICAL')) {
- const crossDim = parent.layoutMode === 'HORIZONTAL' ? 'h' : 'w'
- if (!props.some(([k]) => k === crossDim)) props.push([crossDim, 'fill'])
- }
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ // A flex child's main-axis fill keeps its grow factor; every other fill is `"fill"`.
+ const growAxis = parent?.layoutMode === 'VERTICAL' ? 'VERTICAL' : 'HORIZONTAL'
+ const keepsGrow = parent?.layoutMode !== 'GRID' && node.layoutGrow > 0
+ if (keepsGrow) props.push(['grow', node.layoutGrow])
+ for (const [axis, key] of [
+ ['HORIZONTAL', 'w'],
+ ['VERTICAL', 'h']
+ ] as const) {
+ if (keepsGrow && axis === growAxis) continue
+ if (layoutSizing(graph, node, axis) !== 'FILL') continue
+ // Stretch inherited from the parent's alignment is written on the parent.
+ if (axis !== growAxis && node.layoutAlignSelf !== 'STRETCH') continue
+ // Fill replaces the size the node had before it filled.
+ const index = props.findIndex(([k]) => k === key)
+ if (index === -1) props.push([key, 'fill'])
+ else props[index] = [key, 'fill']
}
}
diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.ts
index a02537b6b..e56745fb7 100644
--- a/packages/design-jsx/src/props-overrides.ts
+++ b/packages/design-jsx/src/props-overrides.ts
@@ -129,9 +129,11 @@ function applyFillSizing(
o: Partial<SceneNode>
): void {
if (dim !== 'fill') return
- const isPrimary = axis === 'width' ? isRow : isCol
- const isCross = axis === 'width' ? isCol : isRow
- if (isGrid || isCross) o.layoutAlignSelf = 'STRETCH'
+ // A grid places its children like a row, so width fills by grow and height by stretch.
+ const rowLike = isRow || isGrid
+ const isPrimary = axis === 'width' ? rowLike : isCol
+ const isCross = axis === 'width' ? isCol : rowLike
+ if (isCross) o.layoutAlignSelf = 'STRETCH'
else if (isPrimary) o.layoutGrow = 1
else {
o.layoutGrow = 1
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index ef17d9002..6519772e3 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -1,6 +1,6 @@
import { fromUint8Array } from 'js-base64'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { layoutSizingInParent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { BLACK } from '@open-pencil/scene-graph/constants'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
@@ -77,9 +77,33 @@ function hugs(node: SceneNode, axis: 'width' | 'height'): boolean {
* A layer's size: fixed on the axes the design fixes, and left to the content where the layer
* hugs it (an auto layout frame set to Hug, or auto-sizing text), so the page grows with it.
*/
-function addSize(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {
- if (node.width > 0 && !hugs(node, 'width')) style.width = css('width', px(node.width))
- if (node.height > 0 && !hugs(node, 'height')) style.height = css('height', px(node.height))
+function addSize(
+ style: DesignStyleDeclaration,
+ node: SceneNode,
+ parent: SceneNode | undefined,
+ css: FieldCSS
+): void {
+ const sized = (axis: 'width' | 'height') =>
+ node[axis] > 0 && !hugs(node, axis) && !stretches(node, parent, axis)
+ if (sized('width')) style.width = css('width', px(node.width))
+ if (sized('height')) style.height = css('height', px(node.height))
+}
+
+/**
+ * Whether a layer fills an axis by stretching, which a fixed CSS size would prevent: across a
+ * flex parent, or either axis of a grid cell. Along a flex parent, fill is `flex-grow`, and the
+ * size stays as its basis.
+ */
+function stretches(
+ node: SceneNode,
+ parent: SceneNode | undefined,
+ axis: 'width' | 'height'
+): boolean {
+ const sizing = layoutSizingInParent(parent, node, axis === 'width' ? 'HORIZONTAL' : 'VERTICAL')
+ if (sizing !== 'FILL' || !parent) return false
+ if (parent.layoutMode === 'GRID') return true
+ const mainAxis = parent.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
+ return axis !== mainAxis
}
/**
@@ -220,7 +244,7 @@ function styleFromSceneNode(
css: FieldCSS
): DesignStyleDeclaration {
const style: DesignStyleDeclaration = {}
- addSize(style, node, css)
+ addSize(style, node, parent, css)
addPositioning(style, node, parent)
addSizeConstraints(style, node, css)
const fill = fillToCSS(node.fills.at(0))
@@ -262,7 +286,7 @@ function styleFromTextNode(
css: FieldCSS
): DesignStyleDeclaration {
const style: DesignStyleDeclaration = {}
- addSize(style, node, css)
+ addSize(style, node, parent, css)
addPositioning(style, node, parent)
addLayoutChild(style, node, parent)
if (resolveNodeTextDirection(node) === 'RTL') style.direction = 'rtl'
diff --git a/packages/dom-css/tests/export/fill-sizing.test.ts b/packages/dom-css/tests/export/fill-sizing.test.ts
new file mode 100644
index 000000000..3cf15a481
--- /dev/null
+++ b/packages/dom-css/tests/export/fill-sizing.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'bun:test'
+
+import { sceneNodeToDesignDocument, type DesignNode } from '@open-pencil/dom-css/export'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+function styleOf(nodes: DesignNode[], name: string): Record<string, string> | undefined {
+ for (const node of nodes) {
+ if (node.type !== 'element') continue
+ if (node.sourceSceneNode?.name === name) return node.inlineStyle
+ const found = styleOf(node.children, name)
+ if (found) return found
+ }
+ return undefined
+}
+
+function exportParent(layout: Partial<SceneNode>, children: Partial<SceneNode>[]) {
+ const graph = new SceneGraph()
+ const parent = graph.createNode('FRAME', graph.getPages()[0].id, {
+ name: 'Parent',
+ width: 300,
+ height: 200,
+ ...layout
+ })
+ for (const child of children) graph.createNode('FRAME', parent.id, child)
+ return sceneNodeToDesignDocument(graph, parent.id).children
+}
+
+describe('fill sizing in DOM/CSS export', () => {
+ it('leaves out the size a flex child stretches across, so align-self can stretch it', () => {
+ const doc = exportParent({ layoutMode: 'HORIZONTAL' }, [
+ { name: 'Tall', width: 40, height: 50, layoutAlignSelf: 'STRETCH' },
+ { name: 'Wide', width: 40, height: 50, layoutGrow: 1 }
+ ])
+
+ expect(styleOf(doc, 'Tall')).toMatchObject({ width: '40px', 'align-self': 'stretch' })
+ expect(styleOf(doc, 'Tall')?.height).toBeUndefined()
+ // Along the row, fill is flex-grow and the size stays as its basis.
+ expect(styleOf(doc, 'Wide')).toMatchObject({ width: '40px', height: '50px', 'flex-grow': '1' })
+ })
+
+ it('leaves out the size of each axis a grid child fills', () => {
+ const doc = exportParent(
+ {
+ layoutMode: 'GRID',
+ gridTemplateColumns: [
+ { sizing: 'FR', value: 1 },
+ { sizing: 'FR', value: 1 }
+ ]
+ },
+ [
+ { name: 'Wide', width: 40, height: 50, layoutGrow: 1 },
+ { name: 'Tall', width: 40, height: 50, layoutAlignSelf: 'STRETCH' }
+ ]
+ )
+
+ expect(styleOf(doc, 'Wide')?.width).toBeUndefined()
+ expect(styleOf(doc, 'Wide')?.height).toBe('50px')
+ expect(styleOf(doc, 'Tall')?.width).toBe('40px')
+ expect(styleOf(doc, 'Tall')?.height).toBeUndefined()
+ })
+})
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 2f3b20418..ec98114f5 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -48,7 +48,7 @@ import type {
StrokeCap,
StrokeJoin,
LayoutMode,
- LayoutSizing,
+ AxisSizingMode,
LayoutAlign,
LayoutAlignSelf,
LayoutCounterAlign,
@@ -151,13 +151,11 @@ function mapStackMode(mode?: string): LayoutMode {
}
}
-export function mapStackSizing(sizing?: string): LayoutSizing {
+export function mapStackSizing(sizing?: string): AxisSizingMode {
switch (sizing) {
case 'RESIZE_TO_FIT':
case 'RESIZE_TO_FIT_WITH_IMPLICIT_SIZE':
return 'HUG'
- case 'FILL':
- return 'FILL'
default:
return 'FIXED'
}
diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.ts
index c869d6989..8647bdd8d 100644
--- a/packages/pen/src/read.ts
+++ b/packages/pen/src/read.ts
@@ -1,5 +1,11 @@
import { SceneGraph } from '@open-pencil/scene-graph'
-import type { LayoutMode, LayoutSizing, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
+import type {
+ AxisSizingMode,
+ LayoutMode,
+ LayoutSizing,
+ SceneNode,
+ VectorNetwork
+} from '@open-pencil/scene-graph'
import { copyEffects, copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
import { populateInstanceChildren } from '@open-pencil/scene-graph/instances'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
@@ -92,12 +98,14 @@ function applyAutoLayout(
? ctx.resolveNumber(pen.gap)
: ((pen.gap ?? 0) as number)
+ // Fill is the child's grow or stretch, set with its parent; the frame itself stays fixed.
+ const own = (sizing: LayoutSizing): AxisSizingMode => (sizing === 'HUG' ? 'HUG' : 'FIXED')
if (layoutMode === 'VERTICAL') {
- overrides.primaryAxisSizing = heightSizing
- overrides.counterAxisSizing = widthSizing
+ overrides.primaryAxisSizing = own(heightSizing)
+ overrides.counterAxisSizing = own(widthSizing)
} else {
- overrides.primaryAxisSizing = widthSizing
- overrides.counterAxisSizing = heightSizing
+ overrides.primaryAxisSizing = own(widthSizing)
+ overrides.counterAxisSizing = own(heightSizing)
}
}
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index f54ced3f4..ae0666b6f 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -13,6 +13,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- A bound numeric field records its unit conversion in `variableBindingScales`; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together in `packages/core/src/layout/variables.ts`, which the editor and the Figma API both call rather than reimplementing.
- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.
- Shared primitives that format packages and collaboration need live here: color conversion and management under `@open-pencil/scene-graph/color`, text/layout direction under `@open-pencil/scene-graph/text-direction`, and fractional sibling order keys under `@open-pencil/scene-graph/order-keys` (`packages/scene-graph/tests/order-keys.test.ts`).
+- A node's per-axis sizing (Figma's `layoutSizingHorizontal`/`Vertical`) is read and written through `packages/scene-graph/src/layout-sizing.ts`. Fill is stored on the child as Figma stores it, `layoutGrow` along the parent's primary axis (a grid's is horizontal) and `layoutAlignSelf: 'STRETCH'` across it; `primaryAxisSizing`/`counterAxisSizing` only fix or hug. Layout, the Figma API, the properties panel, and exporters call it instead of mapping axes themselves (`tests/engine/figma/api/layout/sizing.test.ts`).
- CSS values that become scene-graph types, such as grid track lists, are parsed in `@open-pencil/scene-graph/css` on `postcss-value-parser`; design-jsx and dom-css call it instead of splitting or matching CSS by hand (`packages/scene-graph/tests/css`).
- Every plugin-data key OpenPencil writes is a field of `OPEN_PENCIL_PLUGIN_DATA` in `packages/scene-graph/src/plugin-data/fields.ts`, with the Valibot schema that reads it and its role: `content` travels with library assets and counts towards their hash (`contentPluginData`), `format` repeats a node field for files, `bookkeeping` stays behind. Read and replace entries with `readPluginData` and `withPluginData` instead of matching `pluginId` and `key` by hand. The fields test checks that keys stay unique.
- Vector network types live here; the reverse-engineered `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 7f01ae953..cb31fae72 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -50,6 +50,7 @@ export * from './snap'
export * from './export-format'
export * from './export-scale'
export * from './coordinate'
+export * from './layout-sizing'
export * from './group-bounds'
export * from './constants'
export * from './geometry'
diff --git a/packages/scene-graph/src/layout-sizing.ts b/packages/scene-graph/src/layout-sizing.ts
new file mode 100644
index 000000000..95f5ea12d
--- /dev/null
+++ b/packages/scene-graph/src/layout-sizing.ts
@@ -0,0 +1,168 @@
+import type { SceneGraph } from './index'
+import type { LayoutSizing, SceneNode, TextAutoResize } from './types'
+
+/**
+ * How a node sizes along one screen axis, as Figma's `layoutSizingHorizontal` and
+ * `layoutSizingVertical` report it. Fill is stored on the child, the way Figma stores it:
+ * along the parent's primary axis as `layoutGrow`, across it as `layoutAlignSelf: 'STRETCH'`.
+ * A grid lays its children out like a horizontal stack. Hug is stored on the node itself:
+ * `primaryAxisSizing` and `counterAxisSizing` for an auto-layout frame, `textAutoResize`
+ * for text.
+ */
+export type LayoutSizingAxis = 'HORIZONTAL' | 'VERTICAL'
+
+type AutoLayoutMode = Exclude<SceneNode['layoutMode'], 'NONE'>
+
+function primaryAxis(mode: AutoLayoutMode): LayoutSizingAxis {
+ return mode === 'VERTICAL' ? 'VERTICAL' : 'HORIZONTAL'
+}
+
+/** The auto-layout parent that sizes a node's fill, or `undefined` when nothing does. */
+function fillingParent(parent: SceneNode | undefined, node: SceneNode): SceneNode | undefined {
+ if (!parent || parent.layoutMode === 'NONE' || node.layoutPositioning === 'ABSOLUTE')
+ return undefined
+ return parent
+}
+
+function graphParent(graph: SceneGraph, node: SceneNode): SceneNode | undefined {
+ return node.parentId ? graph.getNode(node.parentId) : undefined
+}
+
+function fills(parent: SceneNode, node: SceneNode, axis: LayoutSizingAxis): boolean {
+ if (parent.layoutMode === 'NONE') return false
+ if (axis === primaryAxis(parent.layoutMode)) return node.layoutGrow > 0
+ if (node.layoutAlignSelf === 'STRETCH') return true
+ return (
+ node.layoutAlignSelf === 'AUTO' &&
+ parent.layoutMode !== 'GRID' &&
+ parent.counterAxisAlign === 'STRETCH'
+ )
+}
+
+function ownSizingField(
+ node: SceneNode,
+ axis: LayoutSizingAxis
+): 'primaryAxisSizing' | 'counterAxisSizing' | undefined {
+ if (node.layoutMode === 'NONE') return undefined
+ return axis === primaryAxis(node.layoutMode) ? 'primaryAxisSizing' : 'counterAxisSizing'
+}
+
+function textHugs(autoResize: TextAutoResize, axis: LayoutSizingAxis): boolean {
+ if (autoResize === 'WIDTH_AND_HEIGHT') return true
+ return axis === 'VERTICAL' && autoResize === 'HEIGHT'
+}
+
+function hugs(node: SceneNode, axis: LayoutSizingAxis): boolean {
+ if (node.type === 'TEXT') return textHugs(node.textAutoResize, axis)
+ const field = ownSizingField(node, axis)
+ return field !== undefined && node[field] === 'HUG'
+}
+
+/** The node's sizing along `axis`: fill from its parent, else its own hug, else fixed. */
+export function layoutSizing(
+ graph: SceneGraph,
+ node: SceneNode,
+ axis: LayoutSizingAxis
+): LayoutSizing {
+ return layoutSizingInParent(graphParent(graph, node), node, axis)
+}
+
+/** `layoutSizing` for code that holds the parent rather than the graph. */
+export function layoutSizingInParent(
+ parentNode: SceneNode | undefined,
+ node: SceneNode,
+ axis: LayoutSizingAxis
+): LayoutSizing {
+ const parent = fillingParent(parentNode, node)
+ if (parent && fills(parent, node, axis)) return 'FILL'
+ // Figma reports text outside auto-layout as fixed, though it still resizes to its content.
+ if (hugs(node, axis) && (parent || node.layoutMode !== 'NONE')) return 'HUG'
+ return 'FIXED'
+}
+
+/** The sizings this node accepts on either axis, in Figma's order. */
+export function layoutSizingOptions(graph: SceneGraph, node: SceneNode): LayoutSizing[] {
+ return (['FIXED', 'HUG', 'FILL'] as const).filter(
+ (value) => layoutSizingError(graph, node, value) === undefined
+ )
+}
+
+/** Figma's reason for refusing `value` on this node, or `undefined` when it applies. */
+export function layoutSizingError(
+ graph: SceneGraph,
+ node: SceneNode,
+ value: LayoutSizing
+): string | undefined {
+ const parent = graphParent(graph, node)
+ const inAutoLayout = parent !== undefined && parent.layoutMode !== 'NONE'
+ if (!inAutoLayout && node.layoutMode === 'NONE') {
+ return 'node must be an auto-layout frame or a child of an auto-layout frame'
+ }
+ if (value === 'FILL') {
+ if (!inAutoLayout) return 'FILL can only be set on children of auto-layout frames'
+ if (node.layoutPositioning === 'ABSOLUTE') {
+ return 'FILL cannot be set on absolute positioned auto-layout children'
+ }
+ }
+ if (value === 'HUG' && node.layoutMode === 'NONE' && node.type !== 'TEXT') {
+ return 'HUG can only be set on auto-layout frames or text children of auto-layout frames'
+ }
+ return undefined
+}
+
+function textAutoResizeFor(hugsWidth: boolean, hugsHeight: boolean): TextAutoResize {
+ if (hugsWidth && hugsHeight) return 'WIDTH_AND_HEIGHT'
+ return hugsHeight ? 'HEIGHT' : 'NONE'
+}
+
+function textSizingUpdates(
+ graph: SceneGraph,
+ node: SceneNode,
+ axis: LayoutSizingAxis,
+ value: LayoutSizing
+): Partial<SceneNode> {
+ const other: LayoutSizingAxis = axis === 'HORIZONTAL' ? 'VERTICAL' : 'HORIZONTAL'
+ const hugsAxis = value === 'HUG'
+ const hugsOther = layoutSizing(graph, node, other) === 'HUG'
+ const autoResize =
+ axis === 'HORIZONTAL'
+ ? textAutoResizeFor(hugsAxis, hugsOther)
+ : textAutoResizeFor(hugsOther, hugsAxis)
+ // Truncated text keeps truncating when it stops hugging.
+ if (autoResize === 'NONE' && node.textAutoResize === 'TRUNCATE') return {}
+ return autoResize === node.textAutoResize ? {} : { textAutoResize: autoResize }
+}
+
+/**
+ * The fields that set the node's sizing along `axis` to `value`, as Figma's setter writes
+ * them. A value Figma refuses yields no updates; `layoutSizingError` says why.
+ */
+export function layoutSizingUpdates(
+ graph: SceneGraph,
+ node: SceneNode,
+ axis: LayoutSizingAxis,
+ value: LayoutSizing
+): Partial<SceneNode> {
+ if (layoutSizingError(graph, node, value) !== undefined) return {}
+ const updates: Partial<SceneNode> = {}
+ const parent = fillingParent(graphParent(graph, node), node)
+ if (parent && parent.layoutMode !== 'NONE') {
+ const fill = value === 'FILL'
+ if (axis === primaryAxis(parent.layoutMode)) {
+ if (fill !== node.layoutGrow > 0) updates.layoutGrow = fill ? 1 : 0
+ } else if (fill && node.layoutAlignSelf !== 'STRETCH') {
+ updates.layoutAlignSelf = 'STRETCH'
+ } else if (!fill && fills(parent, node, axis)) {
+ // A flex parent set to stretch its children stretches this one too unless it opts out.
+ const inheritsStretch = parent.layoutMode !== 'GRID' && parent.counterAxisAlign === 'STRETCH'
+ updates.layoutAlignSelf = inheritsStretch ? 'MIN' : 'AUTO'
+ }
+ }
+ const field = ownSizingField(node, axis)
+ if (field) {
+ const own = value === 'HUG' ? 'HUG' : 'FIXED'
+ if (node[field] !== own) updates[field] = own
+ }
+ if (node.type === 'TEXT') Object.assign(updates, textSizingUpdates(graph, node, axis, value))
+ return updates
+}
diff --git a/packages/scene-graph/src/mutation-impact.ts b/packages/scene-graph/src/mutation-impact.ts
index 0c91fa547..fabb58118 100644
--- a/packages/scene-graph/src/mutation-impact.ts
+++ b/packages/scene-graph/src/mutation-impact.ts
@@ -27,30 +27,36 @@ export interface CollectedSceneMutation<T> {
impact: SceneMutationImpact
}
-/** Collects the actual graph nodes and parent containers touched by an operation. */
-export async function collectSceneMutation<T>(
+/** Records into `impact` the nodes and parent containers the graph's edits touch, until unbound. */
+export function recordSceneMutations(
graph: SceneGraph,
- operation: () => T | Promise<T>
-): Promise<CollectedSceneMutation<T>> {
- const impact = createSceneMutationImpact()
- const unbind = graph.onNodeEvents({
+ impact: SceneMutationImpact,
+ shouldRecord: () => boolean = () => true
+): () => void {
+ return graph.onNodeEvents({
created: (node) => {
+ if (!shouldRecord()) return
impact.createdNodeIds.add(node.id)
impact.changedNodeIds.add(node.id)
if (node.parentId) impact.currentParentIds.add(node.parentId)
},
- updated: (id) => impact.changedNodeIds.add(id),
+ updated: (id) => {
+ if (shouldRecord()) impact.changedNodeIds.add(id)
+ },
deleted: (id, parentId) => {
+ if (!shouldRecord()) return
if (parentId) impact.previousParentIds.add(parentId)
impact.deletedNodeIds.add(id)
impact.changedNodeIds.add(id)
},
reparented: (nodeId, oldParentId, newParentId) => {
+ if (!shouldRecord()) return
impact.changedNodeIds.add(nodeId)
if (oldParentId) impact.previousParentIds.add(oldParentId)
impact.currentParentIds.add(newParentId)
},
reordered: (nodeId, parentId, _index, previousParentId) => {
+ if (!shouldRecord()) return
impact.changedNodeIds.add(nodeId)
if (previousParentId && previousParentId !== parentId) {
impact.previousParentIds.add(previousParentId)
@@ -58,6 +64,15 @@ export async function collectSceneMutation<T>(
impact.currentParentIds.add(parentId)
}
})
+}
+
+/** Collects the actual graph nodes and parent containers touched by an operation. */
+export async function collectSceneMutation<T>(
+ graph: SceneGraph,
+ operation: () => T | Promise<T>
+): Promise<CollectedSceneMutation<T>> {
+ const impact = createSceneMutationImpact()
+ const unbind = recordSceneMutations(graph, impact)
try {
return { result: await operation(), impact }
} finally {
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index beb76f255..e30aa5199 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -278,7 +278,10 @@ export interface ArcData {
}
export type LayoutMode = 'NONE' | 'HORIZONTAL' | 'VERTICAL' | 'GRID'
+/** A node's sizing along one axis; fill is stored on the child, see `layoutSizing`. */
export type LayoutSizing = 'FIXED' | 'HUG' | 'FILL'
+/** Whether an auto-layout frame keeps its size or hugs its children along one of its axes. */
+export type AxisSizingMode = 'FIXED' | 'HUG'
export type GridTrackSizing = 'FIXED' | 'FR' | 'AUTO'
@@ -489,8 +492,8 @@ export interface SceneNode {
layoutWrap: LayoutWrap
primaryAxisAlign: LayoutAlign
counterAxisAlign: LayoutCounterAlign
- primaryAxisSizing: LayoutSizing
- counterAxisSizing: LayoutSizing
+ primaryAxisSizing: AxisSizingMode
+ counterAxisSizing: AxisSizingMode
itemSpacing: number
counterAxisSpacing: number
paddingTop: number
diff --git a/packages/scene-graph/tests/layout-sizing.test.ts b/packages/scene-graph/tests/layout-sizing.test.ts
new file mode 100644
index 000000000..c0641a209
--- /dev/null
+++ b/packages/scene-graph/tests/layout-sizing.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, test } from 'bun:test'
+
+import { layoutSizing, layoutSizingUpdates, SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+function child(parent: Partial<SceneNode>, node: Partial<SceneNode> = {}) {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ width: 300,
+ height: 200,
+ ...parent
+ })
+ return { graph, node: graph.createNode('FRAME', frame.id, { width: 40, height: 30, ...node }) }
+}
+
+describe('layout sizing across a stretching parent', () => {
+ test('fixing the cross axis opts out of stretch the parent applies to every child', () => {
+ const { graph, node } = child({ layoutMode: 'HORIZONTAL', counterAxisAlign: 'STRETCH' })
+ expect(layoutSizing(graph, node, 'VERTICAL')).toBe('FILL')
+
+ const updates = layoutSizingUpdates(graph, node, 'VERTICAL', 'FIXED')
+ expect(updates).toEqual({ layoutAlignSelf: 'MIN' })
+ graph.updateNode(node.id, updates)
+ expect(layoutSizing(graph, node, 'VERTICAL')).toBe('FIXED')
+ })
+
+ test('fixing an explicit stretch clears it', () => {
+ const { graph, node } = child({ layoutMode: 'HORIZONTAL' }, { layoutAlignSelf: 'STRETCH' })
+ expect(layoutSizingUpdates(graph, node, 'VERTICAL', 'FIXED')).toEqual({
+ layoutAlignSelf: 'AUTO'
+ })
+ })
+})
diff --git a/packages/vue/src/controls/layout/helpers.ts b/packages/vue/src/controls/layout/helpers.ts
index 1938e9d7e..998b12a39 100644
--- a/packages/vue/src/controls/layout/helpers.ts
+++ b/packages/vue/src/controls/layout/helpers.ts
@@ -2,13 +2,18 @@ import { computed, ref } from 'vue'
import type { ComputedRef } from 'vue'
import type { Editor } from '@open-pencil/core/editor'
-import type {
- GridTrack,
- LayoutAlign,
- LayoutCounterAlign,
- LayoutSizing,
- NumericNodeProperty,
- SceneNode
+import {
+ layoutSizing,
+ layoutSizingOptions,
+ layoutSizingUpdates,
+ type GridTrack,
+ type LayoutAlign,
+ type LayoutCounterAlign,
+ type LayoutSizing,
+ type LayoutSizingAxis,
+ type NumericNodeProperty,
+ type SceneGraph,
+ type SceneNode
} from '@open-pencil/scene-graph'
import { useNodePreview } from '#vue/controls/node-preview/use'
@@ -173,43 +178,25 @@ export function createPaddingActions(editor: Editor, node: ComputedRef<SceneNode
}
}
+function sizingAxis(axis: LayoutAxis): LayoutSizingAxis {
+ return axis === 'width' ? 'HORIZONTAL' : 'VERTICAL'
+}
+
export function axisSizingPatchForNode(
+ graph: SceneGraph,
node: SceneNode,
axis: LayoutAxis,
- sizing: LayoutSizing,
- isInAutoLayout: boolean
+ sizing: LayoutSizing
): Partial<SceneNode> {
- const patch: Partial<SceneNode> = {}
- const isFlex = node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL'
- if (isFlex) {
- const primary =
- (axis === 'width' && node.layoutMode === 'HORIZONTAL') ||
- (axis === 'height' && node.layoutMode === 'VERTICAL')
- patch[primary ? 'primaryAxisSizing' : 'counterAxisSizing'] = sizing
- } else if (sizing === 'HUG' && node.childIds.length > 0) {
- patch[axis === 'width' ? 'counterAxisSizing' : 'primaryAxisSizing'] = 'HUG'
- if (isInAutoLayout) {
- if (axis === 'width') patch.layoutGrow = 0
- else patch.layoutAlignSelf = 'AUTO'
- }
- } else if (axis === 'width') {
- if (node.counterAxisSizing === 'HUG') patch.counterAxisSizing = 'FIXED'
- if (isInAutoLayout) patch.layoutGrow = sizing === 'FILL' ? 1 : 0
- } else {
- if (node.primaryAxisSizing === 'HUG') patch.primaryAxisSizing = 'FIXED'
- if (isInAutoLayout) patch.layoutAlignSelf = sizing === 'FILL' ? 'STRETCH' : 'AUTO'
- }
- return patch
+ return layoutSizingUpdates(graph, node, sizingAxis(axis), sizing)
}
export function createLayoutActions({
editor,
- node,
- isInAutoLayout
+ node
}: {
editor: Editor
node: ComputedRef<SceneNode | null>
- isInAutoLayout: ComputedRef<boolean>
}) {
const preview = useNodePreview(editor)
@@ -254,7 +241,7 @@ export function createLayoutActions({
if (!n) return
editor.updateNodeWithUndo(
n.id,
- axisSizingPatchForNode(n, axis, sizing, isInAutoLayout.value),
+ axisSizingPatchForNode(editor.graph, n, axis, sizing),
`Set ${axis} sizing`
)
}
@@ -262,12 +249,9 @@ export function createLayoutActions({
function updateAxisSize(axis: LayoutAxis, value: number) {
const n = node.value
if (!n) return
- const sizing =
- axis === 'width'
- ? widthSizingForNode(n, isInAutoLayout.value)
- : heightSizingForNode(n, isInAutoLayout.value)
+ const sizing = axisSizingForNode(editor.graph, n, axis)
const sizingPatch =
- sizing !== 'FIXED' ? axisSizingPatchForNode(n, axis, 'FIXED', isInAutoLayout.value) : {}
+ sizing !== 'FIXED' ? axisSizingPatchForNode(editor.graph, n, axis, 'FIXED') : {}
preview.update([n.id], { ...sizingPatch, [axis]: value }, `Change ${axis}`)
}
@@ -321,40 +305,24 @@ export function createLayoutActions({
}
}
-export function canNodeHugContents(node: SceneNode | null): boolean {
- return !!node && node.childIds.length > 0
-}
-
-export function widthSizingForNode(node: SceneNode | null, isInAutoLayout: boolean): LayoutSizing {
- if (!node) return 'FIXED'
- if (node.layoutMode === 'HORIZONTAL') return node.primaryAxisSizing
- if (node.layoutMode === 'VERTICAL') return node.counterAxisSizing
- if (canNodeHugContents(node) && node.counterAxisSizing === 'HUG') return 'HUG'
- if (isInAutoLayout && node.layoutGrow > 0) return 'FILL'
- return 'FIXED'
-}
-
-export function heightSizingForNode(node: SceneNode | null, isInAutoLayout: boolean): LayoutSizing {
- if (!node) return 'FIXED'
- if (node.layoutMode === 'VERTICAL') return node.primaryAxisSizing
- if (node.layoutMode === 'HORIZONTAL') return node.counterAxisSizing
- if (canNodeHugContents(node) && node.primaryAxisSizing === 'HUG') return 'HUG'
- if (isInAutoLayout && node.layoutAlignSelf === 'STRETCH') return 'FILL'
- return 'FIXED'
+export function axisSizingForNode(
+ graph: SceneGraph,
+ node: SceneNode | null,
+ axis: LayoutAxis
+): LayoutSizing {
+ return node ? layoutSizing(graph, node, sizingAxis(axis)) : 'FIXED'
}
export function sizingOptionsForNode(
+ graph: SceneGraph,
node: SceneNode | null,
- isInAutoLayout: boolean,
labels: Partial<Record<LayoutSizing, string>> = {}
): { value: LayoutSizing; label: string }[] {
- const isFlex = node?.layoutMode === 'HORIZONTAL' || node?.layoutMode === 'VERTICAL'
- const options: { value: LayoutSizing; label: string }[] = [
- { value: 'FIXED', label: labels.FIXED ?? 'Fixed' }
- ]
- if (isFlex || canNodeHugContents(node)) options.push({ value: 'HUG', label: labels.HUG ?? 'Hug' })
- if (isInAutoLayout || isFlex) options.push({ value: 'FILL', label: labels.FILL ?? 'Fill' })
- return options
+ const allowed = node ? layoutSizingOptions(graph, node) : []
+ // A node outside auto-layout still shows its fixed size.
+ const values: LayoutSizing[] = allowed.length > 0 ? allowed : ['FIXED']
+ const fallback: Record<LayoutSizing, string> = { FIXED: 'Fixed', HUG: 'Hug', FILL: 'Fill' }
+ return values.map((value) => ({ value, label: labels[value] ?? fallback[value] }))
}
export function createLayoutSizingState(
@@ -373,16 +341,11 @@ export function createLayoutSizingState(
const isFlex = computed(
() => node.value?.layoutMode === 'HORIZONTAL' || node.value?.layoutMode === 'VERTICAL'
)
- const widthSizing = computed<LayoutSizing>(() =>
- widthSizingForNode(node.value, isInAutoLayout.value)
- )
-
- const heightSizing = computed<LayoutSizing>(() =>
- heightSizingForNode(node.value, isInAutoLayout.value)
- )
+ const widthSizing = computed(() => axisSizingForNode(editor.graph, node.value, 'width'))
+ const heightSizing = computed(() => axisSizingForNode(editor.graph, node.value, 'height'))
function sizingOptions() {
- return sizingOptionsForNode(node.value, isInAutoLayout.value, {
+ return sizingOptionsForNode(editor.graph, node.value, {
FIXED: panels.value.sizingFixed,
HUG: panels.value.sizingHug,
FILL: panels.value.sizingFill
diff --git a/packages/vue/src/controls/layout/use.ts b/packages/vue/src/controls/layout/use.ts
index 787a9892c..eaaa2122b 100644
--- a/packages/vue/src/controls/layout/use.ts
+++ b/packages/vue/src/controls/layout/use.ts
@@ -45,7 +45,7 @@ export function useLayout() {
cancelPaddingPreview
} = createPaddingActions(editor, node)
- const layoutActions = createLayoutActions({ editor, node, isInAutoLayout })
+ const layoutActions = createLayoutActions({ editor, node })
const { updateGridTrack, addTrack, removeTrack } = createGridTrackActions(editor, node)
diff --git a/tests/e2e/editor/auto-layout/basic.spec.ts b/tests/e2e/editor/auto-layout/basic.spec.ts
index 91cd1ad29..890c838a4 100644
--- a/tests/e2e/editor/auto-layout/basic.spec.ts
+++ b/tests/e2e/editor/auto-layout/basic.spec.ts
@@ -224,29 +224,35 @@ test('editing a Hug width switches to Fixed in one reversible interaction', asyn
})
test('editing a Fill height switches to Fixed in one undo step', async () => {
- await selectFrame()
+ const frame = expectDefined(await getNodeById(page, frameId), 'frame')
+ const childId = expectDefined(frame.childIds[0], 'child')
+ await page.evaluate((id: string) => window.openPencil?.getStore?.()?.select([id]), childId)
+ await canvas.waitForRender()
+ // Fill is stored on the child: grow along a column, stretch across a row.
+ const fillsHeight = (node: { layoutGrow: number; layoutAlignSelf: string }) =>
+ frame.layoutMode === 'VERTICAL' ? node.layoutGrow > 0 : node.layoutAlignSelf === 'STRETCH'
const heightField = propertyField(page, 'height')
await heightField.getByRole('combobox', { name: 'Height' }).click()
await page.getByRole('option', { name: 'Fill' }).click()
await canvas.waitForRender()
- const before = expectDefined(await getNodeById(page, frameId), 'before')
- expect(before.primaryAxisSizing).toBe('FILL')
+ const before = expectDefined(await getNodeById(page, childId), 'before')
+ expect(fillsHeight(before)).toBe(true)
await heightField.focus()
await heightField.getByRole('spinbutton').fill(String(Math.round(before.height + 30)))
await heightField.getByRole('spinbutton').press('Enter')
await canvas.waitForRender()
- const changed = expectDefined(await getNodeById(page, frameId), 'changed')
- expect(changed.primaryAxisSizing).toBe('FIXED')
+ const changed = expectDefined(await getNodeById(page, childId), 'changed')
+ expect(fillsHeight(changed)).toBe(false)
expect(changed.height).toBe(Math.round(before.height + 30))
await canvas.pressKey('Meta+z')
await canvas.waitForRender()
- const undone = expectDefined(await getNodeById(page, frameId), 'undone')
- expect(undone.primaryAxisSizing).toBe('FILL')
+ const undone = expectDefined(await getNodeById(page, childId), 'undone')
+ expect(fillsHeight(undone)).toBe(true)
expect(undone.height).toBeCloseTo(before.height)
canvas.assertNoErrors()
})
diff --git a/tests/engine/figma/api/layout/sizing.test.ts b/tests/engine/figma/api/layout/sizing.test.ts
index d82c72db9..79afd0b6a 100644
--- a/tests/engine/figma/api/layout/sizing.test.ts
+++ b/tests/engine/figma/api/layout/sizing.test.ts
@@ -2,43 +2,135 @@ import { describe, expect, test } from 'bun:test'
import { getNodeOrThrow } from '#tests/helpers/assert'
-import { createAPI } from '../helpers'
+import { asTextNode, createAPI } from '../helpers'
+
+// Expected values were observed by running the same scripts in live Figma on 2026-10-06.
+
+function fixedRow(api: ReturnType<typeof createAPI>, mode: 'HORIZONTAL' | 'VERTICAL') {
+ const parent = api.createFrame()
+ parent.layoutMode = mode
+ parent.resize(300, 300)
+ parent.primaryAxisSizingMode = 'FIXED'
+ parent.counterAxisSizingMode = 'FIXED'
+ return parent
+}
+
+function read(node: {
+ layoutSizingHorizontal: string
+ layoutSizingVertical: string
+ layoutGrow: number
+ layoutAlign: string
+}) {
+ return {
+ h: node.layoutSizingHorizontal,
+ v: node.layoutSizingVertical,
+ grow: node.layoutGrow,
+ align: node.layoutAlign
+ }
+}
describe('layout sizing', () => {
- test('child in horizontal parent: h=primary, v=counter', () => {
+ test('fill along the parent axis grows, fill across it stretches', () => {
const api = createAPI()
- const parent = api.createFrame()
- parent.layoutMode = 'HORIZONTAL'
- const child = api.createFrame()
- parent.appendChild(child)
- child.layoutSizingHorizontal = 'FILL'
- child.layoutSizingVertical = 'HUG'
- expect(child.layoutSizingHorizontal).toBe('FILL')
- expect(child.layoutSizingVertical).toBe('HUG')
- })
+ const row = fixedRow(api, 'HORIZONTAL')
+ const wide = api.createFrame()
+ row.appendChild(wide)
+ wide.layoutSizingHorizontal = 'FILL'
+ const tall = api.createFrame()
+ row.appendChild(tall)
+ tall.layoutSizingVertical = 'FILL'
- test('child in vertical parent: h=counter, v=primary', () => {
- const api = createAPI()
- const parent = api.createFrame()
- parent.layoutMode = 'VERTICAL'
- const child = api.createFrame()
- parent.appendChild(child)
- child.layoutSizingHorizontal = 'FILL'
- child.layoutSizingVertical = 'HUG'
- expect(child.layoutSizingHorizontal).toBe('FILL')
- expect(child.layoutSizingVertical).toBe('HUG')
+ expect(read(wide)).toEqual({ h: 'FILL', v: 'FIXED', grow: 1, align: 'INHERIT' })
+ expect(read(tall)).toEqual({ h: 'FIXED', v: 'FILL', grow: 0, align: 'STRETCH' })
})
- test('auto-layout frame that is also a child of auto-layout', () => {
+ test('an auto-layout child fills through its parent and hugs through its own axes', () => {
const api = createAPI()
- const outer = api.createFrame()
- outer.layoutMode = 'HORIZONTAL'
+ const column = fixedRow(api, 'VERTICAL')
const inner = api.createFrame()
- inner.layoutMode = 'VERTICAL'
- outer.appendChild(inner)
+ inner.layoutMode = 'HORIZONTAL'
+ column.appendChild(inner)
inner.layoutSizingHorizontal = 'FILL'
- expect(inner.layoutSizingHorizontal).toBe('FILL')
- expect(inner.layoutMode).toBe('VERTICAL')
+ inner.layoutSizingVertical = 'HUG'
+
+ expect(read(inner)).toEqual({ h: 'FILL', v: 'HUG', grow: 0, align: 'STRETCH' })
+ expect(inner.primaryAxisSizingMode).toBe('FIXED')
+ expect(inner.counterAxisSizingMode).toBe('AUTO')
+
+ inner.layoutSizingVertical = 'FILL'
+ expect(read(inner)).toEqual({ h: 'FILL', v: 'FILL', grow: 1, align: 'STRETCH' })
+ expect(inner.counterAxisSizingMode).toBe('FIXED')
+ expect(inner.width).toBe(300)
+ expect(inner.height).toBe(300)
+ })
+
+ test('text hugs through textAutoResize', () => {
+ const api = createAPI()
+ const row = fixedRow(api, 'HORIZONTAL')
+ const text = asTextNode(api.createText())
+ // Figma's createText() starts at WIDTH_AND_HEIGHT; ours starts at NONE.
+ text.textAutoResize = 'WIDTH_AND_HEIGHT'
+ text.characters = 'Hello'
+ row.appendChild(text)
+ const state = () => ({ ...read(text), auto: text.textAutoResize })
+
+ expect(state()).toEqual({
+ h: 'HUG',
+ v: 'HUG',
+ grow: 0,
+ align: 'INHERIT',
+ auto: 'WIDTH_AND_HEIGHT'
+ })
+ text.layoutSizingHorizontal = 'FIXED'
+ expect(state()).toMatchObject({ h: 'FIXED', v: 'HUG', auto: 'HEIGHT' })
+ text.layoutSizingVertical = 'FIXED'
+ expect(state()).toMatchObject({ h: 'FIXED', v: 'FIXED', auto: 'NONE' })
+ text.layoutSizingVertical = 'HUG'
+ expect(state()).toMatchObject({ h: 'FIXED', v: 'HUG', auto: 'HEIGHT' })
+ text.layoutSizingHorizontal = 'HUG'
+ expect(state()).toMatchObject({ h: 'HUG', v: 'HUG', auto: 'WIDTH_AND_HEIGHT' })
+ text.layoutSizingHorizontal = 'FILL'
+ expect(state()).toEqual({ h: 'FILL', v: 'HUG', grow: 1, align: 'INHERIT', auto: 'HEIGHT' })
+ text.layoutSizingVertical = 'FILL'
+ expect(state()).toEqual({ h: 'FILL', v: 'FILL', grow: 1, align: 'STRETCH', auto: 'NONE' })
+ // Text cannot hug its width while its height fills, so the width becomes fixed.
+ text.layoutSizingHorizontal = 'HUG'
+ expect(state()).toEqual({ h: 'FIXED', v: 'FILL', grow: 0, align: 'STRETCH', auto: 'NONE' })
+ })
+
+ test('refuses sizing that Figma refuses', () => {
+ const api = createAPI()
+ const loose = api.createFrame()
+ expect(() => (loose.layoutSizingHorizontal = 'FILL')).toThrow(
+ 'in set_layoutSizingHorizontal: node must be an auto-layout frame or a child of an auto-layout frame'
+ )
+ expect(read(loose)).toMatchObject({ h: 'FIXED', v: 'FIXED' })
+
+ loose.layoutMode = 'VERTICAL'
+ loose.layoutSizingVertical = 'HUG'
+ expect(read(loose)).toMatchObject({ h: 'FIXED', v: 'HUG' })
+ expect(loose.primaryAxisSizingMode).toBe('AUTO')
+
+ const row = fixedRow(api, 'HORIZONTAL')
+ const plain = api.createFrame()
+ row.appendChild(plain)
+ expect(() => (plain.layoutSizingVertical = 'HUG')).toThrow(
+ 'in set_layoutSizingVertical: HUG can only be set on auto-layout frames or text children of auto-layout frames'
+ )
+ const absolute = api.createFrame()
+ row.appendChild(absolute)
+ absolute.layoutPositioning = 'ABSOLUTE'
+ expect(() => (absolute.layoutSizingHorizontal = 'FILL')).toThrow(
+ 'in set_layoutSizingHorizontal: FILL cannot be set on absolute positioned auto-layout children'
+ )
+ expect(read(absolute)).toMatchObject({ h: 'FIXED', v: 'FIXED' })
+ })
+
+ test('text outside auto-layout reports fixed sizing', () => {
+ const api = createAPI()
+ const text = asTextNode(api.createText())
+ text.characters = 'Hello'
+ expect(read(text)).toMatchObject({ h: 'FIXED', v: 'FIXED' })
})
test('HORIZONTAL child in VERTICAL parent: sizing maps to correct raw axis', () => {
diff --git a/tests/engine/layout/auto-layout/fill/flex-basis.test.ts b/tests/engine/layout/auto-layout/fill/flex-basis.test.ts
index 4427a3872..a109fdeb5 100644
--- a/tests/engine/layout/auto-layout/fill/flex-basis.test.ts
+++ b/tests/engine/layout/auto-layout/fill/flex-basis.test.ts
@@ -45,20 +45,17 @@ describe('FILL flexBasis', () => {
itemSpacing: 0
})
autoFrame(graph, frame.id, {
- primaryAxisSizing: 'FILL' as const,
- counterAxisSizing: 'FIXED',
+ layoutGrow: 1,
width: 50,
height: 100
})
autoFrame(graph, frame.id, {
- primaryAxisSizing: 'FILL' as const,
- counterAxisSizing: 'FIXED',
+ layoutGrow: 1,
width: 50,
height: 100
})
autoFrame(graph, frame.id, {
- primaryAxisSizing: 'FILL' as const,
- counterAxisSizing: 'FIXED',
+ layoutGrow: 1,
width: 50,
height: 100
})
diff --git a/tests/engine/layout/auto-layout/layout/imported-derived.test.ts b/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
index 6a1c34647..b93483e86 100644
--- a/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
+++ b/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
@@ -293,7 +293,8 @@ describe('imported auto-layout bounds', () => {
expect(graph.getNode(label.id)).toMatchObject({ x: 0, width: 302 })
})
- test('does not infer authoritative stretch without generated parent bounds', () => {
+ // Stretch is fill, as in Figma, whether or not the parent's bounds came from the file.
+ test('stretches an auto-layout child without generated parent bounds', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
const column = graph.createNode('FRAME', page.id, {
@@ -314,7 +315,7 @@ describe('imported auto-layout bounds', () => {
computeAllLayouts(graph)
- expect(graph.getNode(label.id)?.width).toBe(44)
+ expect(graph.getNode(label.id)?.width).toBe(624)
})
test('preserves hidden child geometry while excluding it from parent flow', () => {
diff --git a/tests/engine/layout/grid-layout.test.ts b/tests/engine/layout/grid-layout.test.ts
index d1bc78939..e4d4b59df 100644
--- a/tests/engine/layout/grid-layout.test.ts
+++ b/tests/engine/layout/grid-layout.test.ts
@@ -327,8 +327,9 @@ describe('Grid Layout', () => {
})
})
+ // Figma fills a grid cell per axis: grow fills its width, stretch fills its height.
describe('grid stretch sizing', () => {
- test('STRETCH child fills grid cell', () => {
+ test('STRETCH child fills the cell height only', () => {
const graph = new SceneGraph()
const frame = gridFrame(graph, pageId(graph), [fr(), fr()], [fr()], {
width: 300,
@@ -340,11 +341,11 @@ describe('Grid Layout', () => {
computeLayout(graph, frame.id)
const children = graph.getChildren(frame.id)
- expect(children[0].width).toBe(150)
+ expect(children[0].width).toBe(50)
expect(children[0].height).toBe(100)
})
- test('layoutGrow child fills grid cell', () => {
+ test('layoutGrow child fills the cell width only', () => {
const graph = new SceneGraph()
const frame = gridFrame(graph, pageId(graph), [fr(), fr()], [fr()], {
width: 400,
@@ -355,10 +356,41 @@ describe('Grid Layout', () => {
computeLayout(graph, frame.id)
+ const children = graph.getChildren(frame.id)
+ expect(children[0].width).toBe(200)
+ expect(children[0].height).toBe(50)
+ })
+
+ test('grow and stretch together fill the whole cell', () => {
+ const graph = new SceneGraph()
+ const frame = gridFrame(graph, pageId(graph), [fr(), fr()], [fr()], {
+ width: 400,
+ height: 200
+ })
+ rect(graph, frame.id, 50, 50, { layoutGrow: 1, layoutAlignSelf: 'STRETCH' as const })
+ rect(graph, frame.id, 50, 50)
+
+ computeLayout(graph, frame.id)
+
const children = graph.getChildren(frame.id)
expect(children[0].width).toBe(200)
expect(children[0].height).toBe(200)
})
+
+ test('an auto-layout child keeps its size unless it fills', () => {
+ const graph = new SceneGraph()
+ const frame = gridFrame(graph, pageId(graph), [fr(), fr()], [fr()], {
+ width: 300,
+ height: 200
+ })
+ autoFrame(graph, frame.id, { layoutMode: 'VERTICAL', width: 40, height: 30 })
+
+ computeLayout(graph, frame.id)
+
+ const children = graph.getChildren(frame.id)
+ expect(children[0].width).toBe(40)
+ expect(children[0].height).toBe(30)
+ })
})
describe('layoutSizingVertical with cross-axis children', () => {
diff --git a/tests/engine/render/jsx/grid-layout.test.ts b/tests/engine/render/jsx/grid-layout.test.ts
index 45d176326..9ad8e5069 100644
--- a/tests/engine/render/jsx/grid-layout.test.ts
+++ b/tests/engine/render/jsx/grid-layout.test.ts
@@ -218,33 +218,32 @@ describe('grid layout rendering', () => {
expect(updated.height).toBe(150)
})
- it('grid children with flex stretch to cell width', async () => {
+ // A hugging card keeps its content width in a grid cell, as in live Figma; w="fill" fills it.
+ it('grid children with flex hug their content unless they fill the cell', async () => {
const g = makeSceneGraph()
- const tree = Frame(
- { name: 'Grid', w: 200, grid: true, columns: '1fr 1fr', gap: 0 },
- Frame({
- name: 'A',
- flex: 'col',
- gap: 4,
- p: 8,
- children: [Rectangle({ name: 'R1', w: 10, h: 20 })]
- }),
+ const card = (name: string, w?: 'fill') =>
Frame({
- name: 'B',
+ name,
+ ...(w ? { w } : {}),
flex: 'col',
gap: 4,
p: 8,
- children: [Rectangle({ name: 'R2', w: 10, h: 20 })]
+ children: [Rectangle({ name: `${name} content`, w: 10, h: 20 })]
})
+ const tree = Frame(
+ { name: 'Grid', w: 200, grid: true, columns: '1fr 1fr', gap: 0 },
+ card('A'),
+ card('B', 'fill')
)
const result = await renderTree(g, tree)
computeAllLayouts(g)
const children = g.getChildren(result.id)
- expect(children[0].width).toBe(100)
+ expect(children[0].width).toBe(26)
expect(children[1].width).toBe(100)
expect(children[0].x).toBe(0)
expect(children[1].x).toBe(100)
+ expect(children[1].height).toBe(36)
})
it('grid prop takes precedence over padding-triggered auto-layout', async () => {
diff --git a/tests/engine/vue/controls/property-preview.test.ts b/tests/engine/vue/controls/property-preview.test.ts
index c533ee5a8..372338225 100644
--- a/tests/engine/vue/controls/property-preview.test.ts
+++ b/tests/engine/vue/controls/property-preview.test.ts
@@ -48,8 +48,7 @@ describe('property previews', () => {
const original = frame.width
const actions = createLayoutActions({
editor,
- node: computed(() => frame),
- isInAutoLayout: computed(() => false)
+ node: computed(() => frame)
})
actions.updateAxisSize('width', 200)
expect(frame.primaryAxisSizing).toBe('FIXED')
diff --git a/tests/engine/vue/layout/hug-contents.test.ts b/tests/engine/vue/layout/hug-contents.test.ts
index 03091bace..d2b323e40 100644
--- a/tests/engine/vue/layout/hug-contents.test.ts
+++ b/tests/engine/vue/layout/hug-contents.test.ts
@@ -1,88 +1,86 @@
import { describe, expect, test } from 'bun:test'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import {
+ axisSizingForNode,
axisSizingPatchForNode,
- widthSizingForNode,
- heightSizingForNode,
sizingOptionsForNode
} from '#vue/controls/layout/helpers'
-function node(overrides: Partial<SceneNode>): SceneNode {
- return {
- id: 'node',
- type: 'FRAME',
- name: 'Frame',
- parentId: 'page',
- childIds: [],
- x: 0,
- y: 0,
- width: 100,
- height: 100,
- rotation: 0,
- layoutMode: 'NONE',
- primaryAxisSizing: 'FIXED',
- counterAxisSizing: 'FIXED',
- layoutGrow: 0,
- layoutAlignSelf: 'AUTO',
- ...overrides
- } as SceneNode
+function setup(parentMode: SceneNode['layoutMode'], child: Partial<SceneNode> = {}) {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const parent = graph.createNode('FRAME', page.id, {
+ layoutMode: parentMode,
+ width: 300,
+ height: 200
+ })
+ const node = graph.createNode('FRAME', parent.id, { width: 100, height: 100, ...child })
+ return { graph, node }
+}
+
+function options(graph: SceneGraph, node: SceneNode) {
+ return sizingOptionsForNode(graph, node).map((option) => option.value)
}
describe('layout sizing controls', () => {
- test('plain containers with children expose hug contents', () => {
- const frame = node({ childIds: ['child'] })
+ test('a frame outside auto-layout only shows its fixed size', () => {
+ const { graph, node } = setup('NONE', { childIds: ['child'] })
- expect(sizingOptionsForNode(frame, false).map((option) => option.value)).toContain('HUG')
+ expect(options(graph, node)).toEqual(['FIXED'])
})
- test('plain container width and height reflect hug sizing fields', () => {
- const frame = node({
- childIds: ['child'],
- primaryAxisSizing: 'HUG',
- counterAxisSizing: 'HUG'
- })
+ test('an auto-layout child offers fill, and hug once it has its own auto-layout', () => {
+ const plain = setup('HORIZONTAL')
+ expect(options(plain.graph, plain.node)).toEqual(['FIXED', 'FILL'])
+
+ const stack = setup('HORIZONTAL', { layoutMode: 'VERTICAL' })
+ expect(options(stack.graph, stack.node)).toEqual(['FIXED', 'HUG', 'FILL'])
+ })
- expect(widthSizingForNode(frame, false)).toBe('HUG')
- expect(heightSizingForNode(frame, false)).toBe('HUG')
+ test('fill is stored on the child per axis, as grow along the parent and stretch across it', () => {
+ const { graph, node } = setup('HORIZONTAL')
+
+ expect(axisSizingPatchForNode(graph, node, 'width', 'FILL')).toEqual({ layoutGrow: 1 })
+ expect(axisSizingPatchForNode(graph, node, 'height', 'FILL')).toEqual({
+ layoutAlignSelf: 'STRETCH'
+ })
})
- test('leaf frames do not expose hug contents', () => {
- const frame = node({ childIds: [] })
+ test('grid cells fill their width by grow and their height by stretch', () => {
+ const { graph, node } = setup('GRID', { layoutAlignSelf: 'STRETCH' })
- expect(sizingOptionsForNode(frame, false).map((option) => option.value)).not.toContain('HUG')
+ expect(axisSizingForNode(graph, node, 'width')).toBe('FIXED')
+ expect(axisSizingForNode(graph, node, 'height')).toBe('FILL')
+ expect(axisSizingPatchForNode(graph, node, 'width', 'FILL')).toEqual({ layoutGrow: 1 })
})
- test('editing derived flex dimensions can switch only that axis to fixed', () => {
- const frame = node({
+ test('editing a filled and hugged stack switches only that axis to fixed', () => {
+ const { graph, node } = setup('HORIZONTAL', {
layoutMode: 'VERTICAL',
- primaryAxisSizing: 'FILL',
- counterAxisSizing: 'HUG'
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'FIXED',
+ layoutGrow: 1
})
- expect(axisSizingPatchForNode(frame, 'width', 'FIXED', false)).toEqual({
- counterAxisSizing: 'FIXED'
- })
- expect(axisSizingPatchForNode(frame, 'height', 'FIXED', false)).toEqual({
+ expect(axisSizingForNode(graph, node, 'width')).toBe('FILL')
+ expect(axisSizingForNode(graph, node, 'height')).toBe('HUG')
+ expect(axisSizingPatchForNode(graph, node, 'width', 'FIXED')).toEqual({ layoutGrow: 0 })
+ expect(axisSizingPatchForNode(graph, node, 'height', 'FIXED')).toEqual({
primaryAxisSizing: 'FIXED'
})
})
- test('switching an auto-layout child from fill to hug clears fill mechanics', () => {
- const frame = node({
- childIds: ['child'],
- layoutGrow: 1,
+ test('switching a stack from fill to hug clears the fill', () => {
+ const { graph, node } = setup('VERTICAL', {
+ layoutMode: 'HORIZONTAL',
layoutAlignSelf: 'STRETCH'
})
- expect(axisSizingPatchForNode(frame, 'width', 'HUG', true)).toEqual({
- counterAxisSizing: 'HUG',
- layoutGrow: 0
- })
- expect(axisSizingPatchForNode(frame, 'height', 'HUG', true)).toEqual({
- primaryAxisSizing: 'HUG',
- layoutAlignSelf: 'AUTO'
+ expect(axisSizingPatchForNode(graph, node, 'width', 'HUG')).toEqual({
+ layoutAlignSelf: 'AUTO',
+ primaryAxisSizing: 'HUG'
})
})
})