Skip to content

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

feat(storybook): generate tabs, radio groups, toggle groups, and accordions (#1007)

Danila Poyarkov7c016e3096ad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index febdf4495..94cafedc4 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; inside it, an instance of another generated component uses that component, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
+- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, or Accordion becomes a Reka UI or Radix UI component whose variants are compiled into state styles and whose text properties are string props with a text control, tabs and groups choosing a value named after each tab's or item's label, and groups writing an item component they use once per item; inside it, an instance of another generated component uses that component, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do. Vector shapes, booleans, stars, and polygons export as inline SVG with their fills, gradients, strokes, and shadows, in HTML, Tailwind JSX, and Storybook stories.
- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.
- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index 05322fa9e..c19b4dbb6 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -162,7 +162,9 @@ 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. 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 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.
+With `--framework vue` or `--framework react`, a component set or component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, or Accordion 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.
+
+Tabs take the open tab as `value` (`v-model:value`, or `defaultValue` and `onValueChange` in React), named by each trigger's words as a slug, such as `account` or `password`, and starting on the first; each trigger and its panel are Reka's or Radix's `Tabs` parts around the design's layers, and the stories get a `select` control and a story per tab. A Radio group, Toggle group, or Accordion writes two components: the group, which chooses one item the same way, starting on the item the design draws on, and `<Group>Item` from its items' component set, built as the group's item primitive (`RadioGroupItem`, `ToggleGroupItem`, or `AccordionItem` with its trigger in a header) and taking the `value` it stands for. The group uses it once per item in its items slot, with each item's value, named by its label property or else its words, and its text values. A Radio is only generated as a group's item; a Toggle or Collapsible used on its own still becomes its own component.
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.
diff --git a/packages/dom-css/src/behaviours/reset.ts b/packages/dom-css/src/behaviours/reset.ts
index 433255e0b..f9dba318b 100644
--- a/packages/dom-css/src/behaviours/reset.ts
+++ b/packages/dom-css/src/behaviours/reset.ts
@@ -12,3 +12,12 @@ export const BUTTON_RESET: Record<string, string> = {
'text-align': 'inherit',
cursor: 'pointer'
}
+
+/**
+ * Element styles the heading around an accordion trigger adds, cleared so the trigger lays
+ * out as designed while the heading keeps its level.
+ */
+export const HEADING_RESET: Record<string, string> = {
+ margin: '0',
+ font: 'inherit'
+}
diff --git a/packages/dom-css/src/behaviours/states/layers.ts b/packages/dom-css/src/behaviours/states/layers.ts
index a0aa36e48..a8c1a64a3 100644
--- a/packages/dom-css/src/behaviours/states/layers.ts
+++ b/packages/dom-css/src/behaviours/states/layers.ts
@@ -5,7 +5,16 @@ import {
import type { DesignElement, DesignNode, DesignText } from '#dom-css/types'
import { omit } from 'es-toolkit/object'
-import { layerPath, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ behaviourOwner,
+ instanceSlotFrames,
+ layerPath,
+ partBinding,
+ readBehaviour,
+ slotPropertyId,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import type { StateElement } from './types'
@@ -48,6 +57,20 @@ function variantLayer(
}
}
+/**
+ * The tab panels a variant draws hidden behind the first. The generated tabs show each when its
+ * tab is chosen, so they are projected as drawn.
+ */
+function tabPanels(graph: SceneGraph, variant: SceneNode): Set<string> {
+ const owner = behaviourOwner(graph, variant)
+ const behaviour = owner && readBehaviour(owner)
+ const propertyId = behaviour?.kind === 'tabs' ? partBinding(behaviour, 'panels') : undefined
+ const panels = propertyId
+ ? instanceSlotFrames(graph, variant).find((frame) => slotPropertyId(frame) === propertyId)
+ : undefined
+ return new Set(panels?.childIds)
+}
+
/** A variant projected to DOM, without where the set places it. */
export function projectVariant(
graph: SceneGraph,
@@ -56,7 +79,8 @@ export function projectVariant(
): VariantLayer | null {
const document = sceneNodeToDesignDocument(graph, variant.id, {
includeSourceIds: false,
- vectorElement
+ vectorElement,
+ shown: tabPanels(graph, variant)
})
const root = document.children.at(0)
if (root?.type !== 'element') return null
diff --git a/packages/dom-css/src/behaviours/states/model.ts b/packages/dom-css/src/behaviours/states/model.ts
index 9a0fbc872..7a399bfa1 100644
--- a/packages/dom-css/src/behaviours/states/model.ts
+++ b/packages/dom-css/src/behaviours/states/model.ts
@@ -66,6 +66,15 @@ function pruneCombined(rules: StateRule[]): StateRule[] {
})
}
+/**
+ * The variants a behaviour's owner draws: a set's components, or a standalone component, such
+ * as a radio group or tabs, which is its own only variant.
+ */
+export function ownerVariants(graph: SceneGraph, owner: SceneNode): SceneNode[] {
+ if (owner.type === 'COMPONENT') return [owner]
+ return graph.getChildren(owner.id).filter((child) => child.type === 'COMPONENT')
+}
+
/**
* A component set's variants as one markup tree with a rest style per layer and a rule per
* variant holding only what that variant changes, under the conditions that show it. Layers
@@ -79,9 +88,8 @@ export function stateStyles(
options: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}
): StateStyles | null {
const conditionsOf = variantConditions(graph, set)
- const variants = graph
- .getChildren(set.id)
- .filter((child) => child.type === 'COMPONENT' && child.visible)
+ const variants = ownerVariants(graph, set)
+ .filter((variant) => variant.visible)
.flatMap((variant) => {
const conditions = conditionsOf(variant)
const root = conditions && projectVariant(graph, variant, options)
diff --git a/packages/dom-css/src/export/components/groups.ts b/packages/dom-css/src/export/components/groups.ts
new file mode 100644
index 000000000..1719bae6c
--- /dev/null
+++ b/packages/dom-css/src/export/components/groups.ts
@@ -0,0 +1,82 @@
+import type { StateElement } from '#dom-css/behaviours/states/types'
+
+import {
+ behaviourOwner,
+ findLayerByPath,
+ instanceMainComponent,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import type { ComponentModel } from './model'
+import { placementOnly, referenceValues, type UsedLayer } from './references'
+import { slugValues, textOf, type ChoiceModel } from './repeats'
+
+/** Groups whose items are their own primitive inside the group, as Reka and Radix have them. */
+export const GROUP_ITEMS = {
+ radioGroup: 'radioGroupItem',
+ toggleGroup: 'toggleGroupItem',
+ accordion: 'accordionItem'
+} as const
+
+export type GroupKind = keyof typeof GROUP_ITEMS
+export type ItemKind = (typeof GROUP_ITEMS)[GroupKind]
+
+export const isGroup = (kind: string): kind is GroupKind => Object.hasOwn(GROUP_ITEMS, kind)
+
+/** Builds the component of a group's items, named for the group. */
+export type ItemBuilder = (owner: SceneNode) => ComponentModel | null
+
+/**
+ * A group's items: the component they share, generated as the group's item primitive, and
+ * each item in the items slot as a use of it with the value it stands for. The group chooses
+ * among those values, starting on the item the design draws on, or none.
+ */
+export function groupItems(
+ graph: SceneGraph,
+ variantIds: readonly string[],
+ itemsElement: StateElement | undefined,
+ build: ItemBuilder
+): { item: ComponentModel; used: Map<StateElement, UsedLayer>; choice: ChoiceModel } | null {
+ const elements = (itemsElement?.children ?? []).filter(
+ (child): child is StateElement => child.type === 'element'
+ )
+ const instances = elements.map((element) => {
+ const path = element.key.split('\0')[0] ?? ''
+ const node = variantIds
+ .map((id) => findLayerByPath(graph, id, path))
+ .find((found) => found?.type === 'INSTANCE')
+ const main = node && instanceMainComponent(graph, node)
+ return node && main ? { node, owner: behaviourOwner(graph, main) } : null
+ })
+ const owner = instances.find((instance) => instance?.owner)?.owner
+ const item = owner && build(owner)
+ if (!owner || !item) return null
+
+ // An item is named by its label property when it has one, else by the words it reads.
+ const label = item.texts.at(0)
+ const values = slugValues(
+ elements.map((element, index) => {
+ const assigned = label && instances[index]?.node.componentPropertyAssignments[label.id]
+ return typeof assigned === 'string' ? assigned : textOf(element)
+ })
+ )
+ const used = new Map<StateElement, UsedLayer>()
+ let chosen: string | null = null
+ for (const [index, element] of elements.entries()) {
+ const instance = instances[index]
+ const value = values.at(index)
+ if (instance?.owner?.id !== owner.id || value === undefined) continue
+ const { props, model } = referenceValues(graph, instance.node, item)
+ if (model) chosen ??= value
+ used.set(element, {
+ type: 'reference',
+ component: item.name,
+ props: [{ name: 'value', value }, ...props],
+ model: null
+ })
+ element.children = []
+ placementOnly(element)
+ }
+ return { item, used, choice: { options: values, default: chosen } }
+}
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index b843112a2..b64011f00 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -1,7 +1,7 @@
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'
+import { ownerVariants, stateStyles } from '#dom-css/behaviours/states/model'
import { layerClassNames, propAttribute } from '#dom-css/behaviours/states/names'
import type { StateElement, StateStyles } from '#dom-css/behaviours/states/types'
import { camelCase } from 'es-toolkit/string'
@@ -20,6 +20,14 @@ import {
import type { SceneGraphToDesignOptions } from '../projection'
import { claimName, identifierName } from '../storybook/names'
+import {
+ groupItems,
+ GROUP_ITEMS,
+ isGroup,
+ type GroupKind,
+ type ItemBuilder,
+ type ItemKind
+} from './groups'
import {
referencedLayers,
type ComponentReference,
@@ -27,10 +35,23 @@ import {
type IconReference,
type UsedLayer
} from './references'
+import { tabParts, type ChoiceModel, type RepeatedPart } from './repeats'
/** 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]
+export const GENERATED_KINDS = [
+ 'button',
+ 'switch',
+ 'checkbox',
+ 'toggle',
+ 'collapsible',
+ 'tabs',
+ 'radioGroup',
+ 'toggleGroup',
+ 'accordion'
+] as const
+
+/** What a generated component is: a control on its own, or a group's item. */
+export type GeneratedKind = (typeof GENERATED_KINDS)[number] | ItemKind
/** A variant property the component takes as a prop and sets on its root as `data-*`. */
export interface VariantProp {
@@ -50,6 +71,8 @@ export interface VariantProp {
export type ComponentBinding =
| { type: 'model'; name: string }
| { type: 'disabled' }
+ /** A group's item: the value it stands for, which the group chooses among. */
+ | { type: 'value' }
| { type: 'prop'; prop: VariantProp; attribute: string }
/** A layer of the generated markup, before a framework picks its element or component. */
@@ -65,6 +88,8 @@ export interface ComponentElement {
attrs: Record<string, string>
/** On the root only. */
bindings: ComponentBinding[]
+ /** The value a repeated part stands for, such as a tab trigger's tab. */
+ value?: string
children: ComponentNode[]
}
@@ -95,8 +120,17 @@ export interface ComponentModel {
styles: StateStyles
/** The markup every framework writes, with each layer's part and the root's bindings. */
tree: ComponentElement
- /** The boolean the component binds two ways: `checked`, `pressed`, or `open`. */
+ /**
+ * The value the component binds two ways: a boolean such as `checked`, `pressed`, or `open`,
+ * or `value` when it chooses among `choice`, as tabs do.
+ */
model: string | null
+ /** The options a string model takes and the one it starts on. */
+ choice: ChoiceModel | null
+ /** A group's item takes the `value` it stands for, which the group chooses among. */
+ valueProp: boolean
+ /** The component of a group's items, generated beside the group's own. */
+ item: ComponentModel | null
/** Whether the set draws a disabled state, so the component takes `disabled`. */
disabled: boolean
props: VariantProp[]
@@ -112,6 +146,8 @@ interface TreeLabels {
texts: Map<StateElement, string>
/** Layers that use another component or an icon in place of drawing themselves. */
used: Map<StateElement, UsedLayer>
+ /** Layers drawn once per value, such as tab triggers and panels. */
+ repeated: Map<StateElement, RepeatedPart>
}
function componentTree(
@@ -119,11 +155,13 @@ function componentTree(
labels: TreeLabels,
bindings: ComponentBinding[]
): ComponentElement {
- const part = labels.parts.get(node) ?? null
+ const repeated = labels.repeated.get(node)
+ const part = repeated?.part ?? labels.parts.get(node) ?? null
const text = labels.texts.get(node)
return {
type: 'element',
part,
+ ...(repeated ? { value: repeated.value } : {}),
tag: node.tagName,
className: labels.classes.get(node) ?? '',
attrs: node.attrs,
@@ -161,7 +199,7 @@ function textProps(
default: definition.defaultValue
}))
const byId = new Map(definitions.map((definition, i) => [definition.id, texts[i]]))
- const variants = graph.getChildren(set.id)
+ const variants = ownerVariants(graph, set)
const bound = new Map<StateElement, string>()
for (const element of elements) {
// A key ends with the words a layer reads, which a text prop draws in every variant.
@@ -197,12 +235,25 @@ const BUTTON_PARTS: Record<GeneratedKind, readonly string[]> = {
switch: ['root'],
checkbox: ['root'],
toggle: ['root'],
- collapsible: ['trigger']
+ collapsible: ['trigger'],
+ tabs: ['trigger'],
+ radioGroup: [],
+ toggleGroup: [],
+ accordion: [],
+ radioGroupItem: ['root'],
+ toggleGroupItem: ['root'],
+ accordionItem: ['trigger']
}
-const isGenerated = (kind: Behaviour['kind']): kind is GeneratedKind =>
+const isGenerated = (kind: Behaviour['kind']): kind is (typeof GENERATED_KINDS)[number] =>
(GENERATED_KINDS as readonly string[]).includes(kind)
+/** What an owner generates as: a group's item when it is one, its own kind, or nothing. */
+function generatedKind(kind: Behaviour['kind'], itemOf?: GroupKind): GeneratedKind | null {
+ if (itemOf) return GROUP_ITEMS[itemOf]
+ return isGenerated(kind) ? kind : null
+}
+
/** 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]))
@@ -212,7 +263,7 @@ function partPaths(graph: SceneGraph, set: SceneNode, behaviour: Behaviour): Map
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 variant of ownerVariants(graph, set))
for (const child of graph.getChildren(variant.id)) visit(variant, child)
return paths
}
@@ -227,35 +278,51 @@ export interface ComponentModelOptions extends Pick<SceneGraphToDesignOptions, '
* drawing their layers.
*/
references?: ComponentReferences
+ /** The component's identifier and file name; the owner's name by default. */
+ name?: string
+ /** A group's item component's name; the group's name with `Item` by default. */
+ itemName?: string
+ /** Generate the owner as the item of a group of this kind, which only lives in the group. */
+ itemOf?: GroupKind
}
-export function componentModel(
+/** Each layer's behaviour part: the root, and the slot frames that draw the others. */
+function behaviourParts(
graph: SceneGraph,
set: SceneNode,
- options: ComponentModelOptions = {}
-): ComponentModel | null {
- const behaviour = readBehaviour(set)
- if (!behaviour || !isGenerated(behaviour.kind)) return null
- const styles = stateStyles(graph, set, options)
- const args = behaviourArgs(graph, set)
- if (!styles || !args) return null
-
+ behaviour: Behaviour,
+ root: StateElement
+): Map<StateElement, string> {
const paths = partPaths(graph, set, behaviour)
- const parts = new Map<StateElement, string>([[styles.root, 'root']])
- for (const element of allElements(styles.root)) {
+ const contract = behaviourContract(behaviour.kind).parts
+ const parts = new Map<StateElement, string>([[root, 'root']])
+ for (const element of allElements(root)) {
const part = paths.get(element.key)
- if (part && behaviourContract(behaviour.kind).parts.some((item) => item.id === part))
- parts.set(element, part)
+ if (part && contract.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 }
+ return parts
+}
+
+/** Clears the native button look from the parts a kind renders as buttons. */
+function resetButtons(
+ kind: GeneratedKind,
+ parts: ReadonlyMap<StateElement, string>,
+ repeated: ReadonlyMap<StateElement, RepeatedPart>
+): void {
+ const all = [...parts, ...[...repeated].map(([element, item]) => [element, item.part] as const)]
+ for (const [element, part] of all)
+ if (BUTTON_PARTS[kind].includes(part)) element.base = { ...BUTTON_RESET, ...element.base }
+}
- const booleans = [...args.booleans.values()]
- const model = booleans.find((arg) => arg.name !== 'disabled')?.name ?? null
+/** The variant properties that are not values or states, as props set as `data-*`. */
+function variantProps(
+ graph: SceneGraph,
+ set: SceneNode,
+ args: BehaviourArgs,
+ taken: Set<string>
+): VariantProp[] {
const bound = new Set([...args.booleans.keys(), args.states?.property])
- const taken = new Set([...(model ? [model] : []), 'disabled'])
- const props = behaviourProperties(graph, set)
+ return behaviourProperties(graph, set)
.filter((definition) => definition.type === 'VARIANT' && !bound.has(definition.name))
.map((definition) => ({
name: claimName(camelCase(identifierName(definition.name, 'Prop')), taken),
@@ -263,10 +330,18 @@ export function componentModel(
options: definition.variantOptions ?? [],
default: definition.defaultValue
}))
- const disabled =
- booleans.some((arg) => arg.name === 'disabled') || args.states?.disabled !== undefined
- const bindings: ComponentBinding[] = [
+}
+
+/** What the root binds: its model, an item's value, `disabled`, and its variant props. */
+function rootBindings(
+ model: string | null,
+ item: boolean,
+ disabled: boolean,
+ props: readonly VariantProp[]
+): ComponentBinding[] {
+ return [
...(model ? [{ type: 'model' as const, name: model }] : []),
+ ...(item ? [{ type: 'value' as const }] : []),
...(disabled ? [{ type: 'disabled' as const }] : []),
...props.map((prop) => ({
type: 'prop' as const,
@@ -274,25 +349,109 @@ 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>()
+}
+
+/**
+ * A group's items, built as the group's item component; null for other owners and for a
+ * group's item itself.
+ */
+function itemsOf(
+ graph: SceneGraph,
+ behaviour: Behaviour,
+ variantIds: readonly string[],
+ parts: ReadonlyMap<StateElement, string>,
+ options: ComponentModelOptions,
+ build: (itemOf: GroupKind) => ItemBuilder
+): ReturnType<typeof groupItems> {
+ if (options.itemOf || !isGroup(behaviour.kind)) return null
+ const itemsElement = [...parts].find(([, part]) => part === 'items')?.[0]
+ return groupItems(graph, variantIds, itemsElement, build(behaviour.kind))
+}
+
+/**
+ * The value the component binds two ways: `value` when it chooses among options, its boolean
+ * such as `checked`, or none for a group's item, which its group chooses.
+ */
+function modelName(args: BehaviourArgs, item: boolean, choice: ChoiceModel | null): string | null {
+ if (choice) return 'value'
+ if (item) return null
+ return [...args.booleans.values()].find((arg) => arg.name !== 'disabled')?.name ?? null
+}
+
+/** Whether the set draws a disabled look, as a boolean or an interaction state. */
+const drawsDisabled = (args: BehaviourArgs) =>
+ [...args.booleans.values()].some((arg) => arg.name === 'disabled') ||
+ args.states?.disabled !== undefined
+
+/** The layers used rather than drawn: a group's items, then other generated components. */
+function usedLayers(
+ graph: SceneGraph,
+ root: StateElement,
+ variantIds: readonly string[],
+ items: ReadonlyMap<StateElement, UsedLayer> | undefined,
+ references: ComponentReferences | undefined
+): Map<StateElement, UsedLayer> {
+ const used = new Map(items)
+ if (references)
+ for (const [element, layer] of referencedLayers(graph, root, variantIds, references, used))
+ used.set(element, layer)
+ return used
+}
+
+export function componentModel(
+ graph: SceneGraph,
+ set: SceneNode,
+ options: ComponentModelOptions = {}
+): ComponentModel | null {
+ const behaviour = readBehaviour(set)
+ const kind = behaviour && generatedKind(behaviour.kind, options.itemOf)
+ const styles = kind ? stateStyles(graph, set, options) : null
+ const args = behaviourArgs(graph, set)
+ if (!behaviour || !kind || !styles || !args) return null
+ const name = options.name ?? identifierName(set.name, 'Component')
+
+ const parts = behaviourParts(graph, set, behaviour, styles.root)
+ const tabs = behaviour.kind === 'tabs' ? tabParts(parts) : null
+ const repeated = tabs?.repeated ?? new Map<StateElement, RepeatedPart>()
+ resetButtons(kind, parts, repeated)
+
+ // A group's items first, so its item component is used for them rather than a standalone one.
+ const variantIds = [styles.restId, ...ownerVariants(graph, set).map((variant) => variant.id)]
+ const items = itemsOf(
+ graph,
+ behaviour,
+ variantIds,
+ parts,
+ options,
+ (itemOf) => (owner) =>
+ componentModel(graph, owner, {
+ ...options,
+ name: options.itemName ?? `${name}Item`,
+ itemName: undefined,
+ itemOf
+ })
+ )
+
+ const choice = tabs?.choice ?? items?.choice ?? null
+ const model = modelName(args, !!options.itemOf, choice)
+ const taken = new Set([...(model ? [model] : []), 'disabled', 'value'])
+ const props = variantProps(graph, set, args, taken)
+ const disabled = drawsDisabled(args)
+ const used = usedLayers(graph, styles.root, variantIds, items?.used, options.references)
const texts = textProps(graph, set, allElements(styles.root), taken)
return {
- name: identifierName(set.name, 'Component'),
- kind: behaviour.kind,
+ name,
+ kind,
styles,
tree: componentTree(
styles.root,
- { parts, classes: layerClassNames(styles), texts: texts.bound, used },
- bindings
+ { parts, classes: layerClassNames(styles), texts: texts.bound, used, repeated },
+ rootBindings(model, !!options.itemOf, disabled, props)
),
model,
+ choice,
+ valueProp: !!options.itemOf,
+ item: items?.item ?? null,
disabled,
props,
texts: texts.texts,
diff --git a/packages/dom-css/src/export/components/react.ts b/packages/dom-css/src/export/components/react.ts
index 834f36c09..d0c96ebb6 100644
--- a/packages/dom-css/src/export/components/react.ts
+++ b/packages/dom-css/src/export/components/react.ts
@@ -1,7 +1,8 @@
+import { HEADING_RESET } from '#dom-css/behaviours/reset'
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 { camelCase, upperFirst } from 'es-toolkit/string'
import { es, jsx } from '@open-pencil/emit'
@@ -27,11 +28,38 @@ const RADIX: Record<GeneratedKind, { namespace: string; parts: Record<string, st
collapsible: {
namespace: 'Collapsible',
parts: { root: 'Root', trigger: 'Trigger', content: 'Content' }
+ },
+ tabs: {
+ namespace: 'Tabs',
+ parts: { root: 'Root', list: 'List', trigger: 'Trigger', content: 'Content' }
+ },
+ radioGroup: { namespace: 'RadioGroup', parts: { root: 'Root' } },
+ toggleGroup: { namespace: 'ToggleGroup', parts: { root: 'Root' } },
+ accordion: { namespace: 'Accordion', parts: { root: 'Root' } },
+ radioGroupItem: { namespace: 'RadioGroup', parts: { root: 'Item', indicator: 'Indicator' } },
+ toggleGroupItem: { namespace: 'ToggleGroup', parts: { root: 'Item' } },
+ accordionItem: {
+ namespace: 'Accordion',
+ parts: { root: 'Item', trigger: 'Trigger', content: 'Content' }
}
}
+/** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
+const ROOT_ATTRIBUTES: Partial<Record<GeneratedKind, es.SyntaxNode[]>> = {
+ toggleGroup: [jsx.attribute('type', jsx.stringValue('single'))],
+ accordion: [jsx.attribute('type', jsx.stringValue('single')), jsx.attribute('collapsible', null)]
+}
+
const PRIMITIVE = (namespace: string) => `${namespace}Primitive`
+const HEADING_STYLE = jsx.container(
+ es.object(
+ Object.entries(HEADING_RESET).map(
+ ([property, value]) => [camelCase(property), es.string(value)] as const
+ )
+ )
+)
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
/** `styles.thumb`, or `styles['switch-thumb']` for a class that isn't an identifier. */
@@ -62,6 +90,7 @@ const DISABLED_FLAG = es.parseExpression('props.disabled || undefined')
/** What a component's markup uses, which its module imports. */
interface MarkupUses {
kind: GeneratedKind
+ choice: ComponentModel['choice']
/** Other generated components. */
components: Set<string>
icons: boolean
@@ -105,48 +134,79 @@ function element(node: ComponentNode, uses: MarkupUses, depth: number): es.Synta
depth
)
}
- const kind = uses.kind
- const radix = RADIX[kind]
- const part = node.part ? radix?.parts[node.part] : undefined
- const root = node.part === 'root'
- const native = root && !part
- // The design's own classes, the state styles' module class, and on the root the caller's,
- // which the spread would otherwise lose to the generated one.
+ return designElement(node, uses, depth)
+}
+
+/**
+ * The design's own classes, the state styles' module class, and on the root the caller's,
+ * which the spread would otherwise lose to the generated one.
+ */
+function classNameOf(node: ComponentElement, root: boolean): es.SyntaxNode {
const classes = [
...(node.attrs.class ? [es.string(node.attrs.class)] : []),
moduleClass(node.className),
...(root ? [es.parseExpression('props.className')] : [])
]
const only = classes.length === 1 ? classes.at(0) : undefined
- const className = only ?? es.fill(CLASS_NAMES, { $classes: es.array(classes) })
+ return only ?? es.fill(CLASS_NAMES, { $classes: es.array(classes) })
+}
+
+/** What a root fixes before the caller's props: a group's single choice, and its start. */
+function rootAttributes(uses: MarkupUses): es.SyntaxNode[] {
+ const start = uses.choice?.default
+ return [
+ ...(ROOT_ATTRIBUTES[uses.kind] ?? []),
+ // A choice starts on the design's option, which the caller's props can change.
+ ...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : [])
+ ]
+}
+
+function bindingAttributes(node: ComponentElement, native: boolean): es.SyntaxNode[] {
+ return node.bindings.flatMap((binding) => {
+ if (binding.type === 'prop')
+ return [jsx.attribute(binding.attribute, jsx.container(es.identifier(binding.prop.name)))]
+ // Radix sets `data-disabled` on its own roots; a native button needs it for the styles.
+ if (binding.type === 'disabled' && native)
+ return [jsx.attribute('data-disabled', jsx.container(DISABLED_FLAG))]
+ return []
+ })
+}
+
+function designElement(node: ComponentElement, uses: MarkupUses, depth: number): es.SyntaxNode {
+ const kind = uses.kind
+ const root = node.part === 'root'
+ const native = root && !(node.part && RADIX[kind]?.parts[node.part])
const attributes = [
...(native ? [jsx.attribute('type', jsx.stringValue('button'))] : []),
+ ...(root ? rootAttributes(uses) : []),
// The root passes the caller's props on, such as `checked` or `onClick`.
...(root ? [jsx.spread(es.identifier('props'))] : []),
+ ...(node.value === undefined ? [] : [jsx.attribute('value', jsx.stringValue(node.value))]),
...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
jsx.attribute(name, jsx.stringValue(value))
),
- jsx.attribute('className', jsx.container(className)),
- ...node.bindings.flatMap((binding) => {
- if (binding.type === 'prop')
- return [jsx.attribute(binding.attribute, jsx.container(es.identifier(binding.prop.name)))]
- // Radix sets `data-disabled` on its own roots; a native button needs it for the styles.
- if (binding.type === 'disabled' && native)
- return [jsx.attribute('data-disabled', jsx.container(DISABLED_FLAG))]
- return []
- })
+ jsx.attribute('className', jsx.container(classNameOf(node, root))),
+ ...bindingAttributes(node, native)
]
// 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(
+ const only = node.children.length === 1 ? node.children[0]?.type : undefined
+ const inline = only === 'text' || only === 'textProp'
+ // Radix puts an accordion item's trigger in a header, which carries the heading level.
+ const header = kind === 'accordionItem' && node.part === 'trigger'
+ const drawn = jsx.element(
tagOf(node, kind),
attributes,
- node.children.map((child) => element(child, uses, depth + 1)),
- depth,
+ node.children.map((child) => element(child, uses, depth + (header ? 2 : 1))),
+ depth + (header ? 1 : 0),
inline
)
+ if (!header) return drawn
+ return jsx.element(
+ `${PRIMITIVE('Accordion')}.Header`,
+ [jsx.attribute('style', HEADING_STYLE)],
+ [drawn],
+ depth
+ )
}
const MODULE = es.parseModule(dedent`
@@ -165,18 +225,38 @@ const RADIX_IMPORT = es.parseModule(`import { $Namespace as $Primitive } from 'r
const ICONIFY_IMPORT = es.parseModule(`import { Icon as ${ICONIFY} } from '@iconify/react'`).body
const IMPORT_COMPONENT = es.parseModule(`import { $Component } from '$path'`)
+/**
+ * The props of a group that fixes one choice at a time, without the `type` it fixes. The
+ * root's own props join the single and multiple choice, which a single value can't satisfy.
+ */
+const SINGLE_PROPS: Partial<Record<GeneratedKind, string>> = {
+ toggleGroup: 'ToggleGroupSingleProps',
+ accordion: 'AccordionSingleProps'
+}
+
+const qualified = (namespace: string, name: string) => ({
+ type: 'TSQualifiedName',
+ left: es.identifier(PRIMITIVE(namespace)),
+ right: es.identifier(name)
+})
+
+/** The root's own props, or a single choice group's. */
+function rootPropsType(kind: GeneratedKind): es.SyntaxNode {
+ const radix = RADIX[kind]
+ if (!radix) return es.parseType("ComponentProps<'button'>")
+ const single = SINGLE_PROPS[kind]
+ if (single)
+ return es.fill(es.parseType("Omit<$Props, 'type'>"), {
+ $Props: qualified(radix.namespace, single)
+ })
+ return es.fill(es.parseType('ComponentProps<typeof $Root>'), {
+ $Root: qualified(radix.namespace, radix.parts.root)
+ })
+}
+
/** The root's own props, extended with the component's variant props when it has any. */
function propsType(component: ComponentModel): es.SyntaxNode {
- const radix = RADIX[component.kind]
- const base = radix
- ? es.fill(es.parseType('ComponentProps<typeof $Root>'), {
- $Root: {
- type: 'TSQualifiedName',
- left: es.identifier(PRIMITIVE(radix.namespace)),
- right: es.identifier('Root')
- }
- })
- : es.parseType("ComponentProps<'button'>")
+ const base = rootPropsType(component.kind)
if (component.props.length === 0 && component.texts.length === 0) return base
return {
type: 'TSIntersectionType',
@@ -234,7 +314,12 @@ function parameters(component: ComponentModel): es.SyntaxNode {
export const reactComponent: ComponentGenerator = async (component) => {
const radix = RADIX[component.kind]
const stylesPath = `${component.name}.module.css`
- const uses: MarkupUses = { kind: component.kind, components: new Set(), icons: false }
+ const uses: MarkupUses = {
+ kind: component.kind,
+ choice: component.choice,
+ components: new Set(),
+ icons: false
+ }
const body = element(component.tree, uses, 1)
const imports = [
...(uses.icons ? ICONIFY_IMPORT : []),
@@ -263,12 +348,16 @@ export const reactComponent: ComponentGenerator = async (component) => {
const program = {
type: 'Program',
sourceType: 'module',
- body: [typeImport, ...imports, stylesImport, ...rest]
+ // A single choice group's props come from Radix's own type, not `ComponentProps`.
+ body: [...(SINGLE_PROPS[component.kind] ? [] : [typeImport]), ...imports, stylesImport, ...rest]
}
const { css } = await stateStylesToCSS(component.styles)
const model = component.model
+ // A group's items are their own component, which the group's markup uses.
+ const item = component.item ? await reactComponent(component.item) : null
return {
files: [
+ ...(item?.files ?? []),
{ path: `${component.name}.tsx`, content: `${jsx.printModule(program)}\n` },
{ path: stylesPath, content: css }
],
diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.ts
index 5a97d1768..ab64f454b 100644
--- a/packages/dom-css/src/export/components/references.ts
+++ b/packages/dom-css/src/export/components/references.ts
@@ -49,7 +49,7 @@ export interface IconReference {
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 {
+export 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)
@@ -67,8 +67,11 @@ function ownerId(graph: SceneGraph, component: SceneNode): string {
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(
+/**
+ * What `instance` sets on `component`: the values it is drawn with that differ from defaults,
+ * and whether it is drawn on: its model, or for a group's item the value that marks it chosen.
+ */
+export function referenceValues(
graph: SceneGraph,
instance: SceneNode,
component: ComponentModel
@@ -78,7 +81,8 @@ function referenceValues(
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
+ const on = arg.name === component.model || (component.valueProp && arg.name !== 'disabled')
+ if (on) model = arg.name
else props.push({ name: arg.name, value: true })
}
const states = component.args.states
@@ -136,12 +140,14 @@ export function referencedLayers(
graph: SceneGraph,
root: StateElement,
variantIds: readonly string[],
- references: ComponentReferences
+ references: ComponentReferences,
+ /** Layers already used otherwise, such as a group's items. */
+ taken: ReadonlyMap<StateElement, unknown> = new Map()
): Map<StateElement, UsedLayer> {
const used = new Map<StateElement, UsedLayer>()
const visit = (element: StateElement) => {
for (const child of element.children) {
- if (child.type !== 'element') continue
+ if (child.type !== 'element' || taken.has(child)) continue
const layer = usedLayer(graph, variantIds, child, references)
if (!layer) {
visit(child)
diff --git a/packages/dom-css/src/export/components/repeats.ts b/packages/dom-css/src/export/components/repeats.ts
new file mode 100644
index 000000000..2d10aed6c
--- /dev/null
+++ b/packages/dom-css/src/export/components/repeats.ts
@@ -0,0 +1,59 @@
+import type { StateElement, StateNode } from '#dom-css/behaviours/states/types'
+import { kebabCase } from 'es-toolkit/string'
+
+import { claimName } from '../storybook/names'
+
+/** A layer drawn once per value, such as a tab's trigger or its panel, and the value it is. */
+export interface RepeatedPart {
+ part: string
+ value: string
+}
+
+/**
+ * The string a component chooses among, such as the open tab, and the one it starts on, or
+ * none, as a radio group with no item chosen.
+ */
+export interface ChoiceModel {
+ options: string[]
+ default: string | null
+}
+
+/** The words a layer reads, joined across its text. */
+export function textOf(node: StateNode): string {
+ if (node.type === 'text') return node.text
+ return node.children.map(textOf).join(' ')
+}
+
+const elementsOf = (element: StateElement | undefined) =>
+ (element?.children ?? []).filter((child): child is StateElement => child.type === 'element')
+
+/**
+ * The value each label stands for: the label as a slug, such as `account`, apart from the
+ * others, or its position when it has no words.
+ */
+export function slugValues(labels: readonly string[]): string[] {
+ const taken = new Set<string>()
+ return labels.map((label, index) => claimName(kebabCase(label) || String(index), taken))
+}
+
+/**
+ * Tabs' triggers, the layers in its list, and its panels, the layers in its panels slot, each
+ * with the value of the tab it belongs to, matched by position. The tabs start on the first.
+ */
+export function tabParts(parts: ReadonlyMap<StateElement, string>): {
+ repeated: Map<StateElement, RepeatedPart>
+ choice: ChoiceModel | null
+} {
+ const partElement = (id: string) => [...parts].find(([, part]) => part === id)?.[0]
+ const triggers = elementsOf(partElement('list'))
+ const values = slugValues(triggers.map(textOf))
+ const repeated = new Map<StateElement, RepeatedPart>()
+ for (const [index, trigger] of triggers.entries())
+ repeated.set(trigger, { part: 'trigger', value: values[index] ?? String(index) })
+ for (const [index, panel] of elementsOf(partElement('panels')).entries()) {
+ const value = values.at(index)
+ if (value !== undefined) repeated.set(panel, { part: 'content', value })
+ }
+ const first = values.at(0)
+ return { repeated, choice: first === undefined ? null : { options: values, default: first } }
+}
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index 2faa0f780..f6c3a73a1 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -1,3 +1,4 @@
+import { HEADING_RESET } from '#dom-css/behaviours/reset'
import { stateStylesToCSS } from '#dom-css/behaviours/states/css'
import { compact } from 'es-toolkit/array'
import { omit } from 'es-toolkit/object'
@@ -34,11 +35,33 @@ const REKA: Record<
content: 'CollapsibleContent'
},
model: 'open'
+ },
+ tabs: {
+ parts: { root: 'TabsRoot', list: 'TabsList', trigger: 'TabsTrigger', content: 'TabsContent' },
+ model: 'modelValue'
+ },
+ radioGroup: { parts: { root: 'RadioGroupRoot' }, model: 'modelValue' },
+ toggleGroup: { parts: { root: 'ToggleGroupRoot' }, model: 'modelValue' },
+ accordion: { parts: { root: 'AccordionRoot' }, model: 'modelValue' },
+ radioGroupItem: { parts: { root: 'RadioGroupItem', indicator: 'RadioGroupIndicator' } },
+ toggleGroupItem: { parts: { root: 'ToggleGroupItem' } },
+ accordionItem: {
+ parts: { root: 'AccordionItem', trigger: 'AccordionTrigger', content: 'AccordionContent' }
}
}
+/** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
+const ROOT_ATTRIBUTES: Partial<Record<GeneratedKind, vue.VueAttribute[]>> = {
+ toggleGroup: [vue.attribute('type', 'single')],
+ accordion: [vue.attribute('type', 'single'), vue.bound('collapsible', es.parseExpression('true'))]
+}
+
const identifier = (name: string) => es.identifier(name)
+const HEADING_STYLE = Object.entries(HEADING_RESET)
+ .map(([property, value]) => `${property}: ${value}`)
+ .join('; ')
+
/** `disabled || undefined`, so a native button sets `data-disabled` only while disabled. */
const DISABLED_FLAG = es.parseExpression('disabled || undefined')
@@ -50,6 +73,7 @@ function bindingAttributes(
if (binding.type === 'model')
return [vue.model(identifier(binding.name), REKA[kind].model === 'open' ? 'open' : undefined)]
if (binding.type === 'prop') return [vue.bound(binding.attribute, identifier(binding.prop.name))]
+ if (binding.type === 'value') return [vue.bound('value', identifier('value'))]
// Reka sets `data-disabled` on its own roots; a native button needs it for the state styles.
return [
vue.bound('disabled', identifier('disabled')),
@@ -104,18 +128,24 @@ function templateNode(node: ComponentNode, uses: TemplateUses): vue.VueNode {
const reka = node.part ? REKA[uses.kind].parts[node.part] : undefined
if (reka) uses.reka.add(reka)
const native = node.part === 'root' && !reka
- return vue.element(
+ const element = vue.element(
reka ?? (native ? 'button' : node.tag),
[
...(native ? [vue.attribute('type', 'button')] : []),
+ ...(node.part === 'root' ? (ROOT_ATTRIBUTES[uses.kind] ?? []) : []),
...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
vue.attribute(name, value)
),
vue.attribute('class', compact([node.attrs.class, node.className]).join(' ')),
+ ...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
...node.bindings.flatMap((binding) => bindingAttributes(binding, uses.kind, native))
],
node.children.map((child) => templateNode(child, uses))
)
+ // Reka puts an accordion item's trigger in a header, which carries the heading level.
+ if (uses.kind !== 'accordionItem' || node.part !== 'trigger') return element
+ uses.reka.add('AccordionHeader')
+ return vue.element('AccordionHeader', [vue.attribute('style', HEADING_STYLE)], [element])
}
function propsType(component: ComponentModel): es.SyntaxNode {
@@ -125,10 +155,20 @@ function propsType(component: ComponentModel): es.SyntaxNode {
true
])
if (component.disabled) members.unshift(['disabled', es.parseType('boolean'), true])
+ // A group's item always stands for a value, which has no default.
+ if (component.valueProp) members.unshift(['value', es.parseType('string'), false])
for (const text of component.texts) members.push([text.name, es.parseType('string'), true])
return es.objectType(members)
}
+/** `defineProps`, with `withDefaults` when any prop has a default to give. */
+function propsDeclaration(component: ComponentModel): es.SyntaxNode[] {
+ const optional = component.disabled || component.props.length > 0 || component.texts.length > 0
+ return optional
+ ? es.fill(PROPS, { $Props: propsType(component), $defaults: propsDefaults(component) }).body
+ : es.fill(REQUIRED_PROPS, { $Props: propsType(component) }).body
+}
+
function propsDefaults(component: ComponentModel): es.SyntaxNode {
return es.object([
...(component.disabled ? [['disabled', es.parseExpression('false')] as const] : []),
@@ -138,7 +178,12 @@ function propsDefaults(component: ComponentModel): es.SyntaxNode {
}
const PROPS = es.parseModule('withDefaults(defineProps<$Props>(), $defaults)')
+const REQUIRED_PROPS = es.parseModule('defineProps<$Props>()')
const MODEL = es.parseModule('const $model = defineModel<boolean>($name, { default: false })')
+const CHOICE_MODEL = es.parseModule(
+ 'const $model = defineModel<$Type>($name, { default: $default })'
+)
+const OPEN_CHOICE_MODEL = es.parseModule('const $model = defineModel<$Type>($name)')
function namedImport(names: readonly string[], source: string, local = (name: string) => name) {
return {
@@ -170,13 +215,23 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {
)
]
const props =
- component.disabled || component.props.length > 0 || component.texts.length > 0
- ? es.fill(PROPS, { $Props: propsType(component), $defaults: propsDefaults(component) }).body
+ component.valueProp ||
+ component.disabled ||
+ component.props.length > 0 ||
+ component.texts.length > 0
+ ? propsDeclaration(component)
: []
- const model = component.model
- ? es.fill(MODEL, { $model: identifier(component.model), $name: es.string(component.model) })
- .body
- : []
+ const name = component.model
+ const choice = component.choice
+ let model: es.SyntaxNode[] = []
+ if (name && choice)
+ model = es.fill(choice.default === null ? OPEN_CHOICE_MODEL : CHOICE_MODEL, {
+ $model: identifier(name),
+ $name: es.string(name),
+ $Type: es.stringUnionType(choice.options),
+ $default: choice.default === null ? es.OMIT : es.string(choice.default)
+ }).body
+ else if (name) model = es.fill(MODEL, { $model: identifier(name), $name: es.string(name) }).body
const refs = uses.models.flatMap(
(item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body
)
@@ -210,8 +265,11 @@ export const vueComponent: ComponentGenerator = async (component) => {
const template = templateNode(component.tree, uses)
const { css } = await stateStylesToCSS(component.styles)
const path = `${component.name}.vue`
+ // A group's items are their own component, which the group's template uses.
+ const item = component.item ? await vueComponent(component.item) : null
return {
files: [
+ ...(item?.files ?? []),
{
path,
content: vue.printComponent({ script: script(component, uses), template, style: css })
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index 0e5b4dd85..370cf1f76 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -30,6 +30,8 @@ export interface SceneGraphToDesignOptions {
tokens?: boolean
/** Vector, boolean, star, polygon, and icon layers as inline SVG; without it they project as boxes. */
vectorElement?: VectorElementRenderer
+ /** Hidden layers to project as shown, such as the tab panels a component reveals itself. */
+ shown?: ReadonlySet<string>
}
/** Layers whose shape only paths describe, which CSS boxes cannot draw. */
@@ -367,6 +369,7 @@ interface ProjectionContext {
includeSourceIds: boolean
tokens: DesignTokens | undefined
vectorElement: VectorElementRenderer | undefined
+ shown: ReadonlySet<string> | undefined
}
/**
@@ -399,7 +402,7 @@ function sceneNodeToDesignNode(
inherited: CSSModes,
root: boolean
): DesignNode | null {
- if (!node.visible || node.internalOnly) return null
+ if ((!node.visible && !context.shown?.has(node.id)) || node.internalOnly) return null
const { graph, includeSourceIds, tokens } = context
const parent = node.parentId ? graph.getNode(node.parentId) : undefined
const entered = tokens?.enter(node, inherited, root)
@@ -453,13 +456,14 @@ function sceneNodeToDesignNode(
function projectionContext(
graph: SceneGraph,
- { includeSourceIds = true, tokens = true, vectorElement }: SceneGraphToDesignOptions
+ { includeSourceIds = true, tokens = true, vectorElement, shown }: SceneGraphToDesignOptions
): ProjectionContext {
return {
graph,
includeSourceIds,
tokens: tokens ? new DesignTokens(graph) : undefined,
- vectorElement
+ vectorElement,
+ shown
}
}
diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.ts
index 5909efb61..951acf047 100644
--- a/packages/dom-css/src/export/storybook/component.ts
+++ b/packages/dom-css/src/export/storybook/component.ts
@@ -62,9 +62,16 @@ export interface ComponentStoriesData {
const FALSE = es.parseExpression('false')
const TRUE = es.parseExpression('true')
+/** A model's value at rest: off, the option a choice starts on, or none for an open choice. */
+function restValue(component: ComponentModel): es.SyntaxNode | null {
+ if (!component.choice) return FALSE
+ return component.choice.default === null ? null : es.string(component.choice.default)
+}
+
function restArgs(component: ComponentModel, model: string | null): [string, es.SyntaxNode][] {
+ const rest = restValue(component)
return [
- ...(model ? [[model, FALSE] as [string, es.SyntaxNode]] : []),
+ ...(model && rest ? [[model, rest] as [string, es.SyntaxNode]] : []),
...(component.disabled ? [['disabled', FALSE] as [string, es.SyntaxNode]] : []),
...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, es.string(prop.default)]),
...component.texts.map((text): [string, es.SyntaxNode] => [text.name, es.string(text.default)])
@@ -73,16 +80,16 @@ function restArgs(component: ComponentModel, model: string | null): [string, es.
function argTypes(component: ComponentModel, model: string | null): es.SyntaxNode {
const boolean = es.object([['control', es.string('boolean')]])
+ const select = (options: readonly string[]) =>
+ es.object([
+ ['control', es.string('select')],
+ ['options', es.array(options.map(es.string))]
+ ])
+ const modelControl = component.choice ? select(component.choice.options) : boolean
return es.object([
- ...(model ? [[model, boolean] as [string, es.SyntaxNode]] : []),
+ ...(model ? [[model, modelControl] 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))]
- ])
- ]),
+ ...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, select(prop.options)]),
...component.texts.map((text): [string, es.SyntaxNode] => [
text.name,
es.object([['control', es.string('text')]])
@@ -111,7 +118,15 @@ function stories(
interaction &&
es.fill(PLAY, { $role: es.string(interaction.role), $state: es.string(interaction.state) })
),
- ...(component.model && model ? [story(component.model, [[model, TRUE]])] : []),
+ ...(component.model && model && !component.choice
+ ? [story(component.model, [[model, TRUE]])]
+ : []),
+ // A choice gets a story per option it does not start on, such as each other tab.
+ ...(component.choice && model
+ ? component.choice.options
+ .filter((option) => option !== component.choice?.default)
+ .map((option) => story(option, [[model, es.string(option)]]))
+ : []),
...(component.disabled ? [story('Disabled', [['disabled', TRUE]])] : []),
...component.props.flatMap((prop) =>
prop.options
diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.ts
index 77cacb366..c48ade5fe 100644
--- a/packages/dom-css/src/export/storybook/export.ts
+++ b/packages/dom-css/src/export/storybook/export.ts
@@ -154,12 +154,22 @@ function generatedModels(
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
- }
+ // Components are imported by their files' names, so the two always match. A group's item
+ // component gets a file of its own, named apart from every story file.
+ const taken = new Set(entries.map((entry) => entry.file.toLowerCase()))
+ const itemNames = new Map(
+ entries.map((entry) => [
+ entry.file,
+ claimName(`${entry.file}Item`, taken, { key: (name) => name.toLowerCase() })
+ ])
+ )
+ const model = (set: SceneNode, file: string, references?: ComponentReferences) =>
+ componentModel(graph, set, {
+ vectorElement,
+ references,
+ name: file,
+ itemName: itemNames.get(file)
+ })
const alone = new Map<string, ComponentModel>()
for (const { group, file } of entries) {
const component = group.set && model(group.set, file)
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index 7c76c868f..a71b9f08e 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -1,7 +1,7 @@
import { behaviourArgs } from '#dom-css/behaviours/args'
import { uniq } from 'es-toolkit/array'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { readBehaviour, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'
import type { StoryProp } from './module'
@@ -21,7 +21,10 @@ 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. */
+ /**
+ * The component set, or standalone component with a behaviour, the group shows, which may
+ * generate a component of its own.
+ */
set?: SceneNode
}
@@ -87,7 +90,9 @@ function componentGroup(page: SceneNode, component: SceneNode): StoryGroup {
name: component.name,
props: [],
variants: [{ values: [], node: component }],
- linkNode: component.name
+ linkNode: component.name,
+ // A standalone component with a behaviour, such as tabs, may generate a component too.
+ ...(readBehaviour(component) ? { set: component } : {})
}
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index d7ffb5057..085bd4a08 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -3,7 +3,8 @@ import {
SceneGraph,
withBehaviour,
withIcon,
- type Behaviour
+ type Behaviour,
+ type SceneNode
} from '@open-pencil/scene-graph'
const solid = (r: number, g: number, b: number) => [
@@ -112,7 +113,7 @@ export function checkboxSet() {
}
/** A toggle whose label reads differently when pressed. */
-export function toggleSet() {
+export function toggleSet(graph?: SceneGraph) {
return componentSet(
'Toggle',
{ Pressed: ['No', 'Yes'] },
@@ -122,7 +123,9 @@ export function toggleSet() {
},
(graph, variant, { Pressed }) => {
graph.createNode('TEXT', variant, { name: 'Label', text: Pressed === 'Yes' ? 'On' : 'Off' })
- }
+ },
+ undefined,
+ graph
)
}
@@ -222,8 +225,191 @@ export function settingsSectionSet() {
return { graph, set: section.set, switchSet: toggle.set }
}
+/**
+ * Tabs as a standalone component, as design JSX's `Tabs.Root` builds them: a list of triggers
+ * and a panel per trigger, each labelled.
+ */
+export function tabsComponent() {
+ const graph = new SceneGraph()
+ const slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]
+ const tabs = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ name: 'Settings',
+ width: 200,
+ height: 120
+ })
+ const list = graph.createNode('FRAME', tabs.id, {
+ name: 'List',
+ componentPropertyReferences: slot('list-slot'),
+ width: 200,
+ height: 24
+ })
+ const panels = graph.createNode('FRAME', tabs.id, {
+ name: 'Panels',
+ componentPropertyReferences: slot('panels-slot'),
+ y: 30,
+ width: 200,
+ height: 80
+ })
+ for (const [index, label] of ['Account', 'Password'].entries()) {
+ const trigger = graph.createNode('FRAME', list.id, {
+ name: 'Trigger',
+ x: index * 90,
+ width: 80,
+ height: 24,
+ fills: index === 0 ? COLORS.on : COLORS.off
+ })
+ graph.createNode('TEXT', trigger.id, { name: 'Label', text: label })
+ // Only the first tab's panel shows as designed, as design JSX draws tabs.
+ const panel = graph.createNode('FRAME', panels.id, {
+ name: 'Panel',
+ width: 200,
+ height: 80,
+ visible: index === 0
+ })
+ graph.createNode('TEXT', panel.id, { name: 'Body', text: `${label} settings` })
+ }
+ graph.updateNode(tabs.id, {
+ pluginData: withBehaviour(tabs, {
+ ...emptyBehaviour('tabs'),
+ parts: { list: 'list-slot', panels: 'panels-slot' }
+ })
+ })
+ return { graph, set: graph.getNode(tabs.id) ?? tabs }
+}
+
+/**
+ * A group as design JSX builds one: a standalone component with the group's behaviour whose
+ * items slot holds instances of `item`, each labelled through the item's text property, with
+ * the item at `chosen` drawn on.
+ */
+function groupComponent(
+ graph: SceneGraph,
+ item: { set: SceneNode; on: string; off: string },
+ kind: 'radioGroup' | 'toggleGroup' | 'accordion',
+ labels: string[],
+ chosen: number | null
+) {
+ const variant = (value: string) =>
+ graph.getChildren(item.set.id).find((child) => child.name.includes(value))
+ const on = variant(item.on)
+ const off = variant(item.off)
+ if (!on || !off) throw new Error('Expected the item drawn on and off')
+ const group = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ name: 'Plan',
+ width: 200,
+ height: 120
+ })
+ const items = graph.createNode('FRAME', group.id, {
+ name: 'Items',
+ componentPropertyReferences: [{ propertyId: 'items-slot', field: 'SLOT_CONTENT' }],
+ width: 200,
+ height: 120
+ })
+ for (const [index, label] of labels.entries()) {
+ const instance = graph.createInstance(index === chosen ? on.id : off.id, items.id, {
+ name: 'Item',
+ y: index * 30
+ })
+ if (!instance) throw new Error('Expected the item placed')
+ graph.updateNode(instance.id, {
+ componentPropertyAssignments: { ...instance.componentPropertyAssignments, label }
+ })
+ const relabel = (id: string) => {
+ for (const child of graph.getChildren(id)) {
+ if (child.type === 'TEXT') graph.updateNode(child.id, { text: label })
+ relabel(child.id)
+ }
+ }
+ relabel(instance.id)
+ }
+ graph.updateNode(group.id, {
+ pluginData: withBehaviour(group, { ...emptyBehaviour(kind), parts: { items: 'items-slot' } })
+ })
+ return { graph, set: graph.getNode(group.id) ?? group }
+}
+
+/** Gives a set a text property and a label layer in every variant bound to it. */
+function labelled(graph: SceneGraph, set: SceneNode) {
+ graph.updateNode(set.id, {
+ componentPropertyDefinitions: [
+ ...set.componentPropertyDefinitions,
+ { id: 'label', name: 'Label', type: 'TEXT', defaultValue: 'Option' }
+ ]
+ })
+ for (const variant of graph.getChildren(set.id))
+ graph.createNode('TEXT', variant.id, {
+ name: 'Label',
+ text: 'Option',
+ x: 24,
+ componentPropertyReferences: [{ propertyId: 'label', field: 'TEXT' }]
+ })
+}
+
+/** A radio group of three labelled radios, the second chosen. */
+export function radioGroupComponent() {
+ const graph = new SceneGraph()
+ const radio = componentSet(
+ 'Radio',
+ { Checked: ['Off', 'On'] },
+ {
+ ...emptyBehaviour('radio'),
+ booleans: { value: { propertyId: 'checked', on: 'On', off: 'Off' } }
+ },
+ (graph, variant, { Checked }) => {
+ graph.updateNode(variant, { width: 120, height: 20 })
+ graph.createNode('FRAME', variant, {
+ name: 'Dot',
+ width: 16,
+ height: 16,
+ fills: Checked === 'On' ? COLORS.on : COLORS.off
+ })
+ },
+ undefined,
+ graph
+ )
+ labelled(graph, radio.set)
+ return groupComponent(
+ graph,
+ { set: graph.getNode(radio.set.id) ?? radio.set, on: 'On', off: 'Off' },
+ 'radioGroup',
+ ['Basic', 'Pro', 'Team'],
+ 1
+ )
+}
+
+/**
+ * A toggle group of the standalone toggle, which a document can also use on its own, the
+ * first chosen.
+ */
+export function toggleGroupComponent() {
+ const graph = new SceneGraph()
+ const { set } = toggleSet(graph)
+ labelled(graph, set)
+ return groupComponent(
+ graph,
+ { set: graph.getNode(set.id) ?? set, on: 'Yes', off: 'No' },
+ 'toggleGroup',
+ ['Left', 'Center'],
+ 0
+ )
+}
+
+/** An accordion of two collapsible items, none open. */
+export function accordionComponent() {
+ const graph = new SceneGraph()
+ const { set } = collapsibleSet(graph)
+ labelled(graph, set)
+ return groupComponent(
+ graph,
+ { set: graph.getNode(set.id) ?? set, on: 'Yes', off: 'No' },
+ 'accordion',
+ ['Billing', 'Usage'],
+ null
+ )
+}
+
/** A collapsible whose content shows only when open. */
-export function collapsibleSet() {
+export function collapsibleSet(graph?: SceneGraph) {
const slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]
return componentSet(
'Disclosure',
@@ -249,6 +435,8 @@ export function collapsibleSet() {
width: 40,
height: 10
})
- }
+ },
+ undefined,
+ graph
)
}
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index fdc54dc13..4297b8e16 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -4,22 +4,35 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import {
+ accordionComponent,
buttonSet,
collapsibleSet,
labelledButtonSet,
+ radioGroupComponent,
settingsSectionSet,
- switchSet
+ switchSet,
+ tabsComponent,
+ toggleGroupComponent
} from '#dom-css-tests/behaviours/fixtures'
import { exportStorybook } from '#dom-css/index'
import { createElement, type ComponentType } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
+import ts from 'typescript'
/** The packages generated code imports, linked so it resolves them as an app would. */
-const APP_PACKAGES = ['react', 'react-dom', 'radix-ui', '@iconify/react', 'storybook']
+const APP_PACKAGES = [
+ 'react',
+ 'react-dom',
+ 'radix-ui',
+ '@iconify/react',
+ 'storybook',
+ '@types/react'
+]
const output = await mkdtemp(join(tmpdir(), 'open-pencil-react-'))
await mkdir(join(output, 'node_modules'))
await mkdir(join(output, 'node_modules', '@iconify'))
+await mkdir(join(output, 'node_modules', '@types'))
for (const name of APP_PACKAGES)
await symlink(
dirname(Bun.resolveSync(`${name}/package.json`, import.meta.dir)),
@@ -42,7 +55,31 @@ async function generate(fixture: ReturnType<typeof switchSet>) {
)
const component = module[name]
if (!component) throw new Error(`${name}.tsx exports no ${name}`)
- return { files, component, stories }
+ return { files, component, stories, folder }
+}
+
+const CSS_MODULES =
+ "declare module '*.module.css' { const styles: Record<string, string>; export default styles }"
+
+/** A generated component's type errors, checked as an app's strict TypeScript would. */
+async function typeErrors(folder: string, name: string): Promise<string[]> {
+ await writeFile(join(folder, 'css-modules.d.ts'), CSS_MODULES)
+ const program = ts.createProgram(
+ [join(folder, `${name}.tsx`), join(folder, 'css-modules.d.ts')],
+ {
+ strict: true,
+ noEmit: true,
+ skipLibCheck: true,
+ jsx: ts.JsxEmit.ReactJSX,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ target: ts.ScriptTarget.ES2022,
+ types: []
+ }
+ )
+ return ts
+ .getPreEmitDiagnostics(program)
+ .map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
}
const render = (component: ComponentType<Props>, props: Props = {}) =>
@@ -93,6 +130,60 @@ describe('generated React components', () => {
expect(html).toContain('data-state="checked"')
})
+ test('tabs show the panel of the chosen tab, by the slug of its label', async () => {
+ const { component } = await generate(tabsComponent())
+ const first = render(component)
+ expect(first).toContain('role="tablist"')
+ expect(first).toContain('Account settings')
+ expect(first).not.toContain('Password settings')
+ const second = render(component, { defaultValue: 'password' })
+ expect(second).toContain('Password settings')
+ expect(second).not.toContain('Account settings')
+ })
+
+ test('a radio group writes an item component and chooses among its labelled items', async () => {
+ const { files, component } = await generate(radioGroupComponent())
+ expect(files.map((file) => file.path)).toContain('PlanItem.tsx')
+ const checked = (html: string) =>
+ [...html.matchAll(/<button[^>]*role="radio"[^>]*>/g)].map((tag) =>
+ tag[0].includes('aria-checked="true"')
+ )
+ // The design draws the second item chosen.
+ const drawn = render(component)
+ expect(checked(drawn)).toEqual([false, true, false])
+ expect(drawn).toContain('Team')
+ expect(checked(render(component, { defaultValue: 'team' }))).toEqual([false, false, true])
+ })
+
+ test("a toggle group's items are the group's item, not the standalone toggle", async () => {
+ const { files, component } = await generate(toggleGroupComponent())
+ const group = String(files.find((file) => file.path === 'Plan.tsx')?.content)
+ expect(group).toContain('PlanItem')
+ expect(group).not.toMatch(/import \{? ?Toggle\b/)
+ const html = render(component)
+ expect([...html.matchAll(/data-state="(on|off)"/g)].map((match) => match[1])).toEqual([
+ 'on',
+ 'off'
+ ])
+ })
+
+ test('an accordion opens the item it is given and starts with none', async () => {
+ const { component } = await generate(accordionComponent())
+ const states = (html: string) =>
+ [...html.matchAll(/<button[^>]*aria-expanded="(true|false)"/g)].map((match) => match[1])
+ expect(states(render(component))).toEqual(['false', 'false'])
+ expect(states(render(component, { defaultValue: 'usage' }))).toEqual(['false', 'true'])
+ // The heading around each trigger keeps its level but not its own margins.
+ expect(render(component)).toMatch(/<h3[^>]*style="margin:0;font:inherit"/)
+ })
+
+ test('a single choice group takes the single choice props Radix types', async () => {
+ for (const fixture of [accordionComponent(), toggleGroupComponent()]) {
+ const { folder } = await generate(fixture)
+ expect(await typeErrors(folder, fixture.set.name)).toEqual([])
+ }
+ })
+
test('a button sets its other variant properties as data attributes', async () => {
const { component } = await generate(buttonSet())
const large = render(component, { size: 'Large' })
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index 3d8e22fc4..64f3c5f98 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -4,11 +4,15 @@ import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import {
+ accordionComponent,
buttonSet,
collapsibleSet,
labelledButtonSet,
+ radioGroupComponent,
settingsSectionSet,
- switchSet
+ switchSet,
+ tabsComponent,
+ toggleGroupComponent
} from '#dom-css-tests/behaviours/fixtures'
import { exportStorybook } from '#dom-css/index'
import { createSSRApp, h, type Component } from 'vue'
@@ -106,6 +110,66 @@ describe('generated Vue components', () => {
expect(html).toContain('data-state="checked"')
})
+ test('tabs show the panel of the chosen tab, by the slug of its label', async () => {
+ const { component } = await generate(tabsComponent())
+ const first = await render(component)
+ expect(first).toContain('role="tablist"')
+ expect(first).toContain('Account settings')
+ expect(first).not.toContain('Password settings')
+ const second = await render(component, { value: 'password' })
+ expect(second).toContain('Password settings')
+ expect(second).not.toContain('Account settings')
+ })
+
+ test('a radio group writes an item component and chooses among its labelled items', async () => {
+ const { files, component } = await generate(radioGroupComponent())
+ expect(files.map((file) => file.path)).toContain('PlanItem.vue')
+ const checked = (html: string) =>
+ [...html.matchAll(/<button[^>]*role="radio"[^>]*>/g)].map((tag) =>
+ tag[0].includes('aria-checked="true"')
+ )
+ // The design draws the second item chosen.
+ const drawn = await render(component)
+ expect(checked(drawn)).toEqual([false, true, false])
+ expect(drawn).toContain('Team')
+ expect(checked(await render(component, { value: 'team' }))).toEqual([false, false, true])
+ })
+
+ test("a group's item component is named apart from another component's file", async () => {
+ const fixture = radioGroupComponent()
+ const page = fixture.graph.getPages()[0].id
+ fixture.graph.createNode('COMPONENT', page, { name: 'PlanItem' })
+ const files = await exportStorybook(fixture.graph, { framework: 'vue' })
+ const paths = files.map((file) => file.path)
+ expect(paths).toContain('PlanItem.stories.ts')
+ expect(paths).toContain('PlanItem2.vue')
+ expect(String(files.find((file) => file.path === 'Plan.vue')?.content)).toContain(
+ `import PlanItem2 from './PlanItem2.vue'`
+ )
+ })
+
+ test("a toggle group's items are the group's item, not the standalone toggle", async () => {
+ const { files, component } = await generate(toggleGroupComponent())
+ const group = String(files.find((file) => file.path === 'Plan.vue')?.content)
+ expect(group).toContain('PlanItem')
+ expect(group).not.toMatch(/import \{? ?Toggle\b/)
+ const html = await render(component)
+ expect([...html.matchAll(/data-state="(on|off)"/g)].map((match) => match[1])).toEqual([
+ 'on',
+ 'off'
+ ])
+ })
+
+ test('an accordion opens the item it is given and starts with none', async () => {
+ const { component } = await generate(accordionComponent())
+ const states = (html: string) =>
+ [...html.matchAll(/<button[^>]*aria-expanded="(true|false)"/g)].map((match) => match[1])
+ expect(states(await render(component))).toEqual(['false', 'false'])
+ expect(states(await render(component, { value: 'usage' }))).toEqual(['false', 'true'])
+ // The heading around each trigger keeps its level but not its own margins.
+ expect(await render(component)).toMatch(/<h3[^>]*style="margin:0;font:inherit;?"/)
+ })
+
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.ts
index e6f1e8746..de6a72a68 100644
--- a/tests/e2e/dom-css/generated-components.spec.ts
+++ b/tests/e2e/dom-css/generated-components.spec.ts
@@ -83,6 +83,92 @@ function switchGraph(graph?: SceneGraph): SceneGraph {
)
}
+/** A radio group of two radios, each labelled through the radio's text property, the first chosen. */
+function radioGroupGraph(): SceneGraph {
+ const graph = controlSet(
+ 'Radio',
+ { name: 'Checked', values: ['Off', 'On'] },
+ {
+ ...emptyBehaviour('radio'),
+ booleans: { value: { propertyId: 'value', on: 'On', off: 'Off' } }
+ },
+ (graph, variantId, value) => {
+ graph.updateNode(variantId, {
+ width: 100,
+ height: 20,
+ fills: value === 'On' ? fill(0.3, 0.27, 0.9) : fill(0.8, 0.84, 0.88)
+ })
+ graph.createNode('TEXT', variantId, {
+ name: 'Label',
+ text: 'Option',
+ componentPropertyReferences: [{ propertyId: 'label', field: 'TEXT' }]
+ })
+ }
+ )
+ const radio = [...graph.getAllNodes()].find((node) => node.type === 'COMPONENT_SET')
+ if (!radio) throw new Error('Expected the radio set')
+ graph.updateNode(radio.id, {
+ componentPropertyDefinitions: [
+ ...radio.componentPropertyDefinitions,
+ { id: 'label', name: 'Label', type: 'TEXT', defaultValue: 'Option' }
+ ]
+ })
+ const variant = (value: string) =>
+ graph.getChildren(radio.id).find((child) => child.name === `Checked=${value}`)
+ const group = graph.createNode('COMPONENT', graph.getPages()[0].id, { name: 'Plan' })
+ const items = graph.createNode('FRAME', group.id, {
+ name: 'Items',
+ componentPropertyReferences: slot('items'),
+ width: 100,
+ height: 50
+ })
+ for (const [index, label] of ['Basic', 'Pro'].entries()) {
+ const main = variant(index === 0 ? 'On' : 'Off')
+ if (!main) throw new Error('Expected the radio drawn on and off')
+ const item = graph.createInstance(main.id, items.id, { name: 'Item', y: index * 25 })
+ if (!item) throw new Error('Expected the item placed')
+ graph.updateNode(item.id, {
+ componentPropertyAssignments: { ...item.componentPropertyAssignments, label }
+ })
+ }
+ graph.updateNode(group.id, {
+ pluginData: withBehaviour(group, { ...emptyBehaviour('radioGroup'), parts: { items: 'items' } })
+ })
+ return graph
+}
+
+/** Tabs whose list holds a trigger and whose panels a panel per tab. */
+function tabsGraph(): SceneGraph {
+ const graph = new SceneGraph()
+ const tabs = graph.createNode('COMPONENT', graph.getPages()[0].id, { name: 'Settings' })
+ const list = graph.createNode('FRAME', tabs.id, {
+ name: 'List',
+ componentPropertyReferences: slot('list'),
+ width: 160,
+ height: 20
+ })
+ const panels = graph.createNode('FRAME', tabs.id, {
+ name: 'Panels',
+ componentPropertyReferences: slot('panels'),
+ y: 24,
+ width: 160,
+ height: 40
+ })
+ for (const label of ['Account', 'Password']) {
+ const trigger = graph.createNode('FRAME', list.id, { name: 'Trigger', width: 70, height: 20 })
+ graph.createNode('TEXT', trigger.id, { name: 'Label', text: label })
+ const panel = graph.createNode('FRAME', panels.id, { name: 'Panel', width: 160, height: 40 })
+ graph.createNode('TEXT', panel.id, { name: 'Body', text: `${label} settings` })
+ }
+ graph.updateNode(tabs.id, {
+ pluginData: withBehaviour(tabs, {
+ ...emptyBehaviour('tabs'),
+ parts: { list: 'list', panels: 'panels' }
+ })
+ })
+ return graph
+}
+
/** A collapsible section whose content holds a switch drawn on, with the switch's set beside it. */
function sectionGraph(): SceneGraph {
const graph = switchGraph()
@@ -319,6 +405,28 @@ for (const framework of ['vue', 'react'] as const) {
await expect(nested).toHaveCSS('background-color', 'rgb(204, 214, 224)')
})
+ test('a radio group chooses the radio clicked, starting on the one drawn chosen', async ({
+ page
+ }, info) => {
+ server = await serveComponent(radioGroupGraph(), framework, info.outputPath('plan'), 'Plan')
+ await page.goto(server.resolvedUrls?.local[0] ?? '')
+ const enabled = page.locator('#enabled')
+ await expect(enabled.getByRole('radio', { name: 'Basic' })).toBeChecked()
+ await enabled.getByRole('radio', { name: 'Pro' }).click()
+ await expect(enabled.getByRole('radio', { name: 'Pro' })).toBeChecked()
+ await expect(enabled.getByRole('radio', { name: 'Basic' })).not.toBeChecked()
+ })
+
+ test('tabs show the panel of the tab clicked', async ({ page }, info) => {
+ server = await serveComponent(tabsGraph(), framework, info.outputPath('tabs'), 'Settings')
+ await page.goto(server.resolvedUrls?.local[0] ?? '')
+ const enabled = page.locator('#enabled')
+ await expect(enabled.getByText('Account settings')).toBeVisible()
+ await enabled.getByRole('tab', { name: 'Password' }).click()
+ await expect(enabled.getByText('Password settings')).toBeVisible()
+ await expect(enabled.getByText('Account settings')).toBeHidden()
+ })
+
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] ?? '')