aboutsummaryrefslogtreecommitdiffstats
path: root/ui-web/src/App.tsx
diff options
context:
space:
mode:
authorKostya <mail@sartin.in>2026-10-15 19:35:48 +0300
committerKostya <mail@sartin.in>2026-10-15 19:36:15 +0300
commitc263497ec8b05bc0f9254ed2f7ecb4dba6f67d4e (patch)
treed9b721c72a4ffa2d6256adc305716c8432cb190c /ui-web/src/App.tsx
parentc67d5ff663b876a15a3831f5a2b564c4002e99b6 (diff)
downloadguess-market-master.tar.gz
guess-market-master.tar.xz
guess-market-master.zip
ui-web: add browser client for the Ex4 bonus HEAD4.0master
A React + TypeScript single-page client served by Vite, working against the same servlets as the desktop client: login, the events screen with filters, details, order books and trading, and the account screen with deposit, holdings, ledger rows and the user directory. No file upload, as the exercise specifies. It looks like the desktop client on purpose: the three skins of theme.css as CSS variables, the four animations redone with SVG and keyframes, and the desktop's Nerd Fonts, which npm run dev copies from ui-fx instead of keeping a second copy in the repo. The shared chat sits in a drawer above the status bar, as on the desktop, on its own poll because chat lines don't move the market version. Vite forwards /guess-market to Tomcat on 8080, so the page and the API share an origin and the session cookie needs no CORS. The client polls /api/sync once a second and reloads only when the version moved. run-web.bat installs the packages and starts it on localhost:5173. package.sh stages the sources under build/dist/ex4, without node_modules.
Diffstat (limited to 'ui-web/src/App.tsx')
-rw-r--r--ui-web/src/App.tsx502
1 files changed, 502 insertions, 0 deletions
diff --git a/ui-web/src/App.tsx b/ui-web/src/App.tsx
new file mode 100644
index 0000000..204beae
--- /dev/null
+++ b/ui-web/src/App.tsx
@@ -0,0 +1,502 @@
1import { FormEvent, ReactNode, useCallback, useEffect, useRef, useState } from 'react';
2import {
3 api,
4 ApiError,
5 ChatMessage,
6 CHEVRON,
7 EventDetail,
8 eventPath,
9 GLYPH,
10 Ledger,
11 MarketData,
12 money,
13 num,
14 optionTitle,
15 same,
16 Sync,
17} from './api';
18import { Events } from './Events';
19import { MarketChart, Pinwheel } from './graphics';
20import { Users } from './Users';
21
22export type Act = (work: () => Promise<unknown>, done: string) => Promise<void>;
23
24const SKINS = [
25 ['rose-pine-dawn', 'Rosé Pine Dawn'],
26 ['catppuccin', 'Catppuccin'],
27 ['gruvbox', 'Gruvbox'],
28];
29
30function useSetting(key: string, initial: string): [string, (value: string) => void] {
31 const [value, setValue] = useState(() => {
32 try {
33 return localStorage.getItem(key) ?? initial;
34 } catch {
35 return initial;
36 }
37 });
38 const set = (next: string) => {
39 setValue(next);
40 try {
41 localStorage.setItem(key, next);
42 } catch {
43 }
44 };
45 return [value, set];
46}
47
48export function App() {
49 const [user, setUser] = useState<string | null | undefined>(undefined);
50 const [notice, setNotice] = useState<string | null>(null);
51 const [skin, setSkin] = useSetting('gm-skin', SKINS[0][0]);
52 const [animations, setAnimations] = useSetting('gm-animations', 'on');
53
54 useEffect(() => {
55 document.documentElement.dataset.skin = skin;
56 document.documentElement.classList.toggle('anim', animations === 'on');
57 }, [skin, animations]);
58
59 useEffect(() => {
60 api<Ledger>('/user/account')
61 .then((account) => setUser(account.owner))
62 .catch(() => setUser(null));
63 }, []);
64
65 const leave = useCallback((why?: string) => {
66 setNotice(why ?? null);
67 setUser(null);
68 }, []);
69
70 const controls = (
71 <>
72 <button
73 className={animations === 'on' ? 'btn icon on' : 'btn icon'}
74 title="Toggle animations"
75 aria-label="Toggle animations"
76 aria-pressed={animations === 'on'}
77 onClick={() => setAnimations(animations === 'on' ? 'off' : 'on')}
78 >
79 <Pinwheel />
80 </button>
81 <select className="select" aria-label="Skin" value={skin} onChange={(e) => setSkin(e.target.value)}>
82 {SKINS.map(([id, name]) => (
83 <option key={id} value={id}>
84 {name}
85 </option>
86 ))}
87 </select>
88 </>
89 );
90
91 if (user === undefined) return null;
92 if (user === null) return <Login notice={notice} onLoggedIn={setUser} />;
93 return <Market user={user} onLoggedOut={leave} controls={controls} />;
94}
95
96function Login({ notice, onLoggedIn }: { notice: string | null; onLoggedIn: (user: string) => void }) {
97 const [name, setName] = useState('');
98 const [error, setError] = useState(notice);
99 const [busy, setBusy] = useState(false);
100
101 async function submit(e: FormEvent) {
102 e.preventDefault();
103 setBusy(true);
104 setError(null);
105 try {
106 const res = await api<{ username: string }>('/login', { username: name });
107 onLoggedIn(res.username);
108 } catch (err) {
109 setError((err as Error).message);
110 setBusy(false);
111 }
112 }
113
114 return (
115 <main className="login">
116 <form className="card" onSubmit={submit}>
117 <h1 className="xl bold">Guess Market</h1>
118 <p className="base ink2">Sign in to a market server</p>
119 <label className="base ink2" htmlFor="username" style={{ marginTop: 8 }}>
120 User name
121 </label>
122 <input id="username" className="field" autoFocus value={name} onChange={(e) => setName(e.target.value)} />
123 {error && <p className="base bold no">{error}</p>}
124 <button className="btn primary" style={{ marginTop: 8 }} disabled={busy || name.trim() === ''}>
125 Log in
126 </button>
127 </form>
128 </main>
129 );
130}
131
132function Market(props: { user: string; onLoggedOut: (why?: string) => void; controls: ReactNode }) {
133 const { user, onLoggedOut } = props;
134 const [data, setData] = useState<MarketData | null>(null);
135 const [tab, setTab] = useState<'events' | 'users'>('events');
136 const [selectedKey, setSelectedKey] = useState<string | null>(null);
137 const [dialog, setDialog] = useState<'deposit' | 'resolve' | null>(null);
138 const [offline, setOffline] = useState(false);
139 const [toast, setToast] = useState<string | null>(null);
140 const refresh = useRef<() => Promise<void>>(async () => {});
141
142 useEffect(() => {
143 let stopped = false;
144 let version = -1;
145 let timer: number | undefined;
146
147 async function pull() {
148 const sync = await api<Sync>(`/sync?since=${version}`);
149 if (!sync.changed) return;
150 const details = await Promise.all(sync.events.map((e) => api<EventDetail>(eventPath(e.name))));
151 if (stopped || sync.version < version) return;
152 version = sync.version;
153 setData({
154 events: sync.events,
155 details: Object.fromEntries(details.map((d) => [d.summary.key, d])),
156 users: sync.users,
157 account: sync.account,
158 });
159 }
160
161 async function tick() {
162 try {
163 await pull();
164 setOffline(false);
165 } catch (err) {
166 if (err instanceof ApiError && err.status === 401) {
167 stopped = true;
168 onLoggedOut('Your session ended. Please log in again.');
169 } else {
170 setOffline(true);
171 }
172 }
173 }
174
175 async function loop() {
176 await tick();
177 if (!stopped) timer = window.setTimeout(loop, 1000);
178 }
179
180 refresh.current = tick;
181 loop();
182 return () => {
183 stopped = true;
184 window.clearTimeout(timer);
185 };
186 }, [onLoggedOut]);
187
188 useEffect(() => {
189 if (!toast) return;
190 const timer = window.setTimeout(() => setToast(null), 2500);
191 return () => window.clearTimeout(timer);
192 }, [toast]);
193
194 const act: Act = useCallback(async (work, done) => {
195 try {
196 await work();
197 setToast(done);
198 } catch (err) {
199 setToast((err as Error).message);
200 }
201 await refresh.current();
202 }, []);
203
204 async function logout() {
205 try {
206 await api('/logout', {});
207 } catch {
208 }
209 onLoggedOut();
210 }
211
212 const selected = data?.events.find((e) => e.key === selectedKey) ?? data?.events[0];
213 const detail = selected && data?.details[selected.key];
214
215 return (
216 <div className="app">
217 <div className="windowbar">Guess Market</div>
218
219 <div className="toolbar">
220 <button className="btn primary" onClick={logout}>
221 Log out
222 </button>
223 <div className="path card2 grow">
224 <span className="ink2">{CHEVRON}</span>
225 <span className="ellipsis">{window.location.host}/guess-market</span>
226 </div>
227 {props.controls}
228 </div>
229
230 {offline && <div className="banner">Cannot reach the server. Retrying every second…</div>}
231
232 {data === null || data.events.length === 0 ? (
233 <div className="empty">
234 <MarketChart />
235 <p className="xl bold">{data === null ? 'Loading the market…' : 'No events yet'}</p>
236 {data !== null && (
237 <p className="ink2" style={{ maxWidth: 420 }}>
238 Events are uploaded from the desktop client. They appear here by themselves.
239 </p>
240 )}
241 </div>
242 ) : (
243 <>
244 <div className="tabs">
245 <button className={tab === 'events' ? 'tab on' : 'tab'} onClick={() => setTab('events')}>
246 Events
247 </button>
248 <button className={tab === 'users' ? 'tab on' : 'tab'} onClick={() => setTab('users')}>
249 Users
250 </button>
251 <span className="grow" />
252 <span className="tabinfo">
253 <span style={{ paddingRight: 12 }}>acting as {user}</span>
254 ACCOUNT BALANCE
255 <span className={num(data.account.balance) < 0 ? 'lg bold no' : 'lg bold accent'}>
256 {money(data.account.balance)}
257 </span>
258 </span>
259 </div>
260
261 {/* key: a new element per tab, so the fade-in runs on every switch */}
262 <div className="content fade" key={tab}>
263 {tab === 'events' ? (
264 <Events
265 data={data}
266 user={user}
267 selected={selected}
268 onSelect={setSelectedKey}
269 act={act}
270 onTrade={() => setTab('users')}
271 onResolve={() => setDialog('resolve')}
272 />
273 ) : (
274 <Users
275 data={data}
276 user={user}
277 selected={selected}
278 onSelect={setSelectedKey}
279 act={act}
280 onDeposit={() => setDialog('deposit')}
281 />
282 )}
283 </div>
284 </>
285 )}
286
287 <div className="statusbar">
288 <span className="grow">
289 {data === null
290 ? ` IDLE ${CHEVRON}`
291 : ` ${GLYPH.file} ${user} ${CHEVRON} ${GLYPH.bolt} ${data.events.length} events ${CHEVRON} ${GLYPH.users} ${data.users.length} users`}
292 </span>
293 <Chat user={user} onError={setToast} />
294 </div>
295
296 {dialog === 'deposit' && (
297 <DepositDialog
298 onCancel={() => setDialog(null)}
299 onConfirm={(amount) => {
300 setDialog(null);
301 act(() => api('/user/deposit', { amount }), `Deposited ${money(amount)}`);
302 }}
303 />
304 )}
305 {dialog === 'resolve' && detail && (
306 <ResolveDialog
307 detail={detail}
308 onCancel={() => setDialog(null)}
309 onConfirm={(i) => {
310 setDialog(null);
311 act(
312 () => api(eventPath(detail.summary.name) + '/resolve', { option: detail.state.markets[i].key }),
313 `Event resolved as ${detail.summary.optionNames[i]}`,
314 );
315 }}
316 />
317 )}
318
319 {toast && (
320 <div className="toast" role="status">
321 {toast}
322 </div>
323 )}
324 </div>
325 );
326}
327
328function Chat({ user, onError }: { user: string; onError: (message: string) => void }) {
329 const [messages, setMessages] = useState<ChatMessage[]>([]);
330 const [open, setOpen] = useState(false);
331 const [unread, setUnread] = useState(0);
332 const [text, setText] = useState('');
333 const openRef = useRef(open);
334 openRef.current = open;
335 const list = useRef<HTMLDivElement>(null);
336
337 useEffect(() => {
338 let stopped = false;
339 let last = 0;
340 let timer: number | undefined;
341 async function loop() {
342 try {
343 const said = await api<ChatMessage[]>(`/chat?since=${last}`);
344 if (!stopped && said.length > 0) {
345 last = said[said.length - 1].id;
346 setMessages((m) => [...m, ...said]);
347 if (!openRef.current) setUnread((n) => n + said.length);
348 }
349 } catch {
350 }
351 if (!stopped) timer = window.setTimeout(loop, 1000);
352 }
353 loop();
354 return () => {
355 stopped = true;
356 window.clearTimeout(timer);
357 };
358 }, []);
359
360 useEffect(() => {
361 if (list.current) list.current.scrollTop = list.current.scrollHeight;
362 }, [messages, open]);
363
364 async function send(e: FormEvent) {
365 e.preventDefault();
366 const line = text.trim();
367 if (line === '') return;
368 setText('');
369 try {
370 await api('/chat', { text: line.slice(0, 500) });
371 } catch (err) {
372 onError((err as Error).message);
373 }
374 }
375
376 return (
377 <>
378 <button
379 className={open ? 'chatbtn on' : 'chatbtn'}
380 title="Chat"
381 aria-label="Chat"
382 aria-expanded={open}
383 onClick={() => {
384 setOpen(!open);
385 setUnread(0);
386 }}
387 >
388 {GLYPH.chat}
389 {unread > 0 && ` ${unread}`}
390 </button>
391 {open && (
392 <div className="card chat">
393 <p className="base bold">Chat</p>
394 <div className="chatlist" ref={list}>
395 {messages.map((m) => (
396 <div key={m.id}>
397 <div className={same(m.sender, user) ? 'xs bold accent' : 'xs bold ink2'}>
398 {m.sender} {m.at}
399 </div>
400 <div className="base">{m.text}</div>
401 </div>
402 ))}
403 </div>
404 <form className="row" onSubmit={send}>
405 <input
406 className="field grow"
407 placeholder="Message everyone"
408 autoFocus
409 value={text}
410 onChange={(e) => setText(e.target.value)}
411 />
412 <button className="btn primary" disabled={text.trim() === ''}>
413 Send
414 </button>
415 </form>
416 </div>
417 )}
418 </>
419 );
420}
421
422function DepositDialog(props: { onCancel: () => void; onConfirm: (amount: string) => void }) {
423 const [amount, setAmount] = useState('');
424 const valid = num(amount) > 0;
425 return (
426 <div className="scrim">
427 <form
428 className="card dialog"
429 onSubmit={(e) => {
430 e.preventDefault();
431 if (valid) props.onConfirm(amount.trim());
432 }}
433 >
434 <header>Deposit funds</header>
435 <div>
436 <label className="base ink2" htmlFor="amount">
437 Amount to add to your account
438 </label>
439 <input
440 id="amount"
441 className={amount !== '' && !valid ? 'field bad' : 'field'}
442 style={{ width: '100%' }}
443 autoFocus
444 placeholder="100.00"
445 inputMode="decimal"
446 value={amount}
447 onChange={(e) => setAmount(e.target.value)}
448 />
449 </div>
450 <footer>
451 <button type="button" className="btn" onClick={props.onCancel}>
452 Cancel
453 </button>
454 <button className="btn primary" disabled={!valid}>
455 Deposit
456 </button>
457 </footer>
458 </form>
459 </div>
460 );
461}
462
463function ResolveDialog(props: { detail: EventDetail; onCancel: () => void; onConfirm: (option: number) => void }) {
464 const [option, setOption] = useState<number | null>(null);
465 const e = props.detail.summary;
466 return (
467 <div className="scrim">
468 <div className="card dialog" style={{ width: 470 }}>
469 <header>Close &amp; resolve event</header>
470 <div>
471 <p className="base ink2">
472 Pick the option the event ended with. The contract account is emptied to holders of the winning option; a
473 close-time fee is moved to the market maker. This cannot be undone.
474 </p>
475 <div className="row">
476 {[0, 1].map((i) => (
477 <button
478 key={i}
479 className={`resolveopt ${i === 0 ? 'yes' : 'no'}${option === i ? ' on' : ''}`}
480 onClick={() => setOption(i)}
481 >
482 {optionTitle(e, i)}
483 </button>
484 ))}
485 </div>
486 </div>
487 <footer>
488 <button className="btn" onClick={props.onCancel}>
489 Cancel
490 </button>
491 <button
492 className="btn destructive"
493 disabled={option === null}
494 onClick={() => option !== null && props.onConfirm(option)}
495 >
496 Resolve as {option === null ? '…' : option === 0 ? 'YES' : 'NO'}
497 </button>
498 </footer>
499 </div>
500 </div>
501 );
502}