SPB Git

Repository Public

Leaderboard.tsx 16.1 KB 299 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : apps/web/src/pages/Leaderboard.tsx9 * Module           : pages10 * Repository       : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website  : https://jeux.uqo-eval.app12 * Created          : 2026-11-2513 * Last Modified    : 2026-11-2514 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { AnimatePresence, motion } from "motion/react";44import { useCallback, useEffect, useMemo, useRef, useState } from "react";45import { Link, useLocation } from "wouter";46import { formatPercent, ordinal } from "@jeux/engine/format";47import { formatDeadline, formatMoney } from "@jeux/engine/format";48import { Countdown } from "../components/Countdown";49import { IconFlame, IconSearch } from "../components/Icons";50import { Logo } from "../components/Logo";51import { ApiError, api } from "../lib/api";52import { prefersReducedMotion, useGames } from "../lib/store";53import type { LeaderboardData, LeaderboardRow, PublicCompetition } from "../lib/types";5455interface BoardIndex {56  competitions: PublicCompetition[];57  daily: { id: string; name: string } | null;58}5960const COURSE_FILTERS = [61  { key: "", label: "Général" },62  { key: "IMM1003", label: "IMM1003" },63  { key: "IMM1033", label: "IMM1033" },64];6566function Podium({ rows }: { rows: LeaderboardRow[] }) {67  // Disposition classique : 2e à gauche, 1er au centre, 3e à droite.68  const order = [2, 1, 3];69  const reduced = prefersReducedMotion();70  return (71    <ol role="list" className="podium" aria-label="Podium">72      {order.map((place) => {73        const tied = rows.filter((r) => r.rank === place);74        const delay = place === 1 ? 0.75 : place === 2 ? 0.4 : 0.1;75        return (76          <li key={place} className="podium-step" data-place={place}>77            <motion.div initial={reduced ? false : { opacity: 0, y: 14 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: delay + 0.5, duration: 0.5 }} className="stack" style={{ "--gap": "2px" } as React.CSSProperties}>78              {tied.length === 0 ? (79                <p className="muted small">À conquérir</p>80              ) : (81                tied.map((r) => (82                  <div key={r.sessionId}>83                    <p className="podium-name">{r.displayName}</p>84                    <p className="small muted tabular">{r.correct} / {r.total} · {formatPercent(r.mape, 1)}</p>85                    {r.prize !== null && <p className="tag tag-gold">Carte-cadeau {formatMoney(r.prize)}{r.prizeTied ? " · tirage au sort" : ""}</p>}86                  </div>87                ))88              )}89            </motion.div>90            <motion.div className="podium-block" initial={reduced ? false : { scaleY: 0 }} animate={{ scaleY: 1 }} transition={{ delay, duration: 0.8, ease: [0.16, 1, 0.3, 1] }}>91              <span className="num">{place}</span>92              <span className="sr-only">{place === 1 ? "Première place, or" : place === 2 ? "Deuxième place, argent" : "Troisième place, bronze"}</span>93            </motion.div>94          </li>95        );96      })}97    </ol>98  );99}100101export default function Leaderboard({ id }: { id?: string }) {102  const [, navigate] = useLocation();103  const games = useGames();104  const [index, setIndex] = useState<BoardIndex | null>(null);105  const [data, setData] = useState<LeaderboardData | null>(null);106  const [course, setCourse] = useState("");107  const [search, setSearch] = useState("");108  const [page, setPage] = useState(1);109  const [error, setError] = useState<string | null>(null);110  const [live, setLive] = useState(false);111  const [changed, setChanged] = useState<Record<string, "up" | "down">>({});112  const previous = useRef<Map<string, number>>(new Map());113114  useEffect(() => {115    document.title = "Classement — Le Grand Défi Immobilier";116    void api<BoardIndex>("/api/v1/leaderboard").then(setIndex).catch((e) => setError(e instanceof ApiError ? e.message : "Classement indisponible."));117  }, []);118119  const currentId = id ?? index?.competitions.find((c) => c.state === "ouverte")?.id ?? index?.competitions[0]?.id ?? index?.daily?.id;120  const me = useMemo(() => games.find((g) => g.competitionId === currentId)?.id ?? null, [games, currentId]);121122  const load = useCallback(async () => {123    if (!currentId) return;124    try {125      const params = new URLSearchParams({ page: String(page) });126      if (course) params.set("cours", course);127      if (search.trim()) params.set("q", search.trim());128      const next = await api<LeaderboardData>(`/api/v1/leaderboard/${currentId}?${params}`, { game: me });129      const moves: Record<string, "up" | "down"> = {};130      for (const row of next.rows) {131        const before = previous.current.get(row.sessionId);132        if (before !== undefined && before !== row.rank) moves[row.sessionId] = row.rank < before ? "up" : "down";133        previous.current.set(row.sessionId, row.rank);134      }135      setChanged(moves);136      setData(next);137      setError(null);138    } catch (e) {139      setError(e instanceof ApiError ? e.message : "Classement indisponible.");140    }141  }, [currentId, course, me, page, search]);142143  useEffect(() => {144    const t = window.setTimeout(() => void load(), search ? 250 : 0);145    return () => window.clearTimeout(t);146  }, [load, search]);147148  // Mises à jour en direct : le serveur signale un changement, on relit le classement.149  useEffect(() => {150    if (!currentId) return;151    const source = new EventSource(`/api/v1/leaderboard/${currentId}/stream`);152    let timer = 0;153    const refresh = (): void => {154      window.clearTimeout(timer);155      timer = window.setTimeout(() => void load(), 300);156    };157    source.addEventListener("progress", refresh);158    source.addEventListener("completed", refresh);159    source.onopen = () => setLive(true);160    source.onerror = () => setLive(false);161    return () => {162      window.clearTimeout(timer);163      source.close();164    };165  }, [currentId, load]);166167  const pages = data ? Math.max(1, Math.ceil(data.matches / data.pageSize)) : 1;168  const options = [...(index?.competitions ?? []).map((c) => ({ id: c.id, label: `${c.name}${c.state === "terminee" ? " (terminée)" : ""}` })), ...(index?.daily ? [{ id: index.daily.id, label: index.daily.name }] : [])];169170  return (171    <div className="theme-night board">172      <header className="topbar">173        <Link href="/"><Logo /></Link>174        <Link href="/" className="btn btn-primary">Jouer</Link>175      </header>176      <main id="contenu" className="wrap" style={{ paddingBottom: "var(--s-9)" }}>177        <div className="board-head">178          <div className="row" style={{ justifyContent: "space-between" }}>179            <p className="kicker">Classement officiel</p>180            <p className="live-badge" role="status"><span className="live-dot" style={{ background: live ? "var(--success)" : "var(--stone-2)", animation: live ? undefined : "none" }} aria-hidden="true" />{live ? "En direct" : "Hors ligne"}</p>181          </div>182          <h1 className="display">{data?.competition.name ?? "Classement"}</h1>183          {options.length > 1 && (184            <div className="field" style={{ maxWidth: 420 }}>185              <label htmlFor="competition">Compétition</label>186              <select id="competition" className="input" value={currentId ?? ""} onChange={(e) => { setPage(1); previous.current.clear(); navigate(`/classement/${e.target.value}`); }}>187                {options.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}188              </select>189            </div>190          )}191          {data?.competition.endsAt && data.competition.status === "published" && (192            <div className="deadline deadline-board">193              <Countdown endsAt={data.competition.endsAt} label="Temps restant pour terminer" />194              <p className="small muted">Les parties doivent être terminées avant le {formatDeadline(data.competition.endsAt)}. Seules les parties complètes sont classées.</p>195            </div>196          )}197          {data && <p className="muted">{data.totalFinished} partie{data.totalFinished > 1 ? "s" : ""} terminée{data.totalFinished > 1 ? "s" : ""} · {data.inProgress.length} en cours. Seules les parties terminées sont classées.</p>}198        </div>199200        {error && <p className="error-text" role="alert">{error}</p>}201        {!data && !error && <div style={{ display: "grid", placeItems: "center", padding: "var(--s-8)" }}><span className="spinner" /></div>}202203        {data && (204          <>205            {page === 1 && !search && <Podium rows={data.podium} />}206            {data.competition.prizes && (207              <p className="small muted" style={{ textAlign: "center", marginBottom: "var(--s-5)" }}>208                Prix : {data.competition.prizes.label.toLowerCase()} de {data.competition.prizes.amounts.map((a) => formatMoney(a)).join(", ")} aux trois meilleurs scores parmi les étudiants des groupes IMM1003 et IMM1033.{" "}209                {data.competition.status === "published" ? "Attribution provisoire tant que la compétition est ouverte." : "Attribution finale."}210              </p>211            )}212213            {data.me && (214              <p className="callout">215                {data.me.horsConcours ? <>Vous jouez <strong>hors concours</strong> : </> : <>Vous êtes <strong>{ordinal(data.me.rank)}</strong>{data.me.tied ? " (ex æquo)" : ""} avec </>}{data.me.correct} / {data.me.total}.216              </p>217            )}218219            <div className="board-tools">220              <div className="row" role="radiogroup" aria-label="Filtrer par groupe">221                {COURSE_FILTERS.map((f) => (222                  <button key={f.key} type="button" role="radio" aria-checked={course === f.key} className="chip" onClick={() => { setCourse(f.key); setPage(1); previous.current.clear(); }}>{f.label}</button>223                ))}224              </div>225              <div className="search">226                <IconSearch size={18} />227                <label htmlFor="recherche" className="sr-only">Rechercher un participant</label>228                <input id="recherche" className="input" type="search" placeholder="Rechercher un nom" value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }} />229              </div>230            </div>231232            <div className="board-table-wrap">233              <table className="table">234                <caption className="sr-only">Classement des parties terminées, du meilleur au moins bon</caption>235                <thead>236                  <tr>237                    <th scope="col">Rang</th>238                    <th scope="col">Participant</th>239                    <th scope="col" className="hide-mobile">Groupe</th>240                    <th scope="col" className="right">Score</th>241                    <th scope="col" className="right">Erreur moy.</th>242                    <th scope="col" className="right hide-mobile">Série</th>243                  </tr>244                </thead>245                <tbody>246                  <AnimatePresence initial={false}>247                    {data.rows.map((row) => (248                      <motion.tr key={row.sessionId} layout={!prefersReducedMotion()} className={`board-row${row.isMe ? " is-me" : ""}`} initial={{ opacity: 0 }} animate={{ opacity: 1, backgroundColor: changed[row.sessionId] ? ["rgba(43,204,174,0.35)", "rgba(43,204,174,0)"] : "rgba(0,0,0,0)" }} exit={{ opacity: 0 }} transition={{ layout: { type: "spring", stiffness: 300, damping: 32 }, backgroundColor: { duration: 1.6 } }}>249                        <td className="rank-cell">250                          {row.horsConcours ? <span className="muted small" title="Hors concours">HC</span> : row.rank <= 3 ? <span className="medal" data-place={row.rank}>{row.rank}</span> : row.rank}251                          {changed[row.sessionId] && <span className="sr-only">{changed[row.sessionId] === "up" ? " (en hausse)" : " (en baisse)"}</span>}252                        </td>253                        <td>{row.displayName}{row.isMe && <span className="tag tag-gold" style={{ marginLeft: 8 }}>Vous</span>}{row.prize !== null && <span className="tag tag-gold" style={{ marginLeft: 8 }}>{formatMoney(row.prize)}</span>}{row.horsConcours && <span className="tag" style={{ marginLeft: 8 }}>Enseignant · hors concours</span>}{row.tied && <span className="muted small"> · ex æquo</span>}</td>254                        <td className="hide-mobile muted">{row.course ?? "Hors cours"}</td>255                        <td className="right"><strong>{row.correct}</strong><span className="muted"> / {row.total}</span></td>256                        <td className="right">{formatPercent(row.mape, 1)}</td>257                        <td className="right hide-mobile"><IconFlame size={14} /> {row.bestStreak}</td>258                      </motion.tr>259                    ))}260                  </AnimatePresence>261                </tbody>262              </table>263              {data.rows.length === 0 && <p className="muted" style={{ padding: "var(--s-6) 0", textAlign: "center" }}>{search ? "Aucun participant ne correspond à cette recherche." : "Aucune partie terminée pour l'instant. Le podium vous attend."}</p>}264            </div>265266            {pages > 1 && (267              <nav className="row" aria-label="Pagination" style={{ justifyContent: "center", paddingTop: "var(--s-5)" }}>268                <button type="button" className="btn btn-ghost" disabled={page <= 1} onClick={() => setPage(page - 1)}>Précédent</button>269                <span className="muted tabular">Page {page} sur {pages}</span>270                <button type="button" className="btn btn-ghost" disabled={page >= pages} onClick={() => setPage(page + 1)}>Suivant</button>271              </nav>272            )}273274            {data.inProgress.length > 0 && (275              <section className="stack" style={{ marginTop: "var(--s-8)" }} aria-labelledby="en-cours">276                <h2 id="en-cours" className="title" style={{ fontSize: "var(--step-2)" }}>Parties en cours</h2>277                <p className="muted small">Progression seulement : les scores ne sont dévoilés qu'une fois la partie terminée.</p>278                <ul role="list" className="resume-list">279                  {data.inProgress.map((p, i) => (280                    <li key={`${p.displayName}-${i}`}>281                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: "var(--s-4)", minHeight: 52, padding: "var(--s-2)", borderBottom: "1px solid var(--line)" }}>282                        <span>{p.displayName}{p.isMe && <span className="tag tag-gold" style={{ marginLeft: 8 }}>Vous</span>} <span className="muted small">· {p.course ?? "Hors cours"}</span></span>283                        <span className="row" style={{ flexWrap: "nowrap" }}>284                          <span className="progress-mini" aria-hidden="true"><span style={{ width: `${(100 * p.answered) / p.total}%` }} /></span>285                          <span className="tabular small">{p.answered} / {p.total}</span>286                        </span>287                      </div>288                    </li>289                  ))}290                </ul>291              </section>292            )}293          </>294        )}295      </main>296    </div>297  );298}299
Files main
Menu

Theme