Skip to content

[combobox][menu][select] Add highlightItem imperative action - #5586

Merged
michaldudak merged 11 commits into
mui:masterfrom
michaldudak:claude/base-ui-issue-5146-009a11
Sep 23, 2026
Merged

michaldudak merged 11 commits into
mui:masterfrom
michaldudak:claude/base-ui-issue-5146-009a11

Conversation

@michaldudak

@michaldudak michaldudak commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

Closes #5146
Supersedes #4815

Autocomplete and Combobox navigate the list with the arrow keys, but there is no way for an app to drive the highlight itself — so bindings like Ctrl+N/Ctrl+P (cmdk's defaults, and also standard macOS text navigation) can't be added in application code. Rather than adding vim-specific keys to the library, this adds the missing primitive.

API

highlightItem(target) on the actionsRef of Combobox.Root, Autocomplete.Root, Menu.Root and Select.Root:

const actionsRef = React.useRef<Autocomplete.Root.Actions>(null);

<Autocomplete.Input
  onKeyDown={(event) => {
    if (event.ctrlKey && event.key === 'n') {
      event.preventDefault();
      actionsRef.current?.highlightItem('next');
    }
  }}
/>

type HighlightItemTarget = 'next' | 'previous' | 'first' | 'last' | 'none', exported per namespace as <Component>.Root.HighlightItemTarget. No numeric index — indices are unstable under filtering, grouping and virtualization.

Semantics

  • Mirrors the component's main-orientation arrow key while the popup is open.
  • From no highlight, 'next' enters at the first item and 'previous' at the last.
  • 'previous' on the first item wraps to the last item, never back to the input — the method is highlightItem, so landing on the input would be wrong.
  • Wrapping respects each component's loopFocus. Note Select doesn't loop, so it never wraps.
  • No-op while the popup is closed; 'next'/'previous' are no-ops in Combobox grid mode.
  • Programmatic highlights report reason: 'imperative-action' to onItemHighlighted.
  • Menu and Select use real DOM focus, so the action moves focus with the highlight — including on 'none', which hands focus back to the popup rather than stranding it on a now-unhighlighted item.

Implemented once in useListNavigation, so the virtual-focus (Combobox/Autocomplete) and DOM-focus (Menu/Select) components share a single traversal implementation.

Known limitations, deliberately

  • Open-and-highlight is not expressible. setOpen(true); highlightItem('first') in one tick is a no-op, because open is still false at call time. There is no queued/pending highlight.
  • Virtualized lists can be asked to highlight an item that isn't rendered. The shipped virtualized demos now scroll on the 'imperative-action' reason, and the docs say to do the same.

Not included

  • Home/End/PageUp/PageDown list navigation — a separate feature with its own APG questions.
  • Extracting a shared stepListIndex() so highlightItem and commonOnKeyDown don't each implement the traversal maths. Worth doing, but it rewrites arrow-key navigation for every list component in the library and belongs in its own PR.

Demo

https://deploy-preview-5586--base-ui.netlify.app/react/components/autocomplete#custom-keyboard-shortcuts

Note on the demo's bindings

The demo binds Ctrl+N/Ctrl+P only. cmdk also maps Ctrl+J/Ctrl+K, but Ctrl+K opens the search on this docs site, so a demo advertising it would not work on the page it ships on.

Testing

22 new tests, including the issue's actual scenario (Ctrl+N/P driving an Autocomplete end to end, plus Ctrl+J/K to show the action doesn't care which key drives it), the wrap-to-last rule, loopFocus on and off, grid no-ops, closed-popup no-ops, the 'imperative-action' reason, and DOM-focus handoff on 'none' for Menu and Select.

🤖 Generated with Claude Code

@pkg-pr-new

pkg-pr-new Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

commit: e08ac06

@michaldudak michaldudak added component: select Changes related to the select component. component: menu Changes related to the menu component. type: new feature Expand the scope of the product to solve a new problem. component: autocomplete Changes related to the autocomplete component. component: combobox Changes related to the combobox component. labels Aug 28, 2026
@netlify

netlify Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit e08ac06
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6ab3a365efe59400086b5654
😎 Deploy Preview https://deploy-preview-5586--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 Aug 28, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+856B(+0.19%) 🔺+261B(+0.17%)

Details of bundle changes

Performance

Total duration: 1,149.10 ms -133.35 ms(-10.4%) | Renders: 76 (+0) | Paint: 1,913.31 ms -182.12 ms(-8.7%)

Test Duration Renders
Combobox type — 500 items, narrows to ~11 (type "Row 25") 37.06 ms 🔺+7.57 ms(+25.7%) 15 (+0)
Combobox open — 500 items 29.30 ms 🔺+5.34 ms(+22.3%) 4 (+0)
Tabs mount (200 instances) 204.11 ms ▼-60.48 ms(-22.9%) 3 (+0)
Popover mount (300 instances) 41.24 ms ▼-11.73 ms(-22.1%) 1 (+0)

11 tests within noise — details

Metric alarms

Test Metric Change
Combobox type — 500 items, narrows to ~11 (type "Row 25") bench:paint#combobox-open 🔺 +11.82 ms
Combobox type — 500 items, narrows to ~11 (type "Row 25") bench:paint 🔺 +11.82 ms

Check out the code infra dashboard for more information about this PR.

@michaldudak
michaldudak force-pushed the claude/base-ui-issue-5146-009a11 branch 2 times, most recently from 5b388d4 to 761c869 Compare August 28, 2026 10:00
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 28, 2026
@michaldudak
michaldudak force-pushed the claude/base-ui-issue-5146-009a11 branch from 761c869 to 0c06fc2 Compare August 28, 2026 10:21
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 28, 2026
@michaldudak
michaldudak force-pushed the claude/base-ui-issue-5146-009a11 branch 2 times, most recently from 0881005 to 4c28121 Compare August 28, 2026 11:00
@jjenzz

jjenzz commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

i haven't looked to closely so i'll leave it to you to decipher if these make sense haha

DX review

The navigation primitive is useful, but it currently inherits legacy popup-lifecycle behavior that applications cannot opt out of independently. The public contract needs a v2-safe direction before release.

Findings (3)

1. 🔴 actionsRef couples navigation to manual popup lifecycle ownership

Source: AriaCombobox.tsx:974, SelectRoot.tsx:314, AutocompleteRoot.test.tsx:2740

Problem:

Autocomplete, Combobox, and Select disable automatic unmounting whenever actionsRef exists. Adding highlightItem to that ref makes navigation and popup lifecycle ownership inseparable. The new test confirms that closing leaves the listbox mounted and suppresses onOpenChangeComplete(false) until the consumer calls unmount().

User scenario:

A design-system CommandPalette installs an internal action ref for Ctrl+N/Ctrl+P. Every application using that wrapper now also inherits manual animation timing and unmount cleanup. The wrapper cannot preserve the application's ordinary popup lifecycle without reimplementing close completion, and the completion callback it would normally use is itself suppressed.

Decision needed:

Could we settle the mount-ownership contract before adding highlightItem to this ref? Moving the fix to [issue #5587](#5587) means the newly documented navigation path ships on behavior that is already scheduled to change.

If the current release can change the existing behavior, I suggest aligning these components with Menu now: actionsRef remains additive, while preventUnmountOnClose() explicitly opts a particular close into manual lifecycle ownership. If that change is not allowed now, highlightItem needs a separate permanent access path that does not inherit the legacy actionsRef behavior.

Please also define the v2 mapping. The replacement navigation path should survive unchanged, while any legacy mount-ownership behavior needs a tooling-visible migration signal before removal.

2. 🟠 autoHighlight="always" makes highlightItem('none') report a state that never persists

Source: AutocompleteRoot.tsx:256, AriaCombobox.tsx:1116

Problem:

The public action says 'none' clears the highlight. With autoHighlight="always", it synchronously emits an imperative clear and then restores the first item with another reason. Consumers observe a transient unhighlighted value even though the rendered component never remains in that state.

User scenario:

An Autocomplete wrapper keeps the first command highlighted and an application calls 'none' before moving focus elsewhere. Its onItemHighlighted handler first receives undefined, then the first item again, potentially resetting external state or scrolling a virtualizer twice.

Suggested change:

I suggest making 'none' a true no-op under autoHighlight="always", without emitting a transient clear event. That preserves the meaning of “always,” gives configuration clear precedence, and keeps callbacks aligned with observable state. Please document this interaction on the public Autocomplete API and add a test covering the callback sequence.

3. 🟠 Menu documentation assigns manual unmount ownership incorrectly

Source: MenuRoot.tsx:736, popupStoreUtils.ts:589

Problem:

Menu’s new JSDoc says that passing actionsRef disables automatic unmounting. Menu actually continues to unmount automatically unless that close cycle calls preventUnmountOnClose(). The incorrect text is also propagated to Context Menu and submenu API tables.

User scenario:

A consumer follows the documentation and calls unmount() after every Menu close. Automatic close completion may already have unmounted it, causing duplicate completion work; calling it earlier can cut off the exit transition.

Suggested change:

Could we remove the manual-unmount warning from Menu and the generated Context Menu/submenu API docs? Please state that automatic unmounting continues when actionsRef is present and that unmount() is needed only after a close explicitly calls preventUnmountOnClose(). A regression test with actionsRef attached would help keep the documented distinction intact.

What is already sound

  • The value-independent targets avoid unstable numeric indices.
  • The distinct 'imperative-action' reason gives virtualized consumers a reliable scroll signal.
  • The shared traversal implementation and tests cover looping, disabled items, grid behavior, virtual focus, and DOM-focus handoff.

Verdict

Needs product/API decision - Decide whether the existing actionsRef lifecycle semantics may change now or navigation needs an independent, v2-stable access path. CC: @jjenzz


🤖 Review generated with Codex

@michaldudak

Copy link
Copy Markdown
Member Author

Yes, the actionsRef thing must be resolved first. IMO it's a bug (though a fix might be breaking).
I'll take care of #2

@michaldudak
michaldudak force-pushed the claude/base-ui-issue-5146-009a11 branch from 4c28121 to ca947b7 Compare August 28, 2026 11:19
@michaldudak
michaldudak marked this pull request as ready for review August 28, 2026 11:52

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca947b7a18

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


export interface Actions {
unmount: () => void;
highlightItem: (target: HighlightItemTarget) => void;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve assignability of existing actions refs

Making highlightItem required breaks existing consumers that initialize an actions ref with the previously valid shape, such as useRef<Combobox.Root.Actions>({ unmount() {} }); the changes to test/public-types/autocomplete.tsx and combobox.tsx from such initializers to null demonstrate the downstream compilation regression rather than preserving compatibility. The same issue affects the newly required members on Autocomplete, Menu, Context Menu, and Select, so the exported ref type should remain assignable from the prior action shape on a non-major release.

Useful? React with 👍 / 👎.

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.

This follows the precedent set by #5734, which added a required close member to the same Actions interfaces on master; ref initializers with the previous object shape were updated there too. Making highlightItem optional would force every caller into actionsRef.current?.highlightItem?.() for a corner case, so we are keeping it required.

Comment on lines +752 to +754
if (floatingFocusEl && contains(previouslyHighlightedItem, activeEl)) {
cancelQueuedFocusRef.current?.();
floatingFocusEl.focus({ preventScroll: true });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Cancel pending item focus when clearing the highlight

When highlightItem('none') is called after another imperative highlight has committed but before enqueueFocus's animation frame runs, focus is still on the popup, so this condition is false and the queued item focus is not canceled. The pending frame then focuses the now-unhighlighted item, recreating the exact focus/highlight divergence described above and allowing Enter to activate an item that no longer appears highlighted; cancel the queued focus whenever the previous highlighted item exists, before conditionally moving current focus back to the popup.

Useful? React with 👍 / 👎.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 2, 2026
michaldudak and others added 2 commits September 22, 2026 13:20
Adds `highlightItem(target)` to the `actionsRef` of `Combobox.Root`,
`Autocomplete.Root`, `Menu.Root` and `Select.Root`, so apps can bind their own
keyboard shortcuts (Ctrl+N/Ctrl+P, the cmdk aliases Ctrl+J/Ctrl+K) on top of the
built-in arrow keys.

`target` is `'next' | 'previous' | 'first' | 'last' | 'none'`. It mirrors the
main-orientation arrow key while the popup is open, but never lands outside the
list: `'previous'` on the first item wraps to the last one rather than escaping
to the input. Wrapping respects each component's `loopFocus`. It is a no-op
while the popup is closed, and `'next'`/`'previous'` are no-ops in Combobox grid
mode. Programmatic highlights report `reason: 'imperative-action'`.

Closes mui#5146

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…lightItem

mui#5734 decoupled automatic unmounting from `actionsRef`, so the notes,
the demo's manual `unmount()` call and the regression guard that pinned
the old coupling no longer apply. Keep `close` alongside `highlightItem`
on the Combobox and Select actions.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@michaldudak
michaldudak force-pushed the claude/base-ui-issue-5146-009a11 branch from ca947b7 to 01b6637 Compare September 22, 2026 11:25
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 22, 2026
michaldudak and others added 2 commits September 22, 2026 13:38
Adds the new "Custom keyboard shortcuts" sections to the index so
`pnpm docs:validate` passes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Clearing the highlight now cancels a focus move that is still queued for
the next frame and reclaims focus from whichever item holds it, not only
the one the highlight points at. Otherwise a queued focus landing after
the clear re-highlighted the item, and a clear that followed a move in
the same tick left focus on an item that no longer looked highlighted.

Tests: assert the popup receives focus on clear, prove closed-popup calls
are dropped rather than queued, await the open sequence before driving
the highlight, cover the inline cursor after a clear, virtualized targets
beyond the rendered window, entry from the selected Select item, the
`'none'` payload, arrows after an imperative move, and the hook's own
`source` argument and no-op guards.

Docs: explain that a same-event open-and-highlight is dropped, document
where the key handler goes for Menu and Select, state the wrap rule and
the focus handoff on the actionsRef props, describe the `'none'` reason
by its sources, and give the HighlightItemTarget aliases JSDoc.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@jjenzz

jjenzz commented Sep 22, 2026

Copy link
Copy Markdown
Member

PR review all good, DX review incoming...

PR review

No findings.

Targeted tests passed: 42 in jsdom and 45 in Chromium, including focus cancellation and virtualized navigation. The full suite and typecheck were not run.

Verdict

Approve — no actionable correctness, test, simplification, or documentation issues found.


🤖 Review generated with Codex

@jjenzz

jjenzz commented Sep 22, 2026

Copy link
Copy Markdown
Member

DX review

The navigation action is a useful, lasting addition. No blocking API or composition issues found; one documentation correction remains.

Findings (1)

1. 🟡 Combobox documents an unsupported autoHighlight value

Source: [ComboboxRoot.tsx:130](

* `'next'`/`'previous'` do nothing when `grid` is enabled. `'none'` does nothing under `autoHighlight="always"`, which by definition
)

Problem:

The new actionsRef documentation says 'none' does nothing under autoHighlight="always". That mode belongs to Autocomplete; Combobox’s public autoHighlight prop accepts only boolean. The same misleading guidance appears in its generated API documentation.

User scenario:

A developer configuring Combobox follows this guidance to keep an item highlighted, but TypeScript rejects the documented value.

Suggested change:

Could we remove the autoHighlight="always" caveat from Combobox’s public JSDoc and regenerate its API docs? Keep it in Autocomplete, where that mode is supported.

What is already sound

  • The action supplies missing navigation control. Existing highlight callbacks observe changes; they cannot request relative traversal.
  • Applications own shortcut bindings while Base UI owns item traversal and focus. This avoids baking product-specific keyboard policies into props.
  • Wrappers can retain their own action ref and expose it through ordinary React imperative-handle forwarding.
  • The closed-popup, grid, wrapping, and clearing behavior is explicit. This additive API can survive unchanged through v2 without compatibility modes.

The earlier targeted jsdom and Chromium results still apply to this unchanged PR head. Installed-package type generation was not verified.

Verdict

Approve after nits — correct the Combobox documentation; the API is coherent.


🤖 Review generated with Codex

michaldudak and others added 2 commits September 22, 2026 14:29
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ctionsRef docs

Combobox's autoHighlight prop is boolean only; the 'always' mode belongs to
Autocomplete, whose docs keep the note.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
michaldudak and others added 4 commits September 22, 2026 15:04
Combobox drives grids with a horizontal main orientation, so ArrowRight
and ArrowLeft already step through the cells in DOM order and cross row
boundaries. `'next'` and `'previous'` now do the same instead of being a
no-op, which drops the special case and its caveats.

Bundle size: every entry that includes the hook shrinks by 33 B parsed
and 10-17 B gzipped; nothing grows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
An inline grid Combobox with buttons and shortcuts for every
highlightItem target, plus a log of onItemHighlighted events, to
exercise DOM-order stepping across row boundaries alongside the
arrow keys.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The grid navigator returns the unchanged index for keys it does not
handle, and the key handler treated any non-null result as a
navigation, so every keydown in a grid re-emitted onItemHighlighted
for the current item, and ArrowLeft/ArrowRight reported it twice.

Also type the experiment's log entry as unknown, which is what
onItemHighlighted hands an untyped Combobox.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ntract to the reference

Per review: the Autocomplete and Combobox pages now introduce the
action in a couple of sentences around the demo, the virtualization
sections carry the scroll-on-'imperative-action' note, and the full
contract (sequential traversal including grids, wrapping, clearing,
the closed-popup rule and the reported reason) lives in the actionsRef
JSDoc on every root.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 23, 2026
Resolves the SelectRoot import conflict with mui#5589, which removed the
root props context: keep the HighlightItemTarget import alongside
master's reduced context import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 23, 2026
@michaldudak
michaldudak merged commit 9d150e4 into mui:master Sep 23, 2026
24 checks passed
@michaldudak
michaldudak deleted the claude/base-ui-issue-5146-009a11 branch September 23, 2026 10:09
michaldudak added a commit to michaldudak/base-ui that referenced this pull request Sep 23, 2026
Resolves conflicts with mui#5586 (highlightItem) and mui#5734 (unmount decoupling):
- AriaCombobox: keep scrollItemIntoView alongside the new onNavigate source/inline handling;
  drop the now-unused useOpenChangeComplete import.
- Combobox virtualized demos keep the built-in Virtualizer; the `imperative-action` scroll
  handling moves to the TanStack demos, and the docs note to the third-party section.
- Add `imperative-action` to ListHighlightReason so imperative highlights scroll the
  built-in virtualizer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
michaldudak added a commit to michaldudak/base-ui that referenced this pull request Oct 7, 2026
The grid guard in useListNavigation is a standalone fix that mui#5586
shipped, not part of highlightItem. Without it, keys the grid does not
handle re-report the current highlight, which corrupts inline
Autocomplete input in grid mode.

Also keep three onItemHighlighted tests from mui#5527 that cover live
syncHighlightedItem behavior, now set up through keyboard and hover.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: autocomplete Changes related to the autocomplete component. component: combobox Changes related to the combobox component. component: menu Changes related to the menu component. component: select Changes related to the select component. 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.

[autocomplete] Support vim-style Ctrl+N/Ctrl+P keyboard navigation

2 participants