AI-native design editor. Open-source Figma alternative.
feat(storybook): generate sliders, progress bars, number fields, and text fields (#1029)
Danila Poyarkoveb8d5a9d5886
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6c03909e3..203a65924 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -82,7 +82,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, titled by the document and, when several have components, its page, 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, each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, 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, titled by the document and, when several have components, its page, 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, Accordion, Slider, Progress, Number field, Text field, or Textarea 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, sliders, progress bars, and number fields binding a number within their range, text fields and textareas binding their text as a native input or textarea with the design's placeholder and filled look (React's number field is a native number input with its steppers wired, since Radix has none), each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, 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/core/tests/icons/glyph.test.ts b/packages/core/tests/icons/glyph.test.tsindex 8d3d16054..e767899db 100644--- a/packages/core/tests/icons/glyph.test.ts+++ b/packages/core/tests/icons/glyph.test.ts@@ -8,16 +8,17 @@ import {} from '@open-pencil/scene-graph/resize'import { detachIcon, placeIcon, recolorIcon, swapIcon } from '#core/icons/render'+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'import { buildIconData } from '#core/icons/svg'const BLACK = parseColor('#000000')const OUTLINE = '<path fill="none" stroke="currentColor" stroke-width="2" d="M4 4h16v16H4z"/>'const LOGO = '<path fill="#e11d48" d="M2 2h20v20H2z"/><path fill="currentColor" d="M8 8h8v8H8z"/>'-function placed(body: string) {+function placed(body: string, size = 24) {const graph = new SceneGraph()- const icon = buildIconData({ body }, 'test', 'icon', 24, 24, 24)- const frame = placeIcon(graph, graph.getPages()[0].id, icon, { size: 24, color: BLACK })+ const icon = buildIconData({ body }, 'test', 'icon', 24, 24, size)+ const frame = placeIcon(graph, graph.getPages()[0].id, icon, { size, color: BLACK })const modified = () => isIconModified(graph, graph.getNode(frame.id) ?? frame)return { graph, frame, modified }}@@ -36,6 +37,25 @@ function resize(graph: SceneGraph, id: string, width: number, height: number) {}describe('icon glyphs', () => {+ test('a placed icon is as placed after saving and loading the document', async () => {+ // Lucide's save icon, whose curves land near rounding boundaries once stored as floats.+ const SAVE =+ '<g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7M7 3v4a1 1 0 0 0 1 1h7"/></g>'+ for (const [body, size] of [+ [OUTLINE, 24],+ [LOGO, 24],+ [SAVE, 16]+ ] as const) {+ const { graph, frame } = placed(body, size)+ const loaded = await parseFigFile((await exportFigFile(graph)).slice().buffer)+ const icon = [...loaded.getAllNodes()].find((node) => readIcon(node)?.name === readIcon(frame)?.name)+ if (!icon) throw new Error('Expected the icon to load')+ // An icon without a glyph also reads as unedited, so the glyph itself has to survive.+ expect(readIcon(icon)?.glyph).toBe(readIcon(frame)?.glyph ?? 'missing')+ expect(isIconModified(loaded, icon)).toBe(false)+ }+ })+test('a placed icon is as placed, and stays so when recolored or resized, unevenly too', () => {const { graph, frame, modified } = placed(OUTLINE)expect(readIcon(graph.getNode(frame.id) ?? frame)?.glyph).toMatch(/^[0-9a-f]{8}$/)diff --git a/packages/design-jsx/src/behaviours/index.ts b/packages/design-jsx/src/behaviours/index.tsindex 3dedb61ec..ce5404863 100644--- a/packages/design-jsx/src/behaviours/index.ts+++ b/packages/design-jsx/src/behaviours/index.ts@@ -47,7 +47,7 @@ const REKA_PARTS = {Range: part('range'),Thumb: part('thumb')},- Progress: { Root: root('progress'), Indicator: part('indicator') },+ Progress: { Root: root('progress'), Track: part('track'), Indicator: part('indicator') },Tabs: {Root: root('tabs'),List: part('list'),diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex fc2eb89bf..57ca0a91d 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -41,7 +41,7 @@ This reference describes scene creation, not React DOM output. Use the `render`## Controls-- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.+- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Track`, `Progress.Indicator`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex fc54bdb3b..f0b2bf101 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -162,9 +162,9 @@ Stories are titled by the document's file name, and then the page when more thanStories 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 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.+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, Accordion, Slider, Progress, Number field, Text field, or Textarea 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, every trigger drawn like the design's other triggers and taking the first trigger's look while its tab is active, 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.+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, every trigger drawn like the design's other triggers and taking the first trigger's look while its tab is active, 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 Slider, Progress, or Number field binds its number as `value` (`v-model:value`, or `defaultValue` in React, a list for Radix's slider), within the range its behaviour sets, starting where the design does; the slider's range and thumb and the progress indicator drop the place the design draws them at, since the value sets it, and stories get a range control and a story at each end. A Text field or Textarea draws its text layer as a native `input` or `textarea` binding `value`, which in React takes the component's props; when the design draws the field filled and empty, the empty field's words are the placeholder and its look the placeholder's, and the filled look shows while the field has text. Reka UI's number field draws the input and steppers in Vue; Radix has none, so React's is a native number input whose steppers change it by a step and which settles within its range when left. Focus on a slider's thumb or a field's input draws the control's focus state. 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/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex ad12e1daf..f5b6a4f6a 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -43,7 +43,7 @@ This reference describes scene creation, not React DOM output. Use the `render`## Controls-- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.+- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Track`, `Progress.Indicator`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.@@ -86,7 +86,7 @@ The examples below are executed by the authoring-reference tests. Create the namGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.+**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.diff --git a/packages/dom-css/src/behaviours/args.ts b/packages/dom-css/src/behaviours/args.tsindex 84a407ac9..90f2f510c 100644--- a/packages/dom-css/src/behaviours/args.ts+++ b/packages/dom-css/src/behaviours/args.ts@@ -1,7 +1,9 @@import {behaviourProperties,readBehaviour,+ type Behaviour,type BehaviourKind,+ type ComponentPropertyDefinition,type SceneGraph,type SceneNode} from '@open-pencil/scene-graph'@@ -24,6 +26,11 @@ export interface BehaviourArgs {* disabled prop shows, if the set draws it.*/states?: { property: string; rest: string; disabled?: string }+ /**+ * The variant property that draws a field with text, which the field shows while its input+ * has text rather than taking as a prop.+ */+ filled?: { property: string; on: string; off: string }}/** Values a behaviour derives from others instead of taking as props. */@@ -34,6 +41,19 @@ function booleanArgName(kind: BehaviourKind, valueId: string): string {return kind === 'toggle' ? 'pressed' : 'checked'}+/** The variant property a field's `filled` value draws, with its on and off values. */+function filledArg(+ behaviour: Behaviour,+ variant: (id: string) => ComponentPropertyDefinition | undefined+): BehaviourArgs['filled'] {+ const binding = Object.hasOwn(behaviour.booleans, 'filled')+ ? behaviour.booleans.filled+ : undefined+ const definition = binding && variant(binding.propertyId)+ if (!definition || binding.on === undefined || binding.off === undefined) return undefined+ return { property: definition.name, on: binding.on, off: binding.off }+}+/*** The props of a component set with a behaviour. Only variant properties become props here,* since each variant is drawn; a boolean value becomes a boolean prop when its property offers@@ -62,5 +82,6 @@ export function behaviourArgs(graph: SceneGraph, set: SceneNode): BehaviourArgsdisabled: behaviour.states?.disabled}: undefined- return { booleans, states }+ const filled = filledArg(behaviour, variant)+ return { booleans, states, ...(filled ? { filled } : {}) }}diff --git a/packages/dom-css/src/behaviours/index.ts b/packages/dom-css/src/behaviours/index.tsindex 77c6e3035..f80688a40 100644--- a/packages/dom-css/src/behaviours/index.ts+++ b/packages/dom-css/src/behaviours/index.ts@@ -6,6 +6,6 @@ export {type ControlModel,type StatesModel} from './controls'-export { BUTTON_RESET } from './reset'+export { BUTTON_RESET, INPUT_RESET } from './reset'export { controlRoles, groupOf, type ControlRole } from './roles'export * from './states'diff --git a/packages/dom-css/src/behaviours/reset.ts b/packages/dom-css/src/behaviours/reset.tsindex f9dba318b..de2eceece 100644--- a/packages/dom-css/src/behaviours/reset.ts+++ b/packages/dom-css/src/behaviours/reset.ts@@ -21,3 +21,17 @@ export const HEADING_RESET: Record<string, string> = {margin: '0',font: 'inherit'}++/**+ * Element styles an input or textarea adds, cleared so the field's text layer it replaces+ * keeps its look. Preview and generated components both draw a field's text as one.+ */+export const INPUT_RESET: Record<string, string> = {+ border: 'none',+ outline: 'none',+ padding: '0',+ margin: '0',+ background: 'transparent',+ resize: 'none',+ 'box-sizing': 'border-box'+}diff --git a/packages/dom-css/src/behaviours/states/conditions.ts b/packages/dom-css/src/behaviours/states/conditions.tsindex 4da1f9afc..f3ab2d6e2 100644--- a/packages/dom-css/src/behaviours/states/conditions.ts+++ b/packages/dom-css/src/behaviours/states/conditions.ts@@ -1,6 +1,7 @@import {behaviourProperties,readBehaviour,+ type BehaviourKind,type ComponentPropertyDefinition,type SceneGraph,type SceneNode@@ -18,6 +19,9 @@ const DATA_STATE_ON: Partial<Record<string, string>> = {const INTERACTIONS = ['hover', 'pressed', 'focus'] as const+/** Controls whose focus lands on a layer inside them: a slider's thumb, a field's input. */+const FOCUS_WITHIN = new Set<BehaviourKind>(['slider', 'textField', 'textarea', 'numberField'])+/** The condition a variant property's value adds, or `null` for its rest value. */type ValueCondition = (value: string) => StateCondition | null@@ -32,12 +36,17 @@ function booleanCondition(arg: BooleanArg): ValueCondition {/** 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 behaviour = readBehaviour(set)+ const within = behaviour ? FOCUS_WITHIN.has(behaviour.kind) : falseconst byValue = new Map<string, StateCondition>()for (const state of INTERACTIONS) {- const value = stored?.[state]+ const value = behaviour?.states?.[state]if (value !== undefined && value !== states.rest)- byValue.set(value, { type: 'interaction', state })+ byValue.set(value, {+ type: 'interaction',+ state,+ ...(state === 'focus' && within ? { within } : {})+ })}if (states.disabled !== undefined) byValue.set(states.disabled, { type: 'disabled' })const name = states.property@@ -68,6 +77,9 @@ export function variantConditions(const boolean = args?.booleans.get(definition.name)if (boolean) return booleanCondition(boolean)if (args?.states?.property === definition.name) return interactionCondition(set, args.states)+ const filled = args?.filled+ if (filled?.property === definition.name)+ return (value) => (value === filled.on ? { type: 'filled' } : null)return propCondition(definition)}const byProperty = new Map(diff --git a/packages/dom-css/src/behaviours/states/css.ts b/packages/dom-css/src/behaviours/states/css.tsindex c20ea92db..3dc6484eb 100644--- a/packages/dom-css/src/behaviours/states/css.ts+++ b/packages/dom-css/src/behaviours/states/css.ts@@ -19,13 +19,17 @@ export interface StateStylesheet {/** A CSS string for an attribute selector's value. */const quoted = (value: string) => cssesc(value, { quotes: 'double', wrap: true })+/** A field whose input or textarea shows text rather than its placeholder. */+export const FILLED = ':has(:is(input, textarea):not(:placeholder-shown))'+/** 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 === 'filled') return FILLEDif (condition.type === 'prop')return `[${propAttribute(condition.name)}=${quoted(condition.value)}]`- if (condition.state === 'focus') return ':focus-visible'+ if (condition.state === 'focus') return condition.within ? ':focus-within' : ':focus-visible'// A disabled control keeps its disabled look under the pointer.return `${condition.state === 'hover' ? ':hover' : ':active'}:not([data-disabled])`}@@ -59,7 +63,10 @@ export async function stateStylesToCSS(styles: StateStyles): Promise<StateStylesfor (const rule of element.rules) {const when = rule.conditions.map(conditionSelector).join('')const on = rule.on && classes.get(rule.on)- const tested = on ? ` .${on}${when}${rule.on === element ? '' : own}` : `${when}${own}`+ const pseudo = rule.pseudo ? `::${rule.pseudo}` : ''+ const tested = on+ ? ` .${on}${when}${rule.on === element ? '' : own}${pseudo}`+ : `${when}${own}${pseudo}`rules.push({order: rule.conditions.length,selector: `.${rootClass}${tested}`,diff --git a/packages/dom-css/src/behaviours/states/tailwind.ts b/packages/dom-css/src/behaviours/states/tailwind.tsindex 043e7a475..31bcb4b0c 100644--- a/packages/dom-css/src/behaviours/states/tailwind.ts+++ b/packages/dom-css/src/behaviours/states/tailwind.ts@@ -22,11 +22,12 @@ 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 === 'filled') return on('has-[:is(input,textarea):not(:placeholder-shown)]')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')+ if (condition.state === 'focus') return on(condition.within ? 'focus-within' : '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')}`@@ -75,7 +76,12 @@ function designNode(...utilities(node.base, options),...node.rules.flatMap((rule) => {const group = testedGroup(node, rule.on, groups, isRoot)- const prefix = rule.conditions.map((condition) => variant(condition, group)).join('')+ const prefix = [+ ...rule.conditions.map((condition) => variant(condition, group)),+ ...(rule.pseudo+ ? [rule.pseudo === 'placeholder' ? 'placeholder:' : `[&::${rule.pseudo}]:`]+ : [])+ ].join('')return utilities(rule.style, options).map((utility) => `${prefix}${utility}`)})]diff --git a/packages/dom-css/src/behaviours/states/types.ts b/packages/dom-css/src/behaviours/states/types.tsindex 9cd63b24d..6f4eac673 100644--- a/packages/dom-css/src/behaviours/states/types.ts+++ b/packages/dom-css/src/behaviours/states/types.ts@@ -8,7 +8,10 @@ import type { DesignStyleDeclaration, DesignText } from '#dom-css/types'export type StateCondition =| { type: 'state'; value: string }| { type: 'disabled' }- | { type: 'interaction'; state: 'hover' | 'pressed' | 'focus' }+ /** `within` when focus lands on a layer inside the control, such as a field's input. */+ | { type: 'interaction'; state: 'hover' | 'pressed' | 'focus'; within?: boolean }+ /** A field whose input holds text. */+ | { type: 'filled' }| { type: 'prop'; name: string; value: string }/** What a variant changes on a layer, and the conditions that show that variant. */@@ -19,6 +22,8 @@ export interface StateRule {* that Reka and Radix mark active itself: the layer the rule styles, or one around it.*/on?: StateElement+ /** The part of the layer the rule styles: an input's placeholder, or a number input's spinner. */+ pseudo?: 'placeholder' | '-webkit-inner-spin-button'style: DesignStyleDeclaration}diff --git a/packages/dom-css/src/export/components/fields.ts b/packages/dom-css/src/export/components/fields.tsnew file mode 100644index 000000000..c799e4319--- /dev/null+++ b/packages/dom-css/src/export/components/fields.ts@@ -0,0 +1,178 @@+import type { BehaviourArgs } from '#dom-css/behaviours/args'+import { INPUT_RESET } from '#dom-css/behaviours/reset'+import type { StateElement } from '#dom-css/behaviours/states/types'+import { omit, pick } from 'es-toolkit/object'+import { isEmptyObject } from 'es-toolkit/predicate'++import { es } from '@open-pencil/emit'+import {+ DEFAULT_NUMBER_SETTINGS,+ numberSettings,+ type Behaviour,+ type ComponentPropertyDefinition+} from '@open-pencil/scene-graph'++import type { GeneratedKind, RangeModel, TextModel } from './model'++/** Kinds that hold a number in a range. */+const RANGED: ReadonlySet<GeneratedKind> = new Set(['slider', 'progress', 'numberField'])++/** Kinds whose text layer is an input, and the text value that layer shows. */+const INPUT_VALUES: Partial<Record<GeneratedKind, string>> = {+ textField: 'value',+ textarea: 'value',+ numberField: 'text'+}++/** The text value whose bound layer a kind draws as its input, if it has one. */+export const inputValue = (kind: GeneratedKind): string | undefined => INPUT_VALUES[kind]++/** The number a ranged kind binds, starting where the design's behaviour does. */+export function rangeModel(kind: GeneratedKind, behaviour: Behaviour): RangeModel | null {+ if (!RANGED.has(kind)) return null+ return { ...(numberSettings(behaviour, 'value') ?? DEFAULT_NUMBER_SETTINGS) }+}++/**+ * The text a text field or textarea binds. When the design draws it filled and empty, the+ * empty field shows its text property's words as a placeholder and starts empty; otherwise it+ * starts with them.+ */+export function textModel(+ kind: GeneratedKind,+ definition: ComponentPropertyDefinition | undefined,+ args: BehaviourArgs+): TextModel | null {+ if (kind !== 'textField' && kind !== 'textarea') return null+ const words = typeof definition?.defaultValue === 'string' ? definition.defaultValue : ''+ return args.filled ? { default: '', placeholder: words } : { default: words, placeholder: null }+}++/** A field's text layer drawn as its input, and the same layer in other words, which it replaces. */+export interface InputLayers {+ element: StateElement+ replaced: StateElement[]+}++/** What a text layer's look is, as opposed to where it sits. */+const TEXT_LOOK = [+ 'color',+ 'opacity',+ 'font-family',+ 'font-size',+ 'font-style',+ 'font-weight',+ 'letter-spacing',+ 'line-height',+ 'text-decoration',+ 'text-transform'+]++/**+ * The input among a field's bound text layers: the one shown at rest. A layer reading other+ * words is the same layer in another state; drawn while filled, its look is the typed text's,+ * and the resting look becomes the placeholder's.+ */+export function inputLayers(bound: readonly StateElement[]): InputLayers | null {+ const element = bound.find((layer) => layer.base.display !== 'none') ?? bound.at(0)+ if (!element) return null+ const replaced = bound.filter((layer) => layer !== element)+ const filled = replaced.find((layer) =>+ layer.rules.some((rule) => rule.conditions.some((condition) => condition.type === 'filled'))+ )+ if (filled) {+ const typed = pick(omit(filled.base, ['display']), TEXT_LOOK)+ element.rules.push({+ conditions: [],+ pseudo: 'placeholder',+ style: pick(element.base, TEXT_LOOK)+ })+ element.base = { ...element.base, ...typed }+ // The layer shows in every state now, so states that hid or showed it no longer do.+ element.rules = element.rules.filter((rule) => !rule.style.display)+ }+ element.base = { ...INPUT_RESET, ...omit(element.base, ['display', 'white-space']) }+ return { element, replaced }+}++/** What the library sets on a part it places itself, which the design's drawn place gives way to. */+const PLACED: Partial<Record<GeneratedKind, Record<string, readonly string[]>>> = {+ slider: { range: ['left', 'right', 'width'], thumb: ['left', 'right', 'transform'] },+ progress: { indicator: ['width'] }+}++/**+ * Gives a number field's input, which the design draws as words that hug their value, room+ * for its longest value rather than an input's default width, and no spinner of the browser's+ * own, since the design draws its steppers.+ */+export function numberInput(input: InputLayers | null, range: RangeModel | null): void {+ if (!input || !range) return+ const { element } = input+ element.base = { ...element.base, appearance: 'textfield' }+ element.rules.push({+ conditions: [],+ pseudo: '-webkit-inner-spin-button',+ style: { appearance: 'none', margin: '0' }+ })+ if (Object.hasOwn(element.base, 'width')) return+ const digits = Math.max(String(range.min).length, String(range.max).length)+ element.base = { ...element.base, width: `${digits + 1}ch` }+}++/** Kinds whose root Reka and Radix render as a span, which a size alone does not lay out. */+const SPAN_ROOTS: ReadonlySet<GeneratedKind> = new Set(['slider'])++/** Lays a span root out as the block the design draws, unless the design says otherwise. */+export function blockRoot(kind: GeneratedKind, root: StateElement): void {+ if (SPAN_ROOTS.has(kind) && !Object.hasOwn(root.base, 'display'))+ root.base = { ...root.base, display: 'block' }+}++/** Drops the place a slider or progress bar draws its moving parts at, which the value sets. */+export function freePlacedParts(+ kind: GeneratedKind,+ parts: ReadonlyMap<StateElement, string>+): void {+ for (const [element, part] of parts) {+ const placed = PLACED[kind]?.[part]+ if (!placed) continue+ element.base = omit(element.base, placed)+ element.rules = element.rules+ .map((rule) => ({ ...rule, style: omit(rule.style, placed) }))+ .filter((rule) => !isEmptyObject(rule.style))+ }+}++const PERCENT = es.parseExpression(`({ width: \`\${$share}%\` })`)++/**+ * A progress bar's indicator style, reaching the value's share of its range, the value held+ * within it: the value itself for a range of 0 to 100. Null for an empty range, which has no+ * share.+ */+export function progressWidth(range: RangeModel, value: es.SyntaxNode): es.SyntaxNode | null {+ const span = range.max - range.min+ if (span <= 0) return null+ // A value outside the range fills the indicator no further than its ends.+ const clamped = es.fill(es.parseExpression('Math.min($max, Math.max($min, $value))'), {+ $value: value,+ $min: es.number(range.min),+ $max: es.number(range.max)+ })+ const offset =+ range.min === 0+ ? clamped+ : es.fill(es.parseExpression('$value - $min'), {+ $value: clamped,+ $min: es.number(range.min)+ })+ const share =+ span === 100+ ? offset+ : es.fill(es.parseExpression('(($offset) / $span) * 100'), {+ $offset: offset,+ $span: es.number(span)+ })+ return es.fill(PERCENT, { $share: share })+}diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.tsindex b591301d5..fb9129e36 100644--- a/packages/dom-css/src/export/components/model.ts+++ b/packages/dom-css/src/export/components/model.ts@@ -13,6 +13,7 @@ import {layerPath,readBehaviour,slotPropertyId,+ textBinding,type Behaviour,type SceneGraph,type SceneNode@@ -20,6 +21,16 @@ import {import type { SceneGraphToDesignOptions } from '../projection'import { claimName, identifierName } from '../storybook/names'+import {+ blockRoot,+ freePlacedParts,+ inputLayers,+ inputValue,+ numberInput,+ rangeModel,+ textModel,+ type InputLayers+} from './fields'import {groupItems,GROUP_ITEMS,@@ -47,7 +58,12 @@ export const GENERATED_KINDS = ['tabs','radioGroup','toggleGroup',- 'accordion'+ 'accordion',+ 'slider',+ 'progress',+ 'numberField',+ 'textField',+ 'textarea'] as const/** What a generated component is: a control on its own, or a group's item. */@@ -104,11 +120,30 @@ export interface TextProp {default: string}+/** A number the component binds two ways, within its range, starting where the design does. */+export interface RangeModel {+ min: number+ max: number+ step: number+ default: number+}++/**+ * Text a field binds two ways: the words it starts with, and the placeholder an empty field+ * shows when the design draws one.+ */+export interface TextModel {+ default: string+ placeholder: string | null+}+export type ComponentNode =| ComponentElement| { type: 'text'; value: string }/** The value of a text prop, drawn where the design binds a text layer to it. */| { type: 'textProp'; name: string }+ /** A field's input, drawn where the design binds its text layer to the field's text. */+ | { type: 'input'; className: string }| ComponentReference| IconReference@@ -127,6 +162,10 @@ export interface ComponentModel {model: string | null/** The options a string model takes and the one it starts on. */choice: ChoiceModel | null+ /** The range a number model takes, as a slider, progress bar, or number field has. */+ range: RangeModel | null+ /** The text a text field or textarea binds. */+ text: TextModel | 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. */@@ -148,6 +187,8 @@ interface TreeLabels {used: Map<StateElement, UsedLayer>/** Layers drawn once per value, such as tab triggers and panels. */repeated: Map<StateElement, RepeatedPart>+ /** A field's text layer, drawn as its input, and the ones it replaces. */+ input: InputLayers | null}function componentTree(@@ -169,16 +210,19 @@ function componentTree(// A bound text layer draws its prop in place of the design's words and their runs.children: text? [{ type: 'textProp', name: text }]- : node.children.map((child) =>- child.type === 'text' ? { type: 'text', value: child.text } : childNode(child, labels)+ : node.children.flatMap((child) =>+ child.type === 'text' ? [{ type: 'text', value: child.text }] : childNode(child, labels))}}-function childNode(element: StateElement, labels: TreeLabels): ComponentNode {+function childNode(element: StateElement, labels: TreeLabels): ComponentNode[] {+ const className = labels.classes.get(element) ?? ''+ if (labels.input?.element === element) return [{ type: 'input', className }]+ if (labels.input?.replaced.includes(element)) return []const used = labels.used.get(element)- if (!used) return componentTree(element, labels, [])- return { ...used, className: labels.classes.get(element) ?? '' }+ if (!used) return [componentTree(element, labels, [])]+ return [{ ...used, className }]}/**@@ -189,9 +233,13 @@ function textProps(graph: SceneGraph,set: SceneNode,elements: readonly StateElement[],- taken: Set<string>-): { texts: TextProp[]; bound: Map<StateElement, string> } {- const definitions = behaviourProperties(graph, set).filter((item) => item.type === 'TEXT')+ taken: Set<string>,+ /** A field's text property, which its input shows rather than a prop. */+ input: string | undefined+): { texts: TextProp[]; bound: Map<StateElement, string>; input: StateElement[] } {+ const definitions = behaviourProperties(graph, set).filter(+ (item) => item.type === 'TEXT' && item.id !== input+ )const texts = definitions.map((definition) => ({name: claimName(camelCase(identifierName(definition.name, 'Text')), taken),id: definition.id,@@ -201,6 +249,7 @@ function textProps(const byId = new Map(definitions.map((definition, i) => [definition.id, texts[i]]))const variants = ownerVariants(graph, set)const bound = new Map<StateElement, string>()+ const inputs: StateElement[] = []for (const element of elements) {// A key ends with the words a layer reads, which a text prop draws in every variant.const path = element.key.split('\0')[0] ?? ''@@ -208,6 +257,10 @@ function textProps(const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find((item) => item.field === 'TEXT')+ if (reference && reference.propertyId === input) {+ inputs.push(element)+ break+ }const prop = reference && byId.get(reference.propertyId)if (prop) {bound.set(element, prop.name)@@ -215,7 +268,7 @@ function textProps(}}}- return { texts, bound }+ return { texts, bound, input: inputs }}/** A generated component's files, and what its stories need to know about it. */@@ -225,6 +278,8 @@ export interface GeneratedComponent {entry: { path: string; named: boolean }/** The prop a story sets the value with, if the component has one. */valueArg: string | null+ /** Whether that prop takes a list of the value, as Radix's slider does. */+ valueList?: boolean}export type ComponentGenerator = (component: ComponentModel) => Promise<GeneratedComponent>@@ -240,6 +295,11 @@ const BUTTON_PARTS: Record<GeneratedKind, readonly string[]> = {radioGroup: [],toggleGroup: [],accordion: [],+ slider: [],+ progress: [],+ numberField: ['increment', 'decrement'],+ textField: [],+ textarea: [],radioGroupItem: ['root'],toggleGroupItem: ['root'],accordionItem: ['trigger']@@ -321,7 +381,7 @@ function variantProps(args: BehaviourArgs,taken: Set<string>): VariantProp[] {- const bound = new Set([...args.booleans.keys(), args.states?.property])+ const bound = new Set([...args.booleans.keys(), args.states?.property, args.filled?.property])return behaviourProperties(graph, set).filter((definition) => definition.type === 'VARIANT' && !bound.has(definition.name)).map((definition) => ({@@ -369,11 +429,12 @@ function itemsOf(}/**- * 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.+ * The value the component binds two ways: `value` when it chooses among options or holds a+ * number or text, 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'+function modelName(args: BehaviourArgs, item: boolean, valued: boolean): string | null {+ if (valued) return 'value'if (item) return nullreturn [...args.booleans.values()].find((arg) => arg.name !== 'disabled')?.name ?? null}@@ -398,6 +459,61 @@ function usedLayers(return used}+/**+ * Sizes the design gives include a layer's padding and border, which a component's own+ * stylesheet has to say, since no page reset around it does. A root without a width hugs its+ * content, as the design draws it.+ */+function borderBoxes(root: StateElement): void {+ // A root the design sizes to its content hugs it, where a block would fill its container.+ if (!Object.hasOwn(root.base, 'width')) root.base = { ...root.base, width: 'fit-content' }+ for (const element of allElements(root)) {+ const has = (property: string) => Object.hasOwn(element.base, property)+ if ((has('width') || has('height')) && !has('box-sizing'))+ element.base = { 'box-sizing': 'border-box', ...element.base }+ }+}++/**+ * Each layer's part, and tabs' triggers and panels, with the styles the generated parts need:+ * native buttons cleared, the chosen tab's look, and moving parts free of their drawn place.+ */+function drawnParts(+ graph: SceneGraph,+ set: SceneNode,+ behaviour: Behaviour,+ kind: GeneratedKind,+ root: StateElement+) {+ const parts = behaviourParts(graph, set, behaviour, root)+ const tabs = behaviour.kind === 'tabs' ? tabParts(parts) : null+ const repeated = tabs?.repeated ?? new Map<StateElement, RepeatedPart>()+ activeTriggers(repeated)+ resetButtons(kind, parts, repeated)+ freePlacedParts(kind, parts)+ blockRoot(kind, root)+ borderBoxes(root)+ return { parts, tabs, repeated }+}++/** The number or text the component holds, and the text property a field's input shows. */+function valueModels(+ graph: SceneGraph,+ set: SceneNode,+ kind: GeneratedKind,+ behaviour: Behaviour,+ args: BehaviourArgs+): { range: RangeModel | null; text: TextModel | null; inputProperty: string | undefined } {+ const valueText = inputValue(kind)+ const inputProperty = valueText && textBinding(behaviour, valueText)+ const definition = behaviourProperties(graph, set).find((item) => item.id === inputProperty)+ return {+ range: rangeModel(kind, behaviour),+ text: textModel(kind, definition, args),+ inputProperty+ }+}+export function componentModel(graph: SceneGraph,set: SceneNode,@@ -410,11 +526,7 @@ export function componentModel(if (!behaviour || !kind || !styles || !args) return nullconst 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>()- activeTriggers(repeated)- resetButtons(kind, parts, repeated)+ const { parts, tabs, repeated } = drawnParts(graph, set, behaviour, kind, styles.root)// 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)]@@ -434,23 +546,28 @@ export function componentModel()const choice = tabs?.choice ?? items?.choice ?? null- const model = modelName(args, !!options.itemOf, choice)+ const { range, text, inputProperty } = valueModels(graph, set, kind, behaviour, args)+ const model = modelName(args, !!options.itemOf, !!(choice ?? range ?? text))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)+ const texts = textProps(graph, set, allElements(styles.root), taken, inputProperty)+ const input = inputLayers(texts.input)+ numberInput(input, range)return {name,kind,styles,tree: componentTree(styles.root,- { parts, classes: layerClassNames(styles), texts: texts.bound, used, repeated },+ { parts, classes: layerClassNames(styles), texts: texts.bound, used, repeated, input },rootBindings(model, !!options.itemOf, disabled, props)),model,choice,+ range,+ text,valueProp: !!options.itemOf,item: items?.item ?? null,disabled,diff --git a/packages/dom-css/src/export/components/react.ts b/packages/dom-css/src/export/components/react.tsindex d0c96ebb6..2f2be4c11 100644--- a/packages/dom-css/src/export/components/react.ts+++ b/packages/dom-css/src/export/components/react.ts@@ -6,9 +6,11 @@ import { camelCase, upperFirst } from 'es-toolkit/string'import { es, jsx } from '@open-pencil/emit'+import { progressWidth } from './fields'import type {ComponentElement,ComponentGenerator,+ GeneratedComponent,ComponentModel,ComponentNode,GeneratedKind@@ -41,7 +43,28 @@ const RADIX: Record<GeneratedKind, { namespace: string; parts: Record<string, staccordionItem: {namespace: 'Accordion',parts: { root: 'Item', trigger: 'Trigger', content: 'Content' }- }+ },+ slider: {+ namespace: 'Slider',+ parts: { root: 'Root', track: 'Track', range: 'Range', thumb: 'Thumb' }+ },+ progress: { namespace: 'Progress', parts: { root: 'Root', indicator: 'Indicator' } },+ // Radix has no number or text field; these are native inputs in the design's own elements.+ numberField: null,+ textField: null,+ textarea: null+}++/** Kinds whose native input takes the caller's props, rather than their root. */+const INPUT_PROPS: Partial<Record<GeneratedKind, 'input' | 'textarea'>> = {+ textField: 'input',+ textarea: 'textarea'+}++/** A number field's stepper parts, which change its value by a step. */+const STEPPERS: Record<string, { label: string; sign: '+' | '-' }> = {+ increment: { label: 'Increase', sign: '+' },+ decrement: { label: 'Decrease', sign: '-' }}/** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */@@ -76,19 +99,28 @@ function moduleClass(className: string): es.SyntaxNode {/** Several classes on one element, skipping a caller's that is absent. */const CLASS_NAMES = es.parseExpression("$classes.filter(Boolean).join(' ')")-/** A Radix primitive's part, a native button for a root without one, or the design's tag. */+/** Whether a layer renders as a native button: a button's root, or a number field's stepper. */+const isNativeButton = (node: ComponentElement, kind: GeneratedKind) =>+ (kind === 'button' && node.part === 'root') ||+ (kind === 'numberField' && node.part !== null && Object.hasOwn(STEPPERS, node.part))++/** A Radix primitive's part, a native button, or the design's tag. */function tagOf(node: ComponentElement, kind: GeneratedKind): string {const radix = RADIX[kind]const part = node.part ? radix?.parts[node.part] : undefinedif (radix && part) return `${PRIMITIVE(radix.namespace)}.${part}`- return node.part === 'root' ? 'button' : node.tag+ return isNativeButton(node, kind) ? 'button' : node.tag}-/** `props.disabled || undefined`, so a native button sets `data-disabled` only while disabled. */-const DISABLED_FLAG = es.parseExpression('props.disabled || undefined')+/** `disabled || undefined`, so a native root sets `data-disabled` only while disabled. */+const disabledFlag = (kind: GeneratedKind) =>+ es.parseExpression(+ kind === 'numberField' ? 'disabled || undefined' : 'props.disabled || undefined'+ )/** What a component's markup uses, which its module imports. */interface MarkupUses {+ component: ComponentModelkind: GeneratedKindchoice: ComponentModel['choice']/** Other generated components. */@@ -122,6 +154,7 @@ function element(node: ComponentNode, uses: MarkupUses, depth: number): es.Syntaif (node.type === 'text') return jsx.text(node.value)if (node.type === 'textProp') return jsx.container(es.identifier(node.name))if (node.type === 'reference') return reference(node, uses, depth)+ if (node.type === 'input') return inputElement(node.className, uses, depth)if (node.type === 'icon') {uses.icons = truereturn jsx.element(@@ -151,42 +184,132 @@ function classNameOf(node: ComponentElement, root: boolean): es.SyntaxNode {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. */+const numeric = (name: string, value: number) =>+ jsx.attribute(name, jsx.container(es.number(value)))++/**+ * What a root fixes before the caller's props: a group's single choice and its start, and a+ * slider's or progress bar's range and the value it starts at.+ */function rootAttributes(uses: MarkupUses): es.SyntaxNode[] {+ const { component } = usesconst start = uses.choice?.default+ const { range } = componentreturn [...(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))] : [])+ ...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : []),+ ...(range && uses.kind === 'slider'+ ? [+ jsx.attribute('defaultValue', jsx.container(es.array([es.number(range.default)]))),+ numeric('min', range.min),+ numeric('max', range.max),+ numeric('step', range.step)+ ]+ : []),+ ...(range && uses.kind === 'progress'+ ? [jsx.attribute('value', jsx.container(es.identifier('value'))), numeric('max', range.max)]+ : [])]}-function bindingAttributes(node: ComponentElement, native: boolean): es.SyntaxNode[] {+function bindingAttributes(+ node: ComponentElement,+ kind: GeneratedKind,+ 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.+ // Radix sets `data-disabled` on its own roots; a native root needs it for the styles.if (binding.type === 'disabled' && native)- return [jsx.attribute('data-disabled', jsx.container(DISABLED_FLAG))]+ return [jsx.attribute('data-disabled', jsx.container(disabledFlag(kind)))]return []})}+/** What a part of a native or measured control needs: a stepper's step, an indicator's width. */+function partAttributes(node: ComponentElement, uses: MarkupUses): es.SyntaxNode[] {+ const { range } = uses.component+ if (!range || !node.part) return []+ if (uses.kind === 'progress' && node.part === 'indicator') {+ const style = progressWidth(range, es.identifier('value'))+ return style ? [jsx.attribute('style', jsx.container(style))] : []+ }+ const stepper = uses.kind === 'numberField' ? STEPPERS[node.part] : undefined+ if (!stepper) return []+ return [+ jsx.attribute('aria-label', jsx.stringValue(stepper.label)),+ jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),+ jsx.attribute(+ 'onClick',+ jsx.container(es.parseExpression(`() => commit(value ${stepper.sign} ${String(range.step)})`))+ )+ ]+}++const NUMBER_INPUT = [+ ['type', jsx.stringValue('number')],+ ['value', jsx.container(es.parseExpression("Number.isNaN(value) ? '' : value"))],+ [+ 'onChange',+ jsx.container(es.parseExpression('(event) => setValue(event.target.valueAsNumber)'))+ ],+ ['onBlur', jsx.container(es.parseExpression('() => commit(value)'))]+] as const++/** A field's input: a number input that commits within its range, or the input or textarea. */+function inputElement(className: string, uses: MarkupUses, depth: number): es.SyntaxNode {+ const { component } = uses+ const classAttribute = jsx.attribute('className', jsx.container(moduleClass(className)))+ const { range } = component+ if (range)+ return jsx.element(+ 'input',+ [+ ...NUMBER_INPUT.map(([name, value]) => jsx.attribute(name, value)),+ numeric('min', range.min),+ numeric('max', range.max),+ numeric('step', range.step),+ jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),+ classAttribute+ ],+ [],+ depth+ )+ const start = component.text?.default+ const placeholder = component.text?.placeholder+ return jsx.element(+ INPUT_PROPS[uses.kind] ?? 'input',+ [+ ...(placeholder ? [jsx.attribute('placeholder', jsx.stringValue(placeholder))] : []),+ ...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : []),+ // The input takes the caller's props, such as `name` or `onChange`.+ jsx.spread(es.identifier('props')),+ classAttribute+ ],+ [],+ depth+ )+}+function designElement(node: ComponentElement, uses: MarkupUses, depth: number): es.SyntaxNode {const kind = uses.kindconst root = node.part === 'root'const native = root && !(node.part && RADIX[kind]?.parts[node.part])const attributes = [- ...(native ? [jsx.attribute('type', jsx.stringValue('button'))] : []),+ ...(isNativeButton(node, kind) ? [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'))] : []),+ // The root passes the caller's props on, such as `checked` or `onClick`, unless its input+ // takes them.+ ...(root && !INPUT_PROPS[kind] ? [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))),+ ...partAttributes(node, uses),jsx.attribute('className', jsx.container(classNameOf(node, root))),- ...bindingAttributes(node, native)+ ...bindingAttributes(node, kind, native)]// Words alone stay on the element's line, where a line break would add a space.const only = node.children.length === 1 ? node.children[0]?.type : undefined@@ -240,8 +363,19 @@ const qualified = (namespace: string, name: string) => ({right: es.identifier(name)})+/** Props a kind declares itself, where no Radix root has them. */+const OWN_PROPS: Partial<Record<GeneratedKind, string>> = {+ progress: "Omit<ComponentProps<typeof ProgressPrimitive.Root>, 'value'> & { value?: number }",+ numberField:+ "Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & { defaultValue?: number; onValueChange?: (value: number) => void; disabled?: boolean }",+ textField: "ComponentProps<'input'>",+ textarea: "ComponentProps<'textarea'>"+}+/** The root's own props, or a single choice group's. */function rootPropsType(kind: GeneratedKind): es.SyntaxNode {+ const own = OWN_PROPS[kind]+ if (own) return es.parseType(own)const radix = RADIX[kind]if (!radix) return es.parseType("ComponentProps<'button'>")const single = SINGLE_PROPS[kind]@@ -278,12 +412,38 @@ function propsType(component: ComponentModel): es.SyntaxNode {}}+/** A destructured prop, with the default it takes when the caller leaves it out. */+interface Parameter {+ name: string+ default?: es.SyntaxNode+}++/** Props a kind reads itself: a progress bar's value, a number field's start and changes. */+function kindParameters(component: ComponentModel): Parameter[] {+ const { range } = component+ if (component.kind === 'progress' && range)+ return [{ name: 'value', default: es.number(range.default) }]+ if (component.kind === 'numberField' && range)+ return [+ { name: 'defaultValue', default: es.number(range.default) },+ { name: 'onValueChange' },+ { name: 'disabled' }+ ]+ return []+}+/*** `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,* kept off the root, and the rest passed on.*/function parameters(component: ComponentModel): es.SyntaxNode {- const own = [...component.props, ...component.texts]+ const own: Parameter[] = [+ ...kindParameters(component),+ ...[...component.props, ...component.texts].map((prop) => ({+ name: prop.name,+ default: es.string(prop.default)+ }))+ ]if (own.length === 0) return es.identifier('props')return {type: 'ObjectPattern',@@ -292,11 +452,9 @@ function parameters(component: ComponentModel): es.SyntaxNode {type: 'Property',kind: 'init',key: es.identifier(prop.name),- value: {- type: 'AssignmentPattern',- left: es.identifier(prop.name),- right: es.string(prop.default)- },+ value: prop.default+ ? { type: 'AssignmentPattern', left: es.identifier(prop.name), right: prop.default }+ : es.identifier(prop.name),computed: false,method: false,shorthand: true@@ -306,6 +464,49 @@ function parameters(component: ComponentModel): es.SyntaxNode {}}+/**+ * A number field's value: typed freely, and settled within its range when it loses focus or a+ * stepper moves it, which is when the caller hears of it.+ */+const NUMBER_STATE = (range: { min: number; max: number }) =>+ es.fill(+ es.parseModule(dedent`+ const [value, setValue] = useState(defaultValue)+ const commit = (next: number) => {+ const settled = Number.isNaN(next) ? $min : Math.min($max, Math.max($min, next))+ setValue(settled)+ onValueChange?.(settled)+ }+ `),+ { $min: es.number(range.min), $max: es.number(range.max) }+ ).body++const REACT_STATE_IMPORT = es.parseModule(+ "import { useState, type ComponentProps } from 'react'"+).body++/** The component function's statements before it returns, such as a number field's state. */+function prepend(declaration: es.SyntaxNode | undefined, statements: es.SyntaxNode[]): void {+ const fn = es.child(declaration, 'declaration')+ const body = es.child(fn, 'body')+ if (!body || statements.length === 0) return+ body.body = [...statements, ...es.children(body, 'body')]+}++/**+ * The prop a story sets the value with: Radix's uncontrolled value, so a story's control and+ * its play function can both change it, which a slider takes as a list; a progress bar's own+ * value, which nothing else changes.+ */+function valueArg(+ kind: GeneratedKind,+ model: string | null+): Pick<GeneratedComponent, 'valueArg' | 'valueList'> {+ if (!model) return { valueArg: null }+ if (kind === 'progress') return { valueArg: 'value' }+ return { valueArg: defaultOf(model), ...(kind === 'slider' ? { valueList: true } : {}) }+}+/*** A component as a React component on Radix UI: its parts as Radix primitives from the* `radix-ui` package, its variants' state styles in a CSS module, and props that extend the@@ -315,6 +516,7 @@ export const reactComponent: ComponentGenerator = async (component) => {const radix = RADIX[component.kind]const stylesPath = `${component.name}.module.css`const uses: MarkupUses = {+ component,kind: component.kind,choice: component.choice,components: new Set(),@@ -345,11 +547,15 @@ export const reactComponent: ComponentGenerator = async (component) => {$params: parameters(component),$body: body}).body+ const state =+ component.kind === 'numberField' && component.range ? NUMBER_STATE(component.range) : []+ prepend(rest.at(-1), state)+ // A single choice group's props come from Radix's own type, not `ComponentProps`.+ const reactImport = state.length > 0 ? REACT_STATE_IMPORT : [typeImport]const program = {type: 'Program',sourceType: 'module',- // A single choice group's props come from Radix's own type, not `ComponentProps`.- body: [...(SINGLE_PROPS[component.kind] ? [] : [typeImport]), ...imports, stylesImport, ...rest]+ body: [...(SINGLE_PROPS[component.kind] ? [] : reactImport), ...imports, stylesImport, ...rest]}const { css } = await stateStylesToCSS(component.styles)const model = component.model@@ -362,7 +568,6 @@ export const reactComponent: ComponentGenerator = async (component) => {{ path: stylesPath, content: css }],entry: { path: `./${component.name}`, named: true },- // Radix's uncontrolled value, so a story's control and its play function can both change it.- valueArg: model ? defaultOf(model) : null+ ...valueArg(component.kind, model)}}diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.tsindex e2f6fbb8a..a19677707 100644--- a/packages/dom-css/src/export/components/references.ts+++ b/packages/dom-css/src/export/components/references.ts@@ -4,6 +4,7 @@ import type { DesignStyleDeclaration } from '#dom-css/types'import { isEmptyObject } from 'es-toolkit/predicate'import {+ behaviourOwner,findComponentPropertyTargets,findLayerByPath,instanceMainComponent,@@ -82,18 +83,22 @@ function ownerId(graph: SceneGraph, component: SceneNode): string {}/**- * The words an instance shows for a text property: what its bound text layer reads, which an- * assignment or a direct edit sets, else the assignment itself.+ * The words an instance shows for a text property: an assignment that overrides the default,+ * else what its bound text layer reads, which a direct edit changes, else the assignment.*/export function shownText(graph: SceneGraph,instance: SceneNode,propertyId: string): string | undefined {+ const assigned = instance.componentPropertyAssignments[propertyId]+ const main = instanceMainComponent(graph, instance)+ const owner = main && behaviourOwner(graph, main)+ const definition = owner?.componentPropertyDefinitions.find((item) => item.id === propertyId)+ if (typeof assigned === 'string' && assigned !== definition?.defaultValue) return assignedconst target = findComponentPropertyTargets(graph, instance, propertyId).find((item) => item.field === 'TEXT' && item.node.type === 'TEXT')- const assigned = instance.componentPropertyAssignments[propertyId]return target?.node.text ?? (typeof assigned === 'string' ? assigned : undefined)}diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.tsindex f6c3a73a1..0b5984109 100644--- a/packages/dom-css/src/export/components/vue.ts+++ b/packages/dom-css/src/export/components/vue.ts@@ -1,5 +1,6 @@import { HEADING_RESET } from '#dom-css/behaviours/reset'import { stateStylesToCSS } from '#dom-css/behaviours/states/css'+import dedent from 'dedent'import { compact } from 'es-toolkit/array'import { omit } from 'es-toolkit/object'import { camelCase, upperFirst } from 'es-toolkit/string'@@ -7,6 +8,7 @@ import { camelCase, upperFirst } from 'es-toolkit/string'import { es, vue } from '@open-pencil/emit'import { claimName } from '../storybook/names'+import { progressWidth } from './fields'import type {ComponentBinding,ComponentGenerator,@@ -47,9 +49,31 @@ const REKA: Record<toggleGroupItem: { parts: { root: 'ToggleGroupItem' } },accordionItem: {parts: { root: 'AccordionItem', trigger: 'AccordionTrigger', content: 'AccordionContent' }- }+ },+ slider: {+ parts: { root: 'SliderRoot', track: 'SliderTrack', range: 'SliderRange', thumb: 'SliderThumb' },+ model: 'modelValue'+ },+ progress: {+ parts: { root: 'ProgressRoot', indicator: 'ProgressIndicator' },+ model: 'modelValue'+ },+ numberField: {+ parts: {+ root: 'NumberFieldRoot',+ increment: 'NumberFieldIncrement',+ decrement: 'NumberFieldDecrement'+ },+ model: 'modelValue'+ },+ // Reka has no text field; the root is the design's own element around a native input.+ textField: { parts: {} },+ textarea: { parts: {} }}+/** Kinds whose two-way value is their input's, which binds it rather than the root. */+const INPUT_MODEL: ReadonlySet<GeneratedKind> = new Set(['textField', 'textarea'])+/** 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')],@@ -67,23 +91,64 @@ const DISABLED_FLAG = es.parseExpression('disabled || undefined')function bindingAttributes(binding: ComponentBinding,- kind: GeneratedKind,+ uses: TemplateUses,native: boolean): vue.VueAttribute[] {- if (binding.type === 'model')- return [vue.model(identifier(binding.name), REKA[kind].model === 'open' ? 'open' : undefined)]+ const { kind } = uses+ if (binding.type === 'model') {+ if (INPUT_MODEL.has(kind)) return []+ // Reka's slider takes a list of values, which the model's single one stands in.+ const bound = uses.sliderValues ?? binding.name+ return [vue.model(identifier(bound), 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.+ // Reka sets `data-disabled` on its own roots; a native root needs it for the state styles.return [- vue.bound('disabled', identifier('disabled')),+ ...(native && kind !== 'button' ? [] : [vue.bound('disabled', identifier('disabled'))]),...(native ? [vue.bound('data-disabled', DISABLED_FLAG)] : [])]}+/** The number range a slider, progress bar, or number field's root is given. */+function rangeAttributes(component: ComponentModel): vue.VueAttribute[] {+ const { range } = component+ if (!range) return []+ const bound = (name: 'min' | 'max' | 'step') => vue.bound(name, es.number(range[name]))+ // A progress bar only takes its maximum; its minimum is where the indicator is empty.+ return component.kind === 'progress'+ ? [bound('max')]+ : [bound('min'), bound('max'), bound('step')]+}++function progressStyle(component: ComponentModel): vue.VueAttribute[] {+ const { range, model } = component+ const style = range && model ? progressWidth(range, identifier(model)) : null+ return style ? [vue.bound('style', style)] : []+}++/** A field's input: Reka's for a number field, else a native input or textarea. */+function inputNode(className: string, uses: TemplateUses): vue.VueNode {+ const { component } = uses+ if (component.kind === 'numberField') {+ uses.reka.add('NumberFieldInput')+ return vue.element('NumberFieldInput', [vue.attribute('class', className)])+ }+ const placeholder = component.text?.placeholder+ return vue.element(component.kind === 'textarea' ? 'textarea' : 'input', [+ vue.attribute('class', className),+ ...(component.model ? [vue.model(identifier(component.model))] : []),+ ...(placeholder ? [vue.attribute('placeholder', placeholder)] : []),+ ...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : [])+ ])+}+/** What a template uses, which its script imports and declares. */interface TemplateUses {+ component: ComponentModelkind: GeneratedKind+ /** The list a slider's root binds, standing in for its single value. */+ sliderValues: string | null/** Reka components. */reka: Set<string>/** Other generated components. */@@ -118,6 +183,7 @@ function templateNode(node: ComponentNode, uses: TemplateUses): vue.VueNode {if (node.type === 'text') return vue.text(node.value)if (node.type === 'textProp') return vue.interpolation(identifier(node.name))if (node.type === 'reference') return reference(node, uses)+ if (node.type === 'input') return inputNode(node.className, uses)if (node.type === 'icon') {uses.icons = truereturn vue.element(ICONIFY, [@@ -127,18 +193,23 @@ function templateNode(node: ComponentNode, uses: TemplateUses): vue.VueNode {}const reka = node.part ? REKA[uses.kind].parts[node.part] : undefinedif (reka) uses.reka.add(reka)- const native = node.part === 'root' && !reka+ const root = node.part === 'root'+ const native = root && !reka+ const button = native && uses.kind === 'button'const element = vue.element(- reka ?? (native ? 'button' : node.tag),+ reka ?? (button ? 'button' : node.tag),[- ...(native ? [vue.attribute('type', 'button')] : []),- ...(node.part === 'root' ? (ROOT_ATTRIBUTES[uses.kind] ?? []) : []),+ ...(button ? [vue.attribute('type', 'button')] : []),+ ...(root ? [...(ROOT_ATTRIBUTES[uses.kind] ?? []), ...rangeAttributes(uses.component)] : []),+ ...(uses.kind === 'progress' && node.part === 'indicator'+ ? progressStyle(uses.component)+ : []),...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.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))],node.children.map((child) => templateNode(child, uses)))@@ -184,6 +255,17 @@ const CHOICE_MODEL = es.parseModule('const $model = defineModel<$Type>($name, { default: $default })')const OPEN_CHOICE_MODEL = es.parseModule('const $model = defineModel<$Type>($name)')+const VALUE_MODEL = es.parseModule(+ 'const $model = defineModel<$Type>($name, { default: $default })'+)+const SLIDER_VALUES = es.parseModule(dedent`+ const $values = computed({+ get: () => [$model.value],+ set: (next: number[] | undefined) => {+ $model.value = next?.[0] ?? $model.value+ }+ })+`)function namedImport(names: readonly string[], source: string, local = (name: string) => name) {return {@@ -201,9 +283,11 @@ function namedImport(names: readonly string[], source: string, local = (name: stconst IMPORT_COMPONENT = es.parseModule(`import $Component from '$path'`)const MODEL_REF = es.parseModule('const $name = ref(true)')-function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {- const imports = [- ...(uses.models.length > 0 ? [namedImport(['ref'], 'vue')] : []),+/** What the script imports: Vue's helpers, Iconify, Reka, and other generated components. */+function scriptImports(uses: TemplateUses): es.SyntaxNode[] {+ const helpers = compact([uses.sliderValues && 'computed', uses.models.length > 0 && 'ref'])+ return [+ ...(helpers.length > 0 ? [namedImport(helpers, 'vue')] : []),...(uses.icons ? [namedImport(['Icon'], '@iconify/vue', () => ICONIFY)] : []),...(uses.reka.size > 0 ? [namedImport([...uses.reka].sort(), 'reka-ui')] : []),...[...uses.components].sort().flatMap(@@ -214,6 +298,34 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {}).body)]+}++/** The model's declaration: a choice, a number or text, or a boolean, and a slider's list. */+function modelDeclaration(component: ComponentModel, uses: TemplateUses): es.SyntaxNode[] {+ const name = component.model+ if (!name) return []+ const { choice, range, text } = component+ const base = { $model: identifier(name), $name: es.string(name) }+ if (choice)+ return es.fill(choice.default === null ? OPEN_CHOICE_MODEL : CHOICE_MODEL, {+ ...base,+ $Type: es.stringUnionType(choice.options),+ $default: choice.default === null ? es.OMIT : es.string(choice.default)+ }).body+ if (!range && !text) return es.fill(MODEL, base).body+ const model = es.fill(VALUE_MODEL, {+ ...base,+ $Type: es.parseType(range ? 'number' : 'string'),+ $default: range ? es.number(range.default) : es.string(text?.default ?? '')+ }).body+ const values = uses.sliderValues+ ? es.fill(SLIDER_VALUES, { $values: identifier(uses.sliderValues), $model: identifier(name) })+ .body+ : []+ return [...model, ...values]+}++function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {const props =component.valueProp ||component.disabled ||@@ -221,24 +333,13 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {component.texts.length > 0? propsDeclaration(component): []- 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) }).bodyconst refs = uses.models.flatMap((item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body)return {type: 'Program',sourceType: 'module',- body: [...imports, ...props, ...model, ...refs]+ body: [...scriptImports(uses), ...props, ...modelDeclaration(component, uses), ...refs]}}@@ -248,19 +349,23 @@ function script(component: ComponentModel, uses: TemplateUses): es.SyntaxNode {* other variant properties.*/export const vueComponent: ComponentGenerator = async (component) => {+ const taken = new Set([+ ...component.props.map((prop) => prop.name),+ ...component.texts.map((text) => text.name),+ ...(component.model ? [component.model] : []),+ 'disabled'+ ])const uses: TemplateUses = {+ component,kind: component.kind,+ sliderValues:+ component.kind === 'slider' && component.model ? claimName('values', taken) : null,reka: new Set(),components: new Set(),icons: false,models: [],// Refs share the script with the component's own props and model.- taken: new Set([- ...component.props.map((prop) => prop.name),- ...component.texts.map((text) => text.name),- ...(component.model ? [component.model] : []),- 'disabled'- ])+ taken}const template = templateNode(component.tree, uses)const { css } = await stateStylesToCSS(component.styles)diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.tsindex 951acf047..70863aa5c 100644--- a/packages/dom-css/src/export/storybook/component.ts+++ b/packages/dom-css/src/export/storybook/component.ts@@ -3,7 +3,12 @@ import { compact } from 'es-toolkit/array'import { es } from '@open-pencil/emit'-import type { ComponentModel, GeneratedComponent, GeneratedKind } from '../components/model'+import type {+ ComponentModel,+ ComponentNode,+ GeneratedComponent,+ GeneratedKind+} from '../components/model'import { claimName, identifierName } from './names'/** Tells readers the file is generated; nothing parses it. */@@ -49,12 +54,75 @@ const PLAY = es.parseExpression(dedent`}`)+/** A slider's Home key moves it to its minimum, as Reka and Radix both handle it. */+const SLIDER_PLAY = es.parseExpression(dedent`+ async ({ canvas, userEvent }) => {+ const thumb = canvas.getByRole('slider')+ thumb.focus()+ await userEvent.keyboard('{Home}')+ await expect(thumb).toHaveAttribute('aria-valuenow', $min)+ }+`)++/**+ * A stepper steps a number field. Both Reka's and the native field's steppers are named by+ * what they do, where a key would only step Reka's input, not a native number input.+ */+const NUMBER_PLAY = es.parseExpression(dedent`+ async ({ canvas, userEvent }) => {+ await userEvent.click(canvas.getByRole('button', { name: $stepper }))+ await expect(canvas.getByRole('spinbutton')).toHaveDisplayValue($value)+ }+`)++/** Whether the component draws a part, such as a number field's increment. */+function drawsPart(node: ComponentNode, part: string): boolean {+ return (+ node.type === 'element' &&+ (node.part === part || node.children.some((child) => drawsPart(child, part)))+ )+}++/** Typing replaces a text field's words. */+const TEXT_PLAY = es.parseExpression(dedent`+ async ({ canvas, userEvent }) => {+ const field = canvas.getByRole('textbox')+ await userEvent.clear(field)+ await userEvent.type(field, 'Hello')+ await expect(field).toHaveValue('Hello')+ }+`)++/** The play function that operates a generated component, if it has one. */+function playOf(component: ComponentModel): es.SyntaxNode | undefined {+ const interaction = INTERACTIONS[component.kind]+ if (interaction)+ return es.fill(PLAY, {+ $role: es.string(interaction.role),+ $state: es.string(interaction.state)+ })+ const { range } = component+ if (component.kind === 'slider' && range)+ return es.fill(SLIDER_PLAY, { $min: es.string(String(range.min)) })+ if (component.kind === 'numberField' && range) {+ const up = range.default + range.step <= range.max+ const part = up ? 'increment' : 'decrement'+ if (!drawsPart(component.tree, part)) return undefined+ return es.fill(NUMBER_PLAY, {+ $stepper: es.string(up ? 'Increase' : 'Decrease'),+ $value: es.string(String(up ? range.default + range.step : range.default - range.step))+ })+ }+ if (component.kind === 'textField' || component.kind === 'textarea') return TEXT_PLAY+ return undefined+}+export interface ComponentStoriesData {/** The Storybook renderer package the stories import their types from. */storybook: stringtitle: stringcomponent: ComponentModel- generated: Pick<GeneratedComponent, 'entry' | 'valueArg'>+ generated: Pick<GeneratedComponent, 'entry' | 'valueArg' | 'valueList'>/** Design links for the whole file, as `parameters.design` entries. */design: { name: string; type: string; url: string }[]}@@ -62,14 +130,27 @@ 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 {+/** A number model's value as its prop takes it: on its own, or in a list for a slider. */+const numberArg = (value: number, list: boolean) =>+ list ? es.array([es.number(value)]) : es.number(value)++/**+ * A model's value at rest: off, the option a choice starts on, none for an open choice, the+ * number a range starts at, or the words a field starts with.+ */+function restValue(component: ComponentModel, list: boolean): es.SyntaxNode | null {+ if (component.range) return numberArg(component.range.default, list)+ if (component.text) return es.string(component.text.default)if (!component.choice) return FALSEreturn component.choice.default === null ? null : es.string(component.choice.default)}-function restArgs(component: ComponentModel, model: string | null): [string, es.SyntaxNode][] {- const rest = restValue(component)+function restArgs(+ component: ComponentModel,+ model: string | null,+ list: boolean+): [string, es.SyntaxNode][] {+ const rest = restValue(component, list)return [...(model && rest ? [[model, rest] as [string, es.SyntaxNode]] : []),...(component.disabled ? [['disabled', FALSE] as [string, es.SyntaxNode]] : []),@@ -78,16 +159,41 @@ function restArgs(component: ComponentModel, model: string | null): [string, es.]}-function argTypes(component: ComponentModel, model: string | null): es.SyntaxNode {+/** The control a model's value gets: a choice's options, a range, text, or a boolean. */+function modelControl(component: ComponentModel, list: boolean): es.SyntaxNode {+ const control = (type: string) => es.object([['control', es.string(type)]])+ const { choice, range } = component+ if (choice)+ return es.object([+ ['control', es.string('select')],+ ['options', es.array(choice.options.map(es.string))]+ ])+ // A slider's list of values is edited as one, not as a range.+ if (range && list) return control('object')+ if (range)+ return es.object([+ [+ 'control',+ es.object([+ ['type', es.string('range')],+ ['min', es.number(range.min)],+ ['max', es.number(range.max)],+ ['step', es.number(range.step)]+ ])+ ]+ ])+ return control(component.text ? 'text' : 'boolean')+}++function argTypes(component: ComponentModel, model: string | null, list: boolean): 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) : booleanreturn es.object([- ...(model ? [[model, modelControl] as [string, es.SyntaxNode]] : []),+ ...(model ? [[model, modelControl(component, list)] as [string, es.SyntaxNode]] : []),...(component.disabled ? [['disabled', boolean] as [string, es.SyntaxNode]] : []),...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, select(prop.options)]),...component.texts.map((text): [string, es.SyntaxNode] => [@@ -100,7 +206,8 @@ function argTypes(component: ComponentModel, model: string | null): es.SyntaxNod/** A story per state worth seeing: at rest, each boolean on, disabled, and each prop value. */function stories(component: ComponentModel,- model: string | null+ model: string | null,+ list: boolean): { name: string; story: es.SyntaxNode }[] {const taken = new Set<string>()const story = (label: string, args: [string, es.SyntaxNode][], play?: es.SyntaxNode) => ({@@ -110,16 +217,21 @@ function stories(...(play ? [['play', play] as [string, es.SyntaxNode]] : [])])})- const interaction = INTERACTIONS[component.kind]+ const { range } = component+ const boolean = !component.choice && !range && !component.textreturn [- story(- 'Default',- [],- interaction &&- es.fill(PLAY, { $role: es.string(interaction.role), $state: es.string(interaction.state) })- ),- ...(component.model && model && !component.choice- ? [story(component.model, [[model, TRUE]])]+ story('Default', [], playOf(component)),+ ...(component.model && model && boolean ? [story(component.model, [[model, TRUE]])] : []),+ // A range gets a story at each end it does not start at.+ ...(range && model+ ? (+ [+ ['Minimum', range.min],+ ['Maximum', range.max]+ ] as const+ )+ .filter(([, value]) => value !== range.default)+ .map(([label, value]) => story(label, [[model, numberArg(value, list)]])): []),// A choice gets a story per option it does not start on, such as each other tab....(component.choice && model@@ -157,24 +269,25 @@ export function printComponentStories(data: ComponentStoriesData): string {]): es.OMITconst { entry, valueArg: model } = data.generated+ const list = data.generated.valueList ?? falseconst body = es.fill(MODULE, {$storybook: es.string(data.storybook),$Component: es.identifier(component.name),$title: es.string(data.title),$parameters: parameters,- $args: es.object(restArgs(component, model)),- $argTypes: argTypes(component, model)+ $args: es.object(restArgs(component, model, list)),+ $argTypes: argTypes(component, model, list)}).bodyconst componentImport = es.fill(entry.named ? IMPORT_NAMED : IMPORT_DEFAULT, {$Component: es.identifier(component.name),$path: es.string(entry.path)}).body- const exported = stories(component, model).flatMap(+ const exported = stories(component, model, list).flatMap((item) => es.fill(STORY, { $name: es.identifier(item.name), $story: item.story }).body)// Only a control with a play function uses `expect`.const [types, expectImport, ...rest] = body- const imports = INTERACTIONS[component.kind] ? [types, expectImport] : [types]+ const imports = playOf(component) ? [types, expectImport] : [types]const module = es.printModule({type: 'Program',sourceType: 'module',diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.tsindex 1ec606076..f6f0b44fa 100644--- a/packages/dom-css/tests/behaviours/fixtures.ts+++ b/packages/dom-css/tests/behaviours/fixtures.ts@@ -475,3 +475,185 @@ export function collapsibleSet(graph?: SceneGraph) {graph)}++const slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]++/** A standalone component with a behaviour, its layers drawn by `draw`. */+function standalone(+ name: string,+ behaviour: Behaviour,+ draw: (graph: SceneGraph, component: SceneNode) => void,+ size: { width: number; height: number }+) {+ const graph = new SceneGraph()+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, { name, ...size })+ draw(graph, component)+ graph.updateNode(component.id, { pluginData: withBehaviour(component, behaviour) })+ return { graph, set: graph.getNode(component.id) ?? component }+}++/** A slider at 60 of 0 to 100 in steps of 5: a track holding its range, and a thumb. */+export function sliderComponent() {+ return standalone(+ 'Volume',+ {+ ...emptyBehaviour('slider'),+ parts: { track: 'track-slot', range: 'range-slot', thumb: 'thumb-slot' },+ numbers: { value: { min: 0, max: 100, step: 5, default: 60 } }+ },+ (graph, slider) => {+ const track = graph.createNode('FRAME', slider.id, {+ name: 'Track',+ componentPropertyReferences: slot('track-slot'),+ y: 8,+ width: 200,+ height: 4,+ fills: COLORS.off+ })+ graph.createNode('FRAME', track.id, {+ name: 'Range',+ componentPropertyReferences: slot('range-slot'),+ width: 120,+ height: 4,+ fills: COLORS.on+ })+ graph.createNode('FRAME', slider.id, {+ name: 'Thumb',+ componentPropertyReferences: slot('thumb-slot'),+ x: 110,+ width: 20,+ height: 20,+ fills: COLORS.white+ })+ },+ { width: 200, height: 20 }+ )+}++/** A progress bar at 50 of 0 to 200, its indicator inside its track. */+export function progressComponent() {+ return standalone(+ 'Upload',+ {+ ...emptyBehaviour('progress'),+ parts: { track: 'track-slot', indicator: 'indicator-slot' },+ numbers: { value: { min: 0, max: 200, step: 1, default: 50 } }+ },+ (graph, progress) => {+ const track = graph.createNode('FRAME', progress.id, {+ name: 'Track',+ componentPropertyReferences: slot('track-slot'),+ width: 200,+ height: 8,+ fills: COLORS.off+ })+ graph.createNode('FRAME', track.id, {+ name: 'Indicator',+ componentPropertyReferences: slot('indicator-slot'),+ width: 50,+ height: 8,+ fills: COLORS.on+ })+ },+ { width: 200, height: 8 }+ )+}++/** A number field at 2 of 1 to 10 between its decrement and increment, hugging them. */+export function numberFieldComponent() {+ const fixture = standalone(+ 'Quantity',+ {+ ...emptyBehaviour('numberField'),+ texts: { text: { propertyId: 'count' } },+ parts: { decrement: 'decrement-slot', increment: 'increment-slot' },+ numbers: { value: { min: 1, max: 10, step: 1, default: 2 } }+ },+ (graph, field) => {+ graph.updateNode(field.id, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ itemSpacing: 8+ })+ const stepper = (name: string, property: string) =>+ graph.createNode('FRAME', field.id, {+ name,+ componentPropertyReferences: slot(property),+ width: 24,+ height: 24,+ fills: COLORS.off+ })+ stepper('Decrement', 'decrement-slot')+ graph.createNode('TEXT', field.id, {+ name: 'Count',+ text: '2',+ componentPropertyReferences: [{ propertyId: 'count', field: 'TEXT' }]+ })+ stepper('Increment', 'increment-slot')+ },+ { width: 80, height: 24 }+ )+ fixture.graph.updateNode(fixture.set.id, {+ componentPropertyDefinitions: [{ id: 'count', name: 'Count', type: 'TEXT', defaultValue: '2' }]+ })+ return { graph: fixture.graph, set: fixture.graph.getNode(fixture.set.id) ?? fixture.set }+}++const INK = solid(0.07, 0.09, 0.15)+const MUTED = solid(0.61, 0.64, 0.69)++/**+ * A text field drawn empty, its placeholder in a muted color, and filled, its words in ink, its+ * text bound to an Email property whose words are the placeholder.+ */+export function textFieldSet() {+ const fixture = componentSet(+ 'Email',+ { Filled: ['No', 'Yes'] },+ {+ ...emptyBehaviour('textField'),+ texts: { value: { propertyId: 'email' } },+ booleans: { filled: { propertyId: 'filled', on: 'Yes', off: 'No' } }+ },+ (graph, variant, { Filled }) => {+ graph.updateNode(variant, { width: 240, height: 36, strokes: [] })+ graph.createNode('TEXT', variant, {+ name: 'Value',+ text: Filled === 'Yes' ? '[email protected]' : 'Email',+ fills: Filled === 'Yes' ? INK : MUTED,+ componentPropertyReferences: [{ propertyId: 'email', field: 'TEXT' }]+ })+ }+ )+ const { graph, set } = fixture+ graph.updateNode(set.id, {+ componentPropertyDefinitions: [+ ...set.componentPropertyDefinitions,+ { id: 'email', name: 'Email', type: 'TEXT', defaultValue: 'Email' }+ ]+ })+ return { graph, set: graph.getNode(set.id) ?? set }+}++/** A textarea starting with its words, with nothing drawn empty. */+export function textareaComponent() {+ const fixture = standalone(+ 'Message',+ { ...emptyBehaviour('textarea'), texts: { value: { propertyId: 'message' } } },+ (graph, field) => {+ graph.createNode('TEXT', field.id, {+ name: 'Value',+ text: 'Tell us more',+ componentPropertyReferences: [{ propertyId: 'message', field: 'TEXT' }]+ })+ },+ { width: 240, height: 80 }+ )+ fixture.graph.updateNode(fixture.set.id, {+ componentPropertyDefinitions: [+ { id: 'message', name: 'Message', type: 'TEXT', defaultValue: 'Tell us more' }+ ]+ })+ return { graph: fixture.graph, set: fixture.graph.getNode(fixture.set.id) ?? fixture.set }+}diff --git a/packages/dom-css/tests/behaviours/states.test.ts b/packages/dom-css/tests/behaviours/states.test.tsindex 6c4f1a0c2..b362ab323 100644--- a/packages/dom-css/tests/behaviours/states.test.ts+++ b/packages/dom-css/tests/behaviours/states.test.ts@@ -19,6 +19,7 @@ import {componentSet,switchSet,tabsComponent,+ textFieldSet,toggleSet} from './fixtures'@@ -172,6 +173,14 @@ describe('state stylesheet', () => {)})+ test("shows a field's filled look while its input or textarea has words", async () => {+ const rules = cssRules((await stateStylesToCSS(styles(textFieldSet()))).css)+ const filled = [...rules].filter(([selector]) =>+ selector.startsWith('.email:has(:is(input, textarea):not(:placeholder-shown))')+ )+ expect(filled.length).toBeGreaterThan(0)+ })+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' })@@ -187,6 +196,24 @@ describe('state stylesheet', () => {})describe('state Tailwind', () => {+ test('writes the filled look as a variant Tailwind compiles to the same condition', async () => {+ const document = stateStylesToTailwind(styles(textFieldSet()))+ const classes = elements(document.children[0] ?? { type: 'text', text: '' }).flatMap(+ (element) => element.attrs.class.split(' ')+ )+ const filled = classes.filter((item) =>+ item.includes('has-[:is(input,textarea):not(:placeholder-shown)]')+ )+ expect(filled.length).toBeGreaterThan(0)+ const rules = compiledRules(await compileTailwindCSS(filled))+ // Tailwind writes the condition as the stylesheet does, inside an `:is()` of its own.+ expect(+ rules.some(([selector]) =>+ selector.includes(':has(:is(:is(input, textarea):not(:placeholder-shown)))')+ )+ ).toBe(true)+ })+test('names a group for the layer a rule tests, which the layers inside it test', async () => {const document = stateStylesToTailwind(anchoredTabs().root)const [, , trigger, label] = elements(document.children[0] ?? { type: 'text', text: '' })diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.tsindex b85b78f5f..4a84e9463 100644--- a/packages/dom-css/tests/export/components/react.test.ts+++ b/packages/dom-css/tests/export/components/react.test.ts@@ -6,6 +6,11 @@ import { dirname, join } from 'node:path'import {accordionComponent,badgeToggleSet,+ numberFieldComponent,+ progressComponent,+ sliderComponent,+ textareaComponent,+ textFieldSet,buttonSet,collapsibleSet,labelledButtonSet,@@ -87,6 +92,59 @@ async function typeErrors(folder: string, name: string): Promise<string[]> {const render = (component: ComponentType<Props>, props: Props = {}) =>renderToStaticMarkup(createElement(component, props))+describe('generated React form controls', () => {+ test('type-check against Radix and React', async () => {+ for (const fixture of [+ sliderComponent(),+ progressComponent(),+ numberFieldComponent(),+ textFieldSet(),+ textareaComponent()+ ]) {+ const { folder } = await generate(fixture)+ expect(await typeErrors(folder, fixture.set.name)).toEqual([])+ }+ })++ test("a slider starts at the design's value as Radix's list, within its range", async () => {+ const { component } = await generate(sliderComponent())+ // Radix places its range from the value, already on the server.+ expect(render(component)).toContain('right:40%')+ expect(render(component, { defaultValue: [25] })).toContain('right:75%')+ })++ test("a progress bar's indicator reaches the value's share of its range", async () => {+ const { component } = await generate(progressComponent())+ expect(render(component)).toContain('width:25%')+ expect(render(component, { value: 150 })).toContain('width:75%')+ // A value past the end fills the indicator, and no further.+ expect(render(component, { value: 500 })).toContain('width:100%')+ })++ test('a number field is a native number input between steppers named for what they do', async () => {+ const { component } = await generate(numberFieldComponent())+ const html = render(component)+ expect(html).toMatch(/<input[^>]*type="number"[^>]*value="2"/)+ expect(html).toMatch(/<input[^>]*min="1"[^>]*max="10"/)+ expect(html).toContain('aria-label="Decrease"')+ expect(html).toContain('aria-label="Increase"')+ expect(render(component, { defaultValue: 7 })).toMatch(/<input[^>]*value="7"/)+ })++ test('a text field takes its props on its input, starting empty with its placeholder', async () => {+ const { component } = await generate(textFieldSet())+ const html = render(component, { name: 'email', className: 'custom' })+ expect(html).toMatch(/<input[^>]*placeholder="Email"[^>]*name="email"/)+ // The caller's class goes on the root, as on every generated component.+ expect(html).toMatch(/^<div class="[^"]*custom/)+ })++ test('a textarea starts with its words', async () => {+ const { component } = await generate(textareaComponent())+ expect(render(component)).toMatch(/<textarea[^>]*>Tell us more<\/textarea>/)+ })+})+describe('generated React components', () => {test('a switch is a Radix switch whose state follows its props', async () => {const { files, component } = await generate(switchSet())diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.tsindex 6d12d8042..08aa1f04d 100644--- a/packages/dom-css/tests/export/components/vue.test.ts+++ b/packages/dom-css/tests/export/components/vue.test.ts@@ -8,12 +8,18 @@ import {buttonSet,collapsibleSet,labelledButtonSet,+ numberFieldComponent,+ progressComponent,+ sliderComponent,+ textareaComponent,+ textFieldSet,radioGroupComponent,settingsSectionSet,switchSet,tabsComponent,toggleGroupComponent} from '#dom-css-tests/behaviours/fixtures'+import { cssRules } from '#dom-css-tests/helpers'import { exportStorybook } from '#dom-css/index'import { createSSRApp, h, type Component } from 'vue'import { compileScript, parse } from 'vue/compiler-sfc'@@ -135,13 +141,27 @@ describe('generated Vue components', () => {expect(checked(await render(component, { value: 'team' }))).toEqual([false, false, true])})- test('an item edited directly shows its own words and is chosen by them', async () => {+ test('an item takes the words its label property assigns, before its layer is synced', async () => {+ const fixture = radioGroupComponent()+ const { graph } = fixture+ const [items] = graph.getChildren(fixture.set.id)+ const last = graph.getChildren(items?.id ?? '').at(-1)+ if (!last) throw new Error('Expected the last item')+ graph.updateNode(last.id, {+ componentPropertyAssignments: { ...last.componentPropertyAssignments, label: 'Scale' }+ })+ const { component } = await generate(fixture)+ expect(await render(component, { value: 'scale' })).toContain('Scale')+ })++ test('an item without its label assigned shows the words its layer reads', async () => {const fixture = radioGroupComponent()const { graph } = fixtureconst [items] = graph.getChildren(fixture.set.id)const last = graph.getChildren(items?.id ?? '').at(-1)const label = graph.getChildren(last?.id ?? '').find((layer) => layer.type === 'TEXT')- if (!label) throw new Error('Expected the item to show its label')+ if (!last || !label) throw new Error('Expected the item to show its label')+ graph.updateNode(last.id, { componentPropertyAssignments: {} })graph.updateNode(label.id, { text: 'Enterprise' })const { component } = await generate(fixture)@@ -196,6 +216,70 @@ describe('generated Vue components', () => {})})+/** The rules of a single-file component's scoped stylesheet, by selector. */+const styleOf = (files: { path: string; content: string | Uint8Array }[], path: string) =>+ cssRules(+ /<style scoped>([\s\S]*)<\/style>/.exec(+ String(files.find((file) => file.path === path)?.content)+ )?.[1] ?? ''+ )++describe('generated Vue form controls', () => {+ test('a slider binds one number within its range, the thumb and range placed by Reka', async () => {+ const { files, component } = await generate(sliderComponent())+ // Reka shows its thumb once mounted; its range already reaches the value on the server.+ const range = (html: string) => /style="([^"]*)" class="volume__range"/.exec(html)?.[1]+ expect(range(await render(component))).toBe('left:0%;right:40%;')+ expect(range(await render(component, { value: 25 }))).toBe('left:0%;right:75%;')+ expect(await render(component)).toContain('aria-valuemax="100"')+ const css = styleOf(files, 'Volume.vue')+ // Reka sets where they are from the value, so the place the design draws them at goes.+ expect(css.get('.volume .volume__thumb')?.left).toBeUndefined()+ expect(css.get('.volume .volume__range')?.width).toBeUndefined()+ // Its root is a span, which lays out as the block the design draws.+ expect(css.get('.volume')?.display).toBe('block')+ expect(css.get('.volume .volume__thumb')?.['box-sizing']).toBe('border-box')+ })++ test("a progress bar's indicator reaches the value's share of its range", async () => {+ const { component } = await generate(progressComponent())+ expect(await render(component)).toMatch(+ /class="upload__indicator"[^>]*style="width:25%;"|style="width:25%;"[^>]*class="upload__indicator"/+ )+ expect(await render(component, { value: 150 })).toContain('width:75%;')+ // A value past the end fills the indicator, and no further.+ expect(await render(component, { value: 500 })).toContain('width:100%')+ })++ test('a number field shows its value in its input, and its root hugs it', async () => {+ const { files, component } = await generate(numberFieldComponent())+ expect(await render(component)).toMatch(/<input[^>]*value="2"/)+ expect(await render(component, { value: 7 })).toMatch(/<input[^>]*value="7"/)+ expect(styleOf(files, 'Quantity.vue').get('.quantity')?.width).toBe('fit-content')+ })++ test('a text field starts empty with its placeholder, and looks filled while it has words', async () => {+ const { files, component } = await generate(textFieldSet())+ const html = await render(component)+ expect(html).toMatch(/<input[^>]*placeholder="Email"/)+ expect(html).not.toContain('[email protected]')+ expect(await render(component, { value: '[email protected]' })).toContain(+ 'value="[email protected]"'+ )+ const css = styleOf(files, 'Email.vue')+ const input = [...css].find(([selector]) => /^\.email \.email__value[^:]*$/.test(selector))?.[1]+ const placeholder = [...css].find(([selector]) => selector.endsWith('::placeholder'))?.[1]+ // Typed words take the filled look; the empty look is the placeholder's.+ expect(input?.color).toBe('#121726')+ expect(placeholder?.color).toBe('#9CA3B0')+ })++ test('a textarea starts with its words', async () => {+ const { component } = await generate(textareaComponent())+ expect(await render(component)).toMatch(/<textarea[^>]*>Tell us more<\/textarea>/)+ })+})+describe('generated Vue stories', () => {test('show each state and operate the control', async () => {const { component, stories } = await generate(switchSet())diff --git a/packages/emit/src/estree.ts b/packages/emit/src/estree.tsindex 610e5f0d9..d03d36a50 100644--- a/packages/emit/src/estree.ts+++ b/packages/emit/src/estree.ts@@ -108,6 +108,15 @@ export const identifier = (name: string): SyntaxNode => ({ type: 'Identifier', nexport const string = (value: string): SyntaxNode => ({ type: 'Literal', value })+/** A finite number, with a negative one written as `-` before its magnitude, as source does. */+export function number(value: number): SyntaxNode {+ if (!Number.isFinite(value)) throw new Error(`Not a finite number: ${value}`)+ const literal = { type: 'Literal', value: Math.abs(value) }+ return value < 0+ ? { type: 'UnaryExpression', operator: '-', prefix: true, argument: literal }+ : literal+}+const propertyKey = (key: string) =>/^[A-Za-z_$][\w$]*$/.test(key) ? identifier(key) : string(key)diff --git a/packages/emit/tests/jsx.test.ts b/packages/emit/tests/jsx.test.tsindex a8b91d1f9..c9645e966 100644--- a/packages/emit/tests/jsx.test.ts+++ b/packages/emit/tests/jsx.test.ts@@ -84,3 +84,11 @@ describe('filling templates', () => {)})})++describe('numbers', () => {+ test('print as source writes them, a negative one with its sign', () => {+ expect(es.printExpression(es.number(2.5))).toBe('2.5')+ expect(es.printExpression(es.number(-10))).toBe('-10')+ expect(() => es.number(Number.NaN)).toThrow()+ })+})diff --git a/packages/scene-graph/src/icons/glyph.ts b/packages/scene-graph/src/icons/glyph.tsindex e4def4fb3..a79b8b77e 100644--- a/packages/scene-graph/src/icons/glyph.ts+++ b/packages/scene-graph/src/icons/glyph.ts@@ -20,38 +20,67 @@ const round = (value: number) => Math.round(value * PRECISION) / PRECISION*/function shape(network: VectorNetwork | null | undefined) {if (!network) return null- const xs = network.vertices.map((vertex) => vertex.x)- const ys = network.vertices.map((vertex) => vertex.y)+ // A saved document keeps coordinates as 32-bit floats, so they are read at that precision+ // either way; rounding alone would still split a value that lands on a rounding boundary.+ const f = Math.fround+ const xs = network.vertices.map((vertex) => f(vertex.x))+ const ys = network.vertices.map((vertex) => f(vertex.y))const minX = Math.min(...xs)const minY = Math.min(...ys)const sx = 1 / (Math.max(...xs) - minX || 1)const sy = 1 / (Math.max(...ys) - minY || 1)return {vertices: network.vertices.map((vertex) => [- round((vertex.x - minX) * sx),- round((vertex.y - minY) * sy),+ round((f(vertex.x) - minX) * sx),+ round((f(vertex.y) - minY) * sy),vertex.strokeCap ?? null,vertex.strokeJoin ?? null]),segments: network.segments.map((segment) => [segment.start,segment.end,- round(segment.tangentStart.x * sx),- round(segment.tangentStart.y * sy),- round(segment.tangentEnd.x * sx),- round(segment.tangentEnd.y * sy)+ round(f(segment.tangentStart.x) * sx),+ round(f(segment.tangentStart.y) * sy),+ round(f(segment.tangentEnd.x) * sx),+ round(f(segment.tangentEnd.y) * sy)]),regions: network.regions}}+/**+ * Paint fields that read the same as when they are absent, which saving and loading a document+ * fills in: a normal blend and no dashes.+ */+const PAINT_DEFAULTS: Readonly<Record<string, unknown>> = { blendMode: 'NORMAL' }++/**+ * A value described the same however it was stored: keys sorted, defaults and empty lists left+ * out, and numbers rounded, since a saved document keeps them at lower precision.+ */+function canonical(value: unknown): unknown {+ // Stored as 32-bit floats too, so read at that precision before rounding, as coordinates are.+ if (typeof value === 'number') return round(Math.fround(value))+ if (Array.isArray(value)) return value.map(canonical)+ if (typeof value !== 'object' || value === null) return value+ const entries = Object.entries(value)+ .filter(+ ([key, item]) =>+ item !== undefined &&+ PAINT_DEFAULTS[key] !== item &&+ !(Array.isArray(item) && item.length === 0)+ )+ .sort(([a], [b]) => a.localeCompare(b))+ return Object.fromEntries(entries.map(([key, item]) => [key, canonical(item)]))+}+/*** A paint as it looks, leaving out the color when the icon's color sets it, and a stroke's* weight, which resizing scales.*/function paint(fill: Fill | Stroke, tinted: boolean) {const { color, ...rest } = 'weight' in fill ? omit(fill, ['weight']) : fill- return tinted ? rest : { ...rest, color }+ return canonical(tinted ? rest : { ...rest, color })}/** FNV-1a, enough to tell one glyph from another without keeping the whole description. */diff --git a/packages/vue/src/canvas/islands/controls/fields.ts b/packages/vue/src/canvas/islands/controls/fields.tsindex 3109552db..d0d8a53b0 100644--- a/packages/vue/src/canvas/islands/controls/fields.ts+++ b/packages/vue/src/canvas/islands/controls/fields.ts@@ -6,7 +6,12 @@ import {} from 'reka-ui'import { h, type VNode } from 'vue'-import { booleanOf, type ControlModel, type ControlRole } from '@open-pencil/dom-css/export'+import {+ booleanOf,+ INPUT_RESET,+ type ControlModel,+ type ControlRole+} from '@open-pencil/dom-css/export'import { numberSettings } from '@open-pencil/scene-graph'import type { ElementOverride, IslandRenderContext } from '#vue/canvas/islands/render'@@ -15,17 +20,6 @@ import { disabled, interaction, stateOf } from './shared'type Base = (override?: ElementOverride) => VNode-/** A text layer's look carried over to the input that replaces it. */-const INPUT_RESET: Record<string, string> = {- border: 'none',- outline: 'none',- padding: '0',- margin: '0',- background: 'transparent',- resize: 'none',- 'box-sizing': 'border-box'-}-/** A text field, textarea, or number field: its root shows focus and drives its look. */export function fieldRoot(island: IslandRenderContext, control: ControlModel, base: Base): VNode {const state = stateOf(island, control)diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex ad12e1daf..f5b6a4f6a 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -43,7 +43,7 @@ This reference describes scene creation, not React DOM output. Use the `render`## Controls-- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.+- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Track`, `Progress.Indicator`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.@@ -86,7 +86,7 @@ The examples below are executed by the authoring-reference tests. Create the namGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.+**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.diff --git a/tests/e2e/dom-css/generated-components.spec.ts b/tests/e2e/dom-css/generated-components.spec.tsindex de6a72a68..a8060129c 100644--- a/tests/e2e/dom-css/generated-components.spec.ts+++ b/tests/e2e/dom-css/generated-components.spec.ts@@ -235,6 +235,140 @@ function disclosureGraph(): SceneGraph {type Framework = 'vue' | 'react'+/** A standalone component with a behaviour, drawn by `draw`. */+function controlComponent(+ name: string,+ behaviour: Behaviour,+ draw: (graph: SceneGraph, componentId: string) => void,+ size: { width: number; height: number }+): SceneGraph {+ const graph = new SceneGraph()+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, { name, ...size })+ draw(graph, component.id)+ graph.updateNode(component.id, { pluginData: withBehaviour(component, behaviour) })+ return graph+}++/** A slider at 60 of 0 to 100 in steps of 5. */+function sliderGraph(): SceneGraph {+ return controlComponent(+ 'Volume',+ {+ ...emptyBehaviour('slider'),+ parts: { track: 'track-slot', range: 'range-slot', thumb: 'thumb-slot' },+ numbers: { value: { min: 0, max: 100, step: 5, default: 60 } }+ },+ (graph, id) => {+ const track = graph.createNode('FRAME', id, {+ name: 'Track',+ componentPropertyReferences: slot('track-slot'),+ y: 8,+ width: 200,+ height: 4,+ fills: fill(0.8, 0.84, 0.88)+ })+ graph.createNode('FRAME', track.id, {+ name: 'Range',+ componentPropertyReferences: slot('range-slot'),+ width: 120,+ height: 4,+ fills: fill(0.31, 0.27, 0.9)+ })+ graph.createNode('FRAME', id, {+ name: 'Thumb',+ componentPropertyReferences: slot('thumb-slot'),+ x: 110,+ width: 20,+ height: 20,+ fills: fill(1, 1, 1)+ })+ },+ { width: 200, height: 20 }+ )+}++/** A number field at 9 of 1 to 10, between its steppers. */+function numberFieldGraph(): SceneGraph {+ const graph = controlComponent(+ 'Quantity',+ {+ ...emptyBehaviour('numberField'),+ texts: { text: { propertyId: 'count' } },+ parts: { decrement: 'decrement-slot', increment: 'increment-slot' },+ numbers: { value: { min: 1, max: 10, step: 1, default: 9 } }+ },+ (graph, id) => {+ graph.updateNode(id, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ itemSpacing: 8+ })+ const stepper = (name: string, property: string) =>+ graph.createNode('FRAME', id, {+ name,+ componentPropertyReferences: slot(property),+ width: 24,+ height: 24,+ fills: fill(0.8, 0.84, 0.88)+ })+ stepper('Decrement', 'decrement-slot')+ graph.createNode('TEXT', id, {+ name: 'Count',+ text: '9',+ textAutoResize: 'WIDTH_AND_HEIGHT',+ width: 16,+ height: 20,+ componentPropertyReferences: [{ propertyId: 'count', field: 'TEXT' }]+ })+ stepper('Increment', 'increment-slot')+ },+ { width: 100, height: 24 }+ )+ const component = graph.getChildren(graph.getPages()[0].id)[0]+ if (component)+ graph.updateNode(component.id, {+ componentPropertyDefinitions: [+ { id: 'count', name: 'Count', type: 'TEXT', defaultValue: '9' }+ ]+ })+ return graph+}++/** A text field drawn white while empty and grey once filled, its placeholder `Email`. */+function textFieldGraph(): SceneGraph {+ const graph = controlSet(+ 'Email',+ { name: 'Filled', values: ['No', 'Yes'] },+ {+ ...emptyBehaviour('textField'),+ texts: { value: { propertyId: 'email' } },+ booleans: { filled: { propertyId: 'value', on: 'Yes', off: 'No' } }+ },+ (graph, variantId, value) => {+ graph.updateNode(variantId, {+ width: 200,+ height: 32,+ fills: value === 'Yes' ? fill(0.95, 0.96, 0.97) : fill(1, 1, 1)+ })+ graph.createNode('TEXT', variantId, {+ name: 'Value',+ text: value === 'Yes' ? '[email protected]' : 'Email',+ componentPropertyReferences: [{ propertyId: 'email', field: 'TEXT' }]+ })+ }+ )+ const set = graph.getChildren(graph.getPages()[0].id)[0]+ if (set)+ graph.updateNode(set.id, {+ componentPropertyDefinitions: [+ ...set.componentPropertyDefinitions,+ { id: 'email', name: 'Email', type: 'TEXT', defaultValue: 'Email' }+ ]+ })+ return graph+}+/*** Runs the stories' Default story in `#story` the way Storybook does: with its args, then its* play function given Storybook's own `within` and `userEvent`. The outcome is recorded on@@ -427,6 +561,52 @@ for (const framework of ['vue', 'react'] as const) {await expect(enabled.getByText('Account settings')).toBeHidden()})+ test('a slider moves by its step from the keyboard, within its range', async ({+ page+ }, info) => {+ server = await serveComponent(sliderGraph(), framework, info.outputPath('slider'))+ await page.goto(server.resolvedUrls?.local[0] ?? '')+ const thumb = page.locator('#enabled').getByRole('slider')+ await expect(thumb).toHaveAttribute('aria-valuenow', '60')+ // The root lays out at the size the design draws, though Reka and Radix render a span.+ await expect(page.locator('#enabled > *').first()).toHaveCSS('width', '200px')+ await thumb.focus()+ await page.keyboard.press('ArrowRight')+ await expect(thumb).toHaveAttribute('aria-valuenow', '65')+ await page.keyboard.press('End')+ await page.keyboard.press('ArrowRight')+ await expect(thumb).toHaveAttribute('aria-valuenow', '100')+ })++ test('a number field steps with its buttons and settles within its range', async ({+ page+ }, info) => {+ server = await serveComponent(numberFieldGraph(), framework, info.outputPath('quantity'))+ await page.goto(server.resolvedUrls?.local[0] ?? '')+ const enabled = page.locator('#enabled')+ const field = enabled.getByRole('spinbutton')+ await expect(field).toHaveValue('9')+ await enabled.getByRole('button', { name: 'Increase' }).click()+ await expect(field).toHaveValue('10')+ // A value typed past the maximum settles on it once the field is left.+ await field.fill('42')+ await field.blur()+ await expect(field).toHaveValue('10')+ })++ test('a text field takes its filled look while it has words', async ({ page }, info) => {+ server = await serveComponent(textFieldGraph(), framework, info.outputPath('email'))+ await page.goto(server.resolvedUrls?.local[0] ?? '')+ const field = page.locator('#enabled').getByRole('textbox')+ const root = page.locator('#enabled > *').first()+ await expect(field).toHaveAttribute('placeholder', 'Email')+ await expect(root).toHaveCSS('background-color', 'rgb(255, 255, 255)')+ await field.fill('[email protected]')+ await expect(root).toHaveCSS('background-color', 'rgb(242, 245, 247)')+ await field.fill('')+ await expect(root).toHaveCSS('background-color', 'rgb(255, 255, 255)')+ })+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] ?? '')