Spaces:
Paused

miracle / frontend /packages /shared /src /contexts /NotificationContext.tsx
dushyantsingh0
backend stabilization
20c290f
Raw History Blame Contribute Delete
2.93 kB
import React, { createContext, useContext, useState, useCallback } from 'react';
import { NexusPopup } from '../components/NexusPopup';
import type { PopupType } from '../components/NexusPopup';
interface NotificationOptions {
title?: string;
confirmLabel?: string;
cancelLabel?: string;
type?: PopupType;
danger?: boolean;
}
interface NotificationContextType {
alert: (message: string, options?: NotificationOptions) => Promise<void>;
confirm: (message: string, options?: NotificationOptions) => Promise<boolean>;
}
const NotificationContext = createContext<NotificationContextType | undefined>(undefined);
export const NotificationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [isOpen, setIsOpen] = useState(false);
const [config, setConfig] = useState<{
title: string;
message: string;
type: PopupType;
confirmLabel: string;
cancelLabel: string;
isConfirm: boolean;
danger: boolean;
resolve: (val: any) => void;
} | null>(null);
const alert = useCallback((message: string, options: NotificationOptions = {}) => {
return new Promise<void>((resolve) => {
setConfig({
title: options.title || 'Notification',
message,
type: options.type || 'info',
confirmLabel: options.confirmLabel || 'Dismiss',
cancelLabel: '',
isConfirm: false,
danger: options.danger || false,
resolve
});
setIsOpen(true);
});
}, []);
const confirm = useCallback((message: string, options: NotificationOptions = {}) => {
return new Promise<boolean>((resolve) => {
setConfig({
title: options.title || 'Confirm Action',
message,
type: options.type || 'warning',
confirmLabel: options.confirmLabel || 'Confirm',
cancelLabel: options.cancelLabel || 'Cancel',
isConfirm: true,
danger: options.danger || false,
resolve
});
setIsOpen(true);
});
}, []);
const handleConfirm = () => {
setIsOpen(false);
config?.resolve(true);
};
const handleCancel = () => {
setIsOpen(false);
config?.resolve(false);
};
return (
<NotificationContext.Provider value={{ alert, confirm }}>
{children}
{config && (
<NexusPopup
isOpen={isOpen}
title={config.title}
message={config.message}
type={config.type}
confirmLabel={config.confirmLabel}
cancelLabel={config.cancelLabel}
isConfirm={config.isConfirm}
onConfirm={handleConfirm}
onCancel={handleCancel}
danger={config.danger}
/>
)}
</NotificationContext.Provider>
);
};
export const useNotification = () => {
const context = useContext(NotificationContext);
if (!context) {
throw new Error('useNotification must be used within a NotificationProvider');
}
return context;
};