NotificationStore.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { MESSAGE_STATUS } from "@/constants";
  2. import { create } from "zustand";
  3. interface NotificationStore {
  4. notifications: any[];
  5. }
  6. interface NotificationAction {
  7. changeNotification: ({
  8. type,
  9. notification,
  10. }: {
  11. type: string;
  12. notification?: any;
  13. }) => void;
  14. }
  15. const initialState = {
  16. notifications: [],
  17. };
  18. export const useNotificationStore = create<
  19. NotificationStore & NotificationAction
  20. >((set, get) => ({
  21. ...initialState,
  22. changeNotification: ({ type, notification }) => {
  23. let new_notification: any = [];
  24. switch (type) {
  25. case "new_msg":
  26. // 新消息添加到数组头部
  27. new_notification = [...notification, ...get().notifications];
  28. break;
  29. case "update_msg":
  30. // 加载更多的消息添加到数组尾部
  31. new_notification = [...get().notifications, ...notification];
  32. break;
  33. case "clear":
  34. if (!notification) {
  35. // 清空所有消息
  36. const notifications = get().notifications;
  37. new_notification = notifications.map((item) => ({
  38. ...item,
  39. is_read: MESSAGE_STATUS.HAS_READ,
  40. }));
  41. } else {
  42. // 清空指定消息
  43. new_notification = get().notifications.map((item) => {
  44. if (notification.includes(item.id)) {
  45. return {
  46. ...item,
  47. is_read: MESSAGE_STATUS.HAS_READ,
  48. };
  49. }
  50. return item;
  51. });
  52. }
  53. break;
  54. default:
  55. new_notification = get().notifications;
  56. }
  57. set({ notifications: new_notification });
  58. },
  59. }));