Modal dialog
An accessible modal dialog rendered in a portal: focus moves in on open and returns to the trigger on close, Tab is trapped, Escape and backdrop clicks close it, page scroll is locked without layout shift, and the title and description are linked with aria-labelledby and aria-describedby. Supports role="alertdialog", nested dialogs, three sizes, a footer slot, a bottom-sheet layout on small screens and a reduced-motion-aware enter and exit.
Source
"use client";
import {
useEffect, useId, useLayoutEffect, useRef, useState,
type KeyboardEvent, type MouseEvent, type PointerEvent, type ReactNode, type RefObject,
} from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
export type ModalDialogSize = "sm" | "md" | "lg";
export interface ModalDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: ReactNode;
description?: ReactNode;
children?: ReactNode;
/** Actions along the bottom, usually Cancel and a primary button. */
footer?: ReactNode;
size?: ModalDialogSize;
/** "alertdialog" for confirmations that need an answer; it also stops backdrop clicks from closing by default. */
role?: "dialog" | "alertdialog";
/** Element to focus on open. Defaults to the first focusable element in the body, then the close button. */
initialFocus?: RefObject<HTMLElement | null>;
closeOnBackdrop?: boolean;
hideCloseButton?: boolean;
className?: string;
}
const FOCUSABLE = [
"a[href]", "area[href]", "button:not([disabled])", "input:not([disabled]):not([type=hidden])", "select:not([disabled])",
"textarea:not([disabled])", "iframe", "audio[controls]", "video[controls]", "[contenteditable]:not([contenteditable=false])",
"[tabindex]:not([tabindex='-1'])",
].join(",");
function focusables(container: HTMLElement) {
return Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
(element) => !element.closest("[inert]") && element.getClientRects().length > 0,
);
}
// Open dialogs, innermost last: only the top one traps focus. Scroll lock is counted for nested dialogs.
const openStack: symbol[] = [];
let lockCount = 0;
let savedBodyStyle = { overflow: "", paddingRight: "" };
function lockScroll() {
if (lockCount++ > 0) return;
const { body, documentElement } = document;
const scrollbar = window.innerWidth - documentElement.clientWidth;
savedBodyStyle = { overflow: body.style.overflow, paddingRight: body.style.paddingRight };
body.style.overflow = "hidden";
if (scrollbar > 0) body.style.paddingRight = `${parseFloat(getComputedStyle(body).paddingRight) + scrollbar}px`;
}
function unlockScroll() {
if (--lockCount > 0) return;
document.body.style.overflow = savedBodyStyle.overflow;
document.body.style.paddingRight = savedBodyStyle.paddingRight;
}
const sizes: Record<ModalDialogSize, string> = { sm: "sm:max-w-sm", md: "sm:max-w-lg", lg: "sm:max-w-2xl" };
const EXIT_MS = 160;
export function ModalDialog({
open, onOpenChange, title, description, children, footer, size = "md", role = "dialog", initialFocus,
closeOnBackdrop = role !== "alertdialog", hideCloseButton, className,
}: ModalDialogProps) {
const id = useId();
const titleId = `${id}-title`;
const descriptionId = `${id}-description`;
const panelRef = useRef<HTMLDivElement>(null);
const closeRef = useRef<HTMLButtonElement>(null);
const returnFocus = useRef<HTMLElement | null>(null);
const pressedBackdrop = useRef(false);
const [mounted, setMounted] = useState(false);
const [present, setPresent] = useState(open);
const closing = present && !open;
useEffect(() => setMounted(true), []);
// Keep the dialog in the DOM briefly after closing so it can fade out.
useEffect(() => {
if (open) {
setPresent(true);
return;
}
const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const timer = setTimeout(() => setPresent(false), reduce ? 0 : EXIT_MS);
return () => clearTimeout(timer);
}, [open]);
// Remember what had focus and move focus in; the effect below gives it back on close.
useLayoutEffect(() => {
if (!open || !mounted) return;
const panel = panelRef.current;
if (!panel) return;
returnFocus.current = document.activeElement as HTMLElement | null;
const body = panel.querySelector<HTMLElement>("[data-dialog-body]");
const target = initialFocus?.current ?? (body && focusables(body)[0]) ?? closeRef.current ?? panel;
target.focus({ preventScroll: true });
}, [open, mounted, initialFocus]);
// Scroll lock and focus containment for as long as the dialog is open.
useEffect(() => {
if (!open) return;
const token = Symbol("dialog");
openStack.push(token);
lockScroll();
function keepFocusInside(event: FocusEvent) {
const panel = panelRef.current;
if (!panel || openStack[openStack.length - 1] !== token) return;
if (event.target instanceof Node && !panel.contains(event.target)) (focusables(panel)[0] ?? panel).focus({ preventScroll: true });
}
document.addEventListener("focusin", keepFocusInside);
return () => {
document.removeEventListener("focusin", keepFocusInside);
openStack.splice(openStack.indexOf(token), 1);
unlockScroll();
const previous = returnFocus.current;
returnFocus.current = null;
if (previous?.isConnected) previous.focus({ preventScroll: true });
};
}, [open]);
function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
if (event.key === "Escape" && !event.defaultPrevented) {
event.stopPropagation();
onOpenChange(false);
return;
}
if (event.key !== "Tab" || !panelRef.current) return;
const items = focusables(panelRef.current);
if (!items.length) {
event.preventDefault();
return;
}
const first = items[0];
const last = items[items.length - 1];
if (event.shiftKey && (document.activeElement === first || document.activeElement === panelRef.current)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
// A click counts as a backdrop click only if it also started there (dragging a text selection out does not close).
function handlePointerDown(event: PointerEvent<HTMLDivElement>) {
pressedBackdrop.current = event.target === event.currentTarget;
}
function handleClick(event: MouseEvent<HTMLDivElement>) {
if (closeOnBackdrop && pressedBackdrop.current && event.target === event.currentTarget) onOpenChange(false);
pressedBackdrop.current = false;
}
if (!mounted || (!open && !present)) return null;
return createPortal(
<div className="fixed inset-0 z-50" onKeyDown={handleKeyDown}>
<div
aria-hidden="true"
className={cn(
"absolute inset-0 bg-black/45 backdrop-blur-[2px] transition-opacity duration-200 starting:opacity-0 dark:bg-black/65",
closing && "opacity-0",
)}
/>
<div
onPointerDown={handlePointerDown}
onClick={handleClick}
className="relative flex h-full items-end justify-center overflow-y-auto sm:items-center sm:p-6"
>
<div
ref={panelRef}
role={role}
aria-modal="true"
aria-labelledby={titleId}
aria-describedby={description ? descriptionId : undefined}
tabIndex={-1}
className={cn(
"relative flex max-h-[92dvh] w-full flex-col overflow-hidden rounded-t-2xl border border-border bg-popover text-popover-foreground outline-hidden",
"shadow-[0_24px_64px_-16px_rgb(0_0_0/0.35)] sm:max-h-[calc(100dvh-3rem)] sm:rounded-xl",
"transition-[opacity,translate,scale] duration-200 ease-[cubic-bezier(.2,.8,.2,1)]",
"starting:opacity-0 motion-safe:starting:translate-y-6 motion-safe:sm:starting:translate-y-2 motion-safe:sm:starting:scale-[0.97]",
closing && "opacity-0 motion-safe:translate-y-4 motion-safe:sm:translate-y-1 motion-safe:sm:scale-[0.98]",
sizes[size],
className,
)}
>
<div className={cn("px-5 pt-5 sm:px-6 sm:pt-6", !hideCloseButton && "pr-12 sm:pr-14")}>
<h2 id={titleId} className="text-lg font-semibold leading-6 tracking-tight text-foreground">{title}</h2>
{description && <p id={descriptionId} className="mt-1.5 text-sm leading-5 text-muted-foreground">{description}</p>}
</div>
{children && (
<div data-dialog-body className="min-h-0 flex-1 overflow-y-auto px-5 pb-5 pt-4 sm:px-6 sm:pb-6">
{children}
</div>
)}
{footer && (
<div
className={cn(
"flex flex-col-reverse gap-2 border-t border-border bg-muted/40 px-5 py-4 sm:flex-row sm:justify-end sm:px-6 dark:bg-muted/20",
!children && "mt-5",
)}
>
{footer}
</div>
)}
{!hideCloseButton && (
<button
ref={closeRef}
type="button"
aria-label="Close"
onClick={() => onOpenChange(false)}
className="absolute right-3 top-3 inline-flex size-8 items-center justify-center rounded-md text-muted-foreground outline-hidden transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 sm:right-4 sm:top-4"
>
<X aria-hidden="true" className="size-4" />
</button>
)}
</div>
</div>
</div>,
document.body,
);
}
