|
| 1 | +import type { DNotificationProps } from '@react-devui/ui'; |
| 2 | + |
| 3 | +import { useNotifications } from '../core/state'; |
| 4 | +import { getGlobalKey } from './vars'; |
| 5 | + |
| 6 | +interface NotificationInstance { |
| 7 | + key: string | number; |
| 8 | + close: () => void; |
| 9 | + rerender: (props: DNotificationProps) => void; |
| 10 | +} |
| 11 | + |
| 12 | +export class NotificationService { |
| 13 | + static open(props: Omit<DNotificationProps, 'dVisible'>, _key?: string | number): NotificationInstance { |
| 14 | + const key = _key ?? getGlobalKey(); |
| 15 | + |
| 16 | + useNotifications.setState((draft) => { |
| 17 | + draft.push({ |
| 18 | + ...props, |
| 19 | + key, |
| 20 | + dVisible: true, |
| 21 | + onClose: () => { |
| 22 | + props.onClose?.(); |
| 23 | + |
| 24 | + NotificationService.close(key); |
| 25 | + }, |
| 26 | + afterVisibleChange: (visible) => { |
| 27 | + props.afterVisibleChange?.(visible); |
| 28 | + |
| 29 | + if (!visible) { |
| 30 | + const index = useNotifications.state.findIndex((n) => n.key === key); |
| 31 | + if (index !== -1) { |
| 32 | + useNotifications.setState((draft) => { |
| 33 | + draft.splice(index, 1); |
| 34 | + }); |
| 35 | + } |
| 36 | + } |
| 37 | + }, |
| 38 | + }); |
| 39 | + }); |
| 40 | + |
| 41 | + return { |
| 42 | + key, |
| 43 | + close: () => { |
| 44 | + NotificationService.close(key); |
| 45 | + }, |
| 46 | + rerender: (props) => { |
| 47 | + NotificationService.rerender(key, props); |
| 48 | + }, |
| 49 | + }; |
| 50 | + } |
| 51 | + |
| 52 | + static close(key: string | number) { |
| 53 | + const index = useNotifications.state.findIndex((n) => n.key === key); |
| 54 | + if (index !== -1) { |
| 55 | + useNotifications.setState((draft) => { |
| 56 | + draft[index].dVisible = false; |
| 57 | + }); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + static rerender(key: string | number, props: DNotificationProps) { |
| 62 | + const index = useNotifications.state.findIndex((n) => n.key === key); |
| 63 | + if (index !== -1) { |
| 64 | + useNotifications.setState((draft) => { |
| 65 | + draft.splice(index, 1, { key, ...props }); |
| 66 | + }); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + static closeAll(animation = true) { |
| 71 | + if (animation) { |
| 72 | + useNotifications.setState((draft) => { |
| 73 | + draft.forEach((notification) => { |
| 74 | + notification.dVisible = false; |
| 75 | + }); |
| 76 | + }); |
| 77 | + } else { |
| 78 | + useNotifications.setState([]); |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments