Skip to content

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

feat: give tab triggers their own selected and disabled states (#1710)

Danila Poyarkove23f60138c72
diff --git a/changes/1710/added.md b/changes/1710/added.md
new file mode 100644
index 000000000..c335d030a
--- /dev/null
+++ b/changes/1710/added.md
@@ -0,0 +1 @@
+- A Tab behaviour for tab triggers drawn as instances of a component, as in the shadcn/ui kit: in preview and generated Reka and Radix code, the chosen tab shows its selected variant and a tab drawn disabled cannot be chosen; design JSX writes such triggers as `Tabs.Tab` (#1710).
diff --git a/packages/core/tests/design-jsx/behaviours.test.ts b/packages/core/tests/design-jsx/behaviours.test.ts
index 14537a0ba..55867ee1c 100644
--- a/packages/core/tests/design-jsx/behaviours.test.ts
+++ b/packages/core/tests/design-jsx/behaviours.test.ts
@@ -222,6 +222,42 @@ describe('Reka UI elements in JSX export', () => {
expect(code).not.toContain('name="Panels"')
})
+ test('a Tabs.Tab component draws the triggers a tab list holds as its instances', async () => {
+ const graph = new SceneGraph()
+ const [tab] = await renderJSX(
+ graph,
+ `<Tabs.Tab name="Tab" modelValue="Selected">
+ <Component name="Selected=Off" w={60} h={24} />
+ <Component name="Selected=On" w={60} h={24} />
+ </Tabs.Tab>`
+ )
+ expect(readBehaviour(getNodeOrThrow(graph, tab.id))?.kind).toBe('tab')
+ const [tabs] = await renderJSX(
+ graph,
+ `<Tabs.Root name="Tabs" flex="col">
+ <Tabs.Tab of="${tab.id}" Selected="On" />
+ <Tabs.Tab of="${tab.id}" />
+ <Tabs.Content><Text>First</Text></Tabs.Content>
+ <Tabs.Content><Text>Second</Text></Tabs.Content>
+ </Tabs.Root>`
+ )
+ const root = getNodeOrThrow(graph, tabs.id)
+ const [list] = graph.getChildren(root.id)
+ expect(list?.name).toBe('List')
+ expect(graph.getChildren(list?.id ?? '').map((trigger) => trigger.type)).toEqual([
+ 'INSTANCE',
+ 'INSTANCE'
+ ])
+ const behaviour = readBehaviour(root)
+ expect(behaviour && missingBindings(graph, root, behaviour)).toEqual([])
+
+ const exported = sceneNodeToJSX(tabs.id, graph)
+ expect(exported).toContain('<Tabs.Tab of="Tab" Selected="On" />')
+ expect(exported).toContain('<Tabs.Tab of="Tab" Selected="Off" />')
+ const [copy] = await renderJSX(graph, exported)
+ expect(sceneNodeToJSX(copy.id, graph)).toBe(exported)
+ })
+
test('a group item whose changes JSX cannot write is written as the layer it draws', async () => {
const graph = new SceneGraph()
await renderJSX(
diff --git a/packages/core/tests/openpencil-api/behaviours.test.ts b/packages/core/tests/openpencil-api/behaviours.test.ts
index 412af96da..a88ebd868 100644
--- a/packages/core/tests/openpencil-api/behaviours.test.ts
+++ b/packages/core/tests/openpencil-api/behaviours.test.ts
@@ -55,7 +55,7 @@ describe('openpencil scripting API', () => {
openpencil.getBehaviour(set).remove()
return [kind, openpencil.getBehaviour(set), openpencil.behaviourKinds.length]
`)
- expect(result).toEqual(['switch', null, 15])
+ expect(result).toEqual(['switch', null, 16])
expect(graph.getNode(set.id)?.componentPropertyDefinitions.map((item) => item.name)).toContain(
'State'
)
diff --git a/packages/design-jsx/src/behaviours/export.ts b/packages/design-jsx/src/behaviours/export.ts
index 795f9fb74..4a49be3b9 100644
--- a/packages/design-jsx/src/behaviours/export.ts
+++ b/packages/design-jsx/src/behaviours/export.ts
@@ -2,6 +2,7 @@ import { findKey } from 'es-toolkit'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import {
+ behaviourOwner,
behaviourToSpec,
readBehaviour,
textBinding,
@@ -27,6 +28,7 @@ const ROOTS: Record<BehaviourKind, [namespace: string, element: string]> = {
slider: ['Slider', 'Root'],
progress: ['Progress', 'Root'],
tabs: ['Tabs', 'Root'],
+ tab: ['Tabs', 'Tab'],
collapsible: ['Collapsible', 'Root'],
accordion: ['Accordion', 'Root'],
numberField: ['NumberField', 'Root'],
@@ -51,6 +53,15 @@ function elementFor(namespace: string, match: (role: ReturnType<typeof rekaRole>
return found ? `${namespace}.${found}` : undefined
}
+/** The element in a namespace whose root is the kind an item's component behaves as, if any. */
+function itemElement(graph: SceneGraph, namespace: string, component: SceneNode) {
+ const owner = behaviourOwner(graph, component)
+ const kind = owner && readBehaviour(owner)?.kind
+ return kind
+ ? elementFor(namespace, (role) => role?.role === 'root' && role.kind === kind)
+ : undefined
+}
+
function rootProps(graph: SceneGraph, owner: SceneNode): JSXProp[] {
const behaviour = readBehaviour(owner)
if (!behaviour) return []
@@ -95,12 +106,14 @@ function exportPart(
for (const child of graph.getChildren(layer.id)) {
if (repeated) result.tags.set(child.id, repeated)
const item = child.type === 'INSTANCE' ? instanceMainComponent(graph, child) : undefined
- if (partId !== 'items' || !item) continue
- // A group's items are written as the group's Item, naming their component and variant, and
+ const tag = item && itemElement(graph, namespace, item)
+ if (!item || !tag) continue
+ // A group's items and a tab list's tabs are written as the namespace's element of their
+ // component's kind, `RadioGroup.Item` or `Tabs.Tab`, naming their component and variant, and
// what the item changes in it; an item whose changes cannot be written is written as a layer.
const props = itemProps(graph, child, item, componentRef)
if (!props) continue
- result.tags.set(child.id, `${namespace}.Item`)
+ result.tags.set(child.id, tag)
result.props.set(child.id, props)
}
}
diff --git a/packages/design-jsx/src/behaviours/index.ts b/packages/design-jsx/src/behaviours/index.ts
index 39cf65dc7..d221d6d27 100644
--- a/packages/design-jsx/src/behaviours/index.ts
+++ b/packages/design-jsx/src/behaviours/index.ts
@@ -49,10 +49,13 @@ const REKA_PARTS = {
Thumb: part('thumb')
},
Progress: { Root: root('progress'), Track: part('track'), Indicator: part('indicator') },
+ // `Trigger` is a plain trigger; `Tab` is a trigger with states of its own, written alone as
+ // its component and in a list as an instance of it, as a group's `Item` is.
Tabs: {
Root: root('tabs'),
List: part('list'),
Trigger: repeat('list'),
+ Tab: root('tab'),
Content: repeat('panels')
},
Collapsible: { Root: root('collapsible'), Trigger: part('trigger'), Content: part('content') },
@@ -109,8 +112,10 @@ const GROUPS = new Set<BehaviourKind>(['radioGroup', 'toggleGroup', 'accordion']
function containerOf(child: TreeNode, kind: BehaviourKind): string | undefined {
const role = rekaRole(child.type)
if (role?.role === 'repeat') return role.container
- if (GROUPS.has(kind) && role?.role === 'root' && namesComponent(child.props)) return 'items'
- return undefined
+ if (role?.role !== 'root' || !namesComponent(child.props)) return undefined
+ if (GROUPS.has(kind)) return 'items'
+ // A tab written directly under its Tabs.Root goes in the list, as a plain trigger does.
+ return kind === 'tabs' ? 'list' : undefined
}
/**
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index bf05c27f7..23f5880f8 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -58,6 +58,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.
- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.
- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.
+- 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.
```tsx
<Switch.Root name="Switch" modelValue="State" states="Interaction">
diff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.md
index 06df7d5fd..3eecc0ef3 100644
--- a/packages/docs/development/behaviours-and-preview.md
+++ b/packages/docs/development/behaviours-and-preview.md
@@ -36,7 +36,7 @@ Preview is a per-pane canvas view (`EditorViewState.canvasView`, `{ id: 'play',
2. **Shadow DOM.** Each island renders into its own shadow root: app CSS does not reach in, island CSS does not leak out, fonts already loaded by the app apply, and the island moves with the canvas in the same frame. Wheel gestures over an island are passed to the canvas.
3. **State to design.** An island keeps each control's state (values, choice, number, typed text, hover, pressed, focus). Core's `resolvePlayState` copies the island's layers into a private graph and shows each instance in its state: the matching variant, boolean properties, and layers a control reveals, such as tab panels. The copy comes from the page extractor history and export use (`extractPageContext`), with every variant of each instance's set so it can switch, and the document's variables and images shared rather than copied, since a state never changes them. The document is never changed.
4. **Design to DOM.** The private graph is projected to DOM through `@open-pencil/dom-css`, the same projection HTML export uses, so island fidelity and export fidelity improve together.
-5. **DOM to Reka.** Each projected layer has a role: a control's root, a part, a group's item, a tab trigger or panel, or a text input. `behaviourControls` and `controlRoles` in `@open-pencil/dom-css` (`packages/dom-css/src/behaviours/`) assign them, so code export reads the same roles. Roles wrap the layer in its Reka UI primitive with `asChild`, so Reka renders through the designed element. Typing, focus, keyboard navigation, and accessibility are the browser's and Reka's.
+5. **DOM to Reka.** Each projected layer has a role: a control's root, a part, a group's item, a tab trigger or panel, or a text input. A tab list's triggers may be instances of a component with the `tab` behaviour: such a trigger keeps the trigger role and carries its own control, which the tabs turn on and off as a group turns its items, so its selected variant follows the choice, and which disables the trigger while it is drawn disabled. `behaviourControls` and `controlRoles` in `@open-pencil/dom-css` (`packages/dom-css/src/behaviours/`) assign them, so code export reads the same roles. Roles wrap the layer in its Reka UI primitive with `asChild`, so Reka renders through the designed element. Typing, focus, keyboard navigation, and accessibility are the browser's and Reka's.
Controls and DOM keys use layer paths (names below the island root), not node ids: a variant switch rebuilds an instance's layers with new ids, and a stable path keeps the DOM in place, including a focused input.
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index 1e54beac4..e38b6e53d 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -60,6 +60,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.
- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.
- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.
+- 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.
```tsx
<Switch.Root name="Switch" modelValue="State" states="Interaction">
@@ -131,7 +132,7 @@ return <Frame name="Dark note" mode={dark} w={280} h="hug" flex="col" gap={8} p=
Generated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.
-**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Tab`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.
diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.md
index 8228e9686..57bc6244d 100644
--- a/packages/docs/user-guide/components.md
+++ b/packages/docs/user-guide/components.md
@@ -45,12 +45,12 @@ A slot is a frame of a main component whose content each instance can change. Se
## Behaviours and Preview
-A behaviour makes a main component or component set work like a real control, after [Reka UI](https://reka-ui.com)'s primitives: Button, Text field, Textarea, Number field, Toggle, Switch, Checkbox, Radio, Radio group, Toggle group, Slider, Progress, Tabs, Collapsible, or Accordion. Select the component and use **+** in the **Behaviour** section to choose one.
+A behaviour makes a main component or component set work like a real control, after [Reka UI](https://reka-ui.com)'s primitives: Button, Text field, Textarea, Number field, Toggle, Switch, Checkbox, Radio, Radio group, Toggle group, Slider, Progress, Tabs, Tab, Collapsible, or Accordion. Select the component and use **+** in the **Behaviour** section to choose one.
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.
-- **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.
+- **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.
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.
diff --git a/packages/dom-css/src/behaviours/roles.ts b/packages/dom-css/src/behaviours/roles.ts
index 5160a6b44..a6f791072 100644
--- a/packages/dom-css/src/behaviours/roles.ts
+++ b/packages/dom-css/src/behaviours/roles.ts
@@ -5,7 +5,8 @@ export type ControlRole =
| { type: 'root'; control: ControlModel }
| { type: 'part'; control: ControlModel; part: string }
| { type: 'item'; group: ControlModel; control: ControlModel; index: number }
- | { type: 'trigger'; control: ControlModel; index: number }
+ /** A tab trigger; `tab` is its own control when it is an instance with the tab behaviour. */
+ | { type: 'trigger'; control: ControlModel; index: number; tab?: ControlModel }
| { type: 'panel'; control: ControlModel; index: number }
| { type: 'text'; control: ControlModel; valueId: string }
@@ -28,8 +29,16 @@ export function controlRoles(
roles.set(path, { type: 'trigger', control, index })
for (const [index, path] of control.panels.entries())
roles.set(path, { type: 'panel', control, index })
- for (const [index, item] of control.items.entries())
- roles.set(item.path, { type: 'item', group: control, control: item, index })
+ for (const [index, item] of control.items.entries()) {
+ // A tab stays its list's trigger, at its place among the triggers, with its own states.
+ const trigger = control.kind === 'tabs' ? control.triggers.indexOf(item.path) : -1
+ roles.set(
+ item.path,
+ trigger === -1
+ ? { type: 'item', group: control, control: item, index }
+ : { type: 'trigger', control, index: trigger, tab: item }
+ )
+ }
}
return roles
}
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index af026b936..dc0747f44 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -1,4 +1,5 @@
import { behaviourArgs, type BehaviourArgs } 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'
import { ownerVariants, restLayerOf, stateStyles } from '#dom-css/behaviours/states/model'
@@ -124,6 +125,8 @@ export interface ComponentElement {
layerId?: string
/** The value a repeated part stands for, such as a tab trigger's tab. */
value?: string
+ /** A tab trigger that cannot be chosen. */
+ disabled?: boolean
/** The shader the layer fills with, which plays behind its content. */
shader?: ShaderLayer
children: ComponentNode[]
@@ -406,6 +409,24 @@ function borderBoxes(root: StateElement): void {
}
}
+/**
+ * A trigger that is a tab drawn disabled, by its disabled value or its disabled state, is a
+ * disabled trigger, which cannot be chosen, as preview runs it.
+ */
+function disableDrawnTabs(
+ graph: SceneGraph,
+ styles: StateStyles,
+ repeated: ReadonlyMap<StateElement, RepeatedPart>
+): void {
+ for (const [element, item] of repeated) {
+ if (item.part !== 'trigger') continue
+ const layerId = restLayerOf(graph, styles, element)
+ const tab = layerId ? behaviourControls(graph, layerId).get('') : undefined
+ if (tab?.kind !== 'tab') continue
+ if (booleanOf(tab, 'disabled')?.designed || tab.states?.designedDisabled) item.disabled = true
+ }
+}
+
/**
* Each layer's part, and tabs' triggers and panels, with the styles the generated parts need:
* native buttons cleared, the chosen tab's look, and moving parts free of their drawn place.
@@ -464,6 +485,7 @@ export function componentModel(
const name = options.name ?? identifierName(set.name, 'Component')
const { parts, tabs, repeated } = drawnParts(graph, set, behaviour, kind, styles.root)
+ disableDrawnTabs(graph, styles, repeated)
// A group's items first, so its item component is used for them rather than a standalone one.
const variantIds = [styles.restId, ...ownerVariants(graph, set).map((variant) => variant.id)]
diff --git a/packages/dom-css/src/export/components/react/index.ts b/packages/dom-css/src/export/components/react/index.ts
index 7f8111f68..ac2eb67cd 100644
--- a/packages/dom-css/src/export/components/react/index.ts
+++ b/packages/dom-css/src/export/components/react/index.ts
@@ -282,6 +282,7 @@ function designElement(node: ComponentElement, uses: MarkupUses, depth: number):
// takes them.
...(root && !INPUT_PROPS[kind] ? [jsx.spread(es.identifier('props'))] : []),
...(node.value === undefined ? [] : [jsx.attribute('value', jsx.stringValue(node.value))]),
+ ...(node.disabled ? [jsx.attribute('disabled', null)] : []),
...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
jsx.attribute(name, jsx.stringValue(value))
),
diff --git a/packages/dom-css/src/export/components/repeats.ts b/packages/dom-css/src/export/components/repeats.ts
index 5d586b589..4cc910b4d 100644
--- a/packages/dom-css/src/export/components/repeats.ts
+++ b/packages/dom-css/src/export/components/repeats.ts
@@ -11,6 +11,8 @@ import { isPlacement } from './references'
export interface RepeatedPart {
part: string
value: string
+ /** A trigger drawn as a disabled tab, which cannot be chosen. */
+ disabled?: boolean
}
/**
diff --git a/packages/dom-css/src/export/components/tree.ts b/packages/dom-css/src/export/components/tree.ts
index c68d02642..e3b92d816 100644
--- a/packages/dom-css/src/export/components/tree.ts
+++ b/packages/dom-css/src/export/components/tree.ts
@@ -30,6 +30,15 @@ export interface TreeLabels {
layerOf: (element: StateElement) => string | undefined
}
+/** What a repeated part adds to its element: the value it stands for, and a disabled trigger. */
+function repeatedFields(
+ repeated: RepeatedPart | undefined
+): Pick<ComponentElement, 'value' | 'disabled'> {
+ if (!repeated) return {}
+ if (repeated.disabled) return { value: repeated.value, disabled: true }
+ return { value: repeated.value }
+}
+
export function componentTree(
node: StateElement,
labels: TreeLabels,
@@ -43,7 +52,7 @@ export function componentTree(
return {
type: 'element',
part,
- ...(repeated ? { value: repeated.value } : {}),
+ ...repeatedFields(repeated),
tag: node.tagName,
className,
layerId,
diff --git a/packages/dom-css/src/export/components/vue.ts b/packages/dom-css/src/export/components/vue.ts
index 8ee19623c..55e003d7b 100644
--- a/packages/dom-css/src/export/components/vue.ts
+++ b/packages/dom-css/src/export/components/vue.ts
@@ -226,6 +226,7 @@ function elementAttributes(
),
vue.attribute('class', compact([node.attrs.class, uses.classOf(node.className)]).join(' ')),
...(node.value === undefined ? [] : [vue.attribute('value', node.value)]),
+ ...(node.disabled ? [vue.bound('disabled', es.parseExpression('true'))] : []),
...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
]
}
diff --git a/packages/dom-css/tests/behaviours/controls.test.ts b/packages/dom-css/tests/behaviours/controls.test.ts
index a64347881..ab83fd9b2 100644
--- a/packages/dom-css/tests/behaviours/controls.test.ts
+++ b/packages/dom-css/tests/behaviours/controls.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, test } from 'bun:test'
-import { progressComponent, sliderComponent } from '#dom-css-tests/behaviours/fixtures'
+import {
+ progressComponent,
+ sliderComponent,
+ tabsOfTabSets
+} from '#dom-css-tests/behaviours/fixtures'
import { behaviourControls, booleanOf } from '#dom-css/behaviours/controls'
import { controlRoles } from '#dom-css/behaviours/roles'
@@ -71,6 +75,38 @@ describe('behaviour controls', () => {
}
})
+ test('a tab list’s Tab instances are its triggers and items, each with its own value', () => {
+ const { graph, set } = tabsOfTabSets()
+ const card = graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Card' })
+ const instance = graph.createInstance(set.id, card.id)
+ if (!instance) throw new Error('No instance')
+ const controls = behaviourControls(graph, card.id)
+ const tabs = controls.get(instance.name)
+ expect(tabs?.triggers).toEqual([
+ 'Settings/List/Account',
+ 'Settings/List/Password',
+ 'Settings/List/Billing'
+ ])
+ expect(tabs?.items.map((item) => item.kind)).toEqual(['tab', 'tab', 'tab'])
+ // Each tab is a control of its own too, copies of instances in the Settings instance as
+ // they are, so preview keeps its state.
+ expect([...controls.keys()]).toEqual(['Settings', ...(tabs?.triggers ?? [])])
+ expect(tabs?.items.map((item) => booleanOf(item, 'value')?.designed)).toEqual([
+ true,
+ false,
+ false
+ ])
+ expect(tabs?.items.map((item) => item.states?.designedDisabled)).toEqual([false, false, true])
+
+ const roles = controlRoles(controls)
+ const billing = roles.get('Settings/List/Billing')
+ expect(billing?.type).toBe('trigger')
+ expect(billing?.type === 'trigger' && [billing.index, billing.tab?.path]).toEqual([
+ 2,
+ 'Settings/List/Billing'
+ ])
+ })
+
test('gives a control root its role by layer path', () => {
const { graph, card } = switchCard()
const roles = controlRoles(behaviourControls(graph, card.id))
diff --git a/packages/dom-css/tests/behaviours/fixtures.ts b/packages/dom-css/tests/behaviours/fixtures.ts
index 4c2cbec9a..2a591b694 100644
--- a/packages/dom-css/tests/behaviours/fixtures.ts
+++ b/packages/dom-css/tests/behaviours/fixtures.ts
@@ -307,6 +307,77 @@ export function tabsComponent() {
return { graph, set: graph.getNode(tabs.id) ?? tabs }
}
+/**
+ * Tabs whose triggers are instances of a Tab set, as the shadcn/ui kit draws them: the set
+ * draws Selected On and Off and a disabled look, and the list holds Account (selected),
+ * Password, and Billing (drawn disabled), each with a panel.
+ */
+export function tabsOfTabSets() {
+ const graph = new SceneGraph()
+ const { set: tab } = componentSet(
+ 'Tab',
+ { Selected: ['Off', 'On'], State: ['Default', 'Disabled'] },
+ {
+ ...emptyBehaviour('tab'),
+ booleans: { value: { propertyId: 'selected', on: 'On', off: 'Off' } },
+ states: { propertyId: 'state', rest: 'Default', disabled: 'Disabled' }
+ },
+ (graph, variant, { Selected, State }) =>
+ graph.updateNode(variant, {
+ width: 80,
+ height: 24,
+ fills: Selected === 'On' ? COLORS.on : COLORS.off,
+ opacity: State === 'Disabled' ? 0.5 : 1
+ }),
+ ({ Selected, State }) => Selected === 'On' && State === 'Disabled',
+ graph
+ )
+ const variant = (values: string) =>
+ graph.getChildren(tab.id).find((child) => child.name === values)
+ const tabs = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ name: 'Settings',
+ y: 100,
+ width: 260,
+ height: 120
+ })
+ const list = graph.createNode('FRAME', tabs.id, {
+ name: 'List',
+ componentPropertyReferences: slot('list-slot'),
+ width: 260,
+ height: 24
+ })
+ const panels = graph.createNode('FRAME', tabs.id, {
+ name: 'Panels',
+ componentPropertyReferences: slot('panels-slot'),
+ y: 30,
+ width: 260,
+ height: 80
+ })
+ const triggers = [
+ ['Account', 'Selected=On, State=Default'],
+ ['Password', 'Selected=Off, State=Default'],
+ ['Billing', 'Selected=Off, State=Disabled']
+ ] as const
+ for (const [index, [label, values]] of triggers.entries()) {
+ const main = variant(values)
+ if (!main) throw new Error(`No ${values} variant`)
+ graph.createInstance(main.id, list.id, { name: label, x: index * 86 })
+ graph.createNode('FRAME', panels.id, {
+ name: `${label} panel`,
+ width: 260,
+ height: 80,
+ visible: index === 0
+ })
+ }
+ graph.updateNode(tabs.id, {
+ pluginData: withBehaviour(tabs, {
+ ...emptyBehaviour('tabs'),
+ parts: { list: 'list-slot', panels: 'panels-slot' }
+ })
+ })
+ return { graph, tab: graph.getNode(tab.id) ?? tab, set: graph.getNode(tabs.id) ?? tabs }
+}
+
/**
* A group as design JSX builds one: a standalone component with the group's behaviour whose
* items slot holds instances of `item`, each labelled through the item's text property, with
diff --git a/packages/dom-css/tests/export/components/react.test.ts b/packages/dom-css/tests/export/components/react.test.ts
index 670c31084..b2260b16c 100644
--- a/packages/dom-css/tests/export/components/react.test.ts
+++ b/packages/dom-css/tests/export/components/react.test.ts
@@ -19,6 +19,7 @@ import {
settingsSectionSet,
switchSet,
tabsComponent,
+ tabsOfTabSets,
toggleGroupComponent
} from '#dom-css-tests/behaviours/fixtures'
import { shaderBackdropSet, shaderHeroSet } from '#dom-css-tests/export/components/shader-fixtures'
@@ -331,6 +332,15 @@ describe('generated React components', () => {
expect(second?.active).toEqual(first?.active)
})
+ test('tabs drawn as Tab instances start on the selected one and keep a disabled tab disabled', async () => {
+ const { component } = await generate(tabsOfTabSets())
+ // Account, Password, and Billing, in their list's order.
+ const [account, password, billing] = render(component).match(/<button[^>]*>/g) ?? []
+ expect(account).toContain('aria-selected="true"')
+ expect(password).not.toContain('disabled')
+ expect(billing).toContain('disabled=""')
+ })
+
test('a layer drawn as a frame in one state and an instance in another is both', async () => {
const { files, component } = await generate(badgeToggleSet())
const css = cssRules(String(files.find((file) => file.path === 'Alert.module.css')?.content))
diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.ts
index 39d7b5141..e9324576a 100644
--- a/packages/dom-css/tests/export/components/vue.test.ts
+++ b/packages/dom-css/tests/export/components/vue.test.ts
@@ -18,6 +18,7 @@ import {
settingsSectionSet,
switchSet,
tabsComponent,
+ tabsOfTabSets,
toggleGroupComponent
} from '#dom-css-tests/behaviours/fixtures'
import { shaderBackdropSet, shaderHeroSet } from '#dom-css-tests/export/components/shader-fixtures'
@@ -130,6 +131,20 @@ describe('generated Vue components', () => {
expect(second).not.toContain('Account settings')
})
+ test('tabs drawn as Tab instances take the selected look when active and keep a disabled tab disabled', async () => {
+ const { files, component } = await generate(tabsOfTabSets())
+ const html = await render(component)
+ const trigger = (name: string) =>
+ new RegExp(`<button class="settings__${name}"[^>]*>`).exec(html)?.[0] ?? ''
+ expect(trigger('account')).toContain('data-state="active"')
+ expect(trigger('billing')).toContain('data-disabled')
+ expect(trigger('password')).not.toContain('data-disabled')
+ const css = cssRules(String(files.find((file) => file.path === 'Settings.vue')?.content))
+ expect(css.get('.settings .settings__password[data-state="active"]')).toEqual(
+ css.get('.settings .settings__account[data-state="active"]')
+ )
+ })
+
test('a radio group writes an item component and chooses among its labelled items', async () => {
const { files, component } = await generate(radioGroupComponent())
expect(files.map((file) => file.path)).toContain('PlanItem.vue')
diff --git a/packages/scene-graph/src/behaviours/kinds.ts b/packages/scene-graph/src/behaviours/kinds.ts
index 3f5870189..daf79bb61 100644
--- a/packages/scene-graph/src/behaviours/kinds.ts
+++ b/packages/scene-graph/src/behaviours/kinds.ts
@@ -13,6 +13,7 @@ export const BEHAVIOUR_KINDS = [
'slider',
'progress',
'tabs',
+ 'tab',
'collapsible',
'accordion'
] as const
@@ -52,7 +53,8 @@ export interface BehaviourPartContract {
required: boolean
/**
* Whether the slot holds the control's items, each an instance with its own behaviour (a
- * radio, a toggle, a collapsible), which the control turns on and off.
+ * radio, a toggle, a collapsible, a tab), which the control turns on and off. A tab list's
+ * triggers may also be plain layers, which have no state of their own.
*/
items?: boolean
/**
@@ -153,10 +155,18 @@ export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContra
tabs: {
values: [{ id: 'value', type: 'choice', required: false }],
parts: [
- { id: 'list', required: true, children: 'trigger' },
+ { id: 'list', required: true, items: true, children: 'trigger' },
{ id: 'panels', required: false, children: 'content' }
]
},
+ // A tab list's trigger, after Reka's TabsTrigger: on while its tab is the chosen one.
+ tab: {
+ values: [
+ { id: 'value', type: 'boolean', required: true },
+ { id: 'disabled', type: 'boolean', required: false }
+ ],
+ parts: []
+ },
progress: {
values: [{ id: 'value', type: 'number', required: false }],
parts: [
diff --git a/packages/scene-graph/src/behaviours/layers.ts b/packages/scene-graph/src/behaviours/layers.ts
index a4db1e9f7..5b05b231c 100644
--- a/packages/scene-graph/src/behaviours/layers.ts
+++ b/packages/scene-graph/src/behaviours/layers.ts
@@ -1,11 +1,13 @@
import type { SceneGraph } from '../graph'
+import { instanceMainComponent } from '../instances/main-component'
import type { SceneNode } from '../types'
import { behaviourOwner, readBehaviour } from './model'
/** Whether an instance's main component, or its set, has a behaviour. */
export function hasBehaviour(graph: SceneGraph, node: SceneNode): boolean {
- if (node.type !== 'INSTANCE' || !node.componentId) return false
- const component = graph.getNode(node.componentId)
+ if (node.type !== 'INSTANCE') return false
+ // A copy of a nested instance names the instance it copies, so follow it to the component.
+ const component = instanceMainComponent(graph, node)
const owner = component && behaviourOwner(graph, component)
return !!owner && !!readBehaviour(owner)
}
diff --git a/packages/vue/src/canvas/islands/controls/index.ts b/packages/vue/src/canvas/islands/controls/index.ts
index 5d210a870..632a10ea7 100644
--- a/packages/vue/src/canvas/islands/controls/index.ts
+++ b/packages/vue/src/canvas/islands/controls/index.ts
@@ -117,7 +117,9 @@ function valueRoot(
TabsRoot,
{
modelValue: state.choice,
- 'onUpdate:modelValue': (value: string | number) => (state.choice = String(value))
+ // Tabs that are instances show whether they are the chosen one, as group items do.
+ 'onUpdate:modelValue': (value: string | number) =>
+ chooseItem(island, control, String(value))
},
() => base()
)
@@ -222,6 +224,25 @@ function disclosurePart(
return base()
}
+/**
+ * A tab trigger. A tab with the tab behaviour takes hover, press, and focus as its own states
+ * and is disabled while its disabled value is on or it is drawn disabled, so it cannot be
+ * chosen, as Reka's TabsTrigger is.
+ */
+function trigger(
+ island: IslandRenderContext,
+ role: Extract<ControlRole, { type: 'trigger' }>,
+ base: RoleContext['base']
+): VNode {
+ const tab = role.tab
+ const props = tab ? interaction(stateOf(island, tab)) : {}
+ return asChild(
+ TabsTrigger,
+ { value: String(role.index), disabled: tab ? disabled(island, tab) : false },
+ () => base({ tag: 'button', props: { type: 'button', ...props } })
+ )
+}
+
/** Render a layer with the role it has for the controls of its island. */
export function wrapRole(
island: IslandRenderContext,
@@ -237,9 +258,7 @@ export function wrapRole(
case 'part':
return part({ island, role, element, base })
case 'trigger':
- return asChild(TabsTrigger, { value: String(role.index) }, () =>
- base({ tag: 'button', props: { type: 'button' } })
- )
+ return trigger(island, role, base)
case 'panel':
return asChild(TabsContent, { value: String(role.index) }, () => base())
case 'text':
diff --git a/packages/vue/src/canvas/islands/controls/shared.ts b/packages/vue/src/canvas/islands/controls/shared.ts
index a1636eeff..2740a67d2 100644
--- a/packages/vue/src/canvas/islands/controls/shared.ts
+++ b/packages/vue/src/canvas/islands/controls/shared.ts
@@ -44,11 +44,15 @@ export function interaction(state: ControlState, focusOnPress = false): Record<s
}
}
-/** Turn a group's items on and off so that only the chosen one is on. */
+/**
+ * Turn a group's items on and off so that only the chosen one is on. Tabs choose by trigger,
+ * so a tab's place is among its list's triggers, plain ones included.
+ */
export function chooseItem(island: IslandRenderContext, group: ControlModel, choice: string): void {
stateOf(island, group).choice = choice
for (const [index, item] of group.items.entries()) {
const valueId = item.kind === 'collapsible' ? 'open' : 'value'
- stateOf(island, item).booleans[valueId] = String(index) === choice
+ const place = group.kind === 'tabs' ? group.triggers.indexOf(item.path) : index
+ stateOf(island, item).booleans[valueId] = String(place) === choice
}
}
diff --git a/packages/vue/src/canvas/islands/state.ts b/packages/vue/src/canvas/islands/state.ts
index 051daea25..a4032f34b 100644
--- a/packages/vue/src/canvas/islands/state.ts
+++ b/packages/vue/src/canvas/islands/state.ts
@@ -20,7 +20,12 @@ export interface ControlState {
const TEXT_INPUTS = new Set(['textField', 'textarea', 'numberField'])
function initialChoice(control: ControlModel): string {
- if (control.kind === 'tabs') return '0'
+ if (control.kind === 'tabs') {
+ // The tab drawn selected, at its place among the triggers; else the first, as Reka starts.
+ const tab = control.items.find((item) => booleanOf(item, 'value')?.designed)
+ const index = tab ? control.triggers.indexOf(tab.path) : -1
+ return String(Math.max(index, 0))
+ }
const index = control.items.findIndex((item) => {
const value = booleanOf(item, 'value') ?? booleanOf(item, 'open')
return value?.designed ?? false
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index d47818469..dfecce449 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -565,6 +565,9 @@
"behaviourCheckboxDescription": "Hakt an und ab",
"behaviourSliderDescription": "Zieht einen Regler an einer Spur entlang",
"behaviourTabsDescription": "Zeigt jeweils ein Panel",
+ "behaviourTab": "Tab",
+ "behaviourTabDescription": "Ein Auslöser von Tabs, gezeichnet ausgewählt oder nicht",
+ "behaviourSelected": "Ausgewählt",
"behaviourTextField": "Textfeld",
"behaviourTextFieldDescription": "Nimmt eine Zeile Eingabe auf",
"behaviourTextarea": "Textbereich",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 778dcc886..0424ef342 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -565,6 +565,9 @@
"behaviourCheckboxDescription": "Marca y desmarca",
"behaviourSliderDescription": "Desliza un control a lo largo de una pista",
"behaviourTabsDescription": "Muestra un panel a la vez",
+ "behaviourTab": "Pestaña",
+ "behaviourTabDescription": "Un activador de pestañas, dibujado seleccionado o no",
+ "behaviourSelected": "Seleccionada",
"behaviourTextField": "Campo de texto",
"behaviourTextFieldDescription": "Admite una línea de texto",
"behaviourTextarea": "Área de texto",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 1d97bec3d..fa1e7c874 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -565,6 +565,9 @@
"behaviourCheckboxDescription": "Coche et décoche",
"behaviourSliderDescription": "Fait glisser un bouton le long d’une piste",
"behaviourTabsDescription": "Affiche un panneau à la fois",
+ "behaviourTab": "Onglet",
+ "behaviourTabDescription": "Un déclencheur d’onglets, dessiné sélectionné ou non",
+ "behaviourSelected": "Sélectionné",
"behaviourTextField": "Champ de texte",
"behaviourTextFieldDescription": "Accepte une ligne de saisie",
"behaviourTextarea": "Zone de texte",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 1e4e0a659..6fd5ae9e8 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -565,6 +565,9 @@
"behaviourCheckboxDescription": "Seleziona e deseleziona",
"behaviourSliderDescription": "Trascina un cursore lungo una traccia",
"behaviourTabsDescription": "Mostra un pannello alla volta",
+ "behaviourTab": "Scheda singola",
+ "behaviourTabDescription": "Un attivatore delle schede, disegnato selezionato o no",
+ "behaviourSelected": "Selezionata",
"behaviourTextField": "Campo di testo",
"behaviourTextFieldDescription": "Accetta una riga di testo",
"behaviourTextarea": "Area di testo",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 7c5a9a00d..c437766c9 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -558,6 +558,9 @@
"behaviourCheckboxDescription": "チェックを付け外しします",
"behaviourSliderDescription": "トラックに沿ってつまみをドラッグします",
"behaviourTabsDescription": "一度に 1 つのパネルを表示します",
+ "behaviourTab": "タブ項目",
+ "behaviourTabDescription": "タブのトリガー。選択中かどうかで描き分けます",
+ "behaviourSelected": "選択中",
"behaviourTextField": "テキストフィールド",
"behaviourTextFieldDescription": "1 行の入力を受け付けます",
"behaviourTextarea": "テキストエリア",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 69d4fbd53..f343e1aaf 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -572,6 +572,9 @@
"behaviourCheckboxDescription": "Zaznacza i odznacza",
"behaviourSliderDescription": "Przesuwa uchwyt wzdłuż ścieżki",
"behaviourTabsDescription": "Pokazuje jeden panel naraz",
+ "behaviourTab": "Karta",
+ "behaviourTabDescription": "Wyzwalacz kart, rysowany jako wybrany lub nie",
+ "behaviourSelected": "Wybrana",
"behaviourTextField": "Pole tekstowe",
"behaviourTextFieldDescription": "Przyjmuje jeden wiersz tekstu",
"behaviourTextarea": "Obszar tekstowy",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 964cfabcb..26a2f1303 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -572,6 +572,9 @@
"behaviourCheckboxDescription": "Ставит и снимает отметку",
"behaviourSliderDescription": "Перемещает бегунок по дорожке",
"behaviourTabsDescription": "Показывает одну панель за раз",
+ "behaviourTab": "Вкладка",
+ "behaviourTabDescription": "Переключатель вкладок, нарисованный выбранным или нет",
+ "behaviourSelected": "Выбрана",
"behaviourTextField": "Текстовое поле",
"behaviourTextFieldDescription": "Принимает одну строку текста",
"behaviourTextarea": "Многострочное поле",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 393b71642..707d0712a 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -558,6 +558,9 @@
"behaviourCheckboxDescription": "勾选和取消勾选",
"behaviourSliderDescription": "沿轨道拖动滑块",
"behaviourTabsDescription": "一次显示一个面板",
+ "behaviourTab": "标签",
+ "behaviourTabDescription": "标签页的触发器,绘制为选中或未选中",
+ "behaviourSelected": "已选中",
"behaviourTextField": "文本框",
"behaviourTextFieldDescription": "接受单行输入",
"behaviourTextarea": "多行文本框",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 457a12060..a05ec128c 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -255,6 +255,9 @@ export const panelMessageDefaults = {
behaviourCheckboxDescription: 'Checks and unchecks',
behaviourSliderDescription: 'Drags a thumb along a track',
behaviourTabsDescription: 'Shows one panel at a time',
+ behaviourTab: 'Tab',
+ behaviourTabDescription: 'A trigger of tabs, drawn selected or not',
+ behaviourSelected: 'Selected',
behaviourTextField: 'Text field',
behaviourTextFieldDescription: 'Takes one line of typing',
behaviourTextarea: 'Textarea',
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index 1e54beac4..e38b6e53d 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -60,6 +60,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.
- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing. A part with children and no `flex`, `display`, `w`, or `h` of its own stacks them in a column that hugs them.
- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.
+- 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.
```tsx
<Switch.Root name="Switch" modelValue="State" states="Interaction">
@@ -131,7 +132,7 @@ return <Frame name="Dark note" mode={dark} w={280} h="hug" flex="col" gap={8} p=
Generated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.
-**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Tab`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.
diff --git a/src/components/properties/component-properties/behaviour/labels.ts b/src/components/properties/component-properties/behaviour/labels.ts
index 464bc52bc..4211cfa6a 100644
--- a/src/components/properties/component-properties/behaviour/labels.ts
+++ b/src/components/properties/component-properties/behaviour/labels.ts
@@ -28,6 +28,7 @@ export function useBehaviourLabels() {
slider: { label: p.behaviourSlider, description: p.behaviourSliderDescription },
progress: { label: p.behaviourProgress, description: p.behaviourProgressDescription },
tabs: { label: p.behaviourTabs, description: p.behaviourTabsDescription },
+ tab: { label: p.behaviourTab, description: p.behaviourTabDescription },
collapsible: {
label: p.behaviourCollapsible,
description: p.behaviourCollapsibleDescription
@@ -67,6 +68,7 @@ export function useBehaviourLabels() {
checkbox: p.behaviourChecked,
radio: p.behaviourChecked,
toggle: p.behaviourPressed,
+ tab: p.behaviourSelected,
textField: p.behaviourText,
textarea: p.behaviourText
}
diff --git a/tests/e2e/components/behaviours.spec.ts b/tests/e2e/components/behaviours.spec.ts
index b5de87e33..6d83ceee2 100644
--- a/tests/e2e/components/behaviours.spec.ts
+++ b/tests/e2e/components/behaviours.spec.ts
@@ -229,6 +229,141 @@ test('a slider instance in preview moves the range inside its track', async () =
await editor.page.keyboard.press('Escape')
})
+// Tabs as the shadcn/ui kit draws them: triggers are instances of a Tab set that draws
+// Selected On and Off and a disabled look.
+test('tabs whose triggers are Tab instances show the chosen one and skip a disabled one', async () => {
+ const ids = await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const graph = store.graph
+ const pageId = store.state.currentPageId
+ const solid = (r: number, g: number, b: number) => [
+ { type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }
+ ]
+ const slot = (propertyId: string) => [{ propertyId, field: 'SLOT_CONTENT' as const }]
+ const tab = graph.createNode('COMPONENT_SET', pageId, {
+ name: 'Tab',
+ x: 120,
+ y: 60,
+ width: 300,
+ height: 40,
+ componentPropertyDefinitions: [
+ {
+ id: 'selected',
+ name: 'Selected',
+ type: 'VARIANT' as const,
+ defaultValue: 'Off',
+ variantOptions: ['Off', 'On']
+ },
+ {
+ id: 'state',
+ name: 'State',
+ type: 'VARIANT' as const,
+ defaultValue: 'Default',
+ variantOptions: ['Default', 'Disabled']
+ }
+ ]
+ })
+ const variants = new Map<string, string>()
+ for (const [index, [selected, state]] of [
+ ['Off', 'Default'],
+ ['On', 'Default'],
+ ['Off', 'Disabled']
+ ].entries()) {
+ const name = `Selected=${selected}, State=${state}`
+ const variant = graph.createNode('COMPONENT', tab.id, {
+ name,
+ x: 10 + index * 90,
+ y: 8,
+ width: 80,
+ height: 24,
+ fills: selected === 'On' ? solid(0.2, 0.4, 1) : solid(0.85, 0.85, 0.9),
+ opacity: state === 'Disabled' ? 0.5 : 1,
+ componentPropertyValues: { Selected: selected, State: state }
+ })
+ variants.set(name, variant.id)
+ }
+ store.setBehaviour(tab.id, {
+ kind: 'tab',
+ booleans: { value: { propertyId: 'selected', on: 'On', off: 'Off' } },
+ texts: {},
+ numbers: {},
+ parts: {},
+ states: { propertyId: 'state', rest: 'Default', disabled: 'Disabled' }
+ })
+ const tabs = graph.createNode('COMPONENT', pageId, {
+ name: 'Settings',
+ x: 120,
+ y: 140,
+ width: 260,
+ height: 120
+ })
+ const list = graph.createNode('FRAME', tabs.id, {
+ name: 'List',
+ componentPropertyReferences: slot('list-slot'),
+ width: 260,
+ height: 24
+ })
+ const panels = graph.createNode('FRAME', tabs.id, {
+ name: 'Panels',
+ componentPropertyReferences: slot('panels-slot'),
+ y: 30,
+ width: 260,
+ height: 80
+ })
+ for (const [index, [label, values]] of [
+ ['Account', 'Selected=On, State=Default'],
+ ['Password', 'Selected=Off, State=Default'],
+ ['Billing', 'Selected=Off, State=Disabled']
+ ].entries()) {
+ const main = variants.get(values)
+ if (!main) throw new Error(`No ${values}`)
+ graph.createInstance(main, list.id, { name: label, x: index * 86 })
+ graph.createNode('FRAME', panels.id, {
+ name: `${label} panel`,
+ width: 260,
+ height: 80,
+ visible: index === 0
+ })
+ }
+ store.setBehaviour(tabs.id, {
+ kind: 'tabs',
+ booleans: {},
+ texts: {},
+ numbers: {},
+ parts: { list: 'list-slot', panels: 'panels-slot' }
+ })
+ const instance = graph.createInstance(tabs.id, pageId, { x: 120, y: 300 })
+ if (!instance) throw new Error('Instance not created')
+ return { instanceId: instance.id }
+ })
+ await editor.canvas.waitForRender()
+ await startPreview()
+
+ const triggers = island(ids.instanceId).getByRole('tab')
+ await expect(triggers).toHaveCount(3)
+ const [account, password, billing] = [triggers.nth(0), triggers.nth(1), triggers.nth(2)]
+ const fill = (trigger: typeof account) =>
+ trigger.evaluate((element) => getComputedStyle(element).backgroundColor)
+ await expect(account).toHaveAttribute('aria-selected', 'true')
+ const selectedFill = await fill(account)
+ const restFill = await fill(password)
+ expect(selectedFill).not.toBe(restFill)
+
+ await password.click()
+ await expect(password).toHaveAttribute('aria-selected', 'true')
+ // Each Tab instance now shows its Selected variant as the choice says.
+ await expect.poll(() => fill(password)).toBe(selectedFill)
+ await expect.poll(() => fill(account)).toBe(restFill)
+
+ // Drawn disabled, Billing is a disabled trigger: clicking it changes nothing.
+ await expect(billing).toBeDisabled()
+ await billing.click({ force: true })
+ await expect(password).toHaveAttribute('aria-selected', 'true')
+ await expect(billing).toHaveAttribute('aria-selected', 'false')
+ await editor.page.keyboard.press('Escape')
+})
+
test('preview islands move with the frames the canvas draws, not ahead of them', async () => {
const ids = await createSwitch({ nested: true })
await editor.canvas.waitForRender()
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 5529f3ab4..3a36cb588 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -55,6 +55,7 @@ de:panels.radius
de:panels.stickyColorOrange
de:panels.textCaseOriginal
de:panels.slots
+de:panels.behaviourTab
de:panels.behaviourTabs
de:panels.behaviourMin
de:panels.behaviourMax