From 553a0e57b24c75aec2b239d984f8eed05cde53c6 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 13 Nov 2026 17:57:47 +0100 Subject: [PATCH] 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. --- apps/app/src/app/useLeaveGuard.ts | 23 +- apps/app/src/components/ui/Dialog.tsx | 20 +- apps/app/src/components/ui/ModalDialog.tsx | 47 +++- .../src/components/ui/afterModalsClosed.ts | 30 +++ apps/app/src/editor/focusRequest.ts | 8 +- .../tests/unit/ui.dialog-primitives.test.tsx | 238 ++++++++++++++++++ 6 files changed, 336 insertions(+), 30 deletions(-) create mode 100644 apps/app/src/components/ui/afterModalsClosed.ts create mode 100644 apps/app/tests/unit/ui.dialog-primitives.test.tsx diff --git a/apps/app/src/app/useLeaveGuard.ts b/apps/app/src/app/useLeaveGuard.ts index 9f0e672b..593aa94d 100644 --- a/apps/app/src/app/useLeaveGuard.ts +++ b/apps/app/src/app/useLeaveGuard.ts @@ -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) } diff --git a/apps/app/src/components/ui/Dialog.tsx b/apps/app/src/components/ui/Dialog.tsx index 5b85a9c4..d171b669 100644 --- a/apps/app/src/components/ui/Dialog.tsx +++ b/apps/app/src/components/ui/Dialog.tsx @@ -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) { const t = useT() + const reduced = useReducedMotion() + const scale = reduced ? 1 : 0.96 const titleId = useId() const descriptionId = useId() return (
diff --git a/apps/app/src/components/ui/ModalDialog.tsx b/apps/app/src/components/ui/ModalDialog.tsx index 5e5cf3bd..07632bd3 100644 --- a/apps/app/src/components/ui/ModalDialog.tsx +++ b/apps/app/src/components/ui/ModalDialog.tsx @@ -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(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(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) => { 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 ( diff --git a/apps/app/src/components/ui/afterModalsClosed.ts b/apps/app/src/components/ui/afterModalsClosed.ts new file mode 100644 index 00000000..d5ff2b9e --- /dev/null +++ b/apps/app/src/components/ui/afterModalsClosed.ts @@ -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()) +} diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts index 37f563ca..97b7cbca 100644 --- a/apps/app/src/editor/focusRequest.ts +++ b/apps/app/src/editor/focusRequest.ts @@ -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`. */ diff --git a/apps/app/tests/unit/ui.dialog-primitives.test.tsx b/apps/app/tests/unit/ui.dialog-primitives.test.tsx new file mode 100644 index 00000000..2d6b4b5c --- /dev/null +++ b/apps/app/tests/unit/ui.dialog-primitives.test.tsx @@ -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( + + + , + ) + 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( + + + , + ) + 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) => ( + + body + + ) + 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( + + + , + ) + 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 ( +
+ + + setOpen(false)} + returnFocus={returnFocus} + title="X" + > + body + +
+ ) +} + +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( + 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( null} />) + await openThenEscape() + expect(screen.getByRole('button', { name: 'Open' })).toHaveFocus() + }) + + it('null leaves the focus to the move that closed the dialog', async () => { + render() + 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( + {}} label="Menu"> + + , + ) + 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( + {}} label="Menu"> + + , + ) + 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() + 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( + {}} title="X"> + body + , + ) + const panel = screen.getByRole('heading', { name: 'X' }).closest('div') + expect(panel?.getAttribute('style') ?? '').not.toContain('0.96') + }) + + it('scales in otherwise', () => { + render( + {}} title="X"> + body + , + ) + 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( + , + ) + expect(focusRow(key)).toBe(false) + cleanup() + render() + expect(focusRow(key)).toBe(true) + }) +})