-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathchatWidgetStore.ts
More file actions
102 lines (86 loc) · 2.32 KB
/
Copy pathchatWidgetStore.ts
File metadata and controls
102 lines (86 loc) · 2.32 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { create } from "zustand";
export type ChatWidgetMode = "minimized" | "expanded";
interface PersistedWidgetState {
mode: ChatWidgetMode;
lastThreadId: string | null;
}
interface ChatWidgetStore extends PersistedWidgetState {
expand: () => void;
minimize: () => void;
setLastThreadId: (id: string) => void;
}
const WIDGET_STORAGE_KEY = "okcode:chat-widget:v1";
function createEmptyState(): PersistedWidgetState {
return {
mode: "expanded",
lastThreadId: null,
};
}
function readPersistedState(): PersistedWidgetState {
if (typeof window === "undefined") {
return createEmptyState();
}
try {
const raw = window.localStorage.getItem(WIDGET_STORAGE_KEY);
if (!raw) {
return createEmptyState();
}
const parsed = JSON.parse(raw) as Partial<PersistedWidgetState>;
return {
mode: parsed.mode === "minimized" || parsed.mode === "expanded" ? parsed.mode : "expanded",
lastThreadId:
typeof parsed.lastThreadId === "string" && parsed.lastThreadId.length > 0
? parsed.lastThreadId
: null,
};
} catch {
return createEmptyState();
}
}
function persistState(state: PersistedWidgetState): void {
if (typeof window === "undefined") {
return;
}
try {
window.localStorage.setItem(
WIDGET_STORAGE_KEY,
JSON.stringify({
mode: state.mode,
lastThreadId: state.lastThreadId,
} satisfies PersistedWidgetState),
);
} catch {
// Ignore storage errors.
}
}
function snapshotState(state: ChatWidgetStore): PersistedWidgetState {
return {
mode: state.mode,
lastThreadId: state.lastThreadId,
};
}
const initialState = readPersistedState();
export const useChatWidgetStore = create<ChatWidgetStore>((set, get) => ({
...initialState,
expand: () => {
set(() => {
const next = { ...snapshotState(get()), mode: "expanded" as const };
persistState(next);
return { mode: "expanded" };
});
},
minimize: () => {
set(() => {
const next = { ...snapshotState(get()), mode: "minimized" as const };
persistState(next);
return { mode: "minimized" };
});
},
setLastThreadId: (id: string) => {
set(() => {
const next = { ...snapshotState(get()), lastThreadId: id };
persistState(next);
return { lastThreadId: id };
});
},
}));