diff --git a/apps/app/src/components/account/AvatarSection.tsx b/apps/app/src/components/account/AvatarSection.tsx index e50041fe..04a8a3d3 100644 --- a/apps/app/src/components/account/AvatarSection.tsx +++ b/apps/app/src/components/account/AvatarSection.tsx @@ -256,8 +256,13 @@ export default function AvatarSection() { {t(`account.avatar.error.${phase.failure}`)} )} {rejected && {t(`account.avatar.rejected.${rejected}`)}} - setConfirmOpen(false)} title={t('account.avatar.remove_title')} size="sm"> -

{t('account.avatar.remove_body')}

+ setConfirmOpen(false)} + title={t('account.avatar.remove_title')} + description={

{t('account.avatar.remove_body')}

} + size="sm" + >
-
+
+
) diff --git a/apps/app/src/components/report/HeldSessionPanel.tsx b/apps/app/src/components/report/HeldSessionPanel.tsx index 226fceb9..3ea0af19 100644 --- a/apps/app/src/components/report/HeldSessionPanel.tsx +++ b/apps/app/src/components/report/HeldSessionPanel.tsx @@ -114,15 +114,17 @@ export default function HeldSessionPanel({ ? 'session.held.open_title' : `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`, )} + description={ +

+ {t( + pending?.action === 'open' + ? 'session.held.open_body' + : 'session.held.discard_body', + )} +

+ } size="sm" > -

- {t( - pending?.action === 'open' - ? 'session.held.open_body' - : 'session.held.discard_body', - )} -

-
-
- -
-
- - -
- + + - )} - +
+ +
+
+ + +
+ + ) } diff --git a/apps/app/src/components/ui/Dialog.tsx b/apps/app/src/components/ui/Dialog.tsx index 8d9211ac..5b85a9c4 100644 --- a/apps/app/src/components/ui/Dialog.tsx +++ b/apps/app/src/components/ui/Dialog.tsx @@ -1,11 +1,15 @@ -import { useEffect, type ReactNode } from 'react' +import { useId, type ReactNode } from 'react' import { AnimatePresence, motion } from 'motion/react' +import ModalDialog 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 title: string + /** The dialog's message, announced with its name (aria-describedby). */ + description?: ReactNode children: ReactNode size?: 'sm' | 'md' | 'lg' | 'xl' } @@ -17,61 +21,66 @@ const SIZE: Record, string> = { xl: 'max-w-4xl', } -export default function Dialog({ - open, - onClose, - title, - children, - size = 'md', -}: DialogProps) { - const t = useT() - useEffect(() => { - if (!open) return - const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [open, onClose]) - +export default function Dialog({ open, ...surface }: DialogProps) { return ( - - {open && ( -
- {open && } + ) +} + +function DialogSurface({ + onClose, + title, + description, + children, + size = 'md', +}: Omit) { + const t = useT() + const titleId = useId() + const descriptionId = useId() + return ( + + + +
+

+ {title} +

+ -
-
{children}
-
+ ✕ + + +
+ {description &&
{description}
} + {children}
- )} - +
+
) } diff --git a/apps/app/src/components/ui/ModalDialog.tsx b/apps/app/src/components/ui/ModalDialog.tsx new file mode 100644 index 00000000..f2892d37 --- /dev/null +++ b/apps/app/src/components/ui/ModalDialog.tsx @@ -0,0 +1,133 @@ +import { + useLayoutEffect, + useRef, + type KeyboardEvent, + type ReactNode, + type SyntheticEvent, +} from 'react' + +export interface ModalDialogProps { + /** Asked on Escape and on the platform's close requests; the consumer decides. */ + onClose: () => void + /** Id of the visible title; `label` names a dialog that shows none. */ + labelledBy?: string + label?: string + describedBy?: string + className?: string + children: ReactNode +} + +/** Controls that can take focus: the first one on open, a fallback when the opener is gone. */ +const FOCUSABLE = [ + 'a[href]', + 'button:not([disabled])', + 'input:not([disabled]):not([type="hidden"])', + 'select:not([disabled])', + 'textarea:not([disabled])', + '[tabindex]:not([tabindex="-1"])', +].join(', ') + +/** Full-viewport transparent container: the consumer draws its own backdrop and panel. */ +const SURFACE = + 'm-0 h-full max-h-none w-full max-w-none overflow-hidden border-0 bg-transparent p-0 ' + + '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() + return document.activeElement === element +} + +function ancestorsOf(element: HTMLElement | null): HTMLElement[] { + const chain: HTMLElement[] = [] + for (let node = element?.parentElement; node; node = node.parentElement) + chain.push(node) + return chain +} + +/** + * The opener when it still takes focus, else the first control of its nearest + * container still on the page. + */ +function restoreFocus( + opener: HTMLElement | null, + ancestors: HTMLElement[], +): void { + 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 + } +} + +/** + * Native modal `` shown while mounted (D13): `showModal()` makes the + * rest of the page inert and keeps focus in the top layer. The dialog never + * closes itself: Escape and close requests call `onClose`, and it leaves the + * screen when the consumer unmounts it. Focus starts on the first control and + * then returns to the opener. Tab past the last control reaches the browser's + * own interface, never the page, as the platform intends. + */ +export default function ModalDialog({ + onClose, + labelledBy, + label, + describedBy, + className = '', + children, +}: ModalDialogProps) { + const ref = useRef(null) + + useLayoutEffect(() => { + const dialog = ref.current + if (!dialog) return + const active = document.activeElement + const opener = + active instanceof HTMLElement && active !== document.body ? active : null + const ancestors = ancestorsOf(opener) + dialog.showModal() + // The first control, not the platform's pick: Chromium focuses a scrollable + // panel when the content is long, the close button otherwise. + dialog.querySelector(FOCUSABLE)?.focus() + return () => { + if (dialog.open) dialog.close() + restoreFocus(opener, ancestors) + } + }, []) + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || event.nativeEvent.isComposing) return + // A cancelled keydown is no close request: Chromium would otherwise close the + // dialog on a second Escape without asking (close watcher anti-abuse rule). + event.preventDefault() + event.stopPropagation() + onClose() + } + const onCancel = (event: SyntheticEvent) => { + event.preventDefault() + onClose() + } + // 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. + const onClosed = () => { + if (ref.current && !ref.current.open) onClose() + } + + return ( + + {children} + + ) +} diff --git a/apps/app/src/styles/index.css b/apps/app/src/styles/index.css index e7d281d3..e3013938 100644 --- a/apps/app/src/styles/index.css +++ b/apps/app/src/styles/index.css @@ -2,6 +2,8 @@ @import './tokens.css'; html, body, #root { height: 100%; } +/* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */ +html:has(dialog:modal) { overflow: hidden; } body { background: var(--color-bg); color: var(--color-ink); diff --git a/apps/app/tests/unit/ui.Dialog.test.tsx b/apps/app/tests/unit/ui.Dialog.test.tsx index 32ea6659..7bd73f67 100644 --- a/apps/app/tests/unit/ui.Dialog.test.tsx +++ b/apps/app/tests/unit/ui.Dialog.test.tsx @@ -1,7 +1,14 @@ import { describe, it, expect, vi } from 'vitest' -import { render, screen } from '@testing-library/react' +import { useState } from 'react' +import { 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 { useLocaleStore } from '@/state/localeStore' + +// happy-dom implements neither the top layer nor inertness nor the dialog's focus +// steps: these tests cover the React wiring, the browser behaviour is proven by +// the Playwright suites (apps/app/e2e). describe('Dialog', () => { it('renders nothing when open=false', () => { @@ -32,4 +39,173 @@ describe('Dialog', () => { await userEvent.click(screen.getByTestId('dialog-backdrop')) expect(onClose).toHaveBeenCalled() }) + + it('is a native dialog named by its title and described by its message', () => { + render( + {}} + title="Remove the photo?" + description={

It goes for good.

} + > + +
, + ) + const dialog = screen.getByRole('dialog', { name: 'Remove the photo?' }) + expect(dialog.tagName).toBe('DIALOG') + expect(dialog).toHaveAccessibleDescription('It goes for good.') + }) + + it('has no description when none is given', () => { + render( + {}} title="X"> + body + , + ) + expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-describedby') + }) + + it.each([ + ['fr', 'Fermer'], + ['en', 'Close'], + ] as const)( + 'asks to close from the close button, named in %s', + async (locale, name) => { + useLocaleStore.setState({ locale }) + const onClose = vi.fn() + render( + + body + , + ) + await userEvent.click(screen.getByRole('button', { name })) + expect(onClose).toHaveBeenCalledTimes(1) + }, + ) +}) + +describe('ModalDialog', () => { + it('opens as a modal while mounted and closes on unmount', () => { + const showModal = vi.spyOn(HTMLDialogElement.prototype, 'showModal') + const close = vi.spyOn(HTMLDialogElement.prototype, 'close') + const { unmount } = render( + {}} label="Menu"> + + , + ) + expect(showModal).toHaveBeenCalledTimes(1) + unmount() + expect(close).toHaveBeenCalledTimes(1) + showModal.mockRestore() + close.mockRestore() + }) + + it('turns Escape into a request: the consumer decides, the dialog stays open', () => { + const onClose = vi.fn() + render( + + + , + ) + const dialog = screen.getByRole('dialog', { + name: 'Menu', + }) as HTMLDialogElement + const escape = new KeyboardEvent('keydown', { + key: 'Escape', + bubbles: true, + cancelable: true, + }) + screen.getByRole('button', { name: 'Inside' }).dispatchEvent(escape) + fireEvent.keyDown(dialog, { key: 'Escape' }) + expect(escape.defaultPrevented).toBe(true) + expect(onClose).toHaveBeenCalledTimes(2) + expect(dialog.open).toBe(true) + }) + + it('ignores Escape while a composition is in progress', () => { + const onClose = vi.fn() + render( + + + , + ) + fireEvent.keyDown(screen.getByLabelText('Name'), { + key: 'Escape', + isComposing: true, + }) + expect(onClose).not.toHaveBeenCalled() + }) + + it('cancels the platform close request and asks the consumer instead', () => { + const onClose = vi.fn() + render( + + + , + ) + const cancel = new Event('cancel', { cancelable: true }) + screen.getByRole('dialog').dispatchEvent(cancel) + expect(cancel.defaultPrevented).toBe(true) + expect(onClose).toHaveBeenCalledTimes(1) + }) + + it('follows a close the platform forced, and ignores a close event while still open', () => { + const onClose = vi.fn() + render( + + + , + ) + const dialog = screen.getByRole('dialog') as HTMLDialogElement + dialog.dispatchEvent(new Event('close')) + expect(onClose).not.toHaveBeenCalled() + dialog.close() + expect(onClose).toHaveBeenCalledTimes(1) + }) +}) + +/** An opener that can disappear while its dialog is open, beside a sibling control. */ +function Harness({ removeOpener = false }: { removeOpener?: boolean }) { + const [open, setOpen] = useState(false) + const [openerShown, setOpenerShown] = useState(true) + const confirm = () => { + if (removeOpener) setOpenerShown(false) + setOpen(false) + } + return ( +
+
+ + {openerShown && ( + + )} +
+ setOpen(false)} title="Confirm"> + + +
+ ) +} + +describe('Dialog focus return', () => { + it('returns focus to the opener', async () => { + render() + await userEvent.click(screen.getByRole('button', { name: 'Open' })) + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(screen.getByRole('button', { name: 'Open' })).toHaveFocus() + }) + + it('falls back to the first control of the opener’s container when the opener is gone', async () => { + render() + await userEvent.click(screen.getByRole('button', { name: 'Open' })) + await userEvent.click(screen.getByRole('button', { name: 'Confirm' })) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(screen.queryByRole('button', { name: 'Open' })).toBeNull() + expect(screen.getByRole('button', { name: 'Sibling' })).toHaveFocus() + }) })