The dialog closed before the request, focus went back to the remove button, then the button vanished and focus fell on the page. The confirmation now closes with the photo gone, Escape and Cancel wait for it, and ModalDialog restores focus after the commit so its fallback sees the opener removed. The sr-only file input leaves the tab order: it was an invisible tab stop.
143 lines
4.4 KiB
TypeScript
143 lines
4.4 KiB
TypeScript
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 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): 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()
|
|
// 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 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>
|
|
)
|
|
}
|