Files
faunosteo/apps/app/src/components/ui/ModalDialog.tsx
T

193 lines
6.6 KiB
TypeScript

import { useIsPresent } from 'motion/react'
import {
useLayoutEffect,
useRef,
type KeyboardEvent,
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. 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
/**
* A view layer of the editor (R2F-1): its state is in the browser history, so a Back
* may close it. Any other modal open refuses a Back.
*/
layer?: boolean
/** Id of the visible title; `label` names a dialog that shows none. */
labelledBy?: string
label?: string
describedBy?: string
className?: string
children: ReactNode
}
/**
* Controls in the tab order: the first one takes focus on open, and serves as 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]',
]
.map((selector) => `${selector}: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, preventScroll = false): boolean {
element.focus({ preventScroll })
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 resolved target when it takes focus; else, if the focus is nowhere (`body`), the
* opener when it still does, else the first control of its nearest container still on
* the page. A focus another closing dialog already placed is left alone.
*/
function restoreFocus(
target: HTMLElement | null,
opener: HTMLElement | null,
ancestors: HTMLElement[],
): void {
if (target && tryFocus(target, true)) return
const active = document.activeElement
if (active && active !== document.body) 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((control) => tryFocus(control))) 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,
returnFocus,
layer,
labelledBy,
label,
describedBy,
className = '',
children,
}: ModalDialogProps) {
const ref = useRef<HTMLDialogElement>(null)
const latest = useRef({ returnFocus, onClose })
latest.current = { returnFocus, onClose }
const isPresent = useIsPresent()
const present = useRef(true)
present.current = isPresent
// The `close` event of the cleanup's own `close()` is no request (a DOM that fires it
// at once, as the test DOM does, would otherwise reach the consumer).
const closingSelf = useRef(false)
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) {
closingSelf.current = true
dialog.close()
closingSelf.current = false
}
// 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(() => {
const resolve = latest.current.returnFocus
if (!dialog.isConnected && resolve !== null) {
restoreFocus(resolve?.() ?? null, opener, ancestors)
}
// After the restores of every dialog closed in this commit: a landing that
// waited for them must not be undone by a later one.
queueMicrotask(flushAfterModals)
})
}
}, [])
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()
// A held key repeats: only the first press asks.
if (event.repeat) return
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.
// A refused close shows the dialog again, never during an exit or once it is gone.
const onClosed = () => {
const dialog = ref.current
if (!dialog || dialog.open || closingSelf.current) return
const refused = latest.current.onClose() === 'kept'
if (refused && present.current && dialog.isConnected) dialog.showModal()
}
return (
<dialog
ref={ref}
// A dialog playing its exit answers nothing: a second click or key is lost.
inert={!isPresent}
data-layer={layer ? '' : undefined}
aria-labelledby={labelledBy}
aria-label={label}
aria-describedby={describedBy}
onKeyDown={onKeyDown}
onCancel={onCancel}
onClose={onClosed}
className={`${SURFACE} ${className}`}
>
{children}
</dialog>
)
}