Explain concepts on the site, and reuse their code from the CLI
Test and publish the site / test (push) Successful in 1m19s
Test and publish the site / publish (push) Successful in 1m31s

/usaco/concepts is a library of techniques Claude explained: the admin
asks by topic ("help explain fenwick trees") or pastes code they could
not follow, and gets an intuitive explanation with SVG diagrams plus a
C++ snippet in contest style. Given code, the walkthrough traces that
code and the snippet is a general version of it. Anyone can read the
library; generating, rewriting and deleting are admin-only.

Each concept is committed as concepts/<slug>/: concept.md (tags in a
header comment, then a # title), snippet.cpp (first line
"// concept: <slug>") and request.md (the question, for rewrites). The
slug is Claude's to pick, so a new concept's job is keyed by an id and
returns {slug} as its result; a taken slug gets -2, -3... rather than
overwriting. Rewriting starts from the saved question and version plus
a note on what to change. The index reads concepts into Index.Concepts,
with their date from git.

internal/concept shares explain's math and diagram rules, now split out
as explain.MathRules and explain.DiagramRules; the explain prompt is
byte-for-byte unchanged. Code fences in explanations are highlighted
with the same highlight.js setup as CodeBlock (web/src/highlight.js).

`usaco snippet` lists concepts, prints one's snippet, or pastes it into
a solution above main (or class Solution), keeping a .bak and refusing
a concept the file already has. In interactive mode it pastes into the
selection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-20 12:58:38 +01:00
co-authored by Claude Opus 5.5
parent d4849859df
commit ccf4e4dd74
25 changed files with 1750 additions and 33 deletions
+1
View File
@@ -17,6 +17,7 @@ const route = useRoute();
<RouterLink to="/" class="brand">USACO practice</RouterLink>
<nav>
<RouterLink to="/" exact-active-class="on">Problems</RouterLink>
<RouterLink to="/concepts" :class="{ on: route.name === 'concept' }" active-class="on">Concepts</RouterLink>
<RouterLink to="/stats" active-class="on">Stats</RouterLink>
<RouterLink to="/cli" active-class="on">CLI</RouterLink>
<a href="/gitea/adamf/usaco">Source</a>
+13
View File
@@ -68,3 +68,16 @@ export const evaluateStatus = (name) => request("GET", `/problems/${encodeURICom
// Imports today's LeetCode daily question (or finds it, if it is already a
// problem) and answers { name, created }. It takes a few seconds.
export const startDaily = () => request("POST", "/leetcode/daily");
// Concepts: techniques Claude explained, with a C++ snippet. Anyone can read
// them; starting one answers 202 { id, status } and the job's status, at
// conceptJob(id), has result { slug } once it is saved.
export const listConcepts = () => request("GET", "/concepts");
export const getConcept = (slug) => request("GET", `/concepts/${encodeURIComponent(slug)}`);
// body: { topic, code? }
export const startConcept = (body) => request("POST", "/concepts", body);
export const conceptJob = (id) => request("GET", `/concept-jobs/${encodeURIComponent(id)}`);
// body: { note? }. Rewrites the concept in place; polled like an explanation.
export const rewriteConcept = (slug, body) => request("POST", `/concepts/${encodeURIComponent(slug)}/explain`, body);
export const rewriteStatus = (slug) => request("GET", `/concepts/${encodeURIComponent(slug)}/explain`);
export const deleteConcept = (slug) => request("DELETE", `/concepts/${encodeURIComponent(slug)}`);
+3 -20
View File
@@ -1,19 +1,9 @@
<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.
* A file with line numbers, highlighting and a copy button.
*/
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";
import rust from "highlight.js/lib/languages/rust";
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("c", cpp);
hljs.registerLanguage("python", python);
hljs.registerLanguage("rust", rust);
import { highlight } from "@/highlight";
const props = defineProps({
content: { type: String, required: true },
@@ -21,14 +11,7 @@ const props = defineProps({
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 html = computed(() => highlight(props.content.replace(/\n$/, ""), props.lang));
const lines = computed(() => props.content.replace(/\n$/, "").split("\n").length);
const copied = ref(false);
+19 -2
View File
@@ -11,11 +11,13 @@
* they are inserted as SVG after DOMPurify's SVG profile has stripped
* scripts, event handlers and
* anything else that is not drawing. Claude wrote them, the admin can edit
* them, and the public sees them once the problem is solved.
* them, and the public sees them once the problem is solved. Code fences in
* a language CodeBlock knows (a concept's usage example) are highlighted.
*/
import { computed } from "vue";
import { markdown } from "@/markdown";
import DOMPurify from "dompurify";
import { highlight } from "@/highlight";
const props = defineProps({
source: { type: String, required: true },
@@ -26,7 +28,11 @@ const md = markdown();
const fence = md.renderer.rules.fence;
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
const t = tokens[idx];
if (t.info.trim() !== "svg") return fence(tokens, idx, options, env, self);
const lang = t.info.trim();
if (lang === "cpp" || lang === "python") {
return `<pre class="hljs code"><code>${highlight(t.content.replace(/\n$/, ""), lang)}</code></pre>`;
}
if (lang !== "svg") return fence(tokens, idx, options, env, self);
const clean = DOMPurify.sanitize(t.content, { USE_PROFILES: { svg: true, svgFilters: true } });
return `<figure class="diagram">${clean}</figure>`;
};
@@ -91,6 +97,17 @@ const parts = computed(() => {
background: var(--color-paper);
color: var(--color-ink);
}
.body :deep(pre.code) {
margin: 12px 0;
padding: 12px;
overflow-x: auto;
border: 1px solid var(--color-line-soft);
border-radius: 4px;
background: var(--color-paper);
font-family: var(--font-mono);
font-size: 0.8125rem;
line-height: 1.55;
}
.body :deep(.diagram svg) {
display: block;
width: 100%;
+22
View File
@@ -0,0 +1,22 @@
/**
* highlight.js with only the languages the workspace uses registered, which
* keeps it to a few kilobytes instead of the full bundle. CodeBlock and the
* code fences in explanations share it.
*/
import hljs from "highlight.js/lib/core";
import cpp from "highlight.js/lib/languages/cpp";
import python from "highlight.js/lib/languages/python";
import rust from "highlight.js/lib/languages/rust";
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("c", cpp);
hljs.registerLanguage("python", python);
hljs.registerLanguage("rust", rust);
const escape = (text) => text.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
// highlight.js escapes the source itself, so the result is safe for v-html.
export function highlight(text, lang) {
if (lang && hljs.getLanguage(lang)) return hljs.highlight(text, { language: lang }).value;
return escape(text);
}
+2
View File
@@ -20,6 +20,8 @@ export default createRouter({
props: true,
meta: { wide: true },
},
{ path: "/concepts", name: "concepts", component: () => import("@/views/ConceptList.vue") },
{ path: "/c/:slug", name: "concept", component: () => import("@/views/ConceptPage.vue"), props: true },
{ path: "/stats", name: "stats", component: () => import("@/views/StatsPage.vue") },
{ path: "/cli", name: "cli", component: () => import("@/views/CliPage.vue") },
{ path: "/:pathMatch(.*)*", redirect: "/" },
+1
View File
@@ -53,6 +53,7 @@ const sections = [
["usaco open <name>", "Open the saved problem link in a browser."],
["usaco cat <name>", "Print the solution to stdout."],
["usaco copy <name>", "Copy the solution to the clipboard (wl-copy, xclip/xsel, or OSC52 over SSH)."],
["usaco snippet [concept] [name]", "List the concepts explained on this site, print one's C++ snippet, or paste it into a solution above main (the old one goes to a .bak)."],
],
},
{
+262
View File
@@ -0,0 +1,262 @@
<script setup>
/**
* The concept library: techniques Claude explained, each with a C++ snippet
* to reuse. Anyone can browse it; the admin also gets the form that asks
* for a new one, by topic ("help explain fenwick trees") or by pasting code
* they could not follow.
*
* A new concept is a job keyed by an id, since Claude picks the slug. The id
* is kept in localStorage while it runs, so leaving the page and coming
* back picks the wait up again; the job opens the concept when it is done.
*/
import { computed, onMounted, onUnmounted, ref } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import { conceptJob, listConcepts, startConcept } from "@/api";
import { formatDate } from "@/format";
const route = useRoute();
const router = useRouter();
const concepts = ref([]);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
const search = computed({
get: () => route.query.q || "",
set: (v) => router.replace({ query: { ...route.query, q: v || undefined } }),
});
const shown = computed(() => {
const q = search.value.trim().toLowerCase();
if (!q) return concepts.value;
return concepts.value.filter(
(c) =>
c.title.toLowerCase().includes(q) ||
c.slug.includes(q.replace(/\s+/g, "-")) ||
(c.summary || "").toLowerCase().includes(q) ||
c.tags.some((t) => t.includes(q.replace(/\s+/g, "-"))),
);
});
// ---- asking for a new one ----
const PENDING = "usaco.pendingConcept";
const topic = ref("");
const code = ref("");
const showCode = ref(false);
const job = ref({ state: "idle" });
let poll = null;
function remember(id) {
try {
if (id) localStorage.setItem(PENDING, id);
else localStorage.removeItem(PENDING);
} catch {
// Storage blocked: the wait just does not survive leaving the page.
}
}
async function check(id) {
clearTimeout(poll);
try {
const s = await conceptJob(id);
job.value = s;
if (s.state === "running") {
poll = setTimeout(() => check(id), 3000);
return;
}
remember(null);
if (s.state === "done" && s.result?.slug) router.push({ name: "concept", params: { slug: s.result.slug } });
} catch (e) {
remember(null);
job.value = { state: "error", error: e.message };
}
}
async function ask() {
try {
const { id, status } = await startConcept({ topic: topic.value, code: showCode.value ? code.value : "" });
job.value = status;
remember(id);
poll = setTimeout(() => check(id), 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
const canAsk = computed(
() => job.value.state !== "running" && (topic.value.trim() || (showCode.value && code.value.trim())),
);
onMounted(async () => {
try {
const data = await listConcepts();
concepts.value = data.concepts;
admin.value = data.admin;
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
let pending = null;
try {
pending = localStorage.getItem(PENDING);
} catch {
// As above.
}
// A job the server no longer knows (it restarted) comes back idle.
if (pending && admin.value) check(pending);
});
onUnmounted(() => clearTimeout(poll));
</script>
<template>
<section class="page">
<p class="intro muted">
Techniques and data structures, explained with diagrams, each with C++ ready to paste into a solution.
</p>
<form v-if="admin" class="ask card" @submit.prevent="ask">
<h2>Explain a concept</h2>
<input
v-model="topic"
type="text"
placeholder="e.g. help explain fenwick trees"
aria-label="What to explain"
:disabled="job.state === 'running'"
/>
<textarea
v-if="showCode"
v-model="code"
rows="10"
placeholder="Paste code you want explained"
aria-label="Code to explain"
:disabled="job.state === 'running'"
></textarea>
<div class="row">
<label class="check"><input v-model="showCode" type="checkbox" /> Explain some code</label>
<button class="btn primary" type="submit" :disabled="!canAsk">
{{ job.state === "running" ? "Claude is writing…" : "Explain" }}
</button>
<span v-if="job.state === 'running'" class="muted">This takes a minute or two; the concept opens when it is saved.</span>
</div>
<p v-if="job.state === 'error'" class="error">{{ job.error }}</p>
</form>
<div class="controls">
<input v-model="search" type="search" placeholder="Search concepts" aria-label="Search concepts" />
</div>
<p v-if="loading" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
<p v-else-if="!concepts.length" class="muted">No concepts yet.</p>
<p v-else-if="!shown.length" class="muted">Nothing matches.</p>
<ul v-else class="list card">
<li v-for="c in shown" :key="c.slug">
<RouterLink :to="{ name: 'concept', params: { slug: c.slug } }" class="item">
<span class="name">{{ c.title }}</span>
<time v-if="c.updated" class="muted" :datetime="c.updated">{{ formatDate(c.updated) }}</time>
<span v-if="c.summary" class="summary muted">{{ c.summary }}</span>
<span v-if="c.tags.length" class="tags">
<span v-for="t in c.tags" :key="t" class="badge">{{ t }}</span>
</span>
</RouterLink>
</li>
</ul>
</section>
</template>
<style scoped>
.page {
display: grid;
gap: 16px;
min-width: 0;
}
.intro {
margin: 0;
}
.ask {
display: grid;
gap: 10px;
padding: 16px;
}
.ask h2 {
font-size: 1.6rem;
margin: 0;
}
input[type="text"],
input[type="search"],
textarea {
padding: 6px 10px;
border: 1px solid var(--color-line);
border-radius: 4px;
background: var(--color-paper);
color: var(--color-ink);
min-width: 0;
}
textarea {
font-family: var(--font-mono);
font-size: 0.85rem;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
}
.row .muted {
font-size: 0.85rem;
}
.check {
display: flex;
align-items: center;
gap: 6px;
margin-right: auto;
}
.controls input {
width: 100%;
max-width: 320px;
}
.list > li + li {
border-top: 1px solid var(--color-line-soft);
}
.item {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 2px 16px;
padding: 10px 16px;
color: inherit;
text-decoration: none;
}
.item:hover {
background: var(--color-paper-tint);
}
li:first-child .item {
border-radius: 6px 6px 0 0;
}
li:last-child .item {
border-radius: 0 0 6px 6px;
}
.name {
font-size: 1.05rem;
overflow-wrap: anywhere;
}
time {
font-size: 0.85rem;
white-space: nowrap;
}
.summary,
.tags {
grid-column: 1 / -1;
}
.summary {
font-size: 0.875rem;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 4px;
}
</style>
+226
View File
@@ -0,0 +1,226 @@
<script setup>
/**
* One concept: the snippet to reuse first, since that is what a return
* visit is usually for, then the explanation folded into sections like a
* problem's. The admin can have it rewritten, with a note on what to
* change, or forget it.
*/
import { onUnmounted, ref, watch } from "vue";
import { RouterLink, useRouter } from "vue-router";
import { deleteConcept, getConcept, getMe, rewriteConcept, rewriteStatus } from "@/api";
import { formatDate } from "@/format";
import CodeBlock from "@/components/CodeBlock.vue";
import Explanation from "@/components/Explanation.vue";
const props = defineProps({ slug: { type: String, required: true } });
const router = useRouter();
const concept = ref(null);
const admin = ref(false);
const loading = ref(true);
const error = ref("");
const panel = ref("");
const note = ref("");
const job = ref({ state: "idle" });
const actionError = ref("");
let poll = null;
function stopPolling() {
clearTimeout(poll);
poll = null;
}
onUnmounted(stopPolling);
async function load() {
stopPolling();
loading.value = true;
error.value = "";
panel.value = "";
job.value = { state: "idle" };
try {
const [c, me] = await Promise.all([getConcept(props.slug), getMe().catch(() => ({ admin: false }))]);
concept.value = c;
admin.value = me.admin;
// A rewrite started before a reload is still worth waiting for.
if (me.admin) checkRewrite();
} catch (e) {
error.value = e.message;
} finally {
loading.value = false;
}
}
watch(() => props.slug, load, { immediate: true });
async function checkRewrite() {
stopPolling();
const slug = props.slug;
try {
const s = await rewriteStatus(slug);
if (slug !== props.slug) return;
const finished = job.value.state === "running" && s.state === "done";
job.value = s;
if (s.state === "running") {
poll = setTimeout(checkRewrite, 3000);
} else if (finished) {
concept.value = await getConcept(slug);
}
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
async function rewrite() {
try {
job.value = await rewriteConcept(props.slug, { note: note.value });
panel.value = "";
note.value = "";
poll = setTimeout(checkRewrite, 3000);
} catch (e) {
job.value = { state: "error", error: e.message };
}
}
async function forget() {
if (!confirm(`Delete “${concept.value.title}” and its snippet?`)) return;
actionError.value = "";
try {
await deleteConcept(props.slug);
router.push({ name: "concepts" });
} catch (e) {
actionError.value = e.message;
}
}
</script>
<template>
<div class="page">
<RouterLink to="/concepts" class="back">← All concepts</RouterLink>
<p v-if="loading && !concept" class="muted">Loading…</p>
<p v-else-if="error" class="error">{{ error }}</p>
<template v-else-if="concept">
<header>
<h1>{{ concept.title }}</h1>
<div class="facts">
<span v-for="t in concept.tags" :key="t" class="badge">{{ t }}</span>
<time v-if="concept.updated" class="muted" :datetime="concept.updated">
Updated {{ formatDate(concept.updated) }}
</time>
</div>
</header>
<section v-if="admin" class="admin">
<div class="admin-row">
<button class="btn" :disabled="job.state === 'running'" @click="panel = panel === 'rewrite' ? '' : 'rewrite'">
{{ job.state === "running" ? "Claude is rewriting…" : "Rewrite" }}
</button>
<button class="btn" :disabled="job.state === 'running'" @click="forget">Delete</button>
</div>
<div v-if="panel === 'rewrite'" class="panel">
<p class="muted">
Claude writes it again from the same question, starting from this version. Say what to change, or leave it
empty for a fresh take.
</p>
<textarea v-model="note" rows="3" placeholder="e.g. step 3's diagram is wrong; add range updates"></textarea>
<div class="admin-row">
<button class="btn primary" @click="rewrite">Rewrite</button>
<button class="btn" @click="panel = ''">Cancel</button>
</div>
</div>
<p v-if="job.state === 'error'" class="error">Rewrite: {{ job.error }}</p>
<p v-if="actionError" class="error">{{ actionError }}</p>
</section>
<section v-if="concept.snippet">
<h2>Code</h2>
<p class="filename muted">snippet.cpp</p>
<CodeBlock :content="concept.snippet.content" lang="cpp" :truncated="concept.snippet.truncated" />
<p class="cli muted">
From the CLI: <code>usaco snippet {{ concept.slug }} &lt;problem&gt;</code> pastes it above
<code>main</code>.
</p>
</section>
<section v-if="concept.content">
<h2>Explanation</h2>
<Explanation :source="concept.content" :open="['Intuition']" />
</section>
</template>
</div>
</template>
<style scoped>
.page {
display: grid;
gap: 24px;
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: 0 0 10px;
overflow-wrap: anywhere;
}
h2 {
font-size: 1.6rem;
margin-bottom: 8px;
}
.facts {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 10px;
font-size: 0.9rem;
}
.admin {
display: grid;
gap: 10px;
}
.admin-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.panel {
display: grid;
gap: 10px;
}
.panel p {
margin: 0;
font-size: 0.9rem;
}
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);
}
.filename {
margin: 0 0 4px;
font-family: var(--font-mono);
font-size: 0.8rem;
}
.cli {
margin: 8px 0 0;
font-size: 0.85rem;
}
.cli code {
font-family: var(--font-mono);
}
</style>