All files / src/components/detail ConfirmDialog.tsx

87.5% Statements 7/8
90.9% Branches 20/22
100% Functions 3/3
100% Lines 7/7

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                                                                                                                    105x     42x         105x                           24x       24x   24x       4x                                                                                                                          
import { Loader2 } from "lucide-react";
import React, { useRef } from "react";
 
import { useModalBehaviour } from "./Modal";
 
/**
 * The "are you sure?" modal that guards a destructive action.
 *
 * Six pages declared their own `DeleteModal` / `ConfirmModal` and several
 * more inlined the same markup in their JSX; `RuleViewer` gave up and called
 * the browser's `confirm()`, which looks nothing like the rest of the app.
 * They differed only in their copy.
 *
 * Behaviour none of the copies had, and every one of them wanted: Escape
 * closes it, a click on the backdrop closes it, focus is trapped inside and
 * restored on the way out, and the dialog is announced as a modal to
 * assistive technology. Because it lives in one place, every call site gets
 * that for free — from `Modal`'s `useModalBehaviour`, so a question and a
 * form behave the same way.
 *
 * This is the *question* dialog: fixed copy and two buttons. A dialog with a
 * form in it is a `Modal`, which scrolls its body rather than its page.
 *
 * ```tsx
 * {confirming && (
 *   <ConfirmDialog
 *     title="Delete Scenario"
 *     body={<>Delete <Strong>{scenario.name}</Strong>? This cannot be undone.</>}
 *     loading={remove.isPending}
 *     onConfirm={() => remove.mutate()}
 *     onCancel={() => setConfirming(false)}
 *   />
 * )}
 * ```
 */
export interface ConfirmDialogProps {
  title: string;
  /** The question. Use {@link Strong} to emphasise the resource's name. */
  body: React.ReactNode;
  /** Lucide icon beside the title. Defaults to none. */
  icon?: React.ElementType;
  confirmLabel?: string;
  /** Shown on the confirm button while `loading`. */
  loadingLabel?: string;
  cancelLabel?: string;
  /** Red confirm button. On by default — this guards destructive actions. */
  destructive?: boolean;
  loading?: boolean;
  /** Failure text, rendered above the buttons so the dialog can stay open. */
  error?: string | null;
  /** Extra content between the body and the buttons — an opt-in checkbox, a
   *  list of what else will be removed. */
  children?: React.ReactNode;
  onConfirm: () => void;
  onCancel: () => void;
}
 
/** Emphasises the resource's name inside a dialog's `body`. */
export const Strong: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => (
  <span className="font-medium text-gray-800 dark:text-gray-200">
    {children}
  </span>
);
 
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
  title,
  body,
  icon: Icon,
  confirmLabel = "Delete",
  loadingLabel,
  cancelLabel = "Cancel",
  destructive = true,
  loading = false,
  error,
  children,
  onConfirm,
  onCancel,
}) => {
  const panelRef = useRef<HTMLDivElement>(null);
  // Escape and the backdrop cancel — but never while the action is in
  // flight, where closing would hide a request the user can no longer see
  // the outcome of.
  useModalBehaviour(panelRef, { onClose: onCancel, busy: loading });
 
  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40"
      onMouseDown={(e) => {
        Iif (e.target === e.currentTarget && !loading) onCancel();
      }}
    >
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-label={title}
        tabIndex={-1}
        className="w-full max-w-sm max-h-full overflow-y-auto rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-xl p-6 space-y-4 outline-none"
      >
        <div className="flex items-center gap-2">
          {Icon && (
            <Icon
              className={`size-5 ${destructive ? "text-red-500" : "text-gray-500 dark:text-gray-400"}`}
            />
          )}
          <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-200">
            {title}
          </h2>
        </div>
 
        <div className="text-sm text-gray-500 dark:text-gray-400">{body}</div>
 
        {children}
 
        {error && (
          <p className="text-xs text-red-600 dark:text-red-400 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/40 px-3 py-2">
            {error}
          </p>
        )}
 
        <div className="flex items-center justify-end gap-3">
          <button
            type="button"
            onClick={onCancel}
            disabled={loading}
            className="px-4 py-2 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
          >
            {cancelLabel}
          </button>
          <button
            type="button"
            onClick={onConfirm}
            disabled={loading}
            className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-white text-sm font-medium hover:opacity-80 disabled:opacity-50 transition-opacity ${
              destructive
                ? "bg-red-600"
                : "bg-gray-900 dark:bg-white dark:text-gray-900"
            }`}
          >
            {loading && <Loader2 className="size-3.5 animate-spin" />}
            {loading ? (loadingLabel ?? `${confirmLabel}…`) : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
};
 
export default ConfirmDialog;