AI-native design editor. Open-source Figma alternative.
feat(storybook): use generated components and Iconify icons inside generated components (#1004)
Danila Poyarkovcb764955ba30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 607810fc9..febdf4495 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 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 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; 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 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/bun.lock b/bun.lockindex 1403c08e8..d033020f5 100644--- a/bun.lock+++ b/bun.lock@@ -306,6 +306,8 @@"twirlwind": "^0.4.0",},"devDependencies": {+ "@iconify/react": "^6.0.2",+ "@iconify/vue": "^5.0.1","@types/bun": "^1.3.14","@types/css-tree": "^3.2.0","@types/cssesc": "^3.0.2",@@ -1248,6 +1250,8 @@"@iconify-json/simple-icons": ["@iconify-json/[email protected]", "", { "dependencies": { "@iconify/types": "*" } }, "sha512-/XhANjfGYOuqvSR3TmUnkQkINvQ4GVjVuukvymRbxtVFBvIq/yiXJqCDycKcQPT401OYT9H2vIY6ihAlz1QIAw=="],+ "@iconify/react": ["@iconify/[email protected]", "", { "dependencies": { "@iconify/types": "^2.0.0" }, "peerDependencies": { "react": ">=16" } }, "sha512-SMmC2sactfpJD427WJEDN6PMyznTFMhByK9yLW0gOTtnjzzbsi/Ke/XqsumsavFPwNiXs8jSiYeZTmLCLwO+Fg=="],+"@iconify/types": ["@iconify/[email protected]", "", {}, "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg=="],"@iconify/utils": ["@iconify/[email protected]", "", { "dependencies": { "@antfu/install-pkg": "^1.1.0", "@iconify/types": "^2.0.0", "import-meta-resolve": "^4.2.0" } }, "sha512-b1S7B1k9ohZ+iNTi2ATxbRYG9fTrJmUT0rc46bvVnNxqNRGW7dyo/vRREwyniI5IRN2RSJHDcm+s3BjWrSAjHw=="],diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex f70c71d97..05322fa9e 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -160,9 +160,13 @@ Pass several documents, or a quoted glob such as `'src/**/*.pen'` that OpenPenciEach 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. Text, boolean, and instance-swap properties are not exported yet.+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.-With `--framework vue` or `--framework react`, a component set whose behaviour is a Button, Switch, Checkbox, Toggle, or Collapsible becomes a real component instead: `<Name>.vue` built on Reka UI, or `<Name>.tsx` with a `<Name>.module.css` built on Radix UI's `radix-ui` package. Its variants are compiled into a stylesheet keyed on the states Reka and Radix set (`data-state`, `data-disabled`, hover, and focus), and every other variant property is a prop the component sets as a `data-*` attribute. In Vue its value is a `v-model` such as `checked` or `open`; in React the component takes the Radix root's props, such as `checked`, `defaultChecked`, and `onCheckedChange`. Its stories render the component, and a play function clicks the control and checks its state, so the Storybook project needs `reka-ui` or `radix-ui` installed.+With `--framework vue` or `--framework react`, a component set whose behaviour is a Button, Switch, Checkbox, Toggle, or Collapsible becomes a real component instead: `<Name>.vue` built on Reka UI, or `<Name>.tsx` with a `<Name>.module.css` built on Radix UI's `radix-ui` package. Its variants are compiled into a stylesheet keyed on the states Reka and Radix set (`data-state`, `data-disabled`, hover, and focus), and every other variant property is a prop the component sets as a `data-*` attribute. In Vue its value is a `v-model` such as `checked` or `open`; in React the component takes the Radix root's props, such as `checked`, `defaultChecked`, and `onCheckedChange`. Its text properties are string props, defaulting to the design's words, which the layers bound to them draw, with a text control in its stories.++Inside a generated component, an instance of another component generated in the same export uses that component rather than drawing its layers: `<Switch>` imported from `./Switch.vue` or `./Switch`, set to the variant, text, and `disabled` values the instance shows. A control the design draws on, such as a checked switch, starts on and stays operable: a local `ref` bound with `v-model` in Vue, `defaultChecked` in React. The parent only places it, so the control keeps its own look and state styles. Instances of components not exported, or exported only as static stories, are drawn as before. An icon placed from a set, unless its paths were edited, is Iconify's component, `<Icon icon="lucide:bell">` from `@iconify/vue` or `@iconify/react`, which loads the icon when shown.++Its stories render the component, and a play function clicks the control and checks its state, so the Storybook project needs `reka-ui` or `radix-ui` installed, and `@iconify/vue` or `@iconify/react` when components hold icons.Stories carry `parameters.design` entries for [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs):diff --git a/packages/dom-css/package.json b/packages/dom-css/package.jsonindex 08aceed9d..45a22e7ac 100644--- a/packages/dom-css/package.json+++ b/packages/dom-css/package.json@@ -72,6 +72,8 @@"@open-pencil/scene-graph": "workspace:*"},"devDependencies": {+ "@iconify/react": "^6.0.2",+ "@iconify/vue": "^5.0.1","@types/bun": "^1.3.14","@types/css-tree": "^3.2.0","@types/cssesc": "^3.0.2",diff --git a/packages/dom-css/src/behaviours/states/model.ts b/packages/dom-css/src/behaviours/states/model.tsindex 577015e0f..9a0fbc872 100644--- a/packages/dom-css/src/behaviours/states/model.ts+++ b/packages/dom-css/src/behaviours/states/model.ts@@ -85,7 +85,7 @@ export function stateStyles(.flatMap((variant) => {const conditions = conditionsOf(variant)const root = conditions && projectVariant(graph, variant, options)- return conditions && root ? [{ conditions, root }] : []+ return conditions && root ? [{ id: variant.id, conditions, root }] : []})const rest = variants.find((variant) => variant.conditions.length === 0)if (!rest) return null@@ -104,5 +104,5 @@ export function stateStyles(}}for (const element of elements) element.rules = pruneCombined(element.rules)- return { name: set.name, root }+ return { name: set.name, restId: rest.id, root }}diff --git a/packages/dom-css/src/behaviours/states/types.ts b/packages/dom-css/src/behaviours/states/types.tsindex 3c60b479e..8ceec4c02 100644--- a/packages/dom-css/src/behaviours/states/types.ts+++ b/packages/dom-css/src/behaviours/states/types.ts@@ -36,5 +36,7 @@ export type StateNode = StateElement | DesignTextexport interface StateStyles {/** The set's name, for the root's class name. */name: string+ /** The variant drawing the rest state, which the merged tree starts from. */+ restId: stringroot: StateElement}diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.tsindex 831d9deba..b843112a2 100644--- a/packages/dom-css/src/export/components/model.ts+++ b/packages/dom-css/src/export/components/model.ts@@ -1,4 +1,4 @@-import { behaviourArgs } from '#dom-css/behaviours/args'+import { behaviourArgs, type BehaviourArgs } from '#dom-css/behaviours/args'import { BUTTON_RESET } from '#dom-css/behaviours/reset'import { allElements } from '#dom-css/behaviours/states/layers'import { stateStyles } from '#dom-css/behaviours/states/model'@@ -20,6 +20,13 @@ import {import type { SceneGraphToDesignOptions } from '../projection'import { claimName, identifierName } from '../storybook/names'+import {+ referencedLayers,+ type ComponentReference,+ type ComponentReferences,+ type IconReference,+ type UsedLayer+} from './references'/** Kinds generated as components so far; the rest keep static stories. */export const GENERATED_KINDS = ['button', 'switch', 'checkbox', 'toggle', 'collapsible'] as const@@ -65,6 +72,8 @@ export interface ComponentElement {export interface TextProp {/** The prop's identifier. */name: string+ /** The text property's id, which instances assign values by. */+ id: string/** The text property's name. */property: stringdefault: string@@ -75,6 +84,8 @@ export type ComponentNode =| { type: 'text'; value: string }/** The value of a text prop, drawn where the design binds a text layer to it. */| { type: 'textProp'; name: string }+ | ComponentReference+ | IconReference/** One component generated from a component set with a behaviour. */export interface ComponentModel {@@ -90,6 +101,8 @@ export interface ComponentModel {disabled: booleanprops: VariantProp[]texts: TextProp[]+ /** The variant properties that draw its booleans and states, which references set. */+ args: BehaviourArgs}interface TreeLabels {@@ -97,6 +110,8 @@ interface TreeLabels {classes: Map<StateElement, string>/** The text prop each bound text layer draws, by layer. */texts: Map<StateElement, string>+ /** Layers that use another component or an icon in place of drawing themselves. */+ used: Map<StateElement, UsedLayer>}function componentTree(@@ -117,13 +132,17 @@ function componentTree(children: text? [{ type: 'textProp', name: text }]: node.children.map((child) =>- child.type === 'text'- ? { type: 'text', value: child.text }- : componentTree(child, labels, [])+ child.type === 'text' ? { type: 'text', value: child.text } : childNode(child, labels))}}+function childNode(element: StateElement, labels: TreeLabels): ComponentNode {+ const used = labels.used.get(element)+ if (!used) return componentTree(element, labels, [])+ return { ...used, className: labels.classes.get(element) ?? '' }+}+/*** 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.@@ -137,6 +156,7 @@ function textProps(const definitions = behaviourProperties(graph, set).filter((item) => item.type === 'TEXT')const texts = definitions.map((definition) => ({name: claimName(camelCase(identifierName(definition.name, 'Text')), taken),+ id: definition.id,property: definition.name,default: definition.defaultValue}))@@ -201,10 +221,18 @@ function partPaths(graph: SceneGraph, set: SceneNode, behaviour: Behaviour): Map* The component a set with a behaviour generates, or `null` when its kind is not generated* yet or its variants have no rest state to start from.*/+export interface ComponentModelOptions extends Pick<SceneGraphToDesignOptions, 'vectorElement'> {+ /**+ * The other components generated alongside, which instances of them use rather than+ * drawing their layers.+ */+ references?: ComponentReferences+}+export function componentModel(graph: SceneGraph,set: SceneNode,- options: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}+ options: ComponentModelOptions = {}): ComponentModel | null {const behaviour = readBehaviour(set)if (!behaviour || !isGenerated(behaviour.kind)) return null@@ -246,6 +274,14 @@ export function componentModel(attribute: propAttribute(prop.property)}))]+ const used = options.references+ ? referencedLayers(+ graph,+ styles.root,+ [styles.restId, ...graph.getChildren(set.id).map((variant) => variant.id)],+ options.references+ )+ : new Map<StateElement, UsedLayer>()const texts = textProps(graph, set, allElements(styles.root), taken)return {name: identifierName(set.name, 'Component'),@@ -253,12 +289,13 @@ export function componentModel(styles,tree: componentTree(styles.root,- { parts, classes: layerClassNames(styles), texts: texts.bound },+ { parts, classes: layerClassNames(styles), texts: texts.bound, used },bindings),model,disabled,props,- texts: texts.texts+ texts: texts.texts,+ args}}diff --git a/packages/dom-css/src/export/components/react.ts b/packages/dom-css/src/export/components/react.tsindex 11911a7bf..834f36c09 100644--- a/packages/dom-css/src/export/components/react.ts+++ b/packages/dom-css/src/export/components/react.ts@@ -1,6 +1,7 @@import { stateStylesToCSS } from '#dom-css/behaviours/states/css'import dedent from 'dedent'import { omit } from 'es-toolkit/object'+import { upperFirst } from 'es-toolkit/string'import { es, jsx } from '@open-pencil/emit'@@ -11,6 +12,7 @@ import type {ComponentNode,GeneratedKind} from './model'+import type { ComponentReference } from './references'/*** The Radix primitive a kind renders, from the unified `radix-ui` package, and the component@@ -57,9 +59,53 @@ function tagOf(node: ComponentElement, kind: GeneratedKind): string {/** `props.disabled || undefined`, so a native button sets `data-disabled` only while disabled. */const DISABLED_FLAG = es.parseExpression('props.disabled || undefined')-function element(node: ComponentNode, kind: GeneratedKind, depth: number): es.SyntaxNode {+/** What a component's markup uses, which its module imports. */+interface MarkupUses {+ kind: GeneratedKind+ /** Other generated components. */+ components: Set<string>+ icons: boolean+}++/** The Iconify component, named apart from any component the design calls `Icon`. */+const ICONIFY = 'IconifyIcon'++/** `defaultChecked`: Radix's uncontrolled value, which a nested control starts from. */+const defaultOf = (model: string) => `default${upperFirst(model)}`++function reference(node: ComponentReference, uses: MarkupUses, depth: number): es.SyntaxNode {+ uses.components.add(node.component)+ return jsx.element(+ node.component,+ [+ jsx.attribute('className', jsx.container(moduleClass(node.className))),+ ...node.props.map((prop) =>+ jsx.attribute(prop.name, prop.value === true ? null : jsx.stringValue(prop.value))+ ),+ ...(node.model ? [jsx.attribute(defaultOf(node.model), null)] : [])+ ],+ [],+ depth+ )+}++function element(node: ComponentNode, uses: MarkupUses, depth: number): es.SyntaxNode {if (node.type === 'text') return jsx.text(node.value)if (node.type === 'textProp') return jsx.container(es.identifier(node.name))+ if (node.type === 'reference') return reference(node, uses, depth)+ if (node.type === 'icon') {+ uses.icons = true+ return jsx.element(+ ICONIFY,+ [+ jsx.attribute('icon', jsx.stringValue(node.icon)),+ jsx.attribute('className', jsx.container(moduleClass(node.className)))+ ],+ [],+ depth+ )+ }+ const kind = uses.kindconst radix = RADIX[kind]const part = node.part ? radix?.parts[node.part] : undefinedconst root = node.part === 'root'@@ -90,11 +136,14 @@ function element(node: ComponentNode, kind: GeneratedKind, depth: number): es.Syreturn []})]- const inline = node.children.length === 1 && node.children[0]?.type !== 'element'+ // Words alone stay on the element's line, where a line break would add a space.+ const inline =+ node.children.length === 1 &&+ (node.children[0]?.type === 'text' || node.children[0]?.type === 'textProp')return jsx.element(tagOf(node, kind),attributes,- node.children.map((child) => element(child, kind, depth + 1)),+ node.children.map((child) => element(child, uses, depth + 1)),depth,inline)@@ -113,6 +162,8 @@ const MODULE = es.parseModule(dedent``)const RADIX_IMPORT = es.parseModule(`import { $Namespace as $Primitive } from 'radix-ui'`)+const ICONIFY_IMPORT = es.parseModule(`import { Icon as ${ICONIFY} } from '@iconify/react'`).body+const IMPORT_COMPONENT = es.parseModule(`import { $Component } from '$path'`)/** The root's own props, extended with the component's variant props when it has any. */function propsType(component: ComponentModel): es.SyntaxNode {@@ -183,19 +234,31 @@ function parameters(component: ComponentModel): es.SyntaxNode {export const reactComponent: ComponentGenerator = async (component) => {const radix = RADIX[component.kind]const stylesPath = `${component.name}.module.css`- const imports = radix- ? es.fill(RADIX_IMPORT, {- $Namespace: es.identifier(radix.namespace),- $Primitive: es.identifier(PRIMITIVE(radix.namespace))- }).body- : []+ const uses: MarkupUses = { kind: component.kind, components: new Set(), icons: false }+ const body = element(component.tree, uses, 1)+ const imports = [+ ...(uses.icons ? ICONIFY_IMPORT : []),+ ...(radix+ ? es.fill(RADIX_IMPORT, {+ $Namespace: es.identifier(radix.namespace),+ $Primitive: es.identifier(PRIMITIVE(radix.namespace))+ }).body+ : []),+ ...[...uses.components].sort().flatMap(+ (name) =>+ es.fill(IMPORT_COMPONENT, {+ $Component: es.identifier(name),+ $path: es.string(`./${name}`)+ }).body+ )+ ]const [typeImport, stylesImport, ...rest] = es.fill(MODULE, {$styles: es.string(`./${stylesPath}`),$Props: es.identifier(`${component.name}Props`),$Type: propsType(component),$Name: es.identifier(component.name),$params: parameters(component),- $body: element(component.tree, component.kind, 1)+ $body: body}).bodyconst program = {type: 'Program',@@ -211,6 +274,6 @@ export const reactComponent: ComponentGenerator = async (component) => {],entry: { path: `./${component.name}`, named: true },// Radix's uncontrolled value, so a story's control and its play function can both change it.- valueArg: model ? `default${model.charAt(0).toUpperCase()}${model.slice(1)}` : null+ valueArg: model ? defaultOf(model) : null}}diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.tsnew file mode 100644index 000000000..5a97d1768--- /dev/null+++ b/packages/dom-css/src/export/components/references.ts@@ -0,0 +1,157 @@+import type { StateElement } from '#dom-css/behaviours/states/types'+import type { DesignStyleDeclaration } from '#dom-css/types'+import { isEmptyObject } from 'es-toolkit/predicate'++import {+ findLayerByPath,+ instanceMainComponent,+ isIconModified,+ readIcon,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++import type { ComponentModel } from './model'++/** A prop a reference sets on the component it uses: a variant or text value, or `disabled`. */+export interface ReferenceProp {+ name: string+ value: string | true+}++/**+ * Another generated component used where the design places an instance of it, with the values+ * the instance shows. Its own layers are the component's, so they are not drawn here.+ */+export interface ComponentReference {+ type: 'reference'+ /** The component's identifier and file name. */+ component: string+ /** The class the parent's state styles place it by. */+ className: string+ props: ReferenceProp[]+ /** The two-way value the instance is drawn with, when it is on. */+ model: string | null+}++/** An icon from a set, drawn by the framework's Iconify component. */+export interface IconReference {+ type: 'icon'+ /** `prefix:name`. */+ icon: string+ className: string+}++/**+ * How a parent places a layer, as opposed to how the layer looks. A component used in place of+ * a layer keeps its own look and state styles; the parent only places it.+ */+const PLACEMENT =+ /^(position|inset|left|top|right|bottom|(min-|max-)?(width|height)|margin(-.+)?|flex(-.+)?|align-self|justify-self|order|grid-(area|column|row)(-.+)?|transform(-origin)?|rotate|translate|scale|z-index)$/++function placementOnly(element: StateElement): void {+ const placement = (style: DesignStyleDeclaration): DesignStyleDeclaration =>+ Object.fromEntries(Object.entries(style).filter(([property]) => PLACEMENT.test(property)))+ element.base = placement(element.base)+ element.rules = element.rules+ .map((rule) => ({ ...rule, style: placement(rule.style) }))+ .filter((rule) => !isEmptyObject(rule.style))+}++/** Generated components by the id of the set they come from, which instances refer to. */+export type ComponentReferences = ReadonlyMap<string, ComponentModel>++/** The set a component belongs to, or the component itself when it stands alone. */+function ownerId(graph: SceneGraph, component: SceneNode): string {+ const parent = component.parentId ? graph.getNode(component.parentId) : undefined+ return parent?.type === 'COMPONENT_SET' ? parent.id : component.id+}++/** What `instance` sets on `component`: the values it is drawn with that differ from defaults. */+function referenceValues(+ graph: SceneGraph,+ instance: SceneNode,+ component: ComponentModel+): Pick<ComponentReference, 'props' | 'model'> {+ const values = instanceMainComponent(graph, instance)?.componentPropertyValues ?? {}+ const props: ReferenceProp[] = []+ let model: string | null = null+ for (const [property, arg] of component.args.booleans) {+ if (values[property] !== arg.on) continue+ if (arg.name === component.model) model = arg.name+ else props.push({ name: arg.name, value: true })+ }+ const states = component.args.states+ if (states?.disabled && values[states.property] === states.disabled)+ props.push({ name: 'disabled', value: true })+ for (const prop of component.props) {+ const value = values[prop.property]+ if (Object.hasOwn(values, prop.property) && value !== prop.default)+ 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 })+ }+ return { props, model }+}++/** A used layer, before the parent's class name for it is known. */+export type UsedLayer = Omit<ComponentReference, 'className'> | Omit<IconReference, 'className'>++/**+ * 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.+ */+function usedLayer(+ graph: SceneGraph,+ variantIds: readonly string[],+ element: StateElement,+ references: ComponentReferences+): UsedLayer | null {+ const path = element.key.split('\0')[0] ?? ''+ const node = variantIds+ .map((id) => findLayerByPath(graph, id, path))+ .find((found) => found !== undefined)+ if (!node) return null+ const main = node.type === 'INSTANCE' ? instanceMainComponent(graph, node) : undefined+ const component = main ? references.get(ownerId(graph, main)) : undefined+ if (component)+ return {+ type: 'reference',+ component: component.name,+ ...referenceValues(graph, node, component)+ }+ const icon = readIcon(node)+ return icon && !isIconModified(graph, node) ? { type: 'icon', icon: icon.name } : null+}++/**+ * The layers of a set's merged markup that are used rather than drawn: instances of other+ * generated components, and icons from a set, read from the variants in order, the rest state+ * first. Their own layers are dropped from the markup and the styles, which belong to the+ * component or the icon.+ */+export function referencedLayers(+ graph: SceneGraph,+ root: StateElement,+ variantIds: readonly string[],+ references: ComponentReferences+): Map<StateElement, UsedLayer> {+ const used = new Map<StateElement, UsedLayer>()+ const visit = (element: StateElement) => {+ for (const child of element.children) {+ if (child.type !== 'element') continue+ const layer = usedLayer(graph, variantIds, child, references)+ if (!layer) {+ visit(child)+ continue+ }+ used.set(child, layer)+ child.children = []+ if (layer.type === 'reference') placementOnly(child)+ }+ }+ visit(root)+ return used+}diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.tsindex 07f7b5f6c..2faa0f780 100644--- a/packages/dom-css/src/export/components/vue.ts+++ b/packages/dom-css/src/export/components/vue.ts@@ -1,9 +1,11 @@import { stateStylesToCSS } from '#dom-css/behaviours/states/css'import { compact } from 'es-toolkit/array'import { omit } from 'es-toolkit/object'+import { camelCase, upperFirst } from 'es-toolkit/string'import { es, vue } from '@open-pencil/emit'+import { claimName } from '../storybook/names'import type {ComponentBinding,ComponentGenerator,@@ -11,6 +13,7 @@ import type {ComponentNode,GeneratedKind} from './model'+import type { ComponentReference } from './references'/** The Reka UI components a kind renders, by part, and the prop its model binds. */const REKA: Record<@@ -54,11 +57,52 @@ function bindingAttributes(]}-function templateNode(node: ComponentNode, kind: GeneratedKind, used: Set<string>): vue.VueNode {+/** What a template uses, which its script imports and declares. */+interface TemplateUses {+ kind: GeneratedKind+ /** Reka components. */+ reka: Set<string>+ /** Other generated components. */+ components: Set<string>+ icons: boolean+ /** A ref per nested control drawn on, which its `v-model` binds. */+ models: { name: string }[]+ taken: Set<string>+}++/** The Iconify component, named apart from any component the design calls `Icon`. */+const ICONIFY = 'IconifyIcon'+const TRUE = es.parseExpression('true')++function reference(node: ComponentReference, uses: TemplateUses): vue.VueNode {+ uses.components.add(node.component)+ const model = node.model+ ? claimName(`${camelCase(node.component)}${upperFirst(node.model)}`, uses.taken)+ : null+ if (model) uses.models.push({ name: model })+ return vue.element(node.component, [+ vue.attribute('class', node.className),+ ...node.props.map((prop) =>+ prop.value === true ? vue.bound(prop.name, TRUE) : vue.attribute(prop.name, prop.value)+ ),+ // The control stays operable, starting from the value the design draws.+ ...(model && node.model ? [vue.model(identifier(model), node.model)] : [])+ ])+}++function templateNode(node: ComponentNode, uses: TemplateUses): 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)+ if (node.type === 'reference') return reference(node, uses)+ if (node.type === 'icon') {+ uses.icons = true+ return vue.element(ICONIFY, [+ vue.attribute('icon', node.icon),+ vue.attribute('class', node.className)+ ])+ }+ const reka = node.part ? REKA[uses.kind].parts[node.part] : undefined+ if (reka) uses.reka.add(reka)const native = node.part === 'root' && !rekareturn vue.element(reka ?? (native ? 'button' : node.tag),@@ -68,9 +112,9 @@ function templateNode(node: ComponentNode, kind: GeneratedKind, used: Set<stringvue.attribute(name, value)),vue.attribute('class', compact([node.attrs.class, node.className]).join(' ')),- ...node.bindings.flatMap((binding) => bindingAttributes(binding, kind, native))+ ...node.bindings.flatMap((binding) => bindingAttributes(binding, uses.kind, native))],- node.children.map((child) => templateNode(child, kind, used))+ node.children.map((child) => templateNode(child, uses)))}@@ -96,22 +140,35 @@ function propsDefaults(component: ComponentModel): es.SyntaxNode {const PROPS = es.parseModule('withDefaults(defineProps<$Props>(), $defaults)')const MODEL = es.parseModule('const $model = defineModel<boolean>($name, { default: false })')-function script(component: ComponentModel, used: Set<string>): es.SyntaxNode {- const imports =- used.size > 0- ? [- {- type: 'ImportDeclaration',- importKind: 'value',- specifiers: [...used].sort().map((name) => ({- type: 'ImportSpecifier',- imported: identifier(name),- local: identifier(name)- })),- source: es.string('reka-ui')- }- ]- : []+function namedImport(names: readonly string[], source: string, local = (name: string) => name) {+ return {+ type: 'ImportDeclaration',+ importKind: 'value',+ specifiers: names.map((name) => ({+ type: 'ImportSpecifier',+ imported: identifier(name),+ local: identifier(local(name))+ })),+ source: es.string(source)+ }+}++const IMPORT_COMPONENT = es.parseModule(`import $Component from '$path'`)+const MODEL_REF = es.parseModule('const $name = ref(true)')++function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {+ const imports = [+ ...(uses.models.length > 0 ? [namedImport(['ref'], 'vue')] : []),+ ...(uses.icons ? [namedImport(['Icon'], '@iconify/vue', () => ICONIFY)] : []),+ ...(uses.reka.size > 0 ? [namedImport([...uses.reka].sort(), 'reka-ui')] : []),+ ...[...uses.components].sort().flatMap(+ (name) =>+ es.fill(IMPORT_COMPONENT, {+ $Component: identifier(name),+ $path: es.string(`./${name}.vue`)+ }).body+ )+ ]const props =component.disabled || component.props.length > 0 || component.texts.length > 0? es.fill(PROPS, { $Props: propsType(component), $defaults: propsDefaults(component) }).body@@ -120,7 +177,14 @@ function script(component: ComponentModel, used: Set<string>): es.SyntaxNode {? es.fill(MODEL, { $model: identifier(component.model), $name: es.string(component.model) }).body: []- return { type: 'Program', sourceType: 'module', body: [...imports, ...props, ...model] }+ const refs = uses.models.flatMap(+ (item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body+ )+ return {+ type: 'Program',+ sourceType: 'module',+ body: [...imports, ...props, ...model, ...refs]+ }}/**@@ -129,15 +193,28 @@ function script(component: ComponentModel, used: Set<string>): es.SyntaxNode {* other variant properties.*/export const vueComponent: ComponentGenerator = async (component) => {- const used = new Set<string>()- const template = templateNode(component.tree, component.kind, used)+ const uses: TemplateUses = {+ kind: component.kind,+ reka: new Set(),+ components: new Set(),+ icons: false,+ models: [],+ // Refs share the script with the component's own props and model.+ taken: new Set([+ ...component.props.map((prop) => prop.name),+ ...component.texts.map((text) => text.name),+ ...(component.model ? [component.model] : []),+ 'disabled'+ ])+ }+ const template = templateNode(component.tree, uses)const { css } = await stateStylesToCSS(component.styles)const path = `${component.name}.vue`return {files: [{path,- content: vue.printComponent({ script: script(component, used), template, style: css })+ content: vue.printComponent({ script: script(component, uses), template, style: css })}],entry: { path: `./${path}`, named: false },diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.tsindex acdff203b..77cacb366 100644--- a/packages/dom-css/src/export/storybook/export.ts+++ b/packages/dom-css/src/export/storybook/export.ts@@ -1,8 +1,9 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import type { ExportHTMLFile } from '../bundle'-import { componentModel, type ComponentGenerator } from '../components/model'+import { componentModel, type ComponentGenerator, type ComponentModel } from '../components/model'import { reactComponent } from '../components/react'+import type { ComponentReferences } from '../components/references'import { vueComponent } from '../components/vue'import { serializeHTML } from '../html'import { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'@@ -114,6 +115,64 @@ function storyModule(group: StoryGroup, context: ModuleContext): string {})}+/** A story file to write: its group, the page it comes from, and its claimed file name. */+interface StoryEntry {+ page: SceneNode+ group: StoryGroup+ file: string+}++/**+ * 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[] {+ 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)) {+ // 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.+ const file = claimName(identifierName(group.name, 'Component'), takenFiles, {+ key: (name) => name.toLowerCase()+ })+ if (!pageId || page.id === pageId) entries.push({ page, group, file })+ }+ }+ return entries+}++/**+ * The component each entry's set generates, by set id, built twice: first alone, so each+ * knows its props, then knowing all the others, so an instance of one uses it rather than+ * drawing its layers.+ */+function generatedModels(+ graph: SceneGraph,+ entries: readonly StoryEntry[],+ vectorElement: VectorElementRenderer | undefined+): Map<string, ComponentModel> {+ const model = (set: SceneNode, file: string, references?: ComponentReferences) => {+ const component = componentModel(graph, set, { vectorElement, references })+ // The component is imported by the file's name, so the two always match.+ if (component) component.name = file+ return component+ }+ const alone = new Map<string, ComponentModel>()+ for (const { group, file } of entries) {+ const component = group.set && model(group.set, file)+ if (group.set && component) alone.set(group.set.id, component)+ }+ const models = new Map<string, ComponentModel>()+ for (const { group, file } of entries) {+ const component = group.set && alone.has(group.set.id) && model(group.set, file, alone)+ if (group.set && component) models.set(group.set.id, component)+ }+ return models+}+/*** Generate one CSF3 `.stories.ts` file per component or component set, plus a* `<Name>.design/` folder of variant images when `renderDesignImage` is given.@@ -124,60 +183,45 @@ export async function exportStorybook(): Promise<StorybookFile[]> {const framework = options.framework ?? 'react'const uniqueNames = uniqueLayerNames(graph)- const takenFiles = new Set<string>()- const takenIds = new Set<string>()const files: StorybookFile[] = []const add = (page: SceneNode, path: string, content: string | Uint8Array) =>files.push({ path, content, page: page.name })- // Names are claimed on every page, so a one-page export picks the same names as a full one.- for (const page of graph.getPages()) {- for (const group of collectGroups(graph, 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.- const file = claimName(identifierName(group.name, 'Component'), takenFiles, {- key: (name) => name.toLowerCase()- })- if (options.pageId && page.id !== options.pageId) continue-- const generate = GENERATORS[framework]- const component =- generate && group.set- ? componentModel(graph, group.set, { vectorElement: options.vectorElement })- : null- if (generate && component) {- // The component is imported by the file's name, so the two always match.- component.name = file- const generated = await generate(component)- for (const item of generated.files) add(page, item.path, item.content)- const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)- add(- page,- `${file}.stories.ts`,- printComponentStories({- storybook: STORYBOOK_PACKAGES[framework],- title: group.title,- component,- generated,- design: design.flatMap((entry) =>- entry.type === 'link' ? [{ name: 'OpenPencil', type: 'link', url: entry.url }] : []- )- })- )- continue- }-- const names = storyNames(group)- const render = options.renderDesignImage- const images = render ? names.map((name) => `${file}.design/${name}.png`) : []- if (render) {- for (const [i, variant] of group.variants.entries())- add(page, images[i] ?? '', await render(variant.node.id))- }- const context = { ...options, graph, framework, uniqueNames, storyNames: names, images }- add(page, `${file}.stories.ts`, storyModule(group, context))+ const entries = storyEntries(graph, options.pageId)+ const generate = GENERATORS[framework]+ const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()++ for (const { page, group, file } of entries) {+ const component = group.set && models.get(group.set.id)+ if (generate && component) {+ const generated = await generate(component)+ for (const item of generated.files) add(page, item.path, item.content)+ const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)+ add(+ page,+ `${file}.stories.ts`,+ printComponentStories({+ storybook: STORYBOOK_PACKAGES[framework],+ title: group.title,+ component,+ generated,+ design: design.flatMap((entry) =>+ entry.type === 'link' ? [{ name: 'OpenPencil', type: 'link', url: entry.url }] : []+ )+ })+ )+ continue+ }++ const names = storyNames(group)+ const render = options.renderDesignImage+ const images = render ? names.map((name) => `${file}.design/${name}.png`) : []+ if (render) {+ for (const [i, variant] of group.variants.entries())+ add(page, images[i] ?? '', await render(variant.node.id))}+ const context = { ...options, graph, framework, uniqueNames, storyNames: names, images }+ add(page, `${file}.stories.ts`, storyModule(group, context))}return files}diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.tsindex 0040ff0d9..d7ffb5057 100644--- a/packages/dom-css/tests/behaviours/fixtures.ts+++ b/packages/dom-css/tests/behaviours/fixtures.ts@@ -1,4 +1,10 @@-import { emptyBehaviour, SceneGraph, withBehaviour, type Behaviour } from '@open-pencil/scene-graph'+import {+ emptyBehaviour,+ SceneGraph,+ withBehaviour,+ withIcon,+ type Behaviour+} from '@open-pencil/scene-graph'const solid = (r: number, g: number, b: number) => [{ type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }@@ -17,9 +23,9 @@ export function componentSet(axes: Record<string, string[]>,behaviour: Behaviour,draw: (graph: SceneGraph, variant: string, values: Record<string, string>) => void,- skip: (values: Record<string, string>) => boolean = () => false+ skip: (values: Record<string, string>) => boolean = () => false,+ graph = new SceneGraph()) {- const graph = new SceneGraph()const pageId = graph.getPages()[0].idconst set = graph.createNode('COMPONENT_SET', pageId, {name,@@ -52,7 +58,7 @@ export function componentSet(return { graph, set: graph.getNode(set.id) ?? set }}-export function switchSet() {+export function switchSet(graph?: SceneGraph) {return componentSet('Switch',{ State: ['Off', 'On'], Interaction: ['Default', 'Hover', 'Disabled'] },@@ -75,7 +81,9 @@ export function switchSet() {height: 18,fills: COLORS.white})- }+ },+ undefined,+ graph)}@@ -165,6 +173,55 @@ export function labelledButtonSet() {return { graph, set: graph.getNode(set.id) ?? set }}+/**+ * A collapsible section whose trigger holds an icon and a label and whose content, shown only+ * when open, holds a switch drawn on, with the switch's own set in the same document, so the+ * section's component can use the switch's rather than draw it.+ */+export function settingsSectionSet() {+ 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 slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]+ const section = componentSet(+ 'Section',+ { Open: ['No', 'Yes'] },+ {+ ...emptyBehaviour('collapsible'),+ booleans: { open: { propertyId: 'open', on: 'Yes', off: 'No' } },+ parts: { trigger: 'trigger-slot', content: 'content-slot' }+ },+ (graph, variant, { Open }) => {+ graph.updateNode(variant, { width: 160, height: 60 })+ const trigger = graph.createNode('FRAME', variant, {+ name: 'Trigger',+ componentPropertyReferences: slot('trigger-slot'),+ width: 160,+ height: 20+ })+ const icon = graph.createNode('FRAME', trigger.id, { name: 'bell', width: 16, height: 16 })+ graph.updateNode(icon.id, { pluginData: withIcon(icon, { name: 'lucide:bell' }) })+ graph.createNode('VECTOR', icon.id, { name: 'path', width: 16, height: 16 })+ graph.createNode('TEXT', trigger.id, { name: 'Title', text: 'Notifications', x: 20 })+ if (Open !== 'Yes') return+ const content = graph.createNode('FRAME', variant, {+ name: 'Content',+ componentPropertyReferences: slot('content-slot'),+ y: 24,+ width: 160,+ height: 30+ })+ graph.createInstance(on.id, content.id, { name: 'Switch' })+ },+ undefined,+ graph+ )+ return { graph, set: section.set, switchSet: toggle.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.tsindex abae7ce3f..fdc54dc13 100644--- a/packages/dom-css/tests/export/components/react.test.ts+++ b/packages/dom-css/tests/export/components/react.test.ts@@ -7,6 +7,7 @@ import {buttonSet,collapsibleSet,labelledButtonSet,+ settingsSectionSet,switchSet} from '#dom-css-tests/behaviours/fixtures'import { exportStorybook } from '#dom-css/index'@@ -14,10 +15,11 @@ import { createElement, type ComponentType } from 'react'import { renderToStaticMarkup } from 'react-dom/server'/** The packages generated code imports, linked so it resolves them as an app would. */-const APP_PACKAGES = ['react', 'react-dom', 'radix-ui', 'storybook']+const APP_PACKAGES = ['react', 'react-dom', 'radix-ui', '@iconify/react', 'storybook']const output = await mkdtemp(join(tmpdir(), 'open-pencil-react-'))await mkdir(join(output, 'node_modules'))+await mkdir(join(output, 'node_modules', '@iconify'))for (const name of APP_PACKAGES)await symlink(dirname(Bun.resolveSync(`${name}/package.json`, import.meta.dir)),@@ -80,6 +82,17 @@ describe('generated React components', () => {expect(meta.args).toMatchObject({ label: 'Save' })})+ test('an instance of another generated component uses it, even in open-only content, and an icon uses Iconify', async () => {+ const { files, component } = await generate(settingsSectionSet())+ const source = String(files.find((file) => file.path === 'Section.tsx')?.content)+ expect(source).toContain(`import { Switch } from "./Switch"`)+ expect(source).toContain('@iconify/react')+ const html = render(component, { defaultOpen: true })+ // The switch is the generated one, drawn on as the design places it, and only once.+ expect(html.match(/role="switch"/g)?.length).toBe(1)+ expect(html).toContain('data-state="checked"')+ })+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.tsindex b7c0d3d6a..3d8e22fc4 100644--- a/packages/dom-css/tests/export/components/vue.test.ts+++ b/packages/dom-css/tests/export/components/vue.test.ts@@ -7,6 +7,7 @@ import {buttonSet,collapsibleSet,labelledButtonSet,+ settingsSectionSet,switchSet} from '#dom-css-tests/behaviours/fixtures'import { exportStorybook } from '#dom-css/index'@@ -15,10 +16,11 @@ import { compileScript, parse } from 'vue/compiler-sfc'import { renderToString } from 'vue/server-renderer'/** The packages generated code imports, linked so it resolves them as an app would. */-const APP_PACKAGES = ['vue', 'reka-ui', 'storybook']+const APP_PACKAGES = ['vue', 'reka-ui', '@iconify/vue', 'storybook']const output = await mkdtemp(join(tmpdir(), 'open-pencil-vue-'))await mkdir(join(output, 'node_modules'))+await mkdir(join(output, 'node_modules', '@iconify'))for (const name of APP_PACKAGES)await symlink(dirname(Bun.resolveSync(`${name}/package.json`, import.meta.dir)),@@ -32,13 +34,16 @@ async function generate(fixture: ReturnType<typeof switchSet>) {const source = (suffix: string) =>String(files.find((file) => file.path.endsWith(suffix))?.content)const name = fixture.set.name- const { descriptor, errors } = parse(source('.vue'), { filename: `${name}.vue` })- expect(errors).toEqual([])- const script = compileScript(descriptor, { id: name, inlineTemplate: true })// Bun caches a folder's listing once it imports from it, so each export gets its own.const folder = await mkdtemp(join(output, `${name}-`))- // `./Name.vue` resolves to `Name.vue.ts`, so the stories import the compiled component.- await writeFile(join(folder, `${name}.vue.ts`), script.content)+ // `./Name.vue` resolves to `Name.vue.ts`, so components and stories import compiled ones.+ for (const file of files.filter((item) => item.path.endsWith('.vue'))) {+ const id = file.path.slice(0, -'.vue'.length)+ const { descriptor, errors } = parse(String(file.content), { filename: file.path })+ expect(errors).toEqual([])+ const script = compileScript(descriptor, { id, inlineTemplate: true })+ await writeFile(join(folder, `${file.path}.ts`), script.content)+ }await writeFile(join(folder, `${name}.stories.ts`), source('.stories.ts'))const component: { default: Component } = await import(join(folder, `${name}.vue.ts`))const stories: Record<string, { args?: Record<string, unknown>; play?: unknown }> = await import(@@ -90,6 +95,17 @@ describe('generated Vue components', () => {expect(meta.argTypes).toMatchObject({ label: { control: 'text' } })})+ test('an instance of another generated component uses it, even in open-only content, and an icon uses Iconify', async () => {+ const { files, component } = await generate(settingsSectionSet())+ const source = String(files.find((file) => file.path === 'Section.vue')?.content)+ expect(source).toContain(`import Switch from './Switch.vue'`)+ expect(source).toContain('@iconify/vue')+ const html = await render(component, { open: true })+ // The switch is the generated one, drawn on as the design places it, and only once.+ expect(html.match(/role="switch"/g)?.length).toBe(1)+ expect(html).toContain('data-state="checked"')+ })+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/tests/e2e/dom-css/generated-components.spec.ts b/tests/e2e/dom-css/generated-components.spec.tsindex f71349c90..e6f1e8746 100644--- a/tests/e2e/dom-css/generated-components.spec.ts+++ b/tests/e2e/dom-css/generated-components.spec.ts@@ -28,9 +28,9 @@ function controlSet(name: string,property: { name: string; values: string[] },behaviour: Behaviour,- draw: (graph: SceneGraph, variantId: string, value: string) => void+ draw: (graph: SceneGraph, variantId: string, value: string) => void,+ graph = new SceneGraph()): SceneGraph {- const graph = new SceneGraph()const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, {name,componentPropertyDefinitions: [@@ -56,7 +56,7 @@ function controlSet(return graph}-function switchGraph(): SceneGraph {+function switchGraph(graph?: SceneGraph): SceneGraph {return controlSet('Switch',{ name: 'State', values: ['Off', 'On'] },@@ -78,7 +78,43 @@ function switchGraph(): SceneGraph {height: 18,fills: fill(1, 1, 1)})- }+ },+ graph+ )+}++/** A collapsible section whose content holds a switch drawn on, with the switch's set beside it. */+function sectionGraph(): SceneGraph {+ const graph = switchGraph()+ const on = [...graph.getAllNodes()].find((node) => node.name === 'State=On')+ if (!on) throw new Error('Expected the switch drawn on')+ return controlSet(+ 'Section',+ { name: 'Open', values: ['No', 'Yes'] },+ {+ ...emptyBehaviour('collapsible'),+ booleans: { open: { propertyId: 'value', on: 'Yes', off: 'No' } },+ parts: { trigger: 'trigger', content: 'content' }+ },+ (graph, variantId, value) => {+ graph.updateNode(variantId, { width: 120, height: 60 })+ graph.createNode('FRAME', variantId, {+ name: 'Trigger',+ componentPropertyReferences: slot('trigger'),+ width: 120,+ height: 20+ })+ if (value !== 'Yes') return+ const content = graph.createNode('FRAME', variantId, {+ name: 'Content',+ componentPropertyReferences: slot('content'),+ y: 24,+ width: 120,+ height: 30+ })+ graph.createInstance(on.id, content.id, { name: 'Switch' })+ },+ graph)}@@ -190,11 +226,13 @@ const APPS: Record<async function serveComponent(graph: SceneGraph,framework: Framework,- folder: string+ folder: string,+ name?: string): Promise<ViteDevServer> {const files = await exportStorybook(graph, { framework })- const component = files.find((file) => /\.(vue|tsx)$/.test(file.path))- const stories = files.find((file) => file.path.endsWith('.stories.ts'))+ const named = (file: { path: string }) => !name || file.path.startsWith(`${name}.`)+ const component = files.find((file) => named(file) && /\.(vue|tsx)$/.test(file.path))+ const stories = files.find((file) => named(file) && file.path.endsWith('.stories.ts'))if (!component || !stories) throw new Error('No component was generated')await mkdir(folder, { recursive: true })for (const file of files) await writeFile(join(folder, file.path), file.content)@@ -260,6 +298,27 @@ for (const framework of ['vue', 'react'] as const) {)})+ test('a switch in the content of a section is the generated switch, operable', async ({+ page+ }, info) => {+ server = await serveComponent(+ sectionGraph(),+ framework,+ info.outputPath('section'),+ 'Section'+ )+ await page.goto(server.resolvedUrls?.local[0] ?? '')+ await page.locator('#enabled').getByRole('button').first().click()+ const nested = page.locator('#enabled').getByRole('switch')+ // It starts as the design draws it and keeps working as a switch.+ await expect(nested).toHaveAttribute('data-state', 'checked')+ await nested.click()+ await expect(nested).toHaveAttribute('data-state', 'unchecked')+ await expect(page.locator('#enabled [class*="switch__thumb"]')).toHaveCSS('left', '2px')+ // The section only places the switch; its own state styles still paint it.+ await expect(nested).toHaveCSS('background-color', 'rgb(204, 214, 224)')+ })+test('a collapsible shows its content when its trigger opens it', async ({ page }, info) => {server = await serveComponent(disclosureGraph(), framework, info.outputPath('disclosure'))await page.goto(server.resolvedUrls?.local[0] ?? '')