feat(ui): harden modal dialogs, add afterModalsClosed

Re-show a natively closed dialog only when its consumer answered
'kept'; returnFocus; ignore a held Escape; Dialog honours reduced
motion; useBeforeUnload extracted; focusRow reports found only when
the row holds focus.
This commit is contained in:
bchanot committed 2026-11-13 17:57:47 +01:00
1 parent 36c6eb3fea
commit 553a0e57b2
6 files changed
+336 -30

No files matched your search

+13 -7
View File
@@ -1,12 +1,14 @@
import { useId, type ReactNode } from 'react'
import { AnimatePresence, motion } from 'motion/react'
import ModalDialog from './ModalDialog'
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import ModalDialog, { type ModalDialogProps } from './ModalDialog'
import { useT } from '@/i18n/useT'
export interface DialogProps {
open: boolean
/** Asked on Escape, the close button and a backdrop click; the dialog leaves when `open` turns false. */
onClose: () => void
onClose: () => unknown
/** Where the focus goes after the close (ModalDialog): a target, or null when a move owns it. */
returnFocus?: ModalDialogProps['returnFocus']
title: string
/** The dialog's message, announced with its name (aria-describedby). */
description?: ReactNode
@@ -29,17 +31,21 @@ export default function Dialog({ open, ...surface }: DialogProps) {
function DialogSurface({
onClose,
returnFocus,
title,
description,
children,
size = 'md',
}: Omit<DialogProps, 'open'>) {
const t = useT()
const reduced = useReducedMotion()
const scale = reduced ? 1 : 0.96
const titleId = useId()
const descriptionId = useId()
return (
<ModalDialog
onClose={onClose}
returnFocus={returnFocus}
labelledBy={titleId}
describedBy={description ? descriptionId : undefined}
className="open:flex items-center justify-center p-3 sm:p-4"
@@ -50,14 +56,14 @@ function DialogSurface({
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
transition={{ duration: reduced ? 0 : 0.15 }}
onClick={onClose}
/>
<motion.div
initial={{ opacity: 0, scale: 0.96 }}
initial={{ opacity: 0, scale }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.96 }}
transition={{ duration: 0.18 }}
exit={{ opacity: 0, scale }}
transition={{ duration: reduced ? 0 : 0.18 }}
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto overscroll-contain rounded-2xl bg-[var(--color-surface)] shadow-xl`}
>
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
+37 -10
View File
@@ -1,3 +1,4 @@
import { useIsPresent } from 'motion/react'
import {
useLayoutEffect,
useRef,
@@ -5,10 +6,20 @@ import {
type ReactNode,
type SyntheticEvent,
} from 'react'
import { flushAfterModals } from './afterModalsClosed'
export interface ModalDialogProps {
/** Asked on Escape and on the platform's close requests; the consumer decides. */
onClose: () => void
/**
* Asked on Escape and on the platform's close requests; the consumer decides. Answering
* `'kept'` says the close was refused: a dialog the platform closed anyway is shown again.
*/
onClose: () => unknown
/**
* Where the focus goes once the dialog is gone: a function resolves the target (the
* opener, then its ancestors, when it answers null); `null` leaves the focus to the
* move that closed it.
*/
returnFocus?: (() => HTMLElement | null) | null
/** Id of the visible title; `label` names a dialog that shows none. */
labelledBy?: string
label?: string
@@ -38,8 +49,8 @@ const SURFACE =
'text-inherit backdrop:bg-transparent'
/** False when the browser refused the focus (element gone, disabled, hidden or inert). */
function tryFocus(element: HTMLElement): boolean {
element.focus()
function tryFocus(element: HTMLElement, preventScroll = false): boolean {
element.focus({ preventScroll })
return document.activeElement === element
}
@@ -51,20 +62,22 @@ function ancestorsOf(element: HTMLElement | null): HTMLElement[] {
}
/**
* The opener when it still takes focus, else the first control of its nearest
* container still on the page.
* The resolved target when it takes focus, else the opener when it still does, else the
* first control of its nearest container still on the page.
*/
function restoreFocus(
target: HTMLElement | null,
opener: HTMLElement | null,
ancestors: HTMLElement[],
): void {
if (target && tryFocus(target, true)) return
if (!opener || tryFocus(opener)) return
for (const container of ancestors) {
if (!container.isConnected) continue
const controls = Array.from(
container.querySelectorAll<HTMLElement>(FOCUSABLE),
)
if (controls.some(tryFocus)) return
if (controls.some((control) => tryFocus(control))) return
}
}
@@ -78,6 +91,7 @@ function restoreFocus(
*/
export default function ModalDialog({
onClose,
returnFocus,
labelledBy,
label,
describedBy,
@@ -85,6 +99,10 @@ export default function ModalDialog({
children,
}: ModalDialogProps) {
const ref = useRef<HTMLDialogElement>(null)
const latest = useRef({ returnFocus, onClose })
latest.current = { returnFocus, onClose }
const present = useRef(true)
present.current = useIsPresent()
useLayoutEffect(() => {
const dialog = ref.current
@@ -102,7 +120,11 @@ export default function ModalDialog({
// After the commit: the render that closes the dialog may remove the opener
// too. A dialog still on screen was only remounted (React StrictMode).
queueMicrotask(() => {
if (!dialog.isConnected) restoreFocus(opener, ancestors)
const resolve = latest.current.returnFocus
if (!dialog.isConnected && resolve !== null) {
restoreFocus(resolve?.() ?? null, opener, ancestors)
}
flushAfterModals()
})
}
}, [])
@@ -113,7 +135,8 @@ export default function ModalDialog({
// dialog on a second Escape without asking (close watcher anti-abuse rule).
event.preventDefault()
event.stopPropagation()
onClose()
// A held key repeats: only the first press asks.
if (!event.repeat) onClose()
}
const onCancel = (event: SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault()
@@ -121,8 +144,12 @@ export default function ModalDialog({
}
// Closed by the platform anyway: keep the consumer's state in step. The check
// ignores the `close` event queued by a cleanup the dialog has since reopened from.
// A refused close shows the dialog again, never during an exit or once it is gone.
const onClosed = () => {
if (ref.current && !ref.current.open) onClose()
const dialog = ref.current
if (!dialog || dialog.open) return
const refused = latest.current.onClose() === 'kept'
if (refused && present.current && dialog.isConnected) dialog.showModal()
}
return (
@@ -0,0 +1,30 @@
/**
* Work that must wait for the last modal dialog to close: a landing focus or an
* announcement that follows a close would otherwise reach an inert page. The set of
* open dialogs is the document's, so the queue is the module's (one per page).
*/
const waiting = new Set<() => void>()
/** happy-dom has no `:modal`: an open dialog is `dialog[open]`. */
const anyOpen = () => document.querySelector('dialog[open]') !== null
/**
* Runs `fn` at once when no dialog is open, else once none remains. Answers a cancel
* for a caller that goes away first.
*/
export function afterModalsClosed(fn: () => void): () => void {
if (!anyOpen()) {
fn()
return () => undefined
}
waiting.add(fn)
return () => void waiting.delete(fn)
}
/** Called by ModalDialog once it has closed: runs what waited, if no dialog is left. */
export function flushAfterModals(): void {
if (anyOpen()) return
const ready = [...waiting]
waiting.clear()
ready.forEach((fn) => fn())
}