Skip to content

[composite] Fix roving focus when items are added or removed - #5447

Merged
atomiks merged 5 commits into
mui:masterfrom
atomiks:codex/fix-tabs-roving-focus-removal
Aug 11, 2026
Merged

atomiks merged 5 commits into
mui:masterfrom
atomiks:codex/fix-tabs-roving-focus-removal

Conversation

@atomiks

@atomiks atomiks commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Adding or removing composite items could leave the roving tab stop on the wrong item, or on no item at all. The highlighted index is stored as a plain number and nothing revalidated it when the item map changed.

Affects Tabs, Toolbar, Toggle Group, Radio Group, Menubar, and Navigation Menu. OTP Field is unaffected because it derives and clamps its active index during render.

Changes

useCompositeRoot now revalidates the highlighted index on every item map change instead of only the first one:

  • Items added or removed around the highlighted one move its index, so the highlight follows it. Before, the tab stop silently moved to a different item and arrow keys resumed from the wrong position, sometimes doing nothing at all.
  • Removing the highlighted item moves the tab stop to the active item, or to the first item that can take focus. Hidden and disabled items are skipped. Before, an index past the end of the list left every item with tabIndex="-1", which dropped the whole widget out of the tab order.
  • When no item can take focus, the index falls back to 0, so the composite regains a tab stop as soon as one of its items becomes focusable again.

This replaces the Tabs-local fix in the first two commits. The same bug affects every composite, so the fallback lives with the shared highlighted index.

@atomiks atomiks added type: bug It doesn't behave as expected. component: tabs Changes related to the tabs component. labels Aug 10, 2026
@pkg-pr-new

pkg-pr-new Bot commented Aug 10, 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@5447
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@5447
    

commit: 508de3e

@code-infra-dashboard

code-infra-dashboard Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+351B(+0.08%) 🔺+137B(+0.09%)

Details of bundle changes

Performance

Total duration: 1,167.40 ms -13.81 ms(-1.2%) | Renders: 76 (+0) | Paint: 1,828.88 ms -19.35 ms(-1.0%)

No significant changes — details


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

@netlify

netlify Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

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

@atomiks atomiks changed the title [tabs] Fix roving focus after tab removal [composite] Fix roving focus when items are added or removed Aug 11, 2026
@atomiks atomiks added scope: all components Widespread work has an impact on almost all components. and removed component: tabs Changes related to the tabs component. labels Aug 11, 2026
@atomiks

atomiks commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@claude review low

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

The review finished without producing a report.


🤖 Review generated with Claude Code · Opus 5 (High) · low review depth · run

@atomiks
atomiks force-pushed the codex/fix-tabs-roving-focus-removal branch from 0fcae59 to d302f00 Compare August 11, 2026 02:22
@atomiks

atomiks commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@claude review low

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

PR review

Nothing here is merge-blocking: the new revalidation in useCompositeRoot is sound for the cases it targets, and the removal/insertion paths converge (no re-entrant map-change loop, and indexOf on the sparse elementsRef array skips holes, so a null ref safely resolves to -1). Three things are worth tightening before merge, all in the new onMapChange branch: disabledIndices is not threaded into the new eligibility checks, the tracked element is never seeded for the default tab stop, and the all-disabled fallback does not deliver what its comment promises. Findings were verified by reading only; no tests were run.

Bugs (3)

1. 🟡 New eligibility checks ignore disabledIndices, so focusable-when-disabled items are skipped

Location: packages/react/src/internals/composite/root/useCompositeRoot.ts:126

const replacement = elements[highlightedIndex];
if (!replacement || isListIndexDisabled(elements, highlightedIndex)) {
  onHighlightedIndexChange(getFallbackIndex(elements));
}

Both new call sites — line 126 and getFallbackIndex (useCompositeRoot.ts:351) — call isListIndexDisabled without disabledIndices, while every pre-existing call in this file passes it (lines 151, 157, 181, 182, 294). That third argument is not just an extra filter; it flips semantics. In floating-ui-react/utils/composite.ts:502-505 the aria-disabled check is gated on !disabledIndices, so omitting it makes every aria-disabled item ineligible. Composite items are aria-disabled (and not natively disabled) by default — see useFocusableWhenDisabled.ts:15,38-47, where focusableWhenDisabled === undefined on a composite item yields aria-disabled only — and both composites that pass disabledIndices rely on that: TabsList.tsx:125 passes EMPTY_ARRAY and ToolbarRoot.tsx:36-45 passes only items that are not focusable when disabled. So the new fallback disagrees with the composite's own definition of a valid tab stop.

Failure scenario: <Tabs.List> with [Tab 0 disabled, Tab 1, Tab 2] and Tab 2 selected/highlighted. Removing Tab 2 sends getFallbackIndex down the list; it skips Tab 0 because it is aria-disabled, and parks the tab stop on Tab 1. Everywhere else in this hook (findNonDisabledListIndex with disabledIndices: []) Tab 0 is a legal roving target, so tabbing into the list now enters at a different tab than arrow navigation and the initial-index logic would pick. The Toolbar equivalent is a Toolbar.Button disabled (focusable when disabled) that the fallback refuses to land on.

Fix: Pass disabledIndices through: isListIndexDisabled(elements, highlightedIndex, disabledIndices) at line 126, and give getFallbackIndex a disabledIndices parameter forwarded to its isListIndexDisabled call.

2. ℹ️ The tracked element is never seeded, so "highlight follows its item" does not apply to the default tab stop

Location: packages/react/src/internals/composite/root/useCompositeRoot.ts:119

const nextIndex = elements.indexOf(highlightedElementRef.current);

highlightedElementRef is only written inside onHighlightedIndexChange (line 102) and in the replacement branch (line 129). On the first map change the hook calls onHighlightedIndexChange only when an ACTIVE_COMPOSITE_ITEM exists or when index 0 is disabled (lines 149-161). Only Radio and Tabs set ACTIVE_COMPOSITE_ITEM (RadioRoot.tsx:134, TabsTab.tsx:199), so for Toolbar, Toggle Group, Menubar, Navigation Menu and bare Composite the ref stays null until the user first focuses or arrows an item.

Failure scenario: An untouched Toolbar renders [A, B, C] with the default tab stop on A. The app then conditionally renders a new first button X. indexOf(null) is -1, so the code takes the replacement path, binds the tab stop to elements[0] === X, and index 0 is kept — the tab stop lands on the newly inserted item, which is exactly the shift the PR sets out to prevent. It only behaves as advertised once the composite has been interacted with.

Fix: Seed highlightedElementRef.current = elementsRef.current[highlightedIndex] ?? null at the end of the default-index branch (or whenever it is null at the top of the revalidation branch), so the tracked element is defined from the first commit.

3. ℹ️ The all-disabled fallback does not "regain a tab stop" unless index 0 is the item that becomes focusable

Location: packages/react/src/internals/composite/root/useCompositeRoot.ts:342

// ... Falls back to index 0 so an all-disabled composite keeps the
// index in range and regains a tab stop as soon as one of its items becomes focusable.

After the fallback returns 0, onHighlightedIndexChange(0) also pins highlightedElementRef to elements[0]. Every later map change then finds indexOf(elements[0]) === 0 === highlightedIndex and returns without re-running the eligibility check, so the claim in the comment only holds when item 0 itself becomes focusable. Composites that pass disabledIndices recover through the useIsoLayoutEffect at lines 166-193; those that do not (Toggle Group, Radio Group, Menubar, Navigation Menu) stay pinned.

Failure scenario: A Toggle Group renders with every item disabled, the highlighted item is removed, the index falls back to 0, and later item 1 is enabled while item 0 stays disabled. A map change fires, but the early indexOf match short-circuits revalidation, so item 0 keeps tabIndex="0" and the group is still not reachable with Tab. (This matches the pre-PR behavior, so it is not a regression — but the comment reads as if it were fixed.)

Fix: Either re-check eligibility of the matched index when it equals highlightedIndex, or reword the comment to say the index is only kept in range and recovery depends on a later index change.

Verdict

Approve after nits — no regression found in the new revalidation path; the only substantive issue is the missing disabledIndices argument, which changes which items the fallback considers eligible in Tabs and Toolbar.


🤖 Review generated with Claude Code · Opus 5 (High) · low review depth · 32 turns · 8m14s · $2.25 · run

@atomiks
atomiks force-pushed the codex/fix-tabs-roving-focus-removal branch from d302f00 to 508de3e Compare August 11, 2026 02:36
@atomiks

atomiks commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@claude review low

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

PR review

The revalidation logic in useCompositeRoot's onMapChange is well-targeted and the new tests pin the important paths (index shift, out-of-range highlight, active-item fallback, hidden/disabled skipping, chained removals). Nothing here is merge-blocking. The one substantive gap is that the "move the tab stop to the active item" behavior only kicks in when the removed item's slot is empty or ineligible, so the same user action produces different tab stops depending on where in the list the removal happened — which does not match what the PR description promises. Reviewed at low effort, so this covers correctness only (no test/simplification/docs pass).

Bugs (1)

1. 🟠 Tab stop only falls back to the active item when the highlighted slot is empty

Location: packages/react/src/internals/composite/root/useCompositeRoot.ts:121

if (nextIndex === -1) {
  // A replacement at the same index can keep the tab stop. Otherwise move it to an
  // eligible item so a missing, hidden, or disabled replacement does not take the
  // composite out of the tab order.
  const replacement = elements[highlightedIndex];
  if (!replacement || isListIndexDisabled(elements, highlightedIndex, disabledIndices)) {
    onHighlightedIndexChange(getFallbackIndex(elements, disabledIndices));
  } else {
    highlightedElementRef.current = replacement;
  }
}

The PR description states that "removing the highlighted item moves the tab stop to the active item, or to the first item that can take focus." In practice that only happens when nothing valid occupies highlightedIndex after the removal — i.e. when the removed item was at (or near) the end of the list. When an item earlier in the list is removed, whatever slides into the vacated index silently inherits the tab stop, and ACTIVE_COMPOSITE_ITEM is never consulted.

For Tabs and RadioGroup the active item is not arbitrary: the ARIA tabs and radio-group patterns both require the selected/checked item to be the group's tab entry point. getFallbackIndex already encodes that preference, but the same-index branch bypasses it.

Failure scenario: <Tabs.Root value={2}> with tabs 0–3. The user focuses Tab 0 (highlight → index 0), then the app removes Tab 0. indexOf(Tab0) is -1, elements[0] is now Tab 1 and is enabled, so the tab stop stays at index 0 on the unselected Tab 1 while Tab 2 is selected. Removing the highlighted last tab in the same list instead lands the tab stop on the selected Tab 2 (this is what TabsList.test.tsx's "can fall back to a tab that is focusable when disabled" and RadioGroup.test.tsx's "moves the tab stop to the checked radio…" exercise). Same user action, position-dependent result; the equivalent <RadioGroup value="b"> case leaves the tab stop on an unchecked radio, so tabbing back into the group focuses the wrong radio.

Fix: In the nextIndex === -1 branch, prefer the active item when one exists and can take focus, and only keep the same-index replacement otherwise — e.g. compute getFallbackIndex(elements, disabledIndices) first and use it when the element at that index carries ACTIVE_COMPOSITE_ITEM. Alternatively, if keeping the replacement is the deliberate choice, adjust the PR description and the comment at line 122 so they don't over-promise.

2. ℹ️ Revalidation is keyed on identity/index only, so in-place hidden or disabled transitions still strand the tab stop

Location: packages/react/src/internals/composite/root/useCompositeRoot.ts:119

const nextIndex = elements.indexOf(highlightedElementRef.current);

When the highlighted element stays in the list but stops being able to hold the tab stop — hidden toggled on, display: none applied, disabled added — indexOf still finds it, nextIndex === highlightedIndex, and the whole branch is a no-op. Nothing else recovers for Tabs: the useIsoLayoutEffect at line 166 bails out because externalHighlightedIndex != null, and toggling an attribute does not re-register the item so flush() never fires onMapChange at all. The composite keeps tabIndex="0" on an unfocusable element and drops out of the tab order — the exact failure mode this PR targets, just reached through a different edit.

Relatedly, the comment on getFallbackIndex ("regains a tab stop as soon as one of its items becomes focusable again") only holds if the item that becomes focusable is index 0; for a composite with internal highlight and no disabledIndices, re-enabling item 2 produces no map change and no effect run, so the tab stop stays parked on the disabled index 0.

Failure scenario: <Tabs.Root defaultValue={1}> with tabs 0–2; the app sets hidden on Tab 1 without unmounting it. Tab 1 keeps tabindex="0" while being invisible, and no visible tab is reachable via Tab.

Fix: Out of scope for this PR as written — this is pre-existing behavior, not a regression. Worth either following up separately or noting in the PR that only mount/unmount transitions are revalidated, so the description's "hidden and disabled items are skipped" is not read as covering in-place changes.

Verdict

Approve after nits - no regressions found; the one 🟠 is an incomplete fallback that contradicts the PR description rather than a break in existing behavior.


🤖 Review generated with Claude Code · Opus 5 (High) · low review depth · 30 turns · 7m51s · $2.13 · run

@atomiks
atomiks marked this pull request as ready for review August 11, 2026 02:46
@atomiks
atomiks merged commit 1d5131c into mui:master Aug 11, 2026
6 checks passed
@atomiks
atomiks deleted the codex/fix-tabs-roving-focus-removal branch August 11, 2026 03:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope: all components Widespread work has an impact on almost all components. type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant