Skip to content

[listbox] Create the Listbox component - #5115

Open
michaldudak wants to merge 92 commits into
mui:masterfrom
michaldudak:listbox-revival
Open

michaldudak wants to merge 92 commits into
mui:masterfrom
michaldudak:listbox-revival

Conversation

@michaldudak

@michaldudak michaldudak commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

Adds the Listbox component: a list of options that is always visible, with single, multiple and opt-in multiple selection.

import { ListboxPreview as Listbox } from '@base-ui/react/listbox';

<Listbox.Root items={fonts} multiple>
  <Listbox.Label>Fonts</Listbox.Label>
  <Listbox.List>
    {(font) => (
      <Listbox.Item key={font.value} value={font.value}>
        <Listbox.ItemIndicator />
        {font.label}
      </Listbox.Item>
    )}
  </Listbox.List>
</Listbox.Root>

Listbox ships in preview, so the namespace is exported as ListboxPreview, as OTPFieldPreview and DrawerPreview were. The flat type exports and the data attribute exports carry the same prefix (ListboxPreviewRootProps, ListboxPreviewItemDataAttributes and so on), because the API docs generator matches them to the namespace's parts by name. All of these drop the Preview part when Listbox becomes stable.

API decisions

The value is a plain list of selected values

value is a single value, or with multiple an 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.

multiple is boolean | 'opt-in', matching the multiple prop 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 items prop

Without items, the rendered Listbox.Item parts are the whole list: each item's value, disabled and label props describe it, and its position is its order in the DOM.

value is required on Listbox.Item. An explicit value={null} is allowed and is selected while the listbox's value is null, as in Select.

items on Listbox.Root describes every item, including those that aren't rendered. It accepts:

  • An array of strings or numbers, each of which is an item's value and label.
  • A collection from Listbox.createItems(data, { getValue, getLabel, getDisabled }) for any other data: objects, or an array of groups, each with an items array. getLabel returns a string, because it drives keyboard text navigation. The collection has get(value) to map a value back to its item and a typed map() 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 items throws.

What follows from that:

  • The selection always holds the items' values: the primitive itself, or what getValue returns. Objects are never selection values.
  • The data is the only source for an item's disabled state and label, so the result of a selection or a text search never depends on which items happen to be rendered. The disabled and label props of Listbox.Item are ignored, and setting either logs a warning in development.
  • An item's position is its position in items, not its order in the DOM. A rendered Listbox.Item whose value isn't in items logs an error in development.
  • createItems is 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.
  • Disabled state lives in the data, through getDisabled, not in a function prop on the root. An array of strings or numbers has no disabled items.
  • items should 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:

  • Open: map over your data and render Listbox.Item parts as children. This works in Server Components.
  • Closed: pass a function to Listbox.List, which calls it with each of the root's items, or with each group when they are grouped. Listbox.Collection does the same next to other content, and inside a Listbox.Group that has items it 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 a createItems collection 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 current items, 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

  • The first selected item, or the first item, is the only tab stop, and Tab returns to it.
  • When the focused item is removed, focus goes to the item that took its position, or to the last item when it was the last one.
  • Arrow keys scroll the list by the smallest amount that reveals the focused item.
  • Focus doesn't wrap at the ends of the list. There is no loopFocus prop.
  • In opt-in mode, the selection follows focus: arrow keys, Home, End and typing move the selection to the item they move focus to. Ctrl+arrows move focus without selecting, and Ctrl+Space toggles the focused item. On macOS, Option replaces Ctrl. Disabled items can receive focus, and the selection stays where it was while focus is on one.
  • Typing moves focus to the next item whose label starts with the typed text. It runs after key handlers passed to the items and the list, which can call preventBaseUIHandler(), and a key that matches no item carries on to handlers outside the list.
  • Escape isn't handled, so a popup or dialog around the listbox closes without the selection changing.
  • Shift+arrows and Shift+click replace the selection with a range from a shared anchor. Shift+Space selects from the anchor to the focused item, and Ctrl/Cmd+Shift+Home or End adds the items up to the first or last one. Disabled items keep their state through all of these.
  • Moving the pointer over an item highlights it. It moves focus only while focus is already in the list, and never in opt-in mode, so hovering can't take focus from another control or change the selection.
  • onItemHighlighted(itemValue, eventDetails) reports the highlighted item, which with items may not be rendered yet. eventDetails.index is -1 when 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

  • useTypeahead is split in two. useTypeahead is now the matching logic alone: it reads labels through getLabel and getCount, reads the active item through getActiveIndex when a key is pressed, and returns onKeyDown, endSession and reset. Listbox uses it directly. usePopupTypeahead wraps 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.
  • isStationaryWebKitPointer is exported from useListNavigation, so Listbox items ignore the same phantom mouse moves.
  • useLabel has a labelsFieldControl option. Listbox.Label turns it off, because Listbox isn't a Field control and its label would otherwise replace the label of an enclosing Field.Root. Field, Select, Combobox and Slider labels are unchanged.

Not included

  • Form integration (name, required, Field support). Use Select in forms.
  • Drag-and-drop reordering and infinite loading.
  • Listbox.ItemText. An item's text content, or its label from the data, is used for text navigation.
  • Interactive content inside items. An option's content is plain text to assistive technology, and the listbox handles key presses on its items, so buttons, links and inputs don't belong in a Listbox.Item. The docs say so.

@pkg-pr-new

pkg-pr-new Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

commit: 4a3e8a4

@netlify

netlify Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 4a3e8a4
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6b09dff5155a9128c2e01b6d
😎 Deploy Preview https://deploy-preview-5115--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@code-infra-dashboard

code-infra-dashboard Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+20.7KB(+3.92%) 🔺+6.39KB(+3.74%)

Details of bundle changes

Performance

No 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.

@atomiks

atomiks commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

PR review

PR #5115 adds a new Listbox component (~8k lines: selection modes, keyboard nav, Pragmatic drag-and-drop, lazy loading, form integration). There is one merge-blocker: itemToStringLabel is a documented public prop that is wired into the store but has no consumer, so it silently does nothing. Beyond that, the notable items are a confirmed wrong-highlight after non-contiguous multi-select reorder, a first-ArrowDown that skips the first option, a duplicate-key form bug, an RTL gap, a stale group-label id, a double tab-stop, and two large-list perf cliffs. The scariest candidates I chased — composite-index vs. DOM-order desync and a Shift+Arrow double-move — are non-issues (composite sorts by compareDocumentPosition and bails on Shift). Verification was static (no test run / profiler).

Bugs (12)

1. 🔴 itemToStringLabel ships as a no-op public API

Location: packages/react/src/listbox/root/ListboxRoot.tsx:414

itemToStringLabel?: ((itemValue: Value) => string) | undefined;

The prop is stored on the Listbox store (store.ts:14,66) and passed through Root, but nothing reads selectors.itemToStringLabel. labelsRef (used by typeahead) is populated only from each item's label prop or rendered text content (via useCompositeListItem). Unlike Combobox — where itemToStringLabel is consumed in ComboboxValue.tsx — Listbox has no consumer.

Failure scenario: A user passes itemToStringLabel={(item) => item.name} expecting object-value typeahead to work; matching still fails unless every Listbox.Item also has an explicit label. The documented prop does nothing.

Fix: Wire it into item label registration with stringifyAsLabel (so typeahead can match object values), or remove the prop and its docs before release.

2. 🟡 Multi-select keyboard reorder highlights/focuses the wrong item for non-contiguous selections

Location: packages/react/src/listbox/item/ListboxItem.tsx:446

const offsetInSelection = selectedIndices.indexOf(resolvedIndex);
const newFirstIdx = moveUp ? firstIdx - 1 : firstIdx + 1;
store.set('activeIndex', newFirstIdx + offsetInSelection);

newFirstIdx = firstIdx ± 1 only equals the moved block's landing index when the selection is contiguous. For a non-contiguous selection the highlight (and restoreFocusAndScroll, which focuses [role="option"][tabindex="0"]) lands on the wrong row. Confirmed by tracing.

Failure scenario: multiple mode, items [0,1,2,3,4]. Toggle-select 1 and 3, focus item 3, Alt+ArrowDown → items move correctly to [0,2,4,1,3] but activeIndex is set to 3 (value 1) while the initiating item is now at index 4. Focus jumps to the wrong item, and a follow-up Alt+Arrow then reorders the wrong item. The contiguous case works.

Fix: After the move, recompute the initiating item's index from the registry: store.set('activeIndex', findItemIndex(valuesRef.current, itemValue, eqFn)).

3. 🟡 First ArrowDown skips the first option

Location: packages/react/src/listbox/list/ListboxList.tsx:50

highlightedIndex: activeIndex ?? 0,

When the list container is focused with nothing highlighted, activeIndex is null so composite is seeded with highlightedIndex: 0 — but no item is actually highlighted/focused. The first ArrowDown advances from the phantom index 0 to index 1 (useCompositeRoot treats nextIndex === highlightedIndex as "already there" and steps forward).

Failure scenario: A keyboard user tabs into a fresh listbox and presses ArrowDown; option 1 is highlighted and option 0 is skipped.

Fix: Report the first item as highlighted on list focus, or pass a sentinel (e.g. null/-1 semantics) so the first forward arrow lands on index 0.

4. 🟡 Duplicate React keys on hidden inputs drop a form value

Location: packages/react/src/listbox/root/ListboxRoot.tsx:280

return <input key={currentSerializedValue} type="hidden" name={name} value={currentSerializedValue} />;

The key is the serialized value, so two selected values that serialize to the same string collide → React drops one input and the form submits fewer values than selected (plus a console warning).

Failure scenario: A controlled value={['a', 'a']} (controlled mode bypasses the reducer dedup), or two distinct objects with a by-id isItemEqualToValue and a non-injective itemToStringValue → one <input> dropped → FormData has one entry instead of two.

Fix: Include the index in the key: key={`${i}-${currentSerializedValue}`}. (The comma-join for serializedValue is not a submission bug — per-value hidden inputs carry submission; the joined string only feeds validity tracking.)

5. 🟡 Horizontal Alt+Arrow reorder ignores RTL

Location: packages/react/src/listbox/item/ListboxItem.tsx:317

const moveUp = (isVertical && event.key === 'ArrowUp') || (!isVertical && event.key === 'ArrowLeft');
const moveDown = (isVertical && event.key === 'ArrowDown') || (!isVertical && event.key === 'ArrowRight');

ListboxList.handleSelectionKeyDown swaps Left/Right for direction === 'rtl' (List.tsx:155-161), but this keyboard-reorder handler does not.

Failure scenario: Horizontal listbox with dir="rtl" and DnD enabled — ArrowLeft reorders the opposite direction from how Shift+Arrow navigates the same widget.

Fix: Mirror the RTL swap: in horizontal RTL, ArrowRight → before/moveUp, ArrowLeft → after/moveDown.

6. 🟡 Group labels leave a stale aria-labelledby

Location: packages/react/src/listbox/group-label/ListboxGroupLabel.tsx:25

useIsoLayoutEffect(() => {
  setLabelId(id);
}, [id, setLabelId]);

Unlike MenuGroupLabel and ComboboxGroupLabel (both return () => setLabelId(undefined)), this effect never unregisters the id.

Failure scenario: A conditional Listbox.GroupLabel unmounts and the parent group keeps aria-labelledby pointing at a removed element.

Fix: return () => setLabelId(undefined);

7. 🟡 Double tab stop: list container and roving item both tabIndex={0}

Location: packages/react/src/listbox/list/ListboxList.tsx:233 + packages/react/src/listbox/item/ListboxItem.tsx:478

The list is permanently tabIndex: disabled ? undefined : 0 and items use roving tabindex (highlighted ? 0 : -1) with real DOM focus (no aria-activedescendant). When an item is highlighted, both the container and that item are in the tab order. Sibling Combobox.List uses tabIndex: -1 (ComboboxList.tsx:76).

Failure scenario: With a highlighted item, Tab into the listbox stops on the container, then on the option — an extra, semantically empty stop.

Fix: Set the container tabIndex={-1} once items can take the roving stop (keep 0 only for the empty-list case); confirm the intended focus model first.

8. 🟡 Typeahead can't cycle on a repeated character and skips the current item

Location: packages/react/src/listbox/list/ListboxList.tsx:85,95

typeaheadStringRef.current += event.key.toLowerCase();
// ...
const startIndex = activeIndex != null ? activeIndex + 1 : 0;

The comment claims "typing the same character repeatedly cycles through matches," but the buffer always appends, so pressing a then a searches for aa and cannot cycle through Apple, Apricot, … Separately, starting at activeIndex + 1 means a growing multi-char buffer can jump away from a still-matching current item.

Failure scenario: Repeatedly pressing the same starting letter stops matching instead of cycling through same-initial options.

Fix: Special-case a single repeated-character buffer to cycle from activeIndex + 1, and start at activeIndex (inclusive) for genuine multi-char searches — or reuse the existing useTypeahead behavior.

9. 🟡 onHighlightChange runs a full querySelectorAll on every store mutation

Location: packages/react/src/listbox/utils/useHighlightChangeNotifier.ts:61 (called from store.subscribe at :116)

const element = listEl?.querySelectorAll<HTMLElement>('[role="option"]')[activeIndex] ?? null;

The subscription fires on every store.set (selection, hover, drag, loading), and resolveHighlightedItem walks all N option nodes before the areHighlightsEqual early-out — even when activeIndex didn't change. O(N) DOM query per mutation, only when onHighlightChange is set.

Failure scenario: A 5k-item listbox with an onHighlightChange handler; holding ArrowDown or rapid hover does a full DOM walk per event.

Fix: Gate on an actual activeIndex change (store.observe('activeIndex', …)) and resolve the element from composite.elementsRef rather than re-querying.

10. 🟡 Every item re-registers with Pragmatic DnD on any reorder

Location: packages/react/src/listbox/utils/useDragAndDrop.ts:60-87 (effect deps include index, itemValue)

The setup useIsoLayoutEffect tears down and re-creates draggable() + dropTargetForElements() whenever index changes; a reorder shifts the index of every item between source and target. The handlers already read live data from refs/store.

Failure scenario: Dragging the first item of a 2k-item list to the bottom re-registers ~2k items synchronously post-drop → visible hitch.

Fix: Read index/itemValue from refs (the component has indexRef) inside the Pragmatic callbacks and drop them from the effect deps.

11. ℹ️ Smaller correctness/realm notes

  • Stale closure index in onClick/onFocus/onMouseMove (ListboxItem.tsx:480,484,525) — only keydown re-resolves via findItemIndex; a click/hover in the window between an optimistic registry reorder and React re-render can act on a stale index.
  • IntersectionObserver uses the global constructor (ListboxLoadingTrigger.tsx:76) instead of ownerWindow(root).IntersectionObserver — wrong realm inside a cross-document iframe/portal (AGENTS.md owner-utilities rule); SSR-safe otherwise.
  • Non-memoized selectors (store.ts) — isSelected does value.some(...) per item, so a toggle in multiple mode is O(N·M) in getSnapshot; createSelectorMemoized would short-circuit on unchanged value.

12. ℹ️ API-design footguns on the new public surface (hard to reverse post-release)

  • value is always Value[], even in 'single' mode (ListboxRoot.tsx:424) — Select/Combobox give a scalar in single mode; the single-select hero demo is forced into defaultValue={['billie-jean']} and consumers read value[0] everywhere.
  • selectionMode: 'single' | 'multiple' | 'explicit-multiple' vs. the library-wide public multiple boolean (Combobox maps it internally); 'explicit-multiple' is undiscoverable by name.
  • onHighlightChange(value, element) exposes a raw HTMLElement positionally, whereas the sibling ships onItemHighlighted(value, eventDetails) with a reason (ComboboxRoot.tsx:127); actionsRef.highlightValue(value, element?) similarly leaks keyed-reconciliation internals.

Tests (2)

1. 🟡 Core public behaviors ship with no test

Several headline behaviors are uncovered, so a regression in any would stay green: multi-select Alt+Arrow reorder (including the non-contiguous case from bug #2), single-item pointer-drag reorder (only multi-drag/canDrop=false/drop-on-self are tested), actionsRef.highlightValue, Escape-to-clear and Ctrl+A toggle-all, autofill onChange resolution, required/form-submission round-trip (incl. a duplicate value, which exercises bug #4), and typeahead reset/wrap/cycle. Gate layout-dependent cases in Chromium via it.skipIf(isJSDOM).

2. 🟡 Split the multi-assertion waitFor

Location: packages/react/src/listbox/drag-and-drop-provider/ListboxDragAndDropProvider.test.tsx:131

await waitFor(() => {
  expect(screen.getAllByRole('option').map((el) => el.textContent)).toEqual([...]);
  expect(screen.getByRole('option', { name: 'b' })).toBe(document.activeElement);
});

AGENTS.md asks for one assertion per waitFor so retries stay scoped. Fix: Use separate waitFor calls for the order and the focus assertions.

Simplifications (4)

1. 🟡 Re-use selectedValueIncludes instead of hand-rolling .some(eqFn)

packages/react/src/internals/itemEquality.ts exports selectedValueIncludes(values, item, comparer) (with null guards), re-implemented at ~5 sites: store.ts:82, ListboxList.tsx:211, ListboxItem.tsx:423, ListboxDragAndDropProvider.tsx:158,168. Fix: Call the helper; several sites can drop their compareItemEquality import.

2. 🟡 Dead policySignature field on the DnD context

Location: ListboxDragAndDropProviderContext.ts:41 + ListboxDragAndDropProvider.tsx:326. Declared and constructed but never read (and it pins canDrag, canDrop in the memo deps). Fix: Delete it.

3. 🟡 Raw setTimeout in restoreFocusAndScroll bypasses the useTimeout lifecycle

Location: packages/react/src/listbox/item/ListboxItem.tsx:347. The code documents why it avoids useTimeout (the item can unmount during a cross-group reorder and a hook timer would be canceled). The trade-off is a real, uncancelable timer that can run post-unmount against stale state (it mostly no-ops against the external store). Fix: Move the scheduler to a root/provider-scoped callback (which doesn't unmount mid-reorder) using useTimeout/afterDomSettle, keeping the cross-group robustness without a raw timer.

4. ℹ️ Dead/duplicated state

  • typingRef (store.ts:49, written in ListboxList typeahead) is never read — remove it, or use it to suppress hover-steal during typeahead (the likely intent).
  • The "iterate values, skip undefined/disabled" predicate (selectAll, Ctrl+A pre-check, DnD multi-drag), the "collect selected indices" loop (Item reorder vs. DnD provider), and the 4× reorderRegistry pass over 4 parallel arrays can each collapse to one shared helper.

Docs (2)

1. 🟡 DnD-context error message is terser than its siblings

Location: packages/react/src/listbox/drag-and-drop-provider/ListboxDragAndDropProviderContext.ts:59 — '… is missing. Use <Listbox.DragAndDropProvider>.' drops the convention the other three Listbox context errors use. Fix: 'Base UI: ListboxDragAndDropProviderContext is missing. Listbox drag-and-drop parts must be placed within <Listbox.DragAndDropProvider>.', then re-run pnpm extract-error-codes (same arg count → update code 99 in place).

2. ℹ️ Smaller doc gaps

  • DnD payload type shapes are not rendered. types.md:321-323 references ListboxDragAndDropItem<Value> and ListboxDragAndDropProviderOnItemsReorderEvent<Value> in the prop table, but only ListboxDragAndDropTargetEdge is rendered (:411). Users can't see that items expose { value, index, groupId, disabled } or that reorder events carry reason. Add those shapes.
  • The substantial multi-select keyboard contract (Shift+Arrow, Ctrl/Cmd+A, Ctrl/Cmd+Shift+Home/End, Escape) is implemented but undocumented on listbox/page.mdx (only Alt+Arrow is mentioned).
  • The "two render cycles" comments (ListboxRoot.tsx:191, useHighlightChangeNotifier.ts:20) understate the actual afterDomSettle mechanism (a macrotask + two animation frames).

Verdict

Request changes — the no-op itemToStringLabel public prop (#1) should be wired up or removed before this new API ships; the multi-select-reorder highlight (#2), first-ArrowDown skip (#3), and duplicate-key form bug (#4) are the next most worth fixing.


🤖 Review generated with Claude Code

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Jul 3, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 14, 2026
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 17, 2026
@github-actions github-actions Bot removed PR: out-of-date The pull request has merge conflicts and can't be merged. labels Sep 21, 2026
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 30, 2026
flaviendelangle and others added 6 commits October 9, 2026 10:21
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>
@github-actions github-actions Bot added PR: out-of-date The pull request has merge conflicts and can't be merged. and removed PR: out-of-date The pull request has merge conflicts and can't be merged. labels Oct 9, 2026

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to changes on my Listbox follow-up that I think we should apply here:

  1. Keep group IDs consistent. In ListboxGroup.tsx, use the supplied id for 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.

  2. 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 the DragAndDropProvider wrapper and unused drag styling. The follow-up replaces that wrapper with KeyboardReorderProvider, but the custom shortcuts themselves work directly through application state and do not need either provider.

@jjenzz

jjenzz commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

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.

@jjenzz

jjenzz commented Nov 24, 2026

Copy link
Copy Markdown
Member

obviously we should be coherent on all the components

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?

@flaviendelangle

Copy link
Copy Markdown
Member

If we don't think it would cause any maintenance cost for us in the long run

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`.
@jjenzz

jjenzz commented Nov 25, 2026

Copy link
Copy Markdown
Member

Keeping it up to date will be easy with AI imo

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.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Nov 25, 2026
@michaldudak
michaldudak marked this pull request as ready for review November 25, 2026 14:10
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Nov 25, 2026
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Nov 26, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Nov 26, 2026
Comment on lines +76 to +80
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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Shift+click c and cancel it in onValueChange. Lines 76-77 have already stored a, the default anchor, as pressAnchor.
  2. Set value to ['d'] from outside.
  3. Shift+click b. The range is a..b, from an item the user never pressed and that isn't selected anymore, instead of b..d from 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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/react/src/listbox/index.ts Resolved
Comment thread docs/src/error-codes.json Outdated
Comment on lines +105 to +107
"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>."

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#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

Comment on lines +79 to +86
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]);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

flaviendelangle added a commit to flaviendelangle/base-ui that referenced this pull request Nov 27, 2026
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>
flaviendelangle added a commit to flaviendelangle/base-ui that referenced this pull request Nov 27, 2026
Ports the labelsFieldControl option verbatim from mui#5115 (229e63d).

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: listbox type: new feature Expand the scope of the product to solve a new problem.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants