Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | 105x 105x 105x 105x 713x 158x 77x 77x 77x 77x 77x 77x 424x 424x 424x 424x 424x 424x 67x 67x 67x 45x 45x 67x 424x 67x 273x 5x 5x 268x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 67x 67x 105x 400x 400x 400x 400x 55x 400x 105x 344x | import { Loader2, X } from "lucide-react";
import React, { useCallback, useEffect, useRef } from "react";
/**
* The dialog every form modal in the app is built from.
*
* Nine pages declared their own overlay-plus-panel — `fixed inset-0 … flex
* items-center justify-center` wrapping a `max-w-lg` card — and every one of
* them had the same defect: a panel taller than the viewport is *centred*
* inside a scroll container, and content that overflows the top of a centred
* flex item cannot be scrolled to. The dataset page's "New case" form, which
* is long enough to overflow on a laptop, lost its Name field and its close
* button off the top of the screen with no way to reach them.
*
* `overflow-y-auto` on the overlay does not fix it — that is what those nine
* copies tried. The panel has to be *bounded* instead: a flex column no
* taller than the viewport, whose header and footer hold their place while
* only the body scrolls. That also keeps the title and the Save button
* visible on a long form, which is better than the page-scroll it replaces.
*
* Behaviour none of the copies had and all of them wanted: Escape closes,
* a click on the backdrop closes, focus is trapped inside while it is open
* and restored to whatever opened it on the way out, the page behind it does
* not scroll, and it announces itself to assistive technology.
*
* ```tsx
* <Modal
* title="New case"
* size="lg"
* onClose={close}
* footer={
* <ModalActions
* onCancel={close}
* onConfirm={submit}
* confirmLabel="Save"
* loading={save.isPending}
* />
* }
* >
* …fields…
* </Modal>
* ```
*/
/** Panel width. The body scrolls, so there is no height to choose. */
export type ModalSize = "sm" | "md" | "lg" | "xl";
const WIDTH: Record<ModalSize, string> = {
sm: "max-w-sm",
md: "max-w-md",
lg: "max-w-lg",
xl: "max-w-2xl",
};
export interface ModalProps {
/** Heading, announced as the dialog's name. */
title: React.ReactNode;
/** Lucide icon beside the title. */
icon?: React.ElementType;
/** Explanatory paragraph between the header and the body. */
description?: React.ReactNode;
size?: ModalSize;
/** Pinned below the body — the Cancel/Confirm pair, usually
* {@link ModalActions}. Holds its place while the body scrolls. */
footer?: React.ReactNode;
/**
* A request is in flight: Escape and the backdrop stop closing, because
* dismissing here hides an outcome the user can no longer see.
*/
busy?: boolean;
/** Called by the close button, Escape and a backdrop click. */
onClose: () => void;
children: React.ReactNode;
/** Extra classes on the scrolling body. */
bodyClassName?: string;
}
/** Focusable descendants, in tab order. */
const FOCUSABLE =
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
/**
* How many scroll locks are held — every open modal, and anything else that
* covers the page, like a full-screen chat — and what the page's overflow
* was before the first one was taken.
*
* Counted rather than toggled: a nested dialog closing must not give the
* page its scrollbar back while its parent is still up. The saved value is
* module-level for the same reason — read back per-lock, the *inner* one
* would restore the "hidden" its parent had already set, and the page would
* stay unscrollable once both had gone.
*/
let scrollLocks = 0;
let bodyOverflowBefore = "";
/**
* Stop the page behind scrolling while `active`. Shares one count with
* every modal, so whichever lock is released last gives the scrollbar back.
*/
export function useBodyScrollLock(active = true): void {
useEffect(() => {
if (!active) return;
Eif (scrollLocks === 0) bodyOverflowBefore = document.body.style.overflow;
scrollLocks += 1;
document.body.style.overflow = "hidden";
return () => {
scrollLocks -= 1;
Eif (scrollLocks === 0) document.body.style.overflow = bodyOverflowBefore;
};
}, [active]);
}
/**
* Escape, the focus trap, focus restoration and the body scroll lock.
*
* Exported because {@link ConfirmDialog} is the same dialog with a fixed
* body and a narrower panel, and the behaviour should not differ between the
* two just because their markup does.
*/
export function useModalBehaviour(
ref: React.RefObject<HTMLElement | null>,
{ onClose, busy = false }: { onClose: () => void; busy?: boolean },
): void {
// Read through a ref inside the key handler so a caller passing an inline
// arrow does not re-bind the listener on every render.
const closeRef = useRef(onClose);
closeRef.current = onClose;
const busyRef = useRef(busy);
busyRef.current = busy;
// Lock the page behind the dialog for as long as it is mounted.
useBodyScrollLock();
// Give the dialog focus, and hand it back to whatever opened it. Checked
// rather than forced: a form with an `autoFocus` field has already placed
// the caret where it belongs, and stealing it back to the panel would undo
// that on every mount.
useEffect(() => {
const opener = document.activeElement as HTMLElement | null;
const panel = ref.current;
if (panel && !panel.contains(document.activeElement)) {
const first = panel.querySelector<HTMLElement>(FOCUSABLE);
(first ?? panel).focus({ preventScroll: true });
}
return () => opener?.focus?.({ preventScroll: true });
}, [ref]);
// Escape closes; Tab cycles within the dialog rather than walking out into
// the page behind it, which is inert but still reachable by keyboard.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
if (!busyRef.current) closeRef.current();
return;
}
if (e.key !== "Tab") return;
const panel = ref.current;
Iif (!panel) return;
// Deliberately unfiltered by visibility: `offsetParent` is null for
// every element in jsdom, so a visibility filter would collapse the
// list to whatever already has focus and pin the caret there. The
// selector already excludes disabled controls and `tabindex="-1"`,
// and no dialog here hides a focusable control.
const items = Array.from(panel.querySelectorAll<HTMLElement>(FOCUSABLE));
Iif (items.length === 0) return;
const first = items[0];
const last = items[items.length - 1];
const active = document.activeElement;
if (e.shiftKey && (active === first || !panel.contains(active))) {
e.preventDefault();
last.focus();
} else Eif (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [ref]);
}
export const Modal: React.FC<ModalProps> = ({
title,
icon: Icon,
description,
size = "lg",
footer,
busy = false,
onClose,
children,
bodyClassName = "",
}) => {
const panelRef = useRef<HTMLDivElement>(null);
const titleId = React.useId();
useModalBehaviour(panelRef, { onClose, busy });
// Dismiss on a backdrop press, but only when the press *started* there:
// a drag that begins on a text selection inside the panel and releases
// over the backdrop is not a request to throw the form away.
const onBackdrop = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget && !busy) onClose();
},
[busy, onClose],
);
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40"
onMouseDown={onBackdrop}
>
<div
ref={panelRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
tabIndex={-1}
// `max-h-full` against the padded overlay, and a column whose body is
// the only part allowed to grow: this is what keeps a long form
// reachable instead of overflowing off the top of the screen.
className={`flex flex-col max-h-full w-full ${WIDTH[size]} rounded-2xl bg-white dark:bg-gray-800 shadow-xl outline-none`}
>
<div className="flex items-center justify-between gap-3 px-6 pt-6 pb-4 shrink-0">
<div className="flex items-center gap-2 min-w-0">
{Icon && (
<Icon className="size-4 text-gray-400 dark:text-gray-500 shrink-0" />
)}
<h3
id={titleId}
className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate"
>
{title}
</h3>
</div>
<button
type="button"
aria-label="Close"
onClick={onClose}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors shrink-0"
>
<X className="size-4" />
</button>
</div>
<div
className={`flex-1 overflow-y-auto px-6 pb-6 ${bodyClassName}`.trim()}
>
{description && (
<p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
{description}
</p>
)}
{children}
</div>
{footer && (
<div className="shrink-0 border-t border-gray-100 dark:border-gray-700 px-6 py-4">
{footer}
</div>
)}
</div>
</div>
);
};
export interface ModalActionsProps {
onCancel: () => void;
onConfirm: () => void;
confirmLabel: string;
/** Shown on the confirm button while `loading`; defaults to `<label>…`. */
loadingLabel?: string;
cancelLabel?: string;
/** Lucide icon on the confirm button, replaced by the spinner while
* loading. */
icon?: React.ElementType;
/**
* What the confirm button *does*, not what colour it is. "generative"
* marks an action that asks a model to write something — the violet the
* app already uses for generated content. "danger" marks one that
* destroys something or overrides a refusal, so the button stops looking
* like the ordinary way on.
*/
tone?: "default" | "generative" | "danger";
loading?: boolean;
/** Blocks the confirm button — an incomplete form. `loading` blocks it
* too, so a caller only states what is missing. */
disabled?: boolean;
/** Content on the left of the row — a checkbox, a count, a hint. */
children?: React.ReactNode;
}
/** The Cancel / Confirm pair that closes a {@link Modal}. */
export const ModalActions: React.FC<ModalActionsProps> = ({
onCancel,
onConfirm,
confirmLabel,
loadingLabel,
cancelLabel = "Cancel",
icon: Icon,
tone = "default",
loading = false,
disabled = false,
children,
}) => (
<div className="flex items-center justify-end gap-2">
{children && <div className="mr-auto min-w-0">{children}</div>}
<button
type="button"
onClick={onCancel}
className="px-3 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
>
{cancelLabel}
</button>
<button
type="button"
disabled={disabled || loading}
onClick={onConfirm}
className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium hover:opacity-80 transition-opacity disabled:opacity-40 ${
tone === "generative"
? "bg-violet-600 text-white"
: tone === "danger"
? "bg-red-600 dark:bg-red-500 text-white"
: "bg-gray-900 dark:bg-white text-white dark:text-gray-900"
}`}
>
{loading ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
Icon && <Icon className="size-3.5" />
)}
{loading ? (loadingLabel ?? `${confirmLabel}…`) : confirmLabel}
</button>
</div>
);
export default Modal;
|