All files / src/context/toast ToastContext.ts

97.01% Statements 65/67
66.66% Branches 2/3
100% Functions 1/1
97.01% Lines 65/67

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 681x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x     8x 8x  
/**
 * @file ToastContext.ts
 * @module context/toast/ToastContext
 *
 * @summary
 * Ultra-light toast context: exposes a single function for ephemeral notifications.
 * Kept separate to satisfy react-refresh and to allow reuse across shells (AppShell, AppPublicShell).
 *
 * @enterprise
 * - Provides a simple callback interface for toast notifications
 * - Used by both authenticated (AppShell) and unauthenticated (AppPublicShell) shells
 * - Consumed by page components and dialogs via useToast() hook
 * - No-op default context to prevent errors if used outside provider
 * - Type-safe severity levels matching MUI Alert component
 *
 * @example
 * ```tsx
 * // In a shell:
 * <ToastContext.Provider value={(msg, severity) => showToast(msg, severity)}>
 *   {children}
 * </ToastContext.Provider>
 *
 * // In a component:
 * const toast = useToast();
 * toast('Operation successful', 'success');
 * ```
 */
 
import * as React from 'react';
 
/**
 * Toast function type: message + optional severity level
 * Severity levels match MUI Alert component for consistency
 */
export type ToastFn = (msg: string, severity?: 'success' | 'info' | 'warning' | 'error') => void;
 
/**
 * Global toast context (no-op default).
 * Provides a simple callback to display transient notifications.
 *
 * @remarks
 * Default value is a no-op function to gracefully handle usage outside provider.
 * Actual implementation should check for errors in strict mode.
 */
export const ToastContext = React.createContext<ToastFn>(() => {});
 
/**
 * Access the toast function provided by AppShell or AppPublicShell.
 *
 * @throws Error if used outside of a matching provider
 *
 * @example
 * ```tsx
 * const toast = useToast();
 * toast('Success!', 'success');
 * toast('Warning!', 'warning');
 * ```
 *
 * @returns Toast function to display notifications with optional severity
 */
export const useToast = (): ToastFn => {
  const ctx = React.useContext(ToastContext);
  if (!ctx) {
    throw new Error('useToast must be used within a ToastContext.Provider');
  }
  return ctx;
};