Skip to content

[menu] Add highlightItem('first' | 'last' | 'none') imperative action - #4815

Closed
chsmc-ant wants to merge 8 commits into
mui:masterfrom
chsmc-ant:menu-actionsref-setactiveindex
Closed

chsmc-ant wants to merge 8 commits into
mui:masterfrom
chsmc-ant:menu-actionsref-setactiveindex

Conversation

@chsmc-ant

@chsmc-ant chsmc-ant commented May 12, 2026 •

Copy link
Copy Markdown

When a menu is opened programmatically (via controlled open, or MenuHandle.open(), or onOpenChange(true) from a custom interaction that isn't one of Menu.Trigger's built-in open keys), useListNavigation leaves activeIndex as null. This is correct for pointer-driven opens, but for custom keyboard shortcuts it means every item renders with tabindex="-1" and FloatingFocusManager moves focus to the popup container rather than the first item — the user then has to press ↓ once more before arrow navigation works.

This PR adds an imperative highlightItem(target: 'first' | 'last' | 'none') action so callers can ask the menu to highlight an item once it opens:

  • Menu.Root actionsRef — alongside unmount / close:

    const actionsRef = React.useRef<Menu.Root.Actions>(null);
    
    function onCustomKeyDown(event: React.KeyboardEvent) {
      if (event.key === 'ArrowRight') {
        setOpen(true);
        actionsRef.current?.highlightItem('first');
      }
    }
    
    <Menu.Root open={open} onOpenChange={setOpen} actionsRef={actionsRef}>
  • MenuHandle.open(triggerId, highlightItem?) — same values as a second parameter:

    handle.open('my-trigger', 'first');

The requested target is stored as pendingHighlightItem on MenuStore and resolved inside useListNavigation's initial-sync layout effect once the list is populated, using getMinListIndex / getMaxListIndex so hidden items are skipped — the same logic used for the built-in focusItemOnOpen path. useListNavigation then moves DOM focus to the resolved item (for Menu; virtual-focus consumers like Combobox would only update activeIndex).

A Menu.Root.HighlightItem type alias is exported for the 'first' | 'last' | 'none' union.

Preview: https://deploy-preview-4815--base-ui.netlify.app/react/components/menu#controlled-mode-with-multiple-triggers


Earlier revisions exposed a raw setActiveIndex(index) setter and then a focusItem() action; reworked per review to use highlightItem() with directional targets and to cover MenuHandle.open as well.

@code-infra-dashboard

code-infra-dashboard Bot commented May 12, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+687B(+0.15%) 🔺+162B(+0.11%)

Details of bundle changes

Performance

Total duration: 1,269.84 ms +78.47 ms(+6.6%) | Renders: 50 (+0) | Paint: 1,918.54 ms +96.22 ms(+5.3%)

Test Duration Renders
Checkbox mount (500 instances) 123.07 ms 🔺+54.94 ms(+80.6%) 1 (+0)
Dialog mount (300 instances) 59.09 ms 🔺+13.08 ms(+28.4%) 1 (+0)

10 tests within noise — details


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

@netlify

netlify Bot commented May 12, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit c082ad5
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a1722d997fed10008dc9cf3
😎 Deploy Preview https://deploy-preview-4815--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.

@oliviertassinari oliviertassinari added the component: menu Changes related to the menu component. label May 12, 2026
@oliviertassinari oliviertassinari changed the title [Menu] Expose setActiveIndex on Menu.Root actionsRef [menu] Expose setActiveIndex on Menu.Root actionsRef May 12, 2026
@oliviertassinari oliviertassinari changed the title [menu] Expose setActiveIndex on Menu.Root actionsRef [menu] Expose setActiveIndex() on Menu.Root actionsRef May 12, 2026
@oliviertassinari

oliviertassinari commented May 12, 2026 •

Copy link
Copy Markdown
Member

To help the team a bit (and your team on Claude), here is a reproduction that seems to reproduce the problem: https://stackblitz.com/edit/va1fcbzq?file=src%2FApp.tsx (repro based on this demo):

Screen.Recording.2026-05-13.at.00.37.47.mov

It's not clear that this should be solved with a new API; this feels like a bug: I would expect the same behavior regardless of how the menu is open: with a trigger, with the open prop.

For example, in https://mui.com/material-ui/react-menu/, the focus is placed on the first menu item when the menu opens (with the keyboard) but the behavior can be configured with a prop.

Let's wait for team inputs.

@chsmc-ant
chsmc-ant force-pushed the menu-actionsref-setactiveindex branch from 60e54e8 to e1cad93 Compare May 12, 2026 23:09
@chsmc-ant chsmc-ant changed the title [menu] Expose setActiveIndex() on Menu.Root actionsRef [Menu] Always highlight the first item on open May 12, 2026
@chsmc-ant
chsmc-ant force-pushed the menu-actionsref-setactiveindex branch from e1cad93 to 60e54e8 Compare May 12, 2026 23:11
@chsmc-ant chsmc-ant changed the title [Menu] Always highlight the first item on open [Menu] Expose setActiveIndex on Menu.Root actionsRef May 12, 2026
@chsmc-ant

Copy link
Copy Markdown
Author

Thanks @oliviertassinari and good call! I opened #4816 as well so we can compare this approach to that one. Will defer to the team on which they'd prefer.

@oliviertassinari oliviertassinari changed the title [Menu] Expose setActiveIndex on Menu.Root actionsRef [menu] Expose setActiveIndex on Menu.Root actionsRef May 12, 2026
@atomiks atomiks added the type: new feature Expand the scope of the product to solve a new problem. label May 14, 2026
@pkg-pr-new

pkg-pr-new Bot commented May 14, 2026 •

Copy link
Copy Markdown

commit: c082ad5

@atomiks

atomiks commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the PR @chsmc-ant

Makes sense as controlled-opens are assumed to always be pointer-driven, but a keyboard-driven controlled open is also valid in which case the highlight should be set on the first item.

An imperative action also makes more sense than a prop like autoHighlight (which Autocomplete has) since this is a one-shot/event-driven action that probably shouldn't need state.

The only issue is naming: setActiveIndex is quite broad and "active" is more so an internal name as we use highlighted or focus publicly.

I'm also not sure if exposing the index is a good idea, because 1) disabled items should be skipped on initial open, which should pass through the internal logic to skip them, and 2) it's likely hard to keep track of which index is the last item if the controlled open is an ArrowUp for example.

Possible alternative: .focusItem('first' | 'last' | 'none') or .focusItem('start' | 'end' | 'none')

cc: @colmtuite


Side note: in case you need this behavior before release, this technically already works, if hacky:

firstItem.focus();
// or firstItem.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }))

@michaldudak

Copy link
Copy Markdown
Member

We have another imperative API that has the same issue: MenuHandle.open. Whatever solution we land on for the actionsRef, we should also apply it there. I like @atomiks idea with .focusItem('first' | 'last' | 'none'). We could add an optional parameter to the handle's open method: open(triggerId: string, focusItem?: 'first' | 'last' | 'none').

@chsmc-ant chsmc-ant changed the title [menu] Expose setActiveIndex on Menu.Root actionsRef [Menu] Add focusItem('first' | 'last' | 'none') imperative action May 15, 2026
@chsmc-ant

Copy link
Copy Markdown
Author

Thanks for the feedback @atomiks @michaldudak — pushed 974094c which:

  • Replaces setActiveIndex(index) with focusItem('first' | 'last' | 'none') on actionsRef, resolved via getMinListIndex/getMaxListIndex so hidden items are skipped.
  • Adds the same option as a second parameter to MenuHandle.open(triggerId, focusItem?).
  • Exports Menu.Root.FocusItem for the union type.

PR description updated to match. Happy to bikeshed 'first' | 'last' vs 'start' | 'end' if there's a preference.

@atomiks
atomiks force-pushed the menu-actionsref-setactiveindex branch from 3f70508 to d8abaf8 Compare May 18, 2026 05:17
pendingFocusItem,
onPendingFocusItemChange() {
store.set('pendingFocusItem', null);
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Folded this into useListNavigation as it removes the duplicate effect, and AriaCombobox will likely want this behavior as well: #4745

@atomiks
atomiks force-pushed the menu-actionsref-setactiveindex branch from d8abaf8 to 77d7be1 Compare May 18, 2026 05:28
@atomiks

atomiks commented May 18, 2026

Copy link
Copy Markdown
Contributor

I think .highlightItem() is likely a better term for this, because the public API is about the highlighted state, even though focus is in sync with it. And AriaCombobox doesn't use DOM focus, so highlight makes more sense if this is to be added there — @michaldudak

@chsmc-ant

Copy link
Copy Markdown
Author

thanks @atomiks happy to go ahead and implement that rename if you think it's the right approach

@chsmc-ant
chsmc-ant requested a review from aarongarciah as a code owner May 19, 2026 14:44
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 25, 2026
@colmtuite

Copy link
Copy Markdown
Contributor

Hey @chsmc-ant 👋 Apologies for jumping in at the last minute here, but I'm curious about this API.

It seems that this might be solvable already with the detached triggers API?

Also, I'm struggling to imagine a use case where you might want to highlight the last item? Pressing up/down on an isolated trigger seems like a strange case to me, I'd expect that only Space/Enter would work. And when opening programatically, I'm also struggling to imagine any use case where you'd want to highlight anything other than the first item.

So I'm wondering if this should be handled automatically, somehow. Or whether it's already achievable with our detached triggers API.

Are you able to share more about exactly what your use case is?

@oliviertassinari

oliviertassinari commented May 25, 2026 •

Copy link
Copy Markdown
Member

Side note, I wondered if it would make sense to have a global logic to record the modality in the background, e.g. somethigg like this:

// Keep track of the current interaction modality
let currentModality = 'pointer';

window.addEventListener('keydown', (event) => {
  if (!event.metaKey && !event.altKey && !event.ctrlKey) {
    currentModality = 'keyboard';
  }
}, { capture: true });

window.addEventListener('mousedown', () => {
  currentModality = 'pointer';
}, { capture: true });

window.addEventListener('touchstart', () => {
  currentModality = 'pointer';
}, { capture: true });

or (assuming .matches(':focus-visible') doesn't kill performance)

const AppState = {
  modality: 'pointer' // Default fallback ('pointer' or 'keyboard')
};

window.addEventListener('focusin', (event) => {
  // Use a microtask to let the browser update the pseudo-class state
  queueMicrotask(() => {
    if (event.target.matches(':focus-visible')) {
      AppState.modality = 'keyboard';
    } else {
      AppState.modality = 'pointer';
    }
  });
});

This way, when there is a programmatic change of state from a prop (where there is no access to the event), the focus can default to the modality. Maybe that would solve OG's problem, out of the box.

@atomiks atomiks reopened this May 26, 2026
@chsmc-ant

Copy link
Copy Markdown
Author

@colmtuite thanks for taking a look — happy to share the use case.

Use case: A vertical app sidebar where each row has an associated flyout menu. Desired keyboard UX: → on the sidebar row opens the flyout with the first menuitem highlighted (so ↑/↓ work immediately), ← inside the flyout closes it and returns focus to the row. It's the same cross-orientation pattern Menubar/submenus already implement, but the parent list isn't a Base UI Menubar — it's an existing sidebar with its own routing/selection state, and converting it to a Menubar/Composite parent is a larger refactor than we can take on.

Why detached triggers don't cover it: The row is a Menu.Trigger (in-tree or detached — same result). The trigger's keydown handler only sets useListNavigation's internal keyRef for main-orientation keys (↑/↓ on a vertical menu) plus Enter/Space; → isn't a navigation key for a non-nested vertical menu, so keyRef stays null and focusItemOnOpen: 'auto' falls through to focusing the popup. MenuHandle.open(triggerId) is purely programmatic and never touches the keydown path, so it lands in the same place. Either way we end up writing a custom → handler that opens the menu and then needs a way to say "and highlight the first item" — which is what this PR adds.

On 'last': Agreed it's not needed for our case — we only use 'first'. It's there for symmetry with the existing ↑-on-trigger → last-item behaviour, per @atomiks's original suggestion. Happy to drop it and ship 'first' | 'none' if you'd rather keep the surface minimal.

On handling it automatically: Would love that. @oliviertassinari's modality-tracking idea would make this zero-config for the common case. This PR was scoped as the minimal escape hatch that doesn't commit to a heuristic; if the team would rather pursue auto-detection instead, happy to close this in favour of that (or land this now and treat auto-detection as a follow-up that makes the explicit call unnecessary in most cases).

@chsmc-ant
chsmc-ant force-pushed the menu-actionsref-setactiveindex branch from c555d20 to c082ad5 Compare May 27, 2026 16:59
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 27, 2026
@atomiks

atomiks commented May 29, 2026

Copy link
Copy Markdown
Contributor

@chsmc-ant thanks for the explanation. Would users know → works in that pattern if it's not a menubar? Or is there an ARIA pattern you're using that lets AT know it's menubar-like with keyboard actions?

On @oliviertassinari's point: this seems interesting. I wonder if :focus-visible can work instead on the .Popup element so we can automatically know if it was pointer- or keyboard-opened as the browser should track the modality via that state for us. That would more cleanly solve this issue than adding an imperative escape hatch.


On the (original) implementation:

I'm okay with ditching 'last' until an actual use case comes up instead of adding it just for symmetry.

I also think, for future-proofing/clarity, we should make handle.open(id, ...) take an object with highlightItem as the only parameter (for now).

So the API looks like:

  • actionsRef.current?.highlightItem('first' | 'none')
  • handle.open('id', {highlightItem: 'first' | 'none'})

But again, maybe :focus-visible checking is a better solution for this

@chsmc-ant

Copy link
Copy Markdown
Author

@atomiks

Would users know → works in that pattern if it's not a menubar? Or is there an ARIA pattern you're using that lets AT know it's menubar-like with keyboard actions?

They don't need to — → isn't the accessible path, it's an additive shortcut. The sidebar row is a Menu.Trigger, so it already gets aria-haspopup="menu" + aria-expanded from Base UI; screen readers announce "menu button, collapsed" and AT users open it with Enter/Space, which Base UI already handles correctly (first item focused via the built-in keyRef path). That flow is unchanged.

The → binding is a supplementary shortcut for sighted-keyboard / power users, mirroring the convention from native vertical-nav UIs (macOS Finder sidebar, VS Code Explorer, Slack channel list) where → enters and ← backs out. WAI-ARIA APG's Disclosure Navigation Menu pattern explicitly calls out optional arrow-key support that supplements (not replaces) the standard Tab/Enter interaction, without requiring menubar semantics — that's the model here. So no special role is advertising →; aria-haspopup covers AT, and → is just there for users who try it by muscle memory.

maybe :focus-visible checking is a better solution for this

I'd be happy if it were — it'd cover the → case nicely. The bit I'm less sure it covers is fully-detached opens like handle.open('id') from a command palette / global hotkey, where there's no focused trigger element for the browser to carry modality from; the popup mounts fresh and :focus-visible on it would depend on whatever the last interaction in the document happened to be. The imperative escape hatch is unambiguous there. Not opposed to exploring the heuristic though — they're not mutually exclusive.

ditching 'last' / handle.open(id, { highlightItem }) object param

Both sound good to me — happy to push those changes if we're going ahead with the imperative API.

@oliviertassinari

oliviertassinari commented May 31, 2026 •

Copy link
Copy Markdown
Member

The imperative escape hatch is unambiguous there. Not opposed to exploring the heuristic though — they're not mutually exclusive.

Some historical context: We had this in Material UI for a while (at the time where :focus-visible had no enough browser support). The logic was here: https://github.com/mui/material-ui/blob/v5.11.0/packages/mui-utils/src/useIsFocusVisible.ts. We adopted it from: https://github.com/WICG/focus-visible. On the bundle size cost, it might be too high for this path to be viable.

Oops, closed by mistake, wrong button on my phone.

@atomiks

atomiks commented May 31, 2026

Copy link
Copy Markdown
Contributor

We already use matchesFocusVisible internally which checks the native CSS :focus-visible selector, which you can use once the popup receives focus

Suggestion: try adding this to the floating props in useListNavigation to see if it acts how you'd expect from a UX perspective (instead of the imperative API when testing)

onFocus(event) {
  const target = getTarget(event.nativeEvent) as Element | null;

  if (
    focusItemOnOpenRef.current === 'auto' &&
    open &&
    store.select('activeIndex') == null &&
    keyRef.current == null &&
    target === event.currentTarget &&
    matchesFocusVisible(target)
  ) {
    indexRef.current = getMinListIndex(listRef, disabledIndicesRef.current);
    onNavigate(event);
  }
}

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Jun 15, 2026
@oliviertassinari
oliviertassinari requested a review from jjenzz as a code owner June 27, 2026 20:50
@github-actions

Copy link
Copy Markdown

This pull request has been inactive for 30 days. Please remove the stale label or leave a comment to keep it open. Otherwise, it will be closed in 15 days.

@github-actions github-actions Bot added the stale Inactive for 7 days (issues) or 30 days (PRs); closed after 5 or 15 more days if no update. label Oct 26, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been closed due to 15 days of inactivity after being marked stale.

@github-actions github-actions Bot closed this Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: menu Changes related to the menu component. PR: out-of-date The pull request has merge conflicts and can't be merged. stale Inactive for 7 days (issues) or 30 days (PRs); closed after 5 or 15 more days if no update. 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.

6 participants