Repository navigation
[listbox] Create the Listbox component - #5115
michaldudak wants to merge 92 commits into
Conversation
commit: |
✅ Deploy Preview for base-ui ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify project configuration. |
Bundle size
PerformanceNo regressions in 36 benchmarks · precise to ±9.1% (±15.1% at worst) · ran 3m 54s · details Check out the code infra dashboard for more information about this PR. |
PR reviewPR #5115 adds a new Bugs (12)1. 🔴
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Import the Vitest globals explicitly, stop shadowing the global `test`, and remove the `flushMicrotasks()` calls that directly follow `await render()`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Use top-level type-only imports, replace the inline `import()` type in the store, and wait for a single condition in the drag-and-drop focus test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Master's API docs generator no longer reads enum data attributes, which dropped the List and Item data attribute tables. Use ESM constants and export the namespaces from the entry point. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
flaviendelangle
left a comment
There was a problem hiding this comment.
I have to changes on my Listbox follow-up that I think we should apply here:
-
Keep group IDs consistent. In
ListboxGroup.tsx, use the suppliedidfor the internal group identifier and render generated IDs on the group element:- const groupId = useBaseUiId() ?? ''; + const groupId = useBaseUiId(elementProps.id) ?? '';
{ role: 'group', + id: groupId, 'aria-labelledby': labelId, },This makes the internal identifier match the rendered DOM ID. It originated from cross-group reordering, so it is a consistency improvement rather than a blocker for plain selection.
-
Keep the custom-shortcuts demo independent of DnD. In both the CSS Modules and Tailwind variants, replace the DnD-shaped
reorder()helper with:function moveItem(items: typeof initialItems, value: string, index: number) { const item = items.find((candidate) => candidate.value === value); if (!item) { return items; } const nextItems = items.filter((candidate) => candidate !== item); nextItems.splice(index, 0, item); return nextItems; }
The existing handlers can then use:
// Move to the beginning with "]". setItems((prev) => moveItem(prev, highlighted.value, 0)); // Move to the end with "[". setItems((prev) => moveItem(prev, highlighted.value, prev.length - 1));
Keep the existing
actionsRef.current?.highlightValue(...)calls. Remove theDragAndDropProviderwrapper and unused drag styling. The follow-up replaces that wrapper withKeyboardReorderProvider, but the custom shortcuts themselves work directly through application state and do not need either provider.
|
Here's the DX review and changes based on conversations with Colm: michaldudak#4. PR description was written by Claude so apologies in advance if it sounds a bit abrupt 😅 Feel free to cherry-pick commits or rewrite things entirely, I didn't write any of the code. |
I agree we should be consistent here. My initial concern was breaking changes, because sometimes we add keyboard behaviour that is optional in the APG and might later need to remove, or change it. But, it does seem common to list these. I don't feel strongly either way either. My main concern is consistency because I noticed sometimes we communicate this information and sometimes we don't. If we don't think it would cause any maintenance cost for us in the long run, then it probably doesn't hurt to add it? |
Keeping it up to date will be easy with AI imo |
…esses Rendered items register their value and disabled state with their position, so the tab stop is found from current positions when the focused item is removed. Holding Option+Space toggles the item once. Space and Enter on the list press an item only while the list holds focus for one. Ctrl/Cmd with the physical A key selects everything only on a layout without Latin letters.
…t disabled values The list reads the rendered items' values when their positions change, on top of what each item records itself, so a list that mounts in a detached container still knows its values. Replacing a selection keeps the selected disabled values in the order they were selected, and looks them up through the index when the list has `items`.
…etitle the range tests
…nd disabled items
Sorry, I meant the maintenance cost of legacy code. If we need to change keyboard behaviour, do we now have legacy code hanging around to maintain because we don't want to introduce a breaking change? Once we document, we're committed haha. Worth considering but perhaps okay. |
| if (shiftKey && multiple && this.resolveAnchor(this.pressAnchor) === null) { | ||
| this.pressAnchor = this.createAnchor(this.parameters.getDefaultAnchor()); | ||
| } | ||
| // A Shift+press always has an anchor, which is the pressed item at the least. | ||
| const anchorIndex = this.resolveAnchor(this.pressAnchor) ?? index; |
There was a problem hiding this comment.
A canceled first Shift+press still seeds the anchor, although the comment at :101 says it doesn't. With multiple, controlled value={['a']} and items a to d:
- Shift+click
cand cancel it inonValueChange. Lines 76-77 have already storeda, the default anchor, aspressAnchor. - Set
valueto['d']from outside. - Shift+click
b. The range isa..b, from an item the user never pressed and that isn't selected anymore, instead ofb..dfrom the new default anchor.
Computing the default anchor locally and storing it after the commit fixes it:
const anchorIndex =
this.resolveAnchor(this.pressAnchor) ??
(shiftKey && multiple ? this.parameters.getDefaultAnchor() : index);
// ...
if (this.parameters.commit(nextValue, REASONS.itemPress, event) === false) {
return;
}
this.pressAnchor = this.createAnchor(keepsAnchor ? anchorIndex : index);A related, lower-priority case: setValue returns true when a controlled parent ignores the change without calling cancel() (ListboxRoot.tsx:113-118), so the anchor moves for a selection that never applied. The Tree waits for the controlled prop before it moves its anchor (TreeSelectionPlugin.ts:553 in #6212). setSelected in #6220 also sets pressAnchor without checking what commit returned.
🤖 Comment generated with Claude
There was a problem hiding this comment.
The main case is fixed in 229e63d as suggested: the default anchor is computed locally and pressAnchor is stored only after the commit goes through, so a canceled Shift+press leaves no anchor behind.
The related case isn't handled: a controlled parent that ignores the change without calling cancel() still moves the anchor. Leaving this open for that.
| "106": "Base UI: ListboxGroupContext is missing. ListboxGroup parts must be placed within <Listbox.Group>.", | ||
| "107": "Base UI: ListboxItemContext is missing. ListboxItem parts must be placed within <Listbox.Item>.", | ||
| "108": "Base UI: ListboxRootContext is missing. Listbox parts must be placed within <Listbox.Root>." |
There was a problem hiding this comment.
#6212 claims 106-108 too, with different messages:
- 106:
Base UI: TreeItemContext is missing. Tree item parts read their item from <Tree.Item> and cannot render outside it. … - 107:
Base UI: the `items` or `defaultItems` prop received an object that is not a valid item collection, … - 108:
Base UI: TreeRootContext is missing. Tree parts read their state from <Tree.Root> and cannot render outside it. …
#6212 also still has its Tree filter error at 105, where master has the Select one, so it needs a rebase anyway. Whichever PR merges second should take master's error-codes.json when resolving the conflict and re-run pnpm extract-error-codes, so its messages get fresh codes.
🤖 Comment generated with Claude
| const selectedValues: any[] = React.useMemo(() => { | ||
| if (multiple) { | ||
| return Array.isArray(value) ? value : EMPTY_ARRAY; | ||
| } | ||
| // `null` is a value an item can have, as in Select, so it's selected while the value is | ||
| // `null`. It's also the value when nothing is selected. | ||
| return value === undefined ? EMPTY_ARRAY : [value]; | ||
| }, [value, multiple]); |
There was a problem hiding this comment.
Flipping multiple at runtime breaks an uncontrolled value. With defaultValue="a", switch multiple to true: 'a' isn't an array, so nothing is selected and the next press starts from []. Going the other way, ['a', 'b'] becomes [['a', 'b']], which matches no item. The Tree converts the uncontrolled selection when multiple changes (TreeSelectionPlugin.ts:206-221 in #6212). Going to multiple it wraps the value, with [] for null, and going back it keeps the first value.
🤖 Comment generated with Claude
There was a problem hiding this comment.
Handled: an uncontrolled value now follows multiple when it changes. Going to multiple wraps the selected value in an array ([] when nothing is selected), and going back keeps the first value. A controlled value is left to the parent, and onValueChange isn't called for the conversion. It will be in the next push.
Ports the split from mui#5115 as is, so whichever PR merges second gets a trivial conflict. `useTypeahead` matches labels it reads with `getLabel` and `getCount`, so a list outside a popup can use it. `usePopupTypeahead` keeps the popup and trigger wiring for Select, Menu and Combobox. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… multiple changes The createItems option that marks disabled items is now isDisabled, matching the naming of other boolean callbacks. An uncontrolled value follows a runtime change of multiple: a single value is wrapped in an array, and an array collapses to its first value.
Adds the Listbox component: a list of options that is always visible, with single, multiple and opt-in multiple selection.
Listbox ships in preview, so the namespace is exported as
ListboxPreview, asOTPFieldPreviewandDrawerPreviewwere. The flat type exports and the data attribute exports carry the same prefix (ListboxPreviewRootProps,ListboxPreviewItemDataAttributesand so on), because the API docs generator matches them to the namespace's parts by name. All of these drop thePreviewpart when Listbox becomes stable.API decisions
The value is a plain list of selected values
valueis a single value, or withmultiplean array holding every selected value. There is no symbolic "everything is selected" state: Ctrl/Cmd+A reports the full array. Measured against a{ type: 'all' }model, the array only loses a few milliseconds after selecting all of 100,000 items, so the simpler shape stays. Each item looks itself up in a set built once per value change.multipleisboolean | 'opt-in', matching themultipleprop of Select, Combobox and ToggleGroup:multiple: a press or Space toggles an item, and Shift selects a range.multiple="opt-in": a press or an arrow key moves the selection to one item, and users hold a modifier key to select more. A touch tap toggles the item, since touch has no modifier keys.Items are described by data, through the
itemspropWithout
items, the renderedListbox.Itemparts are the whole list: each item'svalue,disabledandlabelprops describe it, and its position is its order in the DOM.valueis required onListbox.Item. An explicitvalue={null}is allowed and is selected while the listbox's value isnull, as in Select.itemsonListbox.Rootdescribes every item, including those that aren't rendered. It accepts:Listbox.createItems(data, { getValue, getLabel, getDisabled })for any other data: objects, or an array of groups, each with anitemsarray.getLabelreturns a string, because it drives keyboard text navigation. The collection hasget(value)to map a value back to its item and a typedmap()to render the items in order.There are no other shapes, so each kind of data has one way in. An array of objects or of groups passed straight to
itemsthrows.What follows from that:
getValuereturns. Objects are never selection values.disabledandlabelprops ofListbox.Itemare ignored, and setting either logs a warning in development.items, not its order in the DOM. A renderedListbox.Itemwhosevalueisn't initemslogs an error in development.createItemsis specific to Listbox, like Combobox's. The data is client-side and fully loaded, as with Select; there is no remote or partially loaded data model.getDisabled, not in a function prop on the root. An array of strings or numbers has no disabled items.itemsshould be the same array or collection on every render, defined outside the component or memoized, because a new one makes the listbox read the items again and render every item again.Items are rendered either by you or by the list
Both forms are supported, as in Combobox:
Listbox.Itemparts as children. This works in Server Components.Listbox.List, which calls it with each of the root'sitems, or with each group when they are grouped.Listbox.Collectiondoes the same next to other content, and inside aListbox.Groupthat hasitemsit renders that group's items.The function's argument is not typed from the root's
items, the same limitation as in Combobox.items.map()on acreateItemscollection is the typed alternative.Filtering is external
Listbox has no filtering of its own: filter the data and pass the result to
items. Ctrl/Cmd+A and Shift ranges replace the selection with items from the currentitems, so selected items that a filter has removed are deselected. Selected disabled items are kept, since users can't change them.Keyboard and focus follow the APG listbox pattern
loopFocusprop.preventBaseUIHandler(), and a key that matches no item carries on to handlers outside the list.onItemHighlighted(itemValue, eventDetails)reports the highlighted item, which withitemsmay not be rendered yet.eventDetails.indexis-1when no item is highlighted.Virtualization
With
items, keyboard navigation, text navigation, Ctrl/Cmd+A and range selection reach items that aren't rendered, and the list holds focus for a highlighted item until it renders. The docs show this with TanStack Virtual and the open form. Integration with the Virtualizer from #5466 is a follow-up.Changes outside Listbox
useTypeaheadis split in two.useTypeaheadis now the matching logic alone: it reads labels throughgetLabelandgetCount, reads the active item throughgetActiveIndexwhen a key is pressed, and returnsonKeyDown,endSessionandreset. Listbox uses it directly.usePopupTypeaheadwraps it with what a popup needs (the open state, keeping typed keys from other handlers while open, and one typing session across the trigger and the popup), and Select, Menu and the Combobox trigger now call that. Their behavior is unchanged.isStationaryWebKitPointeris exported fromuseListNavigation, so Listbox items ignore the same phantom mouse moves.useLabelhas alabelsFieldControloption.Listbox.Labelturns it off, because Listbox isn't a Field control and its label would otherwise replace the label of an enclosingField.Root. Field, Select, Combobox and Slider labels are unchanged.Not included
name,required, Field support). Use Select in forms.Listbox.ItemText. An item's text content, or its label from the data, is used for text navigation.Listbox.Item. The docs say so.