All files / packages/design-system-2-site/src/components/ui Toast.tsx

95.12% Statements 39/41
91.66% Branches 22/24
87.5% Functions 14/16
94.28% Lines 33/35

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 1423x                                                                     3x       18x 18x 16x     3x   3x               17x 17x   17x 5x     17x 6x 6x 6x     17x           8x               10x           10x   10x     10x   10x 10x 4x 4x 4x 4x 4x       10x   10x   10x       1x 1x                                                        
'use client';
 
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import { CloseIcon, ErrorIcon, InfoIcon, SuccessIcon, WarningIcon } from '@/components/icons';
 
export type ToastType = 'info' | 'success' | 'warning' | 'error';
 
/** A link or action rendered inline after the toast message. Provide `href` for
 *  a navigation link or `onClick` for an action button. */
export interface ToastAction {
  label: string;
  href?: string;
  onClick?: () => void;
}
 
export interface ToastOptions {
  type?: ToastType;
  message: ReactNode;
  action?: ToastAction;
  /** Auto-dismiss after this many ms. `null` (or 0) keeps it until dismissed. */
  duration?: number | null;
  /** Show the close X (default true). */
  dismissible?: boolean;
}
 
interface ToastRecord extends ToastOptions {
  id: number;
}
 
interface ToastContextValue {
  /** Show a toast; returns its id so it can be dismissed programmatically. */
  toast: (options: ToastOptions) => number;
  dismiss: (id: number) => void;
}
 
const ToastContext = createContext<ToastContextValue | null>(null);
 
/** Access the toast API. Must be called under a `<ToastProvider>`. */
export function useToast(): ToastContextValue {
  const ctx = useContext(ToastContext);
  if (!ctx) throw new Error('useToast must be used within a <ToastProvider>');
  return ctx;
}
 
const DEFAULT_DURATION = 5000;
 
const ICONS: Record<ToastType, (props: { className?: string }) => ReactNode> = {
  info: InfoIcon,
  success: SuccessIcon,
  warning: WarningIcon,
  error: ErrorIcon,
};
 
export function ToastProvider({ children }: { children: ReactNode }) {
  const [toasts, setToasts] = useState<ToastRecord[]>([]);
  const nextId = useRef(1);
 
  const dismiss = useCallback((id: number) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);
 
  const toast = useCallback((options: ToastOptions) => {
    const id = nextId.current++;
    setToasts((prev) => [...prev, { ...options, id }]);
    return id;
  }, []);
 
  return (
    <ToastContext.Provider value={{ toast, dismiss }}>
      {children}
      {/* Fixed lower-start viewport. Clicks fall through except on the toasts. */}
      <div className="toast-viewport" role="region" aria-label="Notifications">
        {toasts.map((t) => (
          <ToastItem key={t.id} toast={t} onDismiss={() => dismiss(t.id)} />
        ))}
      </div>
    </ToastContext.Provider>
  );
}
 
function ToastItem({ toast, onDismiss }: { toast: ToastRecord; onDismiss: () => void }) {
  const { type = 'info', message, action, duration = DEFAULT_DURATION, dismissible = true } = toast;
 
  // Auto-dismiss unless there's no duration, it's an error without an explicit
  // duration (sticky by default), or it carries an action the user must be able
  // to reach: auto-hiding actionable content fails WCAG 2.2.1 (Timing
  // Adjustable). The timer pauses while hovered or focused.
  const autoDismiss = !!duration && !action && !(type === 'error' && toast.duration === undefined);
 
  const [paused, setPaused] = useState(false);
  // Time left on the timer, carried across pause / resume so hovering holds the
  // countdown instead of resetting it.
  const remainingRef = useRef<number>(duration || 0);
 
  useEffect(() => {
    if (!autoDismiss || paused) return;
    const startedAt = Date.now();
    const timer = window.setTimeout(onDismiss, remainingRef.current);
    return () => {
      window.clearTimeout(timer);
      remainingRef.current = Math.max(0, remainingRef.current - (Date.now() - startedAt));
    };
  }, [autoDismiss, paused, onDismiss]);
 
  const Icon = ICONS[type];
  // role="alert" is an assertive live region; "status" is polite.
  const role = type === 'error' ? 'alert' : 'status';
 
  return (
    <div
      className={`toast toast--${type}`}
      role={role}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={() => setPaused(false)}
    >
      <span className="toast__icon" aria-hidden="true">
        <Icon />
      </span>
      <div className="toast__body">
        <span>{message}</span>
        {action &&
          (action.href ? (
            <a className="toast__link" href={action.href}>
              {action.label}
            </a>
          ) : (
            <button type="button" className="toast__link" onClick={action.onClick}>
              {action.label}
            </button>
          ))}
      </div>
      {dismissible && (
        <button type="button" className="toast__close" onClick={onDismiss} aria-label="Dismiss notification">
          <CloseIcon />
        </button>
      )}
    </div>
  );
}