The System-Design Question
You are building a search page with thousands of results. The list is virtualized, so only a window of rows exists in the DOM. Each row has a native link to the result and a native Details button. Details open in a modal dialog; from that dialog, a user can delete the result. Search, sorting, deletion, pagination, and detail loading are asynchronous. The selected result is reflected in the URL so Back and Forward can reopen or close details.
How would you design keyboard interaction and focus ownership? Cover loading, success, empty, error, cancellation, deletion of the invoking row, history navigation, virtualization, testing, and production observability.
A Staff-level answer goes beyond calling .focus() after a promise resolves. Define invariants, ownership, races, and a tradeoff between a composite widget and a simpler list.
Start by Separating Three Kinds of State
DOM focus is the browser's current focus target: usually the relevant document.activeElement, governed by the HTML focus model and sequential navigation rules. The HTML Standard defines focusable areas and focus management. Applications track selection and business state separately (HTML focus).
Selection is application state: for example, result ID r-42 is selected, checked, or represented in the URL. Widgets can choose whether selection follows focus. The ARIA Authoring Practices Guide (APG) distinguishes focus from selection and warns that automatic selection can be harmful when it triggers expensive or disruptive work (APG keyboard interface guidance).
Accessibility semantics are the exposed role, name, state, and relationships. A clickable <div> requires deliberate semantics and keyboard handling. aria-selected="true" exposes selection while DOM focus stays where it is. Prefer <a href> for navigation, <button> for actions, form controls for input, and <dialog> where its platform behavior fits. Native controls bring established activation and keyboard behavior; custom ARIA widgets require the author to implement their keyboard model.
Define Ownership Before Writing Handlers
Keep a small focus coordinator at the page boundary. Store identifiers and transition context:
- the stable result ID that invoked details
- the operation and navigation generation that opened it
- the intended fallback if that ID disappears
- whether focus movement was caused by this feature or by the user after the request began.
The component causing a transition owns the outgoing intent. The component rendering the stable destination fulfills it. The dialog owns initial focus and containment. The results surface owns restoration. The router interprets URLs, but requests focus rather than reaching into row DOM.
Match every async response to a request generation or abort signal. A stale details response must not reopen a dialog after Back. A deletion response must not move focus if the user has moved elsewhere. Commit focus only after the destination renders and still represents current state. Use a post-commit hook so the destination has rendered.
During refresh, keep focus on the initiating search or sort control. Mark results busy and expose a concise status update while focus stays on the control. On failure, preserve location and provide a native retry button in normal order. Empty results also retain the initiator unless the product documents another destination.
Keep Focus Inside a Modal with a Keyboard Exit
On open, move focus inside the modal to an appropriate target: often its heading with tabindex="-1" for substantial content, or the least destructive control for a short confirmation. While open, Tab and Shift+Tab cycle through tabbable descendants. The APG pattern recommends Escape to close the dialog. Content outside must actually be inactive, not merely dimmed. The HTML Standard defines inert subtrees and the inert attribute (HTML inert subtrees). The APG modal dialog pattern recommends contained tab navigation and focus placement; this is APG guidance (APG modal dialog pattern).
Valid modal containment has an exit: close, cancel, completion, and usually Escape. A broken trap intercepts Tab globally, loses dynamic controls, leaves focus on a removed node, or offers no keyboard exit. WCAG requires keyboard operation and a way to move focus away using the keyboard, with instructions if that takes a nonstandard exit method (WCAG 2.1.1 Keyboard, WCAG 2.1.2 No Keyboard Trap).
Restore Logical Focus When the Invoker Is Deleted
Closing without deletion restores focus to the invoking Details button by stable ID after asking the virtualizer to materialize that row if necessary. Deletion makes that exact target invalid. The restoration policy must therefore be logical and deterministic:
- Focus the next surviving row's Details button at the deleted row's prior logical index.
- If none exists, focus the previous surviving row's Details button.
- If the list is empty, focus the results heading or empty-state heading made programmatically focusable with
tabindex="-1". - If the results surface is gone because navigation changed, use the destination defined for the new route.
After an optimistic delete, wait for the committed model before restoring focus. If deletion fails, keep focus in the dialog's error or retry path. If it closes before settlement, cancellation and restoration ownership must be explicit.
Tab Order, Arrow Keys, URLs, and Virtualization
My default is a document-like list: each rendered link and button joins ordinary Tab order. Arrow keys retain scrolling expectations. It works with native controls and avoids a custom composite, with more tab stops. Keep the focused row mounted during window updates. If ordinary Tab cannot reach adjacent results predictably, ship paging or a keyboard-accessible load-more control before turning on virtualization. Reduce row actions or use paging before escalating to a grid. A listbox fits when rows are plain selectable options. The APG listbox pattern explains why options cannot support nested links or buttons and points to the grid pattern for interactive rows (APG listbox pattern).
If product research justifies a composite widget, Tab enters and exits the component, while internal arrow keys move its active item. With roving tabindex, DOM focus moves to the active item and only that item participates in the page tab sequence. With aria-activedescendant, DOM focus stays on the composite. Render an owned target before updating its ID reference. Follow the chosen pattern's Home, End, and arrow-key behavior (WAI-ARIA active descendant). Do not mix “Tab through every row” with “arrows also select and navigate” without a clear contract. APG describes the distinction between Tab navigation among components and arrow navigation inside composites; again, that is APG guidance (APG keyboard interface guidance). A combobox is appropriate for a text input with an associated suggestion popup, not as a generic label for the results page (APG combobox pattern).
Virtualization must follow the logical model, not DOM sibling position. Keep an active result ID and logical index; ask the virtualizer to render that item. Move DOM focus or update the active-descendant reference after commit, according to the chosen model. If an item cannot be materialized, apply the same neighbor fallback. Do not use positive tabindex to manufacture an order across recycled nodes. The focus order must preserve meaning and operability (WCAG 2.4.3 Focus Order).
The URL records durable navigation state such as query and open result ID, not ephemeral DOM focus. Back that removes the detail parameter closes the dialog and runs logical restoration. Forward can reopen details after data resolves, but only if the route is current. Deep-linking directly to details has no invoking row, so initial dialog focus works normally and close goes to a defined page destination, such as the results heading—not a fictional invoker.
Focus needs a visible indicator and must not be fully hidden by sticky headers, cookie banners, or the virtualizer viewport (WCAG 2.4.7 Focus Visible, WCAG 2.4.11 Focus Not Obscured (Minimum)). Test the actual scroll and overlay composition; a design-token focus ring alone does not prove either outcome.
Test the Complete Keyboard Journey
At minimum, I would record these cases across supported browser and assistive-technology combinations:
| Scenario | Actions | Expected focus and state |
|---|---|---|
| Open/close details | Tab to Details; Enter; Tab/Shift+Tab; Escape | Initial focus inside; modal containment; return to invoker |
| Delete middle/last/only row | Open; delete; resolve success | Next, previous, or empty heading receives visible focus |
| Delete fails | Delete; reject | Dialog remains coherent; error and retry are reachable |
| Refresh races | Open A; Back; late A response | Dialog stays closed; late response cannot steal focus |
| Virtualized invoker | Open; scroll/recycle row; close | Row is materialized and logical target focused |
| History/deep link | Back, Forward, direct detail URL | Route and dialog agree; documented fallback is used |
| Loading/empty/error | Trigger each async outcome | Initiator retained; no spinner focus; recovery reachable |
| Zoom/overlays | Keyboard at supported zoom with sticky UI | Indicator visible and focused item not fully obscured |
| Composite variant, if chosen | Tab in/out; arrows; Home/End | One entry stop; arrows move active item without accidental route changes |
Automated component tests should assert focus targets, stale-response rejection, neighbor selection, and URL transitions. Browser tests should exercise real Tab, reverse Tab, Enter, Space where native control semantics apply, Escape, and arrows. Use interactive tests for restoration, virtualization timing, and the full journey. Manual checks should include keyboard-only operation, high zoom, forced colors, and representative screen-reader/browser combinations; Report the exact browser and assistive-technology combinations tested.
Production Signals Without Recording Keystrokes
Instrument state transitions as coarse, aggregate events: dialog-open requested/completed, close reason category, restoration target category (invoker, next, previous, empty, route-fallback, failed), stale response discarded, and focus attempt whose target was absent or remained outside the expected modal. Include component/version and broad platform class only where privacy review permits.
Do not capture raw keys, typed query text, result titles, DOM snapshots, accessible names, stable user identifiers, or per-user replay. Apply aggregation, retention, access, and minimum-cohort policies. An illustrative threshold, to be tuned from a reviewed baseline, could alert when restoration failures exceed 1% of eligible closes in a 30-minute window with at least 500 events. Telemetry can miss blocked clients, assistive technology context, and errors before instrumentation loads. Pair it with sampled synthetic journeys and reported user problems.
Example Interview Response
“I would choose the native, document-like list first. The page owns a focus-intent state machine keyed by result ID and request generation; the dialog owns initial focus and modal containment; the committed results view fulfills restoration. Async callbacks cannot focus directly. On close, I restore to the invoker; after deletion, I select next, previous, then the empty-state heading. The virtualizer materializes the logical target before focus, and Back invalidates stale open requests.
“DOM focus, selected result, and ARIA state remain separate. Tab traverses native links and buttons; arrows keep their native behavior unless evidence warrants a fully specified composite pattern. I would validate order, visible and unobscured focus, modal exits, race conditions, history, and recycled rows with the matrix we discussed. In production I would aggregate transition outcomes, never raw keystrokes or content. The tradeoff is extra tab stops versus substantially lower custom-widget complexity; I would pay the latter only after usability evidence shows the former is a material problem.”
Practice your staff engineer interview
Use Interview Copilot to rehearse how you would explain ownership, failure cases, and accessibility tradeoffs.
Start preparing