Files
usaco/site/web/src/components/CodeEditor.vue
T
adamfandClaude Opus 5.5 d4849859df
Test and publish the site / test (push) Successful in 1m25s
Test and publish the site / publish (push) Successful in 1m51s
Autocomplete and evaluate solutions on the solve page
The editor's completion popup was on but empty for C++, since
@codemirror/lang-cpp has no completion source. web/src/completions.js
adds one: keywords, the STL, every name in the file (the template's
macros show their expansion, typedefs what they alias), members after
. and ->, and snippets for the loops and lambdas typed over and over.
Python gains the contest standard library and members after ., on top
of lang-python's builtins and local names. Nothing knows types, so
members are the common ones plus those already used in the file.

Evaluate (POST/GET /problems/<name>/evaluate) has Claude judge the
editor's code as a strong competitive programmer would before
submitting. It runs the saved tests on the runner first, as Submit
does, and gives Claude the verdicts and up to three failing cases. The
reply is a verdict, correctness, complexity against the constraints,
line-anchored issues and a traced counterexample (internal/evaluate).
The page shows it in an Evaluation tab of the results panel, marks the
issues in the editor beside the lint's for as long as their lines are
unchanged, and can load the counterexample as the custom input.

It is a background job the page polls, like explanations, but it
commits nothing: the code is a draft. explain.Jobs.StartWith keeps a
finished job's answer in memory until the next one or a restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 12:46:54 +01:00

230 lines
9.6 KiB
Vue

<script setup>
/**
* The solve page's editor: CodeMirror 6 behind a v-model, in the paper
* palette (the colours are CodeBlock's highlight.js ones, so code reads the
* same in both).
*
* Each language keeps its own EditorState, rather than one state whose
* language sits in a Compartment: reconfiguring a shared state would give
* the two languages one undo history, so Ctrl+Z after a switch would bring
* back the other language's code. With a state each, switching back also
* restores the cursor and history where they were.
*
* Diagnostics come in as a prop, already fetched by the page (its lint call
* is remote and debounced by the page), and are pushed with setDiagnostics
* rather than through a linter() source the editor would schedule itself.
* CodeMirror maps them through later edits until the next set arrives.
*
* Completions come from basicSetup's autocompletion with sources of our own
* (completions.js), since lang-cpp has none.
*/
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { basicSetup } from "codemirror";
import { EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { indentWithTab } from "@codemirror/commands";
import { HighlightStyle, indentUnit, syntaxHighlighting } from "@codemirror/language";
import { lintGutter, setDiagnostics } from "@codemirror/lint";
import { cpp } from "@codemirror/lang-cpp";
import { python } from "@codemirror/lang-python";
import { tags as t } from "@lezer/highlight";
import { cppCompletions, pythonCompletions } from "@/completions";
const props = defineProps({
modelValue: { type: String, required: true },
lang: { type: String, required: true },
// The server's: 1-based line/col, endLine/endCol optional.
diagnostics: { type: Array, default: () => [] },
label: { type: String, default: "Code" },
});
const emit = defineEmits(["update:modelValue", "run", "submit", "save"]);
// The workspace's styles: clang-format's two spaces for C++, PEP 8's four.
const LANGS = {
cpp: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
c: () => [cpp(), cppCompletions(), indentUnit.of(" ")],
python: () => [python(), pythonCompletions(), indentUnit.of(" ")],
};
const highlight = HighlightStyle.define([
{ tag: t.comment, color: "#6a737d", fontStyle: "italic" },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.definitionKeyword, t.moduleKeyword, t.modifier, t.self], color: "#a3268d" },
{ tag: [t.typeName, t.className, t.namespace, t.standard(t.typeName)], color: "#0b6e99" },
{ tag: [t.string, t.special(t.string), t.character, t.escape], color: "#1a7f37" },
{ tag: [t.number, t.bool, t.null, t.atom, t.literal], color: "#b35900" },
{
tag: [t.function(t.variableName), t.function(t.definition(t.variableName)), t.function(t.propertyName)],
color: "#5a3fc0",
},
{ tag: [t.processingInstruction, t.meta, t.special(t.name)], color: "#8250df" },
{ tag: t.invalid, color: "var(--color-ink-danger)" },
]);
const theme = EditorView.theme(
{
"&": {
height: "100%",
fontSize: "0.8125rem",
color: "var(--color-ink-soft)",
backgroundColor: "var(--color-paper)",
},
// The wrapper draws focus, and the site's global :focus-visible ring
// would otherwise land on the contenteditable inside.
"&.cm-focused": { outline: "none" },
".cm-content:focus-visible": { outline: "none" },
".cm-scroller": { fontFamily: "var(--font-mono)", lineHeight: "1.55" },
".cm-content": { caretColor: "var(--color-ink)", padding: "12px 0" },
".cm-cursor, .cm-dropCursor": { borderLeftColor: "var(--color-ink)" },
".cm-gutters": {
backgroundColor: "var(--color-paper)",
color: "var(--color-ink-faint)",
borderRight: "1px solid var(--color-line-soft)",
},
".cm-lineNumbers .cm-gutterElement": { padding: "0 10px 0 12px" },
".cm-activeLine": { backgroundColor: "rgba(0, 0, 0, 0.03)" },
".cm-activeLineGutter": { backgroundColor: "transparent", color: "var(--color-ink)" },
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":
{ backgroundColor: "#d7e6fb" },
".cm-selectionMatch": { backgroundColor: "#eef3e2" },
"&.cm-focused .cm-matchingBracket": { backgroundColor: "var(--color-paper-shade)", outline: "1px solid var(--color-line)" },
".cm-tooltip": {
border: "1px solid var(--color-line)",
borderRadius: "4px",
backgroundColor: "var(--color-paper)",
color: "var(--color-ink)",
},
".cm-diagnostic": { fontFamily: "var(--font-mono)", fontSize: "0.8rem" },
".cm-diagnostic-error": { borderLeftColor: "var(--color-ink-danger)" },
".cm-diagnostic-warning": { borderLeftColor: "var(--color-solving)" },
".cm-diagnostic-info": { borderLeftColor: "var(--color-ink-faint)" },
".cm-diagnosticSource": { color: "var(--color-ink-muted)" },
".cm-panels": { backgroundColor: "var(--color-paper-tint)", color: "var(--color-ink)" },
".cm-tooltip.cm-tooltip-autocomplete > ul": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", maxHeight: "16em" },
".cm-tooltip.cm-tooltip-autocomplete > ul > li": { padding: "1px 8px 1px 4px" },
".cm-tooltip-autocomplete ul li[aria-selected]": { backgroundColor: "#d7e6fb", color: "var(--color-ink)" },
".cm-completionMatchedText": { textDecoration: "none", fontWeight: "600" },
".cm-completionDetail": { color: "var(--color-ink-muted)", fontStyle: "normal", marginLeft: "1em" },
".cm-completionIcon": { opacity: "0.55" },
".cm-tooltip.cm-completionInfo": { fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "4px 8px" },
".cm-snippetField": { backgroundColor: "rgba(0, 0, 0, 0.05)" },
},
{ dark: false },
);
// The page also listens for these on the window, for when the editor is not
// focused; stopping them here keeps one press from running twice, and keeps
// basicSetup's Mod-Enter (insert a blank line) out of the way.
const pageKeys = Prec.highest(
keymap.of([
{ key: "Mod-Shift-Enter", run: () => (emit("submit"), true), stopPropagation: true },
{ key: "Mod-Enter", run: () => (emit("run"), true), stopPropagation: true },
{ key: "Mod-s", run: () => (emit("save"), true), preventDefault: true, stopPropagation: true },
]),
);
const host = ref(null);
let view = null;
const states = new Map();
function newState(doc, lang) {
return EditorState.create({
doc,
extensions: [
pageKeys,
basicSetup,
keymap.of([indentWithTab]),
(LANGS[lang] || (() => []))(),
syntaxHighlighting(highlight),
lintGutter(),
theme,
EditorView.contentAttributes.of({ "aria-label": props.label }),
EditorView.updateListener.of((u) => {
if (u.docChanged) emit("update:modelValue", u.state.doc.toString());
}),
],
});
}
// The server's positions as document offsets. Columns are taken as
// characters; anything past the end of a line or the document is clamped,
// since the source may have moved on since the lint ran. Without an end
// the mark covers the word at the start, or the rest of the line.
function toDiagnostic(d, doc) {
const lineAt = (n) => doc.line(Math.min(Math.max(n || 1, 1), doc.lines));
const at = (lineNo, col) => {
const line = lineAt(lineNo);
return line.from + Math.min(Math.max((col || 1) - 1, 0), line.length);
};
const from = at(d.line, d.col);
let to = d.endLine > 0 ? at(d.endLine, d.endCol || 1) : from;
if (to <= from) {
const line = doc.lineAt(from);
const word = /^\w+/.exec(line.text.slice(from - line.from));
to = word ? from + word[0].length : line.to;
}
const severity = ["error", "warning", "info"].includes(d.severity) ? d.severity : "info";
const source = [d.source, d.rule].filter(Boolean).join(" ");
return { from, to, severity, message: d.message, ...(source ? { source } : {}) };
}
function pushDiagnostics() {
const doc = view.state.doc;
view.dispatch(setDiagnostics(view.state, props.diagnostics.map((d) => toDiagnostic(d, doc))));
}
onMounted(() => {
view = new EditorView({ state: newState(props.modelValue, props.lang), parent: host.value });
states.set(props.lang, view.state);
});
onBeforeUnmount(() => view?.destroy());
// The page sets the language and its source in one go, so they are watched
// together: a new language swaps in that language's state; a new value in
// the same language (Reset, Save's commit) replaces the text as an edit,
// so Ctrl+Z can bring the old text back.
watch(
() => [props.lang, props.modelValue],
([lang, value], [oldLang]) => {
if (!view) return;
if (lang !== oldLang) {
states.set(oldLang, view.state);
const kept = states.get(lang);
view.setState(kept && kept.doc.toString() === value ? kept : newState(value, lang));
pushDiagnostics();
} else if (value !== view.state.doc.toString()) {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
}
},
);
watch(() => props.diagnostics, () => view && pushDiagnostics());
// Puts the cursor at the start of a line's code and shows it.
function goto(line) {
if (!view) return;
const l = view.state.doc.line(Math.min(Math.max(line, 1), view.state.doc.lines));
const at = l.from + (/^\s*/.exec(l.text)?.[0].length || 0);
view.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
view.focus();
}
defineExpose({ focus: () => view?.focus(), goto });
</script>
<template>
<div ref="host" class="editor"></div>
</template>
<style scoped>
.editor {
height: 100%;
min-height: 0;
border: 1px solid var(--color-line-soft);
border-radius: 6px;
overflow: hidden;
background: var(--color-paper);
}
.editor:focus-within {
border-color: var(--color-ink-muted);
}
</style>