Repository navigation
Expand file tree
/
Copy pathprogress-provider.tsx
More file actions
259 lines (246 loc) · 8.12 KB
/
Copy pathprogress-provider.tsx
File metadata and controls
259 lines (246 loc) · 8.12 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import {
readAccountSession,
type AccountSession,
type LearnerUser,
} from "@/features/account/client";
import {
parseAttempts,
parseProgressGeneration,
type AttemptRecord,
} from "./model";
import { createProgressStore } from "./store";
type SyncStatus = "idle" | "syncing" | "synced" | "error";
interface LearnerContextValue {
attempts: AttemptRecord[];
ready: boolean;
storageAvailable: boolean;
user: LearnerUser | null;
accountConfigured: boolean;
csrfToken: string | null;
refreshAccount: () => Promise<void>;
syncStatus: SyncStatus;
syncError: string;
saveAttempt: (attempt: AttemptRecord) => void;
sync: () => Promise<void>;
clearProgress: () => Promise<void>;
importGuestProgress: () => Promise<void>;
}
const LearnerContext = createContext<LearnerContextValue | null>(null);
export function ProgressProvider({ children }: { children: React.ReactNode }) {
const [account, setAccount] = useState<AccountSession>({
configured: false,
user: null,
csrfToken: null,
});
const [accountLoading, setAccountLoading] = useState(true);
const accountRequest = useRef(0);
const user = account.user;
const [syncState, setSyncState] = useState({
scope: "guest",
status: "idle" as SyncStatus,
error: "",
});
const scope = user?.id ?? "guest";
const store = useMemo(() => createProgressStore(scope), [scope]);
const snapshot = useSyncExternalStore(
store.subscribe,
store.getSnapshot,
store.getServerSnapshot,
);
const runExclusive = store.runExclusive;
const refreshAccount = useCallback(async () => {
const version = ++accountRequest.current;
try {
const result = await readAccountSession();
if (accountRequest.current === version) {
setAccount(result);
setAccountLoading(false);
}
} catch {
if (accountRequest.current === version) setAccountLoading(false);
}
}, []);
useEffect(() => {
let active = true;
void Promise.resolve().then(() => {
if (active) return refreshAccount();
});
const refresh = () => {
void refreshAccount();
};
const changed = (event: StorageEvent) => {
if (event.key === "procoderji:auth-change") refresh();
};
window.addEventListener("focus", refresh);
window.addEventListener("storage", changed);
window.addEventListener("procoderji-auth-change", refresh);
return () => {
active = false;
accountRequest.current += 1;
window.removeEventListener("focus", refresh);
window.removeEventListener("storage", changed);
window.removeEventListener("procoderji-auth-change", refresh);
};
}, [refreshAccount]);
const synchronize = useCallback(
(importing?: readonly AttemptRecord[]) =>
runExclusive(async () => {
if (!user) return;
setSyncState({ scope, status: "syncing", error: "" });
const headers = {
"Content-Type": "application/json",
"x-account-id": user.id,
"X-CSRF-Token": account.csrfToken ?? "",
};
try {
const initial = await fetch("/api/platform/progress", {
headers,
cache: "no-store",
});
if (!initial.ok) throw new Error("Progress could not be downloaded.");
const initialBody = await initial.json();
const generation = parseProgressGeneration(initialBody.generation);
if (!generation) throw new Error("Invalid progress response.");
const previousGeneration = store.getGeneration();
if (previousGeneration !== generation) {
const fresh =
previousGeneration === null ? store.getNewAttempts() : [];
store.replace(
[...fresh, ...parseAttempts(initialBody.attempts)],
generation,
);
}
if (importing) store.addMany(importing);
const local = store.getSnapshot().attempts;
if (local.length) {
const write = await fetch("/api/platform/progress", {
method: "POST",
headers,
body: JSON.stringify({ attempts: local, generation }),
});
if (!write.ok) throw new Error("Progress could not be uploaded.");
}
const response = await fetch("/api/platform/progress", {
headers,
cache: "no-store",
});
if (!response.ok)
throw new Error("Progress could not be downloaded.");
const body = await response.json();
const latestGeneration = parseProgressGeneration(body.generation);
if (!latestGeneration) throw new Error("Invalid progress response.");
const remote = parseAttempts(body.attempts);
store.replace(
latestGeneration === generation
? [...remote, ...store.getSnapshot().attempts]
: remote,
latestGeneration,
);
if (importing && latestGeneration !== generation)
throw new Error("Progress changed during import.");
setSyncState({ scope, status: "synced", error: "" });
} catch {
setSyncState({
scope,
status: "error",
error:
"Cloud sync is unavailable. Your progress is still available on this device.",
});
if (importing)
throw new Error(
"Guest import could not be completed. Your guest history is still saved separately; try importing again.",
);
}
}),
[account.csrfToken, runExclusive, scope, store, user],
);
const sync = useCallback(() => synchronize(), [synchronize]);
useEffect(() => {
if (user && snapshot.hydrated) void Promise.resolve().then(sync);
}, [user, snapshot.hydrated, sync]);
const saveAttempt = useCallback(
(attempt: AttemptRecord) => {
store.add(attempt);
if (user) void sync();
},
[store, sync, user],
);
const clearProgress = useCallback(
() =>
runExclusive(async () => {
const deleting = new Set(
store.getSnapshot().attempts.map((attempt) => attempt.id),
);
let generation = store.getGeneration();
if (user) {
const response = await fetch("/api/platform/progress", {
method: "DELETE",
headers: {
"x-account-id": user.id,
"X-CSRF-Token": account.csrfToken ?? "",
},
});
if (!response.ok)
throw new Error(
"Cloud progress could not be deleted. Please try again.",
);
const body = await response.json();
generation = parseProgressGeneration(body.generation);
if (!generation)
throw new Error(
"Deletion could not be verified. Please refresh and try again.",
);
}
store.replace(
store
.getSnapshot()
.attempts.filter((attempt) => !deleting.has(attempt.id)),
generation,
);
}),
[account.csrfToken, runExclusive, store, user],
);
const importGuestProgress = useCallback(async () => {
if (!user) return;
const guest = createProgressStore("guest").getSnapshot().attempts;
await synchronize(guest);
}, [synchronize, user]);
return (
<LearnerContext.Provider
value={{
attempts: snapshot.attempts,
ready: snapshot.hydrated && !accountLoading,
storageAvailable: snapshot.storageAvailable,
user,
accountConfigured: account.configured,
csrfToken: account.csrfToken,
refreshAccount,
syncStatus: syncState.scope === scope ? syncState.status : "idle",
syncError: syncState.scope === scope ? syncState.error : "",
saveAttempt,
sync,
clearProgress,
importGuestProgress,
}}
>
{children}
</LearnerContext.Provider>
);
}
export function useProgress() {
const value = useContext(LearnerContext);
if (!value)
throw new Error("useProgress must be used within ProgressProvider");
return value;
}