@ehfuse/alerts

API 참조

@ehfuse/alerts의 모든 함수, 인터페이스 및 타입에 대한 상세한 설명입니다.

📋 빠른 참조

함수 목록

함수 설명 타입
SuccessAlert 성공 알림 표시 (message: string) => string
InfoAlert 정보 알림 표시 (message: string) => string
WarningAlert 경고 알림 표시 (message: string) => string
ErrorAlert 오류 알림 표시 (message: string) => string
Alert 범용 알림 함수 (message: string, severity?: AlertSeverity) => void
updateAlert 알림 동적 업데이트 (alertId: string, options: AlertCommonProps) => boolean
AlertDialog 알림 다이얼로그 (params: AlertDialogParams) => Promise<void>
ConfirmDialog 확인 다이얼로그 (params: ConfirmDialogParams) => Promise<boolean>

컴포넌트

컴포넌트 설명 타입
AlertProvider 다이얼로그 제공자 React.FC<AlertProviderProps>

전역 설정 함수

함수 설명 타입
configureAlerts 전역 설정 적용 (config: Partial<AlertGlobalConfig>) => void
resetAlertConfig 설정 초기화 () => void

유틸리티 함수

함수 설명 타입
closeAllAlerts 모든 알림 닫기 () => void
updateAlert 알림 동적 업데이트 (alertId: string, options: AlertCommonProps) => boolean

📋 목차

컴포넌트

AlertProvider

⚠️ 중요: AlertDialogConfirmDialog를 사용하려면 애플리케이션을 AlertProvider로 감싸야 합니다.

const AlertProvider: React.FC<AlertProviderProps>;

다이얼로그 기능을 제공하는 컨텍스트 프로바이더입니다. 애플리케이션의 최상위 레벨에서 사용해야 합니다.

Props:

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

기본 사용법:

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

function App() {
    return (
        <AlertProvider>
            {/* 앱의 나머지 컴포넌트들 */}
            <YourAppComponents />
        </AlertProvider>
    );
}

커스텀 스타일과 함께 사용:

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

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

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

주의사항:

알림 함수

SuccessAlert

성공 알림을 표시합니다.

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

매개변수:

예제:

const alertId = SuccessAlert("작업 완료!");
const alertId2 = SuccessAlert("성공", "파일이 업로드되었습니다.");
const alertId3 = SuccessAlert({
    message: "저장 완료",
    position: "top",
    duration: 3000,
});

// 반환된 alertId로 나중에 업데이트 가능
updateAlert(alertId, { message: "업데이트된 메시지" });

InfoAlert

정보 알림을 표시합니다.

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

매개변수:

예제:

const alertId = InfoAlert("새로운 업데이트가 있습니다.");

// 동적 업데이트 예제
setTimeout(() => {
    updateAlert(alertId, { message: "업데이트가 다운로드 중입니다." });
}, 2000);

InfoAlert("알림", "시스템 점검이 예정되어 있습니다.");

WarningAlert

경고 알림을 표시합니다.

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

매개변수:

예제:

const warningId = WarningAlert("디스크 공간이 부족합니다.");

// 동적 업데이트로 상세 정보 추가
setTimeout(() => {
    updateAlert(warningId, {
        message: "디스크 공간이 부족합니다. 여유 공간을 확보해주세요.",
    });
}, 2000);

WarningAlert("주의", "변경사항이 저장되지 않았습니다.");

ErrorAlert

오류 알림을 표시합니다.

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

매개변수:

예제:

const errorId = ErrorAlert("네트워크 연결 오류입니다.");

// 오류 상태 업데이트
setTimeout(() => {
    updateAlert(errorId, {
        message: "네트워크 연결 오류입니다. 다시 시도해주세요.",
        actionButton: {
            text: "재시도",
            onClick: () => {
                // 재시도 로직
            },
        },
    });
}, 1000);

ErrorAlert("오류", "파일을 찾을 수 없습니다.");

Alert

범용 알림 함수입니다. 모든 타입의 알림을 표시할 수 있는 편의 함수입니다.

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;

매개변수:

예제:

// 기본 경고 알림 (severity 생략시 "warning")
Alert("기본 알림 메시지");

// 특정 타입 알림
Alert("성공 메시지", "success");
Alert("경고 메시지", "warning");

// 옵션과 함께
Alert("커스텀 알림", "error", {
    position: "center",
    duration: 5000,
});

// 객체 형태로
Alert({
    message: "상세 옵션 알림",
    severity: "success",
    title: "완료",
    position: "top",
});

참고: 특정 타입의 알림만 표시하는 경우 SuccessAlert, InfoAlert, WarningAlert, ErrorAlert를 직접 사용하는 것이 더 명확합니다.

InfoAlert

커스터마이즈 가능한 알림을 표시합니다.

function InfoAlert(
    message: string,
    severity?: AlertSeverity,
    options?: AlertOptions,
): void;

매개변수:

예제:

InfoAlert("커스텀 알림", "info", {
    position: "center",
    duration: 5000,
    delay: 1000,
});

다이얼로그 함수

AlertDialog

⚠️ AlertProvider 필수: 이 함수를 사용하려면 앱이 AlertProvider로 감싸져 있어야 합니다.

알림 다이얼로그를 표시합니다.

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

매개변수:

예제:

AlertDialog({
    title: "알림",
    message: "작업이 완료되었습니다.",
    confirmText: "확인",
    onConfirm: () => console.log("확인 클릭"),
    maxWidth: 400,
    customStyles: {
        container: {
            backgroundColor: "#f5f5f5",
        },
    },
});

ConfirmDialog

⚠️ AlertProvider 필수: 이 함수를 사용하려면 앱이 AlertProvider로 감싸져 있어야 합니다.

확인/취소 다이얼로그를 표시합니다.

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

반환값: Promise<boolean> - 사용자가 확인을 선택하면 true, 취소하면 false

예제:

// Promise 방식 - 결과를 await로 받아서 처리
const result = await ConfirmDialog({
    title: "삭제 확인",
    message: "정말로 삭제하시겠습니까?",
    confirmText: "삭제",
    cancelText: "취소",
});

if (result) {
    // 삭제 처리
}

// 콜백 방식 - AlertDialog처럼 onConfirm/onCancel 사용
ConfirmDialog({
    title: "삭제 확인",
    message: "정말로 삭제하시겠습니까?",
    confirmText: "삭제",
    cancelText: "취소",
    onConfirm: () => {
        // 삭제 처리
    },
    onCancel: () => {
        // 취소 처리
    },
});

전역 설정 함수

configureAlerts

전역 알림 설정을 적용합니다.

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

매개변수:

예제:

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

resetAlertConfig

전역 설정을 기본값으로 초기화합니다.

function resetAlertConfig(): void;

유틸리티 함수

closeAllAlerts

현재 표시된 모든 알림을 닫습니다.

function closeAllAlerts(): void;

updateAlert

기존에 표시된 알림의 내용을 동적으로 업데이트합니다. 진행률 표시, 상태 변경 등에 유용합니다.

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

매개변수

매개변수 타입 설명
alertId string 업데이트할 알림의 ID (Alert 함수들이 반환하는 값)
options AlertCommonProps 업데이트할 속성들

반환값

타입 설명
boolean 업데이트 성공 여부 (해당 ID의 알림이 존재하는 경우 true)

예제

// 기본 사용법
const alertId = InfoAlert({
    message: "처리 중...",
    autoHide: false,
});

// 메시지만 업데이트
updateAlert(alertId, {
    message: "처리 완료!",
});

// 여러 속성 동시 업데이트
updateAlert(alertId, {
    message: "✅ 모든 작업이 완료되었습니다!",
    title: "작업 완료",
    showIcon: false,
    autoHide: true,
    delay: 3000,
});

진행률 추적 예제

const trackProgress = async () => {
    const alertId = InfoAlert({
        message: "작업 시작...",
        title: "진행률",
        autoHide: false,
    });

    for (let i = 0; i <= 100; i += 10) {
        await new Promise((resolve) => setTimeout(resolve, 200));
        updateAlert(alertId, {
            message: `진행률: ${i}%`,
            title: `작업 진행 중 (${i}%)`,
        });
    }

    updateAlert(alertId, {
        message: "✅ 완료!",
        title: "작업 완료",
        autoHide: true,
        delay: 2000,
    });
};

타입 정의

AlertSeverity

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

알림의 타입을 정의합니다.

AlertCommonProps

동적으로 업데이트 가능한 공통 알림 속성들을 정의합니다. updateAlert 함수에서 사용됩니다.

interface AlertCommonProps {
    message?: string; // 알림 메시지
    title?: string; // 알림 제목
    autoHide?: boolean; // 자동 숨김 여부
    delay?: number; // 지연 시간 (밀리초)
    showIcon?: boolean; // 아이콘 표시 여부
}

속성 설명

속성 타입 기본값 설명
message string - 알림에 표시될 메시지 텍스트
title string - 알림 제목 (선택사항)
autoHide boolean true 자동으로 알림을 숨길지 여부
delay number 0 알림이 닫히기까지의 지연 시간 (밀리초)
showIcon boolean true 알림 아이콘 표시 여부

AlertPosition

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

알림이 표시될 위치를 정의합니다.

DialogButtonType

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

다이얼로그 버튼의 타입을 정의합니다.

인터페이스

AlertParams

알림의 모든 옵션을 정의하는 인터페이스입니다. AlertCommonProps와 정적 속성들을 결합한 형태입니다.

interface AlertParams extends AlertCommonProps, AlertStaticProps {
    message: string; // message는 필수이므로 재정의
}

실제 타입 정의:

interface AlertParams {
    message: string; // 표시할 메시지 (필수)
    title?: string; // 알림 제목
    position?: AlertPosition; // 표시 위치
    x?: number; // 커스텀 x 좌표
    y?: number; // 커스텀 y 좌표
    anchorEl?: HTMLElement | null; // 앵커 엘리먼트
    duration?: number; // 표시 시간 (밀리초)
    severity?: AlertSeverity; // 알림 타입
    showIcon?: boolean; // 아이콘 표시 여부
    delay?: number; // 지연 시간 (밀리초)
    autoHide?: boolean; // 자동 숨김 여부
}

속성 분류

공통 속성 (동적 업데이트 가능):

정적 속성 (생성 시에만 설정):

AlertOptions

알림의 추가 옵션을 정의하는 인터페이스입니다.

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

속성:

위치 지정 방법:

  1. 화면 기준 위치: position만 사용

     {
         position: "top";
     } // 화면 상단에 표시
    
  2. 절대 좌표 위치: x, y만 사용 (position 없이)

     { x: 100, y: 200 } // 화면의 (100, 200) 위치에 표시
    
  3. 앵커 기준 위치: position + anchorEl 조합

     { position: "bottom", anchorEl: element } // 특정 요소 하단에 표시
    

주의사항:

앵커 기반 알림 예제:

// 버튼 클릭 시 해당 버튼 하단에 알림 표시
const handleClick = (event: React.MouseEvent) => {
    InfoAlert("앵커 기반 알림", "info", {
        position: "bottom",
        anchorEl: event.currentTarget as HTMLElement,
    });
};

마우스 좌표 알림 예제:

// 마우스 현재 위치에 알림 표시
const handleMouseClick = (event: React.MouseEvent) => {
    InfoAlert("마우스 위치 알림", "info", {
        position: "mouse",
    });
};

// 또는 특정 좌표에 알림 표시 (position 없이)
const handleCustomPosition = (event: React.MouseEvent) => {
    InfoAlert("특정 좌표 알림", "info", {
        x: event.clientX,
        y: event.clientY,
    });
};

AlertDialogParams

알림 다이얼로그의 모든 옵션을 정의하는 인터페이스입니다.

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

속성:

ConfirmDialogParams

확인 다이얼로그의 모든 옵션을 정의하는 인터페이스입니다.

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

속성:

참고: onConfirmonCancel을 사용하지 않으면 Promise를 반환하여 결과를 받을 수 있습니다.

AlertGlobalConfig

전역 알림 설정을 정의하는 인터페이스입니다.

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은 화면 상단 기준 전역 시작 오프셋입니다. position: "top"인 첫 번째 알림의 시작 위치를 바꿀 때 사용합니다. 기본값은 50입니다.

AlertSeverityConfig

각 심각도별 스타일 설정을 정의하는 인터페이스입니다.

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;
}

속성:

AlertProviderProps

AlertProvider 컴포넌트의 props를 정의하는 인터페이스입니다.

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

속성:

DialogTexts

다이얼로그 버튼 텍스트를 정의하는 기본 인터페이스입니다.

interface DialogTexts {
    confirmText?: string;
}

속성:

ConfirmDialogTexts

확인 다이얼로그 전용 버튼 텍스트를 정의하는 인터페이스입니다.

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

속성:

DialogCustomStyles

알림 다이얼로그의 커스텀 스타일을 정의하는 인터페이스입니다.

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

속성:

ConfirmDialogCustomStyles

확인 다이얼로그의 커스텀 스타일을 정의하는 인터페이스입니다.

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

속성:

기본값

기본 알림 설정

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

기본 다이얼로그 설정

const defaultDialogOptions = {
    maxWidth: 400,
    confirmText: "확인",
    cancelText: "취소",
};

관련 문서

🌐 온라인 문서

📱 오프라인 접근

패키지 설치 후 node_modules/@ehfuse/alerts/docs/ 경로에서도 문서를 확인할 수 있습니다.

버전 히스토리

v1.0.0