Skip to content

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

feat(storybook): export item words, layer kinds per state, and document titles (#1021)

Danila Poyarkovdea3d492b0f1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a0ca1369..ca4182d5c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -78,7 +78,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, Collapsible, Tabs, Radio group, Toggle group, or Accordion 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, tabs and groups choosing a value named after each tab's or item's label, each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item; inside it, an instance of another generated component uses that component, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; 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, titled by the document and, when several have components, its page, 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, Collapsible, Tabs, Radio group, Toggle group, or Accordion 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, tabs and groups choosing a value named after each tab's or item's label, each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; 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/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.ts
index fd0fc4bde..e2d054298 100644
--- a/packages/cli/src/commands/export/storybook/index.ts
+++ b/packages/cli/src/commands/export/storybook/index.ts
@@ -153,6 +153,8 @@ async function writeStories(
const files = await exportStorybook(graph, {
framework,
pageId,
+ // Titled by the document, so stories of documents exported together stay apart.
+ document: basename(file, extname(file)),
linkPath: linkPath(file),
vectorElement,
renderDesignImage: args['design-images']
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index d74f11c9e..fc54bdb3b 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -158,7 +158,7 @@ Keep each component's design file in the component's folder and export with `--b
Pass several documents, or a quoted glob such as `'src/**/*.pen'` that OpenPencil expands itself (Node.js 22 or later). Several documents need `--beside` or `--output`; `--page` works with one document only. Documents are exported one after another, and when one fails the rest are still exported before the command exits with an error. `--watch` watches every matched document; a document created after the watch started needs another run.
-Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, and `disabled` when the set draws a disabled state; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant.
+Stories are titled by the document's file name, and then the page when more than one page has components: `pricing.fig` gives `pricing/Plan picker`, so documents exported together keep their stories apart. Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, and `disabled` when the set draws a disabled state; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant.
Stories render the component as HTML with inline styles, like `-f html`, so they need no OpenPencil runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families, which Storybook has to load itself. Static stories don't export text, boolean, or instance-swap properties yet.
diff --git a/packages/dom-css/src/behaviours/states/layers.ts b/packages/dom-css/src/behaviours/states/layers.ts
index a8c1a64a3..6ef7ddfc3 100644
--- a/packages/dom-css/src/behaviours/states/layers.ts
+++ b/packages/dom-css/src/behaviours/states/layers.ts
@@ -7,10 +7,12 @@ import { omit } from 'es-toolkit/object'
import {
behaviourOwner,
+ instanceMainComponent,
instanceSlotFrames,
layerPath,
partBinding,
readBehaviour,
+ readIcon,
slotPropertyId,
type SceneGraph,
type SceneNode
@@ -22,6 +24,7 @@ import type { StateElement } from './types'
export interface VariantLayer {
type: 'element'
key: string
+ kind: string | undefined
name: string
element: DesignElement
children: Array<VariantLayer | DesignText>
@@ -35,6 +38,21 @@ function textContent(element: DesignElement): string | null {
return texts.length > 0 ? texts.map((text) => text.text).join('') : null
}
+/**
+ * What a layer draws other than its own box: an instance of a component (of any of its set's
+ * variants), or an icon. Undefined for any other layer.
+ */
+export function layerKind(graph: SceneGraph, node: SceneNode | undefined): string | undefined {
+ if (!node) return undefined
+ if (node.type === 'INSTANCE') {
+ const main = instanceMainComponent(graph, node)
+ const owner = main && behaviourOwner(graph, main)
+ return `instance ${owner?.id ?? ''}`
+ }
+ const icon = readIcon(node)
+ return icon ? `icon ${icon.name}` : undefined
+}
+
function variantLayer(
graph: SceneGraph,
variant: SceneNode,
@@ -46,11 +64,14 @@ function variantLayer(
const source = node.sourceSceneNodeId
const path = source ? layerPath(graph, variant.id, source) : `${parentKey}/~${index}`
const text = textContent(node)
- // A label that reads differently in a variant is a different layer, shown by its state.
- const key = text === null ? path : `${path}\0${text}`
+ const kind = layerKind(graph, node.sourceSceneNode)
+ // A label that reads differently in a variant is a different layer, shown by its state, and
+ // so is a layer drawn as another component or icon, or as one instead of its own box.
+ const key = [path, ...(kind ? [kind] : []), ...(text === null ? [] : [text])].join('\0')
return {
type: 'element',
key,
+ kind,
name: node.sourceSceneNode?.name ?? node.tagName,
element: node,
children: node.children.map((child, i) => variantLayer(graph, variant, child, key, i))
@@ -93,6 +114,7 @@ export function projectVariant(
return {
type: 'element',
key: '',
+ kind: undefined,
name: variant.name,
element: root,
children: root.children.map((child, i) => variantLayer(graph, variant, child, '', i))
@@ -114,6 +136,7 @@ export function stateElement(layer: VariantLayer): StateElement {
return {
type: 'element',
key: layer.key,
+ kind: layer.kind,
name: layer.name,
tagName: layer.element.tagName,
attrs: { ...layer.element.attrs },
diff --git a/packages/dom-css/src/behaviours/states/types.ts b/packages/dom-css/src/behaviours/states/types.ts
index 6b7b9c146..9cd63b24d 100644
--- a/packages/dom-css/src/behaviours/states/types.ts
+++ b/packages/dom-css/src/behaviours/states/types.ts
@@ -27,6 +27,8 @@ export interface StateElement {
type: 'element'
/** The layer path below the variant, with the text when variants label a layer differently. */
key: string
+ /** What the layer draws other than its own box, such as an instance or an icon (`layerKind`). */
+ kind: string | undefined
/** The layer's name, for class names. */
name: string
tagName: string
diff --git a/packages/dom-css/src/export/components/groups.ts b/packages/dom-css/src/export/components/groups.ts
index 1719bae6c..e398abdc6 100644
--- a/packages/dom-css/src/export/components/groups.ts
+++ b/packages/dom-css/src/export/components/groups.ts
@@ -9,7 +9,7 @@ import {
} from '@open-pencil/scene-graph'
import type { ComponentModel } from './model'
-import { placementOnly, referenceValues, type UsedLayer } from './references'
+import { placementOnly, referenceValues, shownText, type UsedLayer } from './references'
import { slugValues, textOf, type ChoiceModel } from './repeats'
/** Groups whose items are their own primitive inside the group, as Reka and Radix have them. */
@@ -57,8 +57,8 @@ export function groupItems(
const label = item.texts.at(0)
const values = slugValues(
elements.map((element, index) => {
- const assigned = label && instances[index]?.node.componentPropertyAssignments[label.id]
- return typeof assigned === 'string' ? assigned : textOf(element)
+ const node = instances[index]?.node
+ return (label && node && shownText(graph, node, label.id)) || textOf(element)
})
)
const used = new Map<StateElement, UsedLayer>()
diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.ts
index c2a2d4519..e2f6fbb8a 100644
--- a/packages/dom-css/src/export/components/references.ts
+++ b/packages/dom-css/src/export/components/references.ts
@@ -1,8 +1,10 @@
+import { layerKind } from '#dom-css/behaviours/states/layers'
import type { StateElement } from '#dom-css/behaviours/states/types'
import type { DesignStyleDeclaration } from '#dom-css/types'
import { isEmptyObject } from 'es-toolkit/predicate'
import {
+ findComponentPropertyTargets,
findLayerByPath,
instanceMainComponent,
isIconModified,
@@ -52,9 +54,18 @@ const PLACEMENT =
/** Whether a declaration places a layer rather than drawing it. */
export const isPlacement = (property: string) => PLACEMENT.test(property)
+/** Whether a declaration hides or shows a layer by state, which the parent decides too. */
+const isVisibility = (property: string, value: string) =>
+ property === 'display' && (value === 'none' || value === 'revert')
+
+/** Keeps only where the parent places a layer, and whether a state shows it. */
export function placementOnly(element: StateElement): void {
const placement = (style: DesignStyleDeclaration): DesignStyleDeclaration =>
- Object.fromEntries(Object.entries(style).filter(([property]) => isPlacement(property)))
+ Object.fromEntries(
+ Object.entries(style).filter(
+ ([property, value]) => isPlacement(property) || isVisibility(property, value)
+ )
+ )
element.base = placement(element.base)
element.rules = element.rules
.map((rule) => ({ ...rule, style: placement(rule.style) }))
@@ -70,6 +81,22 @@ function ownerId(graph: SceneGraph, component: SceneNode): string {
return parent?.type === 'COMPONENT_SET' ? parent.id : component.id
}
+/**
+ * The words an instance shows for a text property: what its bound text layer reads, which an
+ * assignment or a direct edit sets, else the assignment itself.
+ */
+export function shownText(
+ graph: SceneGraph,
+ instance: SceneNode,
+ propertyId: string
+): string | undefined {
+ const target = findComponentPropertyTargets(graph, instance, propertyId).find(
+ (item) => item.field === 'TEXT' && item.node.type === 'TEXT'
+ )
+ const assigned = instance.componentPropertyAssignments[propertyId]
+ return target?.node.text ?? (typeof assigned === 'string' ? assigned : undefined)
+}
+
/**
* What `instance` sets on `component`: the values it is drawn with that differ from defaults,
* and whether it is drawn on: its model, or for a group's item the value that marks it chosen.
@@ -97,8 +124,8 @@ export function referenceValues(
props.push({ name: prop.name, value })
}
for (const text of component.texts) {
- const value = instance.componentPropertyAssignments[text.id]
- if (typeof value === 'string' && value !== text.default) props.push({ name: text.name, value })
+ const value = shownText(graph, instance, text.id)
+ if (value !== undefined && value !== text.default) props.push({ name: text.name, value })
}
return { props, model }
}
@@ -108,7 +135,8 @@ export type UsedLayer = Omit<ComponentReference, 'className'> | Omit<IconReferen
/**
* What the layer at `element` uses in place of drawing itself, if anything, read from the first
- * variant that draws it: the rest state, or the one that shows it, such as open content.
+ * variant that draws it as that element: the rest state, or the one that shows it, such as open
+ * content.
*/
function usedLayer(
graph: SceneGraph,
@@ -117,9 +145,10 @@ function usedLayer(
references: ComponentReferences
): UsedLayer | null {
const path = element.key.split('\0')[0] ?? ''
+ // The variant's layer at that path drawn as this element is: a frame, or that instance or icon.
const node = variantIds
.map((id) => findLayerByPath(graph, id, path))
- .find((found) => found !== undefined)
+ .find((found) => found !== undefined && layerKind(graph, found) === element.kind)
if (!node) return null
const main = node.type === 'INSTANCE' ? instanceMainComponent(graph, node) : undefined
const component = main ? references.get(ownerId(graph, main)) : undefined
diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.ts
index c48ade5fe..fd964c399 100644
--- a/packages/dom-css/src/export/storybook/export.ts
+++ b/packages/dom-css/src/export/storybook/export.ts
@@ -29,6 +29,11 @@ export interface ExportStorybookOptions {
framework?: StorybookFramework
/** Limit the export to one page. Defaults to every page. */
pageId?: string
+ /**
+ * The document's name, which titles its stories, such as `Pricing/Plan picker`, with each
+ * page's name between when it has several. Without it, stories are titled by page.
+ */
+ document?: string
/** Repository-relative `.fig`/`.pen` path; adds an `openpencil://` design link to stories. */
linkPath?: string
/** Renders a variant to PNG; each story then shows it next to the link as its design. */
@@ -126,12 +131,23 @@ interface StoryEntry {
* Every group's story file, with names claimed on every page so a one-page export picks the
* same names as a full one, kept for the pages the export covers.
*/
-function storyEntries(graph: SceneGraph, pageId: string | undefined): StoryEntry[] {
+function storyEntries(
+ graph: SceneGraph,
+ pageId: string | undefined,
+ document: string | undefined
+): StoryEntry[] {
const takenFiles = new Set<string>()
const takenIds = new Set<string>()
const entries: StoryEntry[] = []
- for (const page of graph.getPages()) {
- for (const group of collectGroups(graph, page)) {
+ const pages = graph.getPages()
+ // Pages without components, such as an empty first page, add no level to the titles.
+ const storied = pages.filter((page) => collectGroups(graph, page).length > 0)
+ const section = (page: SceneNode) => {
+ if (document === undefined) return page.name
+ return storied.length > 1 ? `${document}/${page.name}` : document
+ }
+ for (const page of pages) {
+ for (const group of collectGroups(graph, page, section(page))) {
// Storybook ids ignore case and punctuation, so `Library/Card` and `library/card` collide.
group.title = claimName(group.title, takenIds, { separator: ' ', key: storyId })
// File names are compared ignoring case for case-insensitive file systems.
@@ -197,7 +213,7 @@ export async function exportStorybook(
const add = (page: SceneNode, path: string, content: string | Uint8Array) =>
files.push({ path, content, page: page.name })
- const entries = storyEntries(graph, options.pageId)
+ const entries = storyEntries(graph, options.pageId, options.document)
const generate = GENERATORS[framework]
const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index a71b9f08e..c626356b2 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -47,7 +47,12 @@ function distinctVariants(group: StoryGroup): StoryGroup {
}
}
-function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode): StoryGroup {
+function componentSetGroup(
+ graph: SceneGraph,
+ page: SceneNode,
+ section: string,
+ set: SceneNode
+): StoryGroup {
const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')
const variants = graph
.getChildren(set.id)
@@ -74,7 +79,7 @@ function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode):
})
return distinctVariants({
page,
- title: `${page.name}/${set.name}`,
+ title: `${section}/${set.name}`,
name: set.name,
props,
variants,
@@ -83,10 +88,10 @@ function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode):
})
}
-function componentGroup(page: SceneNode, component: SceneNode): StoryGroup {
+function componentGroup(page: SceneNode, section: string, component: SceneNode): StoryGroup {
return {
page,
- title: `${page.name}/${component.name}`,
+ title: `${section}/${component.name}`,
name: component.name,
props: [],
variants: [{ values: [], node: component }],
@@ -97,9 +102,14 @@ function componentGroup(page: SceneNode, component: SceneNode): StoryGroup {
}
/** `Button/Primary`, `Button/Secondary` → one `Button` group with a derived variant property. */
-function slashGroups(page: SceneNode, prefix: string, components: SceneNode[]): StoryGroup[] {
+function slashGroups(
+ page: SceneNode,
+ section: string,
+ prefix: string,
+ components: SceneNode[]
+): StoryGroup[] {
const derived = deriveSlashVariantProperties(components, () => '')
- if (!derived) return components.map((component) => componentGroup(page, component))
+ if (!derived) return components.map((component) => componentGroup(page, section, component))
const props = derived.definitions.map((def) => ({
name: def.name,
options: def.variantOptions ?? []
@@ -108,32 +118,38 @@ function slashGroups(page: SceneNode, prefix: string, components: SceneNode[]):
const values = derived.variants.get(component.id)?.componentPropertyValues ?? {}
return { values: props.map((prop) => values[prop.name] ?? ''), node: component }
})
- return [
- distinctVariants({ page, title: `${page.name}/${prefix}`, name: prefix, props, variants })
- ]
+ return [distinctVariants({ page, title: `${section}/${prefix}`, name: prefix, props, variants })]
}
-/** The story files a page produces, in layer order. Instances are never exported. */
-export function collectGroups(graph: SceneGraph, page: SceneNode): StoryGroup[] {
+/**
+ * The story files a page produces, in layer order, titled under `section`, the page's name by
+ * default. Instances are never exported.
+ */
+export function collectGroups(
+ graph: SceneGraph,
+ page: SceneNode,
+ section = page.name
+): StoryGroup[] {
const groups: StoryGroup[] = []
const slashed = new Map<string, SceneNode[]>()
const visit = (node: SceneNode) => {
if (!isExported(node) || node.type === 'INSTANCE') return
if (node.type === 'COMPONENT_SET') {
- const group = componentSetGroup(graph, page, node)
+ const group = componentSetGroup(graph, page, section, node)
if (group.variants.length > 0) groups.push(group)
return
}
if (node.type === 'COMPONENT') {
const [prefix, ...rest] = node.name.split('/')
const name = prefix.trim()
- if (rest.length === 0 || !name) groups.push(componentGroup(page, node))
+ if (rest.length === 0 || !name) groups.push(componentGroup(page, section, node))
else slashed.set(name, [...(slashed.get(name) ?? []), node])
return
}
for (const child of graph.getChildren(node.id)) visit(child)
}
for (const child of graph.getChildren(page.id)) visit(child)
- for (const [prefix, components] of slashed) groups.push(...slashGroups(page, prefix, components))
+ for (const [prefix, components] of slashed)
+ groups.push(...slashGroups(page, section, prefix, components))
return groups
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index 085bd4a08..1ec606076 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -225,6 +225,41 @@ export function settingsSectionSet() {
return { graph, set: section.set, switchSet: toggle.set }
}
+/**
+ * A toggle that draws a plain badge while off and, at the same place and name, the switch drawn
+ * on while pressed, with the switch's own set in the same document.
+ */
+export function badgeToggleSet() {
+ const graph = new SceneGraph()
+ const toggle = switchSet(graph)
+ const on = graph
+ .getChildren(toggle.set.id)
+ .find((variant) => variant.name === 'State=On, Interaction=Default')
+ if (!on) throw new Error('Expected the switch drawn on')
+ const alert = componentSet(
+ 'Alert',
+ { Pressed: ['No', 'Yes'] },
+ {
+ ...emptyBehaviour('toggle'),
+ booleans: { value: { propertyId: 'pressed', on: 'Yes', off: 'No' } }
+ },
+ (graph, variant, { Pressed }) => {
+ graph.updateNode(variant, { width: 80, height: 30 })
+ if (Pressed === 'Yes') graph.createInstance(on.id, variant, { name: 'Badge' })
+ else
+ graph.createNode('FRAME', variant, {
+ name: 'Badge',
+ width: 20,
+ height: 20,
+ fills: COLORS.off
+ })
+ },
+ undefined,
+ graph
+ )
+ return { graph, set: alert.set }
+}
+
/**
* Tabs as a standalone component, as design JSX's `Tabs.Root` builds them: a list of triggers
* and a panel per trigger, each labelled.
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index 5d1fec289..b85b78f5f 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path'
import {
accordionComponent,
+ badgeToggleSet,
buttonSet,
collapsibleSet,
labelledButtonSet,
@@ -160,6 +161,16 @@ describe('generated React components', () => {
expect(second?.active).toEqual(first?.active)
})
+ test('a layer drawn as a frame in one state and an instance in another is both', async () => {
+ const { files, component } = await generate(badgeToggleSet())
+ const css = cssRules(String(files.find((file) => file.path === 'Alert.module.css')?.content))
+ // The pressed state uses the generated switch where the resting one draws its own badge.
+ expect(render(component)).toContain('role="switch"')
+ expect(css.get('.alert .alert__badge')?.display).toBe('none')
+ expect(css.get('.alert[data-state="on"] .alert__badge')).toEqual({ display: 'revert' })
+ expect(css.get('.alert[data-state="on"] .alert__badge-2')).toEqual({ display: 'none' })
+ })
+
test('a radio group writes an item component and chooses among its labelled items', async () => {
const { files, component } = await generate(radioGroupComponent())
expect(files.map((file) => file.path)).toContain('PlanItem.tsx')
diff --git a/packages/dom-css/tests/export/components/repeats.test.ts b/packages/dom-css/tests/export/components/repeats.test.ts
index 98a8cae1e..8b42fd8fe 100644
--- a/packages/dom-css/tests/export/components/repeats.test.ts
+++ b/packages/dom-css/tests/export/components/repeats.test.ts
@@ -9,7 +9,17 @@ function layer(
base: DesignStyleDeclaration,
children: StateElement[] = []
): StateElement {
- return { type: 'element', key: name, name, tagName: 'div', attrs: {}, base, rules: [], children }
+ return {
+ type: 'element',
+ key: name,
+ kind: undefined,
+ name,
+ tagName: 'div',
+ attrs: {},
+ base,
+ rules: [],
+ children
+ }
}
/** A trigger with an icon and a label in `order`. */
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index 64f3c5f98..6d12d8042 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -135,6 +135,24 @@ describe('generated Vue components', () => {
expect(checked(await render(component, { value: 'team' }))).toEqual([false, false, true])
})
+ test('an item edited directly shows its own words and is chosen by them', async () => {
+ const fixture = radioGroupComponent()
+ const { graph } = fixture
+ const [items] = graph.getChildren(fixture.set.id)
+ const last = graph.getChildren(items?.id ?? '').at(-1)
+ const label = graph.getChildren(last?.id ?? '').find((layer) => layer.type === 'TEXT')
+ if (!label) throw new Error('Expected the item to show its label')
+ graph.updateNode(label.id, { text: 'Enterprise' })
+
+ const { component } = await generate(fixture)
+ const html = await render(component, { value: 'enterprise' })
+ expect(html).toContain('Enterprise')
+ expect(html).not.toContain('Team')
+ expect(html).toMatch(
+ /<button[^>]*aria-checked="true"[^>]*value="enterprise"|value="enterprise"[^>]*aria-checked="true"/
+ )
+ })
+
test("a group's item component is named apart from another component's file", async () => {
const fixture = radioGroupComponent()
const page = fixture.graph.getPages()[0].id
diff --git a/packages/dom-css/tests/export/storybook/export.test.ts b/packages/dom-css/tests/export/storybook/export.test.ts
index ebe800719..d22e1a51d 100644
--- a/packages/dom-css/tests/export/storybook/export.test.ts
+++ b/packages/dom-css/tests/export/storybook/export.test.ts
@@ -230,6 +230,23 @@ describe('exportStorybook', () => {
expect(link?.url).toEndWith('node=Button')
})
+ it('titles stories by the document, and by page when several have components', async () => {
+ const { graph } = buttonGraph()
+ const title = async (files: { content: string | Uint8Array }[], index = 0) =>
+ (await importStory(String(files[index]?.content))).default.title
+ expect(await title(await exportStorybook(graph, { framework: 'html', document: 'Kit' }))).toBe(
+ 'Kit/Button'
+ )
+
+ const forms = graph.addPage('Forms')
+ graph.createNode('COMPONENT', forms.id, { name: 'Input', width: 10, height: 10 })
+ const files = await exportStorybook(graph, { framework: 'html', document: 'Kit' })
+ expect([await title(files, 0), await title(files, 1)]).toEqual([
+ 'Kit/Library/Button',
+ 'Kit/Forms/Input'
+ ])
+ })
+
it('gives same-named components on a page distinct titles', async () => {
const graph = new SceneGraph()
const page = graph.addPage('Library')
diff --git a/tests/engine/cli/export/storybook.test.ts b/tests/engine/cli/export/storybook.test.ts
index aafb384f3..821a29945 100644
--- a/tests/engine/cli/export/storybook.test.ts
+++ b/tests/engine/cli/export/storybook.test.ts
@@ -52,7 +52,8 @@ test('export CLI writes Storybook stories with design images', async () => {
expect(stdout).toContain('Exported 1 story files')
const story = await Bun.file(join(output, 'Badge.stories.ts')).text()
expect(story).toContain("from '@storybook/vue3-vite'")
- expect(story).toContain("title: 'Library/Badge'")
+ // Titled by the document's file name; its one page with components adds no level.
+ expect(story).toContain("title: 'library/Badge'")
const manifest: unknown = JSON.parse(await Bun.file(join(output, MANIFEST)).text())
expect(manifest).toEqual({
version: 1,