Delete a project
Delete Q3 launch opens a small Modal that says what goes to Trash and for how long. Cancel is focused first, so Enter never deletes by accident.
Components / OverlaysStable
Asks for a decision or a short task that must be finished or dismissed before going on, on top of a dimmed page.
'use client'
import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
// Nacre Modal: a decision or a short task that must be finished or dismissed before going on. A native <dialog>
// opened with showModal(): the browser keeps focus inside, makes the page inert and turns Esc into a cancel event.
// React plus Tailwind classes only; needs nacre-theme.css. Motion (WAAPI): the panel scales from .96 and fades in on the
// spring curve (gentle 360, it settles with a small overshoot) and leaves in quick 160 out; the scrim, a light blur of
// the page under the overlay colour, fades with it. It stays centred (a modal has no trigger to grow from). Opened or
// closed from the keyboard, only opacity animates: Modal reads the focused element, or set keyboard when a shortcut
// opens it. Reduced motion or [data-nacre-motion="off"]: no animation. Focus stays inside: showModal() makes the page
// inert, and the first field or Cancel takes focus.
export type ModalSize = 'sm' | 'md' | 'lg'
export type ModalPanelProps = {
title: string
description?: string
children?: ReactNode
footer?: ReactNode
size?: ModalSize
closeLabel?: string
onClose?: () => void
titleId?: string
descriptionId?: string
className?: string
}
export type ModalProps = Omit<ModalPanelProps, 'onClose' | 'titleId' | 'descriptionId'> & {
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
keyboard?: boolean
}
// The scrim blurs the page a little. Set inline (prefixed first) so no CSS minifier can drop either line.
const SCRIM = { WebkitBackdropFilter: 'blur(6px)', backdropFilter: 'blur(6px)' }
const widths: Record<ModalSize, string> = { sm: 'max-w-[24rem]', md: 'max-w-[32rem]', lg: 'max-w-[40rem]' }
/** Reads a duration token (240ms or .24s) in ms from the element, so slow motion stretches it too. */
function tokenMs(el: Element, name: string, fallback: number): number {
const v = getComputedStyle(el).getPropertyValue(name).trim()
const n = parseFloat(v)
if (!Number.isFinite(n)) return fallback
return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n
}
/** Reduced motion (OS) or the Nacre Motion switch off: no movement. */
function motionOk(el: Element): boolean {
return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}
function animateModal(d: HTMLDialogElement, enter: boolean, keyboard: boolean): Promise<unknown> {
if (!motionOk(d)) return Promise.resolve()
const ms = enter ? tokenMs(d, '--nx-dur-gentle', 360) : tokenMs(d, '--nx-dur-quick', 160)
const style = getComputedStyle(d)
const out = style.getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
const spring = style.getPropertyValue('--nx-ease-spring').trim() || out
const opts: KeyframeAnimationOptions = { duration: ms, easing: out, fill: enter ? 'none' : 'forwards' }
const fade = enter ? [{ opacity: 0 }, { opacity: 1 }] : [{ opacity: 1 }, { opacity: 0 }]
const scaleFrames = enter
? [{ opacity: 0, transform: 'scale(.96)' }, { opacity: 1, transform: 'none' }]
: [{ opacity: 1, transform: 'none' }, { opacity: 0, transform: 'scale(.96)' }]
const backdrop = d.querySelector('[data-part="backdrop"]')
const panel = d.querySelector('[data-part="panel"]')
return Promise.all([
backdrop?.animate(fade, opts).finished.catch(() => undefined),
panel?.animate(keyboard ? fade : scaleFrames, enter && !keyboard ? { ...opts, easing: spring } : opts).finished.catch(() => undefined),
])
}
/** The visible sheet. Used inside Modal, and on its own for static previews. Close is last in DOM order, so the
* dialog focuses the first real control (a field or Cancel) when it opens. */
export function ModalPanel({ title, description, children, footer, size = 'md', closeLabel = 'Close', onClose, titleId, descriptionId, className = '' }: ModalPanelProps) {
const auto = useId()
const tid = titleId ?? `${auto}-title`
const did = descriptionId ?? `${auto}-desc`
return (
<div data-part="panel" className={`relative flex max-h-full w-full flex-col overflow-hidden rounded-xl bg-raised text-fg shadow-4 ${widths[size]} ${className}`}>
<div data-part="header" className="flex flex-col gap-1 p-6 pe-16">
<h2 id={tid} data-part="title" className="text-heading-3 text-fg-strong">{title}</h2>
{description && <p id={did} data-part="description" className="text-body text-fg-muted">{description}</p>}
</div>
{children && <div data-part="body" className="min-h-0 flex-1 overflow-y-auto px-6 pb-6 text-body text-fg">{children}</div>}
{footer && <div data-part="footer" className="flex flex-wrap justify-end gap-2 border-t border-line-subtle px-6 py-4">{footer}</div>}
<button
type="button"
data-part="close"
aria-label={closeLabel}
onClick={onClose}
className="absolute end-4 top-4 inline-flex size-10 cursor-pointer items-center justify-center rounded-full border border-line-subtle bg-secondary text-icon-strong shadow-1 transition-colors duration-(--nx-dur-quick) ease-out hover:border-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus"
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-4">
<path d="M4 4l8 8M12 4l-8 8" />
</svg>
</button>
</div>
)
}
export function Modal({ open: openProp, defaultOpen = false, onOpenChange, keyboard = false, ...panel }: ModalProps) {
const id = useId()
const [inner, setInner] = useState(defaultOpen)
const open = openProp ?? inner
const setOpen = (next: boolean) => {
// Already closing (scrim, Close and Esc in a row during the exit): onOpenChange(false) fires once.
if (!next && !want.current) return
if (openProp === undefined) {
setInner(next)
if (!next) want.current = false
}
onOpenChange?.(next)
}
const dialog = useRef<HTMLDialogElement>(null)
const want = useRef(open)
const kbd = useRef(false)
const kbdOpen = useRef(keyboard)
const returnTo = useRef<HTMLElement | null>(null)
const prevOverflow = useRef('')
useEffect(() => {
kbdOpen.current = keyboard
})
useEffect(() => {
want.current = open
const d = dialog.current
if (!d) return
// Keyboard rule: Esc, a focus-visible trigger or button, or the keyboard prop on opening: only opacity animates.
const keys = kbd.current || Boolean(document.activeElement?.matches(':focus-visible'))
kbd.current = false
if (open) {
if (d.open) {
// Reopened during its exit: drop the exit and stay open.
for (const a of d.getAnimations({ subtree: true })) a.cancel()
return
}
returnTo.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
prevOverflow.current = document.documentElement.style.overflow
document.documentElement.style.overflow = 'hidden'
d.showModal()
void animateModal(d, true, keys || kbdOpen.current)
} else if (d.open) {
void animateModal(d, false, keys).then(() => {
if (!want.current && d.open) d.close()
})
}
}, [open])
// Unmounted while open: give the page its scroll back.
useEffect(() => {
const d = dialog.current
return () => {
if (d?.open) document.documentElement.style.overflow = prevOverflow.current
}
}, [])
return (
<dialog
ref={dialog}
aria-labelledby={`${id}-title`}
aria-describedby={panel.description ? `${id}-desc` : undefined}
onCancel={(e) => {
e.preventDefault()
kbd.current = true
setOpen(false)
}}
onClose={() => {
document.documentElement.style.overflow = prevOverflow.current
for (const a of dialog.current?.getAnimations({ subtree: true }) ?? []) a.cancel()
returnTo.current?.focus()
if (want.current) setOpen(false)
}}
data-part="root"
className="fixed inset-0 m-0 size-full max-h-none max-w-none items-center justify-center border-0 bg-transparent p-4 text-fg backdrop:bg-transparent open:flex"
>
<div data-part="backdrop" aria-hidden="true" onClick={() => setOpen(false)} style={SCRIM} className="fixed inset-0 bg-overlay/60" />
<ModalPanel {...panel} onClose={() => setOpen(false)} titleId={`${id}-title`} descriptionId={`${id}-desc`} />
</dialog>
)
}
<dialog aria-labelledby="_R_0_-title" aria-describedby="_R_0_-desc" data-part="root" class="fixed inset-0 m-0 size-full max-h-none max-w-none items-center justify-center border-0 bg-transparent p-4 text-fg backdrop:bg-transparent open:flex">
<div data-part="backdrop" aria-hidden="true" style="-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)" class="fixed inset-0 bg-overlay/60"></div>
<div data-part="panel" class="relative flex max-h-full w-full flex-col overflow-hidden rounded-xl bg-raised text-fg shadow-4 max-w-[32rem] ">
<div data-part="header" class="flex flex-col gap-1 p-6 pe-16">
<h2 id="_R_0_-title" data-part="title" class="text-heading-3 text-fg-strong">Delete Q3 launch?</h2>
<p id="_R_0_-desc" data-part="description" class="text-body text-fg-muted">This moves the project and its 24 tasks to Trash.</p>
</div>
<div data-part="body" class="min-h-0 flex-1 overflow-y-auto px-6 pb-6 text-body text-fg">Members lose access right away. You can restore the project from Trash within 30 days.</div>
<div data-part="footer" class="flex flex-wrap justify-end gap-2 border-t border-line-subtle px-6 py-4">
<button type="button" data-part="root" class="group/button relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center rounded-full font-ui font-[600] whitespace-nowrap transition-[color,background-color,border-color,scale] duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:not-focus-visible:scale-[.97] disabled:cursor-not-allowed aria-disabled:cursor-progress border border-line bg-secondary text-fg-strong enabled:hover:border-line-strong disabled:border-line-subtle disabled:text-fg-disabled h-10 px-4 text-label ">
<span data-part="label" class="inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ">Cancel</span>
</button>
<button type="button" data-part="root" class="group/button relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center rounded-full font-ui font-[600] whitespace-nowrap transition-[color,background-color,border-color,scale] duration-(--nx-dur-quick) ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:not-focus-visible:scale-[.97] disabled:cursor-not-allowed aria-disabled:cursor-progress bg-error-strong text-on-action enabled:hover:bg-error disabled:bg-sunken disabled:text-fg-disabled disabled:shadow-[inset_0_0_0_1px_var(--nx-line-subtle)] h-10 px-4 text-label ">
<span data-part="label" class="inline-flex items-center gap-2 transition-[opacity,filter,scale] duration-(--nx-dur-quick) ease-out ">Delete project</span>
</button>
</div>
<button type="button" data-part="close" aria-label="Close" class="absolute end-4 top-4 inline-flex size-10 cursor-pointer items-center justify-center rounded-full border border-line-subtle bg-secondary text-icon-strong shadow-1 transition-colors duration-(--nx-dur-quick) ease-out hover:border-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus">
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" class="size-4">
<path d="M4 4l8 8M12 4l-8 8"></path>
</svg>
</button>
</div>
</dialog>/* The Tailwind theme lines Modal uses. They come from nacre-theme.css (Resources, Tokens), which also defines
the --nx-* values these lines point at. Import that file once; this list is what this component needs from it. */
@theme inline {
--color-raised: var(--nx-raised);
--color-fg-strong: var(--nx-fg-strong);
--color-fg: var(--nx-fg);
--color-fg-muted: var(--nx-fg-muted);
--color-line-subtle: var(--nx-line-subtle);
--color-line: var(--nx-line);
--color-focus: var(--nx-focus);
--color-icon-strong: var(--nx-icon-strong);
--color-secondary: var(--nx-secondary);
--color-overlay: var(--nx-overlay);
--color-transparent: transparent;
--text-heading-3: 1.25rem;
--text-heading-3--line-height: 1.625rem;
--text-heading-3--letter-spacing: -0.01em;
--text-heading-3--font-weight: 600;
--text-body: 0.875rem;
--text-body--line-height: 1.25rem;
--text-body--letter-spacing: 0em;
--text-body--font-weight: 400;
--spacing: 0.25rem;
--radius-xl: 1.75rem;
--shadow-1: var(--nx-shadow-1);
--shadow-4: var(--nx-shadow-4);
--ease-out: cubic-bezier(.23, 1, .32, 1);
--breakpoint-sm: 40rem;
--breakpoint-md: 48rem;
--breakpoint-lg: 64rem;
}
Delete Q3 launch opens a small Modal that says what goes to Trash and for how long. Cancel is focused first, so Enter never deletes by accident.
Rename in the project menu opens a Modal with one Input and Save. The field is focused when it opens, and Esc puts focus back on the menu button.
DoTitle it with the question: Delete Q3 launch?
Don'tTitle it Are you sure?
DoName the buttons by what they do: Delete project.
Don'tUse OK and Cancel for a destructive choice.
This moves the project and its 24 tasks to Trash.