Skip to content

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

fix: lay out fill text and repeat() grid tracks (#866)

Danila Poyarkov37bc706a5910
diff --git a/AGENTS.md b/AGENTS.md
index 1137681f0..89c3cf908 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,7 +8,7 @@ This file holds the repository map and the rules that apply everywhere. Rules fo
| Path | Owns | Guide |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
-| `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, text/layout direction | `packages/scene-graph/AGENTS.md` |
+| `packages/scene-graph` | Framework-neutral graph, node types, geometry, copy/snap/undo, variables, instances, hit testing, plus the shared primitives formats need: color conversion and management, CSS value parsing, text/layout direction | `packages/scene-graph/AGENTS.md` |
| `packages/pen` | Pencil.dev `.pen` model, parser, SceneGraph adapter | — |
| `packages/kiwi` | SceneGraph-independent Kiwi schema/runtime, codecs, containers, parse helpers | `packages/fig/AGENTS.md` |
| `packages/fig` | `.fig` archives, SceneGraph conversion, metadata policy, component/instance interpretation, Figma clipboard | `packages/fig/AGENTS.md` |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c1c68c05f..91c26b272 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -77,6 +77,8 @@
### Fixed
+- Read `repeat()` and `minmax()` in design JSX grid tracks, such as `columns="repeat(7, 1fr)"`, which collapsed the grid to near-zero columns. A track the grid cannot express sizes to its content instead of to 0.
+- Lay out text set to fill its container the way Figma does: fill text in an auto-layout row now shares the free space with its siblings instead of keeping its old width and overflowing the row.
- Report what `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient` expect when design JSX passes them something other than an array of stops, such as `linearGradient('#3b82f6')`, instead of failing with `stops.map is not a function`, so an AI agent can correct the call.
- Keep the canvas context menu open when you right-click again right after closing it, which could close it again at once, especially with reduced motion.
- Show and edit the component properties of an instance nested inside another instance; they were missing because the nested instance was read as its own component.
diff --git a/bun.lock b/bun.lock
index 851383405..91cf4b0f5 100644
--- a/bun.lock
+++ b/bun.lock
@@ -413,6 +413,7 @@
"culori": "^4.0.2",
"es-toolkit": "^1.52.0",
"nanoevents": "^9.1.0",
+ "postcss-value-parser": "^4.2.0",
"svgpath": "^2.6.0",
"valibot": "^1.5.0",
},
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 1fbf5ae6c..6643594c2 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -385,6 +385,24 @@ function derivedGrowingLeafFitsParent(
return sizesFitParent(parent, children.length, sizes, axis)
}
+/**
+ * Fill text shares its parent's main axis like a fill frame: it grows and shrinks from a zero
+ * basis, so its stored width (100px for new text) never decides its share. Returns whether
+ * it fills the row's width, where its stored width must not constrain it either.
+ */
+function configureGrowingText(
+ yogaChild: YogaNode,
+ child: SceneNode,
+ parent: SceneNode,
+ fixedDerivedMainAxis: boolean
+): boolean {
+ if (child.layoutGrow <= 0 || fixedDerivedMainAxis) return false
+ yogaChild.setFlexGrow(child.layoutGrow)
+ yogaChild.setFlexShrink(1)
+ yogaChild.setFlexBasis(0)
+ return parent.layoutMode === 'HORIZONTAL'
+}
+
function configureTextLeafWithoutMeasurer(
yogaChild: YogaNode,
child: SceneNode,
@@ -407,6 +425,7 @@ function configureTextLeafWithoutMeasurer(
}
if (child.textAutoResize !== 'HEIGHT') return
+ const growsWidth = configureGrowingText(yogaChild, child, parent, fixedDerivedMainAxis)
const isRow = parent.layoutMode === 'HORIZONTAL'
const measurementWidth = fixedDerivedMainAxis
? (child.derivedLayout?.width ?? child.width)
@@ -414,7 +433,9 @@ function configureTextLeafWithoutMeasurer(
const stretches =
child.layoutAlignSelf === 'STRETCH' ||
(child.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')
- if (!(!isRow && stretches) && !fixedDerivedMainAxis) yogaChild.setWidth(child.width)
+ if (!(!isRow && stretches) && !fixedDerivedMainAxis && !growsWidth) {
+ yogaChild.setWidth(child.width)
+ }
if (hasStoredSize) yogaChild.setHeight(child.height)
else yogaChild.setHeight(estimateTextSize(child, measurementWidth).height)
}
@@ -472,10 +493,7 @@ function configureTextLeaf(
): void {
const autoResize = child.textAutoResize
const isRow = parent.layoutMode === 'HORIZONTAL'
-
- if (child.layoutGrow > 0 && !fixedDerivedMainAxis) {
- yogaChild.setFlexGrow(child.layoutGrow)
- }
+ const growsWidth = configureGrowingText(yogaChild, child, parent, fixedDerivedMainAxis)
const cache = new Map<number, { width: number; height: number }>()
const UNCONSTRAINED_KEY = -1
@@ -503,8 +521,8 @@ function configureTextLeaf(
const stretchesCross =
child.layoutAlignSelf === 'STRETCH' ||
(child.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')
- // Let Yoga stretch fill-width text instead of fixing its stored width.
- const fillsWidth = !isRow && stretchesCross
+ // Let Yoga stretch or grow fill-width text instead of fixing its stored width.
+ const fillsWidth = (!isRow && stretchesCross) || growsWidth
const fixedWidth = fixedDerivedMainAxis
? (child.derivedLayout?.width ?? child.width)
: child.width
diff --git a/packages/core/tests/design-jsx/grid.test.ts b/packages/core/tests/design-jsx/grid.test.ts
new file mode 100644
index 000000000..9b845ceae
--- /dev/null
+++ b/packages/core/tests/design-jsx/grid.test.ts
@@ -0,0 +1,23 @@
+import { expect, test } from 'bun:test'
+
+import { renderJSX } from '@open-pencil/core/design-jsx'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+test('a repeat() grid places its cells in equal columns, not collapsed ones', async () => {
+ const graph = new SceneGraph()
+ const cells = Array.from({ length: 14 }, (_, i) => `<Frame name="C${i}" w={20} h={36} />`)
+ const [root] = await renderJSX(
+ graph,
+ `<Frame grid columns="repeat(7, 1fr)" gap={4} w={280}>${cells.join('')}</Frame>`
+ )
+
+ const column = (280 - 6 * 4) / 7
+ const children = getNodeOrThrow(graph, root.id).childIds.map((id) => getNodeOrThrow(graph, id))
+ for (const [index, cell] of children.entries()) {
+ expect(cell.x).toBeCloseTo((index % 7) * (column + 4), 3)
+ expect(cell.y).toBe(Math.floor(index / 7) * 40)
+ expect(cell.height).toBe(36)
+ }
+})
diff --git a/packages/core/tests/layout/auto-layout/text/fill.test.ts b/packages/core/tests/layout/auto-layout/text/fill.test.ts
new file mode 100644
index 000000000..ef549f319
--- /dev/null
+++ b/packages/core/tests/layout/auto-layout/text/fill.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { computeAllLayouts, SceneGraph, setTextMeasurer } from '@open-pencil/core'
+
+const DAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
+
+/** Fixed-width text that wraps to its width and grows to fill its share of the parent. */
+function fillText(graph: SceneGraph, parentId: string, text: string) {
+ return graph.createNode('TEXT', parentId, {
+ name: text,
+ text,
+ fontSize: 12,
+ textAutoResize: 'HEIGHT',
+ layoutGrow: 1
+ })
+}
+
+function row(graph: SceneGraph, width: number) {
+ return graph.createNode('FRAME', graph.getPages()[0].id, {
+ layoutMode: 'HORIZONTAL',
+ width,
+ height: 20,
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 2
+ })
+}
+
+afterEach(() => setTextMeasurer(null))
+
+// Fill text starts at the default 100px width, so its stored width must not become its basis.
+describe.each([
+ ['with a text measurer', () => setTextMeasurer(() => ({ width: 15, height: 16 }))],
+ ['without a text measurer', () => setTextMeasurer(null)]
+])('fill text %s', (_, useMeasurer) => {
+ test('shares a fixed row evenly, like fill frames', () => {
+ useMeasurer()
+ const graph = new SceneGraph()
+ const week = row(graph, 280)
+ const labels = DAYS.map((day) => fillText(graph, week.id, day))
+
+ computeAllLayouts(graph)
+
+ const share = (280 - 6 * 2) / 7
+ for (const [index, label] of labels.entries()) {
+ expect(label.width).toBeCloseTo(share, 3)
+ expect(label.x).toBeCloseTo(index * (share + 2), 3)
+ }
+ })
+
+ test('takes the space a fixed sibling leaves', () => {
+ useMeasurer()
+ const graph = new SceneGraph()
+ const header = row(graph, 200)
+ graph.createNode('FRAME', header.id, { width: 40, height: 20 })
+ const title = fillText(graph, header.id, 'March 2025')
+
+ computeAllLayouts(graph)
+
+ expect(title.width).toBeCloseTo(200 - 40 - 2, 3)
+ expect(title.x).toBeCloseTo(42, 3)
+ })
+})
diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.ts
index 127bb1c3d..7f2697b0b 100644
--- a/packages/design-jsx/src/props-overrides.ts
+++ b/packages/design-jsx/src/props-overrides.ts
@@ -1,5 +1,6 @@
-import type { Fill, GridTrack, LayoutMode, SceneNode } from '@open-pencil/scene-graph'
+import type { Fill, LayoutMode, SceneNode } from '@open-pencil/scene-graph'
import { colorToFill } from '@open-pencil/scene-graph/color'
+import { parseCSSGridTracks } from '@open-pencil/scene-graph/css'
import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'
import { applyEffectOverrides } from './overrides/effects'
@@ -258,20 +259,6 @@ function hasAutoLayoutTriggerProps(props: Record<string, unknown>): boolean {
return AUTO_LAYOUT_TRIGGER_KEYS.some((k) => props[k] !== undefined)
}
-function parseTrack(token: string): GridTrack {
- if (token.endsWith('fr')) {
- return { sizing: 'FR', value: Number.parseFloat(token) || 1 }
- }
- if (token === 'auto') {
- return { sizing: 'AUTO', value: 0 }
- }
- return { sizing: 'FIXED', value: Number.parseFloat(token) || 0 }
-}
-
-function parseTrackList(value: string): GridTrack[] {
- return value.trim().split(/\s+/).map(parseTrack)
-}
-
function applyGridOverrides(
props: Record<string, unknown>,
o: Partial<SceneNode>,
@@ -284,7 +271,7 @@ function applyGridOverrides(
if (typeof h === 'number') o.height = h
if (typeof props.columns === 'string') {
- o.gridTemplateColumns = parseTrackList(props.columns)
+ o.gridTemplateColumns = parseCSSGridTracks(props.columns)
} else if (typeof props.columns === 'number') {
o.gridTemplateColumns = Array.from({ length: props.columns }, () => ({
sizing: 'FR' as const,
@@ -293,7 +280,7 @@ function applyGridOverrides(
}
if (typeof props.rows === 'string') {
- o.gridTemplateRows = parseTrackList(props.rows)
+ o.gridTemplateRows = parseCSSGridTracks(props.rows)
} else if (typeof props.rows === 'number') {
o.gridTemplateRows = Array.from({ length: props.rows }, () => ({
sizing: 'FR' as const,
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 92ae7f231..68ff12859 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -10,7 +10,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `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.
- `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"`). Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.
+- `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`.
- `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.
- Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.
- Use measured node bounds and the existing `arrange` tool for independent artboards. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.
diff --git a/packages/design-jsx/tests/grid.test.ts b/packages/design-jsx/tests/grid.test.ts
new file mode 100644
index 000000000..06b807e54
--- /dev/null
+++ b/packages/design-jsx/tests/grid.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from 'bun:test'
+
+import { jsxNodeFields, parseJSXAttributes } from '#design-jsx/index'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function columns(value: string) {
+ const graph = new SceneGraph()
+ const attributes = parseJSXAttributes(`grid columns="${value}"`)
+ return jsxNodeFields(graph, 'FRAME', attributes, graph.getPages()[0].id).fields
+ .gridTemplateColumns
+}
+
+const FR = { sizing: 'FR', value: 1 }
+
+describe('grid track lists', () => {
+ test.each([
+ ['1fr 200px 1fr', [FR, { sizing: 'FIXED', value: 200 }, FR]],
+ ['repeat(3, 1fr)', [FR, FR, FR]],
+ [
+ 'repeat(2, 40px 1fr)',
+ [{ sizing: 'FIXED', value: 40 }, FR, { sizing: 'FIXED', value: 40 }, FR]
+ ],
+ ['minmax(0, 1fr) auto', [FR, { sizing: 'AUTO', value: 0 }]],
+ [
+ '2fr 64',
+ [
+ { sizing: 'FR', value: 2 },
+ { sizing: 'FIXED', value: 64 }
+ ]
+ ]
+ ])('%p', (value, tracks) => {
+ expect(columns(value)).toEqual(tracks)
+ })
+
+ test('sizes a track the grid cannot express to its content, not to zero', () => {
+ expect(columns('10rem 1fr')).toEqual([{ sizing: 'AUTO', value: 0 }, FR])
+ })
+})
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index c69219b0e..61f183d9a 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -12,7 +12,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `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.
- `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"`). Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.
+- `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`.
- `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.
- Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.
- Use measured node bounds and the existing `arrange` tool for independent artboards. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.
diff --git a/packages/dom-css/src/import/css-values.ts b/packages/dom-css/src/import/css-values.ts
index 5de8b988a..5c20679aa 100644
--- a/packages/dom-css/src/import/css-values.ts
+++ b/packages/dom-css/src/import/css-values.ts
@@ -1,4 +1,4 @@
-import valueParser, { type ParsedNode } from 'postcss-value-parser'
+import valueParser, { type Node } from 'postcss-value-parser'
import type { Effect, Fill, Stroke } from '@open-pencil/scene-graph'
import { parseColor } from '@open-pencil/scene-graph/color'
@@ -40,8 +40,8 @@ export function colorToStrokeFromCSS(
return [{ type: 'SOLID', color, weight, opacity: color.a, visible: true, align: 'INSIDE' }]
}
-function firstShadowLayerNodes(value: string): ParsedNode[] {
- const nodes: ParsedNode[] = []
+function firstShadowLayerNodes(value: string): Node[] {
+ const nodes: Node[] = []
for (const node of valueParser(value).nodes) {
if (node.type === 'div' && node.value === ',') return nodes
nodes.push(node)
@@ -49,7 +49,7 @@ function firstShadowLayerNodes(value: string): ParsedNode[] {
return nodes
}
-function shadowColorFromNodes(nodes: ParsedNode[]): Color | null {
+function shadowColorFromNodes(nodes: Node[]): Color | null {
for (const node of nodes) {
if (node.type === 'function') {
const color = parseCSSColor(valueParser.stringify(node))
@@ -64,7 +64,7 @@ function shadowColorFromNodes(nodes: ParsedNode[]): Color | null {
return null
}
-function shadowNumbersFromNodes(nodes: ParsedNode[]): number[] {
+function shadowNumbersFromNodes(nodes: Node[]): number[] {
return nodes
.filter((node) => node.type === 'word' && valueParser.unit(node.value) !== false)
.map((node) => parseCSSNumber(node.value))
diff --git a/packages/dom-css/src/postcss-value-parser.d.ts b/packages/dom-css/src/postcss-value-parser.d.ts
deleted file mode 100644
index 72140fef5..000000000
--- a/packages/dom-css/src/postcss-value-parser.d.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-declare module 'postcss-value-parser' {
- export interface ParsedNodeBase {
- type: string
- value: string
- before?: string
- after?: string
- sourceIndex?: number
- }
-
- export interface FunctionNode extends ParsedNodeBase {
- type: 'function'
- nodes: ParsedNode[]
- }
-
- export type ParsedNode = ParsedNodeBase | FunctionNode
-
- export interface ParsedValue {
- nodes: ParsedNode[]
- }
-
- export interface ParsedUnit {
- number: string
- unit: string
- }
-
- interface ValueParser {
- (value: string): ParsedValue
- stringify(node: ParsedNode | ParsedNode[]): string
- unit(value: string): ParsedUnit | false
- }
-
- const valueParser: ValueParser
- export default valueParser
-}
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index 7d9e89a58..6503b3547 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -11,6 +11,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 need live here: color conversion and management under `@open-pencil/scene-graph/color` and text/layout direction under `@open-pencil/scene-graph/text-direction`.
+- 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; 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/`.
- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes; Core's atomic tool execution relies on it.
diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.json
index 4643f5be5..6db84f577 100644
--- a/packages/scene-graph/package.json
+++ b/packages/scene-graph/package.json
@@ -185,6 +185,12 @@
"import": "./dist/color.js",
"default": "./dist/color.js"
},
+ "./css": {
+ "types": "./dist/css.d.ts",
+ "bun": "./src/css/index.ts",
+ "import": "./dist/css.js",
+ "default": "./dist/css.js"
+ },
"./text-direction": {
"types": "./dist/text-direction.d.ts",
"bun": "./src/text-direction.ts",
@@ -208,6 +214,7 @@
"culori": "^4.0.2",
"es-toolkit": "^1.52.0",
"nanoevents": "^9.1.0",
+ "postcss-value-parser": "^4.2.0",
"svgpath": "^2.6.0",
"valibot": "^1.5.0"
},
diff --git a/packages/scene-graph/src/css/grid.ts b/packages/scene-graph/src/css/grid.ts
new file mode 100644
index 000000000..f3cb649c4
--- /dev/null
+++ b/packages/scene-graph/src/css/grid.ts
@@ -0,0 +1,69 @@
+import valueParser, { type FunctionNode, type Node } from 'postcss-value-parser'
+
+import type { GridTrack } from '../types'
+
+/** Bounds a `repeat()` count, which a typo could make huge. */
+const MAX_REPEATED_TRACKS = 100
+
+/** `auto`, and sizes a grid track cannot express, size to their content rather than to 0. */
+function autoTrack(): GridTrack {
+ return { sizing: 'AUTO', value: 0 }
+}
+
+/** A function's arguments, split at its commas. */
+function argumentsOf(node: FunctionNode): Node[][] {
+ const args: Node[][] = []
+ let current: Node[] = []
+ for (const child of node.nodes) {
+ if (child.type === 'div' && child.value === ',') {
+ args.push(current)
+ current = []
+ } else {
+ current.push(child)
+ }
+ }
+ args.push(current)
+ return args
+}
+
+function wordTrack(word: string): GridTrack {
+ const dimension = valueParser.unit(word)
+ if (!dimension) return autoTrack()
+ const value = Number(dimension.number)
+ if (dimension.unit === 'fr') return { sizing: 'FR', value: value || 1 }
+ if (dimension.unit === '' || dimension.unit === 'px') return { sizing: 'FIXED', value }
+ return autoTrack()
+}
+
+function functionTracks(node: FunctionNode): GridTrack[] {
+ const [first = [], second = [], ...rest] = argumentsOf(node)
+ switch (node.value.toLowerCase()) {
+ case 'repeat': {
+ const count = Number(first.find((child) => child.type === 'word')?.value)
+ // `auto-fill` and `auto-fit` depend on the container, which a track list cannot know.
+ if (!Number.isInteger(count) || count < 1) return [autoTrack()]
+ const tracks = tracksOf([second, ...rest].flat())
+ return Array.from({ length: Math.min(count, MAX_REPEATED_TRACKS) }, () =>
+ tracks.map((track) => ({ ...track }))
+ ).flat()
+ }
+ case 'minmax':
+ // The maximum decides how a track grows, as `minmax(0, 1fr)` is a 1fr column.
+ return tracksOf(second)
+ default:
+ return [autoTrack()]
+ }
+}
+
+function tracksOf(nodes: Node[]): GridTrack[] {
+ return nodes.flatMap((node) => {
+ if (node.type === 'word') return [wordTrack(node.value)]
+ if (node.type === 'function') return functionTracks(node)
+ return []
+ })
+}
+
+/** The tracks of a CSS track list, such as `repeat(3, minmax(0, 1fr)) 120px auto`. */
+export function parseCSSGridTracks(value: string): GridTrack[] {
+ return tracksOf(valueParser(value).nodes)
+}
diff --git a/packages/scene-graph/src/css/index.ts b/packages/scene-graph/src/css/index.ts
new file mode 100644
index 000000000..2ce9b95be
--- /dev/null
+++ b/packages/scene-graph/src/css/index.ts
@@ -0,0 +1 @@
+export { parseCSSGridTracks } from './grid'
diff --git a/packages/scene-graph/tests/css/grid.test.ts b/packages/scene-graph/tests/css/grid.test.ts
new file mode 100644
index 000000000..6ed9dce2a
--- /dev/null
+++ b/packages/scene-graph/tests/css/grid.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from 'bun:test'
+
+import { parseCSSGridTracks } from '@open-pencil/scene-graph/css'
+
+const FR = { sizing: 'FR', value: 1 }
+const AUTO = { sizing: 'AUTO', value: 0 }
+const fixed = (value: number) => ({ sizing: 'FIXED', value })
+
+describe('parseCSSGridTracks', () => {
+ test.each([
+ ['1fr 200px 1fr', [FR, fixed(200), FR]],
+ ['2fr 64', [{ sizing: 'FR', value: 2 }, fixed(64)]],
+ ['repeat(3, 1fr)', [FR, FR, FR]],
+ ['repeat(2, 40px 1fr)', [fixed(40), FR, fixed(40), FR]],
+ ['minmax(0, 1fr) auto', [FR, AUTO]],
+ ['repeat(2, minmax(0, 1fr) 100px)', [FR, fixed(100), FR, fixed(100)]],
+ [' REPEAT( 2 , 1fr ) 120px ', [FR, FR, fixed(120)]]
+ ])('%p', (value, tracks) => {
+ expect(parseCSSGridTracks(value)).toEqual(tracks)
+ })
+
+ test.each([
+ ['a length the grid cannot express', '10rem 1fr', [AUTO, FR]],
+ ['a sizing function', 'fit-content(200px) 1fr', [AUTO, FR]],
+ ['a repeat that depends on the container', 'repeat(auto-fill, 100px)', [AUTO]]
+ ])('sizes %s to its content, not to zero', (_case, value, tracks) => {
+ expect(parseCSSGridTracks(value)).toEqual(tracks)
+ })
+
+ test('bounds a huge repeat count', () => {
+ expect(parseCSSGridTracks('repeat(100000, 1fr)')).toHaveLength(100)
+ })
+
+ test('returns separate track objects for repeated tracks', () => {
+ const [first, second] = parseCSSGridTracks('repeat(2, 1fr)')
+ expect(first).not.toBe(second)
+ })
+})
diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.ts
index 29b2acd0a..c918a3cd2 100644
--- a/packages/scene-graph/tsdown.config.ts
+++ b/packages/scene-graph/tsdown.config.ts
@@ -30,6 +30,7 @@ export default defineConfig({
'parse-path': './src/parse-path.ts',
random: './src/random.ts',
color: './src/color/index.ts',
+ css: './src/css/index.ts',
'text-direction': './src/text-direction.ts'
},
platform: 'neutral',
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index c69219b0e..61f183d9a 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -12,7 +12,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `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.
- `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"`). Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.
+- `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`.
- `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.
- Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.
- Use measured node bounds and the existing `arrange` tool for independent artboards. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.