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

+14 -9
View File
@@ -1,6 +1,19 @@
import { useEffect } from 'react'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
/** While `dirty`, a reload, a tab close or a full-page redirect asks first (beforeunload). */
export function useBeforeUnload(dirty: boolean): void {
useEffect(() => {
if (!dirty) return
const guard = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
window.addEventListener('beforeunload', guard)
return () => window.removeEventListener('beforeunload', guard)
}, [dirty])
}
/**
* While `dirty`, a reload, a tab close or a full-page redirect asks first
* (beforeunload), and AppLayout asks before following a link of the app. The
@@ -13,13 +26,5 @@ export function useLeaveGuard(dirty: boolean): void {
arm(dirty)
return () => arm(false)
}, [dirty, arm])
useEffect(() => {
if (!dirty) return
const guard = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
window.addEventListener('beforeunload', guard)
return () => window.removeEventListener('beforeunload', guard)
}, [dirty])
useBeforeUnload(dirty)
}
+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())
}
+4 -4
View File
@@ -82,7 +82,7 @@ export function visibleElement(
)
}
/** Scrolls to and focuses the visible row tagged with `key`; false when there is none. */
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
export function focusRow(key: ElementKey): boolean {
const wanted = JSON.stringify(key)
const row = [
@@ -94,7 +94,7 @@ export function focusRow(key: ElementKey): boolean {
if (!row) return false
row.scrollIntoView?.({ block: 'center' })
row.focus()
return true
return document.activeElement === row
}
/** Row-based places (Général, Vues, Catégories, Régions): focus the named row. */
@@ -150,8 +150,8 @@ function activeTabButton(): HTMLElement | null {
}
/** Gives the focus to the shown tab's button: a lost focus must not leave on `body`. */
export function focusActiveTab(): void {
activeTabButton()?.focus()
export function focusActiveTab(options?: FocusOptions): void {
activeTabButton()?.focus(options)
}
/** The element holding the focus, when it is something other than `body`. */
@@ -0,0 +1,238 @@
/** R2F-2: kept-refusal re-show, returnFocus, afterModalsClosed, held Escape, reduced motion. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useState } from 'react'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Dialog from '@/components/ui/Dialog'
import ModalDialog from '@/components/ui/ModalDialog'
import {
afterModalsClosed,
flushAfterModals,
} from '@/components/ui/afterModalsClosed'
import { focusRow } from '@/editor/focusRequest'
import { useLocaleStore } from '@/state/localeStore'
import { setReducedMotion } from '../helpers/motion'
beforeEach(() => {
useLocaleStore.setState({ locale: 'en' })
setReducedMotion(false)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
const dialogOf = () => screen.getByRole('dialog') as HTMLDialogElement
describe('a refused close', () => {
it('shows the dialog again when the consumer answers kept', () => {
const onClose = vi.fn(() => 'kept' as const)
render(
<ModalDialog onClose={onClose} label="Form">
<button type="button">Inside</button>
</ModalDialog>,
)
const dialog = dialogOf()
dialog.close()
expect(onClose).toHaveBeenCalledTimes(1)
expect(dialog.open).toBe(true)
})
it('leaves it closed when the consumer accepts', () => {
const onClose = vi.fn()
render(
<ModalDialog onClose={onClose} label="Form">
<button type="button">Inside</button>
</ModalDialog>,
)
const dialog = dialogOf()
dialog.close()
expect(dialog.open).toBe(false)
})
it('never shows a Dialog again once it is set closed and then closed natively', () => {
const onClose = vi.fn(() => 'kept' as const)
const showModal = vi.spyOn(HTMLDialogElement.prototype, 'showModal')
const view = (open: boolean) => (
<Dialog open={open} onClose={onClose} title="X">
body
</Dialog>
)
const { rerender } = render(view(true))
const dialog = dialogOf()
expect(showModal).toHaveBeenCalledTimes(1)
rerender(view(false))
dialog.close()
expect(dialog.open).toBe(false)
expect(showModal).toHaveBeenCalledTimes(1)
})
})
describe('a held Escape', () => {
it('is no close request, and stays cancelled', () => {
const onClose = vi.fn()
render(
<ModalDialog onClose={onClose} label="Menu">
<button type="button">Inside</button>
</ModalDialog>,
)
const held = new KeyboardEvent('keydown', {
key: 'Escape',
repeat: true,
bubbles: true,
cancelable: true,
})
screen.getByRole('button', { name: 'Inside' }).dispatchEvent(held)
expect(held.defaultPrevented).toBe(true)
expect(onClose).not.toHaveBeenCalled()
fireEvent.keyDown(dialogOf(), { key: 'Escape' })
expect(onClose).toHaveBeenCalledTimes(1)
})
})
function Returning({
returnFocus,
}: {
returnFocus?: (() => HTMLElement | null) | null
}) {
const [open, setOpen] = useState(false)
return (
<main>
<button type="button" onClick={() => setOpen(true)}>
Open
</button>
<button type="button">Elsewhere</button>
<Dialog
open={open}
onClose={() => setOpen(false)}
returnFocus={returnFocus}
title="X"
>
body
</Dialog>
</main>
)
}
async function openThenEscape() {
await userEvent.click(screen.getByRole('button', { name: 'Open' }))
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
}
describe('returnFocus', () => {
it('a function resolves the target, focused without scrolling', async () => {
const focus = vi.spyOn(HTMLElement.prototype, 'focus')
render(
<Returning
returnFocus={() => screen.getByRole('button', { name: 'Elsewhere' })}
/>,
)
await openThenEscape()
expect(screen.getByRole('button', { name: 'Elsewhere' })).toHaveFocus()
expect(focus).toHaveBeenCalledWith({ preventScroll: true })
})
it('a function that answers null falls back to the opener', async () => {
render(<Returning returnFocus={() => null} />)
await openThenEscape()
expect(screen.getByRole('button', { name: 'Open' })).toHaveFocus()
})
it('null leaves the focus to the move that closed the dialog', async () => {
render(<Returning returnFocus={null} />)
await openThenEscape()
expect(screen.getByRole('button', { name: 'Open' })).not.toHaveFocus()
})
})
describe('afterModalsClosed', () => {
it('runs at once when no dialog is open', () => {
const fn = vi.fn()
afterModalsClosed(fn)
expect(fn).toHaveBeenCalledTimes(1)
})
it('waits for the last dialog, then runs once', async () => {
const fn = vi.fn()
const { unmount } = render(
<ModalDialog onClose={() => {}} label="Menu">
<button type="button">Inside</button>
</ModalDialog>,
)
afterModalsClosed(fn)
flushAfterModals()
expect(fn).not.toHaveBeenCalled()
unmount()
await waitFor(() => expect(fn).toHaveBeenCalledTimes(1))
})
it('a cancelled wait never runs', async () => {
const fn = vi.fn()
const { unmount } = render(
<ModalDialog onClose={() => {}} label="Menu">
<button type="button">Inside</button>
</ModalDialog>,
)
afterModalsClosed(fn)()
unmount()
await Promise.resolve()
expect(fn).not.toHaveBeenCalled()
})
it('runs after the focus went back, so a landing is not undone', async () => {
const order: string[] = []
render(<Returning />)
await userEvent.click(screen.getByRole('button', { name: 'Open' }))
afterModalsClosed(() =>
order.push(`landed on ${document.activeElement?.textContent}`),
)
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
await waitFor(() => expect(order).toHaveLength(1))
expect(order[0]).toBe('landed on Open')
})
})
describe('Dialog motion', () => {
it('does not scale in when the user asks for reduced motion', () => {
setReducedMotion(true)
render(
<Dialog open onClose={() => {}} title="X">
body
</Dialog>,
)
const panel = screen.getByRole('heading', { name: 'X' }).closest('div')
expect(panel?.getAttribute('style') ?? '').not.toContain('0.96')
})
it('scales in otherwise', () => {
render(
<Dialog open onClose={() => {}} title="X">
body
</Dialog>,
)
const panel = screen.getByRole('heading', { name: 'X' }).closest('div')
expect(panel?.getAttribute('style') ?? '').toContain('0.96')
})
})
describe('focusRow', () => {
it('reports found only when the row holds the focus', () => {
const key = { kind: 'zone', id: 'z' } as const
render(
<button data-focus-key={JSON.stringify(key)} disabled>
row
</button>,
)
expect(focusRow(key)).toBe(false)
cleanup()
render(<button data-focus-key={JSON.stringify(key)}>row</button>)
expect(focusRow(key)).toBe(true)
})
})