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
@@ -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