Add the website: Go server + Vue SPA in site/, with CI

A standalone container for web_server, shaped like job-tracker: serves
/usaco/ with solved problems public and solving/skipped plus edits
(status, link, notes) for the site admin. Git is the only store: the
server clones adamf/usaco from Gitea, pulls on the push webhook, and
commits edits back. CI builds the image only when site/ changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 21:51:34 +01:00
co-authored by Claude Opus 5.5
parent 440d51caba
commit 6d956f1c76
39 changed files with 6285 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Competitive programming practice: USACO and friends, with solutions." />
<title>USACO practice</title>
<link rel="icon" href="/img/favicon.ico" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
+2177
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "usaco-site-web",
"version": "0.0.0",
"private": true,
"type": "module",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"highlight.js": "^11.11.1",
"markdown-it": "^14.1.0",
"vue": "^3.5.22",
"vue-router": "^4.6.3"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"@vitejs/plugin-vue": "^6.0.1",
"tailwindcss": "^4.1.18",
"vite": "^7.3.2"
}
}
Binary file not shown.
Binary file not shown.
+62
View File
@@ -0,0 +1,62 @@
<script setup>
/**
* Root: the header with the page links, and the outlet.
*/
import { RouterLink, RouterView } from "vue-router";
</script>
<template>
<div class="shell">
<header class="top">
<RouterLink to="/" class="brand">USACO practice</RouterLink>
<nav>
<RouterLink to="/" exact-active-class="on">Problems</RouterLink>
<RouterLink to="/stats" active-class="on">Stats</RouterLink>
<a href="/">adam-french.co.uk</a>
</nav>
</header>
<main>
<RouterView />
</main>
</div>
</template>
<style scoped>
.shell {
max-width: 1100px;
margin: 0 auto;
padding: 0 16px 48px;
}
.top {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 8px 24px;
padding: 24px 0 16px;
border-bottom: 1px solid var(--color-line);
margin-bottom: 24px;
}
.brand {
font-family: var(--font-heading);
font-size: 2.25rem;
line-height: 1;
letter-spacing: 0.02em;
color: var(--color-ink);
text-decoration: none;
}
nav {
display: flex;
gap: 20px;
}
nav a {
color: var(--color-ink-muted);
text-decoration: none;
}
nav a:hover,
nav a.on {
color: var(--color-ink);
text-decoration: underline;
text-underline-offset: 4px;
}
</style>
+37
View File
@@ -0,0 +1,37 @@
/**
* The server's REST API (internal/handlers). Every call goes through
* request(), which turns an error response into a thrown Error carrying the
* server's message, and sends a refused admin action to the site's login.
*/
import { goToLogin } from "./session";
const BASE = `${import.meta.env.BASE_URL}api`;
export class ApiError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
async function request(method, path, body) {
const res = await fetch(BASE + path, {
method,
credentials: "same-origin",
headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (res.status === 401) goToLogin();
throw new ApiError(res.status, data.error || `request failed (${res.status})`);
}
return data;
}
export const listProblems = () => request("GET", "/problems");
export const getProblem = (name) => request("GET", `/problems/${encodeURIComponent(name)}`);
export const updateMeta = (name, meta) => request("PUT", `/problems/${encodeURIComponent(name)}/meta`, meta);
export const setStatus = (name, to) => request("POST", `/problems/${encodeURIComponent(name)}/status`, { to });
export const getMe = () => request("GET", "/me");
+215
View File
@@ -0,0 +1,215 @@
/*
* Global stylesheet: tokens, base elements, shared bits (badges, buttons)
* and the code-highlighting colours.
*
* The palette and fonts are the job tracker's paper look (same fonts, copied
* into public/fonts), so the two read as parts of one site. Tailwind is here
* for its preflight reset; components use their own scoped <style> blocks.
*/
@import "tailwindcss";
@font-face {
font-family: "big_noodle_titling";
src: url("/usaco/fonts/big_noodle_titling.woff2") format("woff2");
font-weight: normal;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "CreatoDisplay";
src: url("/usaco/fonts/CreatoDisplay-Bold.woff2") format("woff2");
font-weight: normal;
font-style: normal;
font-display: swap;
}
/* `static` = always emit these variables, because component <style> blocks
reference them with var(). */
@theme static {
--color-ink: #111;
--color-ink-soft: #333;
--color-ink-muted: #555;
--color-ink-faint: #8a8a8a;
--color-ink-link: #0066cc;
--color-ink-danger: #c00;
--color-paper: #fff;
--color-paper-tint: #f5f5f5;
--color-paper-shade: #eee;
--color-line: #ccc;
--color-line-soft: #e0e0e0;
/* Status: identity, so always shown with its label, never colour alone. */
--color-solved: #0a7d0a;
--color-solving: #9a6700;
--color-skipped: #777;
/* Sequential blue (dataviz reference ramp): the solve heatmap. */
--color-seq-0: #ebebe8;
--color-seq-1: #9ec5f4;
--color-seq-2: #5598e7;
--color-seq-3: #256abf;
--color-seq-4: #0d366b;
--font-heading: "big_noodle_titling", sans-serif;
--font-body: "CreatoDisplay", sans-serif;
--font-mono: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;
--default-font-family: var(--font-body);
}
body {
margin: 0;
min-height: 100vh;
overflow-x: hidden;
background: var(--color-paper-tint);
color: var(--color-ink);
line-height: 1.5;
}
h1,
h2,
h3 {
font-family: var(--font-heading);
font-weight: normal;
letter-spacing: 0.02em;
line-height: 1.1;
}
a {
color: var(--color-ink-link);
}
.card {
background: var(--color-paper);
border: 1px solid var(--color-line-soft);
border-radius: 6px;
}
.badge {
display: inline-block;
padding: 1px 8px;
border-radius: 999px;
font-size: 0.75rem;
border: 1px solid var(--color-line);
color: var(--color-ink-muted);
background: var(--color-paper);
white-space: nowrap;
}
.badge.solved {
color: var(--color-solved);
border-color: currentColor;
}
.badge.solving {
color: var(--color-solving);
border-color: currentColor;
}
.badge.skipped {
color: var(--color-skipped);
border-style: dashed;
}
.btn {
padding: 6px 14px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper);
color: var(--color-ink);
cursor: pointer;
}
.btn:hover:not(:disabled) {
border-color: var(--color-ink-muted);
}
.btn:disabled {
opacity: 0.5;
cursor: default;
}
.btn.primary {
background: var(--color-ink);
border-color: var(--color-ink);
color: var(--color-paper);
}
.error {
color: var(--color-ink-danger);
}
.muted {
color: var(--color-ink-muted);
}
/* highlight.js tokens, in the paper palette. */
.hljs {
color: var(--color-ink-soft);
}
.hljs-comment,
.hljs-quote {
color: #6a737d;
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-built_in,
.hljs-meta .hljs-keyword {
color: #a3268d;
}
.hljs-type,
.hljs-title.class_ {
color: #0b6e99;
}
.hljs-string,
.hljs-meta .hljs-string {
color: #1a7f37;
}
.hljs-number,
.hljs-literal {
color: #b35900;
}
.hljs-title.function_,
.hljs-title {
color: #5a3fc0;
}
.hljs-meta {
color: #8250df;
}
.hljs-variable,
.hljs-params {
color: var(--color-ink-soft);
}
/* Rendered notes (markdown-it). */
.prose {
overflow-wrap: anywhere;
}
.prose > * + * {
margin-top: 0.75em;
}
.prose h1,
.prose h2,
.prose h3 {
font-size: 1.5rem;
}
.prose ul {
list-style: disc;
padding-left: 1.5em;
}
.prose ol {
list-style: decimal;
padding-left: 1.5em;
}
.prose code {
font-family: var(--font-mono);
font-size: 0.875em;
background: var(--color-paper-shade);
padding: 1px 4px;
border-radius: 3px;
}
.prose pre {
background: var(--color-paper-tint);
padding: 12px;
border-radius: 4px;
overflow-x: auto;
}
.prose pre code {
background: none;
padding: 0;
}
+109
View File
@@ -0,0 +1,109 @@
<script setup>
/**
* A file with line numbers, highlighting and a copy button. Only the
* languages the workspace uses are registered, which keeps highlight.js to a
* few kilobytes instead of the full bundle.
*/
import { computed, ref } from "vue";
import hljs from "highlight.js/lib/core";
import cpp from "highlight.js/lib/languages/cpp";
import python from "highlight.js/lib/languages/python";
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("c", cpp);
hljs.registerLanguage("python", python);
const props = defineProps({
content: { type: String, required: true },
lang: { type: String, default: "" },
truncated: { type: Boolean, default: false },
});
// highlight.js escapes the source itself, so v-html on its output is safe.
const html = computed(() => {
const text = props.content.replace(/\n$/, "");
if (props.lang && hljs.getLanguage(props.lang)) {
return hljs.highlight(text, { language: props.lang }).value;
}
return text.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
});
const lines = computed(() => props.content.replace(/\n$/, "").split("\n").length);
const copied = ref(false);
async function copy() {
try {
await navigator.clipboard.writeText(props.content);
copied.value = true;
setTimeout(() => (copied.value = false), 1500);
} catch {
// Clipboard access refused (insecure context or permissions): nothing to do.
}
}
</script>
<template>
<div class="code">
<button class="copy" type="button" @click="copy">{{ copied ? "Copied" : "Copy" }}</button>
<div class="scroll">
<pre class="gutter" aria-hidden="true">{{ Array.from({ length: lines }, (_, i) => i + 1).join("\n") }}</pre>
<pre class="hljs src"><code v-html="html"></code></pre>
</div>
<p v-if="truncated" class="cut muted">Cut short: the file is larger than the site shows.</p>
</div>
</template>
<style scoped>
.code {
position: relative;
background: var(--color-paper);
border: 1px solid var(--color-line-soft);
border-radius: 6px;
}
.scroll {
display: flex;
overflow-x: auto;
font-family: var(--font-mono);
font-size: 0.8125rem;
line-height: 1.55;
}
pre {
margin: 0;
padding: 12px 0;
font-family: inherit;
}
.gutter {
padding: 12px 10px 12px 12px;
text-align: right;
color: var(--color-ink-faint);
user-select: none;
border-right: 1px solid var(--color-line-soft);
position: sticky;
left: 0;
background: var(--color-paper);
}
.src {
padding-left: 12px;
padding-right: 64px;
}
.copy {
position: absolute;
top: 8px;
right: 8px;
z-index: 1;
padding: 2px 10px;
font-size: 0.75rem;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper);
color: var(--color-ink-muted);
cursor: pointer;
}
.copy:hover {
color: var(--color-ink);
}
.cut {
padding: 6px 12px;
font-size: 0.8rem;
border-top: 1px solid var(--color-line-soft);
}
</style>
+25
View File
@@ -0,0 +1,25 @@
/**
* Small display helpers shared by the views.
*/
export const STATUS_LABELS = { solving: "Solving", solved: "Solved", skipped: "Skipped" };
export const LANG_LABELS = { cpp: "C++", c: "C", python: "Python", java: "Java", rust: "Rust", go: "Go" };
// "diamond-collector" -> "Diamond Collector"
export function title(name) {
return name.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
export function formatDate(iso, opts = { day: "numeric", month: "short", year: "numeric" }) {
if (!iso) return "";
return new Date(iso).toLocaleDateString(undefined, opts);
}
// Local calendar day, "YYYY-MM-DD": the heatmap and streak count days where
// the viewer is, not in UTC.
export function dayKey(date) {
const d = new Date(date);
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
+10
View File
@@ -0,0 +1,10 @@
/**
* App entry point. Mounts <App> on #app with the router.
*/
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import "./assets/styles.css";
createApp(App).use(router).mount("#app");
+19
View File
@@ -0,0 +1,19 @@
/**
* Routes, under the app's base path (/usaco/, from vite.config.js).
*
* Everything is public; what the admin sees beyond solved problems is decided
* by the server per request (the same URLs, more data), so there are no guards.
*/
import { createRouter, createWebHistory } from "vue-router";
export default createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{ path: "/", name: "list", component: () => import("@/views/ProblemList.vue") },
{ path: "/p/:name", name: "problem", component: () => import("@/views/ProblemPage.vue"), props: true },
{ path: "/stats", name: "stats", component: () => import("@/views/StatsPage.vue") },
{ path: "/:pathMatch(.*)*", redirect: "/" },
],
scrollBehavior: (to, from, saved) => saved || { top: 0 },
});
+13
View File
@@ -0,0 +1,13 @@
/**
* What to do when an admin action is refused.
*
* The site has no login of its own: it borrows the main site's session
* (internal/auth on the server), as the job tracker does. By the time a
* request is refused the server has already tried the site's refresh token,
* so the only way back is the site's login page, which returns here after.
*/
export function goToLogin() {
const here = window.location.pathname + window.location.search;
window.location.assign(`/admin/login?redirect=${encodeURIComponent(here)}`);
}
+207
View File
@@ -0,0 +1,207 @@
<script setup>
/**
* The problem list. Visitors see solved problems; the admin also sees what
* is in progress or skipped (the server decides, this only shows the tabs
* when there is something behind them). Filter and sort live in the query
* string so a filtered view can be linked and survives the back button.
*/
import { computed, onMounted, ref } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import { listProblems } from "@/api";
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
const route = useRoute();
const router = useRouter();
const problems = ref([]);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
const status = computed({
get: () => route.query.status || "all",
set: (v) => router.replace({ query: { ...route.query, status: v === "all" ? undefined : v } }),
});
const sort = computed({
get: () => route.query.sort || "recent",
set: (v) => router.replace({ query: { ...route.query, sort: v === "recent" ? undefined : v } }),
});
const search = computed({
get: () => route.query.q || "",
set: (v) => router.replace({ query: { ...route.query, q: v || undefined } }),
});
onMounted(async () => {
try {
const data = await listProblems();
problems.value = data.problems;
admin.value = data.admin;
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
});
const counts = computed(() => {
const c = { all: problems.value.length, solved: 0, solving: 0, skipped: 0 };
for (const p of problems.value) c[p.status]++;
return c;
});
const tabs = computed(() =>
admin.value ? ["all", "solving", "solved", "skipped"] : [],
);
// When a problem was last worked on, for sorting: the solve date if it has
// one, else its last commit.
const when = (p) => p.solvedAt || p.lastTouched || "";
const shown = computed(() => {
const q = search.value.trim().toLowerCase();
const list = problems.value.filter(
(p) =>
(status.value === "all" || p.status === status.value) &&
(!q || p.name.includes(q.replace(/\s+/g, "-")) || (p.source || "").toLowerCase().includes(q)),
);
if (sort.value === "name") return list.sort((a, b) => a.name.localeCompare(b.name));
return list.sort((a, b) => when(b).localeCompare(when(a)) || a.name.localeCompare(b.name));
});
</script>
<template>
<section>
<p v-if="!loading && !error" class="intro muted">
{{ counts.solved }} solved problems from USACO and other judges, each with its solution and test cases.
</p>
<div class="controls">
<div v-if="tabs.length" class="tabs" role="tablist">
<button
v-for="t in tabs"
:key="t"
role="tab"
:aria-selected="status === t"
:class="{ on: status === t }"
@click="status = t"
>
{{ t === "all" ? "All" : STATUS_LABELS[t] }} <span class="n">{{ counts[t] }}</span>
</button>
</div>
<input v-model="search" type="search" placeholder="Search problems" aria-label="Search problems" />
<select v-model="sort" aria-label="Sort by">
<option value="recent">Most recent</option>
<option value="name">Name</option>
</select>
</div>
<p v-if="loading" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
<p v-else-if="!shown.length" class="muted">Nothing matches.</p>
<ul v-else class="list">
<li v-for="p in shown" :key="p.name">
<RouterLink :to="{ name: 'problem', params: { name: p.name } }" class="row card">
<div class="main">
<span class="name">{{ title(p.name) }}</span>
<span class="meta muted">
<template v-if="p.langs.length">{{ p.langs.map((l) => LANG_LABELS[l] || l).join(", ") }}</template>
<template v-if="p.tests"> · {{ p.tests }} test{{ p.tests === 1 ? "" : "s" }}</template>
<template v-if="p.hasNotes"> · notes</template>
</span>
</div>
<div class="side">
<span v-if="p.source" class="badge">{{ p.source }}</span>
<span v-if="admin || p.status !== 'solved'" class="badge" :class="p.status">{{ STATUS_LABELS[p.status] }}</span>
<time v-if="when(p)" class="muted" :datetime="when(p)">{{ formatDate(when(p)) }}</time>
</div>
</RouterLink>
</li>
</ul>
</section>
</template>
<style scoped>
.intro {
margin-bottom: 16px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
margin-bottom: 16px;
}
.tabs {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-right: auto;
}
.tabs button {
padding: 4px 12px;
border-radius: 999px;
border: 1px solid transparent;
color: var(--color-ink-muted);
cursor: pointer;
}
.tabs button.on {
border-color: var(--color-ink);
color: var(--color-ink);
background: var(--color-paper);
}
.tabs .n {
color: var(--color-ink-faint);
margin-left: 2px;
}
input,
select {
padding: 6px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper);
min-width: 0;
}
input {
flex: 1 1 200px;
max-width: 320px;
}
.list {
display: grid;
gap: 8px;
}
.row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 8px 16px;
padding: 12px 16px;
color: inherit;
text-decoration: none;
}
.row:hover {
border-color: var(--color-ink-faint);
}
.main {
display: flex;
flex-direction: column;
min-width: 0;
}
.name {
font-size: 1.05rem;
}
.meta {
font-size: 0.8rem;
}
.side {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.85rem;
}
time {
min-width: 7.5em;
text-align: right;
}
</style>
+323
View File
@@ -0,0 +1,323 @@
<script setup>
/**
* One problem: its solution files, sample input, saved tests, notes and git
* history. The admin also gets the status buttons and the link/notes editor;
* each edit is a commit the server pushes, and the response is the problem
* as it is afterwards, so the page just takes it.
*/
import { computed, ref, watch } from "vue";
import { RouterLink } from "vue-router";
import MarkdownIt from "markdown-it";
import CodeBlock from "@/components/CodeBlock.vue";
import { getMe, getProblem, setStatus, updateMeta } from "@/api";
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
const props = defineProps({ name: { type: String, required: true } });
// html: false — notes are rendered as markdown only, never as raw HTML.
const md = new MarkdownIt({ html: false, linkify: true });
const problem = ref(null);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
const activeFile = ref(0);
async function load() {
loading.value = true;
error.value = "";
activeFile.value = 0;
try {
const [p, me] = await Promise.all([getProblem(props.name), getMe().catch(() => ({ admin: false }))]);
problem.value = p;
admin.value = me.admin;
} catch (e) {
problem.value = null;
error.value = e.status === 404 ? "No such problem." : e.message;
} finally {
loading.value = false;
}
}
watch(() => props.name, load, { immediate: true });
const notesHtml = computed(() => (problem.value?.notes ? md.render(problem.value.notes) : ""));
const file = computed(() => problem.value?.files[activeFile.value]);
// ---- admin edits ----
const saving = ref(false);
const editError = ref("");
const editing = ref(false);
const draftUrl = ref("");
const draftNotes = ref("");
function startEdit() {
draftUrl.value = problem.value.url || "";
draftNotes.value = problem.value.notes || "";
editError.value = "";
editing.value = true;
}
async function run(action) {
saving.value = true;
editError.value = "";
try {
problem.value = await action();
return true;
} catch (e) {
editError.value = e.message;
return false;
} finally {
saving.value = false;
}
}
async function saveMeta() {
if (await run(() => updateMeta(props.name, { url: draftUrl.value, notes: draftNotes.value }))) {
editing.value = false;
}
}
const moves = computed(() => {
const s = problem.value?.status;
return [
{ to: "solved", label: "Mark solved" },
{ to: "skipped", label: "Skip" },
{ to: "solving", label: "Reopen" },
].filter((m) => m.to !== s);
});
</script>
<template>
<p v-if="loading" class="muted">Loading…</p>
<div v-else-if="error">
<p class="error">{{ error }}</p>
<RouterLink to="/">Back to the list</RouterLink>
</div>
<article v-else-if="problem" class="page">
<header class="head">
<RouterLink to="/" class="back">← All problems</RouterLink>
<h1>{{ title(problem.name) }}</h1>
<div class="facts">
<span class="badge" :class="problem.status">{{ STATUS_LABELS[problem.status] }}</span>
<a v-if="problem.url" :href="problem.url" target="_blank" rel="noopener noreferrer">
{{ problem.source || "Problem statement" }} ↗
</a>
<span v-if="problem.solvedAt" class="muted">Solved {{ formatDate(problem.solvedAt) }}</span>
<span v-else-if="problem.firstSeen" class="muted">Started {{ formatDate(problem.firstSeen) }}</span>
<span v-if="problem.io" class="muted">File I/O: <code>{{ problem.io }}.in</code></span>
</div>
</header>
<section v-if="admin" class="admin card">
<div class="admin-row">
<span class="muted">Admin</span>
<button v-for="m in moves" :key="m.to" class="btn" :disabled="saving" @click="run(() => setStatus(problem.name, m.to))">
{{ m.label }}
</button>
<button v-if="!editing" class="btn" :disabled="saving" @click="startEdit">Edit link and notes</button>
<span v-if="saving" class="muted">Saving to git…</span>
</div>
<form v-if="editing" class="editor" @submit.prevent="saveMeta">
<label>
Problem link
<input v-model="draftUrl" type="url" placeholder="https://usaco.org/index.php?page=viewproblem2&cpid=…" />
</label>
<label>
Notes (markdown)
<textarea v-model="draftNotes" rows="8" placeholder="Approach, complexity, what tripped you up…"></textarea>
</label>
<div class="admin-row">
<button class="btn primary" type="submit" :disabled="saving">Save</button>
<button class="btn" type="button" :disabled="saving" @click="editing = false">Cancel</button>
</div>
</form>
<p v-if="editError" class="error">{{ editError }}</p>
</section>
<section v-if="notesHtml" class="notes card prose" v-html="notesHtml"></section>
<section>
<h2>Solution</h2>
<p v-if="!problem.files.length" class="muted">No solution file yet.</p>
<template v-else>
<div v-if="problem.files.length > 1" class="file-tabs" role="tablist">
<button
v-for="(f, i) in problem.files"
:key="f.name"
role="tab"
:aria-selected="i === activeFile"
:class="{ on: i === activeFile }"
@click="activeFile = i"
>
{{ f.name }} <span class="muted">{{ LANG_LABELS[f.lang] || f.lang }}</span>
</button>
</div>
<p v-else class="filename muted">{{ file.name }}</p>
<CodeBlock :key="file.name" :content="file.content" :lang="file.lang" :truncated="file.truncated" />
</template>
</section>
<section v-if="problem.sample">
<h2>Sample input</h2>
<p class="filename muted">{{ problem.sample.name }}</p>
<CodeBlock :content="problem.sample.content" :truncated="problem.sample.truncated" />
</section>
<section v-if="problem.testCases.length">
<h2>Tests</h2>
<details v-for="t in problem.testCases" :key="t.name" class="test card">
<summary>Test {{ t.name }}</summary>
<div class="io">
<div>
<p class="filename muted">Input</p>
<CodeBlock :content="t.input.content" :truncated="t.input.truncated" />
</div>
<div>
<p class="filename muted">Expected output</p>
<CodeBlock v-if="t.output" :content="t.output.content" :truncated="t.output.truncated" />
<p v-else class="muted">Not saved.</p>
</div>
</div>
</details>
</section>
<section v-if="problem.history.length">
<h2>History</h2>
<ol class="history">
<li v-for="c in problem.history" :key="c.hash">
<time :datetime="c.date" class="muted">{{ formatDate(c.date) }}</time>
<span>{{ c.subject }}</span>
<code class="muted">{{ c.hash.slice(0, 7) }}</code>
</li>
</ol>
</section>
</article>
</template>
<style scoped>
.page {
display: grid;
gap: 28px;
min-width: 0;
}
.page > section {
min-width: 0;
}
.back {
font-size: 0.875rem;
color: var(--color-ink-muted);
text-decoration: none;
}
.back:hover {
color: var(--color-ink);
}
h1 {
font-size: 2.75rem;
margin: 6px 0 10px;
overflow-wrap: anywhere;
}
h2 {
font-size: 1.6rem;
margin-bottom: 8px;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 16px;
font-size: 0.9rem;
}
.facts code,
.history code {
font-family: var(--font-mono);
font-size: 0.85em;
}
.admin {
padding: 12px 16px;
display: grid;
gap: 12px;
}
.admin-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.editor {
display: grid;
gap: 12px;
}
.editor label {
display: grid;
gap: 4px;
font-size: 0.875rem;
color: var(--color-ink-muted);
}
.editor input,
.editor textarea {
padding: 8px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
font-family: var(--font-mono);
font-size: 0.85rem;
color: var(--color-ink);
background: var(--color-paper);
}
.notes {
padding: 16px 20px;
}
.file-tabs {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-bottom: 8px;
}
.file-tabs button {
padding: 4px 12px;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
font-family: var(--font-mono);
font-size: 0.8rem;
cursor: pointer;
}
.file-tabs button.on {
border-color: var(--color-ink);
background: var(--color-paper);
}
.filename {
font-family: var(--font-mono);
font-size: 0.8rem;
margin-bottom: 4px;
}
.test {
margin-bottom: 8px;
}
.test summary {
padding: 8px 14px;
cursor: pointer;
}
.io {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 12px;
padding: 0 14px 14px;
min-width: 0;
}
.io > div {
min-width: 0;
}
.history {
display: grid;
gap: 4px;
font-size: 0.9rem;
}
.history li {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
}
.history time {
min-width: 7.5em;
}
</style>
+345
View File
@@ -0,0 +1,345 @@
<script setup>
/**
* Solve statistics, computed in the browser from the problem list: the
* headline counts, a year of solves as a calendar heatmap, and the same data
* by month as a table (the heatmap's accessible equivalent).
*
* Days are the viewer's local days (format.dayKey). The solve date is the
* commit that moved a problem into solved/, so a batch of problems committed
* together lands on one day.
*/
import { computed, nextTick, onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { listProblems } from "@/api";
import { dayKey, formatDate, title } from "@/format";
const problems = ref([]);
const loading = ref(true);
const error = ref("");
const scroller = ref(null);
onMounted(async () => {
try {
problems.value = (await listProblems()).problems;
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
// Start the heatmap at today's end on narrow screens.
await nextTick();
if (scroller.value) scroller.value.scrollLeft = scroller.value.scrollWidth;
});
const solved = computed(() => problems.value.filter((p) => p.status === "solved" && p.solvedAt));
// day key -> names solved that day
const byDay = computed(() => {
const m = new Map();
for (const p of solved.value) {
const k = dayKey(p.solvedAt);
if (!m.has(k)) m.set(k, []);
m.get(k).push(p.name);
}
return m;
});
const DAY = 86400000;
const today = new Date();
today.setHours(0, 0, 0, 0);
function addDays(d, n) {
const x = new Date(d);
x.setDate(x.getDate() + n);
return x;
}
const streaks = computed(() => {
const days = [...byDay.value.keys()].sort();
let longest = 0;
let run = 0;
let prev = null;
for (const k of days) {
const d = new Date(k + "T00:00:00");
run = prev && Math.round((d - prev) / DAY) === 1 ? run + 1 : 1;
longest = Math.max(longest, run);
prev = d;
}
// The current streak may end yesterday: today is not over yet.
let current = 0;
let d = byDay.value.has(dayKey(today)) ? today : addDays(today, -1);
while (byDay.value.has(dayKey(d))) {
current++;
d = addDays(d, -1);
}
return { current, longest };
});
const recent = (days) => solved.value.filter((p) => new Date(p.solvedAt) >= addDays(today, -days + 1)).length;
const tiles = computed(() => [
{ label: "Solved", value: solved.value.length },
{ label: "Last 30 days", value: recent(30) },
{ label: "Current streak", value: streaks.value.current, unit: streaks.value.current === 1 ? "day" : "days" },
{ label: "Longest streak", value: streaks.value.longest, unit: streaks.value.longest === 1 ? "day" : "days" },
]);
// ---- heatmap: 53 weeks ending this week, Monday-first rows ----
const CELL = 12;
const GAP = 2; // surface gap between cells
const LEFT = 28; // weekday labels
const TOP = 18; // month labels
const WEEKS = 53;
const start = computed(() => {
const dow = (today.getDay() + 6) % 7; // 0 = Monday
return addDays(today, -dow - (WEEKS - 1) * 7);
});
const cells = computed(() => {
const out = [];
for (let w = 0; w < WEEKS; w++) {
for (let d = 0; d < 7; d++) {
const date = addDays(start.value, w * 7 + d);
if (date > today) continue;
const names = byDay.value.get(dayKey(date)) || [];
out.push({ key: dayKey(date), date, names, x: LEFT + w * (CELL + GAP), y: TOP + d * (CELL + GAP) });
}
}
return out;
});
const months = computed(() => {
const out = [];
let last = -1;
for (let w = 0; w < WEEKS; w++) {
const d = addDays(start.value, w * 7);
if (d.getMonth() !== last) {
last = d.getMonth();
// Skip a label squeezed into the first partial column.
if (w > 0 || d.getDate() <= 7) {
out.push({ x: LEFT + w * (CELL + GAP), label: d.toLocaleDateString(undefined, { month: "short" }) });
}
}
}
return out;
});
const width = LEFT + WEEKS * (CELL + GAP);
const height = TOP + 7 * (CELL + GAP);
// Sequential steps: 0 is the empty-day neutral, 4 is "4 or more".
const level = (n) => Math.min(n, 4);
const hover = ref(null);
function show(c, ev) {
const box = ev.currentTarget.closest(".heat").getBoundingClientRect();
const r = ev.currentTarget.getBoundingClientRect();
hover.value = { ...c, left: r.left - box.left + r.width / 2, top: r.top - box.top };
}
// ---- monthly table ----
const monthly = computed(() => {
const m = new Map();
for (const p of solved.value) {
const d = new Date(p.solvedAt);
const k = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
if (!m.has(k)) m.set(k, { key: k, date: new Date(d.getFullYear(), d.getMonth(), 1), names: [] });
m.get(k).names.push(p.name);
}
return [...m.values()].sort((a, b) => b.key.localeCompare(a.key));
});
</script>
<template>
<p v-if="loading" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
<div v-else class="stats">
<div class="tiles">
<div v-for="t in tiles" :key="t.label" class="tile card">
<span class="label muted">{{ t.label }}</span>
<span class="value">{{ t.value }}<small v-if="t.unit" class="muted"> {{ t.unit }}</small></span>
</div>
</div>
<section>
<h2>Solves in the last year</h2>
<div class="heat card" @mouseleave="hover = null">
<div ref="scroller" class="heat-scroll">
<svg :width="width" :height="height" role="img" :aria-label="`Calendar of solves over the last year; ${solved.length} in total. The table below lists them by month.`">
<text v-for="m in months" :key="m.x" :x="m.x" y="11" class="axis">{{ m.label }}</text>
<text v-for="(d, i) in ['Mon', '', 'Wed', '', 'Fri', '', '']" :key="i" x="0" :y="TOP + i * (CELL + GAP) + CELL - 2" class="axis">{{ d }}</text>
<rect
v-for="c in cells"
:key="c.key"
:x="c.x"
:y="c.y"
:width="CELL"
:height="CELL"
rx="2"
:class="['cell', `l${level(c.names.length)}`, { hot: hover && hover.key === c.key }]"
@mouseenter="show(c, $event)"
/>
</svg>
</div>
<div class="legend muted" aria-hidden="true">
Less
<svg v-for="l in [0, 1, 2, 3, 4]" :key="l" width="12" height="12"><rect width="12" height="12" rx="2" :class="['cell', `l${l}`]" /></svg>
More
</div>
<div v-if="hover" class="tip" :style="{ left: hover.left + 'px', top: hover.top + 'px' }">
<strong>{{ hover.names.length || "No" }} solve{{ hover.names.length === 1 ? "" : "s" }}</strong>
<span class="muted">{{ formatDate(hover.date, { weekday: "short", day: "numeric", month: "short", year: "numeric" }) }}</span>
<span v-for="n in hover.names.slice(0, 6)" :key="n">{{ title(n) }}</span>
<span v-if="hover.names.length > 6" class="muted">and {{ hover.names.length - 6 }} more</span>
</div>
</div>
</section>
<section>
<h2>By month</h2>
<table v-if="monthly.length" class="card">
<thead>
<tr><th scope="col">Month</th><th scope="col" class="num">Solved</th><th scope="col">Problems</th></tr>
</thead>
<tbody>
<tr v-for="m in monthly" :key="m.key">
<td>{{ formatDate(m.date, { month: "long", year: "numeric" }) }}</td>
<td class="num">{{ m.names.length }}</td>
<td class="names">
<template v-for="(n, i) in m.names" :key="n">
<RouterLink :to="{ name: 'problem', params: { name: n } }">{{ title(n) }}</RouterLink><span v-if="i < m.names.length - 1">, </span>
</template>
</td>
</tr>
</tbody>
</table>
<p v-else class="muted">Nothing solved yet.</p>
</section>
</div>
</template>
<style scoped>
.stats {
display: grid;
gap: 28px;
min-width: 0;
}
.stats > section {
min-width: 0;
}
h2 {
font-size: 1.6rem;
margin-bottom: 8px;
}
.tiles {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 12px;
}
.tile {
display: flex;
flex-direction: column;
padding: 14px 16px;
}
.label {
font-size: 0.8rem;
}
.value {
font-family: var(--font-heading);
font-size: 2.75rem;
line-height: 1.1;
}
.value small {
margin-left: 0.3em;
font-family: var(--font-body);
font-size: 0.9rem;
}
.heat {
position: relative;
padding: 14px 16px 10px;
}
.heat-scroll {
overflow-x: auto;
}
svg {
display: block;
}
.axis {
font-size: 10px;
fill: var(--color-ink-faint);
}
.cell {
fill: var(--color-seq-0);
}
.cell.l1 {
fill: var(--color-seq-1);
}
.cell.l2 {
fill: var(--color-seq-2);
}
.cell.l3 {
fill: var(--color-seq-3);
}
.cell.l4 {
fill: var(--color-seq-4);
}
.cell.hot {
stroke: var(--color-ink);
stroke-width: 1.5;
}
.legend {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 3px;
margin-top: 8px;
font-size: 0.75rem;
}
.tip {
position: absolute;
transform: translate(-50%, calc(-100% - 8px));
display: flex;
flex-direction: column;
gap: 1px;
padding: 8px 10px;
background: var(--color-paper);
border: 1px solid var(--color-line);
border-radius: 4px;
box-shadow: 0 2px 8px rgb(0 0 0 / 0.12);
font-size: 0.8rem;
white-space: nowrap;
pointer-events: none;
z-index: 2;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
th,
td {
text-align: left;
padding: 8px 12px;
border-bottom: 1px solid var(--color-line-soft);
vertical-align: top;
}
th {
font-weight: normal;
color: var(--color-ink-muted);
}
tr:last-child td {
border-bottom: none;
}
.num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.names {
overflow-wrap: anywhere;
}
td:first-child {
white-space: nowrap;
}
</style>
+26
View File
@@ -0,0 +1,26 @@
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import tailwindcss from "@tailwindcss/vite";
import vue from "@vitejs/plugin-vue";
// The app is served under /usaco/ (BASE_PATH on the server), so every asset
// URL and the router's history base carry it. Changing one means changing both.
//
// `npm run dev` proxies the API to the Go server: VITE_PROXY_USACO (default
// localhost:8080, the standalone docker-compose).
export default defineConfig({
base: "/usaco/",
plugins: [vue(), tailwindcss()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
server: {
host: "0.0.0.0",
proxy: {
"/usaco/api": process.env.VITE_PROXY_USACO || "http://localhost:8080",
},
},
});