File size: 2,467 Bytes
5f40163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";

export const ARCHIVED_CONVERSATIONS_STORAGE_KEY = "archived-conversations";

interface ArchivedConversationsState {
  archivesByBackendId: Record<string, string[]>;
}

interface ArchivedConversationsActions {
  archiveConversation: (backendId: string, conversationId: string) => void;
  removeArchivedConversation: (
    backendId: string,
    conversationId: string,
  ) => void;
  isArchived: (backendId: string, conversationId: string) => boolean;
}

type ArchivedConversationsStore = ArchivedConversationsState &
  ArchivedConversationsActions;

const initialState: ArchivedConversationsState = {
  archivesByBackendId: {},
};

function getArchivesForBackend(
  archivesByBackendId: Record<string, string[]>,
  backendId: string,
): string[] {
  return archivesByBackendId[backendId] ?? [];
}

export const useArchivedConversationsStore =
  create<ArchivedConversationsStore>()(
    persist(
      (set, get) => ({
        ...initialState,

        archiveConversation: (backendId, conversationId) => {
          const current = getArchivesForBackend(
            get().archivesByBackendId,
            backendId,
          );
          if (current.includes(conversationId)) {
            return;
          }
          set((state) => ({
            archivesByBackendId: {
              ...state.archivesByBackendId,
              [backendId]: [conversationId, ...current],
            },
          }));
        },

        removeArchivedConversation: (backendId, conversationId) => {
          const current = getArchivesForBackend(
            get().archivesByBackendId,
            backendId,
          );
          if (!current.includes(conversationId)) {
            return;
          }
          set((state) => ({
            archivesByBackendId: {
              ...state.archivesByBackendId,
              [backendId]: current.filter((id) => id !== conversationId),
            },
          }));
        },

        isArchived: (backendId, conversationId) =>
          getArchivesForBackend(get().archivesByBackendId, backendId).includes(
            conversationId,
          ),
      }),
      {
        name: ARCHIVED_CONVERSATIONS_STORAGE_KEY,
        storage: createJSONStorage(() => localStorage),
        partialize: (state): ArchivedConversationsState => ({
          archivesByBackendId: state.archivesByBackendId,
        }),
      },
    ),
  );