import { createPortal } from 'react-dom' import { useEffect, useState, type ReactNode } from 'react' export interface ConfirmRequest { title: string /** What will happen, in a sentence or two. */ body: ReactNode /** The confirm button's label, e.g. "Remove 3 tracks". */ confirmLabel: string /** `danger` (default) for destructive actions — a pink button; `primary` * for a caution that is not destruction, e.g. switching library. */ tone?: 'danger' | 'primary' /** A second way to go ahead, as a plain button beside the confirm one * (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */ altLabel?: string onAlt?: () => void onConfirm: () => Promise | void } interface Props extends ConfirmRequest { onClose: () => void } /** A yes/no confirmation for destructive actions. Enter confirms and Esc * cancels, so a confirmed Delete key stays a two-keystroke action. */ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) { const [busy, setBusy] = useState(false) const confirm = async () => { if (busy) return setBusy(true) try { await onConfirm() onClose() } catch { setBusy(false) // the caller has already reported it; allow a retry } } useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !busy) onClose() // A focused button handles its own Enter — otherwise tabbing to Cancel // and pressing Enter would run the destructive action. if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) { e.preventDefault() void confirm() } } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }) return createPortal(
!busy && onClose()} >
e.stopPropagation()} >
{title}
{body}
{altLabel && onAlt && ( )}
, document.body, ) }