Skip to content

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

feat: give form controls an invalid state (#1716)

Danila Poyarkovcd1555f749a5
diff --git a/changes/1716/added.md b/changes/1716/added.md
new file mode 100644
index 000000000..8e3f0917d
--- /dev/null
+++ b/changes/1716/added.md
@@ -0,0 +1 @@
+- Form controls (text fields, textareas, number fields, switches, checkboxes, radios, and radio groups) have an invalid state: a behaviour binds it as a value or as an Invalid or Error variant beside Disabled, preview shows it, and generated Vue and React components take an `invalid` prop that sets `aria-invalid` (#1716).
diff --git a/changes/1716/fixed.md b/changes/1716/fixed.md
new file mode 100644
index 000000000..c72252deb
--- /dev/null
+++ b/changes/1716/fixed.md
@@ -0,0 +1 @@
+- A link in a text opens in a new tab in preview, instead of taking the editor away from the document (#1716).
diff --git a/packages/core/src/editor/components/behaviours/complete.ts b/packages/core/src/editor/components/behaviours/complete.ts
index 58a7ffe1a..e3dde0f49 100644
--- a/packages/core/src/editor/components/behaviours/complete.ts
+++ b/packages/core/src/editor/components/behaviours/complete.ts
@@ -1,6 +1,6 @@
import type { SceneNode } from '@open-pencil/scene-graph'
import {
- INTERACTION_STATES,
+ interactionStatesOf,
readBehaviour,
type Behaviour,
type InteractionState
@@ -32,7 +32,8 @@ const STATE_VALUES: Record<InteractionState, string> = {
hover: 'Hover',
pressed: 'Pressed',
focus: 'Focus',
- disabled: 'Disabled'
+ disabled: 'Disabled',
+ invalid: 'Invalid'
}
/** Names tried, in order, for a new states property, skipping ones the set already has. */
const STATE_PROPERTY_NAMES = ['State', 'Interaction', 'Interaction state']
@@ -246,8 +247,8 @@ export function createBehaviourCompletionActions(
/**
* Give a control its interaction states: a new variant property with Default, Hover,
- * Pressed, Focus, and Disabled, a copy of each variant for every state but Default, ready to
- * restyle, and the behaviour's states bound to it. A lone main component first becomes the
+ * Pressed, Focus, Disabled, and, for a form control, Invalid, a copy of each variant for every
+ * state but Default, ready to restyle, and the behaviour's states bound to it. A lone main component first becomes the
* only variant of a new set. Returns the new property's id.
*/
function addBehaviourStates(ownerId: string): string | null {
@@ -260,7 +261,8 @@ export function createBehaviourCompletionActions(
const name = STATE_PROPERTY_NAMES.find((item) => !taken.has(item))
const id = name && variants.addPropertyDefinition(set.id, name, 'VARIANT', STATE_VALUES.rest)
if (!id) return null
- const others = INTERACTION_STATES.filter((state) => state !== 'rest')
+ const shown = interactionStatesOf(found.behaviour.kind)
+ const others = shown.filter((state) => state !== 'rest')
const rows = variantsOf(ctx, set).map((variant) => [
variant.id,
...others.flatMap((state) => {
@@ -271,7 +273,8 @@ export function createBehaviourCompletionActions(
])
layOutRows(ctx, set.id, rows)
const behaviour = readBehaviour(ctx.graph.getNode(set.id) ?? set) ?? found.behaviour
- setBehaviour(set.id, { ...behaviour, states: { propertyId: id, ...STATE_VALUES } })
+ const states = Object.fromEntries(shown.map((state) => [state, STATE_VALUES[state]]))
+ setBehaviour(set.id, { ...behaviour, states: { propertyId: id, ...states } })
ctx.setSelectedIds(new Set([set.id]))
return id
})
diff --git a/packages/core/tests/design-jsx/behaviours.test.ts b/packages/core/tests/design-jsx/behaviours.test.ts
index 55867ee1c..3039bf353 100644
--- a/packages/core/tests/design-jsx/behaviours.test.ts
+++ b/packages/core/tests/design-jsx/behaviours.test.ts
@@ -185,6 +185,29 @@ describe('Reka UI elements in JSX export', () => {
expect(Object.keys(again?.parts ?? {})).toEqual(Object.keys(before?.parts ?? {}))
})
+ test('a checkbox keeps its invalid value and invalid state through export', async () => {
+ const graph = new SceneGraph()
+ const [first] = await renderJSX(
+ graph,
+ `<Checkbox.Root name="Checkbox" modelValue="Checked" invalid="Error" states="State">
+ <Component name="Checked=Off, Error=Off, State=Default" w={16} h={16} />
+ <Component name="Checked=On, Error=Off, State=Default" w={16} h={16} />
+ <Component name="Checked=Off, Error=On, State=Default" w={16} h={16} />
+ <Component name="Checked=Off, Error=Off, State=Invalid" w={16} h={16} />
+ </Checkbox.Root>`
+ )
+ const before = readBehaviour(getNodeOrThrow(graph, first.id))
+ expect(before?.booleans.invalid).toMatchObject({ on: 'On', off: 'Off' })
+ expect(before?.states?.invalid).toBe('Invalid')
+ const code = sceneNodeToJSX(first.id, graph)
+ expect(code).toContain('invalid={{ property: "Error", on: "On", off: "Off" }}')
+
+ const [second] = await renderJSX(graph, code)
+ const again = readBehaviour(getNodeOrThrow(graph, second.id))
+ expect(again?.booleans.invalid).toMatchObject({ on: 'On', off: 'Off' })
+ expect(again?.states?.invalid).toBe('Invalid')
+ })
+
test('tabs and a radio group export their repeated parts and items as Reka writes them', async () => {
const graph = new SceneGraph()
const [radio] = await renderJSX(
diff --git a/packages/core/tests/editor/components/behaviours.test.ts b/packages/core/tests/editor/components/behaviours.test.ts
index e4d29ee69..fa70747fd 100644
--- a/packages/core/tests/editor/components/behaviours.test.ts
+++ b/packages/core/tests/editor/components/behaviours.test.ts
@@ -170,7 +170,9 @@ describe('completing a behaviour', () => {
.getNode(set.id)
?.componentPropertyDefinitions.map((item) => item.name)
expect(names).toEqual(['State', 'Interaction'])
- expect(editor.graph.getChildren(set.id)).toHaveLength(10)
+ // A switch is a form control, so it draws invalid too; a slider above does not.
+ expect(editor.graph.getChildren(set.id)).toHaveLength(12)
+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)?.states?.invalid).toBe('Invalid')
})
test('a lone switch gets Off and On variants as a new set', () => {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts b/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts
index c7efe3ff0..601d52645 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts
@@ -50,7 +50,7 @@ describe('.fig round trip of behaviours', () => {
...emptyBehaviour('textField'),
texts: { value: { propertyId: 'value' } },
booleans: { filled: { propertyId: 'filled', on: 'Yes', off: 'No' } },
- states: guessInteractionStates('interaction', ['Default', 'Focus'])
+ states: guessInteractionStates('textField', 'interaction', ['Default', 'Focus'])
})
expect(
missingBindings(editor.graph, set, readBehaviour(set) ?? emptyBehaviour('button'))
diff --git a/packages/design-jsx/src/behaviours/elements.ts b/packages/design-jsx/src/behaviours/elements.ts
index 8df46fb13..359d4cc72 100644
--- a/packages/design-jsx/src/behaviours/elements.ts
+++ b/packages/design-jsx/src/behaviours/elements.ts
@@ -6,8 +6,13 @@ export interface RekaProps extends BaseProps {
modelValue?: BindingProp
open?: BindingProp
disabled?: BindingProp
+ /** For a form control: the property that draws its value failing validation. */
+ invalid?: BindingProp
filled?: BindingProp
- /** The variant property whose values draw rest, hover, pressed, focus, and disabled. */
+ /**
+ * The variant property whose values draw rest, hover, pressed, focus, disabled, and, for a
+ * form control, invalid.
+ */
states?: string
min?: number
max?: number
diff --git a/packages/design-jsx/src/behaviours/index.ts b/packages/design-jsx/src/behaviours/index.ts
index d221d6d27..002042290 100644
--- a/packages/design-jsx/src/behaviours/index.ts
+++ b/packages/design-jsx/src/behaviours/index.ts
@@ -201,6 +201,7 @@ export const BEHAVIOUR_PROPS = [
'modelValue',
'open',
'disabled',
+ 'invalid',
'filled',
'states',
'min',
@@ -227,8 +228,10 @@ function rootSpec(kind: BehaviourKind, props: Record<string, unknown>): Behaviou
const values: NonNullable<BehaviourSpec['values']> = {}
const main = kind === 'collapsible' ? props.open : props.modelValue
if (isBinding(main)) values[kind === 'collapsible' ? 'open' : 'value'] = main
- if (isBinding(props.disabled)) values.disabled = props.disabled
- if (isBinding(props.filled)) values.filled = props.filled
+ for (const flag of ['disabled', 'invalid', 'filled'] as const) {
+ const binding = props[flag]
+ if (isBinding(binding)) values[flag] = binding
+ }
const range: Record<string, number> = {}
for (const key of ['min', 'max', 'step'] as const) {
const value = props[key]
diff --git a/packages/design-jsx/src/definitions.ts b/packages/design-jsx/src/definitions.ts
index c352fc5c3..a97cba21b 100644
--- a/packages/design-jsx/src/definitions.ts
+++ b/packages/design-jsx/src/definitions.ts
@@ -202,6 +202,7 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = [
'modelValue',
'open',
'disabled',
+ 'invalid',
'filled',
'states',
'min',
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 23f5880f8..1970a51e4 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -55,7 +55,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`, `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`.
+- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, for form controls (fields, switches, checkboxes, radios) `invalid`, 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, disabled, and, for form controls, invalid (a value named Invalid or Error); 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} />`.
- A tab trigger with a selected look of its own is a `Tabs.Tab` component, written on its own with `modelValue` naming its selected variant property; `Tabs.Root` then lists its tabs as `<Tabs.Tab of={tabId} />`, which go in the list as plain `Tabs.Trigger`s do, and each shows its selected variant while its tab is chosen.
diff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.md
index 3eecc0ef3..aa85ae84e 100644
--- a/packages/docs/development/behaviours-and-preview.md
+++ b/packages/docs/development/behaviours-and-preview.md
@@ -14,7 +14,7 @@ The model lives in `@open-pencil/scene-graph` (`packages/scene-graph/src/behavio
- **Kinds and contracts** (`kinds.ts`). `BEHAVIOUR_CONTRACTS` gives each kind its values and parts, keyed by kind, so a kind without a contract does not type-check. Contracts follow Reka UI's anatomy: every Reka subcomponent is a slot of the component, the component itself is the root, and a slot that holds repeated parts names the Reka part of its children, such as the tab list's triggers or a group's items.
- **Storage** (`schema.ts`, `model.ts`). A behaviour is stored as the `behaviour` field of OpenPencil's plugin data on the component or set, with properties and slots bound by id. Its role is `content`, so it travels with library assets and counts towards their update hash. `.fig` export renames the bound ids to the GUIDs it gives the properties.
- **Values**: a boolean is a variant property (with the values that mean on and off) or a boolean property; text is a text property; a number is the behaviour's own range, since Figma has no number property; a choice is which child of a slot is active.
-- **States**: a variant property whose values draw rest, hover, pressed, focus, and disabled.
+- **States**: a variant property whose values draw rest, hover, pressed, focus, disabled, and, for a form control (`hasInvalidState`), invalid. `interactionStatesOf` lists the states a kind shows. Invalid is also a boolean value of form controls, for sets that draw it on a property of its own.
- **Specs** (`spec.ts`). `behaviourFromSpec` and `behaviourToSpec` convert between the stored behaviour and a spec that names properties and slots, which is how every authoring surface except the panel writes it. Errors name what the component has.
## Authoring surfaces
@@ -42,12 +42,12 @@ Controls and DOM keys use layer paths (names below the island root), not node id
## Code export
-Export reads the same model as preview. `behaviourArgs` gives a component set its props: a boolean value drawn by an on/off variant property becomes `checked`, `pressed`, `open`, or `disabled`.
+Export reads the same model as preview. `behaviourArgs` gives a component set its props: a boolean value drawn by an on/off variant property becomes `checked`, `pressed`, `open`, `disabled`, or `invalid`. `invalid` sets `data-invalid` on the root and `aria-invalid` on the control a person fills in: a field's input, or else the root.
`stateStyles` merges a set's variants into one markup tree, matching layers by layer path:
- The rest variant is the base. Each other variant becomes a rule holding only what it changes, under conditions on the control's root.
-- The conditions are the attributes Reka and Radix set, `data-state` and `data-disabled`; the browser's `:hover`, `:active`, and `:focus-visible`; and a `data-*` attribute for any other variant property, which the generated component sets from its prop.
+- The conditions are the attributes Reka and Radix set, `data-state` and `data-disabled`; `data-invalid`, which the generated component sets from `invalid`; the browser's `:hover`, `:active`, and `:focus-visible`; and a `data-*` attribute for any other variant property, which the generated component sets from its prop. One states property shows one value at a time, so when it draws invalid, focus and the pointer leave an invalid control's look alone, and disabled wins over invalid; preview shows the states in the same order.
- Layers only some variants draw stay in the tree, hidden where absent, and a label that reads differently is a layer per state. A combination the set doesn't draw combines from its parts, and a drawn combination keeps only what its parts don't already give.
`stateStylesToCSS` writes the result as a stylesheet with a readable class per layer. `stateStylesToTailwind` writes it as utilities behind state variants, with a named group per control so a control nested in another reacts only to its own root.
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index d6385821c..2716e6d9f 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -193,15 +193,15 @@ Keep each component's design file in the component's folder and export with `--b
Pass several documents, or a quoted glob such as `'src/**/*.pen'` that OpenPencil expands itself (Node.js 22 or later). Several documents need `--beside` or `--output`; `--page` works with one document only. Documents are exported one after another, and when one fails the rest are still exported before the command exits with an error. `--watch` watches every matched document; a document created after the watch started needs another run.
-Stories are titled by the document's file name, and then the page when more than one page has components: `pricing.fig` gives `pricing/Plan picker`, so documents exported together keep their stories apart. Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, and `disabled` when the set draws a disabled state; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant.
+Stories are titled by the document's file name, and then the page when more than one page has components: `pricing.fig` gives `pricing/Plan picker`, so documents exported together keep their stories apart. Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, `disabled` when the set draws a disabled state, and `invalid` when a form control's set draws an invalid one; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant.
Stories render the component as HTML with inline styles, like `-f html`, so they need no OpenPencil runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families: the export fetches their files from the web font providers the editor uses into `openpencil/<document>/` with a `fonts.css` every story file imports, so stories draw in those fonts, never in a fallback first. The document's design variables go there too, as custom properties in a `tokens.css` every story file imports, so styles bound to variables resolve as the design draws them. A family no provider has, such as Menlo, falls back to the browser's fonts, which the export warns about; `--fonts none` ships no font files. Static stories don't export text, boolean, or instance-swap properties yet.
-With `--framework vue` or `--framework react`, every component set and standalone component becomes a real component instead, `<Name>.vue` or `<Name>.tsx` with a `<Name>.module.css` (with `--css tailwind`, Tailwind utilities in its markup, its states as variants such as `data-[state=checked]:`, for a project that builds Tailwind v4), except slash-named components grouped into one file, and any a rule sets `"generate": false` for, which keep static stories. A component without a behaviour is the design's own elements: its root is the element the design draws, a `div` for a frame, and it takes the root element's own props, such as `onClick` and `class`. Its variant properties are props it sets as `data-*` attributes, so a `State=hover` variant is a prop like any other; its boolean properties are boolean props that show or hide the layers bound to them; and its slot properties are content it shows in place of the design's, a named `<slot>` in Vue and a `ReactNode` prop in React, falling back to the design's content. A component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea is built on Reka UI or on Radix UI's `radix-ui` package, and its interaction states, such as hover and disabled, become real `:hover` and `data-disabled` styles. 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`, every component set and standalone component becomes a real component instead, `<Name>.vue` or `<Name>.tsx` with a `<Name>.module.css` (with `--css tailwind`, Tailwind utilities in its markup, its states as variants such as `data-[state=checked]:`, for a project that builds Tailwind v4), except slash-named components grouped into one file, and any a rule sets `"generate": false` for, which keep static stories. A component without a behaviour is the design's own elements: its root is the element the design draws, a `div` for a frame, and it takes the root element's own props, such as `onClick` and `class`. Its variant properties are props it sets as `data-*` attributes, so a `State=hover` variant is a prop like any other; its boolean properties are boolean props that show or hide the layers bound to them; and its slot properties are content it shows in place of the design's, a named `<slot>` in Vue and a `ReactNode` prop in React, falling back to the design's content. A component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea is built on Reka UI or on Radix UI's `radix-ui` package, and its interaction states, such as hover and disabled, become real `:hover` and `data-disabled` styles. A form control whose set draws an invalid state takes an `invalid` prop, which sets `aria-invalid` on the control a person fills in (a field's input, or the root of a switch, checkbox, or radio) and `data-invalid` on the root, which its invalid styles key on. 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 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. Only an instance that draws exactly as its variant, apart from its property values and where its parent places it, uses the component; one with edited text no property sets, a fill of its own, or other changes draws its own layers, so the story keeps what the design shows. Instances of components not exported, or exported only as static stories, are drawn as before. A variant property whose default the document leaves empty starts at the default variant, the one in the set's top-left corner, which opens its stories. 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.
+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, `disabled`, and `invalid` 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. Only an instance that draws exactly as its variant, apart from its property values and where its parent places it, uses the component; one with edited text no property sets, a fill of its own, or other changes draws its own layers, so the story keeps what the design shows. Instances of components not exported, or exported only as static stories, are drawn as before. A variant property whose default the document leaves empty starts at the default variant, the one in the set's top-left corner, which opens its stories. 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.
A layer filled with a shader plays it behind its content with the `shaders` library's `<Shader>` from `shaders/vue` or `shaders/react`, each effect a child with the preset's props and telemetry off (`disableTelemetry`); browsers without WebGPU show nothing in its place.
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index e38b6e53d..03bc30c8e 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -57,7 +57,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`, `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`.
+- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, for form controls (fields, switches, checkboxes, radios) `invalid`, 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, disabled, and, for form controls, invalid (a value named Invalid or Error); 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} />`.
- A tab trigger with a selected look of its own is a `Tabs.Tab` component, written on its own with `modelValue` naming its selected variant property; `Tabs.Root` then lists its tabs as `<Tabs.Tab of={tabId} />`, which go in the list as plain `Tabs.Trigger`s do, and each shows its selected variant while its tab is chosen.
@@ -136,4 +136,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a
**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.
-**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `markdown`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `overrides`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `markdown`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `overrides`, `mode`, `modelValue`, `open`, `disabled`, `invalid`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.md
index 57bc6244d..3a41e76a2 100644
--- a/packages/docs/user-guide/components.md
+++ b/packages/docs/user-guide/components.md
@@ -49,11 +49,11 @@ A behaviour makes a main component or component set work like a real control, af
The section lists what the control needs:
-- **Values** — the property that holds each value: a variant or boolean property for On, Checked, Pressed, Open, Filled, or Disabled (with the variant values that mean on and off), a text property for a field's text, or a slider's own minimum, maximum, step, and default.
+- **Values** — the property that holds each value: a variant or boolean property for On, Checked, Pressed, Open, Filled, Disabled, or, for fields, switches, checkboxes, and radios, Invalid (with the variant values that mean on and off), a text property for a field's text, or a slider's own minimum, maximum, step, and default.
- **Parts** — the slot that draws each part, such as a switch's thumb, a slider's track, range, and thumb, or a tab list. A group's items slot holds instances of its radios, toggles, or collapsibles, and a tab list may hold instances of a Tab component, which then shows its selected look on the chosen tab and cannot be chosen while drawn disabled.
-- **States** — a variant property whose values draw default, hover, pressed, focus, and disabled. Values named like those states are matched automatically.
+- **States** — a variant property whose values draw default, hover, pressed, focus, disabled, and, for fields, switches, checkboxes, and radios, invalid. Values named like those states are matched automatically; Invalid or Error is the invalid state. An invalid control keeps its invalid look in focus and under the pointer, and a disabled one shows disabled.
-Rows the control requires come first; the rest are under **More options**. When a component has nothing to bind yet, a row offers to create it: a text layer and text property, Off and On variants, or a slot, and **States** offers **Add state variants**, which adds a Default, Hover, Pressed, Focus, and Disabled variant of the component. A lone main component that gets variants this way becomes a component set, and a slot added to a set appears in every variant. Until the control works, a line under its name says what is still needed; clicking it goes there.
+Rows the control requires come first; the rest are under **More options**. When a component has nothing to bind yet, a row offers to create it: a text layer and text property, Off and On variants, or a slot, and **States** offers **Add state variants**, which adds a Default, Hover, Pressed, Focus, and Disabled variant of the component, and an Invalid one for a form control. A lone main component that gets variants this way becomes a component set, and a slot added to a set appears in every variant. Until the control works, a line under its name says what is still needed; clicking it goes there.
Press <kbd>⌥</kbd><kbd>⌘</kbd><kbd>↩</kbd> (<kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Enter</kbd>), choose **View → Preview**, or use ▶ next to Share to preview the canvas. Each top-level layer holding controls runs as live Reka UI components over the canvas, drawn by the component's variants: switches flip, sliders drag, tabs and accordions open, and text fields are real inputs with the browser's caret, selection, and paste. Preview never changes the document or its history. **Reset** puts every control back as designed, and <kbd>Esc</kbd> or the pill's close button returns to editing. In split view, each canvas previews on its own.
diff --git a/packages/dom-css/src/behaviours/args.ts b/packages/dom-css/src/behaviours/args.ts
index 57dbf7987..25c5af868 100644
--- a/packages/dom-css/src/behaviours/args.ts
+++ b/packages/dom-css/src/behaviours/args.ts
@@ -8,7 +8,10 @@ import {
/** A variant property a boolean value draws, as the component's boolean prop. */
export interface BooleanArg {
- /** The prop's name, as Reka and Radix call it: `checked`, `pressed`, `open`, `disabled`. */
+ /**
+ * The prop's name, as Reka and Radix call it: `checked`, `pressed`, `open`, `disabled`; or
+ * `invalid`, which code marks with `aria-invalid`.
+ */
name: string
on: string
off: string
@@ -20,10 +23,10 @@ export interface BehaviourArgs {
booleans: Map<string, BooleanArg>
/**
* The variant property that draws interaction states. States follow the pointer and focus,
- * so they are not props; `rest` is the value shown without one, and `disabled` the value the
- * disabled prop shows, if the set draws it.
+ * so they are not props; `rest` is the value shown without one, and `disabled` and `invalid`
+ * the values the `disabled` and `invalid` props show, if the set draws them.
*/
- states?: { property: string; rest: string; disabled?: string }
+ states?: { property: string; rest: string; disabled?: string; invalid?: 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.
@@ -31,6 +34,14 @@ export interface BehaviourArgs {
filled?: { property: string; on: string; off: string }
}
+/** Props that mark the control rather than hold its value. */
+export const FLAGS = ['disabled', 'invalid'] as const
+
+export type Flag = (typeof FLAGS)[number]
+
+/** Whether a boolean prop is a flag rather than the control's value. */
+export const isFlag = (name: string): name is Flag => FLAGS.some((flag) => flag === name)
+
/** Values a behaviour derives from others instead of taking as props. */
const DERIVED_VALUES = new Set(['filled'])
@@ -77,7 +88,8 @@ export function behaviourArgs(graph: SceneGraph, set: SceneNode): BehaviourArgs
? {
property: statesProperty.name,
rest: behaviour.states?.rest ?? statesProperty.defaultValue,
- disabled: behaviour.states?.disabled
+ disabled: behaviour.states?.disabled,
+ invalid: behaviour.states?.invalid
}
: undefined
const filled = filledArg(behaviour, variant)
diff --git a/packages/dom-css/src/behaviours/controls.ts b/packages/dom-css/src/behaviours/controls.ts
index c72c94acc..fbb0c3b11 100644
--- a/packages/dom-css/src/behaviours/controls.ts
+++ b/packages/dom-css/src/behaviours/controls.ts
@@ -32,6 +32,8 @@ export interface StatesModel {
rest: string | undefined
/** Whether the document's instance is drawn disabled. */
designedDisabled: boolean
+ /** Whether the document's instance is drawn invalid. */
+ designedInvalid: boolean
}
/** An instance with a behaviour below a root layer: its values, states, and bound layers. */
@@ -93,7 +95,8 @@ function statesModel(
name: definition.name,
values: states,
rest: states.rest ?? authored,
- designedDisabled: !!states.disabled && authored === states.disabled
+ designedDisabled: !!states.disabled && authored === states.disabled,
+ designedInvalid: !!states.invalid && authored === states.invalid
}
}
diff --git a/packages/dom-css/src/behaviours/states/conditions.ts b/packages/dom-css/src/behaviours/states/conditions.ts
index e0aa953bf..0f7fc361e 100644
--- a/packages/dom-css/src/behaviours/states/conditions.ts
+++ b/packages/dom-css/src/behaviours/states/conditions.ts
@@ -28,24 +28,33 @@ function booleanCondition(arg: BooleanArg): ValueCondition {
return (value) => {
if (value === arg.off) return null
if (arg.name === 'disabled') return { type: 'disabled' }
+ if (arg.name === 'invalid') return { type: 'invalid' }
const state = DATA_STATE_ON[arg.name]
return state ? { type: 'state', value: state } : { type: 'prop', name: arg.name, value }
}
}
-/** The interaction-state property's values: hover, pressed, focus, and disabled. */
+/** The interaction-state property's values: hover, pressed, focus, disabled, and invalid. */
function interactionCondition(set: SceneNode, states: NonNullable<BehaviourArgs['states']>) {
const behaviour = readBehaviour(set)
const within = behaviour ? FOCUS_WITHIN.has(behaviour.kind) : false
+ // One value shows at a time: an invalid control shows invalid in focus and under the pointer,
+ // and a disabled one shows disabled whether or not it is valid.
+ const drawsInvalid = states.invalid !== undefined
+ const drawsDisabled = states.disabled !== undefined
const byValue = new Map<string, StateCondition>()
for (const state of INTERACTIONS) {
const value = behaviour?.states?.[state]
- if (value !== undefined && value !== states.rest)
- byValue.set(value, {
- type: 'interaction',
- state,
- ...(state === 'focus' && within ? { within } : {})
- })
+ if (value === undefined || value === states.rest) continue
+ const condition: StateCondition = { type: 'interaction', state }
+ if (state === 'focus' && within) condition.within = true
+ if (drawsInvalid) condition.valid = true
+ byValue.set(value, condition)
+ }
+ if (states.invalid !== undefined) {
+ const condition: StateCondition = { type: 'invalid' }
+ if (drawsDisabled) condition.enabled = true
+ byValue.set(states.invalid, condition)
}
if (states.disabled !== undefined) byValue.set(states.disabled, { type: 'disabled' })
const name = states.property
diff --git a/packages/dom-css/src/behaviours/states/css.ts b/packages/dom-css/src/behaviours/states/css.ts
index 29b1193fe..2fc7cb03e 100644
--- a/packages/dom-css/src/behaviours/states/css.ts
+++ b/packages/dom-css/src/behaviours/states/css.ts
@@ -26,12 +26,16 @@ export const FILLED = ':has(:is(input, textarea):not(:placeholder-shown))'
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 === 'invalid')
+ return condition.enabled ? '[data-invalid]:not([data-disabled])' : '[data-invalid]'
if (condition.type === 'filled') return FILLED
if (condition.type === 'prop')
return `[${propAttribute(condition.name)}=${quoted(condition.value)}]`
- if (condition.state === 'focus') return condition.within ? ':focus-within' : ':focus-visible'
+ const valid = condition.valid ? ':not([data-invalid])' : ''
+ if (condition.state === 'focus')
+ return `${condition.within ? ':focus-within' : ':focus-visible'}${valid}`
// A disabled control keeps its disabled look under the pointer.
- return `${condition.state === 'hover' ? ':hover' : ':active'}:not([data-disabled])`
+ return `${condition.state === 'hover' ? ':hover' : ':active'}:not([data-disabled])${valid}`
}
function designNode(node: StateNode, classes: Map<StateElement, string>): DesignNode {
diff --git a/packages/dom-css/src/behaviours/states/tailwind.ts b/packages/dom-css/src/behaviours/states/tailwind.ts
index 50711d094..3dc8b0530 100644
--- a/packages/dom-css/src/behaviours/states/tailwind.ts
+++ b/packages/dom-css/src/behaviours/states/tailwind.ts
@@ -23,15 +23,18 @@ 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 === 'invalid')
+ return `${condition.enabled ? on('not-data-disabled') : ''}${on('data-invalid')}`
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(condition.within ? 'focus-within' : 'focus-visible')
+ const valid = condition.valid ? on('not-data-invalid') : ''
+ if (condition.state === 'focus')
+ return `${valid}${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')}`
+ return `${on('not-data-disabled')}${valid}${on(condition.state === 'hover' ? 'hover' : 'active')}`
}
function utilities(style: DesignStyleDeclaration, options: StateTailwindOptions): string[] {
diff --git a/packages/dom-css/src/behaviours/states/types.ts b/packages/dom-css/src/behaviours/states/types.ts
index d016fe25a..e6c887ce1 100644
--- a/packages/dom-css/src/behaviours/states/types.ts
+++ b/packages/dom-css/src/behaviours/states/types.ts
@@ -3,13 +3,25 @@ import type { DesignElement, DesignStyleDeclaration, DesignText } from '#dom-css
/**
* What must hold on a control's root for a variant to show. Reka and Radix set `data-state`
* and `data-disabled` themselves; the browser sets the interactions; a generated component
- * sets `data-*` from its props for every other variant property.
+ * sets `data-invalid` from its `invalid` prop, and `data-*` from its props for every other
+ * variant property.
*/
export type StateCondition =
| { type: 'state'; value: string }
| { type: 'disabled' }
- /** `within` when focus lands on a layer inside the control, such as a field's input. */
- | { type: 'interaction'; state: 'hover' | 'pressed' | 'focus'; within?: boolean }
+ /** `enabled` when the property that draws invalid draws disabled too, which wins over it. */
+ | { type: 'invalid'; enabled?: boolean }
+ | {
+ type: 'interaction'
+ state: 'hover' | 'pressed' | 'focus'
+ /** When focus lands on a layer inside the control, such as a field's input. */
+ within?: boolean
+ /**
+ * When the property that draws the interaction draws invalid too: one value shows at a
+ * time, and an invalid control keeps its invalid look under the pointer and in focus.
+ */
+ valid?: boolean
+ }
/** A field whose input holds text. */
| { type: 'filled' }
| { type: 'prop'; name: string; value: string }
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index dc0747f44..1aaa4b91a 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -1,4 +1,10 @@
-import { behaviourArgs, type BehaviourArgs } from '#dom-css/behaviours/args'
+import {
+ behaviourArgs,
+ FLAGS,
+ isFlag,
+ type BehaviourArgs,
+ type Flag
+} from '#dom-css/behaviours/args'
import { behaviourControls, booleanOf } from '#dom-css/behaviours/controls'
import { BUTTON_RESET } from '#dom-css/behaviours/reset'
import { allElements } from '#dom-css/behaviours/states/layers'
@@ -94,12 +100,14 @@ export interface VariantProp {
/**
* What the control's root binds, which each framework writes in its own idiom: the two-way
- * value (`v-model`, or Radix's `checked` and `onCheckedChange`), `disabled`, and a variant
- * property the component sets as a `data-*` attribute from its prop.
+ * value (`v-model`, or Radix's `checked` and `onCheckedChange`), `disabled`, `invalid`, and a
+ * variant property the component sets as a `data-*` attribute from its prop.
*/
export type ComponentBinding =
| { type: 'model'; name: string }
| { type: 'disabled' }
+ /** `aria-invalid` and `data-invalid` while the `invalid` prop is on. */
+ | { type: 'invalid' }
/** A group's item: the value it stands for, which the group chooses among. */
| { type: 'value' }
| { type: 'prop'; prop: VariantProp; attribute: string }
@@ -184,6 +192,8 @@ export interface ComponentModel {
item: ComponentModel | null
/** Whether the set draws a disabled state, so the component takes `disabled`. */
disabled: boolean
+ /** Whether the set draws an invalid state, so the component takes `invalid`. */
+ invalid: boolean
props: VariantProp[]
texts: TextProp[]
booleans: BooleanProp[]
@@ -327,17 +337,18 @@ function variantProps(
}))
}
-/** What the root binds: its model, an item's value, `disabled`, and its variant props. */
+/** What the root binds: its model, an item's value, `disabled`, `invalid`, and its variant props. */
function rootBindings(
model: string | null,
item: boolean,
- disabled: boolean,
+ flags: Flags,
props: readonly VariantProp[]
): ComponentBinding[] {
return [
...(model ? [{ type: 'model' as const, name: model }] : []),
...(item ? [{ type: 'value' as const }] : []),
- ...(disabled ? [{ type: 'disabled' as const }] : []),
+ ...(flags.disabled ? [{ type: 'disabled' as const }] : []),
+ ...(flags.invalid ? [{ type: 'invalid' as const }] : []),
...props.map((prop) => ({
type: 'prop' as const,
prop,
@@ -371,13 +382,29 @@ function itemsOf(
function modelName(args: BehaviourArgs, item: boolean, valued: boolean): string | null {
if (valued) return 'value'
if (item) return null
- return [...args.booleans.values()].find((arg) => arg.name !== 'disabled')?.name ?? null
+ return [...args.booleans.values()].find((arg) => !isFlag(arg.name))?.name ?? null
}
-/** Whether the set draws a disabled look, as a boolean or an interaction state. */
-const drawsDisabled = (args: BehaviourArgs) =>
- [...args.booleans.values()].some((arg) => arg.name === 'disabled') ||
- args.states?.disabled !== undefined
+/**
+ * Kinds whose input is the control a person fills in, which `aria-invalid` marks; other
+ * controls are marked on their root.
+ */
+export const FIELD_KINDS: ReadonlySet<GeneratedKind> = new Set([
+ 'textField',
+ 'textarea',
+ 'numberField'
+])
+
+/** Whether the set draws each flag, so the component takes it as a prop. */
+type Flags = Record<Flag, boolean>
+
+/** Which flags the set draws, as a boolean or an interaction state. */
+const drawnFlags = (args: BehaviourArgs): Flags => {
+ const draws = (name: Flag) =>
+ [...args.booleans.values()].some((arg) => arg.name === name) ||
+ args.states?.[name] !== undefined
+ return { disabled: draws('disabled'), invalid: draws('invalid') }
+}
/** The layers used rather than drawn: a group's items, then other generated components. */
function usedLayers(
@@ -509,9 +536,9 @@ export function componentModel(
const choice = tabs?.choice ?? items?.choice ?? null
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 taken = new Set([...(model ? [model] : []), ...FLAGS, 'value'])
const props = variantProps(graph, set, args, taken)
- const disabled = drawsDisabled(args)
+ const flags = drawnFlags(args)
const used = usedLayers(graph, styles.root, variantIds, items?.used, options.references)
const elements = allElements(styles.root)
const texts = textProps(graph, set, elements, taken, inputProperty)
@@ -537,7 +564,7 @@ export function componentModel(
shaders: shaderLayers(graph, styles.restId, elements),
layerOf: (element) => restLayerOf(graph, styles, element)
},
- rootBindings(model, !!options.itemOf, disabled, props)
+ rootBindings(model, !!options.itemOf, flags, props)
),
model,
choice,
@@ -545,7 +572,7 @@ export function componentModel(
text,
valueProp: !!options.itemOf,
item: items?.item ?? null,
- disabled,
+ ...flags,
props,
texts: texts.texts,
booleans,
diff --git a/packages/dom-css/src/export/components/react/fields.ts b/packages/dom-css/src/export/components/react/fields.ts
index 1a5841c8b..934632ade 100644
--- a/packages/dom-css/src/export/components/react/fields.ts
+++ b/packages/dom-css/src/export/components/react/fields.ts
@@ -12,6 +12,22 @@ export const INPUT_PROPS: Partial<Record<GeneratedKind, 'input' | 'textarea'>> =
textarea: 'textarea'
}
+/** `invalid || undefined`, so `aria-invalid` and `data-invalid` are set only while invalid. */
+export const INVALID_FLAG = () => es.parseExpression('invalid || undefined')
+
+/**
+ * `aria-invalid` on the control a person fills in: a field's input, or else the root. On an
+ * element that also takes the caller's props, which come first, it keeps an `aria-invalid` the
+ * caller passed while `invalid` is off.
+ */
+export const ariaInvalid = (spread = false) =>
+ jsx.attribute(
+ 'aria-invalid',
+ jsx.container(
+ es.parseExpression(spread ? "invalid || props['aria-invalid']" : 'invalid || undefined')
+ )
+ )
+
/** A number field's stepper parts, which change its value by a step. */
export const STEPPERS: Record<string, { label: string; sign: '+' | '-' }> = {
increment: { label: 'Increase', sign: '+' },
@@ -62,6 +78,7 @@ export function inputElement(className: string, uses: MarkupUses, depth: number)
numeric('max', range.max),
numeric('step', range.step),
jsx.attribute('disabled', jsx.container(es.identifier('disabled'))),
+ ...(component.invalid ? [ariaInvalid()] : []),
classAttribute
],
[],
@@ -76,6 +93,7 @@ export function inputElement(className: string, uses: MarkupUses, depth: number)
...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : []),
// The input takes the caller's props, such as `name` or `onChange`.
jsx.spread(es.identifier('props')),
+ ...(component.invalid ? [ariaInvalid(true)] : []),
classAttribute
],
[],
diff --git a/packages/dom-css/src/export/components/react/index.ts b/packages/dom-css/src/export/components/react/index.ts
index ac2eb67cd..8b7901a59 100644
--- a/packages/dom-css/src/export/components/react/index.ts
+++ b/packages/dom-css/src/export/components/react/index.ts
@@ -8,13 +8,14 @@ import { camelCase, upperFirst } from 'es-toolkit/string'
import { es, jsx } from '@open-pencil/emit'
import type { ShaderComponent } from '@open-pencil/scene-graph/shaders'
-import type {
- ComponentElement,
- ComponentGenerator,
- GeneratedComponent,
- ComponentModel,
- ComponentNode,
- GeneratedKind
+import {
+ FIELD_KINDS,
+ type ComponentElement,
+ type ComponentGenerator,
+ type GeneratedComponent,
+ type ComponentModel,
+ type ComponentNode,
+ type GeneratedKind
} from '../model'
import type { ComponentReference } from '../references'
import {
@@ -28,7 +29,9 @@ import {
} from '../shaders'
import { componentClasses } from '../styling'
import {
+ ariaInvalid,
INPUT_PROPS,
+ INVALID_FLAG,
inputElement,
kindParameters,
NUMBER_STATE,
@@ -233,6 +236,12 @@ function bindingAttributes(
return node.bindings.flatMap((binding) => {
if (binding.type === 'prop')
return [jsx.attribute(binding.attribute, jsx.container(es.identifier(binding.prop.name)))]
+ if (binding.type === 'invalid')
+ return [
+ // The root takes the caller's props before its bindings (`designElement`).
+ ...(FIELD_KINDS.has(kind) ? [] : [ariaInvalid(true)]),
+ jsx.attribute('data-invalid', jsx.container(INVALID_FLAG()))
+ ]
// 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(disabledFlag(kind)))]
@@ -397,12 +406,15 @@ function rootPropsType(kind: GeneratedKind, tag: string): es.SyntaxNode {
function propsType(component: ComponentModel): es.SyntaxNode {
const base = rootPropsType(component.kind, component.tree.tag)
const own = [component.props, component.texts, component.booleans, component.slots]
- if (own.every((list) => list.length === 0)) return base
+ if (!component.invalid && own.every((list) => list.length === 0)) return base
return {
type: 'TSIntersectionType',
types: [
base,
es.objectType([
+ ...(component.invalid
+ ? [['invalid', es.parseType('boolean'), true] as [string, es.SyntaxNode, boolean]]
+ : []),
...component.props.map((prop): [string, es.SyntaxNode, boolean] => [
prop.name,
es.stringUnionType(prop.options),
@@ -435,6 +447,8 @@ function propsType(component: ComponentModel): es.SyntaxNode {
function parameters(component: ComponentModel): es.SyntaxNode {
const own: Parameter[] = [
...kindParameters(component),
+ // Marked as `aria-invalid` and `data-invalid`, never passed on as an attribute of its own.
+ ...(component.invalid ? [{ name: 'invalid' }] : []),
...[...component.props, ...component.texts].map((prop) => ({
name: prop.name,
default: es.string(prop.default)
diff --git a/packages/dom-css/src/export/components/references.ts b/packages/dom-css/src/export/components/references.ts
index a650f6f06..3cd89a6e5 100644
--- a/packages/dom-css/src/export/components/references.ts
+++ b/packages/dom-css/src/export/components/references.ts
@@ -1,3 +1,4 @@
+import { FLAGS, isFlag } from '#dom-css/behaviours/args'
import { layerKind } from '#dom-css/behaviours/states/layers'
import type { StateElement } from '#dom-css/behaviours/states/types'
import type { DesignStyleDeclaration } from '#dom-css/types'
@@ -12,7 +13,7 @@ import { instanceMainComponent } from '@open-pencil/scene-graph/instances'
import { drawsAsMain } from './drawn'
import type { ComponentModel } from './model'
-/** A prop a reference sets on the component it uses: a variant or text value, or `disabled`. */
+/** A prop a reference sets on the component it uses: a variant or text value, or a flag. */
export interface ReferenceProp {
name: string
value: string | boolean
@@ -102,6 +103,16 @@ export function shownText(
return target?.node.text ?? (typeof assigned === 'string' ? assigned : undefined)
}
+/** `disabled` and `invalid`, set where the instance shows the state property's value for them. */
+function drawnFlags(component: ComponentModel, values: Record<string, string>): ReferenceProp[] {
+ const states = component.args.states
+ if (!states) return []
+ return FLAGS.filter((flag) => {
+ const value = states[flag]
+ return value !== undefined && values[states.property] === value
+ }).map((flag) => ({ name: flag, value: true }))
+}
+
/**
* What `instance` sets on `component`: the values it is drawn with that differ from defaults,
* and whether it is drawn on: its model, or for a group's item the value that marks it chosen.
@@ -116,13 +127,13 @@ export function referenceValues(
let model: string | null = null
for (const [property, arg] of component.args.booleans) {
if (values[property] !== arg.on) continue
- const on = arg.name === component.model || (component.valueProp && arg.name !== 'disabled')
+ const on = arg.name === component.model || (component.valueProp && !isFlag(arg.name))
if (on) model = arg.name
else props.push({ name: arg.name, value: true })
}
- const states = component.args.states
- if (states?.disabled && values[states.property] === states.disabled)
- props.push({ name: 'disabled', value: true })
+ // A set may draw a flag both as a boolean and as a state value; the prop is set once.
+ const flags = drawnFlags(component, values)
+ props.push(...flags.filter((flag) => !props.some((prop) => prop.name === flag.name)))
for (const prop of component.props) {
const value = values[prop.property]
if (Object.hasOwn(values, prop.property) && value !== prop.default)
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index 55e003d7b..d5d489a50 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -10,13 +10,14 @@ import type { ShaderComponent } from '@open-pencil/scene-graph/shaders'
import { claimName } from '../storybook/names'
import { progressWidth } from './fields'
-import type {
- ComponentBinding,
- ComponentElement,
- ComponentGenerator,
- ComponentModel,
- ComponentNode,
- GeneratedKind
+import {
+ FIELD_KINDS,
+ type ComponentBinding,
+ type ComponentElement,
+ type ComponentGenerator,
+ type ComponentModel,
+ type ComponentNode,
+ type GeneratedKind
} from './model'
import type { ComponentReference } from './references'
import {
@@ -102,6 +103,19 @@ const HEADING_STYLE = Object.entries(HEADING_RESET)
/** `disabled || undefined`, so a native button sets `data-disabled` only while disabled. */
const DISABLED_FLAG = es.parseExpression('disabled || undefined')
+/** `invalid || undefined`, so `aria-invalid` and `data-invalid` are set only while invalid. */
+const INVALID_FLAG = es.parseExpression('invalid || undefined')
+
+/** `aria-invalid` on the control a person fills in: a field's input, or else the root. */
+const ariaInvalid = () => vue.bound('aria-invalid', INVALID_FLAG)
+
+/**
+ * A field's input reads an `aria-invalid` the caller set too: the caller's attributes fall
+ * through to the root, so the input would not otherwise see it.
+ */
+const INPUT_ARIA_INVALID = es.parseExpression("invalid || $attrs['aria-invalid']")
+const inputAriaInvalid = () => vue.bound('aria-invalid', INPUT_ARIA_INVALID)
+
function bindingAttributes(
binding: ComponentBinding,
uses: TemplateUses,
@@ -116,6 +130,11 @@ function bindingAttributes(
}
if (binding.type === 'prop') return [vue.bound(binding.attribute, identifier(binding.prop.name))]
if (binding.type === 'value') return [vue.bound('value', identifier('value'))]
+ if (binding.type === 'invalid')
+ return [
+ ...(FIELD_KINDS.has(kind) ? [] : [ariaInvalid()]),
+ vue.bound('data-invalid', INVALID_FLAG)
+ ]
// Reka sets `data-disabled` on its own roots; a native root needs it for the state styles.
return [
...(native && kind !== 'button' ? [] : [vue.bound('disabled', identifier('disabled'))]),
@@ -155,14 +174,18 @@ function inputNode(className: string, uses: TemplateUses): vue.VueElement {
const { component } = uses
if (component.kind === 'numberField') {
uses.reka.add('NumberFieldInput')
- return vue.element('NumberFieldInput', [vue.attribute('class', uses.classOf(className))])
+ return vue.element('NumberFieldInput', [
+ vue.attribute('class', uses.classOf(className)),
+ ...(component.invalid ? [inputAriaInvalid()] : [])
+ ])
}
const placeholder = component.text?.placeholder
return vue.element(component.kind === 'textarea' ? 'textarea' : 'input', [
vue.attribute('class', uses.classOf(className)),
...(component.model ? [vue.model(identifier(component.model))] : []),
...(placeholder ? [vue.attribute('placeholder', placeholder)] : []),
- ...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : [])
+ ...(component.disabled ? [vue.bound('disabled', identifier('disabled'))] : []),
+ ...(component.invalid ? [inputAriaInvalid()] : [])
])
}
@@ -305,6 +328,7 @@ function propsType(component: ComponentModel): es.SyntaxNode {
es.stringUnionType(prop.options),
true
])
+ if (component.invalid) members.unshift(['invalid', es.parseType('boolean'), true])
if (component.disabled) members.unshift(['disabled', es.parseType('boolean'), true])
// A group's item always stands for a value, which has no default.
if (component.valueProp) members.unshift(['value', es.parseType('string'), false])
@@ -314,9 +338,10 @@ function propsType(component: ComponentModel): es.SyntaxNode {
}
/** `defineProps`, with `withDefaults` when any prop has a default to give. */
-/** Whether any prop has a default to give: `disabled`, a variant, a text, or a boolean. */
+/** Whether any prop has a default to give: a flag, a variant, a text, or a boolean. */
const hasDefaults = (component: ComponentModel) =>
component.disabled ||
+ component.invalid ||
component.props.length > 0 ||
component.texts.length > 0 ||
component.booleans.length > 0
@@ -331,6 +356,7 @@ function propsDeclaration(component: ComponentModel): es.SyntaxNode[] {
function propsDefaults(component: ComponentModel): es.SyntaxNode {
return es.object([
...(component.disabled ? [['disabled', es.parseExpression('false')] as const] : []),
+ ...(component.invalid ? [['invalid', es.parseExpression('false')] as const] : []),
...component.props.map((prop) => [prop.name, es.string(prop.default)] as const),
...component.texts.map((text) => [text.name, es.string(text.default)] as const),
...component.booleans.map(
@@ -442,7 +468,8 @@ export const vueComponent: ComponentGenerator = async (component, options = {})
...component.booleans.map((prop) => prop.name),
...component.slots.map((slot) => slot.name),
...(component.model ? [component.model] : []),
- 'disabled'
+ 'disabled',
+ 'invalid'
])
const uses: TemplateUses = {
component,
diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.ts
index c04159782..50f02801d 100644
--- a/packages/dom-css/src/export/storybook/component.ts
+++ b/packages/dom-css/src/export/storybook/component.ts
@@ -162,6 +162,7 @@ function restArgs(
return [
...(model && rest ? [[model, rest] as [string, es.SyntaxNode]] : []),
...(component.disabled ? [['disabled', FALSE] as [string, es.SyntaxNode]] : []),
+ ...(component.invalid ? [['invalid', FALSE] as [string, es.SyntaxNode]] : []),
...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, es.string(prop.default)]),
...component.texts.map((text): [string, es.SyntaxNode] => [text.name, es.string(text.default)]),
...component.booleans.map((prop): [string, es.SyntaxNode] => [
@@ -207,6 +208,7 @@ function argTypes(component: ComponentModel, model: string | null, list: boolean
return es.object([
...(model ? [[model, modelControl(component, list)] as [string, es.SyntaxNode]] : []),
...(component.disabled ? [['disabled', boolean] as [string, es.SyntaxNode]] : []),
+ ...(component.invalid ? [['invalid', boolean] as [string, es.SyntaxNode]] : []),
...component.props.map((prop): [string, es.SyntaxNode] => [prop.name, select(prop.options)]),
...component.texts.map((text): [string, es.SyntaxNode] => [
text.name,
@@ -216,7 +218,7 @@ function argTypes(component: ComponentModel, model: string | null, list: boolean
])
}
-/** A story per state worth seeing: at rest, each boolean on, disabled, and each prop value. */
+/** A story per state worth seeing: at rest, each boolean on, each flag, and each prop value. */
function stories(
component: ComponentModel,
model: string | null,
@@ -263,6 +265,7 @@ function stories(
.map((option) => story(option, [[model, es.string(option)]]))
: []),
...(component.disabled ? [story('Disabled', [['disabled', TRUE]])] : []),
+ ...(component.invalid ? [story('Invalid', [['invalid', TRUE]])] : []),
...component.props.flatMap((prop) =>
prop.options
.filter((option) => option !== prop.default)
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index 515b12f65..9ce9607a2 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -79,7 +79,12 @@ function componentSetGroup(
return {
name: def.name,
options,
- control: { type: 'state', rest: args.states.rest, disabled: args.states.disabled }
+ control: {
+ type: 'state',
+ rest: args.states.rest,
+ disabled: args.states.disabled,
+ invalid: args.states.invalid
+ }
}
return { name: def.name, options }
})
diff --git a/packages/dom-css/src/export/storybook/module.ts b/packages/dom-css/src/export/storybook/module.ts
index 295c7a573..d0e95a776 100644
--- a/packages/dom-css/src/export/storybook/module.ts
+++ b/packages/dom-css/src/export/storybook/module.ts
@@ -1,3 +1,4 @@
+import { FLAGS, type Flag } from '#dom-css/behaviours/args'
import dedent from 'dedent'
import { es } from '@open-pencil/emit'
@@ -10,12 +11,12 @@ const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overw
/**
* How a variant property is controlled. A boolean value's property becomes a boolean arg that
- * picks its on or off variant; the interaction-state property is left to each story, with a
- * `disabled` arg picking its disabled variant when the set draws one.
+ * picks its on or off variant; the interaction-state property is left to each story, with
+ * `disabled` and `invalid` args picking those variants when the set draws them.
*/
export type StoryControl =
| { type: 'boolean'; name: string; on: string; off: string }
- | { type: 'state'; rest: string; disabled?: string }
+ | { type: 'state'; rest: string; disabled?: string; invalid?: string }
export interface StoryProp {
name: string
@@ -152,16 +153,27 @@ function argRef(name: string): es.SyntaxNode {
}
}
-/** The `disabled` arg a state property adds, unless a boolean value already takes the name. */
-function disabledArg(data: StoryModuleData): { property: string; value: string } | null {
- if (
- data.props.some((prop) => prop.control?.type === 'boolean' && prop.control.name === 'disabled')
- )
- return null
- for (const prop of data.props)
- if (prop.control?.type === 'state' && prop.control.disabled !== undefined)
- return { property: prop.name, value: prop.control.disabled }
- return null
+/** A `disabled` or `invalid` arg that picks a value of the state property. */
+interface FlagArg {
+ name: Flag
+ property: string
+ value: string
+}
+
+/**
+ * The `disabled` and `invalid` args a state property adds, disabled first, which wins when both
+ * are on; a flag a boolean value already takes is left out.
+ */
+function flagArgs(data: StoryModuleData): FlagArg[] {
+ return FLAGS.flatMap((name) => {
+ if (data.props.some((prop) => prop.control?.type === 'boolean' && prop.control.name === name))
+ return []
+ for (const prop of data.props) {
+ const value = prop.control?.type === 'state' ? prop.control[name] : undefined
+ if (value !== undefined) return [{ name, property: prop.name, value }]
+ }
+ return []
+ })
}
/** The arg a prop is set by: a boolean prop's own name, otherwise the property's. */
@@ -177,30 +189,34 @@ function propValue(data: StoryModuleData, prop: StoryProp): es.SyntaxNode {
$then: es.string(control.on),
$else: es.string(control.off)
})
- const disabled = disabledArg(data)
- if (disabled?.property === prop.name)
- return es.fill(CONDITION, {
- $test: argRef('disabled'),
- $then: es.string(disabled.value),
- $else: argRef(prop.name)
- })
- return argRef(prop.name)
+ // `args.disabled ? 'Disabled' : args.invalid ? 'Invalid' : args.State`
+ return flagArgs(data)
+ .filter((flag) => flag.property === prop.name)
+ .reduceRight<es.SyntaxNode>(
+ (otherwise, flag) =>
+ es.fill(CONDITION, {
+ $test: argRef(flag.name),
+ $then: es.string(flag.value),
+ $else: otherwise
+ }),
+ argRef(prop.name)
+ )
}
function argsObject(data: StoryModuleData, values: string[]): es.SyntaxNode {
+ const flags = flagArgs(data)
const entries = data.props.map((prop, i): [string, es.SyntaxNode] => {
const value = values[i] ?? ''
if (prop.control?.type === 'boolean')
return [prop.control.name, boolean(value === prop.control.on)]
- // A disabled story says so through `disabled`, so clearing it shows the rest state.
- if (prop.control?.type === 'state' && value === disabledArg(data)?.value)
+ // A disabled or invalid story says so through its flag, so clearing it shows the rest state.
+ if (prop.control?.type === 'state' && flags.some((flag) => flag.value === value))
return [prop.name, es.string(prop.control.rest)]
return [prop.name, es.string(value)]
})
- const disabled = disabledArg(data)
- if (disabled) {
- const index = data.props.findIndex((prop) => prop.name === disabled.property)
- entries.push(['disabled', boolean(values[index] === disabled.value)])
+ for (const flag of flags) {
+ const index = data.props.findIndex((prop) => prop.name === flag.property)
+ entries.push([flag.name, boolean(values[index] === flag.value)])
}
return es.object(entries)
}
@@ -219,7 +235,8 @@ function argTypes(data: StoryModuleData): es.SyntaxNode {
])
]
})
- if (disabledArg(data)) entries.push(['disabled', es.object([['control', es.string('boolean')]])])
+ for (const flag of flagArgs(data))
+ entries.push([flag.name, es.object([['control', es.string('boolean')]])])
return es.object(entries)
}
@@ -248,7 +265,7 @@ function argsType(data: StoryModuleData): es.SyntaxNode {
argName(prop),
prop.control?.type === 'boolean' ? BOOLEAN : es.stringUnionType(prop.options)
])
- if (disabledArg(data)) entries.push(['disabled', BOOLEAN])
+ for (const flag of flagArgs(data)) entries.push([flag.name, BOOLEAN])
return es.objectType(entries)
}
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index 2a591b694..d7bbcb7f7 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -10,7 +10,8 @@ export const COLORS = {
off: solid(0.8, 0.84, 0.88),
on: solid(0.31, 0.27, 0.9),
hover: solid(0.72, 0.77, 0.84),
- white: solid(1, 1, 1)
+ white: solid(1, 1, 1),
+ error: solid(0.86, 0.15, 0.15)
}
/** A component set whose variants are built by `draw` for each combination of `axes`. */
@@ -107,6 +108,36 @@ export function checkboxSet() {
)
}
+/**
+ * A checkbox as the shadcn/ui kit draws one: one State property for focus, disabled, and
+ * invalid, which shows a red border.
+ */
+export function invalidCheckboxSet() {
+ return componentSet(
+ 'Checkbox',
+ { Checked: ['Off', 'On'], State: ['Default', 'Focus', 'Disabled', 'Invalid'] },
+ {
+ ...emptyBehaviour('checkbox'),
+ booleans: { value: { propertyId: 'checked', on: 'On', off: 'Off' } },
+ states: {
+ propertyId: 'state',
+ rest: 'Default',
+ focus: 'Focus',
+ disabled: 'Disabled',
+ invalid: 'Invalid'
+ }
+ },
+ (graph, variant, { Checked, State }) => {
+ const border = { Focus: COLORS.hover, Invalid: COLORS.error }[State] ?? COLORS.off
+ graph.updateNode(variant, {
+ fills: Checked === 'On' ? COLORS.on : COLORS.white,
+ strokes: border.map((paint) => ({ ...paint, weight: 1, align: 'INSIDE' as const })),
+ opacity: State === 'Disabled' ? 0.5 : 1
+ })
+ }
+ )
+}
+
/** A toggle whose label reads differently when pressed. */
export function toggleSet(graph?: SceneGraph) {
return componentSet(
@@ -671,19 +702,27 @@ 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.
+ * text bound to an Email property whose words are the placeholder. With `invalid`, an Invalid
+ * property draws it with a red border.
*/
-export function textFieldSet() {
+export function textFieldSet({ invalid = false } = {}) {
const fixture = componentSet(
'Email',
- { Filled: ['No', 'Yes'] },
+ { Filled: ['No', 'Yes'], ...(invalid ? { Invalid: ['No', 'Yes'] } : {}) },
{
...emptyBehaviour('textField'),
texts: { value: { propertyId: 'email' } },
- booleans: { filled: { propertyId: 'filled', on: 'Yes', off: 'No' } }
+ booleans: {
+ filled: { propertyId: 'filled', on: 'Yes', off: 'No' },
+ ...(invalid ? { invalid: { propertyId: 'invalid', on: 'Yes', off: 'No' } } : {})
+ }
},
- (graph, variant, { Filled }) => {
- graph.updateNode(variant, { width: 240, height: 36, strokes: [] })
+ (graph, variant, { Filled, Invalid }) => {
+ const strokes =
+ Invalid === 'Yes'
+ ? COLORS.error.map((paint) => ({ ...paint, weight: 1, align: 'INSIDE' as const }))
+ : []
+ graph.updateNode(variant, { width: 240, height: 36, strokes })
graph.createNode('TEXT', variant, {
name: 'Value',
text: Filled === 'Yes' ? '[email protected]' : 'Email',
diff --git a/packages/dom-css/tests/behaviours/states.test.ts b/packages/dom-css/tests/behaviours/states.test.ts
index e169c82d8..491cc0641 100644
--- a/packages/dom-css/tests/behaviours/states.test.ts
+++ b/packages/dom-css/tests/behaviours/states.test.ts
@@ -22,6 +22,7 @@ import {
buttonSet,
checkboxSet,
componentSet,
+ invalidCheckboxSet,
switchSet,
tabsComponent,
textFieldSet,
@@ -235,6 +236,20 @@ describe('state stylesheet', () => {
)
})
+ test('a state property that draws invalid shows it over focus, and disabled over it', async () => {
+ const rules = cssRules((await stateStylesToCSS(styles(invalidCheckboxSet()))).css)
+ const border = (selector: string) => rules.get(selector)?.border
+ expect(border('.checkbox[data-invalid]:not([data-disabled])')).toBe('1px solid #DB2626')
+ // One value of the property shows at a time: an invalid checkbox keeps its look in focus.
+ expect(border('.checkbox:focus-visible:not([data-invalid])')).toBe('1px solid #B8C4D6')
+ expect(rules.get('.checkbox[data-disabled]')).toEqual({ opacity: '0.5' })
+ })
+
+ test('an invalid boolean is shown on its own, combined with any other state', async () => {
+ const rules = cssRules((await stateStylesToCSS(styles(textFieldSet({ invalid: true })))).css)
+ expect(rules.get('.email[data-invalid]')?.border).toBe('1px solid #DB2626')
+ })
+
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]) =>
@@ -319,4 +334,21 @@ describe('state Tailwind', () => {
)
).toHaveLength(1)
})
+
+ test('writes invalid variants that Tailwind compiles to the same selectors', async () => {
+ const document = stateStylesToTailwind(styles(invalidCheckboxSet()))
+ const [root] = elements(document.children[0] ?? { type: 'text', text: '' })
+ const classes = root?.attrs.class.split(' ') ?? []
+ const rules = compiledRules(await compileTailwindCSS(classes))
+ const borders = rules
+ .filter(([, body]) => body.startsWith('border-color:'))
+ .map(([selector]) => selector)
+ // Disabled wins over invalid, and focus leaves an invalid root as it is.
+ expect(
+ borders.filter((selector) => selector.endsWith(':not([data-disabled])[data-invalid]'))
+ ).toHaveLength(1)
+ expect(
+ borders.filter((selector) => selector.endsWith(':not([data-invalid]):focus-visible'))
+ ).toHaveLength(1)
+ })
})
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index b2260b16c..a66ac4416 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -14,6 +14,7 @@ import {
textFieldSet,
buttonSet,
collapsibleSet,
+ invalidCheckboxSet,
labelledButtonSet,
radioGroupComponent,
settingsSectionSet,
@@ -212,13 +213,38 @@ describe('generated React form controls', () => {
progressComponent(),
numberFieldComponent(),
textFieldSet(),
- textareaComponent()
+ textFieldSet({ invalid: true }),
+ textareaComponent(),
+ invalidCheckboxSet()
]) {
const { folder } = await generate(fixture)
expect(await typeErrors(folder, fixture.set.name)).toEqual([])
}
})
+ test('an invalid checkbox is marked for assistive technology and its styles', async () => {
+ const { component } = await generate(invalidCheckboxSet())
+ const valid = render(component)
+ expect(valid).not.toContain('aria-invalid')
+ expect(valid).not.toContain('data-invalid')
+ const invalid = render(component, { invalid: true })
+ expect(invalid).toContain('aria-invalid="true"')
+ expect(invalid).toContain('data-invalid="true"')
+ // `invalid` is the component's own prop, never passed on to the element.
+ expect(invalid).not.toMatch(/ invalid=/)
+ // An `aria-invalid` the caller passes stays while `invalid` is off.
+ expect(render(component, { 'aria-invalid': 'true' })).toContain('aria-invalid="true"')
+ })
+
+ test("an invalid field marks its input, and its root for the field's styles", async () => {
+ const { component } = await generate(textFieldSet({ invalid: true }))
+ const html = render(component, { invalid: true })
+ expect(html).toMatch(/^<div[^>]*data-invalid="true"/)
+ expect(html).toMatch(/<input[^>]*aria-invalid="true"/)
+ expect(html.match(/aria-invalid/g)).toHaveLength(1)
+ expect(render(component, { 'aria-invalid': 'true' })).toMatch(/<input[^>]*aria-invalid="true"/)
+ })
+
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.
diff --git a/packages/dom-css/tests/export/components/references.test.ts b/packages/dom-css/tests/export/components/references.test.ts
new file mode 100644
index 000000000..53dab24ea
--- /dev/null
+++ b/packages/dom-css/tests/export/components/references.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, test } from 'bun:test'
+
+import { componentSet, COLORS } from '#dom-css-tests/behaviours/fixtures'
+import { componentModel } from '#dom-css/export/components/model'
+import { referenceValues } from '#dom-css/export/components/references'
+
+import { emptyBehaviour } from '@open-pencil/scene-graph/behaviours'
+
+/** A checkbox that draws invalid twice: as its own Invalid property and as a State value. */
+function doublyInvalidCheckbox() {
+ return componentSet(
+ 'Checkbox',
+ { Checked: ['Off', 'On'], Invalid: ['No', 'Yes'], State: ['Default', 'Invalid'] },
+ {
+ ...emptyBehaviour('checkbox'),
+ booleans: {
+ value: { propertyId: 'checked', on: 'On', off: 'Off' },
+ invalid: { propertyId: 'invalid', on: 'Yes', off: 'No' }
+ },
+ states: { propertyId: 'state', rest: 'Default', invalid: 'Invalid' }
+ },
+ (graph, variant) => graph.updateNode(variant, { fills: COLORS.white })
+ )
+}
+
+describe('component references', () => {
+ test('an instance drawn invalid both ways sets invalid once', () => {
+ const { graph, set } = doublyInvalidCheckbox()
+ const model = componentModel(graph, set)
+ if (!model) throw new Error('No component model')
+ const variant = graph
+ .getChildren(set.id)
+ .find((child) => child.name === 'Checked=Off, Invalid=Yes, State=Invalid')
+ if (!variant) throw new Error('No invalid variant')
+ const instance = graph.createInstance(variant.id, graph.getPages()[0].id)
+ if (!instance) throw new Error('No instance')
+ const { props } = referenceValues(graph, instance, model)
+ expect(props.filter((prop) => prop.name === 'invalid')).toEqual([
+ { name: 'invalid', value: true }
+ ])
+ })
+})
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index e9324576a..31cc1c9b7 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -7,6 +7,7 @@ import {
accordionComponent,
buttonSet,
collapsibleSet,
+ invalidCheckboxSet,
labelledButtonSet,
numberFieldComponent,
plainBadgeSet,
@@ -372,6 +373,28 @@ describe('generated Vue form controls', () => {
const { component } = await generate(textareaComponent())
expect(await render(component)).toMatch(/<textarea[^>]*>Tell us more<\/textarea>/)
})
+
+ test('an invalid checkbox is marked for assistive technology and its styles', async () => {
+ const { component, stories } = await generate(invalidCheckboxSet())
+ const valid = await render(component)
+ expect(valid).not.toContain('aria-invalid')
+ expect(valid).not.toContain('data-invalid')
+ const invalid = await render(component, { invalid: true })
+ expect(invalid).toMatch(/<button[^>]*aria-invalid="true"[^>]*role="checkbox"/)
+ expect(invalid).toContain('data-invalid="true"')
+ expect(Object.keys(stories)).toContain('Invalid')
+ })
+
+ test("an invalid field marks its input, and its root for the field's styles", async () => {
+ const { component } = await generate(textFieldSet({ invalid: true }))
+ const html = await render(component, { invalid: true })
+ expect(html).toMatch(/^<div[^>]*data-invalid="true"/)
+ expect(html).toMatch(/<input[^>]*aria-invalid="true"/)
+ expect(html.match(/aria-invalid/g)).toHaveLength(1)
+ // An `aria-invalid` the caller sets reaches the input too, not just the root it falls to.
+ const passed = await render(component, { 'aria-invalid': 'true' })
+ expect(passed).toMatch(/<input[^>]*aria-invalid="true"/)
+ })
})
describe('generated Vue stories', () => {
diff --git a/packages/dom-css/tests/export/storybook/export.test.ts b/packages/dom-css/tests/export/storybook/export.test.ts
index dfdf42870..30c48067e 100644
--- a/packages/dom-css/tests/export/storybook/export.test.ts
+++ b/packages/dom-css/tests/export/storybook/export.test.ts
@@ -3,6 +3,7 @@ import { mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { invalidCheckboxSet } from '#dom-css-tests/behaviours/fixtures'
import { BLUE_500, card, designSystem } from '#dom-css-tests/export/token-fixtures'
import { exportStorybook } from '#dom-css/index'
@@ -293,6 +294,27 @@ describe('exportStorybook', () => {
})
})
+ it('picks the invalid variant by an invalid arg, disabled over it', async () => {
+ const { graph } = invalidCheckboxSet()
+ const story = await importStory(
+ String((await exportStorybook(graph, { framework: 'html' }))[0]?.content)
+ )
+ expect(story.default.args).toEqual({
+ checked: false,
+ State: 'Default',
+ disabled: false,
+ invalid: false
+ })
+ const render = (args: object) =>
+ story.default.render({ checked: false, State: 'Default', disabled: false, ...args })
+ expect(render({ invalid: true })).toContain('#DB2626')
+ expect(render({ invalid: true, disabled: true })).toContain('opacity: 0.5')
+ expect(render({ invalid: true, disabled: true })).not.toContain('#DB2626')
+ expect(storyExport(story, 'OnInvalid')).toMatchObject({
+ args: { checked: true, State: 'Default', disabled: false, invalid: true }
+ })
+ })
+
it('draws a variant as it stands alone: hugging its content, sized with its borders', async () => {
const graph = new SceneGraph()
const page = graph.addPage('Library')
diff --git a/packages/scene-graph/src/behaviours/kinds.ts b/packages/scene-graph/src/behaviours/kinds.ts
index daf79bb61..a7f831e19 100644
--- a/packages/scene-graph/src/behaviours/kinds.ts
+++ b/packages/scene-graph/src/behaviours/kinds.ts
@@ -22,9 +22,17 @@ export type BehaviourKind = (typeof BEHAVIOUR_KINDS)[number]
/**
* The interaction states a control can show, each drawn as a value of one variant property:
- * at rest, under the pointer, while pressed, focused from the keyboard, and disabled.
+ * at rest, under the pointer, while pressed, focused from the keyboard, disabled, and invalid. Only
+ * a form control has an invalid state (`hasInvalidState`), shown while its value fails validation.
*/
-export const INTERACTION_STATES = ['rest', 'hover', 'pressed', 'focus', 'disabled'] as const
+export const INTERACTION_STATES = [
+ 'rest',
+ 'hover',
+ 'pressed',
+ 'focus',
+ 'disabled',
+ 'invalid'
+] as const
export type InteractionState = (typeof INTERACTION_STATES)[number]
@@ -69,6 +77,11 @@ export interface BehaviourContract {
parts: BehaviourPartContract[]
}
+const DISABLED: BehaviourValueContract = { id: 'disabled', type: 'boolean', required: false }
+
+/** Whether a form control's value fails validation, which code marks with `aria-invalid`. */
+const INVALID: BehaviourValueContract = { id: 'invalid', type: 'boolean', required: false }
+
/**
* A text field or textarea: its text is a text property, and `filled`, when bound, draws the
* empty field with its placeholder.
@@ -77,7 +90,8 @@ const TEXT_INPUT: BehaviourContract = {
values: [
{ id: 'value', type: 'text', required: true },
{ id: 'filled', type: 'boolean', required: false },
- { id: 'disabled', type: 'boolean', required: false }
+ DISABLED,
+ INVALID
],
parts: []
}
@@ -89,7 +103,7 @@ const TEXT_INPUT: BehaviourContract = {
*/
export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContract>> = {
button: {
- values: [{ id: 'disabled', type: 'boolean', required: false }],
+ values: [DISABLED],
parts: []
},
textField: TEXT_INPUT,
@@ -98,7 +112,8 @@ export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContra
values: [
{ id: 'value', type: 'number', required: false },
{ id: 'text', type: 'text', required: true },
- { id: 'disabled', type: 'boolean', required: false }
+ DISABLED,
+ INVALID
],
parts: [
{ id: 'increment', required: false },
@@ -106,46 +121,31 @@ export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContra
]
},
toggle: {
- values: [
- { id: 'value', type: 'boolean', required: true },
- { id: 'disabled', type: 'boolean', required: false }
- ],
+ values: [{ id: 'value', type: 'boolean', required: true }, DISABLED],
parts: []
},
switch: {
- values: [
- { id: 'value', type: 'boolean', required: true },
- { id: 'disabled', type: 'boolean', required: false }
- ],
+ values: [{ id: 'value', type: 'boolean', required: true }, DISABLED, INVALID],
parts: [{ id: 'thumb', required: false }]
},
checkbox: {
- values: [
- { id: 'value', type: 'boolean', required: true },
- { id: 'disabled', type: 'boolean', required: false }
- ],
+ values: [{ id: 'value', type: 'boolean', required: true }, DISABLED, INVALID],
parts: [{ id: 'indicator', required: false }]
},
radio: {
- values: [
- { id: 'value', type: 'boolean', required: true },
- { id: 'disabled', type: 'boolean', required: false }
- ],
+ values: [{ id: 'value', type: 'boolean', required: true }, DISABLED, INVALID],
parts: [{ id: 'indicator', required: false }]
},
radioGroup: {
- values: [{ id: 'disabled', type: 'boolean', required: false }],
+ values: [DISABLED, INVALID],
parts: [{ id: 'items', required: true, items: true, children: 'item' }]
},
toggleGroup: {
- values: [{ id: 'disabled', type: 'boolean', required: false }],
+ values: [DISABLED],
parts: [{ id: 'items', required: true, items: true, children: 'item' }]
},
slider: {
- values: [
- { id: 'value', type: 'number', required: false },
- { id: 'disabled', type: 'boolean', required: false }
- ],
+ values: [{ id: 'value', type: 'number', required: false }, DISABLED],
parts: [
{ id: 'track', required: true },
{ id: 'range', required: false },
@@ -175,17 +175,14 @@ export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContra
]
},
collapsible: {
- values: [
- { id: 'open', type: 'boolean', required: false },
- { id: 'disabled', type: 'boolean', required: false }
- ],
+ values: [{ id: 'open', type: 'boolean', required: false }, DISABLED],
parts: [
{ id: 'trigger', required: true },
{ id: 'content', required: true }
]
},
accordion: {
- values: [{ id: 'disabled', type: 'boolean', required: false }],
+ values: [DISABLED],
parts: [{ id: 'items', required: true, items: true, children: 'item' }]
}
}
@@ -193,3 +190,13 @@ export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContra
export function behaviourContract(kind: BehaviourKind): BehaviourContract {
return BEHAVIOUR_CONTRACTS[kind]
}
+
+/** Whether a kind of control can be invalid: a form control, whose contract has `invalid`. */
+export function hasInvalidState(kind: BehaviourKind): boolean {
+ return BEHAVIOUR_CONTRACTS[kind].values.some((value) => value.id === 'invalid')
+}
+
+/** The interaction states a kind of control can show. */
+export function interactionStatesOf(kind: BehaviourKind): InteractionState[] {
+ return INTERACTION_STATES.filter((state) => state !== 'invalid' || hasInvalidState(kind))
+}
diff --git a/packages/scene-graph/src/behaviours/model.ts b/packages/scene-graph/src/behaviours/model.ts
index 650127d5e..31be7f490 100644
--- a/packages/scene-graph/src/behaviours/model.ts
+++ b/packages/scene-graph/src/behaviours/model.ts
@@ -7,7 +7,7 @@ import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
import type { ComponentPropertyDefinition, SceneNode } from '../types'
import {
behaviourContract,
- INTERACTION_STATES,
+ interactionStatesOf,
type BehaviourKind,
type InteractionState
} from './kinds'
@@ -151,19 +151,21 @@ const STATE_NAMES: Record<InteractionState, readonly string[]> = {
hover: ['hover', 'hovered', 'hovering'],
pressed: ['pressed', 'active', 'down', 'pressing'],
focus: ['focus', 'focused', 'focus visible', 'focus-visible'],
- disabled: ['disabled', 'inactive']
+ disabled: ['disabled', 'inactive'],
+ invalid: ['invalid', 'error']
}
/**
- * Interaction states for a variant property, each mapped to the value whose name means it, such
- * as `Hover` or `Pressed`; states without such a value are left unset.
+ * A kind of control's interaction states for a variant property, each mapped to the value whose
+ * name means it, such as `Hover` or `Pressed`; states without such a value are left unset.
*/
export function guessInteractionStates(
+ kind: BehaviourKind,
propertyId: string,
values: readonly string[]
): BehaviourInteractionStates {
const states: BehaviourInteractionStates = { propertyId }
- for (const state of INTERACTION_STATES) {
+ for (const state of interactionStatesOf(kind)) {
const match = values.find((value) => STATE_NAMES[state].includes(value.trim().toLowerCase()))
if (match) states[state] = match
}
diff --git a/packages/scene-graph/src/behaviours/schema.ts b/packages/scene-graph/src/behaviours/schema.ts
index e2e853bcf..46fac9dc0 100644
--- a/packages/scene-graph/src/behaviours/schema.ts
+++ b/packages/scene-graph/src/behaviours/schema.ts
@@ -1,6 +1,6 @@
import * as v from 'valibot'
-import { BEHAVIOUR_KINDS, type InteractionState } from './kinds'
+import { BEHAVIOUR_KINDS, hasInvalidState, type InteractionState } from './kinds'
const booleanBindingSchema = v.object({
propertyId: v.string(),
@@ -33,12 +33,13 @@ export const interactionStateValues = {
hover: v.optional(v.string()),
pressed: v.optional(v.string()),
focus: v.optional(v.string()),
- disabled: v.optional(v.string())
+ disabled: v.optional(v.string()),
+ invalid: v.optional(v.string())
} satisfies Record<InteractionState, unknown>
const interactionStatesSchema = v.object({ propertyId: v.string(), ...interactionStateValues })
-export const behaviourSchema = v.object({
+const storedBehaviourSchema = v.object({
kind: v.picklist(BEHAVIOUR_KINDS),
/** Boolean values, by value id, bound to component properties. */
booleans: v.record(v.string(), booleanBindingSchema),
@@ -51,8 +52,23 @@ export const behaviourSchema = v.object({
states: v.optional(interactionStatesSchema)
})
+type StoredBehaviour = v.InferOutput<typeof storedBehaviourSchema>
+
+/** The behaviour without an invalid state when its kind of control has none. */
+function withoutUnsupportedStates(behaviour: StoredBehaviour): StoredBehaviour {
+ if (behaviour.states?.invalid === undefined || hasInvalidState(behaviour.kind)) return behaviour
+ const { invalid: _invalid, ...states } = behaviour.states
+ return { ...behaviour, states }
+}
+
+/**
+ * A stored behaviour. An invalid state on a kind of control that has none, such as a button,
+ * is dropped as it is read, so nothing draws or exports it; the rest of the behaviour stays.
+ */
+export const behaviourSchema = v.pipe(storedBehaviourSchema, v.transform(withoutUnsupportedStates))
+
/** How a main component behaves as a control, as kept in its plugin data. */
-export type Behaviour = v.InferOutput<typeof behaviourSchema>
+export type Behaviour = StoredBehaviour
export type BehaviourBooleanBinding = v.InferOutput<typeof booleanBindingSchema>
export type BehaviourNumberSettings = v.InferOutput<typeof numberSettingsSchema>
export type BehaviourInteractionStates = v.InferOutput<typeof interactionStatesSchema>
diff --git a/packages/scene-graph/src/behaviours/spec.ts b/packages/scene-graph/src/behaviours/spec.ts
index 9b393b73a..50ca006bb 100644
--- a/packages/scene-graph/src/behaviours/spec.ts
+++ b/packages/scene-graph/src/behaviours/spec.ts
@@ -2,7 +2,7 @@ import { omitBy } from 'es-toolkit/object'
import type { SceneGraph } from '../graph'
import type { ComponentPropertyDefinition, SceneNode } from '../types'
-import { behaviourContract } from './kinds'
+import { behaviourContract, hasInvalidState } from './kinds'
import { behaviourProperties, emptyBehaviour, guessInteractionStates, textBinding } from './model'
import { isNumberRange, type Behaviour, type BehaviourSpec } from './schema'
@@ -90,12 +90,18 @@ function resolveStates(
): void {
const name = typeof states === 'string' ? states : states.property
const definition = findProperty(properties, name, ['VARIANT'], 'states')
- const guessed = guessInteractionStates(definition.id, definition.variantOptions ?? [])
+ const guessed = guessInteractionStates(
+ behaviour.kind,
+ definition.id,
+ definition.variantOptions ?? []
+ )
if (typeof states === 'string') {
behaviour.states = guessed
return
}
const { property: _property, ...values } = states
+ if (values.invalid !== undefined && !hasInvalidState(behaviour.kind))
+ throw new Error(`A ${behaviour.kind} has no invalid state`)
behaviour.states = { ...guessed, ...stripUndefined(values) }
}
diff --git a/packages/scene-graph/tests/behaviours/model.test.ts b/packages/scene-graph/tests/behaviours/model.test.ts
index df4014f36..166e97427 100644
--- a/packages/scene-graph/tests/behaviours/model.test.ts
+++ b/packages/scene-graph/tests/behaviours/model.test.ts
@@ -5,6 +5,7 @@ import {
behaviourOwner,
emptyBehaviour,
guessInteractionStates,
+ interactionStatesOf,
missingBindings,
readBehaviour,
withBehaviour
@@ -83,6 +84,19 @@ describe('behaviour model', () => {
}
})
+ test('a stored invalid state reads only on a kind that can be invalid', () => {
+ const { graph, set } = switchSet()
+ const states = { propertyId: 'state', rest: 'Off', invalid: 'On' }
+ graph.updateNode(set.id, {
+ pluginData: withBehaviour(set, { ...emptyBehaviour('button'), states })
+ })
+ expect(readBehaviour(set)?.states).toEqual({ propertyId: 'state', rest: 'Off' })
+ graph.updateNode(set.id, {
+ pluginData: withBehaviour(set, { ...emptyBehaviour('switch'), states })
+ })
+ expect(readBehaviour(set)?.states).toEqual(states)
+ })
+
test('unreadable plugin data reads as no behaviour', () => {
const { graph, set } = switchSet()
graph.updateNode(set.id, {
@@ -93,7 +107,14 @@ describe('behaviour model', () => {
test('interaction states are guessed from variant value names', () => {
expect(
- guessInteractionStates('interaction', ['Idle', 'Hovered', 'Active', 'Focus visible', 'Big'])
+ guessInteractionStates('button', 'interaction', [
+ 'Idle',
+ 'Hovered',
+ 'Active',
+ 'Focus visible',
+ 'Error',
+ 'Big'
+ ])
).toEqual({
propertyId: 'interaction',
rest: 'Idle',
@@ -102,4 +123,21 @@ describe('behaviour model', () => {
focus: 'Focus visible'
})
})
+
+ // The shadcn/ui kit draws Checkbox and RadioGroup invalid as `Invalid`, and Radio as `Error`,
+ // beside Disabled on one property; a button has no invalid state, so its Error is left alone.
+ test('only a form control is guessed invalid', () => {
+ const values = ['Default', 'Focus', 'Disabled', 'Invalid']
+ expect(guessInteractionStates('checkbox', 'state', values)).toEqual({
+ propertyId: 'state',
+ rest: 'Default',
+ focus: 'Focus',
+ disabled: 'Disabled',
+ invalid: 'Invalid'
+ })
+ expect(guessInteractionStates('radio', 'state', ['Default', 'Error']).invalid).toBe('Error')
+ expect(guessInteractionStates('tabs', 'state', values).invalid).toBeUndefined()
+ expect(interactionStatesOf('textField')).toContain('invalid')
+ expect(interactionStatesOf('toggle')).not.toContain('invalid')
+ })
})
diff --git a/packages/scene-graph/tests/behaviours/spec.test.ts b/packages/scene-graph/tests/behaviours/spec.test.ts
index df881db15..6c1ed7f7d 100644
--- a/packages/scene-graph/tests/behaviours/spec.test.ts
+++ b/packages/scene-graph/tests/behaviours/spec.test.ts
@@ -95,5 +95,11 @@ describe('behaviour specs', () => {
expect(() =>
behaviourFromSpec(graph, set, { kind: 'slider', parts: { track: 'Thumb', thumb: 'Thumb' } })
).toThrow('"Thumb" is already the track; a slot draws one part')
+ expect(() =>
+ behaviourFromSpec(graph, set, {
+ kind: 'button',
+ states: { property: 'Interaction', invalid: 'Disabled' }
+ })
+ ).toThrow('A button has no invalid state')
})
})
diff --git a/packages/vue/src/canvas/islands/render.ts b/packages/vue/src/canvas/islands/render.ts
index c54dfdb99..47cbf7202 100644
--- a/packages/vue/src/canvas/islands/render.ts
+++ b/packages/vue/src/canvas/islands/render.ts
@@ -34,6 +34,13 @@ export interface ElementOverride {
children?: () => (VNode | string)[]
}
+/**
+ * A text's link opens in a new tab, as in Figma's prototype view, so following it never takes
+ * the editor away from the document.
+ */
+const linkProps = (tag: string): Record<string, string> =>
+ tag === 'a' ? { target: '_blank', rel: 'noopener noreferrer' } : {}
+
/** The image a layer's shader fill shows: its first fill's, as the projection reads it. */
function shaderImage(element: DesignElement): string | undefined {
const node = element.sourceSceneNode
@@ -70,9 +77,10 @@ export function renderElement(
...content()
]
const { 'data-open-pencil-node-id': _id, ...attrs } = element.attrs
+ const tag = override.tag ?? element.tagName
return h(
- override.tag ?? element.tagName,
- { ...attrs, key: path, 'data-layer': path, style, ...override.props },
+ tag,
+ { ...attrs, ...linkProps(tag), key: path, 'data-layer': path, style, ...override.props },
children()
)
}
diff --git a/packages/vue/src/canvas/islands/state.ts b/packages/vue/src/canvas/islands/state.ts
index a4032f34b..731a57813 100644
--- a/packages/vue/src/canvas/islands/state.ts
+++ b/packages/vue/src/canvas/islands/state.ts
@@ -75,8 +75,22 @@ export function isDisabled(control: ControlModel, state: ControlState | undefine
return !!state?.booleans.disabled || !!control.states?.designedDisabled
}
+/** Whether a control is invalid: its invalid value is on, or it is drawn invalid. */
+function isInvalid(control: ControlModel, state: ControlState): boolean {
+ return !!state.booleans.invalid || !!control.states?.designedInvalid
+}
+
+/**
+ * The state a control's states property shows: disabled, then invalid, which the pointer and
+ * focus leave as it is, then the interactions. A disabled control the property draws no
+ * disabled value for shows its invalid value, if any, or its rest value, never an interaction.
+ */
function interactionState(control: ControlModel, state: ControlState): InteractionState {
- if (isDisabled(control, state)) return 'disabled'
+ const values = control.states?.values
+ const disabled = isDisabled(control, state)
+ if (disabled && values?.disabled !== undefined) return 'disabled'
+ if (isInvalid(control, state) && values?.invalid !== undefined) return 'invalid'
+ if (disabled) return 'rest'
if (state.pressed) return 'pressed'
if (state.hovered) return 'hover'
if (state.focused) return 'focus'
diff --git a/packages/vue/src/controls/behaviour/types.ts b/packages/vue/src/controls/behaviour/types.ts
index 8fc6a6e90..0b34e4b70 100644
--- a/packages/vue/src/controls/behaviour/types.ts
+++ b/packages/vue/src/controls/behaviour/types.ts
@@ -54,6 +54,8 @@ export interface BehaviourPartControl {
export interface BehaviourStatesControl {
/** The bound variant property, if any. */
propertyId: string | null
+ /** The states this kind of control shows, in order: only a form control can be invalid. */
+ available: InteractionState[]
values: Partial<Record<InteractionState, string>>
/** The component's variant properties. */
options: VariantDefinitionControl[]
diff --git a/packages/vue/src/controls/behaviour/use.ts b/packages/vue/src/controls/behaviour/use.ts
index 619b586b8..6a545ba80 100644
--- a/packages/vue/src/controls/behaviour/use.ts
+++ b/packages/vue/src/controls/behaviour/use.ts
@@ -8,6 +8,7 @@ import {
guessInteractionStates,
guessOnOff,
INTERACTION_STATES,
+ interactionStatesOf,
isNumberRange,
missingBindings,
partBinding,
@@ -103,6 +104,7 @@ export function useBehaviour() {
}),
states: {
propertyId: current.states?.propertyId ?? null,
+ available: interactionStatesOf(current.kind),
values: Object.fromEntries(
INTERACTION_STATES.flatMap((state) => {
const value = current.states?.[state]
@@ -196,7 +198,12 @@ export function useBehaviour() {
? behaviourProperties(editor.graph, target).find((item) => item.id === propertyId)
: undefined
if (!definition) delete current.states
- else current.states = guessInteractionStates(propertyId, definition.variantOptions ?? [])
+ else
+ current.states = guessInteractionStates(
+ current.kind,
+ propertyId,
+ definition.variantOptions ?? []
+ )
return current
}),
/** Choose the variant value of one interaction state; an empty value unsets it. */
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index dfecce449..db328720d 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -602,6 +602,7 @@
"behaviourMoreOptions": "Weitere Optionen",
"behaviourValue": "Wert",
"behaviourDisabled": "Deaktiviert",
+ "behaviourInvalid": "Ungültig",
"behaviourOnValue": "An",
"behaviourOffValue": "Aus",
"behaviourValueField": "{value}: {side}",
@@ -632,6 +633,7 @@
"behaviourStatePressed": "Gedrückt",
"behaviourStateFocus": "Fokus",
"behaviourStateDisabled": "Deaktiviert",
+ "behaviourStateInvalid": "Ungültig",
"behaviourStateUnset": "Keine",
"behaviourStateField": "Zustand {state}",
"searchComponentProperties": "Eigenschaften suchen",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 0424ef342..22afb52be 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -602,6 +602,7 @@
"behaviourMoreOptions": "Más opciones",
"behaviourValue": "Valor",
"behaviourDisabled": "Desactivado",
+ "behaviourInvalid": "No válido",
"behaviourOnValue": "Encendido",
"behaviourOffValue": "Apagado",
"behaviourValueField": "{value}: {side}",
@@ -632,6 +633,7 @@
"behaviourStatePressed": "Pulsado",
"behaviourStateFocus": "Foco",
"behaviourStateDisabled": "Desactivado",
+ "behaviourStateInvalid": "No válido",
"behaviourStateUnset": "Ninguno",
"behaviourStateField": "Estado {state}",
"searchComponentProperties": "Buscar propiedades",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index fa1e7c874..cba642941 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -602,6 +602,7 @@
"behaviourMoreOptions": "Plus d’options",
"behaviourValue": "Valeur",
"behaviourDisabled": "Désactivé",
+ "behaviourInvalid": "Non valide",
"behaviourOnValue": "Activé",
"behaviourOffValue": "Désactivé",
"behaviourValueField": "{value}: {side}",
@@ -632,6 +633,7 @@
"behaviourStatePressed": "Appuyé",
"behaviourStateFocus": "Focus",
"behaviourStateDisabled": "Désactivé",
+ "behaviourStateInvalid": "Non valide",
"behaviourStateUnset": "Aucun",
"behaviourStateField": "État {state}",
"searchComponentProperties": "Rechercher des propriétés",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 6fd5ae9e8..cf99e064e 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -602,6 +602,7 @@
"behaviourMoreOptions": "Altre opzioni",
"behaviourValue": "Valore",
"behaviourDisabled": "Disattivato",
+ "behaviourInvalid": "Non valido",
"behaviourOnValue": "Acceso",
"behaviourOffValue": "Spento",
"behaviourValueField": "{value}: {side}",
@@ -632,6 +633,7 @@
"behaviourStatePressed": "Premuto",
"behaviourStateFocus": "Focus",
"behaviourStateDisabled": "Disattivato",
+ "behaviourStateInvalid": "Non valido",
"behaviourStateUnset": "Nessuno",
"behaviourStateField": "Stato {state}",
"searchComponentProperties": "Cerca proprietà",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index c437766c9..0f2e4fb55 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -595,6 +595,7 @@
"behaviourMoreOptions": "その他のオプション",
"behaviourValue": "値",
"behaviourDisabled": "無効",
+ "behaviourInvalid": "エラー",
"behaviourOnValue": "オン",
"behaviourOffValue": "オフ",
"behaviourValueField": "{value}:{side}",
@@ -625,6 +626,7 @@
"behaviourStatePressed": "押下",
"behaviourStateFocus": "フォーカス",
"behaviourStateDisabled": "無効",
+ "behaviourStateInvalid": "エラー",
"behaviourStateUnset": "なし",
"behaviourStateField": "{state} 状態",
"searchComponentProperties": "プロパティを検索",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index f343e1aaf..9633577e9 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -609,6 +609,7 @@
"behaviourMoreOptions": "Więcej opcji",
"behaviourValue": "Wartość",
"behaviourDisabled": "Wyłączony",
+ "behaviourInvalid": "Nieprawidłowy",
"behaviourOnValue": "Wł.",
"behaviourOffValue": "Wył.",
"behaviourValueField": "{value}: {side}",
@@ -639,6 +640,7 @@
"behaviourStatePressed": "Wciśnięty",
"behaviourStateFocus": "Fokus",
"behaviourStateDisabled": "Wyłączony",
+ "behaviourStateInvalid": "Nieprawidłowy",
"behaviourStateUnset": "Brak",
"behaviourStateField": "Stan {state}",
"searchComponentProperties": "Szukaj właściwości",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 26a2f1303..be3069604 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -609,6 +609,7 @@
"behaviourMoreOptions": "Ещё параметры",
"behaviourValue": "Значение",
"behaviourDisabled": "Отключено",
+ "behaviourInvalid": "Ошибка",
"behaviourOnValue": "Вкл.",
"behaviourOffValue": "Выкл.",
"behaviourValueField": "{value}: {side}",
@@ -639,6 +640,7 @@
"behaviourStatePressed": "Нажата",
"behaviourStateFocus": "Фокус",
"behaviourStateDisabled": "Отключена",
+ "behaviourStateInvalid": "Ошибка",
"behaviourStateUnset": "Нет",
"behaviourStateField": "Состояние «{state}»",
"searchComponentProperties": "Поиск свойств",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 707d0712a..52ea09d9d 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -595,6 +595,7 @@
"behaviourMoreOptions": "更多选项",
"behaviourValue": "值",
"behaviourDisabled": "已禁用",
+ "behaviourInvalid": "无效",
"behaviourOnValue": "开",
"behaviourOffValue": "关",
"behaviourValueField": "{value}:{side}",
@@ -625,6 +626,7 @@
"behaviourStatePressed": "按下",
"behaviourStateFocus": "聚焦",
"behaviourStateDisabled": "禁用",
+ "behaviourStateInvalid": "无效",
"behaviourStateUnset": "无",
"behaviourStateField": "{state}状态",
"searchComponentProperties": "搜索属性",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index a05ec128c..270ef78fa 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -292,6 +292,7 @@ export const panelMessageDefaults = {
behaviourMoreOptions: 'More options',
behaviourValue: 'Value',
behaviourDisabled: 'Disabled',
+ behaviourInvalid: 'Invalid',
behaviourOnValue: 'On',
behaviourOffValue: 'Off',
/** A value's on or off variant field, such as "Checked: On". */
@@ -323,6 +324,7 @@ export const panelMessageDefaults = {
behaviourStatePressed: 'Pressed',
behaviourStateFocus: 'Focus',
behaviourStateDisabled: 'Disabled',
+ behaviourStateInvalid: 'Invalid',
behaviourStateUnset: 'None',
behaviourStateField: params('{state} state'),
searchComponentProperties: 'Search properties',
diff --git a/packages/vue/tests/canvas/islands/render.test.ts b/packages/vue/tests/canvas/islands/render.test.ts
new file mode 100644
index 000000000..836e507cc
--- /dev/null
+++ b/packages/vue/tests/canvas/islands/render.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { DesignElement } from '@open-pencil/dom-css/export'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { renderElement, type IslandRenderContext } from '#vue/canvas/islands/render'
+import { createIslandState } from '#vue/canvas/islands/state'
+
+const context: IslandRenderContext = {
+ graph: new SceneGraph(),
+ rootId: '',
+ controls: new Map(),
+ roles: new Map(),
+ state: createIslandState(new Map())
+}
+
+const element = (tagName: string, attrs: Record<string, string>): DesignElement => ({
+ type: 'element',
+ tagName,
+ attrs,
+ children: [{ type: 'text', text: 'View in shadcn' }]
+})
+
+describe('preview island elements', () => {
+ // The shadcn/ui kit links its "View in Shadcn" labels to the docs; following one in preview
+ // must not take the editor away from the document.
+ test("a text's link opens in a new tab", () => {
+ const link = renderElement(context, element('a', { href: 'https://ui.shadcn.com' }), 'Link')
+ expect(link.props).toMatchObject({
+ href: 'https://ui.shadcn.com',
+ target: '_blank',
+ rel: 'noopener noreferrer'
+ })
+ })
+
+ test('other elements get no link attributes', () => {
+ const frame = renderElement(context, element('div', {}), 'Frame')
+ expect(frame.props?.target).toBeUndefined()
+ })
+})
diff --git a/packages/vue/tests/canvas/islands/state.test.ts b/packages/vue/tests/canvas/islands/state.test.ts
new file mode 100644
index 000000000..13d34741b
--- /dev/null
+++ b/packages/vue/tests/canvas/islands/state.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, test } from 'bun:test'
+
+import { behaviourControls } from '@open-pencil/dom-css/export'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { emptyBehaviour, withBehaviour } from '@open-pencil/scene-graph/behaviours'
+
+import { createIslandState, instanceStates } from '#vue/canvas/islands/state'
+
+const STATES = ['Default', 'Focus', 'Disabled', 'Invalid']
+
+/**
+ * A checkbox as the shadcn/ui kit draws one, and a form holding one drawn `shown`. Without
+ * `drawsDisabled`, its State property has no Disabled value, as when a set draws disabled on a
+ * property of its own.
+ */
+function form(shown: string, { drawsDisabled = true } = {}) {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const set = graph.createNode('COMPONENT_SET', pageId, {
+ name: 'Checkbox',
+ componentPropertyDefinitions: [
+ { id: 'state', name: 'State', type: 'VARIANT', defaultValue: 'Default', variantOptions: STATES }
+ ]
+ })
+ const variants = STATES.map((state) =>
+ graph.createNode('COMPONENT', set.id, {
+ name: `State=${state}`,
+ componentPropertyValues: { State: state }
+ })
+ )
+ graph.updateNode(set.id, {
+ pluginData: withBehaviour(set, {
+ ...emptyBehaviour('checkbox'),
+ states: {
+ propertyId: 'state',
+ rest: 'Default',
+ focus: 'Focus',
+ disabled: drawsDisabled ? 'Disabled' : undefined,
+ invalid: 'Invalid'
+ }
+ })
+ })
+ const card = graph.createNode('FRAME', pageId, { name: 'Form' })
+ const variant = variants[STATES.indexOf(shown)]
+ if (!variant) throw new Error(`No ${shown} variant`)
+ graph.createInstance(variant.id, card.id)
+ const controls = behaviourControls(graph, card.id)
+ const state = createIslandState(controls)
+ const [control] = controls.values()
+ if (!control) throw new Error('No control')
+ const { path } = control
+ const current = state.get(path)
+ if (!current) throw new Error('No state')
+ const shows = () => instanceStates(controls, state).get(path)?.prefer?.State
+ return { current, shows }
+}
+
+describe('preview island states', () => {
+ test('a control drawn invalid stays invalid in focus, and shows disabled over it', () => {
+ const { current, shows } = form('Invalid')
+ expect(shows()).toBe('Invalid')
+ current.focused = true
+ expect(shows()).toBe('Invalid')
+ current.booleans.disabled = true
+ expect(shows()).toBe('Disabled')
+ })
+
+ test('a valid control still shows focus', () => {
+ const { current, shows } = form('Default')
+ current.focused = true
+ expect(shows()).toBe('Focus')
+ })
+
+ test('disabled elsewhere, the states property still shows invalid, and never focus', () => {
+ const invalid = form('Invalid', { drawsDisabled: false })
+ invalid.current.booleans.disabled = true
+ invalid.current.focused = true
+ expect(invalid.shows()).toBe('Invalid')
+ const valid = form('Default', { drawsDisabled: false })
+ valid.current.booleans.disabled = true
+ valid.current.focused = true
+ expect(valid.shows()).toBe('Default')
+ })
+})
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index e38b6e53d..03bc30c8e 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -57,7 +57,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`, `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`.
+- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, for form controls (fields, switches, checkboxes, radios) `invalid`, 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, disabled, and, for form controls, invalid (a value named Invalid or Error); 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} />`.
- A tab trigger with a selected look of its own is a `Tabs.Tab` component, written on its own with `modelValue` naming its selected variant property; `Tabs.Root` then lists its tabs as `<Tabs.Tab of={tabId} />`, which go in the list as plain `Tabs.Trigger`s do, and each shows its selected variant while its tab is chosen.
@@ -136,4 +136,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a
**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.
-**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `markdown`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `overrides`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `markdown`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `overrides`, `mode`, `modelValue`, `open`, `disabled`, `invalid`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
diff --git a/src/app/shell/external-links.ts b/src/app/shell/external-links.ts
index d1de81d20..b24a213f2 100644
--- a/src/app/shell/external-links.ts
+++ b/src/app/shell/external-links.ts
@@ -19,9 +19,12 @@ export function useExternalLinks() {
document,
'click',
(event: MouseEvent) => {
- if (!(event.target instanceof Element)) return
- const anchor = event.target.closest('a[href]')
- if (!(anchor instanceof HTMLAnchorElement) || anchor.target !== '_blank') return
+ // The event's path, not its target, reaches a link inside a shadow root, such as one in a
+ // preview island, which the document sees only as the island's host.
+ const anchor = event
+ .composedPath()
+ .find((item): item is HTMLAnchorElement => item instanceof HTMLAnchorElement && !!item.href)
+ if (anchor?.target !== '_blank') return
// Added while the click is captured, it runs after the link's own handlers in this click.
anchor.addEventListener(
'click',
diff --git a/src/components/properties/component-properties/behaviour/BehaviourStates.vue b/src/components/properties/component-properties/behaviour/BehaviourStates.vue
index 794031ec3..416c0b3d8 100644
--- a/src/components/properties/component-properties/behaviour/BehaviourStates.vue
+++ b/src/components/properties/component-properties/behaviour/BehaviourStates.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue'
-import { INTERACTION_STATES, type InteractionState } from '@open-pencil/scene-graph/behaviours'
+import type { InteractionState } from '@open-pencil/scene-graph/behaviours'
import type { BehaviourStatesControl } from '@open-pencil/vue/controls/behaviour'
import { useI18n } from '@open-pencil/vue/i18n'
@@ -75,11 +75,7 @@ function map(state: InteractionState, value: string | number) {
@update:model-value="emit('bind', $event)"
/>
<div v-if="states.propertyId" class="grid grid-cols-2 gap-x-1 gap-y-1.5">
- <PanelFieldGroup
- v-for="state in INTERACTION_STATES"
- :key="state"
- :label="labels.state(state)"
- >
+ <PanelFieldGroup v-for="state in states.available" :key="state" :label="labels.state(state)">
<AppSelect
:label="panels.behaviourStateField({ state: labels.state(state) })"
:model-value="states.values[state] ?? UNSET"
diff --git a/src/components/properties/component-properties/behaviour/examples/States.vue b/src/components/properties/component-properties/behaviour/examples/States.vue
index 34a403fc3..af7aa386c 100644
--- a/src/components/properties/component-properties/behaviour/examples/States.vue
+++ b/src/components/properties/component-properties/behaviour/examples/States.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { ref } from 'vue'
+import { interactionStatesOf } from '@open-pencil/scene-graph/behaviours'
import type { BehaviourControl } from '@open-pencil/vue/controls/behaviour'
import BehaviourSection from '../BehaviourSection.vue'
@@ -39,6 +40,7 @@ const switchComplete = ref<BehaviourControl>({
parts: [{ id: 'thumb', required: false, propertyId: 'thumb', options: [thumbSlot] }],
states: {
propertyId: 'interaction',
+ available: interactionStatesOf('switch'),
values: { rest: 'Default', hover: 'Hover', pressed: 'Pressed', disabled: 'Disabled' },
options: [stateProperty, sizeProperty, interactionProperty]
}
@@ -61,7 +63,12 @@ const sliderIncomplete = ref<BehaviourControl>({
{ id: 'range', required: false, propertyId: null, options: [trackSlot] },
{ id: 'thumb', required: true, propertyId: null, options: [] }
],
- states: { propertyId: null, values: {}, options: [interactionProperty] }
+ states: {
+ propertyId: null,
+ available: interactionStatesOf('slider'),
+ values: {},
+ options: [interactionProperty]
+ }
})
/** A plain rectangle made a component and given a Textarea behaviour: nothing to bind yet. */
const textareaBare = ref<BehaviourControl>({
@@ -85,7 +92,7 @@ const textareaBare = ref<BehaviourControl>({
}
],
parts: [],
- states: { propertyId: null, values: {}, options: [] }
+ states: { propertyId: null, available: interactionStatesOf('textarea'), values: {}, options: [] }
})
const log = ref<string[]>([])
const record = (entry: string) => {
diff --git a/src/components/properties/component-properties/behaviour/labels.ts b/src/components/properties/component-properties/behaviour/labels.ts
index 4211cfa6a..3f2fbd375 100644
--- a/src/components/properties/component-properties/behaviour/labels.ts
+++ b/src/components/properties/component-properties/behaviour/labels.ts
@@ -40,7 +40,8 @@ export function useBehaviourLabels() {
open: p.behaviourOpen,
filled: p.behaviourFilled,
text: p.behaviourText,
- disabled: p.behaviourDisabled
+ disabled: p.behaviourDisabled,
+ invalid: p.behaviourInvalid
}
const parts: Record<string, string> = {
track: p.behaviourTrack,
@@ -60,7 +61,8 @@ export function useBehaviourLabels() {
hover: p.behaviourStateHover,
pressed: p.behaviourStatePressed,
focus: p.behaviourStateFocus,
- disabled: p.behaviourStateDisabled
+ disabled: p.behaviourStateDisabled,
+ invalid: p.behaviourStateInvalid
}
/** What a control's main value is called, which code calls its `value`. */
const mainValue: Partial<Record<BehaviourKind, string>> = {
diff --git a/tests/e2e/components/behaviours.spec.ts b/tests/e2e/components/behaviours.spec.ts
index 6d83ceee2..e5ff4b897 100644
--- a/tests/e2e/components/behaviours.spec.ts
+++ b/tests/e2e/components/behaviours.spec.ts
@@ -465,6 +465,8 @@ test('a Button behaviour maps its states and shows them in preview', async () =>
await expect(section.getByRole('combobox', { name: 'Hover state' })).toHaveText(/Hover/)
await expect(section.getByRole('combobox', { name: 'Pressed state' })).toHaveText(/Pressed/)
await expect(section.getByRole('combobox', { name: 'Disabled state' })).toHaveText(/Disabled/)
+ // Only a form control has an invalid state.
+ await expect(section.getByRole('combobox', { name: 'Invalid state' })).toHaveCount(0)
await startPreview()
// Each state shows its variant's fill: the components are filled by index, as created above.