Skip to content

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

feat(storybook): generate Reka UI components for Vue stories (#969)

Danila Poyarkov7e9e2933059d
diff --git a/AGENTS.md b/AGENTS.md
index 9eef4bfdb..defa9477a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -45,7 +45,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Across package/app boundaries import the owning package's public exports, never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus the subpaths listed in `packages/core/package.json`.
- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.
-- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`; a package's own tests use `#core-tests/*` and `#fig-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
+- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`; a package's own tests use `#core-tests/*`, `#fig-tests/*`, and `#dom-css-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
- Never drill with `../../`: one `../` to a sibling folder is fine, two or more means an alias. This holds in tests as much as in source — a test reaches its package's source through `#<pkg>/*` and its own helpers through `#<pkg>-tests/*`. `open-pencil/no-deep-parent-relative-imports` enforces it for imports and `open-pencil/no-deep-parent-relative-paths` for paths built from `import.meta`; a new test directory must be added to `lint:structure` so the rules reach it.
- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3337f2da3..16994637e 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 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 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`, a Button, Switch, Checkbox, Toggle, or Collapsible becomes a Reka UI component whose variants are compiled into state styles, with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
- Export 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/bun.lock b/bun.lock
index 94ada27d3..f414a6812 100644
--- a/bun.lock
+++ b/bun.lock
@@ -304,8 +304,11 @@
"@types/bun": "^1.3.14",
"@types/css-tree": "^3.2.0",
"@types/cssesc": "^3.0.2",
+ "reka-ui": "^2.10.5",
+ "storybook": "^10.6.1",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
+ "vue": "^3.5.43",
},
"peerDependencies": {
"@open-pencil/scene-graph": "workspace:*",
@@ -317,12 +320,14 @@
"dependencies": {
"@sveltejs/acorn-typescript": "^1.0.13",
"acorn": "^8.18.0",
+ "entities": "^8.0.0",
"esrap": "^2.3.11",
},
"devDependencies": {
"@types/bun": "^1.3.14",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
+ "vue": "^3.5.43",
},
},
"packages/fig": {
diff --git a/packages/docs/de/programmable/cli/exporting.md b/packages/docs/de/programmable/cli/exporting.md
index 09696a078..0a60eba5e 100644
--- a/packages/docs/de/programmable/cli/exporting.md
+++ b/packages/docs/de/programmable/cli/exporting.md
@@ -61,6 +61,8 @@ Jede Variante eines Komponentensatzes wird zu einer Story, und ihre Variantenmer
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.
+Mit `--framework vue` wird ein Komponentensatz, dessen Verhalten ein Button, Switch, Checkbox, Toggle oder Collapsible ist, stattdessen zu einer echten Komponente: `<Name>.vue` auf Basis von Reka UI. Seine Varianten werden zu einem Scoped-Stylesheet kompiliert, das auf die von Reka gesetzten Zustände reagiert (`data-state`, `data-disabled`, Hover und Fokus), sein Wert ist ein `v-model` wie `checked` oder `open`, und jedes weitere Variantenmerkmal ist ein Prop, das die Komponente als `data-*`-Attribut setzt. Die Storys rendern die Komponente, und eine Play-Funktion klickt das Control an und prüft seinen Zustand; das Storybook-Projekt braucht daher `reka-ui`.
+
Die Stories enthalten `parameters.design`-Einträge für [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs):
- **OpenPencil:** Liegt der Dokumentpfad im aktuellen Verzeichnis, ein [`openpencil://`-Link](../index#url-scheme), der das Dokument in der Desktop-Anwendung öffnet und die Variante auswählt, oder ihren Komponentensatz, wenn eine andere Ebene den Namen der Variante trägt. Das Schema adressiert Ebenen über ihren Namen; eine Story, deren Varianten- und Komponentenname beide von anderen Ebenen geteilt werden, erhält keinen Link.
diff --git a/packages/docs/es/programmable/cli/exporting.md b/packages/docs/es/programmable/cli/exporting.md
index 734f7de62..da0a8c88e 100644
--- a/packages/docs/es/programmable/cli/exporting.md
+++ b/packages/docs/es/programmable/cli/exporting.md
@@ -61,6 +61,8 @@ Cada variante de un conjunto de componentes se convierte en una historia y sus p
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.
+Con `--framework vue`, un conjunto de componentes cuyo comportamiento es un Button, Switch, Checkbox, Toggle o Collapsible se convierte en un componente real: `<Name>.vue` construido sobre Reka UI. Sus variantes se compilan en una hoja de estilos con ámbito que responde a los estados que fija Reka (`data-state`, `data-disabled`, hover y foco), su valor es un `v-model` como `checked` u `open`, y cada otra propiedad de variante es una prop que el componente fija como atributo `data-*`. Sus historias renderizan el componente y una función play hace clic en el control y comprueba su estado, por lo que el proyecto de Storybook necesita `reka-ui`.
+
Las historias incluyen entradas `parameters.design` para [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs):
- **OpenPencil:** cuando la ruta del documento está dentro del directorio actual, un [enlace `openpencil://`](../index#url-scheme) que abre el documento en la aplicación de escritorio y selecciona la variante, o su conjunto de componentes cuando otra capa comparte el nombre de la variante. El esquema direcciona las capas por nombre, así que una historia cuyos nombres de variante y de componente comparten otras capas no recibe enlace.
diff --git a/packages/docs/it/programmable/cli/exporting.md b/packages/docs/it/programmable/cli/exporting.md
index a4c7da564..76438c853 100644
--- a/packages/docs/it/programmable/cli/exporting.md
+++ b/packages/docs/it/programmable/cli/exporting.md
@@ -55,6 +55,8 @@ Ogni variante di un set di componenti diventa una storia e le sue proprietà di
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.
+Con `--framework vue`, un set di componenti il cui comportamento è un Button, Switch, Checkbox, Toggle o Collapsible diventa invece un componente vero: `<Name>.vue` basato su Reka UI. Le sue varianti sono compilate in un foglio di stile con scope che segue gli stati impostati da Reka (`data-state`, `data-disabled`, hover e focus), il suo valore è un `v-model` come `checked` o `open`, e ogni altra proprietà di variante è una prop che il componente imposta come attributo `data-*`. Le sue storie renderizzano il componente e una funzione play fa clic sul controllo e ne verifica lo stato, quindi il progetto Storybook ha bisogno di `reka-ui`.
+
Le storie includono voci `parameters.design` per [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs):
- **OpenPencil:** quando il percorso del documento è dentro la cartella corrente, un [link `openpencil://`](../index#url-scheme) che apre il documento nell’app desktop e seleziona la variante, o il suo set di componenti se un altro livello ha lo stesso nome della variante. Lo schema indirizza i livelli per nome, quindi una storia i cui nomi di variante e di componente sono entrambi condivisi con altri livelli non ottiene alcun link.
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index baa8ec848..10b08cba0 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -144,6 +144,8 @@ Each variant of a component set becomes a story, and its variant properties beco
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.
+With `--framework vue`, a component set whose behaviour is a Button, Switch, Checkbox, Toggle, or Collapsible becomes a real component instead: `<Name>.vue` built on Reka UI. Its variants are compiled into a scoped stylesheet keyed on the states Reka sets (`data-state`, `data-disabled`, hover, and focus), its value is a `v-model` such as `checked` or `open`, and every other variant property is a prop the component sets as a `data-*` attribute. Its stories render the component, and a play function clicks the control and checks its state, so the Storybook project needs `reka-ui` installed.
+
Stories carry `parameters.design` entries for [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs):
- **OpenPencil** — when the document path is inside the current directory, an [`openpencil://` link](../index#url-scheme) that opens the document in the desktop app and selects the variant, or its component set when another layer shares the variant's name. The scheme addresses layers by name, so a story whose variant and component names are both shared by other layers gets no link.
diff --git a/packages/dom-css/AGENTS.md b/packages/dom-css/AGENTS.md
index b5601c767..ec6017d94 100644
--- a/packages/dom-css/AGENTS.md
+++ b/packages/dom-css/AGENTS.md
@@ -12,5 +12,5 @@ Rules:
- Depend only on `@open-pencil/scene-graph` and `@open-pencil/emit`. Engine services such as web-font resolution come in as options; Core registers the HTML and Tailwind JSX formats (`packages/core/AGENTS.md`).
- Keep the `./export` entry browser-safe: load `node:*` modules and the headless CSS object model lazily inside the functions that need them, so the app never bundles them.
-- Build generated code as syntax trees with `@open-pencil/emit` (`es` for TypeScript modules, `jsx` for JSX), not string fragments.
+- Build generated code as syntax trees with `@open-pencil/emit` (`es` for TypeScript modules, `jsx` for JSX, `vue` for single-file components), not string fragments.
- Imported documents are untrusted: check Base64 with `js-base64`'s `isValid` before decoding.
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index dc4c1e5d5..7bbf1c467 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -8,7 +8,8 @@
"types": "./src/*",
"bun": "./src/*",
"default": "./dist/*"
- }
+ },
+ "#dom-css-tests/*": "./tests/*.ts"
},
"exports": {
".": {
@@ -74,8 +75,11 @@
"@types/bun": "^1.3.14",
"@types/css-tree": "^3.2.0",
"@types/cssesc": "^3.0.2",
+ "reka-ui": "^2.10.5",
+ "storybook": "^10.6.1",
"tsdown": "^0.22.14",
- "typescript": "~5.8.3"
+ "typescript": "~5.8.3",
+ "vue": "^3.5.43"
},
"dependencies": {
"@acemir/cssom": "^0.9.31",
diff --git a/packages/dom-css/src/behaviours/index.ts b/packages/dom-css/src/behaviours/index.ts
index 4ca3a132e..77c6e3035 100644
--- a/packages/dom-css/src/behaviours/index.ts
+++ b/packages/dom-css/src/behaviours/index.ts
@@ -6,5 +6,6 @@ export {
type ControlModel,
type StatesModel
} from './controls'
+export { BUTTON_RESET } from './reset'
export { controlRoles, groupOf, type ControlRole } from './roles'
export * from './states'
diff --git a/packages/dom-css/src/behaviours/reset.ts b/packages/dom-css/src/behaviours/reset.ts
new file mode 100644
index 000000000..433255e0b
--- /dev/null
+++ b/packages/dom-css/src/behaviours/reset.ts
@@ -0,0 +1,14 @@
+/**
+ * Element styles a native `<button>` adds, cleared so the design's own styles show. Preview
+ * and generated components render control roots and triggers as buttons for their semantics.
+ */
+export const BUTTON_RESET: Record<string, string> = {
+ border: 'none',
+ padding: '0',
+ margin: '0',
+ background: 'none',
+ font: 'inherit',
+ color: 'inherit',
+ 'text-align': 'inherit',
+ cursor: 'pointer'
+}
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
new file mode 100644
index 000000000..d1cba3707
--- /dev/null
+++ b/packages/dom-css/src/export/components/model.ts
@@ -0,0 +1,119 @@
+import { 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'
+import type { StateElement, StateStyles } from '#dom-css/behaviours/states/types'
+import { camelCase } from 'es-toolkit/string'
+
+import {
+ behaviourContract,
+ behaviourProperties,
+ layerPath,
+ readBehaviour,
+ slotPropertyId,
+ type Behaviour,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { identifierName } from '../storybook/names'
+
+/** Kinds generated as components so far; the rest keep static stories. */
+export const GENERATED_KINDS = ['button', 'switch', 'checkbox', 'toggle', 'collapsible'] as const
+export type GeneratedKind = (typeof GENERATED_KINDS)[number]
+
+/** A variant property the component takes as a prop and sets on its root as `data-*`. */
+export interface VariantProp {
+ /** The prop's identifier. */
+ name: string
+ /** The variant property it draws, which state styles name the condition after. */
+ property: string
+ options: string[]
+ default: string
+}
+
+/** One component generated from a component set with a behaviour. */
+export interface ComponentModel {
+ /** The component's identifier and file name. */
+ name: string
+ kind: GeneratedKind
+ styles: StateStyles
+ /** Each layer's part by the behaviour's part id; the root is `root`. */
+ parts: Map<StateElement, string>
+ /** The boolean the component binds with `v-model` or `onChange`: `checked`, `pressed`, `open`. */
+ model: string | null
+ /** Whether the set draws a disabled state, so the component takes `disabled`. */
+ disabled: boolean
+ props: VariantProp[]
+}
+
+/** Parts each kind renders as a native button, which the reset clears for the design. */
+const BUTTON_PARTS: Record<GeneratedKind, readonly string[]> = {
+ button: ['root'],
+ switch: ['root'],
+ checkbox: ['root'],
+ toggle: ['root'],
+ collapsible: ['trigger']
+}
+
+const isGenerated = (kind: Behaviour['kind']): kind is GeneratedKind =>
+ (GENERATED_KINDS as readonly string[]).includes(kind)
+
+/** Layer paths of the slot frames that draw each part, the same in every variant. */
+function partPaths(graph: SceneGraph, set: SceneNode, behaviour: Behaviour): Map<string, string> {
+ const partOfSlot = new Map(Object.entries(behaviour.parts).map(([part, slot]) => [slot, part]))
+ const paths = new Map<string, string>()
+ const visit = (variant: SceneNode, node: SceneNode) => {
+ const part = partOfSlot.get(slotPropertyId(node) ?? '')
+ if (part) paths.set(layerPath(graph, variant.id, node.id), part)
+ for (const child of graph.getChildren(node.id)) visit(variant, child)
+ }
+ for (const variant of graph.getChildren(set.id))
+ for (const child of graph.getChildren(variant.id)) visit(variant, child)
+ return paths
+}
+
+/**
+ * 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 function componentModel(graph: SceneGraph, set: SceneNode): ComponentModel | null {
+ const behaviour = readBehaviour(set)
+ if (!behaviour || !isGenerated(behaviour.kind)) return null
+ const styles = stateStyles(graph, set)
+ const args = behaviourArgs(graph, set)
+ if (!styles || !args) return null
+
+ const paths = partPaths(graph, set, behaviour)
+ const parts = new Map<StateElement, string>([[styles.root, 'root']])
+ for (const element of allElements(styles.root)) {
+ const part = paths.get(element.key)
+ if (part && behaviourContract(behaviour.kind).parts.some((item) => item.id === part))
+ parts.set(element, part)
+ }
+ for (const [element, part] of parts)
+ if (BUTTON_PARTS[behaviour.kind].includes(part))
+ element.base = { ...BUTTON_RESET, ...element.base }
+
+ const booleans = [...args.booleans.values()]
+ const model = booleans.find((arg) => arg.name !== 'disabled')?.name ?? null
+ const bound = new Set([...args.booleans.keys(), args.states?.property])
+ const props = behaviourProperties(graph, set)
+ .filter((definition) => definition.type === 'VARIANT' && !bound.has(definition.name))
+ .map((definition) => ({
+ name: camelCase(identifierName(definition.name, 'Prop')),
+ property: definition.name,
+ options: definition.variantOptions ?? [],
+ default: definition.defaultValue
+ }))
+ return {
+ name: identifierName(set.name, 'Component'),
+ kind: behaviour.kind,
+ styles,
+ parts,
+ model,
+ disabled:
+ booleans.some((arg) => arg.name === 'disabled') || args.states?.disabled !== undefined,
+ props
+ }
+}
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
new file mode 100644
index 000000000..348ad6180
--- /dev/null
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -0,0 +1,137 @@
+import { stateStylesToCSS } from '#dom-css/behaviours/states/css'
+import { layerClassNames, propAttribute } from '#dom-css/behaviours/states/names'
+import type { StateElement, StateNode } from '#dom-css/behaviours/states/types'
+import { compact } from 'es-toolkit/array'
+
+import { es, vue } from '@open-pencil/emit'
+
+import type { ComponentModel, GeneratedKind } from './model'
+
+/** The Reka UI components a kind renders, by part, and the prop its model binds. */
+const REKA: Record<
+ GeneratedKind,
+ { parts: Record<string, string>; model?: 'modelValue' | 'open' }
+> = {
+ button: { parts: {} },
+ switch: { parts: { root: 'SwitchRoot', thumb: 'SwitchThumb' }, model: 'modelValue' },
+ checkbox: {
+ parts: { root: 'CheckboxRoot', indicator: 'CheckboxIndicator' },
+ model: 'modelValue'
+ },
+ toggle: { parts: { root: 'Toggle' }, model: 'modelValue' },
+ collapsible: {
+ parts: {
+ root: 'CollapsibleRoot',
+ trigger: 'CollapsibleTrigger',
+ content: 'CollapsibleContent'
+ },
+ model: 'open'
+ }
+}
+
+const identifier = (name: string) => es.identifier(name)
+
+/** `disabled || undefined`, so a native button sets `data-disabled` only while disabled. */
+const DISABLED_FLAG = es.parseExpression('disabled || undefined')
+
+function rootAttributes(component: ComponentModel, native: boolean): vue.VueAttribute[] {
+ const reka = REKA[component.kind]
+ const model = component.model && reka.model
+ return [
+ ...(native ? [vue.attribute('type', 'button')] : []),
+ ...(model
+ ? [vue.model(identifier(component.model ?? ''), model === 'open' ? 'open' : undefined)]
+ : []),
+ ...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : []),
+ // Reka sets `data-disabled` on its own roots; a native button needs it for the state styles.
+ ...(component.disabled && native ? [vue.bound('data-disabled', DISABLED_FLAG)] : []),
+ ...component.props.map((prop) => vue.bound(propAttribute(prop.property), identifier(prop.name)))
+ ]
+}
+
+function templateNode(
+ node: StateNode,
+ component: ComponentModel,
+ classes: Map<StateElement, string>,
+ used: Set<string>
+): vue.VueNode {
+ if (node.type === 'text') return vue.text(node.text)
+ const part = component.parts.get(node)
+ const reka = part ? REKA[component.kind].parts[part] : undefined
+ if (reka) used.add(reka)
+ const native = part === 'root' && !reka
+ const className = compact([node.attrs.class, classes.get(node)]).join(' ')
+ const attributes = [
+ ...Object.entries(node.attrs)
+ .filter(([name]) => name !== 'class')
+ .map(([name, value]) => vue.attribute(name, value)),
+ vue.attribute('class', className),
+ ...(part === 'root' ? rootAttributes(component, native) : [])
+ ]
+ const tag = reka ?? (native ? 'button' : node.tagName)
+ return vue.element(
+ tag,
+ attributes,
+ node.children.map((child) => templateNode(child, component, classes, used))
+ )
+}
+
+function propsType(component: ComponentModel): es.SyntaxNode {
+ const members: [string, es.SyntaxNode, boolean][] = component.props.map((prop) => [
+ prop.name,
+ es.stringUnionType(prop.options),
+ true
+ ])
+ if (component.disabled) members.unshift(['disabled', es.parseType('boolean'), true])
+ return es.objectType(members)
+}
+
+function propsDefaults(component: ComponentModel): es.SyntaxNode {
+ return es.object([
+ ...(component.disabled ? [['disabled', es.parseExpression('false')] as const] : []),
+ ...component.props.map((prop) => [prop.name, es.string(prop.default)] as const)
+ ])
+}
+
+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')
+ }
+ ]
+ : []
+ const props =
+ component.disabled || component.props.length > 0
+ ? es.fill(PROPS, { $Props: propsType(component), $defaults: propsDefaults(component) }).body
+ : []
+ const model = component.model
+ ? es.fill(MODEL, { $model: identifier(component.model), $name: es.string(component.model) })
+ .body
+ : []
+ return { type: 'Program', sourceType: 'module', body: [...imports, ...props, ...model] }
+}
+
+/**
+ * A component as a Vue single-file component on Reka UI: its variants' state styles in a
+ * scoped stylesheet, its parts as Reka components, and its props from the behaviour and its
+ * other variant properties.
+ */
+export async function vueComponent(component: ComponentModel): Promise<string> {
+ const classes = layerClassNames(component.styles)
+ const used = new Set<string>()
+ const template = templateNode(component.styles.root, component, classes, used)
+ const { css } = await stateStylesToCSS(component.styles)
+ return vue.printComponent({ script: script(component, used), template, style: css })
+}
diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.ts
new file mode 100644
index 000000000..8a38d6fe6
--- /dev/null
+++ b/packages/dom-css/src/export/storybook/component.ts
@@ -0,0 +1,154 @@
+import dedent from 'dedent'
+import { compact } from 'es-toolkit/array'
+
+import { es } from '@open-pencil/emit'
+
+import type { ComponentModel, GeneratedKind } from '../components/model'
+import { claimName, identifierName } from './names'
+
+/** Tells readers the file is generated; nothing parses it. */
+const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overwritten.'
+
+const MODULE = es.parseModule(dedent`
+ import type { Meta, StoryObj } from '@storybook/vue3-vite'
+ import { expect } from 'storybook/test'
+
+ import $Component from '$path'
+
+ const meta = {
+ title: $title,
+ component: $Component,
+ parameters: $parameters,
+ args: $args,
+ argTypes: $argTypes
+ } satisfies Meta<typeof $Component>
+
+ export default meta
+ type Story = StoryObj<typeof meta>
+`)
+
+const STORY = es.parseModule(`export const $name: Story = $story`)
+
+/**
+ * What clicking a control does, as Reka marks it: the role to find it by, the element that
+ * changes, and the `data-state` it ends in.
+ */
+const INTERACTIONS: Partial<Record<GeneratedKind, { role: string; state: string }>> = {
+ switch: { role: 'switch', state: 'checked' },
+ checkbox: { role: 'checkbox', state: 'checked' },
+ toggle: { role: 'button', state: 'on' },
+ collapsible: { role: 'button', state: 'open' }
+}
+
+const PLAY = es.parseExpression(dedent`
+ async ({ canvas, userEvent }) => {
+ const control = canvas.getByRole($role)
+ await userEvent.click(control)
+ await expect(control).toHaveAttribute('data-state', $state)
+ }
+`)
+
+export interface ComponentStoriesData {
+ title: string
+ component: ComponentModel
+ /** The component's import path next to the stories, such as `./Switch.vue`. */
+ path: string
+ /** Design links for the whole file, as `parameters.design` entries. */
+ design: { name: string; type: string; url: string }[]
+}
+
+const FALSE = es.parseExpression('false')
+const TRUE = es.parseExpression('true')
+
+function restArgs(component: ComponentModel): [string, es.SyntaxNode][] {
+ return [
+ ...(component.model ? [[component.model, FALSE] as [string, es.SyntaxNode]] : []),
+ ...(component.disabled ? [['disabled', FALSE] as [string, es.SyntaxNode]] : []),
+ ...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, es.string(prop.default)])
+ ]
+}
+
+function argTypes(component: ComponentModel): es.SyntaxNode {
+ const boolean = es.object([['control', es.string('boolean')]])
+ return es.object([
+ ...(component.model ? [[component.model, boolean] as [string, es.SyntaxNode]] : []),
+ ...(component.disabled ? [['disabled', boolean] as [string, es.SyntaxNode]] : []),
+ ...component.props.map((prop): [string, es.SyntaxNode] => [
+ prop.name,
+ es.object([
+ ['control', es.string('select')],
+ ['options', es.array(prop.options.map(es.string))]
+ ])
+ ])
+ ])
+}
+
+/** A story per state worth seeing: at rest, each boolean on, disabled, and each prop value. */
+function stories(component: ComponentModel): { name: string; story: es.SyntaxNode }[] {
+ const taken = new Set<string>()
+ const story = (label: string, args: [string, es.SyntaxNode][], play?: es.SyntaxNode) => ({
+ name: claimName(identifierName(label, 'Story'), taken),
+ story: es.object([
+ ...(args.length > 0 ? [['args', es.object(args)] as [string, es.SyntaxNode]] : []),
+ ...(play ? [['play', play] as [string, es.SyntaxNode]] : [])
+ ])
+ })
+ const interaction = INTERACTIONS[component.kind]
+ return [
+ story(
+ 'Default',
+ [],
+ interaction &&
+ es.fill(PLAY, { $role: es.string(interaction.role), $state: es.string(interaction.state) })
+ ),
+ ...(component.model ? [story(component.model, [[component.model, TRUE]])] : []),
+ ...(component.disabled ? [story('Disabled', [['disabled', TRUE]])] : []),
+ ...component.props.flatMap((prop) =>
+ prop.options
+ .filter((option) => option !== prop.default)
+ .map((option) => story(option, [[prop.name, es.string(option)]]))
+ )
+ ]
+}
+
+/** CSF3 stories for a generated Vue component, with a play function that operates it. */
+export function printComponentStories(data: ComponentStoriesData): string {
+ const { component } = data
+ const parameters =
+ data.design.length > 0
+ ? es.object([
+ [
+ 'design',
+ es.array(
+ data.design.map((entry) =>
+ es.object([
+ ['name', es.string(entry.name)],
+ ['type', es.string(entry.type)],
+ ['url', es.string(entry.url)]
+ ])
+ )
+ )
+ ]
+ ])
+ : es.OMIT
+ const body = es.fill(MODULE, {
+ $Component: es.identifier(component.name),
+ $path: es.string(data.path),
+ $title: es.string(data.title),
+ $parameters: parameters,
+ $args: es.object(restArgs(component)),
+ $argTypes: argTypes(component)
+ }).body
+ const exported = stories(component).flatMap(
+ (item) => es.fill(STORY, { $name: es.identifier(item.name), $story: item.story }).body
+ )
+ // Only a control with a play function uses `expect`.
+ const [types, expectImport, ...rest] = body
+ const imports = INTERACTIONS[component.kind] ? [types, expectImport] : [types]
+ const module = es.printModule({
+ type: 'Program',
+ sourceType: 'module',
+ body: compact([...imports, ...rest, ...exported])
+ })
+ return `${HEADER}\n${module}\n`
+}
diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.ts
index e6442d8e5..d99d91cca 100644
--- a/packages/dom-css/src/export/storybook/export.ts
+++ b/packages/dom-css/src/export/storybook/export.ts
@@ -1,8 +1,11 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { ExportHTMLFile } from '../bundle'
+import { componentModel } from '../components/model'
+import { vueComponent } from '../components/vue'
import { serializeHTML } from '../html'
import { sceneNodeToDesignDocument } from '../projection'
+import { printComponentStories } from './component'
import { collectGroups, type StoryGroup } from './groups'
import { printStoryModule, type StoryDesign, type StorybookFramework } from './module'
import { claimName, identifierName, storyId } from './names'
@@ -42,7 +45,10 @@ interface ModuleContext {
images: string[]
}
-function designLink(context: ModuleContext, ...candidates: (string | undefined)[]): StoryDesign[] {
+function designLink(
+ context: Pick<ModuleContext, 'linkPath' | 'uniqueNames'>,
+ ...candidates: (string | undefined)[]
+): StoryDesign[] {
const node = candidates.find((name) => name !== undefined && context.uniqueNames.has(name))
if (!context.linkPath || !node) return []
const url = `openpencil://open?file=${encodeURIComponent(context.linkPath)}&node=${encodeURIComponent(node)}`
@@ -117,6 +123,27 @@ export async function exportStorybook(
})
if (options.pageId && page.id !== options.pageId) continue
+ const component = framework === 'vue' && group.set ? componentModel(graph, group.set) : null
+ if (component) {
+ // The component is imported by the file's name, so the two always match.
+ component.name = file
+ add(page, `${file}.vue`, await vueComponent(component))
+ const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)
+ add(
+ page,
+ `${file}.stories.ts`,
+ printComponentStories({
+ title: group.title,
+ component,
+ path: `./${file}.vue`,
+ 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`) : []
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index 17047e07f..7c76c868f 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -21,6 +21,8 @@ export interface StoryGroup {
variants: StoryVariant[]
/** Layer the story file links to, when the group has a layer of its own. */
linkNode?: string
+ /** The component set the group shows, which may generate a component of its own. */
+ set?: SceneNode
}
function isExported(node: SceneNode): boolean {
@@ -73,7 +75,8 @@ function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode):
name: set.name,
props,
variants,
- linkNode: set.name
+ linkNode: set.name,
+ set
})
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index cbcd7e0fb..5f7c06000 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -59,7 +59,8 @@ export function switchSet() {
{
...emptyBehaviour('switch'),
booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } },
- states: { propertyId: 'interaction', rest: 'Default', hover: 'Hover', disabled: 'Disabled' }
+ states: { propertyId: 'interaction', rest: 'Default', hover: 'Hover', disabled: 'Disabled' },
+ parts: { thumb: 'thumb-slot' }
},
(graph, variant, { State, Interaction }) => {
const offFills = Interaction === 'Hover' ? COLORS.hover : COLORS.off
@@ -67,6 +68,7 @@ export function switchSet() {
graph.updateNode(variant, { fills, opacity: Interaction === 'Disabled' ? 0.5 : 1 })
graph.createNode('FRAME', variant, {
name: 'Thumb',
+ componentPropertyReferences: [{ propertyId: 'thumb-slot', field: 'SLOT_CONTENT' }],
x: State === 'On' ? 20 : 2,
y: 2,
width: 18,
@@ -134,3 +136,34 @@ export function buttonSet() {
({ Size, Interaction }) => Size === 'Large' && Interaction === 'Hover'
)
}
+
+/** A collapsible whose content shows only when open. */
+export function collapsibleSet() {
+ const slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]
+ return componentSet(
+ 'Disclosure',
+ { Open: ['No', 'Yes'] },
+ {
+ ...emptyBehaviour('collapsible'),
+ booleans: { open: { propertyId: 'open', on: 'Yes', off: 'No' } },
+ parts: { trigger: 'trigger-slot', content: 'content-slot' }
+ },
+ (graph, variant, { Open }) => {
+ const trigger = graph.createNode('FRAME', variant, {
+ name: 'Trigger',
+ componentPropertyReferences: slot('trigger-slot'),
+ width: 40,
+ height: 10
+ })
+ graph.createNode('TEXT', trigger.id, { name: 'Title', text: 'Details' })
+ if (Open === 'Yes')
+ graph.createNode('FRAME', variant, {
+ name: 'Content',
+ componentPropertyReferences: slot('content-slot'),
+ y: 12,
+ width: 40,
+ height: 10
+ })
+ }
+ )
+}
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
new file mode 100644
index 000000000..d8fcd7567
--- /dev/null
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -0,0 +1,97 @@
+import { afterAll, describe, expect, test } from 'bun:test'
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+
+import { buttonSet, collapsibleSet, switchSet } from '#dom-css-tests/behaviours/fixtures'
+import { exportStorybook } from '#dom-css/index'
+import { createSSRApp, h, type Component } from 'vue'
+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 output = await mkdtemp(join(tmpdir(), 'open-pencil-vue-'))
+await mkdir(join(output, 'node_modules'))
+for (const name of APP_PACKAGES)
+ await symlink(
+ dirname(Bun.resolveSync(`${name}/package.json`, import.meta.dir)),
+ join(output, 'node_modules', name)
+ )
+afterAll(() => rm(output, { recursive: true, force: true }))
+
+/** Exports a fixture's set to Vue stories and loads the component and stories it writes. */
+async function generate(fixture: ReturnType<typeof switchSet>) {
+ const files = await exportStorybook(fixture.graph, { framework: 'vue' })
+ 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)
+ 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(
+ join(folder, `${name}.stories.ts`)
+ )
+ return { files, component: component.default, stories }
+}
+
+function render(component: Component, props: Record<string, unknown> = {}): Promise<string> {
+ return renderToString(createSSRApp({ render: () => h(component, props) }))
+}
+
+describe('generated Vue components', () => {
+ test('a switch is a Reka switch whose state follows its model', async () => {
+ const { files, component } = await generate(switchSet())
+ expect(files.map((file) => file.path).sort()).toEqual(['Switch.stories.ts', 'Switch.vue'])
+ const off = await render(component)
+ expect(off).toContain('role="switch"')
+ expect(off).toContain('data-state="unchecked"')
+ expect(off).toMatch(/class="switch"/)
+ const on = await render(component, { checked: true })
+ expect(on).toContain('data-state="checked"')
+ expect(on).toContain('aria-checked="true"')
+ expect(await render(component, { disabled: true })).toContain('data-disabled')
+ })
+
+ test('a collapsible shows its content when open', async () => {
+ const { component } = await generate(collapsibleSet())
+ const content = (html: string) => /<div class="disclosure__content"[^>]*>/.exec(html)?.[0] ?? ''
+ // Reka keeps closed content in the document, hidden; the state styles key on the root.
+ const closed = await render(component)
+ expect(content(closed)).toContain(' hidden ')
+ const open = await render(component, { open: true })
+ expect(open).toMatch(/^<div data-state="open" class="disclosure"/)
+ expect(content(open)).not.toContain(' hidden ')
+ })
+
+ test('a button sets its other variant properties as data attributes', async () => {
+ const { component } = await generate(buttonSet())
+ const large = await render(component, { size: 'Large' })
+ expect(large).toMatch(/^<button[^>]*type="button"/)
+ expect(large).toContain('data-size="Large"')
+ })
+})
+
+describe('generated Vue stories', () => {
+ test('show each state and operate the control', async () => {
+ const { component, stories } = await generate(switchSet())
+ const meta = stories.default as { component: Component; args: Record<string, unknown> }
+ expect(meta.component).toBe(component)
+ expect(meta.args).toEqual({ checked: false, disabled: false })
+ // A module lists its exports alphabetically, not in the order they're written.
+ expect(Object.keys(stories).filter((key) => key !== 'default')).toEqual([
+ 'Checked',
+ 'Default',
+ 'Disabled'
+ ])
+ expect(stories.Checked?.args).toEqual({ checked: true })
+ expect(typeof stories.Default?.play).toBe('function')
+ })
+})
diff --git a/packages/emit/README.md b/packages/emit/README.md
index 5d71eb877..8647667af 100644
--- a/packages/emit/README.md
+++ b/packages/emit/README.md
@@ -27,3 +27,12 @@ const module = es.fill(es.parseModule("export const title = '$title'"), {
})
es.printModule(module) // export const title = 'Checkout';
```
+
+`vue` builds templates and single-file components. Text and attribute values are escaped as HTML with `entities`, and text also writes `{` as an entity, since Vue reads `{{` as an interpolation before it decodes entities:
+
+```ts
+import { es, vue } from '@open-pencil/emit'
+
+const template = vue.element('SwitchRoot', [vue.attribute('class', 'switch'), vue.model(es.identifier('checked'))])
+vue.printTemplate(template) // <SwitchRoot class="switch" v-model="checked" />
+```
diff --git a/packages/emit/package.json b/packages/emit/package.json
index d302b72a2..ae4a7c77b 100644
--- a/packages/emit/package.json
+++ b/packages/emit/package.json
@@ -37,12 +37,14 @@
"dependencies": {
"@sveltejs/acorn-typescript": "^1.0.13",
"acorn": "^8.18.0",
+ "entities": "^8.0.0",
"esrap": "^2.3.11"
},
"devDependencies": {
"@types/bun": "^1.3.14",
"tsdown": "^0.22.14",
- "typescript": "~5.8.3"
+ "typescript": "~5.8.3",
+ "vue": "^3.5.43"
},
"repository": {
"type": "git",
diff --git a/packages/emit/src/estree.ts b/packages/emit/src/estree.ts
index a04f2ba61..a987401c2 100644
--- a/packages/emit/src/estree.ts
+++ b/packages/emit/src/estree.ts
@@ -90,6 +90,16 @@ export function printModule(program: SyntaxNode): string {
return print(program, ts(), { indent: ' ' }).code
}
+/** One expression, as a template binding or another host language embeds it. */
+export function printExpression(expression: SyntaxNode): string {
+ const program = {
+ type: 'Program',
+ sourceType: 'module',
+ body: [{ type: 'ExpressionStatement', expression }]
+ }
+ return printModule(program).trim().replace(/;$/, '')
+}
+
export const identifier = (name: string): SyntaxNode => ({ type: 'Identifier', name })
export const string = (value: string): SyntaxNode => ({ type: 'Literal', value })
@@ -129,13 +139,15 @@ export function stringUnionType(values: string[]): SyntaxNode {
: { type: 'TSUnionType', types: literals }
}
-export function objectType(entries: [string, SyntaxNode][]): SyntaxNode {
+/** An object type; a member whose third element is `true` is optional. */
+export function objectType(entries: [string, SyntaxNode, boolean?][]): SyntaxNode {
return {
type: 'TSTypeLiteral',
- members: entries.map(([key, typeAnnotation]) => ({
+ members: entries.map(([key, typeAnnotation, optional = false]) => ({
type: 'TSPropertySignature',
key: propertyKey(key),
computed: false,
+ optional,
typeAnnotation: { type: 'TSTypeAnnotation', typeAnnotation }
}))
}
diff --git a/packages/emit/src/index.ts b/packages/emit/src/index.ts
index 7ffd8569d..6282faac1 100644
--- a/packages/emit/src/index.ts
+++ b/packages/emit/src/index.ts
@@ -1,3 +1,4 @@
export * as es from './estree'
export * as jsx from './jsx'
+export * as vue from './vue'
export type { SyntaxNode } from './estree'
diff --git a/packages/emit/src/vue.ts b/packages/emit/src/vue.ts
new file mode 100644
index 000000000..90b05ed24
--- /dev/null
+++ b/packages/emit/src/vue.ts
@@ -0,0 +1,115 @@
+import { escapeAttribute, escapeText } from 'entities'
+
+import { printExpression, printModule, type SyntaxNode } from './estree'
+
+/**
+ * Text and attribute values are escaped as HTML by `entities`. Vue also reads `{{` as an
+ * interpolation before it decodes entities, so text writes `{` as one too and a design's text
+ * can never become template syntax.
+ */
+const templateText = (value: string) => escapeText(value).replaceAll('{', '&#123;')
+
+export type VueAttribute =
+ | { type: 'static'; name: string; value: string }
+ /** `:name="expression"` */
+ | { type: 'bound'; name: string; expression: SyntaxNode }
+ /** `v-model="expression"`, or `v-model:argument` */
+ | { type: 'model'; argument?: string; expression: SyntaxNode }
+
+export interface VueElement {
+ type: 'element'
+ tag: string
+ attributes: VueAttribute[]
+ children: VueNode[]
+}
+
+export interface VueText {
+ type: 'text'
+ value: string
+}
+
+export type VueNode = VueElement | VueText
+
+export const attribute = (name: string, value: string): VueAttribute => ({
+ type: 'static',
+ name,
+ value
+})
+
+export const bound = (name: string, expression: SyntaxNode): VueAttribute => ({
+ type: 'bound',
+ name,
+ expression
+})
+
+export const model = (expression: SyntaxNode, argument?: string): VueAttribute => ({
+ type: 'model',
+ argument,
+ expression
+})
+
+export const element = (
+ tag: string,
+ attributes: VueAttribute[] = [],
+ children: VueNode[] = []
+): VueElement => ({ type: 'element', tag, attributes, children })
+
+export const text = (value: string): VueText => ({ type: 'text', value })
+
+function printAttribute(item: VueAttribute): string {
+ if (item.type === 'static') return `${item.name}="${escapeAttribute(item.value)}"`
+ const value = escapeAttribute(printExpression(item.expression))
+ if (item.type === 'bound') return `:${item.name}="${value}"`
+ return `${item.argument ? `v-model:${item.argument}` : 'v-model'}="${value}"`
+}
+
+/** Markup with nothing added around it, as text content needs. */
+function printInline(node: VueNode): string {
+ if (node.type === 'text') return templateText(node.value)
+ const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')
+ if (node.children.length === 0) return `<${open} />`
+ return `<${open}>${node.children.map(printInline).join('')}</${node.tag}>`
+}
+
+function printNode(node: VueNode, depth: number): string {
+ const indent = ' '.repeat(depth)
+ // Vue renders whitespace between text and elements as a space, so an element with text
+ // content keeps its children on its own line, exactly as given.
+ if (node.type === 'text' || node.children.some((child) => child.type === 'text'))
+ return `${indent}${printInline(node)}`
+ const open = [node.tag, ...node.attributes.map(printAttribute)].join(' ')
+ if (node.children.length === 0) return `${indent}<${open} />`
+ const children = node.children.map((child) => printNode(child, depth + 1))
+ return [`${indent}<${open}>`, ...children, `${indent}</${node.tag}>`].join('\n')
+}
+
+/** A template's markup, one element per line. */
+export function printTemplate(root: VueNode): string {
+ return printNode(root, 0)
+}
+
+export interface VueComponent {
+ /** The `<script setup lang="ts">` body, a TypeScript program from `es`. */
+ script: SyntaxNode
+ template: VueNode
+ /** Stylesheet text for a `<style scoped>` block. */
+ style?: string
+}
+
+/**
+ * A raw block's content, which ends at the first closing tag for its element. Strings in the
+ * script and values in the stylesheet can come from an imported design, so a closing tag in
+ * them is written `<\\/`, which JavaScript strings and CSS both read back as `</`.
+ */
+const rawBlock = (tag: string, content: string) =>
+ `<${tag}>\n${content.trim().replace(/<\/(?=script|style)/gi, '<\\/')}\n</${tag.split(' ')[0]}>`
+
+/** A single-file component: script setup, template, and scoped style. */
+export function printComponent({ script, template, style }: VueComponent): string {
+ const blocks = [
+ rawBlock('script setup lang="ts"', printModule(script)),
+ `<template>\n${printNode(template, 1)}\n</template>`,
+ ...(style ? [rawBlock('style scoped', style)] : [])
+ ]
+ return `${blocks.join('\n\n')}\n`
+}
diff --git a/packages/emit/tests/vue.test.ts b/packages/emit/tests/vue.test.ts
new file mode 100644
index 000000000..941b4ff63
--- /dev/null
+++ b/packages/emit/tests/vue.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, test } from 'bun:test'
+
+import { es, vue } from '#emit/index'
+import { createSSRApp } from 'vue'
+import { parse } from 'vue/compiler-sfc'
+import { renderToString } from 'vue/server-renderer'
+
+/** Renders printed markup with Vue's own template compiler and server renderer. */
+async function render(node: vue.VueNode, data: Record<string, unknown> = {}): Promise<string> {
+ const app = createSSRApp({ template: vue.printTemplate(node), data: () => data })
+ return renderToString(app)
+}
+
+describe('Vue templates', () => {
+ test.each(['{{ evil }}', '<b>bold</b>', 'Fish &amp; chips', 'a { b } c'])(
+ 'keep text %p as written',
+ async (value) => {
+ const html = await render(vue.element('p', [], [vue.text(value)]), { evil: 'injected' })
+ const escaped = value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+ expect(html).toBe(`<p>${escaped}</p>`)
+ }
+ )
+
+ test('keep attribute values with quotes and entities as written', async () => {
+ const value = 'say "hi" &amp; leave'
+ const html = await render(vue.element('div', [vue.attribute('title', value)]))
+ expect(html).toBe('<div title="say &quot;hi&quot; &amp;amp; leave"></div>')
+ })
+
+ test('bind expressions, including string literals with quotes', async () => {
+ const node = vue.element('div', [
+ vue.bound('data-size', es.identifier('size')),
+ vue.bound('title', es.string('a "quoted" title'))
+ ])
+ expect(vue.printTemplate(node)).toBe(
+ `<div :data-size="size" :title="'a &quot;quoted&quot; title'" />`
+ )
+ expect(await render(node, { size: 'Large' })).toBe(
+ '<div data-size="Large" title="a &quot;quoted&quot; title"></div>'
+ )
+ })
+
+ test('print v-model with and without an argument', () => {
+ const node = vue.element('Toggle', [
+ vue.model(es.identifier('pressed')),
+ vue.model(es.identifier('open'), 'open')
+ ])
+ expect(vue.printTemplate(node)).toBe('<Toggle v-model="pressed" v-model:open="open" />')
+ })
+
+ test('print a component with script setup, nested template, and scoped style', () => {
+ const script = es.parseModule("import { SwitchRoot } from 'reka-ui'")
+ const template = vue.element(
+ 'SwitchRoot',
+ [vue.attribute('class', 'switch')],
+ [vue.element('span', [], [vue.text('On')])]
+ )
+ expect(vue.printComponent({ script, template, style: '.switch { width: 40px; }' })).toBe(
+ [
+ '<script setup lang="ts">',
+ "import { SwitchRoot } from 'reka-ui';",
+ '</script>',
+ '',
+ '<template>',
+ ' <SwitchRoot class="switch">',
+ ' <span>On</span>',
+ ' </SwitchRoot>',
+ '</template>',
+ '',
+ '<style scoped>',
+ '.switch { width: 40px; }',
+ '</style>',
+ ''
+ ].join('\n')
+ )
+ })
+
+ test('keep text next to elements without adding a space', async () => {
+ const node = vue.element(
+ 'div',
+ [],
+ [vue.element('p', [], [vue.text('Hello'), vue.element('strong', [], [vue.text('!')])])]
+ )
+ expect(await render(node)).toBe('<div><p>Hello<strong>!</strong></p></div>')
+ })
+
+ test('keep closing tags in script strings and style values inside their blocks', () => {
+ const script = es.fill(es.parseModule('const label = $label'), {
+ $label: es.string('</script> and </STYLE>')
+ })
+ const source = vue.printComponent({
+ script,
+ template: vue.element('div'),
+ style: '.label::after { content: "</style>"; }'
+ })
+ const { descriptor, errors } = parse(source)
+ expect(errors).toEqual([])
+ expect(descriptor.scriptSetup?.content).toContain('<\\/script> and <\\/STYLE>')
+ expect(descriptor.styles.map((style) => style.content.trim())).toEqual([
+ '.label::after { content: "<\\/style>"; }'
+ ])
+ expect(descriptor.template?.content.trim()).toBe('<div />')
+ })
+})
diff --git a/packages/vue/src/canvas/islands/render.ts b/packages/vue/src/canvas/islands/render.ts
index 2c0f9eacb..fe67cc603 100644
--- a/packages/vue/src/canvas/islands/render.ts
+++ b/packages/vue/src/canvas/islands/render.ts
@@ -1,10 +1,11 @@
import { h, type VNode } from 'vue'
-import type {
- ControlModel,
- ControlRole,
- DesignElement,
- DesignNode
+import {
+ BUTTON_RESET,
+ type ControlModel,
+ type ControlRole,
+ type DesignElement,
+ type DesignNode
} from '@open-pencil/dom-css/export'
import { layerPath, type SceneGraph } from '@open-pencil/scene-graph'
@@ -30,18 +31,6 @@ export interface ElementOverride {
children?: () => (VNode | string)[]
}
-/** Element styles a native `<button>` adds, cleared so the design's own styles show. */
-const BUTTON_RESET: Record<string, string> = {
- border: 'none',
- padding: '0',
- margin: '0',
- background: 'none',
- font: 'inherit',
- color: 'inherit',
- 'text-align': 'inherit',
- cursor: 'pointer'
-}
-
/** Render an element as the design draws it, with a role's changes applied. */
export function renderElement(
context: IslandRenderContext,
diff --git a/tests/e2e/dom-css/vue-components.spec.ts b/tests/e2e/dom-css/vue-components.spec.ts
new file mode 100644
index 000000000..dd8d50a8c
--- /dev/null
+++ b/tests/e2e/dom-css/vue-components.spec.ts
@@ -0,0 +1,183 @@
+import { mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import vue from '@vitejs/plugin-vue'
+import { createServer, type ViteDevServer } from 'vite'
+
+import { exportStorybook } from '@open-pencil/dom-css'
+import {
+ emptyBehaviour,
+ SceneGraph,
+ withBehaviour,
+ type Behaviour,
+ type ComponentPropertyReference
+} from '@open-pencil/scene-graph'
+
+import { expect, test } from '../fixtures'
+
+const fill = (r: number, g: number, b: number) => [
+ { type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }
+]
+const slot = (propertyId: string): ComponentPropertyReference[] => [
+ { propertyId, field: 'SLOT_CONTENT' }
+]
+
+/** A set with a variant per value of one property, drawn by `draw`, and a behaviour. */
+function controlSet(
+ name: string,
+ property: { name: string; values: string[] },
+ behaviour: Behaviour,
+ draw: (graph: SceneGraph, variantId: string, value: string) => void
+): SceneGraph {
+ const graph = new SceneGraph()
+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, {
+ name,
+ componentPropertyDefinitions: [
+ {
+ id: 'value',
+ name: property.name,
+ type: 'VARIANT',
+ defaultValue: property.values[0] ?? '',
+ variantOptions: property.values
+ }
+ ]
+ })
+ for (const value of property.values) {
+ const variant = graph.createNode('COMPONENT', set.id, {
+ name: `${property.name}=${value}`,
+ componentPropertyValues: { [property.name]: value },
+ width: 40,
+ height: 22
+ })
+ draw(graph, variant.id, value)
+ }
+ graph.updateNode(set.id, { pluginData: withBehaviour(set, behaviour) })
+ return graph
+}
+
+function switchGraph(): SceneGraph {
+ return controlSet(
+ 'Switch',
+ { name: 'State', values: ['Off', 'On'] },
+ {
+ ...emptyBehaviour('switch'),
+ booleans: { value: { propertyId: 'value', on: 'On', off: 'Off' } },
+ parts: { thumb: 'thumb' }
+ },
+ (graph, variantId, value) => {
+ graph.updateNode(variantId, {
+ fills: value === 'On' ? fill(0.3, 0.27, 0.9) : fill(0.8, 0.84, 0.88)
+ })
+ graph.createNode('FRAME', variantId, {
+ name: 'Thumb',
+ componentPropertyReferences: slot('thumb'),
+ x: value === 'On' ? 20 : 2,
+ y: 2,
+ width: 18,
+ height: 18,
+ fills: fill(1, 1, 1)
+ })
+ }
+ )
+}
+
+function disclosureGraph(): SceneGraph {
+ return controlSet(
+ 'Disclosure',
+ { name: 'Open', values: ['No', 'Yes'] },
+ {
+ ...emptyBehaviour('collapsible'),
+ booleans: { open: { propertyId: 'value', on: 'Yes', off: 'No' } },
+ parts: { trigger: 'trigger', content: 'content' }
+ },
+ (graph, variantId, value) => {
+ graph.createNode('FRAME', variantId, {
+ name: 'Trigger',
+ componentPropertyReferences: slot('trigger'),
+ width: 40,
+ height: 10
+ })
+ if (value === 'Yes')
+ graph.createNode('FRAME', variantId, {
+ name: 'Content',
+ componentPropertyReferences: slot('content'),
+ y: 12,
+ width: 40,
+ height: 10,
+ fills: fill(0.3, 0.27, 0.9)
+ })
+ }
+ )
+}
+
+/**
+ * Exports `graph` to Vue stories, mounts the generated component twice (as is, and disabled)
+ * in a Vite app under the test's output folder, so it resolves `vue` and `reka-ui` from the
+ * repository as an app would, and serves it.
+ */
+async function serveComponent(graph: SceneGraph, folder: string): Promise<ViteDevServer> {
+ const files = await exportStorybook(graph, { framework: 'vue' })
+ const component = files.find((file) => file.path.endsWith('.vue'))
+ if (!component) throw new Error('No component was generated')
+ await mkdir(folder, { recursive: true })
+ await writeFile(join(folder, component.path), component.content)
+ await writeFile(
+ join(folder, 'main.ts'),
+ [
+ "import { createApp, h } from 'vue'",
+ `import Control from './${component.path}'`,
+ "createApp({ render: () => [h('div', { id: 'enabled' }, h(Control)), h('div', { id: 'disabled' }, h(Control, { disabled: true }))] }).mount('#app')"
+ ].join('\n')
+ )
+ await writeFile(
+ join(folder, 'index.html'),
+ '<!doctype html><div id="app"></div><script type="module" src="/main.ts"></script>'
+ )
+ const server = await createServer({
+ root: folder,
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [vue()],
+ server: { port: 0, host: '127.0.0.1' }
+ })
+ await server.listen()
+ return server
+}
+
+test.describe('generated Vue components in a browser', () => {
+ let server: ViteDevServer | undefined
+ test.afterEach(async () => {
+ await server?.close()
+ server = undefined
+ })
+
+ test('a switch toggles on click and its state styles move the thumb', async ({ page }, info) => {
+ server = await serveComponent(switchGraph(), info.outputPath('switch'))
+ await page.goto(server.resolvedUrls?.local[0] ?? '')
+ const control = page.locator('#enabled').getByRole('switch')
+ const thumb = page.locator('#enabled .switch__thumb')
+ await expect(control).toHaveAttribute('data-state', 'unchecked')
+ await expect(thumb).toHaveCSS('left', '2px')
+
+ await control.click()
+ await expect(control).toHaveAttribute('data-state', 'checked')
+ await expect(thumb).toHaveCSS('left', '20px')
+ await expect(control).toHaveCSS('background-color', 'rgb(77, 69, 230)')
+
+ const disabled = page.locator('#disabled').getByRole('switch')
+ await disabled.click({ force: true })
+ await expect(disabled).toHaveAttribute('data-state', 'unchecked')
+ })
+
+ test('a collapsible shows its content when its trigger opens it', async ({ page }, info) => {
+ server = await serveComponent(disclosureGraph(), info.outputPath('disclosure'))
+ await page.goto(server.resolvedUrls?.local[0] ?? '')
+ const trigger = page.locator('#enabled .disclosure__trigger')
+ const content = page.locator('#enabled .disclosure__content')
+ await expect(content).toBeHidden()
+ await trigger.click()
+ await expect(page.locator('#enabled .disclosure')).toHaveAttribute('data-state', 'open')
+ await expect(content).toBeVisible()
+ await expect(content).toHaveCSS('top', '12px')
+ })
+})
diff --git a/tools/checks/architecture/src/steiger-rules/support.ts b/tools/checks/architecture/src/steiger-rules/support.ts
index 99f3b1bf6..5ab8264fc 100644
--- a/tools/checks/architecture/src/steiger-rules/support.ts
+++ b/tools/checks/architecture/src/steiger-rules/support.ts
@@ -46,6 +46,7 @@ export const PACKAGE_ALIASES: Record<string, string> = {
'#core-tests/': 'packages/core/tests/',
'#fig/': 'packages/fig/src/',
'#fig-tests/': 'packages/fig/tests/',
+ '#dom-css-tests/': 'packages/dom-css/tests/',
'#vue/': 'packages/vue/src/',
'#cli/': 'packages/cli/src/',
'#mcp/': 'packages/mcp/src/'
@@ -58,6 +59,7 @@ export const PACKAGE_ALIAS_OWNERS: Record<string, string> = {
'#core-tests/': 'packages/core/tests/',
'#fig/': 'packages/fig/',
'#fig-tests/': 'packages/fig/tests/',
+ '#dom-css-tests/': 'packages/dom-css/tests/',
'#vue/': 'packages/vue/',
'#cli/': 'packages/cli/',
'#mcp/': 'packages/mcp/src/'