DEV Community

Tran Manh Dung
Tran Manh Dung

Posted on Edited on

When Automatically Restoring Focus Becomes an Accessibility Bug

Focus management is one of those frontend problems that looks relatively simple until you start dealing with reactive state, component lifecycles, and application-controlled behavior.

A recent fix in Reka UI provides an interesting example of how restoring focus can introduce another accessibility problem if the component doesn't understand who owns that focus.

This article explores the behavior behind issue #1296 and the corresponding pull request #3423.

1. The original problem

Imagine a multiple-selection Listbox containing four options:

Apple
Banana
Cherry
Orange
Enter fullscreen mode Exit fullscreen mode

The application implements custom filtering that removes selected options from the available list.

A keyboard user navigates to Apple and presses Space.

The selection succeeds, and the list becomes:

Banana
Cherry
Orange
Enter fullscreen mode Exit fullscreen mode

However, the DOM element representing Apple has been removed. Since that element previously held keyboard focus, focus falls back to document.body.

The user can no longer continue navigating the options as expected.

The selection state is correct. The rendered output is correct. But the interaction is broken.

This is particularly problematic for keyboard users who expect to select multiple options without repeatedly navigating back into the Listbox.

2. The apparently simple solution

A natural approach would be to detect when the focused option disappears and move focus to another available option.

Something like this:

await nextTick()

if (document.activeElement === document.body) {
  nextAvailableOption?.focus()
}
Enter fullscreen mode Exit fullscreen mode

This is a simplified example, not the actual Reka UI implementation.

At first glance, it seems reasonable. Vue updates the DOM, the selected element disappears, and the component restores focus.

But there is a problem.

document.activeElement tells us where focus currently is. It doesn't necessarily tell us why focus ended up there or whether the component should restore it.

A component needs more information before deciding that it owns the recovery operation.

3. Selection, rendering, and focus are different states

An interactive component manages several related but distinct states:

  • Selection state: which values are selected.
  • Rendered state: which options currently exist in the DOM.
  • Highlight state: which option is considered active for navigation.
  • Browser focus: which element actually receives keyboard events.

These states can change at different times.

Consider the following sequence:

Keyboard interaction
        ↓
Selection changes
        ↓
Application callback executes
        ↓
Vue schedules a DOM update
        ↓
Selected option disappears
        ↓
Focus recovery executes
Enter fullscreen mode Exit fullscreen mode

The important detail is that application code can execute during this process.

For example, an application may intentionally move focus to another element after a selection:

function onSelectionChange(value: string[]) {
  selected.value = value
  nextStepButton.value?.focus()
}
Enter fullscreen mode Exit fullscreen mode

If the Listbox subsequently focuses another option without checking whether the application has taken ownership of focus, the component overrides an intentional application decision.

The attempted accessibility fix becomes another accessibility bug.

4. Recovering focus requires evidence of ownership

The approach in Reka UI captures relevant information before applying the selection:

  • The selected DOM element.
  • The currently focused element.
  • The collection of available candidates.
  • The identity of the current selection operation.

After the DOM update, recovery is only attempted when the relevant conditions still hold.

Conceptually, the component needs to establish that:

  1. The selected option originally owned focus.
  2. The selection was accepted.
  3. The selected element was removed.
  4. Focus was actually lost.
  5. Another interaction has not invalidated the recovery operation.
  6. The Listbox is still mounted and eligible to manage focus.

The implementation also checks whether application code moved focus during the selection update.

The important distinction is that losing focus does not automatically authorize a component to take it back.

5. Why using an array index is insufficient

Another interesting problem is identifying the correct option after filtering.

Consider this initial collection:

0: Apple
1: Banana
2: Cherry
3: Orange
Enter fullscreen mode Exit fullscreen mode

The user selects Banana, and application logic removes both Apple and Banana.

The remaining collection becomes:

0: Cherry
1: Orange
Enter fullscreen mode Exit fullscreen mode

If recovery simply uses the previous array index, it may focus Orange rather than Cherry.

The original index no longer represents the intended position in the collection.

Instead, the recovery logic needs to identify surviving options using their logical identity.

Reka UI already supports custom value comparison through its by property. The recovery mechanism uses those existing comparison semantics rather than introducing a separate definition of identity.

This matters when option values are objects that may be recreated during reactive updates.

For example:

const before = {
  id: 2,
  label: 'Banana',
  revision: 0
}

const after = {
  id: 2,
  label: 'Banana',
  revision: 1
}
Enter fullscreen mode Exit fullscreen mode

These are different JavaScript objects, but they can represent the same logical option when identity is determined by id.

DOM identity, object identity, and logical identity are not necessarily the same thing.

6. Asynchronous recovery can become stale

Focus recovery happens after a reactive update, which means the conditions that justified scheduling it may no longer exist when it executes.

The user may have started another interaction. Application code may have changed focus. The entire component may have been unmounted.

The Reka UI implementation uses a selection recovery token to distinguish the current operation from outdated ones.

A simplified illustration:

let recoveryVersion = 0

function scheduleRecovery() {
  const version = ++recoveryVersion

  nextTick(() => {
    if (version !== recoveryVersion) {
      return
    }

    recoverFocusIfStillValid()
  })
}

function cancelRecovery() {
  recoveryVersion++
}
Enter fullscreen mode Exit fullscreen mode

This prevents an older scheduled operation from overriding a newer interaction.

The token does not make the operation valid by itself. It simply helps establish that the operation has not been superseded. The remaining focus and lifecycle conditions still need to be checked.

7. Shared primitives complicate the solution

Reka UI's Listbox behavior is also used by components such as Combobox and Autocomplete.

In those components, keyboard focus may belong to an input while an option is highlighted separately.

Automatically transferring DOM focus to a highlighted option would interfere with typing and keyboard navigation.

This is an example of why a fix inside a shared primitive must consider more than the component where the original bug was reported.

A behavior that is appropriate for a standalone Listbox may be inappropriate for an input-driven component.

The PR therefore preserves input focus ownership and leaves existing virtualized Listbox behavior unchanged.

Its scope is specifically selection-driven option removal, rather than general-purpose focus recovery for every possible DOM mutation.

8. Regression testing the behavior

A single test confirming that focus moves from Apple to Banana would not be sufficient.

The regression coverage in the PR includes several other situations:

Scenario Expected behavior
Selected option is removed Focus moves to a surviving option
Last option is removed Focus moves to a previous available option
Candidate is disabled Candidate is skipped
Option becomes enabled during selection Option can become a recovery candidate
Multiple options disappear Recovery uses logical identity
Selection is canceled Existing focus is preserved
Application moves focus elsewhere Component does not steal focus
Listbox is unmounted Recovery does not run against the removed component
Input owns focus Input retains focus
Object values are recreated Existing value comparison semantics are respected

The PR reports 1,191 passing Chromium browser tests and 4,959 passing unit tests, along with successful type checking, linting, and build validation.

Firefox and WebKit were not tested locally, according to the PR description.

That limitation is worth noting because focus behavior is ultimately browser behavior, not just JavaScript state management.

9. What makes this problem interesting

The original bug appears to be about a missing focus operation.

But the actual problem involves several broader engineering concerns:

  • Establishing ownership before changing shared state.
  • Preserving logical identity across reactive updates.
  • Invalidating asynchronous work when its assumptions become stale.
  • Respecting application-controlled behavior.
  • Protecting existing component contracts when modifying shared infrastructure.

The solution is not simply to call .focus() at the right time.

It is to establish whether calling .focus() is still the correct operation at all.

That's what makes focus management an interesting part of building accessible UI primitives. Sometimes the most important behavior a component can implement is knowing when not to intervene.

References


Disclosure: This article was prepared with AI assistance based on the public issue, pull request, implementation changes, and regression tests. The code examples are simplified illustrations rather than verbatim copies of the implementation.

Top comments (0)