codehygiene / web /src /main.js
brianbellx's picture
Deploy scoring-only Space: remove edit model and fix features
a1415e8 verified
Raw History Blame Contribute Delete
7.74 kB
import { byId, copyWithIcon, prefersReducedMotion } from "./dom.js";
import { isFullRepoUrl, parseRepoSpec, specLabel } from "./github.js";
import { SOURCE_ERRORS, issuesText, toHundred } from "./labels.js";
import { createNavigator } from "./navigator.js";
import { boardLink, rankErrorText, rankLabel, requestRank } from "./ranking.js";
import { fetchStats } from "./refiner.js";
import { paintSample } from "./sample.js";
import { createScorer } from "./scoring.js";
import { loadExamples, loadFolder, loadRepo, loadSnippet } from "./sources.js";
import { createStage } from "./stage.js";
import { hideBannerStats, renderBanner, reportScan } from "./telemetry.js";
const nodes = {
sample: byId("sample"),
stage: byId("stage"),
input: byId("source-input"),
error: byId("source-error"),
progress: byId("source-progress"),
copy: byId("copy"),
copyIcon: byId("copy-icon"),
rank: byId("rank"),
rankOpen: byId("rank-open"),
rankText: byId("rank-text"),
};
const narrowScreen = window.matchMedia("(max-width: 640px)");
const scorer = createScorer();
const stage = createStage();
const fileNav = createNavigator(selectFile);
const app = {
repoSpec: null,
sourceKind: "examples",
files: [],
shown: null,
ingest: null,
standing: null,
ingestAbort: null,
};
function renderProgress() {
nodes.progress.hidden = !app.ingest;
nodes.progress.textContent = app.ingest ?? "";
}
function renderActions(file) {
nodes.copy.hidden = !file;
const rankable = app.sourceKind === "repo" && Boolean(app.repoSpec);
nodes.rank.hidden = !rankable || Boolean(app.standing);
nodes.rankOpen.hidden = !rankable || !app.standing;
}
function paintStanding(standing) {
nodes.rankText.textContent = rankLabel(standing);
nodes.rankOpen.href = boardLink(standing.repo);
const points = Math.round(standing.score);
nodes.rankOpen.title = `${standing.repo}: ${points}/100, #${standing.rank} of ${standing.total}`;
}
function setBusy(button, busy) {
button.disabled = busy;
button.classList.toggle("is-busy", busy);
button.setAttribute("aria-busy", String(busy));
}
function showSourceError(message) {
nodes.error.hidden = !message;
nodes.error.textContent = message;
}
async function rankRepo() {
const spec = app.repoSpec;
showSourceError("");
setBusy(nodes.rank, true);
try {
const standing = await requestRank(spec);
if (app.repoSpec === spec) {
app.standing = standing;
paintStanding(standing);
}
} catch (error) {
showSourceError(rankErrorText(error));
} finally {
setBusy(nodes.rank, false);
renderActions(app.shown);
}
}
function showFile(file, { enter = true, freshTree = false } = {}) {
app.shown = file;
stage.resetScore();
if (freshTree) {
fileNav.render(app.files, file);
} else {
fileNav.update(app.files, file);
}
stage.setHead({
filename: file.path,
statusText: issuesText(file.result.squiggles.length),
points: toHundred(file.result.score),
});
stage.renderPlain({
text: file.content,
filename: file.path,
squiggles: file.result.squiggles,
enter,
});
renderActions(file);
}
function selectFile(file) {
showFile(file);
}
function bringStageIntoView() {
if (narrowScreen.matches) {
const behavior = prefersReducedMotion() ? "auto" : "smooth";
nodes.stage.scrollIntoView({ behavior, block: "start" });
}
}
function revealStage(update) {
if (!nodes.stage.hidden) {
update();
return;
}
const swap = () => {
nodes.sample.hidden = true;
nodes.stage.hidden = false;
update();
};
if (!document.startViewTransition || prefersReducedMotion()) {
swap();
bringStageIntoView();
return;
}
document.startViewTransition(swap).finished.then(bringStageIntoView);
}
function syncUrl() {
const url = new URL(window.location.href);
url.searchParams.delete("repo");
if (app.repoSpec) {
url.searchParams.set("repo", specLabel(app.repoSpec));
}
url.search = url.searchParams.toString().replaceAll("%2F", "/").replaceAll("%40", "@");
window.history.replaceState(null, "", url);
}
function startFiles({ files, sourceKind, repoSpec = null }) {
Object.assign(app, { files, sourceKind, repoSpec, standing: null, ingest: null });
syncUrl();
renderProgress();
reportScan(sourceKind, files);
revealStage(() => showFile(files[0], { enter: true, freshTree: true }));
}
async function startExamples() {
showSourceError("");
app.ingestAbort?.abort();
const files = await loadExamples(scorer.scoreAll);
startFiles({ files, sourceKind: "examples" });
}
async function startRepo(spec) {
showSourceError("");
app.ingestAbort?.abort();
const aborter = new AbortController();
app.ingest = "Fetching";
app.ingestAbort = aborter;
renderProgress();
try {
const files = await loadRepo(spec, {
signal: aborter.signal,
scoreAll: scorer.scoreAll,
onProgress: (text) => {
app.ingest = text;
renderProgress();
},
});
startFiles({ files, sourceKind: "repo", repoSpec: spec });
} catch (error) {
if (error.name === "AbortError") {
return;
}
app.ingest = null;
renderProgress();
showSourceError(SOURCE_ERRORS[error.code] ?? SOURCE_ERRORS.offline);
}
}
async function startFolder(fileList) {
showSourceError("");
app.ingestAbort?.abort();
app.ingest = "Reading";
renderProgress();
try {
const files = await loadFolder(fileList, {
scoreAll: scorer.scoreAll,
onProgress: (text) => {
app.ingest = text;
renderProgress();
},
});
nodes.input.value = "";
startFiles({ files, sourceKind: "folder" });
} catch (error) {
app.ingest = null;
renderProgress();
showSourceError(SOURCE_ERRORS[error.code] ?? SOURCE_ERRORS.no_files);
}
}
async function startSnippet(text) {
showSourceError("");
app.ingestAbort?.abort();
const files = await loadSnippet(text, scorer.scoreAll);
startFiles({ files, sourceKind: "snippet" });
}
function submitLink(text) {
const spec = parseRepoSpec(text);
if (!spec) {
showSourceError(SOURCE_ERRORS.invalid);
return;
}
nodes.input.value = spec.slug;
startRepo(spec);
}
function handlePaste(event) {
const text = event.clipboardData?.getData("text/plain") ?? "";
if (text.trim().includes("\n")) {
event.preventDefault();
startSnippet(text);
return;
}
if (isFullRepoUrl(text)) {
event.preventDefault();
nodes.input.value = text.trim();
submitLink(text);
}
}
function bindControls() {
byId("source").addEventListener("submit", (event) => {
event.preventDefault();
submitLink(nodes.input.value);
});
nodes.copy.addEventListener("click", () => copyWithIcon(nodes.copy, nodes.copyIcon, app.shown.content));
nodes.rank.addEventListener("click", rankRepo);
byId("command-copy").addEventListener("click", () => copyWithIcon(
byId("command-copy"),
byId("command-copy-icon"),
byId("command-text").textContent,
));
byId("sample-run").addEventListener("click", startExamples);
const uploadInput = byId("upload-input");
byId("upload").addEventListener("click", () => uploadInput.click());
uploadInput.addEventListener("change", () => {
if (uploadInput.files.length > 0) {
startFolder([...uploadInput.files]);
}
uploadInput.value = "";
});
document.addEventListener("paste", handlePaste);
}
function boot() {
bindControls();
fetchStats().then(renderBanner, hideBannerStats);
paintSample(scorer.scoreAll);
const repoParam = new URLSearchParams(window.location.search).get("repo");
const spec = repoParam ? parseRepoSpec(repoParam) : null;
if (spec) {
nodes.input.value = spec.slug;
startRepo(spec);
}
}
boot();