From c263497ec8b05bc0f9254ed2f7ecb4dba6f67d4e Mon Sep 17 00:00:00 2001 From: Kostya Date: Thu, 15 Oct 2026 19:35:48 +0300 Subject: ui-web: add browser client for the Ex4 bonus 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. --- ui-web/src/App.tsx | 502 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 502 insertions(+) create mode 100644 ui-web/src/App.tsx (limited to 'ui-web/src/App.tsx') 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 @@ +import { FormEvent, ReactNode, useCallback, useEffect, useRef, useState } from 'react'; +import { + api, + ApiError, + ChatMessage, + CHEVRON, + EventDetail, + eventPath, + GLYPH, + Ledger, + MarketData, + money, + num, + optionTitle, + same, + Sync, +} from './api'; +import { Events } from './Events'; +import { MarketChart, Pinwheel } from './graphics'; +import { Users } from './Users'; + +export type Act = (work: () => Promise, done: string) => Promise; + +const SKINS = [ + ['rose-pine-dawn', 'Rosé Pine Dawn'], + ['catppuccin', 'Catppuccin'], + ['gruvbox', 'Gruvbox'], +]; + +function useSetting(key: string, initial: string): [string, (value: string) => void] { + const [value, setValue] = useState(() => { + try { + return localStorage.getItem(key) ?? initial; + } catch { + return initial; + } + }); + const set = (next: string) => { + setValue(next); + try { + localStorage.setItem(key, next); + } catch { + } + }; + return [value, set]; +} + +export function App() { + const [user, setUser] = useState(undefined); + const [notice, setNotice] = useState(null); + const [skin, setSkin] = useSetting('gm-skin', SKINS[0][0]); + const [animations, setAnimations] = useSetting('gm-animations', 'on'); + + useEffect(() => { + document.documentElement.dataset.skin = skin; + document.documentElement.classList.toggle('anim', animations === 'on'); + }, [skin, animations]); + + useEffect(() => { + api('/user/account') + .then((account) => setUser(account.owner)) + .catch(() => setUser(null)); + }, []); + + const leave = useCallback((why?: string) => { + setNotice(why ?? null); + setUser(null); + }, []); + + const controls = ( + <> + + + + ); + + if (user === undefined) return null; + if (user === null) return ; + return ; +} + +function Login({ notice, onLoggedIn }: { notice: string | null; onLoggedIn: (user: string) => void }) { + const [name, setName] = useState(''); + const [error, setError] = useState(notice); + const [busy, setBusy] = useState(false); + + async function submit(e: FormEvent) { + e.preventDefault(); + setBusy(true); + setError(null); + try { + const res = await api<{ username: string }>('/login', { username: name }); + onLoggedIn(res.username); + } catch (err) { + setError((err as Error).message); + setBusy(false); + } + } + + return ( +
+
+

Guess Market

+

Sign in to a market server

+ + setName(e.target.value)} /> + {error &&

{error}

} + +
+
+ ); +} + +function Market(props: { user: string; onLoggedOut: (why?: string) => void; controls: ReactNode }) { + const { user, onLoggedOut } = props; + const [data, setData] = useState(null); + const [tab, setTab] = useState<'events' | 'users'>('events'); + const [selectedKey, setSelectedKey] = useState(null); + const [dialog, setDialog] = useState<'deposit' | 'resolve' | null>(null); + const [offline, setOffline] = useState(false); + const [toast, setToast] = useState(null); + const refresh = useRef<() => Promise>(async () => {}); + + useEffect(() => { + let stopped = false; + let version = -1; + let timer: number | undefined; + + async function pull() { + const sync = await api(`/sync?since=${version}`); + if (!sync.changed) return; + const details = await Promise.all(sync.events.map((e) => api(eventPath(e.name)))); + if (stopped || sync.version < version) return; + version = sync.version; + setData({ + events: sync.events, + details: Object.fromEntries(details.map((d) => [d.summary.key, d])), + users: sync.users, + account: sync.account, + }); + } + + async function tick() { + try { + await pull(); + setOffline(false); + } catch (err) { + if (err instanceof ApiError && err.status === 401) { + stopped = true; + onLoggedOut('Your session ended. Please log in again.'); + } else { + setOffline(true); + } + } + } + + async function loop() { + await tick(); + if (!stopped) timer = window.setTimeout(loop, 1000); + } + + refresh.current = tick; + loop(); + return () => { + stopped = true; + window.clearTimeout(timer); + }; + }, [onLoggedOut]); + + useEffect(() => { + if (!toast) return; + const timer = window.setTimeout(() => setToast(null), 2500); + return () => window.clearTimeout(timer); + }, [toast]); + + const act: Act = useCallback(async (work, done) => { + try { + await work(); + setToast(done); + } catch (err) { + setToast((err as Error).message); + } + await refresh.current(); + }, []); + + async function logout() { + try { + await api('/logout', {}); + } catch { + } + onLoggedOut(); + } + + const selected = data?.events.find((e) => e.key === selectedKey) ?? data?.events[0]; + const detail = selected && data?.details[selected.key]; + + return ( +
+
Guess Market
+ +
+ +
+ {CHEVRON} + {window.location.host}/guess-market +
+ {props.controls} +
+ + {offline &&
Cannot reach the server. Retrying every second…
} + + {data === null || data.events.length === 0 ? ( +
+ +

{data === null ? 'Loading the market…' : 'No events yet'}

+ {data !== null && ( +

+ Events are uploaded from the desktop client. They appear here by themselves. +

+ )} +
+ ) : ( + <> +
+ + + + + acting as {user} + ACCOUNT BALANCE + + {money(data.account.balance)} + + +
+ + {/* key: a new element per tab, so the fade-in runs on every switch */} +
+ {tab === 'events' ? ( + setTab('users')} + onResolve={() => setDialog('resolve')} + /> + ) : ( + setDialog('deposit')} + /> + )} +
+ + )} + +
+ + {data === null + ? ` IDLE ${CHEVRON}` + : ` ${GLYPH.file} ${user} ${CHEVRON} ${GLYPH.bolt} ${data.events.length} events ${CHEVRON} ${GLYPH.users} ${data.users.length} users`} + + +
+ + {dialog === 'deposit' && ( + setDialog(null)} + onConfirm={(amount) => { + setDialog(null); + act(() => api('/user/deposit', { amount }), `Deposited ${money(amount)}`); + }} + /> + )} + {dialog === 'resolve' && detail && ( + setDialog(null)} + onConfirm={(i) => { + setDialog(null); + act( + () => api(eventPath(detail.summary.name) + '/resolve', { option: detail.state.markets[i].key }), + `Event resolved as ${detail.summary.optionNames[i]}`, + ); + }} + /> + )} + + {toast && ( +
+ {toast} +
+ )} +
+ ); +} + +function Chat({ user, onError }: { user: string; onError: (message: string) => void }) { + const [messages, setMessages] = useState([]); + const [open, setOpen] = useState(false); + const [unread, setUnread] = useState(0); + const [text, setText] = useState(''); + const openRef = useRef(open); + openRef.current = open; + const list = useRef(null); + + useEffect(() => { + let stopped = false; + let last = 0; + let timer: number | undefined; + async function loop() { + try { + const said = await api(`/chat?since=${last}`); + if (!stopped && said.length > 0) { + last = said[said.length - 1].id; + setMessages((m) => [...m, ...said]); + if (!openRef.current) setUnread((n) => n + said.length); + } + } catch { + } + if (!stopped) timer = window.setTimeout(loop, 1000); + } + loop(); + return () => { + stopped = true; + window.clearTimeout(timer); + }; + }, []); + + useEffect(() => { + if (list.current) list.current.scrollTop = list.current.scrollHeight; + }, [messages, open]); + + async function send(e: FormEvent) { + e.preventDefault(); + const line = text.trim(); + if (line === '') return; + setText(''); + try { + await api('/chat', { text: line.slice(0, 500) }); + } catch (err) { + onError((err as Error).message); + } + } + + return ( + <> + + {open && ( +
+

Chat

+
+ {messages.map((m) => ( +
+
+ {m.sender} {m.at} +
+
{m.text}
+
+ ))} +
+
+ setText(e.target.value)} + /> + +
+
+ )} + + ); +} + +function DepositDialog(props: { onCancel: () => void; onConfirm: (amount: string) => void }) { + const [amount, setAmount] = useState(''); + const valid = num(amount) > 0; + return ( +
+
{ + e.preventDefault(); + if (valid) props.onConfirm(amount.trim()); + }} + > +
Deposit funds
+
+ + setAmount(e.target.value)} + /> +
+
+ + +
+
+
+ ); +} + +function ResolveDialog(props: { detail: EventDetail; onCancel: () => void; onConfirm: (option: number) => void }) { + const [option, setOption] = useState(null); + const e = props.detail.summary; + return ( +
+
+
Close & resolve event
+
+

+ Pick the option the event ended with. The contract account is emptied to holders of the winning option; a + close-time fee is moved to the market maker. This cannot be undone. +

+
+ {[0, 1].map((i) => ( + + ))} +
+
+ +
+
+ ); +} -- cgit v1.2.3