Skip to content

Commit 75568c2

Browse files
zernoniaclaude
andauthored
feat(elements): Listbox, Combobox, Autocomplete, Select, Tree, TagsInput, TagGroup, Editable (#3080) (#3094)
* feat(elements): custom elements foundation for eight families (#3080) Add `reka-ui/elements`: a side-effect-free `defineRekaElements()` plus per-family helpers that register `<reka-<family>-<part>>` custom elements for Switch, Checkbox, Toggle, Tabs, Accordion, Collapsible, Dialog and Popover. Each element renders its part onto itself through a small custom renderer, inherits context from the nearest Reka element above it, maps props to attributes/properties and emits to cancelable CustomEvents. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(elements): add custom elements guide Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(elements): add typesVersions entry and raise Dialog element size limit Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(elements): rework the element foundation after review (#3080) - Find parents over the Context Community Protocol (context-request / context-provider) instead of instanceof and whenDefined: synchronous moves rebind, undefined ancestors are skipped, late providers take their descendants over, and copies of the library interoperate. App ids come from a counter shared through Symbol.for. - Drop the data-reka-fragment sibling: root-level nodes stay detached, wrappers take the host's place, and form values go through ElementInternals (reset, state restore, fieldset disabled). - Own the attributes the part renders: consumer writes while mounted become the value given back. `disabled` follows the prop, follows HTML boolean semantics, and is reflected from the property. - Keep uncontrolled state across remounts, strip a cloned element's rendered state, make unrendered parts inert and hidden and leave their fields out of form data. - Only before-update-* and DOM-event emits are cancelable; add the `events` option and restrict `shadowRoot` to `{ mode }`. - Add defineAllRekaElements, element and JSX typings, and React 19/18 smoke tests. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(elements): document forms, ownership, typings and framework usage Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(elements): resolve portal targets up front and support shadow roots (#3080) Build on the Shadow DOM utilities from #3083. A portal element's target is resolved from where the element sits before its first render: its portal's own lookup runs from an anchor in the element's detached container, which sent content inside a shadow root to the document body and cost force-mounted portals an extra render. Parent lookup uses the shared `containsComposed`, so slotted elements are found too. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(elements): address the verification review of #3087 (#3080) - Mirror hidden fields' validity to ElementInternals (required is enforced) - Retarget portals when a consumer move changes their root node - Find late providers' orphans in nested shadow roots - Let a consumer `hidden` / `inert` take over from the unrendered state - Start over when the parent part unmounts; never carry an overlay's `open` - Warn instead of throwing when a part needs another copy's context - `el.disabled` reflects the attribute both ways and reads as a boolean - Add types-only `reka-ui/elements/global` and `reka-ui/elements/react` - Port the review repros into tests, with a Vue as-child group form test Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(elements): follow part `id` props from #3092 (#3080) Collapsible/Accordion/Popover/Tabs/Dialog parts now render the consumer's `id`. The clone test checks the copy against library-owned state (`data-state` and a generated id) instead, and the id tests assert the new behaviour. Raise the all-families size limit for the components' added props. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(elements): address CodeRabbit review of #3087 (#3080) - Reject uppercase tag prefixes up front (custom element names allow none) - Only treat a missing-injection error as "waiting for a parent"; log the rest - Guide: define portal families after React hydration; `.prop` needs `.camel` - Tests for each, including React 18/19 portal hydration and Vue bindings Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(Toggle): submit the value of a pressed Toggle with its form The hidden checkbox had `value` but never `checked`, so a named Toggle was always left out of its form's data, in Vue and as `<reka-toggle>` (also after a form-state restore). Bind `checked` like Checkbox, Switch and Radio do. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * ci(elements): give the browser tests the built dist (#3080) `copies.browser.test.ts` loads the built `reka-ui/elements` next to the source as a second copy of the library, and was skipped in CI for lack of a build. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(elements): add the collection families (#3080) Listbox, Combobox, Autocomplete, Select, Tree, TagsInput, TagGroup and Editable. Collections work as elements: items register in DOM order, values of any type are set as properties and compared with `by`, functions (`filter`, `displayValue`, `getKey`, …) are properties, and the roots submit with their form like the Vue components. Foundation: - `target: 'input'`: a part renders onto the element's `<input>` child, created when missing (ComboboxInput, ListboxFilter, TagsInputInput, …). - `text`: slot fallback content becomes the element's text while it has no children (SelectValue, EditablePreview, TagsInputItemText). - A Teleport into a detached fragment (closed SelectContent) keeps the element in place, unrendered. - A part's root-level `<style>` goes into the shadow root or the head. Vue fixes: inline ComboboxContent and item-aligned SelectContent forward `as`/`asChild`, and ComboboxGroup follows a label that sets up later. Virtualizers and the SVG arrows are left out; the guide documents why and how to render from events where Vue uses scoped slots. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(elements): give the dist import time under coverage (#3080) Importing the built entry now loads the collection families too, which went past the 5s timeout in the CI coverage run. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(elements): address CodeRabbit review of #3094 (#3080) - An input-targeted part gives the input back the DOM properties it had (a pre-disabled input stays disabled), not cleared ones. - Item-aligned SelectContent forwards `as` / `asChild` reactively. - The guide says a multiple select submits repeated entries, like a native `<select multiple>`. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(elements): address the review of #3094 (#3080) - Fallback text lives in a text node of its own: children the consumer adds take its place and are never removed, and the text comes back when they go. - An `<input>` target owns `disabled` like an attribute: consumer writes while rendered are what remain, and a `cloneNode()` copy drops it. A replaced input gets the part; an input the element created is marked (`data-reka-created`) and removed with it. - A form reset or restore dispatches the model's update event when the value changed. - Form-associated elements expose `form`, count as form controls when associated with `form="id"`, and remount when their form changes. - A part's root-level `<style>` is tracked and removed when the part unmounts, instead of piling up in the head. - DOM position uses the host, rendered attributes the target. - Select, Combobox and Autocomplete start closed when moved, like the other overlays. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 47400b0 commit 75568c2

21 files changed

Lines changed: 2313 additions & 48 deletions

‎docs/content/docs/guides/custom-elements.md‎

Lines changed: 112 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,21 @@ The `reka-ui` package is published as ES modules that reference `process.env.NOD
109109
| Family | Register with | Tags |
110110
| --- | --- | --- |
111111
| Accordion | `accordionElements` | `reka-accordion-root`, `-item`, `-header`, `-trigger`, `-content` |
112+
| Autocomplete | `autocompleteElements` | `reka-autocomplete-root`, `-input`, `-anchor`, `-trigger`, `-cancel`, `-portal`, `-content`, `-viewport`, `-empty`, `-item`, `-item-indicator`, `-group`, `-label`, `-separator` |
112113
| Checkbox | `checkboxElements` | `reka-checkbox-root`, `-indicator`, `reka-checkbox-group-root` |
113114
| Collapsible | `collapsibleElements` | `reka-collapsible-root`, `-trigger`, `-content` |
115+
| Combobox | `comboboxElements` | `reka-combobox-root`, `-input`, `-anchor`, `-trigger`, `-cancel`, `-portal`, `-content`, `-viewport`, `-empty`, `-item`, `-item-indicator`, `-group`, `-label`, `-separator` |
114116
| Dialog | `dialogElements` | `reka-dialog-root`, `-trigger`, `-portal`, `-overlay`, `-content`, `-title`, `-description`, `-close` |
117+
| Editable | `editableElements` | `reka-editable-root`, `-area`, `-input`, `-preview`, `-edit-trigger`, `-submit-trigger`, `-cancel-trigger` |
118+
| Listbox | `listboxElements` | `reka-listbox-root`, `-content`, `-filter`, `-item`, `-item-indicator`, `-group`, `-group-label` |
115119
| Popover | `popoverElements` | `reka-popover-root`, `-trigger`, `-anchor`, `-portal`, `-content`, `-close` |
120+
| Select | `selectElements` | `reka-select-root`, `-trigger`, `-value`, `-icon`, `-portal`, `-content`, `-viewport`, `-scroll-up-button`, `-scroll-down-button`, `-item`, `-item-text`, `-item-indicator`, `-group`, `-label`, `-separator` |
116121
| Switch | `switchElements` | `reka-switch-root`, `-thumb` |
117122
| Tabs | `tabsElements` | `reka-tabs-root`, `-list`, `-trigger`, `-content`, `-indicator` |
123+
| TagGroup | `tagGroupElements` | `reka-tag-group-root`, `-item`, `-item-text`, `-item-delete` |
124+
| TagsInput | `tagsInputElements` | `reka-tags-input-root`, `-input`, `-item`, `-item-text`, `-item-delete`, `-clear` |
118125
| Toggle | `toggleElements` | `reka-toggle` |
126+
| Tree | `treeElements` | `reka-tree-root`, `-item` |
119127

120128
Props, events and data attributes are the ones documented on each component page, mapped as described below.
121129

@@ -181,6 +189,32 @@ Elements do not reflect props back to attributes, with one exception: `disabled`
181189

182190
`id`, `dir` and `hidden` are native `HTMLElement` properties, so they stay attribute-driven.
183191

192+
### Values of any type
193+
194+
Collections (Listbox, Combobox, Select, Tree, TagGroup, …) take values of any type, as in Vue. An attribute gives a string (`<reka-listbox-item value="apple">`). Set the property for anything else: an object, a number, an array of selected values with `multiple`.
195+
196+
```js
197+
const root = document.querySelector('reka-listbox-root')
198+
const [ada, grace] = root.querySelectorAll('reka-listbox-item')
199+
ada.value = { id: 1, name: 'Ada' }
200+
grace.value = { id: 2, name: 'Grace' }
201+
202+
// Compared with `by` (a field name, or a function set as a property).
203+
root.setAttribute('by', 'id')
204+
root.modelValue = { id: 2 } // Grace is selected
205+
```
206+
207+
Functions are properties only: `filter`, `displayValue`, `getKey`, `convertValue`, `getNavigationIntent`, and the like.
208+
209+
A few props are read once, when the part sets up: `by` (Listbox, Combobox, Select) and `displayValue` (Combobox). Required props (`getKey` on a tree root, `value` on items) are needed from the start too. Set them before the element is connected, as Vue passes props on creation: create the element, set its properties, then insert it. Properties set before the tags are defined are kept, so `defineRekaElements()` after setting them also works. An element connected without a required prop logs Vue's "Missing required prop" warning.
210+
211+
```js
212+
const tree = document.createElement('reka-tree-root')
213+
tree.items = files
214+
tree.getKey = file => file.path
215+
document.querySelector('#files').append(tree)
216+
```
217+
184218
## Events
185219

186220
Each Vue emit becomes a `CustomEvent`. The name is the emit name in kebab-case, with `:` replaced by `-`:
@@ -259,20 +293,89 @@ This is the one place elements differ from the Vue components. In Vue, closed co
259293

260294
## Forms
261295

262-
Parts with a `name` (Switch, Checkbox, Checkbox group, Toggle) are [form-associated](https://html.spec.whatwg.org/multipage/custom-elements.html#form-associated-custom-elements):
296+
Parts with a `name` (Switch, Checkbox, Checkbox group, Toggle, and the roots of Listbox, Combobox, Autocomplete, Select, TagsInput and Editable) are [form-associated](https://html.spec.whatwg.org/multipage/custom-elements.html#form-associated-custom-elements):
263297

264-
- they submit their value with their form, wherever you move them;
265-
- `<label for>` labels them, `<fieldset disabled>` disables them, and resetting the form resets them;
298+
- they submit their value with their form, wherever you move them, and with a form they are not inside through the `form` attribute (`form="checkout"`); their `form` property is the form, like a native control's;
299+
- `<label for>` labels them, `<fieldset disabled>` disables them, and resetting the form resets them, firing `update-model-value` (or the part's other model events) when the value changes, so what you render from it follows;
266300
- they are validated with it: a `required` checkbox left unchecked makes the form invalid, and matches `:invalid`;
267-
- they submit the same names as the Vue components (a checkbox group named `toppings` submits `toppings[0]`, `toppings[1]`, …);
301+
- they submit the same names as the Vue components (a checkbox group named `toppings` submits `toppings[0]`, `toppings[1]`, …, and so does a `multiple` listbox or combobox, or a tags input; object values submit their fields, `fruit[0][id]`);
302+
- a select submits through the native `<select>` the Vue component renders, so `required` and `autocomplete` behave the same, and a `multiple` select named `fruit` submits one `fruit` entry per selected value, like `<select multiple>`;
268303
- nothing is added next to them: the hidden inputs the Vue components render are not in the document.
269304

270305
Form participation needs `ElementInternals` (Safari 16.4 and later). Without it, the elements work but do not submit.
271306

307+
## Text fields
308+
309+
A custom element can't be a text field. Parts that render an `<input>` in Vue (`ComboboxInput`, `AutocompleteInput`, `ListboxFilter`, `TagsInputInput`, `EditableInput`) render onto the `<input>` (or `<textarea>`) you put inside them, like `asChild` over it. Without one, the element creates an `<input>`.
310+
311+
```html
312+
<reka-combobox-input>
313+
<input id="fruit" placeholder="Pick a fruit" autocomplete="off">
314+
</reka-combobox-input>
315+
```
316+
317+
- The `<input>` gets the role, ARIA, value and listeners. Put your own attributes on it (`id` for `<label for>`, `placeholder`, `class`), and style it rather than the element.
318+
- The element keeps the part's props (`disabled`, `model-value`, `auto-focus`) and fires its events (`update-model-value`).
319+
- Removed, the element gives the input back as it was. A `disabled` you set on the input stays, as do your attributes.
320+
- Replace the input and the part moves to the new one.
321+
272322
## Children instead of slots
273323

274324
Child elements and text work like the default slot. Scoped slots (slot props) are not available. Read state from `data-*` attributes and events instead.
275325

326+
Some parts show text of their own when you give them no children, as the Vue components' slot fallbacks do: `<reka-select-value>` shows the selected labels or its `placeholder`, `<reka-editable-preview>` the value or its placeholder, `<reka-tags-input-item-text>` the tag's `displayValue`, and an empty `<reka-combobox-item>` its value. Give them children, now or later, and yours are shown instead; remove them and the text comes back.
327+
328+
Where a Vue template renders from slot props, render from events instead:
329+
330+
| Vue slot prop | As elements |
331+
| --- | --- |
332+
| `TreeRoot`'s `flattenItems` | Render a `<reka-tree-item>` per visible item: set `value` (the item) and `level`, and render the children of the keys in `update-expanded`. See below. |
333+
| `TagsInputRoot`'s `modelValue` | Render a `<reka-tags-input-item value="…">` per tag from `update-model-value`. |
334+
| `ListboxItem` / `ComboboxItem`'s `selected`, `SelectItem`'s `selected` | `[data-state='checked']` / `aria-selected` on the item, or an `*-item-indicator`. |
335+
| `TreeItem`'s `isExpanded`, `isSelected` | `[data-expanded]`, `[data-selected]`, `aria-expanded`. |
336+
| `SelectValue`'s `selectedLabel` | The element's own text, or `update-model-value`. |
337+
| `EditableRoot`'s `isEditing`, `modelValue` | `update:state` → `update-state`, `update-model-value`, and `[data-placeholder-shown]` on the preview. |
338+
339+
A tree renders its visible items from `items` and the expanded keys. Keep the existing elements where they are, so focus stays on them:
340+
341+
```js
342+
const tree = document.createElement('reka-tree-root')
343+
tree.items = files
344+
tree.getKey = file => file.path
345+
document.querySelector('#files').append(tree)
346+
347+
function render(expanded) {
348+
const visible = (items, level) => items.flatMap(item => [
349+
{ item, level },
350+
...(item.children && expanded.includes(item.path) ? visible(item.children, level + 1) : []),
351+
])
352+
const existing = new Map(Array.from(tree.children, el => [el.value.path, el]))
353+
let previous = null
354+
for (const { item, level } of visible(tree.items, 1)) {
355+
let el = existing.get(item.path)
356+
existing.delete(item.path)
357+
if (!el) {
358+
el = document.createElement('reka-tree-item')
359+
el.value = item
360+
el.setAttribute('level', level)
361+
el.textContent = item.name
362+
tree.insertBefore(el, previous ? previous.nextSibling : tree.firstChild)
363+
}
364+
previous = el
365+
}
366+
existing.forEach(el => el.remove())
367+
}
368+
369+
tree.addEventListener('update-expanded', event => render(event.detail.value))
370+
render([])
371+
```
372+
373+
In a framework, render the same list from its state (React's `useState`, Svelte's `$state`) instead.
374+
375+
### Collections follow the DOM
376+
377+
Items register with their collection in DOM order: insert, remove or reorder `<reka-listbox-item>`s (or any other items) and keyboard navigation, typeahead and Home/End follow the new order. A filtered-out item is unrendered like closed content (hidden, `data-reka-unmounted`), and its group hides when none of its items match.
378+
276379
## Context across elements
277380

278381
Context passes through the DOM the way it passes through components in Vue. An element mounts once the nearest Reka element above it has rendered its part, and it injects the contexts provided there. That is how `<reka-dialog-trigger>` finds its `<reka-dialog-root>`.
@@ -359,7 +462,7 @@ useEffect(() => {
359462

360463
In React 18, `disabled={false}` becomes `disabled="false"`, which is disabled. Leave the prop out instead: `disabled={isDisabled || undefined}`.
361464

362-
Server-rendered elements hydrate without mismatches: nothing is added next to them. Portals are the exception: a defined `<reka-dialog-portal>` or `<reka-popover-portal>` moves to `<body>` as soon as it connects, before React has hydrated the spot it was rendered in. When the server-rendered tree contains portals, define those families after hydration, for example in an effect:
465+
Server-rendered elements hydrate without mismatches: nothing is added next to them. Portals are the exception: a defined `<reka-dialog-portal>`, `<reka-popover-portal>`, `<reka-select-portal>` or `<reka-combobox-portal>` moves to `<body>` as soon as it connects, before React has hydrated the spot it was rendered in. When the server-rendered tree contains portals, define those families after hydration, for example in an effect:
363466

364467
```tsx
365468
useEffect(() => {
@@ -400,7 +503,10 @@ Bind props in camelCase (`:modelValue="checked"`, or `:modelValue.prop` to force
400503

401504
## Limitations
402505

403-
- **Families.** Only the families listed above are available. The rest will follow, and `PopoverArrow` (which renders an SVG) is not included yet.
506+
- **Families.** Only the families listed above are available. The rest will follow. The arrows (`PopoverArrow`, `ComboboxArrow`, `SelectArrow`), which render an SVG, are not included yet.
507+
- **Virtualizers.** `ListboxVirtualizer`, `ComboboxVirtualizer`, `SelectVirtualizer` and `TreeVirtualizer` render each visible row from a scoped slot (`option`, `virtualItem`), which elements don't have, and they position the rows they create. Render the rows yourself, with your own virtualization, or use the Vue components.
508+
- **Tag groups.** Delete and Backspace on a tag, and its delete button, always dispatch `remove`: the element can't tell whether you listen to it, where the Vue component only makes tags removable with a `@remove` listener. Remove the tags from the DOM in your listener. Rows need a `gridcell` child for a valid grid, which the Vue component adds: wrap a tag's content in `<span role="gridcell">`.
509+
- **Props read once.** See [values of any type](#values-of-any-type): set `by`, `displayValue` and required props before the element is connected.
404510
- **SSR.** Server rendering and declarative shadow DOM are not supported. Elements render on the client after they are defined.
405511
- **Bundler required.** See the [quick start](#quick-start).
406512
- **Custom Elements Manifest.** Not generated yet.

‎packages/core/.size-limit.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,19 @@
5656
{
5757
"path": "dist/elements.js",
5858
"import": "{ defineRekaElements, switchElements }",
59-
"limit": "12 KB",
59+
"limit": "13 KB",
6060
"name": "Elements: runtime + Switch"
6161
},
6262
{
6363
"path": "dist/elements.js",
6464
"import": "{ defineRekaElements, dialogElements }",
65-
"limit": "22 KB",
65+
"limit": "23 KB",
6666
"name": "Elements: Dialog"
6767
},
6868
{
6969
"path": "dist/elements.js",
7070
"import": "{ defineRekaElements, rekaElementFamilies }",
71-
"limit": "45 KB",
71+
"limit": "73 KB",
7272
"name": "Elements: all supported families"
7373
},
7474
{

‎packages/core/src/Combobox/ComboboxContentImpl.vue‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,8 @@ const pickedProps = computed(() => {
6868
const { present: _, ...forwardedProps } = props
6969
return forwardedProps
7070
}
71-
else {
72-
return {}
73-
}
71+
// Inline, the content is a plain `Primitive`: it still takes `as` / `asChild`.
72+
return { as: props.as, asChild: props.asChild }
7473
})
7574
7675
const forwardedProps = useForwardProps(pickedProps)

‎packages/core/src/Combobox/ComboboxGroup.vue‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,19 @@ export const [injectComboboxGroupContext, provideComboboxGroupContext]
1414
</script>
1515

1616
<script setup lang="ts">
17+
import { reactive } from 'vue'
1718
import { ListboxGroup } from '@/Listbox'
1819
1920
const props = defineProps<ComboboxGroupProps>()
2021
const id = useId(undefined, 'reka-combobox-group')
2122
22-
const context = provideComboboxGroupContext({
23+
// Reactive: the label sets `labelId` once it sets up, and the group's
24+
// `aria-labelledby` follows, whenever that is (a label rendered later, or one
25+
// that is its own custom element).
26+
const context = provideComboboxGroupContext(reactive({
2327
id,
2428
labelId: '',
25-
})
29+
}))
2630
2731
// `ListboxGroup` hides itself (`hidden`, still mounted) while the filter leaves none of its items.
2832
const { forwardRef, expose } = useForwardElement()

‎packages/core/src/Select/SelectContentImpl.vue‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,11 @@ const positionProps = reactiveOmit(props, 'loop')
167167
const pickedProps = computed(() => {
168168
if (props.position === 'popper')
169169
return positionProps
170-
else return {}
170+
// Item-aligned, the content is a plain `Primitive`: it still takes `as` / `asChild`.
171+
return { as: props.as, asChild: props.asChild }
171172
})
172173
173-
const forwardedProps = useForwardProps(pickedProps.value)
174+
const forwardedProps = useForwardProps(pickedProps)
174175
175176
provideSelectContentContext(contentContext)
176177

0 commit comments

Comments
 (0)