feat(ui): modal dialogs on the native dialog element (D13)
ModalDialog wraps showModal(): the page behind is inert and does not scroll, focus starts on the first control and returns to the opener, or to the first control of its nearest container when the opener is gone. Escape and close requests only ask the consumer. Dialog gains aria-labelledby and an optional described message; the confirmations pass theirs. The mobile drawer uses the same primitive and closes at the sidebar breakpoint.
This commit is contained in:
1 parent
57922e0902
commit
6f885eccb2
9 files changed
+450
-118
No files matched your search
@@ -256,8 +256,13 @@ export default function AvatarSection() {
|
||||
<Notice tone="error">{t(`account.avatar.error.${phase.failure}`)}</Notice>
|
||||
)}
|
||||
{rejected && <Notice tone="error">{t(`account.avatar.rejected.${rejected}`)}</Notice>}
|
||||
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} title={t('account.avatar.remove_title')} size="sm">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>
|
||||
<Dialog
|
||||
open={confirmOpen}
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
title={t('account.avatar.remove_title')}
|
||||
description={<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>}
|
||||
size="sm"
|
||||
>
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => setConfirmOpen(false)}>
|
||||
{t('common.cancel')}
|
||||
|
||||
@@ -18,13 +18,11 @@ export default function DisclaimerDialog({
|
||||
open
|
||||
onClose={onAcknowledge}
|
||||
title={t('editor.disclaimer_title')}
|
||||
description={<p className="text-sm text-[var(--color-ink)]">{text}</p>}
|
||||
size="md"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-[var(--color-ink)]">{text}</p>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={onAcknowledge}>{t('common.understood')}</Button>
|
||||
</div>
|
||||
<div className="mt-4 flex justify-end">
|
||||
<Button onClick={onAcknowledge}>{t('common.understood')}</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -114,15 +114,17 @@ export default function HeldSessionPanel({
|
||||
? 'session.held.open_title'
|
||||
: `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`,
|
||||
)}
|
||||
description={
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t(
|
||||
pending?.action === 'open'
|
||||
? 'session.held.open_body'
|
||||
: 'session.held.discard_body',
|
||||
)}
|
||||
</p>
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t(
|
||||
pending?.action === 'open'
|
||||
? 'session.held.open_body'
|
||||
: 'session.held.discard_body',
|
||||
)}
|
||||
</p>
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => setPending(null)}>
|
||||
{t('common.cancel')}
|
||||
|
||||
@@ -30,8 +30,13 @@ export default function ReplaceSessionDialog({
|
||||
? t('session.replace.body').replace(/\{animal\}/, () => report.animal.name)
|
||||
: t('session.replace.body_unloaded')
|
||||
return (
|
||||
<Dialog open={open} onClose={onCancel} title={t('session.replace.title')} size="sm">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onCancel}
|
||||
title={t('session.replace.title')}
|
||||
description={<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>}
|
||||
size="sm"
|
||||
>
|
||||
{unsaved && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<p className="text-sm">{t('session.replace.unsaved')}</p>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom'
|
||||
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
|
||||
import Brand from '@/components/brand/Brand'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import ModalDialog from '@/components/ui/ModalDialog'
|
||||
import SidebarNav from './SidebarNav'
|
||||
import SignOutButton from './SignOutButton'
|
||||
import UserBadge from './UserBadge'
|
||||
@@ -13,64 +14,65 @@ export interface MobileDrawerProps {
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** The sidebar's breakpoint (Tailwind `lg`): from there the drawer has no reason to stay open. */
|
||||
const LARGE_SCREEN = '(min-width: 64rem)'
|
||||
|
||||
/** Left-side navigation drawer for small screens (transform + opacity only). */
|
||||
export default function MobileDrawer({ open, onClose }: MobileDrawerProps) {
|
||||
return <AnimatePresence>{open && <DrawerSurface onClose={onClose} />}</AnimatePresence>
|
||||
}
|
||||
|
||||
function DrawerSurface({ onClose }: Pick<MobileDrawerProps, 'onClose'>) {
|
||||
const t = useT()
|
||||
const reduced = useReducedMotion()
|
||||
const slide = reduced ? { x: 0 } : { x: '-100%' }
|
||||
// A modal drawer left open while the window widens would keep the page inert.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
const query = window.matchMedia(LARGE_SCREEN)
|
||||
const onChange = (event: MediaQueryListEvent) => event.matches && onClose()
|
||||
query.addEventListener('change', onChange)
|
||||
return () => query.removeEventListener('change', onChange)
|
||||
}, [onClose])
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 lg:hidden">
|
||||
<motion.div
|
||||
data-testid="drawer-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
<ModalDialog onClose={onClose} label={t('shell.nav_label')} className="open:block">
|
||||
<motion.div
|
||||
data-testid="drawer-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.aside
|
||||
initial={slide}
|
||||
animate={{ x: 0 }}
|
||||
exit={slide}
|
||||
transition={{ duration: reduced ? 0 : 0.2, ease: 'easeOut' }}
|
||||
className="absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col bg-[var(--color-surface)] shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)]">
|
||||
<Link to="/app" onClick={onClose} aria-label={t('shell.nav.dashboard')}>
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.aside
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t('shell.nav_label')}
|
||||
initial={slide}
|
||||
animate={{ x: 0 }}
|
||||
exit={slide}
|
||||
transition={{ duration: reduced ? 0 : 0.2, ease: 'easeOut' }}
|
||||
className="absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col bg-[var(--color-surface)] shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
|
||||
aria-label={t('shell.close_menu')}
|
||||
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)]">
|
||||
<Link to="/app" onClick={onClose} aria-label={t('shell.nav.dashboard')}>
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('shell.close_menu')}
|
||||
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-3 py-4">
|
||||
<SidebarNav onNavigate={onClose} />
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
|
||||
<UserBadge />
|
||||
<SignOutButton className="w-full" />
|
||||
</div>
|
||||
</motion.aside>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className="flex-1 overflow-y-auto px-3 py-4">
|
||||
<SidebarNav onNavigate={onClose} />
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
|
||||
<UserBadge />
|
||||
<SignOutButton className="w-full" />
|
||||
</div>
|
||||
</motion.aside>
|
||||
</ModalDialog>
|
||||
)
|
||||
}
|
||||
@@ -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<NonNullable<DialogProps['size']>, 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 (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4">
|
||||
<motion.div
|
||||
data-testid="dialog-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
<AnimatePresence>{open && <DialogSurface {...surface} />}</AnimatePresence>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogSurface({
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
size = 'md',
|
||||
}: Omit<DialogProps, 'open'>) {
|
||||
const t = useT()
|
||||
const titleId = useId()
|
||||
const descriptionId = useId()
|
||||
return (
|
||||
<ModalDialog
|
||||
onClose={onClose}
|
||||
labelledBy={titleId}
|
||||
describedBy={description ? descriptionId : undefined}
|
||||
className="open:flex items-center justify-center p-3 sm:p-4"
|
||||
>
|
||||
<motion.div
|
||||
data-testid="dialog-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.96 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.96 }}
|
||||
transition={{ duration: 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)]">
|
||||
<h2
|
||||
id={titleId}
|
||||
className="text-lg font-semibold text-[var(--color-ink)]"
|
||||
>
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
initial={{ opacity: 0, scale: 0.96 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.96 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
||||
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
|
||||
>
|
||||
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
|
||||
<h2 className="text-lg font-semibold text-[var(--color-ink)]">
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClose}
|
||||
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4">{children}</div>
|
||||
</motion.div>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4">
|
||||
{description && <div id={descriptionId}>{description}</div>}
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</ModalDialog>
|
||||
)
|
||||
}
|
||||
@@ -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<HTMLElement>(FOCUSABLE),
|
||||
)
|
||||
if (controls.some(tryFocus)) return
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Native modal `<dialog>` 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<HTMLDialogElement>(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<HTMLElement>(FOCUSABLE)?.focus()
|
||||
return () => {
|
||||
if (dialog.open) dialog.close()
|
||||
restoreFocus(opener, ancestors)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLDialogElement>) => {
|
||||
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<HTMLDialogElement>) => {
|
||||
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 (
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-labelledby={labelledBy}
|
||||
aria-label={label}
|
||||
aria-describedby={describedBy}
|
||||
onKeyDown={onKeyDown}
|
||||
onCancel={onCancel}
|
||||
onClose={onClosed}
|
||||
className={`${SURFACE} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user