luom2645's picture
Upload folder using huggingface_hub
9dd9a58 verified
Raw History Blame
2.36 kB
import React, { createContext, useContext, useState, useCallback } from 'react';
import { NotificationData } from '../types';
import Notification from '../components/UI/Notification';
interface NotificationContextType {
notifications: NotificationData[];
showNotification: (title: string, message: string, type?: 'success' | 'error' | 'warning' | 'info', duration?: number) => void;
removeNotification: (id: string) => void;
clearAll: () => void;
}
const NotificationContext = createContext<NotificationContextType | undefined>(undefined);
export function NotificationProvider({ children }: { children: React.ReactNode }) {
const [notifications, setNotifications] = useState<NotificationData[]>([]);
const showNotification = useCallback((
title: string,
message: string,
type: 'success' | 'error' | 'warning' | 'info' = 'info',
duration: number = 5000
) => {
const id = `notification_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const notification: NotificationData = {
id,
title,
message,
type,
duration,
timestamp: new Date().toISOString(),
};
setNotifications(prev => [...prev, notification]);
// 自动移除通知
if (duration > 0) {
setTimeout(() => {
removeNotification(id);
}, duration);
}
}, []);
const removeNotification = useCallback((id: string) => {
setNotifications(prev => prev.filter(notification => notification.id !== id));
}, []);
const clearAll = useCallback(() => {
setNotifications([]);
}, []);
const value = {
notifications,
showNotification,
removeNotification,
clearAll,
};
return (
<NotificationContext.Provider value={value}>
{children}
{/* 渲染通知组件 */}
<div className="fixed top-4 right-4 z-50 space-y-2">
{notifications.map(notification => (
<Notification
key={notification.id}
notification={notification}
onClose={() => removeNotification(notification.id)}
/>
))}
</div>
</NotificationContext.Provider>
);
}
export function useNotification() {
const context = useContext(NotificationContext);
if (context === undefined) {
throw new Error('useNotification must be used within a NotificationProvider');
}
return context;
}