react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

Allow customising focus restoration target when `ModalOverlay` trigger element is removed from DOM

Open BlakeSearlSonocent opened this issue 8 months ago โ€ข 1 comments

Provide a general summary of the feature here

Allow customising or disabling focus restoration when a ModalOverlay closes, so consumers can control where focus lands when the original trigger element has been removed from the DOM.

Perhaps there are already patterns to handle this but I could not find any!

๐Ÿค” Expected Behavior?

When a ModalOverlay closes and the element that was focused before it opened is no longer in the DOM, there should be a way to specify a fallback focus target or opt out of automatic restoration. This would prevent focus from falling to document.body.

๐Ÿ˜ฏ Current Behavior

ModalOverlay uses useModalOverlay which sets up a FocusScope with restoreFocus hardcoded to true. When the modal closes, FocusScope tries to restore focus to the previously focused element. If that element has been removed from the DOM, focus falls to document.body.

There is no prop on ModalOverlay or Modal to disable or redirect this behaviour.

This causes a visible focus flicker when consumers try to redirect focus using deferred calls (setTimeout(0) or requestAnimationFrame), since there is always at least one frame where focus sits on body before the deferred call runs. For screen reader users, this also leads to a brief and interrupted announcement of the document.body element.

๐Ÿ’ Possible Solution

Some potential options:

  • Expose restoreFocus as a prop on ModalOverlay. Allowing false would let consumers opt out and manage focus themselves without racing against the default behaviour.
  • restoreFocusTo prop โ€” an element id (or ref but preference for id) that overrides the default restoration target.
  • Fallback behaviour โ€” when the original trigger element is no longer in the DOM, restore focus to an element specified by id instead of letting it fall to body.

๐Ÿ”ฆ Context

We have a confirmation dialog(s) where the triggering button is replaced by a loading state after the user confirms. We need focus to move to a parent container that displays the loading status. Our workaround of using setTimeout(0) in the onClose callback works functionally, but causes a visible single-frame flicker as focus briefly sits at body between FocusScope restoration and our deferred focus call.

Workarounds tried:

  • setTimeout(0) in onClose โ€” works but causes flicker
  • requestAnimationFrame โ€” same flicker
  • useEffect cleanup watching the open prop โ€” same timing issue
  • Focusing before the dialog closes โ€” blocked by the modal's focus trap

Related issues:

  • #2761 โ€” FocusScope loses focus to document.body when focused element is removed (fixed for in-scope case, not modal close)

๐Ÿ’ป Examples

// Option 1: disable restoreFocus
<ModalOverlay isOpen={open} restoreFocus={false}>

// Option 2: specify a fallback target by id
<ModalOverlay isOpen={open} restoreFocusTo="outline-panel">

// Option 3: callback for custom handling
<ModalOverlay isOpen={open} onRestoreFocus={(originalElement) => {
  if (document.contains(originalElement)) {
    originalElement.focus()
  } else {
    document.getElementById('other-element')?.focus()
  }
}}>

๐Ÿงข Your Company/Team

Genio (note-taking and presentation applications)

๐Ÿ•ท Tracking Issue

No response

BlakeSearlSonocent avatar Apr 03 '26 12:04 BlakeSearlSonocent

This isn't only a modal problem. Popover, and so Menu, do the same thing: delete a row from its own "โ‹ฏ" menu, and focus ends up on <body>.

Repro (react-aria-components 1.22.1, Chrome): Tab to "โ‹ฏ", press Enter, then press Enter on Delete. The row is removed, and document.activeElement is <body>. Closing with Escape instead returns focus to "โ‹ฏ" as expected. A DialogTrigger + Modal with a "Confirm" button that removes the row gives the same result.

function Rows() {
  let [rows, setRows] = useState(['Alpha', 'Beta']);
  return rows.map(row => (
    <div key={row}>
      {row}
      <MenuTrigger>
        <Button aria-label={`Actions for ${row}`}>โ‹ฏ</Button>
        <Popover>
          <Menu onAction={() => setRows(r => r.filter(x => x !== row))}>
            <MenuItem>Delete</MenuItem>
          </Menu>
        </Popover>
      </MenuTrigger>
    </div>
  ));
}

Where it happens

  • Overlay always renders <FocusScope restoreFocus>. Modal, ModalOverlay and Popover render Overlay and expose no prop that reaches it.
  • When the scope unmounts, useRestoreFocus waits one frame. If focus is on <body>, it looks for a nodeToRestore that is still connected, walking up the scope tree. If none is found, it tries the first focusable element of an ancestor scope. A top-level overlay has neither, so focus stays on <body>.
  • The react-aria-focus-scope-restore event is dispatched on the restore target only when that target is still connected, so it can't help here.
  • Overlay's disableFocusManagement turns off containment as well, and RAC components don't expose it.

Proposal: widen restoreFocus, the name FocusScope already uses, and pass it through Overlay, Modal, ModalOverlay and Popover. Popover covers Menu, Select, ComboBox and popover dialogs. People using the hooks set it on <Overlay>.

restoreFocus?:
  | boolean
  | RefObject<FocusableElement | null>
  | ((modality: Modality | null) => FocusableElement | boolean | null);
  • true (the default on overlays) keeps today's behaviour.
  • false restores nothing: focus stays where it lands.
  • A ref sends focus to that element on close.
  • A function is called at close time with getInteractionModality(). It returns an element, true for the default, or false for nothing.
<Popover restoreFocus={listRef}>
<Modal restoreFocus={() => (rowStillExists ? true : listRef.current)}>

The target is focused in the same frame FocusScope restores focus in today. That avoids the extra frame on <body> and the race with setTimeout described above.

An explicit target applies only where FocusScope restores focus today: if the user moved focus elsewhere before close, focus stays there.

Prior art: Base UI's finalFocus, and ng-primitives, which shipped the same shape for popover and menu in ng-primitives/ng-primitives#1012.

One question before a PR: should we widen restoreFocus, or add a separate prop (restoreFocusTo)? I'd widen it: with two props, restoreFocus={false} restoreFocusTo={ref} is a contradiction the types can't rule out.

Related: #6765 (the same symptom after deleting a table row, unanswered). #10696 is open and touches the same restore path.

Happy to open the PR once the shape is agreed.

clement-loridan avatar Nov 05 '26 12:11 clement-loridan