@ehfuse/alerts

API Reference

Detailed description of all functions, interfaces, and types in @ehfuse/alerts.

📋 Quick Reference

Function List

Function Description Type
SuccessAlert Display success alert (message: string) => string
InfoAlert Display info alert (message: string) => string
WarningAlert Display warning alert (message: string) => string
ErrorAlert Display error alert (message: string) => string
Alert General purpose alert function (message: string, severity?: AlertSeverity) => void
updateAlert Dynamic alert update (alertId: string, options: AlertCommonProps) => boolean
AlertDialog Alert dialog (params: AlertDialogParams) => Promise<void>
ConfirmDialog Confirmation dialog (params: ConfirmDialogParams) => Promise<boolean>

Components

Component Description Type
AlertProvider Dialog provider React.FC<AlertProviderProps>

Global Configuration Functions

Function Description Type
configureAlerts Apply global configuration (config: Partial<AlertGlobalConfig>) => void
resetAlertConfig Reset configuration () => void

Utility Functions

Function Description Type
closeAllAlerts Close all alerts () => void
updateAlert Dynamic alert update (alertId: string, options: AlertCommonProps) => boolean

📋 Table of Contents

Components

AlertProvider

⚠️ Important: To use AlertDialog and ConfirmDialog, your application must be wrapped with AlertProvider.

const AlertProvider: React.FC<AlertProviderProps>;

A context provider that provides dialog functionality. Must be used at the top level of your application.

Props:

interface AlertProviderProps {
    children: React.ReactNode;
    theme?: any;
    dialogStyles?: DialogCustomStyles;
}

Basic Usage:

import React from "react";
import { AlertProvider } from "@ehfuse/alerts";

function App() {
    return (
        <AlertProvider>
            {/* Rest of your app components */}
            <YourAppComponents />
        </AlertProvider>
    );
}

Usage with Custom Styles:

import { AlertProvider } from "@ehfuse/alerts";

const customDialogStyles = {
    container: {
        backgroundColor: "#f5f5f5",
        borderRadius: "12px",
    },
    title: {
        color: "#333",
        fontSize: "18px",
        fontWeight: "bold",
    },
    texts: {
        confirmText: "OK",
        cancelText: "Cancel",
    },
};

function App() {
    return (
        <AlertProvider dialogStyles={customDialogStyles}>
            <YourAppComponents />
        </AlertProvider>
    );
}

Notes:

Alert Functions

SuccessAlert

Displays a success alert.

function SuccessAlert(message: string): string;
function SuccessAlert(title: string, message: string): string;
function SuccessAlert(params: AlertParams): string;

Parameters:

Examples:

const alertId = SuccessAlert("Task completed!");
const alertId2 = SuccessAlert("Success", "File has been uploaded.");
const alertId3 = SuccessAlert({
    message: "Save completed",
    position: "top",
    duration: 3000,
});

// The returned alertId can be used for later updates
updateAlert(alertId, { message: "Updated message" });

InfoAlert

Displays an information alert.

function InfoAlert(message: string): string;
function InfoAlert(title: string, message: string): string;
function InfoAlert(params: AlertParams): string;

Parameters:

Examples:

const alertId = InfoAlert("New update available.");

// Dynamic update example
setTimeout(() => {
    updateAlert(alertId, { message: "Update is downloading..." });
}, 2000);

InfoAlert("Notice", "System maintenance is scheduled.");

WarningAlert

Displays a warning alert.

function WarningAlert(message: string): string;
function WarningAlert(title: string, message: string): string;
function WarningAlert(params: AlertParams): string;

Parameters:

Examples:

const warningId = WarningAlert("Disk space is low.");

// Dynamic update with additional details
setTimeout(() => {
    updateAlert(warningId, {
        message: "Disk space is low. Please free up some space.",
    });
}, 2000);

WarningAlert("Warning", "Changes have not been saved.");

ErrorAlert

Displays an error alert.

function ErrorAlert(message: string): string;
function ErrorAlert(title: string, message: string): string;
function ErrorAlert(params: AlertParams): string;

Parameters:

Examples:

const errorId = ErrorAlert("Network connection error.");

// Update error status
setTimeout(() => {
    updateAlert(errorId, {
        message: "Network connection error. Please try again.",
        actionButton: {
            text: "Retry",
            onClick: () => {
                // Retry logic
            },
        },
    });
}, 1000);

ErrorAlert("Error", "File not found.");

Alert

General purpose alert function. A convenience function that can display all types of alerts.

function Alert(message: string): void;
function Alert(message: string, severity: AlertSeverity): void;
function Alert(
    message: string,
    severity: AlertSeverity,
    options: AlertOptions,
): void;
function Alert(params: AlertParams): void;

Parameters:

Examples:

// Default warning alert (when severity is omitted)
Alert("Default alert message");

// Specific type alert
Alert("Success message", "success");
Alert("Warning message", "warning");

// With options
Alert("Custom alert", "error", {
    position: "center",
    duration: 5000,
});

// Object form
Alert({
    message: "Detailed options alert",
    severity: "success",
    title: "Complete",
    position: "top",
});

Note: If you only need to display a specific type of alert, it’s clearer to use SuccessAlert, InfoAlert, WarningAlert, or ErrorAlert directly.

Dialog Functions

AlertDialog

⚠️ AlertProvider Required: Your app must be wrapped with AlertProvider to use this function.

Displays an alert dialog.

function AlertDialog(params: AlertDialogParams): Promise<void>;

Parameters:

Examples:

AlertDialog({
    title: "Alert",
    message: "Task has been completed.",
    confirmText: "OK",
    onConfirm: () => console.log("OK clicked"),
    maxWidth: 400,
    customStyles: {
        container: {
            backgroundColor: "#f5f5f5",
        },
    },
});

ConfirmDialog

⚠️ AlertProvider Required: Your app must be wrapped with AlertProvider to use this function.

Displays a confirmation/cancel dialog.

function ConfirmDialog(params: ConfirmDialogParams): Promise<boolean>;

Return Value: Promise<boolean> - Returns true if user confirms, false if user cancels

Examples:

// Promise approach - receive result with await
const result = await ConfirmDialog({
    title: "Confirm Delete",
    message: "Are you sure you want to delete?",
    confirmText: "Delete",
    cancelText: "Cancel",
});

if (result) {
    // Handle deletion
}

// Callback approach - use onConfirm/onCancel like AlertDialog
ConfirmDialog({
    title: "Confirm Delete",
    message: "Are you sure you want to delete?",
    confirmText: "Delete",
    cancelText: "Cancel",
    onConfirm: () => {
        // Handle deletion
    },
    onCancel: () => {
        // Handle cancellation
    },
});

Global Configuration Functions

configureAlerts

Applies global alert configuration.

function configureAlerts(config: Partial<AlertGlobalConfig>): void;

Parameters:

Examples:

configureAlerts({
    success: {
        backgroundColor: "#4caf50",
        textColor: "#ffffff",
        icon: <CustomIcon />,
        fontSize: "16px",
        borderRadius: "12px",
    },
    default: {
        duration: 4000,
        position: "top",
        showIcon: true,
        topOffset: 72,
    },
});

resetAlertConfig

Resets global configuration to default values.

function resetAlertConfig(): void;

Utility Functions

closeAllAlerts

Closes all currently displayed alerts.

function closeAllAlerts(): void;

updateAlert

Dynamically updates the content of an existing alert. Useful for progress indicators, status changes, etc.

function updateAlert(alertId: string, options: AlertCommonProps): boolean;

Parameters

Parameter Type Description
alertId string ID of the alert to update (returned by Alert functions)
options AlertCommonProps Properties to update

Return Value

Type Description
boolean Success status of update (returns true if alert ID exists)

Examples

// Basic usage
const alertId = InfoAlert({
    message: "Processing...",
    autoHide: false,
});

// Update message only
updateAlert(alertId, {
    message: "Processing complete!",
});

// Update multiple properties at once
updateAlert(alertId, {
    message: "✅ All tasks completed!",
    title: "Task Complete",
    showIcon: false,
    autoHide: true,
    delay: 3000,
});

Progress Tracking Example

const trackProgress = async () => {
    const alertId = InfoAlert({
        message: "Starting task...",
        title: "Progress",
        autoHide: false,
    });

    for (let i = 0; i <= 100; i += 10) {
        await new Promise((resolve) => setTimeout(resolve, 200));
        updateAlert(alertId, {
            message: `Progress: ${i}%`,
            title: `Working (${i}%)`,
        });
    }

    updateAlert(alertId, {
        message: "✅ Complete!",
        title: "Task Complete",
        autoHide: true,
        delay: 2000,
    });
};

Type Definitions

AlertSeverity

type AlertSeverity = "success" | "info" | "warning" | "error";

Defines the type of alert.

AlertCommonProps

Defines common alert properties that can be dynamically updated. Used in the updateAlert function.

interface AlertCommonProps {
    message?: string; // Alert message
    title?: string; // Alert title
    autoHide?: boolean; // Auto-hide enabled
    delay?: number; // Delay time (milliseconds)
    showIcon?: boolean; // Show icon
}

Property Description

Property Type Default Description
message string - Message text to display in the alert
title string - Alert title (optional)
autoHide boolean true Whether to automatically hide the alert
delay number 0 Delay time before closing the alert (ms)
showIcon boolean true Whether to display the alert icon

AlertPosition

type AlertPosition =
    | "topLeft"
    | "top"
    | "topRight"
    | "center"
    | "bottomLeft"
    | "bottom"
    | "bottomRight"
    | "left"
    | "right"
    | "mouse";

Defines where the alert will be displayed.

DialogButtonType

type DialogButtonType = "confirm-cancel" | "yes-no";

Defines the type of dialog buttons.

Interfaces

AlertParams

Interface that defines all options for alerts. Combines AlertCommonProps with static properties.

interface AlertParams extends AlertCommonProps, AlertStaticProps {
    message: string; // message is required, so redefined
}

Actual type definition:

interface AlertParams {
    message: string; // Message to display (required)
    title?: string; // Alert title
    position?: AlertPosition; // Display position
    x?: number; // Custom x coordinate
    y?: number; // Custom y coordinate
    anchorEl?: HTMLElement | null; // Anchor element
    duration?: number; // Display duration (milliseconds)
    severity?: AlertSeverity; // Alert type
    showIcon?: boolean; // Show icon
    delay?: number; // Delay time (milliseconds)
    autoHide?: boolean; // Auto-hide enabled
}

Property Classification

Common Properties (dynamically updatable):

Static Properties (set only at creation):

AlertOptions

Interface that defines additional options for alerts.

interface AlertOptions {
    title?: string;
    position?: AlertPosition;
    x?: number;
    y?: number;
    anchorEl?: HTMLElement | null;
    duration?: number;
    showIcon?: boolean;
    delay?: number;
    autoHide?: boolean;
}

Properties:

Position Specification Methods:

  1. Screen-relative position: Use position only

     {
         position: "top";
     } // Display at top of screen
    
  2. Absolute coordinate position: Use x, y only (without position)

     { x: 100, y: 200 } // Display at screen position (100, 200)
    
  3. Anchor-relative position: Combine position + anchorEl

     { position: "bottom", anchorEl: element } // Display below specific element
    

Notes:

Anchor-based Alert Example:

// Display alert below button when button is clicked
const handleClick = (event: React.MouseEvent) => {
    InfoAlert("Anchor-based alert", "info", {
        position: "bottom",
        anchorEl: event.currentTarget as HTMLElement,
    });
};

Mouse Coordinate Alert Example:

// Display alert at current mouse position
const handleMouseClick = (event: React.MouseEvent) => {
    InfoAlert("Mouse position alert", "info", {
        position: "mouse",
    });
};

// Or display alert at specific coordinates (without position)
const handleCustomPosition = (event: React.MouseEvent) => {
    InfoAlert("Specific coordinate alert", "info", {
        x: event.clientX,
        y: event.clientY,
    });
};

AlertDialogParams

Interface that defines all options for alert dialogs.

interface AlertDialogParams {
    title?: string;
    message: string;
    confirmText?: string;
    onConfirm?: () => void;
    maxWidth?: string | number;
    customStyles?: DialogCustomStyles;
}

Properties:

ConfirmDialogParams

Interface that defines all options for confirmation dialogs.

interface ConfirmDialogParams {
    title?: string;
    message: string;
    confirmText?: string;
    cancelText?: string;
    maxWidth?: string | number;
    onConfirm?: () => void;
    onCancel?: () => void;
    customStyles?: ConfirmDialogCustomStyles;
}

Properties:

Note: If you don’t use onConfirm and onCancel, the function returns a Promise to receive the result.

AlertGlobalConfig

Interface that defines global alert configuration.

interface AlertGlobalConfig {
    success?: AlertSeverityConfig;
    info?: AlertSeverityConfig;
    warning?: AlertSeverityConfig;
    error?: AlertSeverityConfig;
    default?: {
        duration?: number;
        position?: AlertPosition;
        showIcon?: boolean;
        autoHide?: boolean;
        animation?: string;
        topOffset?: number;
    };
}

default.topOffset is the global start offset from the top of the viewport. Use it to change the first alert position for position: "top". The default value is 50.

AlertSeverityConfig

Interface that defines style configuration for each severity level.

interface AlertSeverityConfig {
    backgroundColor?: string;
    textColor?: string;
    borderColor?: string;
    iconColor?: string;
    icon?: React.ReactElement;
    fontSize?: string | number;
    fontWeight?: string | number;
    borderRadius?: string | number;
    padding?: string;
    margin?: string;
    marginTop?: string | number;
    boxShadow?: string;
    minWidth?: string | number;
    maxWidth?: string | number;
}

Properties:

AlertProviderProps

Interface that defines props for the AlertProvider component.

interface AlertProviderProps {
    children: React.ReactNode;
    theme?: any;
    dialogStyles?: DialogCustomStyles;
}

Properties:

DialogTexts

Base interface that defines dialog button text.

interface DialogTexts {
    confirmText?: string;
}

Properties:

ConfirmDialogTexts

Interface that defines button text specific to confirmation dialogs.

interface ConfirmDialogTexts {
    confirmText?: string;
    cancelText?: string;
    yesText?: string;
    noText?: string;
}

Properties:

DialogCustomStyles

Interface that defines custom styles for alert dialogs.

interface DialogCustomStyles {
    container?: DialogContainerStyles;
    title?: DialogTitleStyles;
    content?: DialogContentStyles;
    actions?: DialogActionStyles;
    texts?: DialogTexts;
    divider?: boolean;
    dividerWidth?: string;
    dividerColor?: string;
}

Properties:

ConfirmDialogCustomStyles

Interface that defines custom styles for confirmation dialogs.

interface ConfirmDialogCustomStyles extends Omit<DialogCustomStyles, "texts"> {
    texts?: ConfirmDialogTexts;
    buttonType?: DialogButtonType;
}

Properties:

Default Values

Default Alert Configuration

const defaultAlertOptions = {
    position: "top",
    duration: 4000,
    showIcon: true,
    delay: 0,
    autoHide: true,
};

Default Dialog Configuration

const defaultDialogOptions = {
    maxWidth: 400,
    confirmText: "OK",
    cancelText: "Cancel",
};

🌐 Online Documentation

📱 Offline Access

Documentation is also available in the node_modules/@ehfuse/alerts/docs/ folder after package installation.

Version History

v1.0.0