Skip to content

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

feat(storybook): export text properties as props of generated components (#1003)

Danila Poyarkov2c063265f468
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ae4809ae..607810fc9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,7 +76,7 @@
- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.
- Detach an instance from its component with `detachInstance()` in the plugin API, as in Figma, from scripts run through `eval`.
- Run scripts written for Figma's dynamic-page mode that call `figma.getNodeByIdAsync()` or `getMainComponentAsync()`; both resolve to the same nodes as their synchronous forms.
-- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, or Collapsible becomes a Reka UI or Radix UI component whose variants are compiled into state styles, with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
+- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, or Collapsible becomes a Reka UI or Radix UI component whose variants are compiled into state styles and whose text properties are string props with a text control, with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do. Vector shapes, booleans, stars, and polygons export as inline SVG with their fills, gradients, strokes, and shadows, in HTML, Tailwind JSX, and Storybook stories.
- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.
- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index 434ec244e..831d9deba 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -9,6 +9,7 @@ import { camelCase } from 'es-toolkit/string'
import {
behaviourContract,
behaviourProperties,
+ findLayerByPath,
layerPath,
readBehaviour,
slotPropertyId,
@@ -18,7 +19,7 @@ import {
} from '@open-pencil/scene-graph'
import type { SceneGraphToDesignOptions } from '../projection'
-import { identifierName } from '../storybook/names'
+import { claimName, identifierName } from '../storybook/names'
/** Kinds generated as components so far; the rest keep static stories. */
export const GENERATED_KINDS = ['button', 'switch', 'checkbox', 'toggle', 'collapsible'] as const
@@ -60,7 +61,20 @@ export interface ComponentElement {
children: ComponentNode[]
}
-export type ComponentNode = ComponentElement | { type: 'text'; value: string }
+/** A text property the component takes as a string prop and draws in the layers bound to it. */
+export interface TextProp {
+ /** The prop's identifier. */
+ name: string
+ /** The text property's name. */
+ property: string
+ default: string
+}
+
+export type ComponentNode =
+ | ComponentElement
+ | { type: 'text'; value: string }
+ /** The value of a text prop, drawn where the design binds a text layer to it. */
+ | { type: 'textProp'; name: string }
/** One component generated from a component set with a behaviour. */
export interface ComponentModel {
@@ -75,28 +89,75 @@ export interface ComponentModel {
/** Whether the set draws a disabled state, so the component takes `disabled`. */
disabled: boolean
props: VariantProp[]
+ texts: TextProp[]
+}
+
+interface TreeLabels {
+ parts: Map<StateElement, string>
+ classes: Map<StateElement, string>
+ /** The text prop each bound text layer draws, by layer. */
+ texts: Map<StateElement, string>
}
function componentTree(
node: StateElement,
- parts: Map<StateElement, string>,
- classes: Map<StateElement, string>,
+ labels: TreeLabels,
bindings: ComponentBinding[]
): ComponentElement {
- const part = parts.get(node) ?? null
+ const part = labels.parts.get(node) ?? null
+ const text = labels.texts.get(node)
return {
type: 'element',
part,
tag: node.tagName,
- className: classes.get(node) ?? '',
+ className: labels.classes.get(node) ?? '',
attrs: node.attrs,
bindings: part === 'root' ? bindings : [],
- children: node.children.map((child) =>
- child.type === 'text'
- ? { type: 'text', value: child.text }
- : componentTree(child, parts, classes, [])
- )
+ // A bound text layer draws its prop in place of the design's words and their runs.
+ children: text
+ ? [{ type: 'textProp', name: text }]
+ : node.children.map((child) =>
+ child.type === 'text'
+ ? { type: 'text', value: child.text }
+ : componentTree(child, labels, [])
+ )
+ }
+}
+
+/**
+ * The set's text properties as props, and the layers bound to each. A layer is bound when it
+ * is in any variant, found by the path every variant shares.
+ */
+function textProps(
+ graph: SceneGraph,
+ set: SceneNode,
+ elements: readonly StateElement[],
+ taken: Set<string>
+): { texts: TextProp[]; bound: Map<StateElement, string> } {
+ const definitions = behaviourProperties(graph, set).filter((item) => item.type === 'TEXT')
+ const texts = definitions.map((definition) => ({
+ name: claimName(camelCase(identifierName(definition.name, 'Text')), taken),
+ property: definition.name,
+ default: definition.defaultValue
+ }))
+ const byId = new Map(definitions.map((definition, i) => [definition.id, texts[i]]))
+ const variants = graph.getChildren(set.id)
+ const bound = new Map<StateElement, string>()
+ for (const element of elements) {
+ // A key ends with the words a layer reads, which a text prop draws in every variant.
+ const path = element.key.split('\0')[0] ?? ''
+ for (const variant of variants) {
+ const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find(
+ (item) => item.field === 'TEXT'
+ )
+ const prop = reference && byId.get(reference.propertyId)
+ if (prop) {
+ bound.set(element, prop.name)
+ break
+ }
+ }
}
+ return { texts, bound }
}
/** A generated component's files, and what its stories need to know about it. */
@@ -165,10 +226,11 @@ export function componentModel(
const booleans = [...args.booleans.values()]
const model = booleans.find((arg) => arg.name !== 'disabled')?.name ?? null
const bound = new Set([...args.booleans.keys(), args.states?.property])
+ const taken = new Set([...(model ? [model] : []), 'disabled'])
const props = behaviourProperties(graph, set)
.filter((definition) => definition.type === 'VARIANT' && !bound.has(definition.name))
.map((definition) => ({
- name: camelCase(identifierName(definition.name, 'Prop')),
+ name: claimName(camelCase(identifierName(definition.name, 'Prop')), taken),
property: definition.name,
options: definition.variantOptions ?? [],
default: definition.defaultValue
@@ -184,13 +246,19 @@ export function componentModel(
attribute: propAttribute(prop.property)
}))
]
+ const texts = textProps(graph, set, allElements(styles.root), taken)
return {
name: identifierName(set.name, 'Component'),
kind: behaviour.kind,
styles,
- tree: componentTree(styles.root, parts, layerClassNames(styles), bindings),
+ tree: componentTree(
+ styles.root,
+ { parts, classes: layerClassNames(styles), texts: texts.bound },
+ bindings
+ ),
model,
disabled,
- props
+ props,
+ texts: texts.texts
}
}
diff --git a/packages/dom-css/src/export/components/react.ts b/packages/dom-css/src/export/components/react.ts
index de3c3c2ff..11911a7bf 100644
--- a/packages/dom-css/src/export/components/react.ts
+++ b/packages/dom-css/src/export/components/react.ts
@@ -59,6 +59,7 @@ const DISABLED_FLAG = es.parseExpression('props.disabled || undefined')
function element(node: ComponentNode, kind: GeneratedKind, depth: number): es.SyntaxNode {
if (node.type === 'text') return jsx.text(node.value)
+ if (node.type === 'textProp') return jsx.container(es.identifier(node.name))
const radix = RADIX[kind]
const part = node.part ? radix?.parts[node.part] : undefined
const root = node.part === 'root'
@@ -89,7 +90,7 @@ function element(node: ComponentNode, kind: GeneratedKind, depth: number): es.Sy
return []
})
]
- const inline = node.children.length === 1 && node.children[0]?.type === 'text'
+ const inline = node.children.length === 1 && node.children[0]?.type !== 'element'
return jsx.element(
tagOf(node, kind),
attributes,
@@ -125,25 +126,38 @@ function propsType(component: ComponentModel): es.SyntaxNode {
}
})
: es.parseType("ComponentProps<'button'>")
- if (component.props.length === 0) return base
+ if (component.props.length === 0 && component.texts.length === 0) return base
return {
type: 'TSIntersectionType',
types: [
base,
- es.objectType(
- component.props.map((prop) => [prop.name, es.stringUnionType(prop.options), true])
- )
+ es.objectType([
+ ...component.props.map((prop): [string, es.SyntaxNode, boolean] => [
+ prop.name,
+ es.stringUnionType(prop.options),
+ true
+ ]),
+ ...component.texts.map((text): [string, es.SyntaxNode, boolean] => [
+ text.name,
+ es.parseType('string'),
+ true
+ ])
+ ])
]
}
}
-/** `{ size = 'Small', ...props }`: variant props with their defaults, the rest passed on. */
+/**
+ * `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,
+ * kept off the root, and the rest passed on.
+ */
function parameters(component: ComponentModel): es.SyntaxNode {
- if (component.props.length === 0) return es.identifier('props')
+ const own = [...component.props, ...component.texts]
+ if (own.length === 0) return es.identifier('props')
return {
type: 'ObjectPattern',
properties: [
- ...component.props.map((prop) => ({
+ ...own.map((prop) => ({
type: 'Property',
kind: 'init',
key: es.identifier(prop.name),
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index 76f62f395..07f7b5f6c 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -56,6 +56,7 @@ function bindingAttributes(
function templateNode(node: ComponentNode, kind: GeneratedKind, used: Set<string>): vue.VueNode {
if (node.type === 'text') return vue.text(node.value)
+ if (node.type === 'textProp') return vue.interpolation(identifier(node.name))
const reka = node.part ? REKA[kind].parts[node.part] : undefined
if (reka) used.add(reka)
const native = node.part === 'root' && !reka
@@ -80,13 +81,15 @@ function propsType(component: ComponentModel): es.SyntaxNode {
true
])
if (component.disabled) members.unshift(['disabled', es.parseType('boolean'), true])
+ for (const text of component.texts) members.push([text.name, es.parseType('string'), true])
return es.objectType(members)
}
function propsDefaults(component: ComponentModel): es.SyntaxNode {
return es.object([
...(component.disabled ? [['disabled', es.parseExpression('false')] as const] : []),
- ...component.props.map((prop) => [prop.name, es.string(prop.default)] as const)
+ ...component.props.map((prop) => [prop.name, es.string(prop.default)] as const),
+ ...component.texts.map((text) => [text.name, es.string(text.default)] as const)
])
}
@@ -110,7 +113,7 @@ function script(component: ComponentModel, used: Set<string>): es.SyntaxNode {
]
: []
const props =
- component.disabled || component.props.length > 0
+ component.disabled || component.props.length > 0 || component.texts.length > 0
? es.fill(PROPS, { $Props: propsType(component), $defaults: propsDefaults(component) }).body
: []
const model = component.model
diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.ts
index 5b5789372..5909efb61 100644
--- a/packages/dom-css/src/export/storybook/component.ts
+++ b/packages/dom-css/src/export/storybook/component.ts
@@ -66,7 +66,8 @@ function restArgs(component: ComponentModel, model: string | null): [string, es.
return [
...(model ? [[model, FALSE] as [string, es.SyntaxNode]] : []),
...(component.disabled ? [['disabled', FALSE] as [string, es.SyntaxNode]] : []),
- ...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, es.string(prop.default)])
+ ...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, es.string(prop.default)]),
+ ...component.texts.map((text): [string, es.SyntaxNode] => [text.name, es.string(text.default)])
]
}
@@ -81,6 +82,10 @@ function argTypes(component: ComponentModel, model: string | null): es.SyntaxNod
['control', es.string('select')],
['options', es.array(prop.options.map(es.string))]
])
+ ]),
+ ...component.texts.map((text): [string, es.SyntaxNode] => [
+ text.name,
+ es.object([['control', es.string('text')]])
])
])
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index 5f7c06000..0040ff0d9 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -137,6 +137,34 @@ export function buttonSet() {
)
}
+/** A button whose label is a text property, drawn by a text layer in every variant. */
+export function labelledButtonSet() {
+ const fixture = componentSet(
+ 'Action',
+ { Interaction: ['Default', 'Hover'] },
+ {
+ ...emptyBehaviour('button'),
+ states: { propertyId: 'interaction', rest: 'Default', hover: 'Hover' }
+ },
+ (graph, variant, { Interaction }) => {
+ graph.updateNode(variant, { fills: Interaction === 'Hover' ? COLORS.hover : COLORS.off })
+ graph.createNode('TEXT', variant, {
+ name: 'Label',
+ text: 'Save',
+ componentPropertyReferences: [{ propertyId: 'label', field: 'TEXT' }]
+ })
+ }
+ )
+ const { graph, set } = fixture
+ graph.updateNode(set.id, {
+ componentPropertyDefinitions: [
+ ...set.componentPropertyDefinitions,
+ { id: 'label', name: 'Label', type: 'TEXT', defaultValue: 'Save' }
+ ]
+ })
+ return { graph, set: graph.getNode(set.id) ?? set }
+}
+
/** A collapsible whose content shows only when open. */
export function collapsibleSet() {
const slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index 7e3197fb1..abae7ce3f 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -3,7 +3,12 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
-import { buttonSet, collapsibleSet, switchSet } from '#dom-css-tests/behaviours/fixtures'
+import {
+ buttonSet,
+ collapsibleSet,
+ labelledButtonSet,
+ switchSet
+} from '#dom-css-tests/behaviours/fixtures'
import { exportStorybook } from '#dom-css/index'
import { createElement, type ComponentType } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
@@ -65,6 +70,16 @@ describe('generated React components', () => {
expect(render(component, { defaultOpen: true })).toMatch(/^<div data-state="open"/)
})
+ test('a text property is a prop the bound layer draws, kept off the root element', async () => {
+ const { component, stories } = await generate(labelledButtonSet())
+ expect(render(component)).toMatch(/>Save</)
+ const sent = render(component, { label: 'Send <now>' })
+ expect(sent).toMatch(/>Send &lt;now&gt;</)
+ expect(sent).not.toContain('label=')
+ const meta = stories.default as { args?: Record<string, unknown> }
+ expect(meta.args).toMatchObject({ label: 'Save' })
+ })
+
test('a button sets its other variant properties as data attributes', async () => {
const { component } = await generate(buttonSet())
const large = render(component, { size: 'Large' })
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index d8fcd7567..b7c0d3d6a 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -3,7 +3,12 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
-import { buttonSet, collapsibleSet, switchSet } from '#dom-css-tests/behaviours/fixtures'
+import {
+ buttonSet,
+ collapsibleSet,
+ labelledButtonSet,
+ switchSet
+} from '#dom-css-tests/behaviours/fixtures'
import { exportStorybook } from '#dom-css/index'
import { createSSRApp, h, type Component } from 'vue'
import { compileScript, parse } from 'vue/compiler-sfc'
@@ -71,6 +76,20 @@ describe('generated Vue components', () => {
expect(content(open)).not.toContain(' hidden ')
})
+ test('a text property is a prop the bound layer draws, the design value by default', async () => {
+ const { component, stories } = await generate(labelledButtonSet())
+ expect(await render(component)).toMatch(/>Save</)
+ const sent = await render(component, { label: 'Send <now>' })
+ expect(sent).toMatch(/>Send &lt;now&gt;</)
+ expect(sent).not.toContain('Save')
+ const meta = stories.default as {
+ args: Record<string, unknown>
+ argTypes: Record<string, unknown>
+ }
+ expect(meta.args).toMatchObject({ label: 'Save' })
+ expect(meta.argTypes).toMatchObject({ label: { control: 'text' } })
+ })
+
test('a button sets its other variant properties as data attributes', async () => {
const { component } = await generate(buttonSet())
const large = await render(component, { size: 'Large' })
diff --git a/packages/emit/src/vue.ts b/packages/emit/src/vue.ts
index 90b05ed24..4b76fca68 100644
--- a/packages/emit/src/vue.ts
+++ b/packages/emit/src/vue.ts
@@ -28,7 +28,13 @@ export interface VueText {
value: string
}
-export type VueNode = VueElement | VueText
+/** `{{ expression }}`, printed from a syntax tree so it holds only what the tree says. */
+export interface VueInterpolation {
+ type: 'interpolation'
+ expression: SyntaxNode
+}
+
+export type VueNode = VueElement | VueText | VueInterpolation
export const attribute = (name: string, value: string): VueAttribute => ({
type: 'static',
@@ -56,6 +62,11 @@ export const element = (
export const text = (value: string): VueText => ({ type: 'text', value })
+export const interpolation = (expression: SyntaxNode): VueInterpolation => ({
+ type: 'interpolation',
+ expression
+})
+
function printAttribute(item: VueAttribute): string {
if (item.type === 'static') return `${item.name}="${escapeAttribute(item.value)}"`
const value = escapeAttribute(printExpression(item.expression))
@@ -66,6 +77,13 @@ function printAttribute(item: VueAttribute): string {
/** Markup with nothing added around it, as text content needs. */
function printInline(node: VueNode): string {
if (node.type === 'text') return templateText(node.value)
+ if (node.type === 'interpolation') {
+ const expression = printExpression(node.expression)
+ // The template ends an interpolation at the first `}}`, wherever it falls.
+ if (expression.includes('}}'))
+ throw new Error(`An interpolated expression cannot contain "}}": ${expression}`)
+ return `{{ ${expression} }}`
+ }
const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')
if (node.children.length === 0) return `<${open} />`
return `<${open}>${node.children.map(printInline).join('')}</${node.tag}>`
@@ -73,9 +91,9 @@ function printInline(node: VueNode): string {
function printNode(node: VueNode, depth: number): string {
const indent = ' '.repeat(depth)
- // Vue renders whitespace between text and elements as a space, so an element with text
- // content keeps its children on its own line, exactly as given.
- if (node.type === 'text' || node.children.some((child) => child.type === 'text'))
+ // Vue renders whitespace between text and elements as a space, so an element with text or
+ // an interpolation in it keeps its children on its own line, exactly as given.
+ if (node.type !== 'element' || node.children.some((child) => child.type !== 'element'))
return `${indent}${printInline(node)}`
const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')
if (node.children.length === 0) return `${indent}<${open} />`
diff --git a/packages/emit/tests/vue.test.ts b/packages/emit/tests/vue.test.ts
index 941b4ff63..1f429c89f 100644
--- a/packages/emit/tests/vue.test.ts
+++ b/packages/emit/tests/vue.test.ts
@@ -21,6 +21,23 @@ describe('Vue templates', () => {
}
)
+ test('interpolate an expression, keeping text beside it as written', async () => {
+ const node = vue.element(
+ 'p',
+ [],
+ [vue.text('Hi, {name} '), vue.interpolation(es.identifier('name'))]
+ )
+ expect(vue.printTemplate(node)).toBe('<p>Hi, &#123;name} {{ name }}</p>')
+ expect(await render(node, { name: '<b>Ada</b>' })).toBe(
+ '<p>Hi, {name} &lt;b&gt;Ada&lt;/b&gt;</p>'
+ )
+ })
+
+ test('refuse an interpolation the template would end early', () => {
+ const node = vue.element('p', [], [vue.interpolation(es.string('}}'))])
+ expect(() => vue.printTemplate(node)).toThrow('}}')
+ })
+
test('keep attribute values with quotes and entities as written', async () => {
const value = 'say "hi" &amp; leave'
const html = await render(vue.element('div', [vue.attribute('title', value)]))