Skip to content

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

feat(dom-css): compile component variants into state styles (#965)

Danila Poyarkov425420468544
diff --git a/bun.lock b/bun.lock
index e286b98b8..94ada27d3 100644
--- a/bun.lock
+++ b/bun.lock
@@ -291,6 +291,7 @@
"@acemir/cssom": "^0.9.31",
"@open-pencil/emit": "workspace:*",
"css-tree": "^3.2.1",
+ "cssesc": "^3.0.0",
"dedent": "^1.7.2",
"es-toolkit": "^1.52.0",
"js-base64": "^3.9.3",
@@ -302,6 +303,7 @@
"devDependencies": {
"@types/bun": "^1.3.14",
"@types/css-tree": "^3.2.0",
+ "@types/cssesc": "^3.0.2",
"tsdown": "^0.22.14",
"typescript": "~5.8.3",
},
@@ -2071,6 +2073,8 @@
"@types/css-tree": ["@types/[email protected]", "", {}, "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw=="],
+ "@types/cssesc": ["@types/[email protected]", "", {}, "sha512-Qii6nTRktvtI380EloxH/V7MwgrYxkPgBI+NklUjQuhzgAd1AqT3QDJd+eD+0doRADgfwvtagLRo7JFa7aMHXg=="],
+
"@types/culori": ["@types/[email protected]", "", {}, "sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ=="],
"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
diff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.md
index 846c3218e..9c07fdaf2 100644
--- a/packages/docs/development/behaviours-and-preview.md
+++ b/packages/docs/development/behaviours-and-preview.md
@@ -40,6 +40,18 @@ Preview is a per-pane mode (`EditorViewState.play`). It runs controls as real co
Controls and DOM keys use layer paths (names below the island root), not node ids: a variant switch rebuilds an instance's layers with new ids, and a stable path keeps the DOM in place, including a focused input.
+## Code export
+
+Export reads the same model as preview. `behaviourArgs` gives a component set its props: a boolean value drawn by an on/off variant property becomes `checked`, `pressed`, `open`, or `disabled`.
+
+`stateStyles` merges a set's variants into one markup tree, matching layers by layer path:
+
+- The rest variant is the base. Each other variant becomes a rule holding only what it changes, under conditions on the control's root.
+- The conditions are the attributes Reka and Radix set, `data-state` and `data-disabled`; the browser's `:hover`, `:active`, and `:focus-visible`; and a `data-*` attribute for any other variant property, which the generated component sets from its prop.
+- Layers only some variants draw stay in the tree, hidden where absent, and a label that reads differently is a layer per state. A combination the set doesn't draw combines from its parts, and a drawn combination keeps only what its parts don't already give.
+
+`stateStylesToCSS` writes the result as a stylesheet with a readable class per layer. `stateStylesToTailwind` writes it as utilities behind state variants, with a named group per control so a control nested in another reacts only to its own root.
+
## Adding a kind or a part
1. Add the kind to `BEHAVIOUR_KINDS` and its contract to `BEHAVIOUR_CONTRACTS` in scene-graph; part ids follow Reka's part names.
diff --git a/packages/dom-css/AGENTS.md b/packages/dom-css/AGENTS.md
index 53d960e3c..b5601c767 100644
--- a/packages/dom-css/AGENTS.md
+++ b/packages/dom-css/AGENTS.md
@@ -4,6 +4,7 @@ DOM, CSS, HTML, JSX, and Tailwind projection between documents and SceneGraph, w
- `src/import/` — HTML, CSS, JSX, and Tailwind to SceneGraph, including the `jsx-runtime` entries and CSS value parsing.
- `src/export/` — SceneGraph to HTML, Tailwind JSX, and Storybook: projection, CSS formatting, the HTML bundle, and printers. `src/export/index.ts` is the `./export` entry.
+- `src/behaviours/` — what a behaviour means in the DOM, shared by preview and export: controls and layer roles, story props, and state styles compiled from variants. Exported from `./export`.
- `src/runtime/` — browser and headless CSS runtimes.
- `src/tokens/` — variables as design tokens: CSS custom property names, Tailwind namespaces from `twirlwind`, and units. Shared by both directions and exported from `./export`.
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index 98494d213..dc4c1e5d5 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -73,6 +73,7 @@
"devDependencies": {
"@types/bun": "^1.3.14",
"@types/css-tree": "^3.2.0",
+ "@types/cssesc": "^3.0.2",
"tsdown": "^0.22.14",
"typescript": "~5.8.3"
},
@@ -80,6 +81,7 @@
"@acemir/cssom": "^0.9.31",
"@open-pencil/emit": "workspace:*",
"css-tree": "^3.2.1",
+ "cssesc": "^3.0.0",
"dedent": "^1.7.2",
"es-toolkit": "^1.52.0",
"js-base64": "^3.9.3",
diff --git a/packages/dom-css/src/behaviours/index.ts b/packages/dom-css/src/behaviours/index.ts
index 0f90a0a31..4ca3a132e 100644
--- a/packages/dom-css/src/behaviours/index.ts
+++ b/packages/dom-css/src/behaviours/index.ts
@@ -7,3 +7,4 @@ export {
type StatesModel
} from './controls'
export { controlRoles, groupOf, type ControlRole } from './roles'
+export * from './states'
diff --git a/packages/dom-css/src/behaviours/states/conditions.ts b/packages/dom-css/src/behaviours/states/conditions.ts
new file mode 100644
index 000000000..4da1f9afc
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/conditions.ts
@@ -0,0 +1,87 @@
+import {
+ behaviourProperties,
+ readBehaviour,
+ type ComponentPropertyDefinition,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+import { behaviourArgs, type BehaviourArgs, type BooleanArg } from '../args'
+import type { StateCondition } from './types'
+
+/** The `data-state` value a boolean prop sets when on, as Reka and Radix set it. */
+const DATA_STATE_ON: Partial<Record<string, string>> = {
+ checked: 'checked',
+ pressed: 'on',
+ open: 'open'
+}
+
+const INTERACTIONS = ['hover', 'pressed', 'focus'] as const
+
+/** The condition a variant property's value adds, or `null` for its rest value. */
+type ValueCondition = (value: string) => StateCondition | null
+
+function booleanCondition(arg: BooleanArg): ValueCondition {
+ return (value) => {
+ if (value === arg.off) return null
+ if (arg.name === 'disabled') return { type: 'disabled' }
+ const state = DATA_STATE_ON[arg.name]
+ return state ? { type: 'state', value: state } : { type: 'prop', name: arg.name, value }
+ }
+}
+
+/** The interaction-state property's values: hover, pressed, focus, and disabled. */
+function interactionCondition(set: SceneNode, states: NonNullable<BehaviourArgs['states']>) {
+ const stored = readBehaviour(set)?.states
+ const byValue = new Map<string, StateCondition>()
+ for (const state of INTERACTIONS) {
+ const value = stored?.[state]
+ if (value !== undefined && value !== states.rest)
+ byValue.set(value, { type: 'interaction', state })
+ }
+ if (states.disabled !== undefined) byValue.set(states.disabled, { type: 'disabled' })
+ const name = states.property
+ return (value: string): StateCondition | null => {
+ if (value === states.rest) return null
+ // A value the behaviour does not map to a state still shows its variant, as a prop.
+ return byValue.get(value) ?? { type: 'prop', name, value }
+ }
+}
+
+/** Any other variant property is a prop the generated component sets as `data-*`. */
+function propCondition(definition: ComponentPropertyDefinition): ValueCondition {
+ return (value) =>
+ value === definition.defaultValue ? null : { type: 'prop', name: definition.name, value }
+}
+
+/**
+ * Reads the conditions that show each variant of a set: from its behaviour's boolean props and
+ * interaction states, and every other variant property as a prop. `null` for a variant that
+ * leaves a property out, which can't be placed among the others.
+ */
+export function variantConditions(
+ graph: SceneGraph,
+ set: SceneNode
+): (variant: SceneNode) => StateCondition[] | null {
+ const args = behaviourArgs(graph, set)
+ const conditionOf = (definition: ComponentPropertyDefinition): ValueCondition => {
+ const boolean = args?.booleans.get(definition.name)
+ if (boolean) return booleanCondition(boolean)
+ if (args?.states?.property === definition.name) return interactionCondition(set, args.states)
+ return propCondition(definition)
+ }
+ const byProperty = new Map(
+ behaviourProperties(graph, set)
+ .filter((definition) => definition.type === 'VARIANT')
+ .map((definition) => [definition.name, conditionOf(definition)] as const)
+ )
+ return (variant) => {
+ const conditions: StateCondition[] = []
+ for (const [property, condition] of byProperty) {
+ if (!Object.hasOwn(variant.componentPropertyValues, property)) return null
+ const added = condition(variant.componentPropertyValues[property])
+ if (added) conditions.push(added)
+ }
+ return conditions
+ }
+}
diff --git a/packages/dom-css/src/behaviours/states/css.ts b/packages/dom-css/src/behaviours/states/css.ts
new file mode 100644
index 000000000..58ad69614
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/css.ts
@@ -0,0 +1,80 @@
+import type {
+ DesignDocument,
+ DesignElement,
+ DesignNode,
+ DesignStyleDeclaration
+} from '#dom-css/types'
+import cssesc from 'cssesc'
+import { compact, sortBy } from 'es-toolkit/array'
+
+import { layerClassNames, propAttribute } from './names'
+import type { StateCondition, StateElement, StateNode, StateStyles } from './types'
+
+export interface StateStylesheet {
+ /** The merged markup, each layer carrying its class and no inline style. */
+ document: DesignDocument
+ css: string
+}
+
+/** A CSS string for an attribute selector's value. */
+const quoted = (value: string) => cssesc(value, { quotes: 'double', wrap: true })
+
+/** The selector part a condition adds to the control's root. */
+export function conditionSelector(condition: StateCondition): string {
+ if (condition.type === 'state') return `[data-state=${quoted(condition.value)}]`
+ if (condition.type === 'disabled') return '[data-disabled]'
+ if (condition.type === 'prop')
+ return `[${propAttribute(condition.name)}=${quoted(condition.value)}]`
+ if (condition.state === 'focus') return ':focus-visible'
+ // A disabled control keeps its disabled look under the pointer.
+ return `${condition.state === 'hover' ? ':hover' : ':active'}:not([data-disabled])`
+}
+
+function designNode(node: StateNode, classes: Map<StateElement, string>): DesignNode {
+ if (node.type === 'text') return node
+ const className = compact([node.attrs.class, classes.get(node)]).join(' ')
+ const element: DesignElement = {
+ type: 'element',
+ tagName: node.tagName,
+ attrs: { ...node.attrs, class: className },
+ children: node.children.map((child) => designNode(child, classes))
+ }
+ return element
+}
+
+/**
+ * The state styles as a stylesheet with a readable class per layer. A rule with more
+ * conditions comes later and has a more specific selector, so a combined variant wins over
+ * each of its parts. The sheet is built with the CSS object model, which rejects an invalid
+ * selector and prints the declarations.
+ */
+export async function stateStylesToCSS(styles: StateStyles): Promise<StateStylesheet> {
+ const classes = layerClassNames(styles)
+ const rootClass = classes.get(styles.root) ?? ''
+ const rules: { order: number; selector: string; style: DesignStyleDeclaration }[] = []
+ for (const [element, className] of classes) {
+ const own = element === styles.root ? '' : ` .${className}`
+ if (Object.keys(element.base).length > 0)
+ rules.push({ order: 0, selector: `.${rootClass}${own}`, style: element.base })
+ for (const rule of element.rules) {
+ const when = rule.conditions.map(conditionSelector).join('')
+ rules.push({
+ order: rule.conditions.length,
+ selector: `.${rootClass}${when}${own}`,
+ style: rule.style
+ })
+ }
+ }
+ // Loaded only when a stylesheet is written; the CSS object model is not bundled for browsers.
+ const { CSSStyleSheet } = await import('@acemir/cssom')
+ const sheet = new CSSStyleSheet()
+ for (const rule of sortBy(rules, [(item) => item.order])) {
+ const index = sheet.insertRule(`${rule.selector} {}`, sheet.cssRules.length)
+ for (const [property, value] of Object.entries(rule.style))
+ sheet.cssRules[index]?.style.setProperty(property, value)
+ }
+ return {
+ document: { type: 'document', children: [designNode(styles.root, classes)] },
+ css: sheet.toString()
+ }
+}
diff --git a/packages/dom-css/src/behaviours/states/index.ts b/packages/dom-css/src/behaviours/states/index.ts
new file mode 100644
index 000000000..d13eaacee
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/index.ts
@@ -0,0 +1,4 @@
+export { stateStyles } from './model'
+export type { StateCondition, StateElement, StateNode, StateRule, StateStyles } from './types'
+export { conditionSelector, stateStylesToCSS, type StateStylesheet } from './css'
+export { stateStylesToTailwind, type StateTailwindOptions } from './tailwind'
diff --git a/packages/dom-css/src/behaviours/states/layers.ts b/packages/dom-css/src/behaviours/states/layers.ts
new file mode 100644
index 000000000..e5c11d0a0
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/layers.ts
@@ -0,0 +1,132 @@
+import { sceneNodeToDesignDocument } from '#dom-css/export/projection'
+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 type { StateElement } from './types'
+
+/** A variant's projected layer, keyed so the same layer matches across variants. */
+export interface VariantLayer {
+ type: 'element'
+ key: string
+ name: string
+ element: DesignElement
+ children: Array<VariantLayer | DesignText>
+}
+
+/** Where the set places a variant, which is not the component's own style. */
+const PLACEMENT = ['position', 'left', 'top', 'right', 'bottom', 'inset']
+
+function textContent(element: DesignElement): string | null {
+ const texts = element.children.filter((child): child is DesignText => child.type === 'text')
+ return texts.length > 0 ? texts.map((text) => text.text).join('') : null
+}
+
+function variantLayer(
+ graph: SceneGraph,
+ variant: SceneNode,
+ node: DesignNode,
+ parentKey: string,
+ index: number
+): VariantLayer | DesignText {
+ if (node.type === 'text') return node
+ const source = node.sourceSceneNodeId
+ const path = source ? layerPath(graph, variant.id, source) : `${parentKey}/~${index}`
+ const text = textContent(node)
+ // A label that reads differently in a variant is a different layer, shown by its state.
+ const key = text === null ? path : `${path}\0${text}`
+ return {
+ type: 'element',
+ key,
+ name: node.sourceSceneNode?.name ?? node.tagName,
+ element: node,
+ children: node.children.map((child, i) => variantLayer(graph, variant, child, key, i))
+ }
+}
+
+/** A variant projected to DOM, without where the set places it. */
+export function projectVariant(graph: SceneGraph, variant: SceneNode): VariantLayer | null {
+ const document = sceneNodeToDesignDocument(graph, variant.id, { includeSourceIds: false })
+ const root = document.children.at(0)
+ if (root?.type !== 'element') return null
+ const style = root.inlineStyle ?? {}
+ // Absolutely placed layers inside still need the root as their containing block.
+ root.inlineStyle = {
+ ...omit(style, PLACEMENT),
+ ...(style.position ? { position: 'relative' } : {})
+ }
+ return {
+ type: 'element',
+ key: '',
+ name: variant.name,
+ element: root,
+ children: root.children.map((child, i) => variantLayer(graph, variant, child, '', i))
+ }
+}
+
+/** Every layer of a projected variant by key. */
+export function layersByKey(
+ root: VariantLayer,
+ into = new Map<string, VariantLayer>()
+): Map<string, VariantLayer> {
+ into.set(root.key, root)
+ for (const child of root.children) if (child.type === 'element') layersByKey(child, into)
+ return into
+}
+
+/** A merged layer starting from a variant's layer, with that layer's style as its base. */
+export function stateElement(layer: VariantLayer): StateElement {
+ return {
+ type: 'element',
+ key: layer.key,
+ name: layer.name,
+ tagName: layer.element.tagName,
+ attrs: { ...layer.element.attrs },
+ base: { ...layer.element.inlineStyle },
+ rules: [],
+ children: layer.children.map((child) => (child.type === 'text' ? child : stateElement(child)))
+ }
+}
+
+function hideAtRest(element: StateElement, hidden: Set<StateElement>): void {
+ element.base = { ...element.base, display: 'none' }
+ hidden.add(element)
+ for (const child of element.children) if (child.type === 'element') hideAtRest(child, hidden)
+}
+
+/**
+ * Adds the layers only `variant` draws to the merged tree, after the sibling they follow
+ * there. Each keeps the style this variant draws it with, hidden at rest, and is recorded in
+ * `hidden` so the variants that draw it show it again.
+ */
+export function mergeVariant(
+ into: StateElement,
+ variant: VariantLayer,
+ hidden: Set<StateElement>
+): void {
+ let previous = -1
+ for (const child of variant.children) {
+ if (child.type === 'text') continue
+ const index = into.children.findIndex(
+ (item) => item.type === 'element' && item.key === child.key
+ )
+ const existing = into.children.at(index)
+ if (index !== -1 && existing?.type === 'element') {
+ mergeVariant(existing, child, hidden)
+ previous = index
+ continue
+ }
+ const added = stateElement(child)
+ hideAtRest(added, hidden)
+ previous += 1
+ into.children.splice(previous, 0, added)
+ }
+}
+
+/** Every element of the merged tree, root first. */
+export function allElements(root: StateElement, into: StateElement[] = []): StateElement[] {
+ into.push(root)
+ for (const child of root.children) if (child.type === 'element') allElements(child, into)
+ return into
+}
diff --git a/packages/dom-css/src/behaviours/states/model.ts b/packages/dom-css/src/behaviours/states/model.ts
new file mode 100644
index 000000000..3385e9835
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/model.ts
@@ -0,0 +1,103 @@
+import type { DesignStyleDeclaration } from '#dom-css/types'
+import { isEmptyObject, isEqual } from 'es-toolkit/predicate'
+
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { variantConditions } from './conditions'
+import {
+ allElements,
+ layersByKey,
+ mergeVariant,
+ projectVariant,
+ stateElement,
+ type VariantLayer
+} from './layers'
+import type { StateCondition, StateElement, StateRule, StateStyles } from './types'
+
+/** Declarations `drawn` sets differently from `base`, with `unset` for ones it drops. */
+function difference(
+ base: DesignStyleDeclaration,
+ drawn: DesignStyleDeclaration
+): DesignStyleDeclaration {
+ const changed: DesignStyleDeclaration = {}
+ for (const [property, value] of Object.entries(drawn))
+ if (base[property] !== value) changed[property] = value
+ for (const property of Object.keys(base)) if (!(property in drawn)) changed[property] = 'unset'
+ return changed
+}
+
+/**
+ * What a variant changes on a layer: what it draws differently, showing a layer hidden at
+ * rest again, or hiding a layer it doesn't draw.
+ */
+function variantStyle(
+ element: StateElement,
+ layer: VariantLayer | undefined,
+ hiddenAtRest: boolean
+): DesignStyleDeclaration {
+ if (!layer) return hiddenAtRest ? {} : { display: 'none' }
+ const drawn = layer.element.inlineStyle ?? {}
+ if (!hiddenAtRest) return difference(element.base, drawn)
+ const display = Object.hasOwn(drawn, 'display') ? drawn.display : 'revert'
+ return difference(element.base, { ...drawn, display })
+}
+
+const isPartOf = (part: StateCondition[], whole: StateCondition[]) =>
+ part.length < whole.length &&
+ part.every((condition) => whole.some((other) => isEqual(condition, other)))
+
+/**
+ * Drops what a combined variant repeats. A rule for checked + hover also gets the rules for
+ * checked and for hover, so a declaration both of those already give with the same value
+ * goes; one where they disagree or say nothing stays. Rules left empty go.
+ */
+function pruneCombined(rules: StateRule[]): StateRule[] {
+ return rules.flatMap((rule) => {
+ const parts = rules.filter((other) => isPartOf(other.conditions, rule.conditions))
+ const repeated = (property: string, value: string) => {
+ const given = parts.filter((part) => property in part.style)
+ return given.length > 0 && given.every((part) => part.style[property] === value)
+ }
+ const style = Object.fromEntries(
+ Object.entries(rule.style).filter(([property, value]) => !repeated(property, value))
+ )
+ return isEmptyObject(style) ? [] : [{ ...rule, style }]
+ })
+}
+
+/**
+ * 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
+ * only some variants draw stay in the tree, hidden where absent.
+ *
+ * `null` when no variant shows the rest state, since every look then depends on a condition.
+ */
+export function stateStyles(graph: SceneGraph, set: SceneNode): StateStyles | null {
+ const conditionsOf = variantConditions(graph, set)
+ const variants = graph
+ .getChildren(set.id)
+ .filter((child) => child.type === 'COMPONENT' && child.visible)
+ .flatMap((variant) => {
+ const conditions = conditionsOf(variant)
+ const root = conditions && projectVariant(graph, variant)
+ return conditions && root ? [{ conditions, root }] : []
+ })
+ const rest = variants.find((variant) => variant.conditions.length === 0)
+ if (!rest) return null
+ const others = variants.filter((variant) => variant !== rest)
+
+ const root = stateElement(rest.root)
+ const hiddenAtRest = new Set<StateElement>()
+ for (const variant of others) mergeVariant(root, variant.root, hiddenAtRest)
+
+ const elements = allElements(root)
+ for (const variant of others) {
+ const layers = layersByKey(variant.root)
+ for (const element of elements) {
+ const style = variantStyle(element, layers.get(element.key), hiddenAtRest.has(element))
+ if (!isEmptyObject(style)) element.rules.push({ conditions: variant.conditions, style })
+ }
+ }
+ for (const element of elements) element.rules = pruneCombined(element.rules)
+ return { name: set.name, root }
+}
diff --git a/packages/dom-css/src/behaviours/states/names.ts b/packages/dom-css/src/behaviours/states/names.ts
new file mode 100644
index 000000000..9618f7207
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/names.ts
@@ -0,0 +1,39 @@
+import { claimName } from '#dom-css/export/storybook/names'
+import { kebabCase } from 'es-toolkit/string'
+
+import type { StateElement, StateStyles } from './types'
+
+const NOT_NAME_PART = /[^a-z0-9-]/g
+
+/** A CSS identifier made from a layer or set name, `fallback` when nothing of it is usable. */
+export function cssName(text: string, fallback: string): string {
+ const name = kebabCase(text).replace(NOT_NAME_PART, '')
+ return /^[a-z]/.test(name) ? name : `${fallback}${name ? `-${name}` : ''}`
+}
+
+/**
+ * A readable class per layer: the set's name for the root, `<root>__<layer>` below it,
+ * numbered where two layers share a name.
+ */
+export function layerClassNames(styles: StateStyles): Map<StateElement, string> {
+ const root = cssName(styles.name, 'component')
+ const names = new Map<StateElement, string>([[styles.root, root]])
+ const taken = new Set([root])
+ const visit = (element: StateElement) => {
+ for (const child of element.children) {
+ if (child.type !== 'element') continue
+ names.set(
+ child,
+ claimName(`${root}__${cssName(child.name, 'layer')}`, taken, { separator: '-' })
+ )
+ visit(child)
+ }
+ }
+ visit(styles.root)
+ return names
+}
+
+/** The attribute a generated component sets for a variant property it takes as a prop. */
+export function propAttribute(name: string): string {
+ return `data-${cssName(name, 'prop')}`
+}
diff --git a/packages/dom-css/src/behaviours/states/tailwind.ts b/packages/dom-css/src/behaviours/states/tailwind.ts
new file mode 100644
index 000000000..81302f919
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/tailwind.ts
@@ -0,0 +1,81 @@
+import { splitWhitespace } from '#dom-css/export/html'
+import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'
+import { twirl } from 'twirlwind'
+
+import { cssName, propAttribute } from './names'
+import type { StateCondition, StateNode, StateStyles } from './types'
+
+export interface StateTailwindOptions {
+ /** Custom properties declared in `@theme`; a `var()` naming one becomes its utility. */
+ themeVariables?: readonly string[]
+}
+
+/** A value inside a variant: bare when it is a plain word, else quoted with spaces as `_`. */
+const variantValue = (value: string) =>
+ /^[\w-]+$/.test(value) ? value : `"${value.replace(/\s/g, '_').replace(/"/g, '\\"')}"`
+
+/**
+ * The variant a condition adds. On the root it tests the root itself; below it, it tests the
+ * root through its named group, so a control nested in another reacts only to its own root.
+ */
+function variant(condition: StateCondition, group: string | null): string {
+ const on = (name: string) => (group ? `group-${name}/${group}:` : `${name}:`)
+ if (condition.type === 'state') return on(`data-[state=${variantValue(condition.value)}]`)
+ if (condition.type === 'disabled') return on('data-disabled')
+ if (condition.type === 'prop') {
+ const attribute = propAttribute(condition.name).slice('data-'.length)
+ return on(`data-[${attribute}=${variantValue(condition.value)}]`)
+ }
+ if (condition.state === 'focus') return on('focus-visible')
+ // A disabled control keeps its disabled look under the pointer.
+ const enabled = group ? `group-not-data-disabled/${group}:` : 'not-data-disabled:'
+ return `${enabled}${on(condition.state === 'hover' ? 'hover' : 'active')}`
+}
+
+function utilities(style: DesignStyleDeclaration, options: StateTailwindOptions): string[] {
+ const css = Object.entries(style)
+ .map(([property, value]) => `${property}: ${value}`)
+ .join('; ')
+ return css
+ ? splitWhitespace(twirl(css, { theme: { variables: options.themeVariables ?? [] } }))
+ : []
+}
+
+function designNode(
+ node: StateNode,
+ group: string,
+ isRoot: boolean,
+ options: StateTailwindOptions
+): DesignNode {
+ if (node.type === 'text') return node
+ const classes = [
+ ...(node.attrs.class ? splitWhitespace(node.attrs.class) : []),
+ ...(isRoot ? [`group/${group}`] : []),
+ ...utilities(node.base, options),
+ ...node.rules.flatMap((rule) => {
+ const prefix = rule.conditions
+ .map((condition) => variant(condition, isRoot ? null : group))
+ .join('')
+ return utilities(rule.style, options).map((utility) => `${prefix}${utility}`)
+ })
+ ]
+ return {
+ type: 'element',
+ tagName: node.tagName,
+ attrs: { ...node.attrs, class: classes.join(' ') },
+ children: node.children.map((child) => designNode(child, group, false, options))
+ }
+}
+
+/**
+ * The state styles as Tailwind utilities on each element: rest utilities, and each variant's
+ * changes behind the variants that show it. More stacked variants make a more specific
+ * selector, so a combined variant wins over each of its parts.
+ */
+export function stateStylesToTailwind(
+ styles: StateStyles,
+ options: StateTailwindOptions = {}
+): DesignDocument {
+ const group = cssName(styles.name, 'component')
+ return { type: 'document', children: [designNode(styles.root, group, true, options)] }
+}
diff --git a/packages/dom-css/src/behaviours/states/types.ts b/packages/dom-css/src/behaviours/states/types.ts
new file mode 100644
index 000000000..3c60b479e
--- /dev/null
+++ b/packages/dom-css/src/behaviours/states/types.ts
@@ -0,0 +1,40 @@
+import type { DesignStyleDeclaration, DesignText } from '#dom-css/types'
+
+/**
+ * What must hold on a control's root for a variant to show. Reka and Radix set `data-state`
+ * and `data-disabled` themselves; the browser sets the interactions; a generated component
+ * sets `data-*` from its props for every other variant property.
+ */
+export type StateCondition =
+ | { type: 'state'; value: string }
+ | { type: 'disabled' }
+ | { type: 'interaction'; state: 'hover' | 'pressed' | 'focus' }
+ | { type: 'prop'; name: string; value: string }
+
+/** What a variant changes on a layer, and the conditions that show that variant. */
+export interface StateRule {
+ conditions: StateCondition[]
+ style: DesignStyleDeclaration
+}
+
+/** A layer of the merged markup: its rest style and what each other variant changes. */
+export interface StateElement {
+ type: 'element'
+ /** The layer path below the variant, with the text when variants label a layer differently. */
+ key: string
+ /** The layer's name, for class names. */
+ name: string
+ tagName: string
+ attrs: Record<string, string>
+ base: DesignStyleDeclaration
+ rules: StateRule[]
+ children: StateNode[]
+}
+
+export type StateNode = StateElement | DesignText
+
+export interface StateStyles {
+ /** The set's name, for the root's class name. */
+ name: string
+ root: StateElement
+}
diff --git a/packages/dom-css/src/cssom.d.ts b/packages/dom-css/src/cssom.d.ts
index cf2118891..cde1f262f 100644
--- a/packages/dom-css/src/cssom.d.ts
+++ b/packages/dom-css/src/cssom.d.ts
@@ -17,6 +17,15 @@ declare module '@acemir/cssom' {
}
}
+ export class CSSStyleSheet {
+ readonly cssRules: ArrayLike<{
+ readonly style: { setProperty(property: string, value: string): void }
+ }>
+ /** Parses `rule`, throwing on an invalid selector, and returns its index. */
+ insertRule(rule: string, index?: number): number
+ toString(): string
+ }
+
export interface CSSGroupingRuleLike {
cssRules: unknown[]
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
new file mode 100644
index 000000000..cbcd7e0fb
--- /dev/null
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -0,0 +1,136 @@
+import { emptyBehaviour, SceneGraph, withBehaviour, type Behaviour } from '@open-pencil/scene-graph'
+
+const solid = (r: number, g: number, b: number) => [
+ { type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }
+]
+
+export const COLORS = {
+ off: solid(0.8, 0.84, 0.88),
+ on: solid(0.31, 0.27, 0.9),
+ hover: solid(0.72, 0.77, 0.84),
+ white: solid(1, 1, 1)
+}
+
+/** A component set whose variants are built by `draw` for each combination of `axes`. */
+export function componentSet(
+ name: string,
+ axes: Record<string, string[]>,
+ behaviour: Behaviour,
+ draw: (graph: SceneGraph, variant: string, values: Record<string, string>) => void,
+ skip: (values: Record<string, string>) => boolean = () => false
+) {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const set = graph.createNode('COMPONENT_SET', pageId, {
+ name,
+ componentPropertyDefinitions: Object.entries(axes).map(([axis, options]) => ({
+ id: axis.toLowerCase(),
+ name: axis,
+ type: 'VARIANT' as const,
+ defaultValue: options[0] ?? '',
+ variantOptions: options
+ }))
+ })
+ const combos = Object.entries(axes).reduce<Record<string, string>[]>(
+ (all, [axis, options]) =>
+ all.flatMap((combo) => options.map((value) => ({ ...combo, [axis]: value }))),
+ [{}]
+ )
+ for (const values of combos) {
+ if (skip(values)) continue
+ const variant = graph.createNode('COMPONENT', set.id, {
+ name: Object.entries(values)
+ .map(([axis, value]) => `${axis}=${value}`)
+ .join(', '),
+ componentPropertyValues: values,
+ width: 40,
+ height: 22
+ })
+ draw(graph, variant.id, values)
+ }
+ graph.updateNode(set.id, { pluginData: withBehaviour(set, behaviour) })
+ return { graph, set: graph.getNode(set.id) ?? set }
+}
+
+export function switchSet() {
+ return componentSet(
+ 'Switch',
+ { State: ['Off', 'On'], Interaction: ['Default', 'Hover', 'Disabled'] },
+ {
+ ...emptyBehaviour('switch'),
+ booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } },
+ states: { propertyId: 'interaction', rest: 'Default', hover: 'Hover', disabled: 'Disabled' }
+ },
+ (graph, variant, { State, Interaction }) => {
+ const offFills = Interaction === 'Hover' ? COLORS.hover : COLORS.off
+ const fills = State === 'On' ? COLORS.on : offFills
+ graph.updateNode(variant, { fills, opacity: Interaction === 'Disabled' ? 0.5 : 1 })
+ graph.createNode('FRAME', variant, {
+ name: 'Thumb',
+ x: State === 'On' ? 20 : 2,
+ y: 2,
+ width: 18,
+ height: 18,
+ fills: COLORS.white
+ })
+ }
+ )
+}
+
+/** A checkbox whose indicator exists only when checked. */
+export function checkboxSet() {
+ return componentSet(
+ 'Checkbox',
+ { Checked: ['Off', 'On'] },
+ {
+ ...emptyBehaviour('checkbox'),
+ booleans: { value: { propertyId: 'checked', on: 'On', off: 'Off' } }
+ },
+ (graph, variant, { Checked }) => {
+ graph.updateNode(variant, { fills: COLORS.white })
+ if (Checked === 'On')
+ graph.createNode('FRAME', variant, {
+ name: 'Indicator',
+ x: 4,
+ y: 4,
+ width: 10,
+ height: 10,
+ fills: COLORS.on
+ })
+ }
+ )
+}
+
+/** A toggle whose label reads differently when pressed. */
+export function toggleSet() {
+ return componentSet(
+ 'Toggle',
+ { Pressed: ['No', 'Yes'] },
+ {
+ ...emptyBehaviour('toggle'),
+ booleans: { value: { propertyId: 'pressed', on: 'Yes', off: 'No' } }
+ },
+ (graph, variant, { Pressed }) => {
+ graph.createNode('TEXT', variant, { name: 'Label', text: Pressed === 'Yes' ? 'On' : 'Off' })
+ }
+ )
+}
+
+/** A button with sizes, drawn hovered only at its small size. */
+export function buttonSet() {
+ return componentSet(
+ 'Button',
+ { Size: ['Small', 'Large'], Interaction: ['Default', 'Hover'] },
+ {
+ ...emptyBehaviour('button'),
+ states: { propertyId: 'interaction', rest: 'Default', hover: 'Hover' }
+ },
+ (graph, variant, { Size, Interaction }) => {
+ graph.updateNode(variant, {
+ width: Size === 'Large' ? 160 : 80,
+ fills: Interaction === 'Hover' ? COLORS.hover : COLORS.off
+ })
+ },
+ ({ Size, Interaction }) => Size === 'Large' && Interaction === 'Hover'
+ )
+}
diff --git a/packages/dom-css/tests/behaviours/states.test.ts b/packages/dom-css/tests/behaviours/states.test.ts
new file mode 100644
index 000000000..76c155aad
--- /dev/null
+++ b/packages/dom-css/tests/behaviours/states.test.ts
@@ -0,0 +1,198 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ stateStyles,
+ stateStylesToCSS,
+ stateStylesToTailwind,
+ type StateElement,
+ type StateStyles
+} from '#dom-css/behaviours/states/index'
+import { compileTailwindCSS } from '#dom-css/import/tailwind'
+import type { DesignElement, DesignNode } from '#dom-css/types'
+import { parse, type CSSStyleRuleLike } from '@acemir/cssom'
+
+import { emptyBehaviour } from '@open-pencil/scene-graph'
+
+import { buttonSet, checkboxSet, componentSet, switchSet, toggleSet } from './fixtures'
+
+function styles(fixture: ReturnType<typeof switchSet>): StateStyles {
+ const result = stateStyles(fixture.graph, fixture.set)
+ if (!result) throw new Error('No state styles')
+ return result
+}
+
+function child(element: StateElement, key: string): StateElement {
+ const found = element.children.find(
+ (item): item is StateElement => item.type === 'element' && item.key === key
+ )
+ if (!found) throw new Error(`No layer ${JSON.stringify(key)}`)
+ return found
+}
+
+/** Every style rule of a stylesheet, by selector, including ones inside media queries. */
+function cssRules(css: string): Map<string, Record<string, string>> {
+ const rules = new Map<string, Record<string, string>>()
+ const visit = (list: ArrayLike<unknown>) => {
+ for (const item of Array.from(list)) {
+ const rule = item as CSSStyleRuleLike & { cssRules?: ArrayLike<unknown> }
+ if (rule.cssRules) visit(rule.cssRules)
+ if (!rule.selectorText) continue
+ const style: Record<string, string> = {}
+ for (const property of Array.from({ length: rule.style.length }, (_, i) => rule.style[i]))
+ if (property) style[property] = rule.style.getPropertyValue(property)
+ rules.set(rule.selectorText, style)
+ }
+ }
+ visit(parse(css).cssRules)
+ return rules
+}
+
+/**
+ * Tailwind's compiled rules as selector and declarations. Its escaped class selectors are
+ * beyond the CSSOM parser, so innermost `selector { … }` blocks are read directly, which also
+ * reaches rules nested in `@media`.
+ */
+function compiledRules(css: string): [string, string][] {
+ return [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map((match) => [
+ (match[1] ?? '').trim(),
+ (match[2] ?? '').trim()
+ ])
+}
+
+function elements(node: DesignNode, into: DesignElement[] = []): DesignElement[] {
+ if (node.type !== 'element') return into
+ into.push(node)
+ for (const item of node.children) elements(item, into)
+ return into
+}
+
+describe('state styles', () => {
+ test('keeps the rest variant as base and each other variant as only what it changes', () => {
+ const { root } = styles(switchSet())
+ expect(root.base).toEqual({
+ width: '40px',
+ height: '22px',
+ 'background-color': '#CCD6E0',
+ position: 'relative'
+ })
+ expect(root.rules).toEqual([
+ {
+ conditions: [{ type: 'interaction', state: 'hover' }],
+ style: { 'background-color': '#B8C4D6' }
+ },
+ { conditions: [{ type: 'disabled' }], style: { opacity: '0.5' } },
+ {
+ conditions: [{ type: 'state', value: 'checked' }],
+ style: { 'background-color': '#4F45E6' }
+ },
+ // Hover alone would paint a checked switch grey, so the combination keeps its fill.
+ {
+ conditions: [
+ { type: 'state', value: 'checked' },
+ { type: 'interaction', state: 'hover' }
+ ],
+ style: { 'background-color': '#4F45E6' }
+ }
+ ])
+ expect(child(root, 'Thumb').rules).toEqual([
+ { conditions: [{ type: 'state', value: 'checked' }], style: { left: '20px' } }
+ ])
+ })
+
+ test('hides a layer at rest that only a state draws', () => {
+ const indicator = child(styles(checkboxSet()).root, 'Indicator')
+ expect(indicator.base.display).toBe('none')
+ expect(indicator.rules).toEqual([
+ { conditions: [{ type: 'state', value: 'checked' }], style: { display: 'revert' } }
+ ])
+ })
+
+ test('keeps a label that reads differently as a layer per state', () => {
+ const { root } = styles(toggleSet())
+ expect(child(root, 'Label\0Off').rules).toEqual([
+ { conditions: [{ type: 'state', value: 'on' }], style: { display: 'none' } }
+ ])
+ expect(child(root, 'Label\0On').base.display).toBe('none')
+ })
+
+ test('reads other variant properties as props, so missing combinations combine', () => {
+ const { root } = styles(buttonSet())
+ expect(root.rules).toEqual([
+ {
+ conditions: [{ type: 'interaction', state: 'hover' }],
+ style: { 'background-color': '#B8C4D6' }
+ },
+ { conditions: [{ type: 'prop', name: 'Size', value: 'Large' }], style: { width: '160px' } }
+ ])
+ })
+})
+
+test('has no state styles when no variant shows the rest state', () => {
+ // Only the checked variant is drawn; using it as the base would show it checked at rest.
+ const { graph, set } = componentSet(
+ 'Switch',
+ { State: ['Off', 'On'] },
+ {
+ ...emptyBehaviour('switch'),
+ booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } }
+ },
+ () => undefined,
+ ({ State }) => State === 'Off'
+ )
+ expect(stateStyles(graph, set)).toBeNull()
+})
+
+describe('state stylesheet', () => {
+ test('writes readable classes and state selectors on the root', async () => {
+ const { document, css } = await stateStylesToCSS(styles(switchSet()))
+ expect(
+ elements(document.children[0] ?? { type: 'text', text: '' }).map((el) => el.attrs.class)
+ ).toEqual(['switch', 'switch__thumb'])
+ const rules = cssRules(css)
+ expect(rules.get('.switch[data-state="checked"] .switch__thumb')).toEqual({ left: '20px' })
+ expect(rules.get('.switch:hover:not([data-disabled])')).toEqual({
+ 'background-color': '#B8C4D6'
+ })
+ expect(rules.get('.switch[data-state="checked"]:hover:not([data-disabled])')).toEqual({
+ 'background-color': '#4F45E6'
+ })
+ expect(rules.get('.switch[data-disabled]')).toEqual({ opacity: '0.5' })
+ // Fewer conditions come first, so the cascade never depends on emission order.
+ expect(css.indexOf('.switch[data-state="checked"] {')).toBeGreaterThan(-1)
+ expect(css.indexOf('.switch[data-state="checked"] {')).toBeLessThan(
+ css.indexOf('.switch[data-state="checked"]:hover')
+ )
+ })
+
+ test('writes a prop condition as the data attribute a component sets', async () => {
+ const rules = cssRules((await stateStylesToCSS(styles(buttonSet()))).css)
+ expect(rules.get('.button[data-size="Large"]')).toEqual({ width: '160px' })
+ })
+})
+
+describe('state Tailwind', () => {
+ test('writes state variants that Tailwind compiles to the same selectors', async () => {
+ const document = stateStylesToTailwind(styles(switchSet()))
+ const [root, thumb] = elements(document.children[0] ?? { type: 'text', text: '' })
+ const rootClasses = root?.attrs.class.split(' ') ?? []
+ const thumbClasses = thumb?.attrs.class.split(' ') ?? []
+ expect(rootClasses).toContain('group/switch')
+ expect(thumbClasses).toContain('group-data-[state=checked]/switch:left-5')
+
+ const rules = compiledRules(await compileTailwindCSS([...rootClasses, ...thumbClasses]))
+ const declaring = (property: string, matches: (selector: string) => boolean) =>
+ rules.filter(([selector, body]) => matches(selector) && body.startsWith(`${property}:`))
+ // The thumb moves when its own root is checked, found through the named group.
+ expect(
+ declaring('left', (selector) =>
+ selector.endsWith(':is(:where(.group\\/switch)[data-state="checked"] *)')
+ )
+ ).toHaveLength(1)
+ // Hover excludes a disabled root, and a checked hover is more specific than either part.
+ expect(
+ declaring('background-color', (selector) =>
+ selector.endsWith('[data-state="checked"]:not([data-disabled]):hover')
+ )
+ ).toHaveLength(1)
+ })
+})