Skip to content

fix(FocusScope): don't move focus if DOM mutation occurred before any nodes had focus - #2546

Merged
zernonia merged 3 commits into
unovue:v2from
romansp:fix/2506-focus-scope-mutations-observer-preserve-focus
Apr 1, 2026
Merged

zernonia merged 3 commits into
unovue:v2from
romansp:fix/2506-focus-scope-mutations-observer-preserve-focus

Conversation

@romansp

@romansp romansp commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

DOM mutation may be triggered by something unrelated to focus, e.g. class changed on an element, so first check if we even have a previously focused element. Also ensure that captured DOM mutations even have removed nodes before restoring focus.

Add test to ensure focus is restored to container on node removal.

🔗 Linked issue

resolves #2506

❓ Type of change

  • 📖 Documentation (updates to the documentation, readme or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

Did some debugging locally with 1Password extension enabled and noticed that MutationObserver callback might be called even before first element is focused and lastFocusedElementRef is updated. For example, iconify sets class on SVGs. In this case lastFocusedElementRef is still null and container.contains check returns false and focus is move to container.

Additionally updated FocusScope tests as these didn't properly await waitFor results and thus didn't even verify expected results.

📸 Screenshots (if appropriate)

Here's with 1Password extension enabled and mentioned fix. First tabbable element focused correctly each time the dialog is opened.

Screen.Recording.2026-03-25.at.9.56.04.PM.mov

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

Summary by CodeRabbit

  • Bug Fixes

    • Improved focus handling so containers reliably receive and retain focus when previously focused elements are removed; avoids errors when there was no prior focus and skips adjustments if no DOM removals occur.
  • Tests

    • Added regression test for dialogs to autofocus the first tabbable field when opened with a dropdown trigger present.
    • Simplified and hardened focus assertions and added a test for removed-focused-element behavior.

@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

FocusScope's mutation handler now skips when no last-focused element exists and only reacts to mutation records that remove nodes; tests updated with a regression for Dialog+SelectTrigger, a focused-element-removed test, and several simplified focus assertions.

Changes

Cohort / File(s) Summary
FocusScope Tests
packages/core/src/FocusScope/FocusScope.test.ts
Added data-testid="focus-scope", captured focus container, added test asserting focus moves to the FocusScope container when the previously focused tabbable is removed, added Dialog+SelectTrigger regression test, replaced some waitFor wrappers with direct toHaveFocus() assertions, and adjusted test helper to return handleLastFocusableElementBlur.
FocusScope Component
packages/core/src/FocusScope/FocusScope.vue
handleMutations caches lastFocusedElementRef.value, early-returns when it's null, ignores mutation records without removed nodes, uses the cached element for container.contains(...) checks, and focuses the container when the previously focused element was removed.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Trigger as DialogTrigger
    participant Dialog as DialogContent
    participant FocusScope as FocusScope
    participant MutObs as MutationObserver

    User->>Trigger: click
    Trigger->>Dialog: mount & render
    Dialog->>FocusScope: mount (auto-focus)
    FocusScope->>Dialog: focus first tabbable (e.g., input)
    MutObs-->>FocusScope: mutation records
    alt lastFocused is null
        FocusScope-->>FocusScope: ignore mutations
    else mutations contain removed nodes and lastFocused exists
        FocusScope->>FocusScope: use cached lastFocusedElement
        alt lastFocused removed from container
            FocusScope->>Dialog: focus FocusScope container
        else
            FocusScope-->>FocusScope: no action
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped through nodes both lost and found,

When the tabbed one vanished from the ground,
I twitched my whiskers, checked the trace,
If last focus fled its hiding place,
I nudged the scope — soft, steady ground 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: preventing FocusScope from moving focus when DOM mutations occur before any element has been focused.
Linked Issues check ✅ Passed All code changes directly address issue #2506 by preventing unrelated DOM mutations from incorrectly moving focus, with a test ensuring focus restoration when nodes are removed.
Out of Scope Changes check ✅ Passed All changes are narrowly scoped to fixing the FocusScope mutation observer behavior and adding relevant tests; no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/reka-ui@2546

commit: d926701

@romansp

romansp commented Mar 30, 2026

Copy link
Copy Markdown
Contributor Author

Updated: added test case from #2551 to cover #2550. cc @kricsleo

@romansp
romansp force-pushed the fix/2506-focus-scope-mutations-observer-preserve-focus branch from 7071b33 to cd537d9 Compare March 30, 2026 03:14

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
packages/core/src/FocusScope/FocusScope.test.ts (1)

173-182: Consider using waitFor for the focus assertion.

Given that other focus assertions in this file wrap expect(...).toHaveFocus() with waitFor, applying the same pattern here would improve consistency and guard against potential race conditions during dialog mounting and FocusScope initialization.

Additionally, line 180's expect(input).toBeTruthy() is redundant — getByTestId will throw if the element is not found.

♻️ Suggested improvement
     const input = rendered.getByTestId('email-input')
-    expect(input).toBeTruthy()
-    expect(input).toHaveFocus()
+    await waitFor(() => expect(input).toHaveFocus())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/FocusScope/FocusScope.test.ts` around lines 173 - 182, In
the test "should auto-focus the first tabbable element when SelectTrigger is
present", remove the redundant existence assertion for the element returned by
rendered.getByTestId('email-input') and wrap the focus assertion in a waitFor to
mirror other tests — i.e., after clicking the 'Open' button (trigger) await
waitFor(() => expect(rendered.getByTestId('email-input')).toHaveFocus()); this
ensures you reference the same 'email-input' test id and the rendered/getByRole
flow used in this spec.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/core/src/FocusScope/FocusScope.test.ts`:
- Around line 173-182: In the test "should auto-focus the first tabbable element
when SelectTrigger is present", remove the redundant existence assertion for the
element returned by rendered.getByTestId('email-input') and wrap the focus
assertion in a waitFor to mirror other tests — i.e., after clicking the 'Open'
button (trigger) await waitFor(() =>
expect(rendered.getByTestId('email-input')).toHaveFocus()); this ensures you
reference the same 'email-input' test id and the rendered/getByRole flow used in
this spec.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5a566b26-f714-472b-9689-d1509db6f664

📥 Commits

Reviewing files that changed from the base of the PR and between a831a74 and 7071b33.

📒 Files selected for processing (1)
  • packages/core/src/FocusScope/FocusScope.test.ts

… nodes had focus

Fixes unovue#2506.

DOM mutation may be triggered by something unrelated to focus,
e.g. class changed on an element, so first check if we even have a previously focused element.

Also ensure that captured DOM mutations even have removed nodes.

Add test to ensure focus is restored on container on node removal.
@romansp
romansp force-pushed the fix/2506-focus-scope-mutations-observer-preserve-focus branch from aa2bb3e to d818fd5 Compare March 30, 2026 03:30

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
packages/core/src/FocusScope/FocusScope.test.ts (1)

174-182: Expand this regression to include the reopen path from issue #2506.

This currently verifies autofocus only on first open. The reported regression is on subsequent open, so this test can still pass while the original bug reappears.

Suggested test extension
 it('should auto-focus the first tabbable element when SelectTrigger is present', async () => {
   const rendered = render(DialogWithSelect)

   const trigger = rendered.getByRole('button', { name: 'Open' })
   await userEvent.click(trigger)

   const input = rendered.getByTestId('email-input')
   expect(input).toHaveFocus()
+
+  // Reproduce `#2506` path: close and reopen
+  await userEvent.keyboard('{Escape}')
+  await userEvent.click(trigger)
+  expect(input).toHaveFocus()
 })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/FocusScope/FocusScope.test.ts` around lines 174 - 182,
Update the test "should auto-focus the first tabbable element when SelectTrigger
is present" (DialogWithSelect) to exercise the reopen path: after opening via
the Open button and asserting the email-input has focus, close the dialog (e.g.,
using the dialog's close control or pressing Escape), then re-open it with the
same trigger (rendered.getByRole('button', { name: 'Open' })) and assert again
that the element with test id 'email-input' receives focus; ensure you reuse the
same rendered/query helpers (rendered.getByTestId/getByRole) so the second-open
focus check verifies the regression on subsequent opens.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/core/src/FocusScope/FocusScope.test.ts`:
- Around line 174-182: Update the test "should auto-focus the first tabbable
element when SelectTrigger is present" (DialogWithSelect) to exercise the reopen
path: after opening via the Open button and asserting the email-input has focus,
close the dialog (e.g., using the dialog's close control or pressing Escape),
then re-open it with the same trigger (rendered.getByRole('button', { name:
'Open' })) and assert again that the element with test id 'email-input' receives
focus; ensure you reuse the same rendered/query helpers
(rendered.getByTestId/getByRole) so the second-open focus check verifies the
regression on subsequent opens.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3667f573-73ee-4a41-8b28-c84f39ff491a

📥 Commits

Reviewing files that changed from the base of the PR and between aa2bb3e and d818fd5.

📒 Files selected for processing (2)
  • packages/core/src/FocusScope/FocusScope.test.ts
  • packages/core/src/FocusScope/FocusScope.vue
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/FocusScope/FocusScope.vue

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Dialog demo doesn't focus first input on subsequent open by default

2 participants