-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathadmin.tsx
More file actions
378 lines (345 loc) · 10.5 KB
/
Copy pathadmin.tsx
File metadata and controls
378 lines (345 loc) · 10.5 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import React, { useEffect, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import "./admin.css";
type AdminSnapshot = {
isPaused: boolean;
isRunningRound: boolean;
done: boolean;
completedInMemory: number;
persistedRounds: number;
viewerCount: number;
};
type AdminResponse = { ok: true } & AdminSnapshot;
type Mode = "checking" | "locked" | "ready";
const RESET_TOKEN = "RESET";
async function readErrorMessage(res: Response): Promise<string> {
const text = await res.text();
if (text) return text;
return `Request failed (${res.status})`;
}
async function requestAdminJson(
path: string,
init?: RequestInit,
): Promise<AdminResponse> {
const headers = new Headers(init?.headers);
if (!headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const response = await fetch(path, {
...init,
headers,
cache: "no-store",
});
if (!response.ok) {
throw new Error(await readErrorMessage(response));
}
return (await response.json()) as AdminResponse;
}
function StatusCard({ label, value }: { label: string; value: string }) {
return (
<div className="status-card">
<div className="status-card__label">{label}</div>
<div className="status-card__value">{value}</div>
</div>
);
}
function App() {
const [mode, setMode] = useState<Mode>("checking");
const [snapshot, setSnapshot] = useState<AdminSnapshot | null>(null);
const [passcode, setPasscode] = useState("");
const [error, setError] = useState<string | null>(null);
const [pending, setPending] = useState<string | null>(null);
const [isResetOpen, setIsResetOpen] = useState(false);
const [resetText, setResetText] = useState("");
useEffect(() => {
let mounted = true;
requestAdminJson("/api/admin/status")
.then((data) => {
if (!mounted) return;
setSnapshot(data);
setMode("ready");
})
.catch(() => {
if (!mounted) return;
setSnapshot(null);
setMode("locked");
});
return () => {
mounted = false;
};
}, []);
const busy = useMemo(() => pending !== null, [pending]);
async function onLogin(event: React.FormEvent) {
event.preventDefault();
setError(null);
setPending("login");
try {
const data = await requestAdminJson("/api/admin/login", {
method: "POST",
body: JSON.stringify({ passcode }),
});
setSnapshot(data);
setPasscode("");
setMode("ready");
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to log in");
} finally {
setPending(null);
}
}
async function runControl(path: string, task: string) {
setError(null);
setPending(task);
try {
const data = await requestAdminJson(path, { method: "POST" });
setSnapshot(data);
} catch (err) {
const message = err instanceof Error ? err.message : "Admin action failed";
if (message.toLowerCase().includes("unauthorized")) {
setMode("locked");
setSnapshot(null);
}
setError(message);
} finally {
setPending(null);
}
}
async function onExport() {
setError(null);
setPending("export");
try {
const response = await fetch("/api/admin/export", { cache: "no-store" });
if (!response.ok) {
throw new Error(await readErrorMessage(response));
}
const blob = await response.blob();
const disposition = response.headers.get("content-disposition") ?? "";
const fileNameMatch = disposition.match(/filename="([^"]+)"/i);
const fileName = fileNameMatch?.[1] ?? `quipslop-export-${Date.now()}.json`;
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = fileName;
document.body.append(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
} catch (err) {
const message = err instanceof Error ? err.message : "Export failed";
if (message.toLowerCase().includes("unauthorized")) {
setMode("locked");
setSnapshot(null);
}
setError(message);
} finally {
setPending(null);
}
}
async function onReset() {
setError(null);
setPending("reset");
try {
const data = await requestAdminJson("/api/admin/reset", {
method: "POST",
body: JSON.stringify({ confirm: RESET_TOKEN }),
});
setSnapshot(data);
setResetText("");
setIsResetOpen(false);
} catch (err) {
setError(err instanceof Error ? err.message : "Reset failed");
} finally {
setPending(null);
}
}
async function onLogout() {
setError(null);
setPending("logout");
try {
await fetch("/api/admin/logout", {
method: "POST",
cache: "no-store",
});
setSnapshot(null);
setPasscode("");
setMode("locked");
} finally {
setPending(null);
}
}
if (mode === "checking") {
return (
<div className="admin admin--centered">
<div className="loading">Checking admin session...</div>
</div>
);
}
if (mode === "locked") {
return (
<div className="admin admin--centered">
<main className="panel panel--login">
<a href="/" className="logo-link">
<img src="/assets/logo.svg" alt="quipslop" />
</a>
<h1>Admin Access</h1>
<p className="muted">
Enter your passcode once. A secure cookie will keep this browser
logged in.
</p>
<form
onSubmit={onLogin}
className="login-form"
autoComplete="off"
data-1p-ignore
data-lpignore="true"
>
<label htmlFor="passcode" className="field-label">
Passcode
</label>
<input
id="passcode"
type="password"
value={passcode}
onChange={(e) => setPasscode(e.target.value)}
className="text-input"
autoFocus
autoComplete="off"
required
data-1p-ignore
data-lpignore="true"
/>
<button
type="submit"
className="btn btn--primary"
disabled={busy || !passcode.trim()}
data-1p-ignore
data-lpignore="true"
>
{pending === "login" ? "Checking..." : "Unlock Admin"}
</button>
</form>
{error && <div className="error-banner">{error}</div>}
<div className="quick-links">
<a href="/">Live Game</a>
<a href="/history">History</a>
</div>
</main>
</div>
);
}
return (
<div className="admin">
<header className="admin-header">
<a href="/" className="logo-link">
quipslop
</a>
<nav className="quick-links">
<a href="/">Live Game</a>
<a href="/history">History</a>
<button className="link-button" onClick={onLogout} disabled={busy}>
Logout
</button>
</nav>
</header>
<main className="panel panel--main">
<div className="panel-head">
<h1>Admin Console</h1>
<p>
Pause/resume the game loop, export all data as JSON, or wipe all
stored data.
</p>
</div>
{error && <div className="error-banner">{error}</div>}
<section className="status-grid" aria-live="polite">
<StatusCard
label="Engine"
value={snapshot?.isPaused ? "Paused" : "Running"}
/>
<StatusCard
label="Active Round"
value={snapshot?.isRunningRound ? "In Progress" : "Idle"}
/>
<StatusCard
label="Persisted Rounds"
value={String(snapshot?.persistedRounds ?? 0)}
/>
<StatusCard label="Viewers" value={String(snapshot?.viewerCount ?? 0)} />
</section>
<section className="actions" aria-label="Admin actions">
<button
type="button"
className="btn btn--primary"
disabled={busy || Boolean(snapshot?.isPaused)}
onClick={() => runControl("/api/admin/pause", "pause")}
>
{pending === "pause" ? "Pausing..." : "Pause"}
</button>
<button
type="button"
className="btn"
disabled={busy || !snapshot?.isPaused}
onClick={() => runControl("/api/admin/resume", "resume")}
>
{pending === "resume" ? "Resuming..." : "Resume"}
</button>
<button type="button" className="btn" disabled={busy} onClick={onExport}>
{pending === "export" ? "Exporting..." : "Export JSON"}
</button>
<button
type="button"
className="btn btn--danger"
disabled={busy}
onClick={() => setIsResetOpen(true)}
>
Reset Data
</button>
</section>
</main>
{isResetOpen && (
<div className="modal-backdrop" role="dialog" aria-modal="true">
<div className="modal">
<h2>Reset all data?</h2>
<p>
This permanently deletes every saved round and resets scores.
Current game flow is also paused.
</p>
<p>
Type <code>{RESET_TOKEN}</code> to continue.
</p>
<input
type="text"
value={resetText}
onChange={(e) => setResetText(e.target.value)}
className="text-input"
placeholder={RESET_TOKEN}
autoFocus
/>
<div className="modal-actions">
<button
type="button"
className="btn"
onClick={() => {
setIsResetOpen(false);
setResetText("");
}}
disabled={busy}
>
Cancel
</button>
<button
type="button"
className="btn btn--danger"
onClick={onReset}
disabled={busy || resetText !== RESET_TOKEN}
>
{pending === "reset" ? "Resetting..." : "Confirm Reset"}
</button>
</div>
</div>
</div>
)}
</div>
);
}
const root = createRoot(document.getElementById("root")!);
root.render(<App />);