AI-native design editor. Open-source Figma alternative.
feat(storybook): give components with behaviours their own story controls (#961)
Danila Poyarkovb5a5b41523ff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ed9e9c98..afe3448ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -69,7 +69,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 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), 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.- 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/docs/de/programmable/cli/exporting.md b/packages/docs/de/programmable/cli/exporting.mdindex f399656ea..09696a078 100644--- a/packages/docs/de/programmable/cli/exporting.md+++ b/packages/docs/de/programmable/cli/exporting.md@@ -57,7 +57,7 @@ Legen Sie die Designdatei jeder Komponente in den Ordner der Komponente und expoSie können mehrere Dokumente übergeben oder einen Glob in Anführungszeichen wie `'src/**/*.pen'`, den OpenPencil selbst auflöst (Node.js 22 oder neuer). Mehrere Dokumente erfordern `--beside` oder `--output`; `--page` funktioniert nur mit einem Dokument. Die Dokumente werden nacheinander exportiert, und schlägt eines fehl, werden die übrigen trotzdem exportiert, bevor der Befehl mit einem Fehler endet. `--watch` beobachtet jedes passende Dokument; ein Dokument, das nach dem Start der Beobachtung entsteht, erfordert einen neuen Lauf.-Jede Variante eines Komponentensatzes wird zu einer Story, und ihre Variantenmerkmale werden zu `select`-Controls, sodass das Umschalten eines Controls die passende Variante zeigt. Eigenständige Komponenten mit Schrägstrich im Namen, etwa `Button/Primary` und `Button/Secondary`, werden in einer `Button`-Datei mit einem `Variant`-Control zusammengefasst. Eine Kombination, für die das Design keine Variante hat, löst in Storybook einen benannten Fehler aus, statt eine andere Variante zu zeigen.+Jede Variante eines Komponentensatzes wird zu einer Story, und ihre Variantenmerkmale werden zu `select`-Controls, sodass das Umschalten eines Controls die passende Variante zeigt. Ein Satz mit Verhalten erhält stattdessen die Props des Controls: ein Switch oder eine Checkbox ein boolesches `checked`, ein Toggle `pressed`, ein Collapsible `open` und `disabled`, wenn der Satz einen deaktivierten Zustand zeichnet; Hover, Pressed und Fokus bleiben eigene Storys. Eigenständige Komponenten mit Schrägstrich im Namen, etwa `Button/Primary` und `Button/Secondary`, werden in einer `Button`-Datei mit einem `Variant`-Control zusammengefasst. Eine Kombination, für die das Design keine Variante hat, löst in Storybook einen benannten Fehler aus, statt eine andere Variante zu zeigen.Die Stories rendern die Komponente wie `-f html` als HTML mit Inline-Stilen und benötigen daher keine OpenPencil-Laufzeit; `--framework` (`react`, `vue` oder `html`) ändert nur den Wrapper und den Import von `Meta`/`StoryObj` aus `@storybook/react-vite`, `@storybook/vue3-vite` oder `@storybook/html-vite`. Text verwendet die Schriftfamilien des Dokuments, die Storybook selbst laden muss. Text-, Boolean- und Instanztausch-Eigenschaften werden noch nicht exportiert.diff --git a/packages/docs/es/programmable/cli/exporting.md b/packages/docs/es/programmable/cli/exporting.mdindex f9a76b61b..734f7de62 100644--- a/packages/docs/es/programmable/cli/exporting.md+++ b/packages/docs/es/programmable/cli/exporting.md@@ -57,7 +57,7 @@ Guarda el archivo de diseño de cada componente en la carpeta del componente y ePasa varios documentos, o un glob entre comillas como `'src/**/*.pen'` que OpenPencil expande por sí mismo (Node.js 22 o posterior). Varios documentos requieren `--beside` o `--output`; `--page` solo funciona con un documento. Los documentos se exportan uno tras otro y, si uno falla, el resto se exporta igualmente antes de que el comando termine con un error. `--watch` vigila todos los documentos coincidentes; un documento creado después de iniciar la vigilancia requiere ejecutar el comando de nuevo.-Cada variante de un conjunto de componentes se convierte en una historia y sus propiedades de variante pasan a ser controles `select`, de modo que al cambiar un control se muestra la variante correspondiente. Los componentes independientes con nombres separados por barras, como `Button/Primary` y `Button/Secondary`, se agrupan en un único archivo `Button` con un control `Variant`. Una combinación para la que el diseño no tiene variante lanza en Storybook un error con nombre en lugar de mostrar otra variante.+Cada variante de un conjunto de componentes se convierte en una historia y sus propiedades de variante pasan a ser controles `select`, de modo que al cambiar un control se muestra la variante correspondiente. Un conjunto con comportamiento recibe en su lugar las props del control: un Switch o un Checkbox un booleano `checked`, un Toggle `pressed`, un Collapsible `open` y `disabled` cuando el conjunto dibuja un estado deshabilitado; hover, pressed y foco siguen siendo historias propias. Los componentes independientes con nombres separados por barras, como `Button/Primary` y `Button/Secondary`, se agrupan en un único archivo `Button` con un control `Variant`. Una combinación para la que el diseño no tiene variante lanza en Storybook un error con nombre en lugar de mostrar otra variante.Las historias muestran el componente como HTML con estilos en línea, igual que `-f html`, así que no necesitan el runtime de OpenPencil; `--framework` (`react`, `vue` o `html`) solo cambia el contenedor y la importación de `Meta`/`StoryObj` desde `@storybook/react-vite`, `@storybook/vue3-vite` o `@storybook/html-vite`. El texto usa las familias tipográficas del documento, que Storybook debe cargar por su cuenta. Las propiedades de texto, booleanas y de intercambio de instancia aún no se exportan.diff --git a/packages/docs/it/programmable/cli/exporting.md b/packages/docs/it/programmable/cli/exporting.mdindex c0ca89d93..a4c7da564 100644--- a/packages/docs/it/programmable/cli/exporting.md+++ b/packages/docs/it/programmable/cli/exporting.md@@ -51,7 +51,7 @@ Tieni il file di design di ogni componente nella cartella del componente ed espoPuoi passare più documenti, oppure un glob tra apici come `'src/**/*.pen'` che OpenPencil espande da solo (Node.js 22 o successivo). Più documenti richiedono `--beside` oppure `--output`; `--page` funziona solo con un documento. I documenti vengono esportati uno dopo l’altro e, se uno fallisce, gli altri vengono comunque esportati prima che il comando termini con un errore. `--watch` osserva tutti i documenti trovati; un documento creato dopo l’avvio dell’osservazione richiede una nuova esecuzione.-Ogni variante di un set di componenti diventa una storia e le sue proprietà di variante diventano controlli `select`, quindi cambiando un controllo si vede la variante corrispondente. I componenti singoli con nomi separati da barre, come `Button/Primary` e `Button/Secondary`, sono raggruppati in un unico file `Button` con un controllo `Variant`. Una combinazione per cui il design non ha una variante genera in Storybook un errore con nome invece di mostrare un’altra variante.+Ogni variante di un set di componenti diventa una storia e le sue proprietà di variante diventano controlli `select`, quindi cambiando un controllo si vede la variante corrispondente. Un set con un comportamento riceve invece le prop del controllo: uno Switch o una Checkbox un booleano `checked`, un Toggle `pressed`, un Collapsible `open` e `disabled` quando il set disegna uno stato disabilitato; hover, pressed e focus restano storie a sé. I componenti singoli con nomi separati da barre, come `Button/Primary` e `Button/Secondary`, sono raggruppati in un unico file `Button` con un controllo `Variant`. Una combinazione per cui il design non ha una variante genera in Storybook un errore con nome invece di mostrare un’altra variante.Le storie renderizzano il componente come HTML con stili inline, come `-f html`, quindi non richiedono il runtime di OpenPencil; `--framework` (`react`, `vue` o `html`) cambia solo il wrapper e l’import di `Meta`/`StoryObj` da `@storybook/react-vite`, `@storybook/vue3-vite` o `@storybook/html-vite`. Il testo usa le famiglie di font del documento, che Storybook deve caricare per conto proprio. Le proprietà di testo, booleane e di sostituzione dell’istanza non vengono ancora esportate.diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex 7d9784d2c..baa8ec848 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -140,7 +140,7 @@ Keep each component's design file in the component's folder and export with `--bPass 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. 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.+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. Text, boolean, and instance-swap properties are not exported yet.diff --git a/packages/dom-css/src/behaviours/args.ts b/packages/dom-css/src/behaviours/args.tsnew file mode 100644index 000000000..84a407ac9--- /dev/null+++ b/packages/dom-css/src/behaviours/args.ts@@ -0,0 +1,66 @@+import {+ behaviourProperties,+ readBehaviour,+ type BehaviourKind,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++/** A variant property a boolean value draws, as the component's boolean prop. */+export interface BooleanArg {+ /** The prop's name, as Reka and Radix call it: `checked`, `pressed`, `open`, `disabled`. */+ name: string+ on: string+ off: string+}++/** The props a component with a behaviour has, read from the variant properties that draw it. */+export interface BehaviourArgs {+ /** Boolean props by the name of the variant property that draws them. */+ booleans: Map<string, BooleanArg>+ /**+ * The variant property that draws interaction states. States follow the pointer and focus,+ * so they are not props; `rest` is the value shown without one, and `disabled` the value the+ * disabled prop shows, if the set draws it.+ */+ states?: { property: string; rest: string; disabled?: string }+}++/** Values a behaviour derives from others instead of taking as props. */+const DERIVED_VALUES = new Set(['filled'])++function booleanArgName(kind: BehaviourKind, valueId: string): string {+ if (valueId !== 'value') return valueId+ return kind === 'toggle' ? 'pressed' : 'checked'+}++/**+ * The props of a component set with a behaviour. Only variant properties become props here,+ * since each variant is drawn; a boolean value becomes a boolean prop when its property offers+ * exactly its on and off values.+ */+export function behaviourArgs(graph: SceneGraph, set: SceneNode): BehaviourArgs | null {+ const behaviour = readBehaviour(set)+ if (!behaviour) return null+ const variants = behaviourProperties(graph, set).filter((item) => item.type === 'VARIANT')+ const variant = (id: string) => variants.find((item) => item.id === id)+ const booleans = new Map<string, BooleanArg>()+ for (const [valueId, binding] of Object.entries(behaviour.booleans)) {+ const definition = variant(binding.propertyId)+ const { on, off } = binding+ if (!definition || on === undefined || off === undefined || DERIVED_VALUES.has(valueId))+ continue+ const options = new Set(definition.variantOptions)+ if (options.size !== 2 || !options.has(on) || !options.has(off)) continue+ booleans.set(definition.name, { name: booleanArgName(behaviour.kind, valueId), on, off })+ }+ const statesProperty = behaviour.states && variant(behaviour.states.propertyId)+ const states = statesProperty+ ? {+ property: statesProperty.name,+ rest: behaviour.states?.rest ?? statesProperty.defaultValue,+ disabled: behaviour.states?.disabled+ }+ : undefined+ return { booleans, states }+}diff --git a/packages/dom-css/src/behaviours/index.ts b/packages/dom-css/src/behaviours/index.tsindex d81bc418e..0f90a0a31 100644--- a/packages/dom-css/src/behaviours/index.ts+++ b/packages/dom-css/src/behaviours/index.ts@@ -1,3 +1,4 @@+export { behaviourArgs, type BehaviourArgs, type BooleanArg } from './args'export {behaviourControls,booleanOf,diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.tsindex 90dd25af7..17047e07f 100644--- a/packages/dom-css/src/export/storybook/groups.ts+++ b/packages/dom-css/src/export/storybook/groups.ts@@ -1,8 +1,10 @@+import { behaviourArgs } from '#dom-css/behaviours/args'import { uniq } from 'es-toolkit/array'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'+import type { StoryProp } from './module'import { claimName } from './names'export interface StoryVariant {@@ -15,7 +17,7 @@ export interface StoryGroup {page: SceneNodetitle: stringname: string- props: { name: string; options: string[] }[]+ props: StoryProp[]variants: StoryVariant[]/** Layer the story file links to, when the group has a layer of its own. */linkNode?: string@@ -49,10 +51,22 @@ function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode):values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),node: component}))- const props = definitions.map((def, index) => ({- name: def.name,- options: uniq([...(def.variantOptions ?? []), ...variants.map((v) => v.values[index] ?? '')])- }))+ const args = behaviourArgs(graph, set)+ const props = definitions.map((def, index): StoryProp => {+ const options = uniq([+ ...(def.variantOptions ?? []),+ ...variants.map((v) => v.values[index] ?? '')+ ])+ const boolean = args?.booleans.get(def.name)+ if (boolean) return { name: def.name, options, control: { type: 'boolean', ...boolean } }+ if (args?.states?.property === def.name)+ return {+ name: def.name,+ options,+ control: { type: 'state', rest: args.states.rest, disabled: args.states.disabled }+ }+ return { name: def.name, options }+ })return distinctVariants({page,title: `${page.name}/${set.name}`,diff --git a/packages/dom-css/src/export/storybook/module.ts b/packages/dom-css/src/export/storybook/module.tsindex 3efa68c04..76f6ba331 100644--- a/packages/dom-css/src/export/storybook/module.ts+++ b/packages/dom-css/src/export/storybook/module.ts@@ -8,13 +8,28 @@ export type StorybookFramework = (typeof STORYBOOK_FRAMEWORKS)[number]/** Tells readers the file is generated; nothing parses it. */const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overwritten.'+/**+ * How a variant property is controlled. A boolean value's property becomes a boolean arg that+ * picks its on or off variant; the interaction-state property is left to each story, with a+ * `disabled` arg picking its disabled variant when the set draws one.+ */+export type StoryControl =+ | { type: 'boolean'; name: string; on: string; off: string }+ | { type: 'state'; rest: string; disabled?: string }++export interface StoryProp {+ name: string+ options: string[]+ control?: StoryControl+}+/** Everything a story module varies by; the TypeScript around it is a fixed template. */export interface StoryModuleData {framework: StorybookFrameworktitle: string/** Group name used in the missing-variant error. */name: string- props: { name: string; options: string[] }[]+ props: StoryProp[]variants: { values: string[]; html: string }[]metaDesign: StoryDesign[]/** Import path of each design image, by variant index. */@@ -81,8 +96,89 @@ const FRAMEWORKS: Record<const imageName = (variant: number) => `design${variant}`+const BOOLEAN = es.parseType('boolean')+const CONDITION = es.parseExpression('$test ? $then : $else')+const boolean = (value: boolean) => es.parseExpression(String(value))++function argRef(name: string): es.SyntaxNode {+ return {+ type: 'MemberExpression',+ object: es.identifier('args'),+ property: es.string(name),+ computed: true,+ optional: false+ }+}++/** The `disabled` arg a state property adds, unless a boolean value already takes the name. */+function disabledArg(data: StoryModuleData): { property: string; value: string } | null {+ if (+ data.props.some((prop) => prop.control?.type === 'boolean' && prop.control.name === 'disabled')+ )+ return null+ for (const prop of data.props)+ if (prop.control?.type === 'state' && prop.control.disabled !== undefined)+ return { property: prop.name, value: prop.control.disabled }+ return null+}++/** The arg a prop is set by: a boolean prop's own name, otherwise the property's. */+const argName = (prop: StoryProp) =>+ prop.control?.type === 'boolean' ? prop.control.name : prop.name++/** The variant value a prop shows, as an expression over `args`. */+function propValue(data: StoryModuleData, prop: StoryProp): es.SyntaxNode {+ const control = prop.control+ if (control?.type === 'boolean')+ return es.fill(CONDITION, {+ $test: argRef(control.name),+ $then: es.string(control.on),+ $else: es.string(control.off)+ })+ const disabled = disabledArg(data)+ if (disabled?.property === prop.name)+ return es.fill(CONDITION, {+ $test: argRef('disabled'),+ $then: es.string(disabled.value),+ $else: argRef(prop.name)+ })+ return argRef(prop.name)+}+function argsObject(data: StoryModuleData, values: string[]): es.SyntaxNode {- return es.object(data.props.map((prop, i) => [prop.name, es.string(values[i] ?? '')]))+ const entries = data.props.map((prop, i): [string, es.SyntaxNode] => {+ const value = values[i] ?? ''+ if (prop.control?.type === 'boolean')+ return [prop.control.name, boolean(value === prop.control.on)]+ // A disabled story says so through `disabled`, so clearing it shows the rest state.+ if (prop.control?.type === 'state' && value === disabledArg(data)?.value)+ return [prop.name, es.string(prop.control.rest)]+ return [prop.name, es.string(value)]+ })+ const disabled = disabledArg(data)+ if (disabled) {+ const index = data.props.findIndex((prop) => prop.name === disabled.property)+ entries.push(['disabled', boolean(values[index] === disabled.value)])+ }+ return es.object(entries)+}++function argTypes(data: StoryModuleData): es.SyntaxNode {+ const entries = data.props.map((prop): [string, es.SyntaxNode] => {+ if (prop.control?.type === 'boolean')+ return [prop.control.name, es.object([['control', es.string('boolean')]])]+ if (prop.control?.type === 'state')+ return [prop.name, es.object([['table', es.object([['disable', boolean(true)]])]])]+ return [+ prop.name,+ es.object([+ ['control', es.string('select')],+ ['options', es.array(prop.options.map(es.string))]+ ])+ ]+ })+ if (disabledArg(data)) entries.push(['disabled', es.object([['control', es.string('boolean')]])])+ return es.object(entries)}function parameters(design: StoryDesign[]): es.SyntaxNode {@@ -106,7 +202,12 @@ const NO_ARGS = es.parseType('Record<string, never>')function argsType(data: StoryModuleData): es.SyntaxNode {if (data.props.length === 0) return NO_ARGS- return es.objectType(data.props.map((prop) => [prop.name, es.stringUnionType(prop.options)]))+ const entries = data.props.map((prop): [string, es.SyntaxNode] => [+ argName(prop),+ prop.control?.type === 'boolean' ? BOOLEAN : es.stringUnionType(prop.options)+ ])+ if (disabledArg(data)) entries.push(['disabled', BOOLEAN])+ return es.objectType(entries)}/** Print a CSF3 story module for one component or component set. */@@ -118,28 +219,12 @@ export function printStoryModule(data: StoryModuleData): string {$variants: es.object(data.variants.map((variant) => [JSON.stringify(variant.values), es.string(variant.html)])),- $key: es.array(- data.props.map((prop) => ({- type: 'MemberExpression',- object: es.identifier('args'),- property: es.string(prop.name),- computed: true,- optional: false- }))- ),+ $key: es.array(data.props.map((prop) => propValue(data, prop))),$missing: es.string(`${data.name} has no variant `),$title: es.string(data.title),$parameters: data.metaDesign.length > 0 ? parameters(data.metaDesign) : es.OMIT,$args: argsObject(data, data.variants[0]?.values ?? []),- $argTypes: es.object(- data.props.map((prop) => [- prop.name,- es.object([- ['control', es.string('select')],- ['options', es.array(prop.options.map(es.string))]- ])- ])- ),+ $argTypes: argTypes(data),$render: framework.render}).bodyconst images = data.images.flatMap(diff --git a/packages/dom-css/tests/behaviours/args.test.ts b/packages/dom-css/tests/behaviours/args.test.tsnew file mode 100644index 000000000..0b0ce40f4--- /dev/null+++ b/packages/dom-css/tests/behaviours/args.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from 'bun:test'++import { behaviourArgs } from '#dom-css/behaviours/args'++import { emptyBehaviour, SceneGraph, withBehaviour } from '@open-pencil/scene-graph'++function toggleSet(options: string[]) {+ const graph = new SceneGraph()+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, {+ name: 'Toggle',+ componentPropertyDefinitions: [+ {+ id: 'pressed',+ name: 'Pressed',+ type: 'VARIANT',+ defaultValue: 'No',+ variantOptions: options+ }+ ]+ })+ graph.updateNode(set.id, {+ pluginData: withBehaviour(set, {+ ...emptyBehaviour('toggle'),+ booleans: { value: { propertyId: 'pressed', on: 'Yes', off: 'No' } }+ })+ })+ return { graph, set }+}++describe('behaviour args', () => {+ test('a boolean value drawn by an on/off variant property is a prop named as Reka names it', () => {+ const { graph, set } = toggleSet(['No', 'Yes'])+ expect([...(behaviourArgs(graph, set)?.booleans ?? [])]).toEqual([+ ['Pressed', { name: 'pressed', on: 'Yes', off: 'No' }]+ ])+ })++ test('a property with values beyond on and off stays a variant', () => {+ const { graph, set } = toggleSet(['No', 'Yes', 'Mixed'])+ expect(behaviourArgs(graph, set)?.booleans.size).toBe(0)+ })++ test('a component without a behaviour has no behaviour props', () => {+ const graph = new SceneGraph()+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, { name: 'Card' })+ expect(behaviourArgs(graph, set)).toBeNull()+ })+})diff --git a/packages/dom-css/tests/behaviours/controls.test.ts b/packages/dom-css/tests/behaviours/controls.test.tsindex 97d8b3c31..a9908b274 100644--- a/packages/dom-css/tests/behaviours/controls.test.ts+++ b/packages/dom-css/tests/behaviours/controls.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from 'bun:test'-import { behaviourControls, booleanOf, controlRoles } from '#dom-css/behaviours'+import { behaviourControls, booleanOf } from '#dom-css/behaviours/controls'+import { controlRoles } from '#dom-css/behaviours/roles'import { emptyBehaviour, SceneGraph, withBehaviour } from '@open-pencil/scene-graph'diff --git a/packages/dom-css/tests/export/storybook/export.test.ts b/packages/dom-css/tests/export/storybook/export.test.tsindex fede493e4..ebe800719 100644--- a/packages/dom-css/tests/export/storybook/export.test.ts+++ b/packages/dom-css/tests/export/storybook/export.test.ts@@ -5,7 +5,7 @@ import { join } from 'node:path'import { exportStorybook } from '#dom-css/index'-import { SceneGraph } from '@open-pencil/scene-graph'+import { emptyBehaviour, SceneGraph, withBehaviour } from '@open-pencil/scene-graph'function buttonGraph() {const graph = new SceneGraph()@@ -39,14 +39,14 @@ function buttonGraph() {interface Story {name: string- args: Record<string, string>+ args: Record<string, string | boolean>parameters?: { design: { name: string; type: string; url: string }[] }}interface StoryModule {default: {title: string- args: Record<string, string>+ args: Record<string, string | boolean>argTypes: Record<string, unknown>render: (args: object) => string}@@ -92,6 +92,74 @@ describe('exportStorybook', () => {expect(() => story.default.render({ Size: 'Huge' })).toThrow('Button has no variant ["Huge"]')})+ it('gives a component with a behaviour its own props instead of variant selects', async () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Library')+ const set = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Switch',+ componentPropertyDefinitions: [+ {+ id: 'state',+ name: 'State',+ type: 'VARIANT',+ defaultValue: 'Off',+ variantOptions: ['Off', 'On']+ },+ {+ id: 'interaction',+ name: 'Interaction',+ type: 'VARIANT',+ defaultValue: 'Default',+ variantOptions: ['Default', 'Hover', 'Disabled']+ }+ ]+ })+ // Each variant has its own width, so the rendered HTML shows which one a story picked.+ let width = 40+ for (const state of ['Off', 'On'])+ for (const interaction of ['Default', 'Hover', 'Disabled'])+ graph.createNode('COMPONENT', set.id, {+ name: `State=${state}, Interaction=${interaction}`,+ width: width++,+ height: 20,+ componentPropertyValues: { State: state, Interaction: interaction }+ })+ graph.updateNode(set.id, {+ pluginData: withBehaviour(set, {+ ...emptyBehaviour('switch'),+ booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } },+ states: { propertyId: 'interaction', rest: 'Default', hover: 'Hover', disabled: 'Disabled' }+ })+ })++ const story = await importStory(+ String((await exportStorybook(graph, { framework: 'html' }))[0]?.content)+ )+ expect(story.default.argTypes).toEqual({+ checked: { control: 'boolean' },+ Interaction: { table: { disable: true } },+ disabled: { control: 'boolean' }+ })+ expect(story.default.args).toEqual({ checked: false, Interaction: 'Default', disabled: false })+ const render = (args: object) => story.default.render(args)+ expect(render({ checked: true, Interaction: 'Default', disabled: false })).toContain(+ 'width: 43px'+ )+ expect(render({ checked: false, Interaction: 'Hover', disabled: false })).toContain(+ 'width: 41px'+ )+ expect(render({ checked: true, Interaction: 'Default', disabled: true })).toContain(+ 'width: 45px'+ )+ // Each state remains a story; a disabled one clears to the rest state.+ expect(storyExport(story, 'OnHover')).toMatchObject({+ args: { checked: true, Interaction: 'Hover', disabled: false }+ })+ expect(storyExport(story, 'OffDisabled')).toMatchObject({+ args: { checked: false, Interaction: 'Default', disabled: true }+ })+ })+it('groups slash-named components and keeps standalone ones apart', async () => {const graph = new SceneGraph()const page = graph.addPage('Icons')