Skip to content

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

fix: read auto layout keywords the same way in every format (#1016)

Danila Poyarkovae3ae1beb9f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95b0d4757..ed48c3243 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@
- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.
- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGVectorizeResult` adds `texts`, the SVG's text placed in the target space, and `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.
+- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.
+- `@open-pencil/scene-graph/layout-guides` is now `@open-pencil/scene-graph/layout`, which also exports the per-axis sizing helpers and the auto layout keyword parsers; `layoutGuideLines` and `layoutGuideSections` are unchanged.
- `SceneNode` from `@open-pencil/scene-graph` has `isExposedInstance`, whether an instance inside a component shows its properties on instances of that component, so code that builds `SceneNode` objects itself must include it. In the plugin API, `isExposedInstance` and `exposedInstances` follow that flag and Figma's rules instead of treating an instance whose swap is bound to a property as exposed: only an instance in a component's own layers whose component has properties can be exposed, and its copies in instances report it but cannot change it.
- `usePosition` from `@open-pencil/vue` reports and edits `x`, `y`, and `rotation` as Figma's properties panel does: the turned layer's box on the canvas, measured from its frame or page, and its counterclockwise angle. `getDefaultCanvasBgColor` and `CANVAS_BG_COLOR_DARK` are removed from `@open-pencil/core/constants`; new pages use `PAGE_DEFAULT_BACKGROUNDS`, keyed by interface theme.
- `SkiaRenderer.hitTestFrameTitle` no longer takes the selected IDs: it finds the name of any frame on the page or in a section under a point, selected or not.
@@ -155,6 +157,7 @@
- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.
- Reject an argument an AI, MCP, CLI, or WebMCP tool does not take, such as `properties: { y: 500 }` for `update_node` or `font: { family }` for `set_font`, and name it, instead of reporting success without changing anything (#977).
- Choose an instance's variant by its variant property in design JSX, such as `<Instance component="Button" State="Pressed" />`, without a warning that the property is unsupported.
+- Lay out design JSX `justifyContent="space-between"`, `"flex-start"`, and `"flex-end"`, and `alignItems="flex-end"` and `"flex-start"`, as written instead of at the start; `space-around` and `space-evenly`, which auto layout has no equivalent for, still start at the start, and align a row's children by their baseline with `items="baseline"`, which JSX export now writes instead of dropping. A `.pen` padding with one or three values fills the sides it leaves out as CSS does, instead of with 0.
- Keep memory flat while the AI chat or an MCP client edits a document (#587). Each edit kept two copies of its whole page in the undo history, about 10 MB a call on a 400-layer page, until the 200-step history limit, so long sessions grew until the app ran out of memory; an edit now keeps only the layers it changed, and undoing it leaves the other layers as they are.
- Keep the new-tab button and the active tab in view when many documents are open. Tabs shrink before the tab bar scrolls, the clipped side fades with a chevron that scrolls to hidden tabs, and the new-tab button is a compact button beside the last tab instead of scrolling away with the tabs.
- Show when the browser menubar has more menus than fit in the left panel. The clipped side fades out and a chevron scrolls to the hidden menus; before, Arrange and Text could be cut off with no sign the bar scrolls.
diff --git a/packages/core/src/canvas/layout-grids.ts b/packages/core/src/canvas/layout-grids.ts
index 1d8d7f6da..c90253c69 100644
--- a/packages/core/src/canvas/layout-grids.ts
+++ b/packages/core/src/canvas/layout-grids.ts
@@ -2,7 +2,7 @@ import type { Canvas } from 'canvaskit-wasm'
import { readEffectiveFigmaRawField } from '@open-pencil/fig'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { layoutGuideSections } from '@open-pencil/scene-graph/layout-guides'
+import { layoutGuideSections } from '@open-pencil/scene-graph/layout'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { SELECTION_COLOR } from '#core/constants'
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
index 9a160855d..9bc36b99e 100644
--- a/packages/design-jsx/src/export/props.ts
+++ b/packages/design-jsx/src/export/props.ts
@@ -87,6 +87,7 @@ function collectFlexAlignmentProps(node: SceneNode, props: JSXProp[]): void {
if (node.counterAxisAlign === 'CENTER') props.push(['items', 'center'])
else if (node.counterAxisAlign === 'MAX') props.push(['items', 'end'])
else if (node.counterAxisAlign === 'STRETCH') props.push(['items', 'stretch'])
+ else if (node.counterAxisAlign === 'BASELINE') props.push(['items', 'baseline'])
}
function collectAutoLayoutPaddingProps(node: SceneNode, props: JSXProp[]): void {
diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.ts
index e56745fb7..7a6e9ac3a 100644
--- a/packages/design-jsx/src/props-overrides.ts
+++ b/packages/design-jsx/src/props-overrides.ts
@@ -1,4 +1,12 @@
-import type { Fill, LayoutMode, SceneNode } from '@open-pencil/scene-graph'
+import {
+ autoLayoutSizingFields,
+ fillSizingFields,
+ parseAutoLayoutDirection,
+ parseCounterAxisAlign,
+ parsePrimaryAxisAlign,
+ type Fill,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { colorToFill } from '@open-pencil/scene-graph/color'
import { parseCSSGridTracks, parseCSSNumber } from '@open-pencil/scene-graph/css'
import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'
@@ -14,20 +22,6 @@ const WEIGHT_MAP: Record<string, number> = {
bold: 700
}
-const ALIGN_MAP: Record<string, SceneNode['primaryAxisAlign']> = {
- start: 'MIN',
- end: 'MAX',
- center: 'CENTER',
- between: 'SPACE_BETWEEN'
-}
-
-const COUNTER_ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER' | 'STRETCH'> = {
- start: 'MIN',
- end: 'MAX',
- center: 'CENTER',
- stretch: 'STRETCH'
-}
-
const TEXT_ALIGN_MAP: Record<string, SceneNode['textAlignHorizontal']> = {
left: 'LEFT',
center: 'CENTER',
@@ -95,12 +89,8 @@ export function applySizeOverrides(
if (typeof w === 'number') o.width = w
if (typeof h === 'number') o.height = h
- const isParentRow = parentLayout === 'HORIZONTAL'
- const isParentCol = parentLayout === 'VERTICAL'
- const isParentGrid = parentLayout === 'GRID'
-
- applyFillSizing(w, 'width', isParentGrid, isParentRow, isParentCol, o)
- applyFillSizing(h, 'height', isParentGrid, isParentRow, isParentCol, o)
+ if (w === 'fill') Object.assign(o, fillSizingFields(parentLayout, 'HORIZONTAL'))
+ if (h === 'fill') Object.assign(o, fillSizingFields(parentLayout, 'VERTICAL'))
if (props.x !== undefined) o.x = props.x as number
if (props.y !== undefined) o.y = props.y as number
@@ -120,27 +110,6 @@ export function applySizeOverrides(
return { w, h }
}
-function applyFillSizing(
- dim: unknown,
- axis: 'width' | 'height',
- isGrid: boolean,
- isRow: boolean,
- isCol: boolean,
- o: Partial<SceneNode>
-): void {
- if (dim !== 'fill') return
- // 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
- o.layoutAlignSelf = 'STRETCH'
- }
-}
-
function isFill(value: unknown): value is Fill {
return (
value !== null &&
@@ -320,20 +289,10 @@ function applyAutoLayoutSizing(
w: unknown,
h: unknown
): void {
- const dir = (props.flex as string | undefined) ?? 'col'
- const isVertical = dir === 'col' || dir === 'column'
- o.layoutMode = (isVertical ? 'VERTICAL' : 'HORIZONTAL') as LayoutMode
-
- o.primaryAxisSizing = 'HUG'
- o.counterAxisSizing = 'HUG'
-
- const primaryDim = isVertical ? h : w
- const counterDim = isVertical ? w : h
-
- if (typeof primaryDim === 'number') o.primaryAxisSizing = 'FIXED'
- if (typeof counterDim === 'number') o.counterAxisSizing = 'FIXED'
- if (primaryDim === 'hug') o.primaryAxisSizing = 'HUG'
- if (counterDim === 'hug') o.counterAxisSizing = 'HUG'
+ const flex = typeof props.flex === 'string' ? props.flex : 'col'
+ o.layoutMode = parseAutoLayoutDirection(flex) ?? 'HORIZONTAL'
+ const own = (dim: unknown) => (typeof dim === 'number' ? 'FIXED' : 'HUG')
+ Object.assign(o, autoLayoutSizingFields(o.layoutMode, own(w), own(h)))
}
function applyLayoutAlignmentOverrides(
@@ -341,12 +300,12 @@ function applyLayoutAlignmentOverrides(
o: Partial<SceneNode>
): void {
const justify = designJSXProp(props, 'justify')
- if (justify) {
- o.primaryAxisAlign = ALIGN_MAP[justify as string] ?? 'MIN'
+ if (typeof justify === 'string' && justify) {
+ o.primaryAxisAlign = parsePrimaryAxisAlign(justify) ?? 'MIN'
}
const items = designJSXProp(props, 'items')
- if (items) {
- o.counterAxisAlign = COUNTER_ALIGN_MAP[items as string] ?? 'MIN'
+ if (typeof items === 'string' && items) {
+ o.counterAxisAlign = parseCounterAxisAlign(items) ?? 'MIN'
}
}
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 57ca0a91d..0795bff39 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -7,7 +7,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `flex="row"` / `flex="col"` enables auto-layout. Use it for content; reserve explicit `x`/`y` or `position="absolute"` for intentional overlays and artwork. Without layout, children share the origin unless positioned.
- `w` / `h` accept pixels, `"hug"` (content-sized), or `"fill"` (available space in a supported layout parent). Use Hug for notes, cards, and long pages instead of guessing heights. Fixed viewport sizes and artwork geometry are intentional exceptions.
- `gap` controls spacing. `p`, `px`, `py`, and `pt`/`pr`/`pb`/`pl` control padding; longhands override shorthands. There is no margin shorthand.
-- `justify="start"|"end"|"center"|"between"` controls the primary axis; `items="start"|"end"|"center"|"stretch"` controls the cross axis. Distribution needs available space: `between` cannot create extra room in a Hug container.
+- `justify="start"|"end"|"center"|"between"` controls the primary axis; `items="start"|"end"|"center"|"stretch"|"baseline"` controls the cross axis. Distribution needs available space: `between` cannot create extra room in a Hug container.
- `grow` distributes available space. Avoid circular Hug/Fill dependencies and redundant fixed widths on growing children. Keep Fill sizing through intermediate containers that should stretch.
- For wrapping text in a column, prefer `w="fill"`; fixed-width text can use `textAutoResize="height"`. `maxLines` / `truncate` are intentional truncation, not fixes for accidental overflow.
- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.
diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.ts
index 18da4babb..bec0c8da3 100644
--- a/packages/design-jsx/src/tree.ts
+++ b/packages/design-jsx/src/tree.ts
@@ -109,9 +109,9 @@ export type StyleProps = {
columnGap?: number | DesignVariable
justify?: 'start' | 'end' | 'center' | 'between'
justifyContent?: 'start' | 'end' | 'center' | 'between'
- items?: 'start' | 'end' | 'center' | 'stretch'
- align?: 'start' | 'end' | 'center' | 'stretch'
- alignItems?: 'start' | 'end' | 'center' | 'stretch'
+ items?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'
+ align?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'
+ alignItems?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'
grow?: number
w?: number | 'fill' | 'hug' | DesignVariable
diff --git a/packages/design-jsx/tests/export.test.ts b/packages/design-jsx/tests/export.test.ts
index 631048a12..446050294 100644
--- a/packages/design-jsx/tests/export.test.ts
+++ b/packages/design-jsx/tests/export.test.ts
@@ -15,6 +15,16 @@ function pageId(graph: SceneGraph) {
}
describe('sceneNodeToJSX', () => {
+ test('a row aligned by baseline exports items="baseline"', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('FRAME', pageId(graph), {
+ name: 'Row',
+ layoutMode: 'HORIZONTAL',
+ counterAxisAlign: 'BASELINE'
+ })
+ expect(sceneNodeToJSX(node.id, graph)).toContain('items="baseline"')
+ })
+
test('basic rectangle', () => {
const graph = makeGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), {
diff --git a/packages/design-jsx/tests/props-overrides.test.ts b/packages/design-jsx/tests/props-overrides.test.ts
index c83e31597..fcb90f422 100644
--- a/packages/design-jsx/tests/props-overrides.test.ts
+++ b/packages/design-jsx/tests/props-overrides.test.ts
@@ -20,3 +20,25 @@ describe('property names', () => {
expect(overrides).toMatchObject({ width: 100, height: 50, cornerRadius: 8 })
})
})
+
+describe('stack alignment', () => {
+ test('CSS justify and align keywords mean what the short names do', () => {
+ expect(
+ propsToOverrides({ flex: 'row', justifyContent: 'space-between' }, false, 'NONE')
+ ).toMatchObject({
+ primaryAxisAlign: 'SPACE_BETWEEN'
+ })
+ expect(propsToOverrides({ flex: 'row', justify: 'between' }, false, 'NONE')).toMatchObject({
+ primaryAxisAlign: 'SPACE_BETWEEN'
+ })
+ expect(propsToOverrides({ flex: 'row', alignItems: 'flex-end' }, false, 'NONE')).toMatchObject({
+ counterAxisAlign: 'MAX'
+ })
+ })
+
+ test('items can align children by their baseline', () => {
+ expect(propsToOverrides({ flex: 'row', items: 'baseline' }, false, 'NONE')).toMatchObject({
+ counterAxisAlign: 'BASELINE'
+ })
+ })
+})
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index f5b6a4f6a..851b26cd2 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -9,7 +9,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `flex="row"` / `flex="col"` enables auto-layout. Use it for content; reserve explicit `x`/`y` or `position="absolute"` for intentional overlays and artwork. Without layout, children share the origin unless positioned.
- `w` / `h` accept pixels, `"hug"` (content-sized), or `"fill"` (available space in a supported layout parent). Use Hug for notes, cards, and long pages instead of guessing heights. Fixed viewport sizes and artwork geometry are intentional exceptions.
- `gap` controls spacing. `p`, `px`, `py`, and `pt`/`pr`/`pb`/`pl` control padding; longhands override shorthands. There is no margin shorthand.
-- `justify="start"|"end"|"center"|"between"` controls the primary axis; `items="start"|"end"|"center"|"stretch"` controls the cross axis. Distribution needs available space: `between` cannot create extra room in a Hug container.
+- `justify="start"|"end"|"center"|"between"` controls the primary axis; `items="start"|"end"|"center"|"stretch"|"baseline"` controls the cross axis. Distribution needs available space: `between` cannot create extra room in a Hug container.
- `grow` distributes available space. Avoid circular Hug/Fill dependencies and redundant fixed widths on growing children. Keep Fill sizing through intermediate containers that should stretch.
- For wrapping text in a column, prefer `w="fill"`; fixed-width text can use `textAutoResize="height"`. `maxLines` / `truncate` are intentional truncation, not fixes for accidental overflow.
- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.
diff --git a/packages/dom-css/src/import/scene-graph.ts b/packages/dom-css/src/import/scene-graph.ts
index 867ba0a73..cea7c57ef 100644
--- a/packages/dom-css/src/import/scene-graph.ts
+++ b/packages/dom-css/src/import/scene-graph.ts
@@ -8,7 +8,14 @@ import {
type Stroke
} from '@open-pencil/scene-graph'
import { TRANSPARENT } from '@open-pencil/scene-graph/constants'
-import { parseCSSNumber, parseCSSShadows } from '@open-pencil/scene-graph/css'
+import {
+ parseCSSAlignItems,
+ parseCSSAlignSelf,
+ parseCSSFlexDirection,
+ parseCSSJustifyContent,
+ parseCSSNumber,
+ parseCSSShadows
+} from '@open-pencil/scene-graph/css'
import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
@@ -163,30 +170,6 @@ function applyCornerRadii(node: SceneNode, style: DesignStyleDeclaration): void
].some((radius) => radius !== fallback)
}
-function primaryAxisAlignFromCSS(value: string | undefined): SceneNode['primaryAxisAlign'] {
- if (value === 'center') return 'CENTER'
- if (value === 'end' || value === 'flex-end') return 'MAX'
- if (value === 'space-between') return 'SPACE_BETWEEN'
- return 'MIN'
-}
-
-function counterAxisAlignFromCSS(value: string | undefined): SceneNode['counterAxisAlign'] {
- if (value === 'center') return 'CENTER'
- if (value === 'end' || value === 'flex-end') return 'MAX'
- if (value === 'stretch') return 'STRETCH'
- if (value === 'baseline') return 'BASELINE'
- return 'MIN'
-}
-
-function layoutAlignSelfFromCSS(value: string | undefined): SceneNode['layoutAlignSelf'] {
- if (value === 'center') return 'CENTER'
- if (value === 'end' || value === 'flex-end') return 'MAX'
- if (value === 'stretch') return 'STRETCH'
- if (value === 'baseline') return 'BASELINE'
- if (value === 'start' || value === 'flex-start') return 'MIN'
- return 'AUTO'
-}
-
function textCaseFromCSS(value: string | undefined): SceneNode['textCase'] {
if (value === 'uppercase') return 'UPPER'
if (value === 'lowercase') return 'LOWER'
@@ -312,14 +295,14 @@ function applyElementStyle(
const overflow = pickStyle(style, 'overflow')
if (overflow === 'hidden' || overflow === 'clip') node.clipsContent = true
- const alignSelf = layoutAlignSelfFromCSS(pickStyle(style, 'align-self'))
+ const alignSelf = parseCSSAlignSelf(pickStyle(style, 'align-self')) ?? 'AUTO'
if (alignSelf !== 'AUTO') node.layoutAlignSelf = alignSelf
const display = pickStyle(style, 'display')
if (display === 'flex' || display === 'inline-flex') {
- node.layoutMode = pickStyle(style, 'flex-direction') === 'column' ? 'VERTICAL' : 'HORIZONTAL'
- node.primaryAxisAlign = primaryAxisAlignFromCSS(pickStyle(style, 'justify-content'))
- node.counterAxisAlign = counterAxisAlignFromCSS(pickStyle(style, 'align-items'))
+ node.layoutMode = parseCSSFlexDirection(pickStyle(style, 'flex-direction')) ?? 'HORIZONTAL'
+ node.primaryAxisAlign = parseCSSJustifyContent(pickStyle(style, 'justify-content')) ?? 'MIN'
+ node.counterAxisAlign = parseCSSAlignItems(pickStyle(style, 'align-items')) ?? 'MIN'
node.layoutWrap = pickStyle(style, 'flex-wrap') === 'wrap' ? 'WRAP' : 'NO_WRAP'
applyFlexGap(node, style)
}
diff --git a/packages/pen/src/convert.ts b/packages/pen/src/convert.ts
index 8d47b0334..5a498ea64 100644
--- a/packages/pen/src/convert.ts
+++ b/packages/pen/src/convert.ts
@@ -1,4 +1,10 @@
-import { generateId } from '@open-pencil/scene-graph'
+import {
+ generateId,
+ paddingFromShorthand,
+ parseAutoLayoutDirection,
+ parseCounterAxisAlign,
+ parsePrimaryAxisAlign
+} from '@open-pencil/scene-graph'
import type {
Color,
Effect,
@@ -390,27 +396,10 @@ export function applyPadding(node: SceneNode, padding: PenNode['padding'], ctx?:
if (padding === undefined) return
const resolve = (v: number | string): number =>
typeof v === 'string' ? (isVarRef(v) && ctx ? ctx.resolveNumber(v) : Number(v) || 0) : v
- if (Array.isArray(padding)) {
- if (padding.length === 2) {
- const vertical = resolve(padding[0])
- const horizontal = resolve(padding[1])
- node.paddingTop = vertical
- node.paddingRight = horizontal
- node.paddingBottom = vertical
- node.paddingLeft = horizontal
- return
- }
- node.paddingTop = resolve(padding[0] ?? 0)
- node.paddingRight = resolve(padding[1] ?? 0)
- node.paddingBottom = resolve(padding[2] ?? 0)
- node.paddingLeft = resolve(padding[3] ?? 0)
- return
- }
- const resolved = resolve(padding)
- node.paddingTop = resolved
- node.paddingRight = resolved
- node.paddingBottom = resolved
- node.paddingLeft = resolved
+ Object.assign(
+ node,
+ paddingFromShorthand(Array.isArray(padding) ? padding.map(resolve) : [resolve(padding)])
+ )
}
interface ParsedSize {
@@ -467,24 +456,17 @@ export function parseSize(
}
export function mapLayoutMode(pen: PenNode): LayoutMode {
- if (pen.layout === 'row' || pen.layout === 'horizontal') return 'HORIZONTAL'
- if (pen.layout === 'column' || pen.layout === 'vertical') return 'VERTICAL'
- if (pen.type === 'frame' && pen.layout === undefined) return 'HORIZONTAL'
- return 'NONE'
+ const direction = parseAutoLayoutDirection(pen.layout)
+ if (direction) return direction
+ return pen.type === 'frame' && pen.layout === undefined ? 'HORIZONTAL' : 'NONE'
}
export function mapJustifyContent(value: string | undefined): LayoutAlign {
- if (value === 'center') return 'CENTER'
- if (value === 'end') return 'MAX'
- if (value === 'space-between') return 'SPACE_BETWEEN'
- return 'MIN'
+ return parsePrimaryAxisAlign(value) ?? 'MIN'
}
export function mapAlignItems(value: string | undefined): LayoutCounterAlign {
- if (value === 'center') return 'CENTER'
- if (value === 'end') return 'MAX'
- if (value === 'stretch') return 'STRETCH'
- return 'MIN'
+ return parseCounterAxisAlign(value) ?? 'MIN'
}
export function mapTextAlign(value: string | undefined): SceneNode['textAlignHorizontal'] {
diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.ts
index 8647bdd8d..e936caf6d 100644
--- a/packages/pen/src/read.ts
+++ b/packages/pen/src/read.ts
@@ -1,4 +1,4 @@
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { fillSizingFields, SceneGraph } from '@open-pencil/scene-graph'
import type {
AxisSizingMode,
LayoutMode,
@@ -281,15 +281,8 @@ function createSceneNode(
}
if (parentLayout !== 'NONE') {
- const parentVertical = parentLayout === 'VERTICAL'
- if (w.sizing === 'FILL') {
- if (parentVertical) node.layoutAlignSelf = 'STRETCH'
- else node.layoutGrow = 1
- }
- if (h.sizing === 'FILL') {
- if (parentVertical) node.layoutGrow = 1
- else node.layoutAlignSelf = 'STRETCH'
- }
+ if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(parentLayout, 'HORIZONTAL'))
+ if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(parentLayout, 'VERTICAL'))
}
if (pen.reusable) {
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index ae0666b6f..57f338ead 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -13,7 +13,8 @@ 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`).
+- 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`).
+- Formats read auto layout keywords (stack direction, `justify-content`, `align-items`, `align-self`, padding shorthand) through `packages/scene-graph/src/layout/keywords.ts`, and an importer builds fill and hug for a node not yet in the graph with `fillSizingFields` and `autoLayoutSizingFields`. Design JSX and `.pen` pass their own spellings straight to it, and DOM/CSS parses CSS values first with `parseCSSJustifyContent` and its siblings in `@open-pencil/scene-graph/css` (`packages/scene-graph/tests/layout/keywords.test.ts`, `packages/scene-graph/tests/css/layout.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/package.json b/packages/scene-graph/package.json
index 214f115e3..a4f328fee 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -89,11 +89,11 @@
"import": "./dist/guides.js",
"default": "./dist/guides.js"
},
- "./layout-guides": {
- "types": "./dist/layout-guides.d.ts",
- "bun": "./src/layout-guides.ts",
- "import": "./dist/layout-guides.js",
- "default": "./dist/layout-guides.js"
+ "./layout": {
+ "types": "./dist/layout.d.ts",
+ "bun": "./src/layout/index.ts",
+ "import": "./dist/layout.js",
+ "default": "./dist/layout.js"
},
"./types": {
"types": "./dist/types.d.ts",
diff --git a/packages/scene-graph/src/css/index.ts b/packages/scene-graph/src/css/index.ts
index b836936fd..0ae3597cd 100644
--- a/packages/scene-graph/src/css/index.ts
+++ b/packages/scene-graph/src/css/index.ts
@@ -1,3 +1,9 @@
export { parseCSSGridTracks } from './grid'
+export {
+ parseCSSAlignItems,
+ parseCSSAlignSelf,
+ parseCSSFlexDirection,
+ parseCSSJustifyContent
+} from './layout'
export { parseCSSShadows } from './shadows'
export { parseCSSColor, parseCSSNumber, splitCSSValue } from './values'
diff --git a/packages/scene-graph/src/css/layout.ts b/packages/scene-graph/src/css/layout.ts
new file mode 100644
index 000000000..e5d5a5c39
--- /dev/null
+++ b/packages/scene-graph/src/css/layout.ts
@@ -0,0 +1,53 @@
+import valueParser from 'postcss-value-parser'
+
+import {
+ parseAutoLayoutDirection,
+ parseCounterAxisAlign,
+ parseLayoutAlignSelf,
+ parsePrimaryAxisAlign,
+ type AutoLayoutDirection
+} from '../layout/keywords'
+import type { LayoutAlign, LayoutAlignSelf, LayoutCounterAlign } from '../types'
+
+/**
+ * The one alignment keyword a CSS box alignment value names, or `undefined` when it names
+ * something auto layout cannot express. An overflow position (`safe center`) is dropped, and
+ * `first baseline` is the baseline auto layout aligns to.
+ */
+function alignmentKeyword(value: string | undefined): string | undefined {
+ if (!value) return undefined
+ const nodes = valueParser(value).nodes.filter((node) => node.type !== 'space')
+ if (nodes.some((node) => node.type !== 'word')) return undefined
+ const words = nodes.map((node) => node.value.toLowerCase())
+ if (words[0] === 'safe' || words[0] === 'unsafe') words.shift()
+ if (words[0] === 'first' && words[1] === 'baseline') words.shift()
+ return words.length === 1 ? words[0] : undefined
+}
+
+/** A stack direction from `flex-direction`; the reversed directions have no auto layout. */
+export function parseCSSFlexDirection(value: string | undefined): AutoLayoutDirection | undefined {
+ const keyword = alignmentKeyword(value)
+ return keyword === 'row' || keyword === 'column' ? parseAutoLayoutDirection(keyword) : undefined
+}
+
+/**
+ * Primary axis alignment from `justify-content`; `normal` packs flex items at the start. Design
+ * JSX's `between` is not CSS, which browsers ignore, so it is not read here.
+ */
+export function parseCSSJustifyContent(value: string | undefined): LayoutAlign | undefined {
+ const keyword = alignmentKeyword(value)
+ if (keyword === 'between') return undefined
+ return keyword === 'normal' ? 'MIN' : parsePrimaryAxisAlign(keyword)
+}
+
+/** Cross axis alignment from `align-items`; `normal` stretches flex items. */
+export function parseCSSAlignItems(value: string | undefined): LayoutCounterAlign | undefined {
+ const keyword = alignmentKeyword(value)
+ return keyword === 'normal' ? 'STRETCH' : parseCounterAxisAlign(keyword)
+}
+
+/** One flex item's cross axis alignment from `align-self`; `normal` stretches it. */
+export function parseCSSAlignSelf(value: string | undefined): LayoutAlignSelf | undefined {
+ const keyword = alignmentKeyword(value)
+ return keyword === 'normal' ? 'STRETCH' : parseLayoutAlignSelf(keyword)
+}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 0a9883a9d..ae2161879 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -61,12 +61,11 @@ export * from './snap'
export * from './export-format'
export * from './export-scale'
export * from './coordinate'
-export * from './layout-sizing'
+export * from './layout'
export * from './group-bounds'
export * from './constants'
export * from './geometry'
export * from './guides'
-export * from './layout-guides'
export * from './font-style'
export * from './shared-styles'
export { default as TransformMatrix } from './matrix'
diff --git a/packages/scene-graph/src/layout-guides.ts b/packages/scene-graph/src/layout/guides.ts
similarity index 98%
rename from packages/scene-graph/src/layout-guides.ts
rename to packages/scene-graph/src/layout/guides.ts
index cc60bc8c5..4b8e081f2 100644
--- a/packages/scene-graph/src/layout-guides.ts
+++ b/packages/scene-graph/src/layout/guides.ts
@@ -1,4 +1,4 @@
-import type { LayoutGrid, SceneNode } from './types'
+import type { LayoutGrid, SceneNode } from '../types'
export interface LayoutGuideLine {
axis: 'x' | 'y'
diff --git a/packages/scene-graph/src/layout/index.ts b/packages/scene-graph/src/layout/index.ts
new file mode 100644
index 000000000..8c3f79eaa
--- /dev/null
+++ b/packages/scene-graph/src/layout/index.ts
@@ -0,0 +1,3 @@
+export * from './guides'
+export * from './keywords'
+export * from './sizing'
diff --git a/packages/scene-graph/src/layout/keywords.ts b/packages/scene-graph/src/layout/keywords.ts
new file mode 100644
index 000000000..00af61523
--- /dev/null
+++ b/packages/scene-graph/src/layout/keywords.ts
@@ -0,0 +1,73 @@
+import type { LayoutAlign, LayoutAlignSelf, LayoutCounterAlign, SceneNode } from '../types'
+
+/**
+ * Auto layout as the formats that author it spell it: flexbox keywords from CSS, design JSX,
+ * and `.pen` files. Each format keeps its own syntax and defaults; what a keyword means for the
+ * scene graph is decided here once, so `space-between` or `baseline` cannot mean one thing in
+ * one format and fall back to start in another.
+ */
+export type AutoLayoutDirection = 'HORIZONTAL' | 'VERTICAL'
+
+const DIRECTIONS = new Map<string, AutoLayoutDirection>([
+ ['row', 'HORIZONTAL'],
+ ['horizontal', 'HORIZONTAL'],
+ ['column', 'VERTICAL'],
+ ['col', 'VERTICAL'],
+ ['vertical', 'VERTICAL']
+])
+
+const POSITIONS = new Map<string, 'MIN' | 'CENTER' | 'MAX'>([
+ ['start', 'MIN'],
+ ['flex-start', 'MIN'],
+ ['center', 'CENTER'],
+ ['end', 'MAX'],
+ ['flex-end', 'MAX']
+])
+
+function keyword(value: string | undefined): string | undefined {
+ return value?.trim().toLowerCase()
+}
+
+/** The stack direction a `flex-direction`-like keyword names, or `undefined` for any other. */
+export function parseAutoLayoutDirection(
+ value: string | undefined
+): AutoLayoutDirection | undefined {
+ const name = keyword(value)
+ return name === undefined ? undefined : DIRECTIONS.get(name)
+}
+
+/**
+ * Primary axis alignment from a `justify-content` keyword. Auto layout has no
+ * `space-around` or `space-evenly`, so those, like unknown keywords, give `undefined`.
+ */
+export function parsePrimaryAxisAlign(value: string | undefined): LayoutAlign | undefined {
+ const name = keyword(value)
+ if (name === undefined) return undefined
+ if (name === 'space-between' || name === 'between') return 'SPACE_BETWEEN'
+ return POSITIONS.get(name)
+}
+
+/** Cross axis alignment of a stack's children from an `align-items` keyword. */
+export function parseCounterAxisAlign(value: string | undefined): LayoutCounterAlign | undefined {
+ const name = keyword(value)
+ if (name === undefined) return undefined
+ if (name === 'stretch') return 'STRETCH'
+ if (name === 'baseline') return 'BASELINE'
+ return POSITIONS.get(name)
+}
+
+/** One child's cross axis alignment from an `align-self` keyword; `auto` follows the parent. */
+export function parseLayoutAlignSelf(value: string | undefined): LayoutAlignSelf | undefined {
+ return keyword(value) === 'auto' ? 'AUTO' : parseCounterAxisAlign(value)
+}
+
+type PaddingFields = Pick<
+ SceneNode,
+ 'paddingTop' | 'paddingRight' | 'paddingBottom' | 'paddingLeft'
+>
+
+/** Padding from one to four values in CSS shorthand order: top, right, bottom, left. */
+export function paddingFromShorthand(values: readonly number[]): PaddingFields {
+ const [top = 0, right = top, bottom = top, left = right] = values
+ return { paddingTop: top, paddingRight: right, paddingBottom: bottom, paddingLeft: left }
+}
diff --git a/packages/scene-graph/src/layout-sizing.ts b/packages/scene-graph/src/layout/sizing.ts
similarity index 82%
rename from packages/scene-graph/src/layout-sizing.ts
rename to packages/scene-graph/src/layout/sizing.ts
index 95f5ea12d..1c63bf394 100644
--- a/packages/scene-graph/src/layout-sizing.ts
+++ b/packages/scene-graph/src/layout/sizing.ts
@@ -1,5 +1,5 @@
-import type { SceneGraph } from './index'
-import type { LayoutSizing, SceneNode, TextAutoResize } from './types'
+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
@@ -110,7 +110,8 @@ export function layoutSizingError(
return undefined
}
-function textAutoResizeFor(hugsWidth: boolean, hugsHeight: boolean): TextAutoResize {
+/** The text auto-resize that hugs the content along the axes given. */
+export function textAutoResizeFor(hugsWidth: boolean, hugsHeight: boolean): TextAutoResize {
if (hugsWidth && hugsHeight) return 'WIDTH_AND_HEIGHT'
return hugsHeight ? 'HEIGHT' : 'NONE'
}
@@ -166,3 +167,30 @@ export function layoutSizingUpdates(
if (node.type === 'TEXT') Object.assign(updates, textSizingUpdates(graph, node, axis, value))
return updates
}
+
+/**
+ * The fields that make a child fill `axis` of a parent laid out as `parentLayout`, for a node
+ * an importer builds before it joins the graph. Under a parent without auto layout, such as a
+ * staging parent the node leaves when placed, both are set, so it fills whichever axis its
+ * eventual parent stacks along.
+ */
+export function fillSizingFields(
+ parentLayout: SceneNode['layoutMode'],
+ axis: LayoutSizingAxis
+): Partial<Pick<SceneNode, 'layoutGrow' | 'layoutAlignSelf'>> {
+ if (parentLayout === 'NONE') return { layoutGrow: 1, layoutAlignSelf: 'STRETCH' }
+ return axis === primaryAxis(parentLayout) ? { layoutGrow: 1 } : { layoutAlignSelf: 'STRETCH' }
+}
+
+/** An auto-layout frame's own sizing when it hugs or fixes its width and height. */
+export function autoLayoutSizingFields(
+ direction: AutoLayoutMode,
+ width: 'FIXED' | 'HUG',
+ height: 'FIXED' | 'HUG'
+): Pick<SceneNode, 'primaryAxisSizing' | 'counterAxisSizing'> {
+ const horizontal = primaryAxis(direction) === 'HORIZONTAL'
+ return {
+ primaryAxisSizing: horizontal ? width : height,
+ counterAxisSizing: horizontal ? height : width
+ }
+}
diff --git a/packages/scene-graph/tests/css/layout.test.ts b/packages/scene-graph/tests/css/layout.test.ts
new file mode 100644
index 000000000..ea5e2f012
--- /dev/null
+++ b/packages/scene-graph/tests/css/layout.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ parseCSSAlignItems,
+ parseCSSAlignSelf,
+ parseCSSFlexDirection,
+ parseCSSJustifyContent
+} from '@open-pencil/scene-graph/css'
+
+describe('CSS layout values', () => {
+ test('flex directions that auto layout stacks along', () => {
+ expect(parseCSSFlexDirection('row')).toBe('HORIZONTAL')
+ expect(parseCSSFlexDirection(' COLUMN ')).toBe('VERTICAL')
+ expect(parseCSSFlexDirection('row-reverse')).toBeUndefined()
+ // Design JSX and .pen spellings are not CSS.
+ expect(parseCSSFlexDirection('col')).toBeUndefined()
+ expect(parseCSSJustifyContent('between')).toBeUndefined()
+ expect(parseCSSJustifyContent('space-between')).toBe('SPACE_BETWEEN')
+ })
+
+ test('alignment drops the overflow position and reads first baseline as baseline', () => {
+ expect(parseCSSJustifyContent('safe center')).toBe('CENTER')
+ expect(parseCSSJustifyContent('unsafe flex-end')).toBe('MAX')
+ expect(parseCSSAlignItems('first baseline')).toBe('BASELINE')
+ expect(parseCSSAlignItems('last baseline')).toBeUndefined()
+ expect(parseCSSJustifyContent('space-around')).toBeUndefined()
+ expect(parseCSSAlignItems('var(--align)')).toBeUndefined()
+ })
+
+ test('normal aligns flex items as browsers do', () => {
+ expect(parseCSSJustifyContent('normal')).toBe('MIN')
+ expect(parseCSSAlignItems('normal')).toBe('STRETCH')
+ expect(parseCSSAlignSelf('normal')).toBe('STRETCH')
+ expect(parseCSSAlignSelf('auto')).toBe('AUTO')
+ })
+})
diff --git a/packages/scene-graph/tests/layout-sizing.test.ts b/packages/scene-graph/tests/layout-sizing.test.ts
deleted file mode 100644
index c0641a209..000000000
--- a/packages/scene-graph/tests/layout-sizing.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-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/scene-graph/tests/layout-guides.test.ts b/packages/scene-graph/tests/layout/guides.test.ts
similarity index 96%
rename from packages/scene-graph/tests/layout-guides.test.ts
rename to packages/scene-graph/tests/layout/guides.test.ts
index af157545a..8d711f1bd 100644
--- a/packages/scene-graph/tests/layout-guides.test.ts
+++ b/packages/scene-graph/tests/layout/guides.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { layoutGuideLines, layoutGuideSections } from '@open-pencil/scene-graph/layout-guides'
+import { layoutGuideLines, layoutGuideSections } from '@open-pencil/scene-graph/layout'
describe('layout guide geometry bounds', () => {
test('normalizes fractional section counts', () => {
diff --git a/packages/scene-graph/tests/layout/keywords.test.ts b/packages/scene-graph/tests/layout/keywords.test.ts
new file mode 100644
index 000000000..ec25893a9
--- /dev/null
+++ b/packages/scene-graph/tests/layout/keywords.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ paddingFromShorthand,
+ parseAutoLayoutDirection,
+ parseCounterAxisAlign,
+ parseLayoutAlignSelf,
+ parsePrimaryAxisAlign
+} from '@open-pencil/scene-graph'
+
+describe('auto layout keywords', () => {
+ test('read stack directions in each format spelling', () => {
+ for (const value of ['row', 'horizontal', 'ROW']) {
+ expect(parseAutoLayoutDirection(value)).toBe('HORIZONTAL')
+ }
+ for (const value of ['column', 'col', 'vertical']) {
+ expect(parseAutoLayoutDirection(value)).toBe('VERTICAL')
+ }
+ expect(parseAutoLayoutDirection('row-reverse')).toBeUndefined()
+ expect(parseAutoLayoutDirection('constructor')).toBeUndefined()
+ })
+
+ test('read justify keywords from CSS and design JSX alike', () => {
+ expect(parsePrimaryAxisAlign('space-between')).toBe('SPACE_BETWEEN')
+ expect(parsePrimaryAxisAlign('between')).toBe('SPACE_BETWEEN')
+ expect(parsePrimaryAxisAlign('flex-end')).toBe('MAX')
+ expect(parsePrimaryAxisAlign(' Center ')).toBe('CENTER')
+ // Auto layout cannot distribute space around or evenly.
+ expect(parsePrimaryAxisAlign('space-around')).toBeUndefined()
+ expect(parsePrimaryAxisAlign('space-evenly')).toBeUndefined()
+ })
+
+ test('read cross axis keywords, with auto only for one child', () => {
+ expect(parseCounterAxisAlign('baseline')).toBe('BASELINE')
+ expect(parseCounterAxisAlign('stretch')).toBe('STRETCH')
+ expect(parseCounterAxisAlign('flex-start')).toBe('MIN')
+ expect(parseCounterAxisAlign('auto')).toBeUndefined()
+ expect(parseLayoutAlignSelf('auto')).toBe('AUTO')
+ expect(parseLayoutAlignSelf('end')).toBe('MAX')
+ })
+
+ test('expand padding in CSS shorthand order', () => {
+ expect(paddingFromShorthand([8])).toEqual({
+ paddingTop: 8,
+ paddingRight: 8,
+ paddingBottom: 8,
+ paddingLeft: 8
+ })
+ expect(paddingFromShorthand([8, 16])).toEqual({
+ paddingTop: 8,
+ paddingRight: 16,
+ paddingBottom: 8,
+ paddingLeft: 16
+ })
+ expect(paddingFromShorthand([1, 2, 3])).toEqual({
+ paddingTop: 1,
+ paddingRight: 2,
+ paddingBottom: 3,
+ paddingLeft: 2
+ })
+ expect(paddingFromShorthand([1, 2, 3, 4])).toEqual({
+ paddingTop: 1,
+ paddingRight: 2,
+ paddingBottom: 3,
+ paddingLeft: 4
+ })
+ })
+})
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..ae501aa3c
--- /dev/null
+++ b/packages/scene-graph/tests/layout/sizing.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ autoLayoutSizingFields,
+ fillSizingFields,
+ 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'
+ })
+ })
+})
+
+describe('sizing fields for nodes built before they join the graph', () => {
+ test('fill fields read back as fill on each axis of every auto layout parent', () => {
+ for (const layoutMode of ['HORIZONTAL', 'VERTICAL', 'GRID'] as const) {
+ for (const axis of ['HORIZONTAL', 'VERTICAL'] as const) {
+ const { graph, node } = child({ layoutMode }, fillSizingFields(layoutMode, axis))
+ expect(layoutSizing(graph, node, axis)).toBe('FILL')
+ const other = axis === 'HORIZONTAL' ? 'VERTICAL' : 'HORIZONTAL'
+ expect(layoutSizing(graph, node, other)).not.toBe('FILL')
+ }
+ }
+ })
+
+ test('fill under a parent without auto layout fills either axis once placed', () => {
+ const fields = fillSizingFields('NONE', 'HORIZONTAL')
+ for (const layoutMode of ['HORIZONTAL', 'VERTICAL'] as const) {
+ const { graph, node } = child({ layoutMode }, fields)
+ expect(layoutSizing(graph, node, 'HORIZONTAL')).toBe('FILL')
+ }
+ })
+
+ test('own sizing fields read back per screen axis', () => {
+ for (const layoutMode of ['HORIZONTAL', 'VERTICAL'] as const) {
+ const { graph, node } = child(
+ {},
+ { layoutMode, ...autoLayoutSizingFields(layoutMode, 'HUG', 'FIXED') }
+ )
+ expect(layoutSizing(graph, node, 'HORIZONTAL')).toBe('HUG')
+ expect(layoutSizing(graph, node, 'VERTICAL')).toBe('FIXED')
+ }
+ })
+})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index a698af812..60aafff15 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -25,7 +25,7 @@ export default defineConfig({
matrix: './src/matrix.ts',
geometry: './src/geometry.ts',
guides: './src/guides.ts',
- 'layout-guides': './src/layout-guides.ts',
+ layout: './src/layout/index.ts',
resize: './src/resize.ts',
'parse-path': './src/parse-path.ts',
random: './src/random.ts',
diff --git a/packages/vue/src/shared/input/explicit-snap-targets.ts b/packages/vue/src/shared/input/explicit-snap-targets.ts
index b9049c9dd..41b83a92f 100644
--- a/packages/vue/src/shared/input/explicit-snap-targets.ts
+++ b/packages/vue/src/shared/input/explicit-snap-targets.ts
@@ -1,7 +1,7 @@
import type { Editor } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import { layoutGuideLines } from '@open-pencil/scene-graph/layout-guides'
+import { layoutGuideLines } from '@open-pencil/scene-graph/layout'
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Vector } from '@open-pencil/scene-graph/primitives'
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index f5b6a4f6a..851b26cd2 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -9,7 +9,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `flex="row"` / `flex="col"` enables auto-layout. Use it for content; reserve explicit `x`/`y` or `position="absolute"` for intentional overlays and artwork. Without layout, children share the origin unless positioned.
- `w` / `h` accept pixels, `"hug"` (content-sized), or `"fill"` (available space in a supported layout parent). Use Hug for notes, cards, and long pages instead of guessing heights. Fixed viewport sizes and artwork geometry are intentional exceptions.
- `gap` controls spacing. `p`, `px`, `py`, and `pt`/`pr`/`pb`/`pl` control padding; longhands override shorthands. There is no margin shorthand.
-- `justify="start"|"end"|"center"|"between"` controls the primary axis; `items="start"|"end"|"center"|"stretch"` controls the cross axis. Distribution needs available space: `between` cannot create extra room in a Hug container.
+- `justify="start"|"end"|"center"|"between"` controls the primary axis; `items="start"|"end"|"center"|"stretch"|"baseline"` controls the cross axis. Distribution needs available space: `between` cannot create extra room in a Hug container.
- `grow` distributes available space. Avoid circular Hug/Fill dependencies and redundant fixed widths on growing children. Keep Fill sizing through intermediate containers that should stretch.
- For wrapping text in a column, prefer `w="fill"`; fixed-width text can use `textAutoResize="height"`. `maxLines` / `truncate` are intentional truncation, not fixes for accidental overflow.
- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.