@ehfuse/alerts

@ehfuse/alerts 사용 예제

이 문서는 @ehfuse/alerts 라이브러리의 다양한 사용 예제를 제공합니다.

목차

  1. 기본 알림
  2. 동적 알림 업데이트
  3. 위치별 알림
  4. 커스텀 스타일 알림
  5. 다이얼로그 사용

기본 알림

간단한 알림 표시

import {
    SuccessAlert,
    InfoAlert,
    WarningAlert,
    ErrorAlert,
} from "@ehfuse/alerts";

// 기본 알림들
SuccessAlert("작업이 성공적으로 완료되었습니다!");
InfoAlert("새로운 정보가 있습니다.");
WarningAlert("주의가 필요한 사항입니다.");
ErrorAlert("오류가 발생했습니다.");

제목과 함께 표시

// 제목과 메시지 함께 표시
SuccessAlert("작업 완료", "모든 작업이 성공적으로 완료되었습니다.");
InfoAlert("시스템 알림", "새로운 업데이트가 있습니다.");

객체 형태로 알림 설정

InfoAlert({
    message: "우측 상단에 표시되는 알림입니다",
    title: "위치 지정 알림",
    position: "topRight",
    duration: 4000,
    showIcon: true,
    autoHide: true,
});

동적 알림 업데이트

updateAlert 함수 사용법

updateAlert 함수를 사용하면 이미 표시된 알림의 내용을 실시간으로 변경할 수 있습니다.

import { InfoAlert, updateAlert, type AlertCommonProps } from "@ehfuse/alerts";

// 알림 생성 및 ID 받기
const alertId = InfoAlert({
    message: "처리 중...",
    title: "작업 진행",
    autoHide: false,
});

// 알림 내용 업데이트
updateAlert(alertId, {
    message: "새로운 메시지",
    title: "업데이트된 제목",
    showIcon: false,
    autoHide: true,
    delay: 3000,
});

AlertCommonProps 타입

동적으로 업데이트 가능한 속성들:

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

진행률 추적 예제

실시간으로 진행률을 표시하는 알림 예제입니다:

const handleProgressAlert = async () => {
    // 초기 알림 생성
    const alertId = InfoAlert({
        message: "작업 준비 중...",
        title: "진행률 추적",
        autoHide: false,
        showIcon: true,
    });

    // 시작 준비
    await new Promise((resolve) => setTimeout(resolve, 500));
    updateAlert(alertId, {
        message: "작업 진행 중... 0%",
        title: "진행률 추적",
    });

    // 진행률 업데이트 (0~100%)
    for (let progress = 0; progress <= 100; progress += 10) {
        await new Promise((resolve) => setTimeout(resolve, 300));
        const emoji = progress < 50 ? "" : progress < 90 ? "🔄" : "🎯";
        updateAlert(alertId, {
            message: `${emoji} 작업 진행 중... ${progress}%`,
            title: `진행률 추적 (${progress}%)`,
        });
    }

    // 완료 단계 - 아이콘 숨기고 완료 메시지 표시
    updateAlert(alertId, {
        message: "✅ 모든 작업이 완료되었습니다!",
        title: "작업 완료",
        showIcon: false,
    });

    // 3초 후 자동 닫기 활성화
    setTimeout(() => {
        updateAlert(alertId, {
            autoHide: true,
            delay: 2000,
        });
    }, 1000);
};

위치별 알림

화면 기준 위치

// 상단 위치들
InfoAlert({ message: "좌측 상단 알림", position: "topLeft" });
InfoAlert({ message: "상단 중앙 알림", position: "top" });
InfoAlert({ message: "우측 상단 알림", position: "topRight" });

// 중앙 위치들
InfoAlert({ message: "좌측 중앙 알림", position: "left" });
InfoAlert({ message: "중앙 알림", position: "center" });
InfoAlert({ message: "우측 중앙 알림", position: "right" });

// 하단 위치들
InfoAlert({ message: "좌측 하단 알림", position: "bottomLeft" });
InfoAlert({ message: "하단 중앙 알림", position: "bottom" });
InfoAlert({ message: "우측 하단 알림", position: "bottomRight" });

마우스 위치 및 특정 좌표

// 마우스 위치에 표시
InfoAlert({
    message: "마우스 위치에 표시되는 알림입니다",
    position: "mouse",
});

// 특정 좌표에 표시
WarningAlert({
    message: "특정 위치에 표시되는 알림입니다",
    x: 300,
    y: 200,
});

앵커 기반 알림

const handleAnchorAlert = (event: React.MouseEvent) => {
    const anchorElement = event.currentTarget as HTMLElement;

    InfoAlert({
        message: "버튼 기준 위치 알림입니다",
        position: "top",
        anchorEl: anchorElement,
        duration: 4000,
    });
};

// JSX
<button onClick={handleAnchorAlert}>앵커 알림 표시</button>;

커스텀 스타일 알림

지연 시간과 자동 숨김 설정

// 2초 후에 나타나는 알림
WarningAlert({
    message: "2초 후에 나타나는 알림입니다",
    position: "bottom",
    duration: 3000,
    delay: 2000,
    showIcon: true,
});

// 자동으로 닫히지 않는 알림
InfoAlert({
    message: "수동으로 닫아야 하는 알림입니다",
    autoHide: false,
    showIcon: true,
});

아이콘 제어

// 아이콘이 있는 알림
SuccessAlert({
    message: "아이콘이 있는 알림입니다",
    showIcon: true,
});

// 아이콘이 없는 깔끔한 알림
InfoAlert({
    message: "아이콘이 없는 깔끔한 알림입니다",
    showIcon: false,
});

다이얼로그 사용

AlertDialog (확인 버튼만)

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

const showAlert = () => {
    AlertDialog({
        title: "알림 다이얼로그",
        message: "이것은 AlertDialog입니다. 확인 버튼만 있는 다이얼로그입니다.",
        confirmText: "확인했습니다",
        onConfirm: () => {
            SuccessAlert("AlertDialog가 확인되었습니다!");
        },
    });
};

ConfirmDialog (확인/취소 버튼)

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

const showConfirm = async () => {
    const result = await ConfirmDialog({
        title: "확인 다이얼로그",
        message: "계속하시겠습니까?",
        confirmText: "계속하기",
        cancelText: "취소",
        onConfirm: () => {
            SuccessAlert("사용자가 확인을 선택했습니다!");
        },
        onCancel: () => {
            InfoAlert("사용자가 취소를 선택했습니다!");
        },
    });

    if (result) {
        console.log("User confirmed");
    } else {
        console.log("User cancelled");
    }
};

예/아니오 스타일 다이얼로그

const showYesNo = async () => {
    const result = await ConfirmDialog({
        title: "예/아니오 다이얼로그",
        message: "동의하시나요?",
        confirmText: "",
        cancelText: "아니오",
        customStyles: {
            buttonType: "yes-no",
        },
    });
};

전역 알림 제어

모든 알림 닫기

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

const handleCloseAll = () => {
    closeAllAlerts();
};

전역 설정 적용

import { configureAlerts, resetAlertConfig } from "@ehfuse/alerts";

// 전역 설정 적용
const applyGlobalConfig = () => {
    const config = {
        success: {
            backgroundColor: "#4caf50",
            textColor: "#ffffff",
            borderRadius: "12px",
            fontSize: "16px",
        },
        default: {
            duration: 4000,
            position: "topRight",
            showIcon: true,
            autoHide: true,
            topOffset: 72,
        },
    };

    configureAlerts(config);
};

// 설정 리셋
const resetConfig = () => {
    resetAlertConfig();
};

실용적인 사용 패턴

폼 검증 피드백

const validateForm = (formData: any) => {
    if (!formData.email) {
        ErrorAlert("이메일을 입력해주세요.");
        return false;
    }

    if (!formData.password) {
        ErrorAlert("비밀번호를 입력해주세요.");
        return false;
    }

    SuccessAlert("폼 검증이 완료되었습니다!");
    return true;
};

사용자 피드백 수집

const collectFeedback = async () => {
    const result = await ConfirmDialog({
        title: "피드백",
        message: "이 기능이 도움이 되었나요?",
        confirmText: "도움됨",
        cancelText: "개선 필요",
    });

    if (result) {
        SuccessAlert("피드백 감사합니다! 😊");
    } else {
        InfoAlert("소중한 의견 감사합니다. 개선하겠습니다! 🔧");
    }
};

모범 사례

1. 적절한 알림 타입 선택

2. 사용자 경험 고려

3. 성능 최적화

이 예제들을 참고하여 다양한 상황에서 @ehfuse/alerts를 효과적으로 활용해보세요!

관련 문서

🌐 온라인 문서

📱 오프라인 접근

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