Skip to content

[menu] Limit WebKit selection state to focused filter input - #5868

Merged
jjenzz merged 12 commits into
mui:masterfrom
jjenzz:codex/menu-webkit-selection-focus
Oct 6, 2026
Merged

jjenzz merged 12 commits into
mui:masterfrom
jjenzz:codex/menu-webkit-selection-focus

Conversation

@jjenzz

@jjenzz jjenzz commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Safari VoiceOver was announcing a filterable menu item as selected and with an incorrect count while navigating on my older operating system (see the recording below). We originally added aria-selected to support arrow-key navigation in Safari only, but it was also being applied when they used their VoiceOver keys.

This change exposes aria-selected only on the highlighted item while its owning filter input has focus so VO-key navigation is not broken. It removes the attribute on blur, including when focus moves into a filterable submenu. Plain menus and other browser engines continue without this selection state.

We recognize that aria-selected is not a valid state for menuitem, so this ensures a narrow compatibility workaround, not a recommended ARIA pattern: it was the simplest targeted fix we found for arrow-key navigation with Safari and VoiceOver. The focus and WebKit guards limit where the attribute appears.

Validation: pnpm test:jsdom MenuFilterRoot --no-watch, pnpm test:chromium MenuFilterRoot --no-watch, pnpm typescript, pnpm eslint, pnpm stylelint, and pnpm prettier.

CleanShot.2026-10-02.at.10.38.41.mp4

@pkg-pr-new

pkg-pr-new Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@5868
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@5868
    

commit: 68c225f

@code-infra-dashboard

code-infra-dashboard Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+92B(+0.02%) 🔺+21B(+0.01%)

Details of bundle changes

Performance

Total duration: 484.43 ms +31.32 ms(+6.9%) | Renders: 76 (+0) | Paint: 890.58 ms +56.39 ms(+6.8%)

Test Duration Renders
Select mount (200 instances) 70.03 ms 🔺+15.46 ms(+28.3%) 3 (+0)
Select open (500 options) 36.77 ms 🔺+10.54 ms(+40.2%) 14 (+0)
Menu mount (300 instances) 32.43 ms 🔺+8.29 ms(+34.4%) 1 (+0)
Tooltip mount (300 contained roots) 21.86 ms 🔺+4.70 ms(+27.4%) 1 (+0)
Combobox type — 500 items, narrows to ~11 (type "Row 25") 18.32 ms 🔺+3.32 ms(+22.1%) 15 (+0)

10 tests within noise — details

Metric alarms

Test Metric Change
Select mount (200 instances) bench:paint 🔺 +23.73 ms
Select open (500 options) bench:paint 🔺 +24.31 ms
Select open (500 options) bench:paint#select-open 🔺 +24.31 ms
Menu mount (300 instances) bench:paint 🔺 +11.93 ms
Tooltip mount (300 contained roots) bench:paint 🔺 +8.65 ms

…and 2 more metric alarms — details


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

@jjenzz jjenzz added the component: menu Changes related to the menu component. label Oct 2, 2026
@netlify

netlify Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

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

@jjenzz

This comment was marked as resolved.

@jjenzz

jjenzz commented Oct 2, 2026

Copy link
Copy Markdown
Member Author

@claude review low

@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

PR review

No findings.

The change is behaviourally sound on the paths I could verify from source. A few notes on residual risk and verification limits:

  • Hydration guard removal is safe. Dropping useIsHydrating from useMenuFilterRoot does not reintroduce a mismatch: inputFocused is false in createInitialState, so the ariaSelected selector returns undefined during SSR and during the first client render regardless of platform.engine.webkit (which is also false without navigator). Focus only arrives later, from FloatingFocusManager's queued enqueueFocus, which runs after all mount effects.
  • Store routing for submenu triggers is correct. MenuSubmenuTrigger throws unless context.parent.type === 'menu', so the isSubmenuTrigger && rootContext.parent.type === 'menu' branch in useMenuItemCommonProps:64 always resolves to the parent store — matching the old parentWebkitItemSelected semantics. useStoreFast sets didChangeStore when a hook's store identity differs, so subscribing one item hook to a different store than its siblings still subscribes both stores.
  • Unmount cleanup is needed and covered. Removing a focused element fires no blur, so MenuInput.tsx:34 is load-bearing; the new hover-reopen test exercises it. I found no remaining writer of inputFocused that can desync it from real focus (initial focus lands asynchronously, after the effect phase, so even StrictMode's double-invoked cleanup is followed by a real focus event).
  • Behaviour now hinges on the input actually taking real focus. Hover- and touch-opened filterable menus (initialFocus resolves to false) expose no aria-selected on WebKit at all — intended per the description and asserted by the new test. The same is true of a Menu.FilterProvider root that renders no Menu.Input (the shape at MenuFilterRoot.webkit.test.tsx:174-187), whose items previously got the attribute and now never will; that shape is never opened in any test, so it is uncovered either way, and it is already non-functional for virtual navigation.
  • Lost rationale. The comment explaining that aria-selected is invalid on role="menuitem" and therefore scoped to WebKit was deleted with webkitItemSelected and is not re-established anywhere in source — the gate now lives implicitly in the platform.engine.webkit && highlighted argument at the single call site, while the ariaSelected selector in MenuStore.ts:106 is undocumented and named as if it were pure highlight state. A second caller passing a bare highlighted would ship invalid ARIA on Chrome and Firefox.
  • Verification limit. This was a read-only review: I did not run the test suite (the PR tree is treated as data and dependencies are not installed), and the actual Safari/VoiceOver announcement and item count that motivated the change can't be checked here.

Verdict

Approve - no correctness or regression defect survived review; the only loose end is the dropped comment documenting why the attribute is WebKit-only.


🤖 Review generated with Claude Code · Opus 5 (High) · low review depth · 45 turns · 7m50s · $2.71 · run

@jjenzz
jjenzz marked this pull request as ready for review October 2, 2026 14:13
@atomiks

atomiks commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

PR review

One merge-blocking accessibility bug: the new unmount cleanup can clear inputFocused while the input still has focus, which silently turns off the Safari workaround. Otherwise the approach holds up. The hover-reopen test fails without the cleanup, and a local Menu benchmark A/B shows no cost from the extra per-item subscription (the CI perf table is runner noise, since Select moved just as much). Filter menus (#5527) aren't in v1.8.0 yet, so this probably wants the internal label. Safari VoiceOver output itself was not verified here.

Bugs (1)

1. 🔴 Reconcile input focus state when the effect mounts

Location: packages/react/src/menu/input/MenuInput.tsx:34

React.useEffect(() => () => store.set('inputFocused', false), [store]);

The flag is set only by focus/blur events, but the cleanup can run after focus has already landed:

  • <Menu.Input autoFocus /> in Strict Mode: focus sets the flag to true, then Strict Mode's simulated unmount runs this cleanup and resets it to false.
  • Keyed replacement of a focused input: the old input's cleanup runs after the new input has received focus (production too).

Failure scenario: arrowing still moves the highlight and aria-activedescendant, but aria-selected never appears, so Safari arrow-key navigation loses the workaround. Reproduced in jsdom and Chromium with WebKit mocked. Plain autoFocus without Strict Mode is fine.

Fix: read the real focus when the effect mounts. React runs all passive cleanups before passive mounts, so this also runs after the old input's cleanup in the keyed case:

const inputRef = React.useRef<HTMLInputElement>(null);
const ref = useMergedRefs(forwardedRef, inputRef);

React.useEffect(() => {
  // Focus can land before this runs (`autoFocus`, or a keyed replacement whose predecessor's
  // cleanup ran after it), so read it instead of relying on the focus event alone.
  const input = inputRef.current;
  store.set('inputFocused', input != null && activeElement(ownerDocument(input)) === input);
  return () => store.set('inputFocused', false);
}, [store]);

Also pass ref={ref} to FilterDropdownInput, and import activeElement from floating-ui-react/utils. With this change, the MenuFilterRoot suites and repro tests for both cases pass. Add those repros to MenuFilterRoot.webkit.test.tsx, for example:

it('keeps selection state for an auto-focused input in Strict Mode', async () => {
  const { user } = await render(<Test autoFocus />); // `autoFocus` passed through to Menu.Input
  await waitFor(() => expect(screen.getByRole('searchbox')).toHaveFocus());
  await user.keyboard('[ArrowDown]');
  expect(screen.getByRole('menuitem', { name: 'Apple' })).toHaveAttribute('aria-selected', 'true');
});

Verdict

Request changes - a stale focus flag can disable the WebKit selection workaround while the input is focused.


🤖 Review generated with Claude Code

@jjenzz

jjenzz commented Oct 5, 2026 •

Copy link
Copy Markdown
Member Author

Addressed the focus-state race in 636e242.

Menu.Input now tracks which input owns focus. Its callback ref reads actual DOM focus on attachment, so setup after Strict Mode's ref cleanup restores the state even if the focus event happened earlier. Ref cleanup clears the state only when that input still owns it, so an old keyed input cannot clear its replacement's focus state. This removes the passive effect.

I added regression tests for <Menu.Input autoFocus /> in Strict Mode and for replacing a focused keyed input. Both tests failed before the fix and pass afterward.

Verification:

  • pnpm test:jsdom MenuFilterRoot --no-watch (192 passed, 16 skipped)
  • pnpm test:chromium MenuFilterRoot --no-watch (207 passed, 1 skipped)
  • pnpm typescript, focused ESLint and Prettier checks, and git diff --check

Safari VoiceOver output was manually verified.

@jjenzz
jjenzz merged commit f292461 into mui:master Oct 6, 2026
24 checks passed
@jjenzz
jjenzz deleted the codex/menu-webkit-selection-focus branch October 6, 2026 11:00
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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants