mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
# Conflicts: # public/asset-manifest.json # public/css/all.min.css # public/css/style.css # public/partials/gist.htm # public/script/components.js # public/script/vendor.min.js # test/vue-ui.test.js
264 lines
14 KiB
JavaScript
264 lines
14 KiB
JavaScript
// Reviewer pages for an anonymized gist (/gist/:id) and pull request (/pr/:id):
|
|
// outlines, scroll spy, the parsed diff and the conversation timeline.
|
|
import { nextTick, onScopeDispose } from "vue";
|
|
import { activeSection, jumpTo, redactParts } from "./outline.js";
|
|
import { parseDiff, hangIndent, parseDelimited } from "./formatters.js";
|
|
import { createListeners } from "./state.js";
|
|
import { readHashState } from "./table-analysis.js";
|
|
|
|
export const lineCount = (text) => (text ? String(text).replace(/\n$/, "").split("\n").length : 0);
|
|
export const isMarkdownFile = (file) => /\.(md|markdown|mdx)$/i.test(file?.filename || "") || file?.language === "Markdown";
|
|
|
|
// Shared by both pages: slots, the narrow-screen menu and the scroll spy.
|
|
function setupOutline(state, anchors) {
|
|
const listen = createListeners();
|
|
state.redactParts = redactParts;
|
|
state.hangIndent = hangIndent;
|
|
state.isRedactedName = (text) => /^XXXX-\d+$/.test(String(text || "").trim());
|
|
state.tocOpen = false;
|
|
state.activeAnchor = "";
|
|
const update = () => {
|
|
const ids = anchors();
|
|
if (!ids.length) return;
|
|
const current = activeSection(ids, { offset: 64, scroller: window.document.querySelector("main.app-view") });
|
|
if (state.activeAnchor !== current) state.activeAnchor = current;
|
|
};
|
|
// Capture: the page may scroll inside the app's main element rather than the window.
|
|
listen(window, "scroll", update, { capture: true, passive: true });
|
|
listen(window, "resize", update, { passive: true });
|
|
listen(window.document, "click", (e) => { if (state.tocOpen && !e.target.closest?.(".toc-menu")) state.tocOpen = false; });
|
|
listen(window.document, "keydown", (e) => { if (e.key === "Escape" && state.tocOpen) state.tocOpen = false; });
|
|
state.jumpToAnchor = (id) => {
|
|
state.tocOpen = false;
|
|
if (jumpTo(id)) state.activeAnchor = id;
|
|
};
|
|
return update;
|
|
}
|
|
|
|
const extension = (name) => (String(name || "").split(".").pop() || "").toLowerCase();
|
|
const KIND_BY_EXTENSION = {
|
|
md: "markdown", markdown: "markdown", mdx: "markdown", ipynb: "notebook", csv: "csv", tsv: "csv", svg: "svg",
|
|
png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", bmp: "image", ico: "image", avif: "image",
|
|
pdf: "pdf", mp4: "video", webm: "video", mov: "video", m4v: "video", ogv: "video",
|
|
mp3: "audio", wav: "audio", ogg: "audio", oga: "audio", m4a: "audio", flac: "audio", aac: "audio",
|
|
};
|
|
const MIME = {
|
|
svg: "image/svg+xml", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", bmp: "image/bmp",
|
|
ico: "image/x-icon", avif: "image/avif", pdf: "application/pdf", mp4: "video/mp4", webm: "video/webm", mov: "video/quicktime",
|
|
m4v: "video/mp4", ogv: "video/ogg", mp3: "audio/mpeg", wav: "audio/wav", ogg: "audio/ogg", oga: "audio/ogg", m4a: "audio/mp4",
|
|
flac: "audio/flac", aac: "audio/aac",
|
|
};
|
|
const CSV_LIMIT = 1024 * 1024;
|
|
// Which of the explorer's viewers shows a gist file. Binary files arrive as base64.
|
|
export function gistFileKind(file) {
|
|
if (file?.tooLarge) return "too-large";
|
|
if (file?.hidden) return "hidden";
|
|
const kind = KIND_BY_EXTENSION[extension(file?.filename)] || (file?.language === "Markdown" ? "markdown" : null);
|
|
if (file?.encoding === "base64") return ["image", "pdf", "video", "audio"].includes(kind) && file.content ? kind : "binary";
|
|
if (!file?.content) return "empty";
|
|
if (kind === "csv" && file.content.length > CSV_LIMIT) return "code";
|
|
return ["markdown", "notebook", "csv", "svg"].includes(kind) ? kind : "code";
|
|
}
|
|
// Formats with a rendered view as well as their source.
|
|
export const hasRenderedView = (kind) => ["markdown", "notebook", "csv", "svg"].includes(kind);
|
|
const KIND_LABEL = { markdown: "Markdown", notebook: "Jupyter notebook", csv: "Table", svg: "SVG", image: "Image", pdf: "PDF", video: "Video", audio: "Audio", binary: "Binary", "too-large": "Too large", hidden: "Image" };
|
|
// The Prism language of a file's source view.
|
|
export function gistSourceLanguage(file, kind) {
|
|
if (kind === "markdown") return "markdown";
|
|
if (kind === "notebook") return "json";
|
|
if (kind === "svg") return "markup";
|
|
if (kind === "csv") return "none";
|
|
return file?.language || extension(file?.filename) || "none";
|
|
}
|
|
const decodeBase64 = (text) => {
|
|
const bin = window.atob(text || "");
|
|
const bytes = new Uint8Array(bin.length);
|
|
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
return bytes;
|
|
};
|
|
|
|
export function setupGistPage(state) {
|
|
// Rendered or raw, per file; the file's bytes as blob URLs for media, Raw and Download.
|
|
// A shared link can open a CSV file's chart (#table-2:view=chart).
|
|
state.gistViews = {};
|
|
const linked = /^#table-(\d+):/.exec(window.location.hash || "");
|
|
if (linked) {
|
|
const view = readHashState(window.location.hash, "table-" + linked[1])?.view;
|
|
if (view === "chart" || view === "raw") state.gistViews[+linked[1] - 1] = view;
|
|
}
|
|
state.gistKind = (index) => gistFileKind(state.details?.files?.[index]);
|
|
state.gistHasRendered = (index) => hasRenderedView(state.gistKind(index));
|
|
state.gistView = (index) => {
|
|
if (!state.gistHasRendered(index) || state.gistViews[index] === "raw") return "raw";
|
|
return state.gistViews[index] === "chart" && state.gistKind(index) === "csv" ? "chart" : "rendered";
|
|
};
|
|
state.setGistView = (index, view) => { state.gistViews = { ...state.gistViews, [index]: view }; };
|
|
state.gistSourceFile = (index) => {
|
|
const file = state.details?.files?.[index];
|
|
return { ...file, language: gistSourceLanguage(file, state.gistKind(index)), filename: "source.txt" };
|
|
};
|
|
const urls = new Map();
|
|
onScopeDispose(() => { urls.forEach((url) => window.URL.revokeObjectURL?.(url)); urls.clear(); });
|
|
const blobUrl = (file, raw) => {
|
|
if (!file || !window.URL?.createObjectURL) return null;
|
|
const binary = file.encoding === "base64";
|
|
const mime = !raw || binary ? MIME[extension(file.filename)] || (binary ? "application/octet-stream" : "text/plain") : "text/plain";
|
|
const key = (file.filename || "") + "\0" + mime + "\0" + (file.content || "").length;
|
|
if (!urls.has(key)) {
|
|
const body = binary ? decodeBase64(file.content) : file.content || "";
|
|
urls.set(key, window.URL.createObjectURL(new window.Blob([body], { type: mime + (binary ? "" : ";charset=utf-8") })));
|
|
}
|
|
return urls.get(key);
|
|
};
|
|
state.gistMediaUrl = (file) => blobUrl(file, false);
|
|
state.gistRawUrl = (file) => blobUrl(file, true);
|
|
// Parsed once per file: the table viewer re-analyzes only when its rows change.
|
|
// Keyed by the file object: no 1 MB key string per render, and a reloaded
|
|
// gist's old files are released with it.
|
|
const csvCache = new WeakMap();
|
|
state.gistCsvRows = (file) => {
|
|
if (!file) return [];
|
|
let entry = csvCache.get(file);
|
|
if (!entry || entry.content !== file.content || entry.filename !== file.filename) {
|
|
entry = { content: file.content, filename: file.filename, rows: parseDelimited(file.content || "", extension(file.filename) === "tsv" ? "\t" : ",") };
|
|
csvCache.set(file, entry);
|
|
}
|
|
return entry.rows;
|
|
};
|
|
state.gistCopied = null;
|
|
state.copyGistFile = async (index) => {
|
|
const file = state.details?.files?.[index];
|
|
if (!file || file.encoding === "base64" || !window.navigator.clipboard?.writeText) return;
|
|
await window.navigator.clipboard.writeText(file.content || "");
|
|
state.gistCopied = index;
|
|
window.setTimeout(() => { if (state.gistCopied === index) state.gistCopied = null; }, 1600);
|
|
};
|
|
|
|
state.fileOutlines = {};
|
|
state.gistFileId = (index) => "file-" + (index + 1);
|
|
state.setFileOutline = (index, list) => {
|
|
const prev = state.fileOutlines[index];
|
|
if (prev && prev.map((h) => h.id).join() === list.map((h) => h.id).join()) return;
|
|
state.fileOutlines = { ...state.fileOutlines, [index]: list };
|
|
};
|
|
// Each file (name, language, lines), with a Markdown file's headings nested under it.
|
|
state.gistToc = () => (state.details?.files || []).map((file, index) => ({
|
|
id: state.gistFileId(index),
|
|
index,
|
|
parts: redactParts(file.filename),
|
|
kind: gistFileKind(file),
|
|
language: KIND_LABEL[gistFileKind(file)] && gistFileKind(file) !== "csv" ? KIND_LABEL[gistFileKind(file)] : file.language || (gistFileKind(file) === "csv" ? "CSV" : "Text"),
|
|
lines: file.encoding === "base64" ? null : lineCount(file.content),
|
|
size: file.size,
|
|
headings: isMarkdownFile(file) && state.gistView(index) === "rendered" ? state.fileOutlines[index] || [] : [],
|
|
}));
|
|
const anchors = () => state.gistToc().flatMap((f) => [f.id, ...f.headings.map((h) => h.id)]);
|
|
// Worth an outline from two files, or one Markdown file with three headings.
|
|
state.showGistToc = () => {
|
|
const toc = state.gistToc();
|
|
return state.tabState?.active === "files" && (toc.length >= 2 || (toc[0]?.headings.length || 0) >= 3);
|
|
};
|
|
state.activeFileIndex = () => {
|
|
const toc = state.gistToc();
|
|
const hit = toc.find((f) => f.id === state.activeAnchor || f.headings.some((h) => h.id === state.activeAnchor));
|
|
return hit ? hit.index : 0;
|
|
};
|
|
setupOutline(state, anchors);
|
|
}
|
|
|
|
const stateOf = (d) => d?.merged ? "merged" : d?.draft && d?.state === "open" ? "draft" : d?.state === "closed" ? "closed" : "open";
|
|
|
|
export function setupPullRequestPage(state) {
|
|
let diffCache = { diff: null, threads: null, files: [] };
|
|
// Files of the diff; review threads hang under the line they were left on, or
|
|
// at the end of the file when that line is not in the diff.
|
|
state.prFiles = () => {
|
|
const diff = state.details?.diff, threads = state.details?.reviewComments || [];
|
|
if (diffCache.diff === diff && diffCache.threads === threads) return diffCache.files;
|
|
const files = parseDiff(diff).map((file, index) => {
|
|
const own = threads.filter((t) => t.path === file.path);
|
|
const placed = new Set();
|
|
const lines = file.lines.map((line) => {
|
|
// RIGHT threads use the new numbering, LEFT ones the old: the same
|
|
// number can name a removed line and an unrelated added line.
|
|
const at = own.filter((t) => !placed.has(t) && t.line != null
|
|
&& (t.side === "LEFT" ? line.kind === "remove" && t.line === line.oldNo : line.kind !== "remove" && line.kind !== "hunk" && t.line === line.newNo));
|
|
at.forEach((t) => placed.add(t));
|
|
return at.length ? { ...line, threads: at } : line;
|
|
});
|
|
return { ...file, index, id: "diff-" + (index + 1), lines, parts: redactParts(file.path),
|
|
dir: file.path.includes("/") ? file.path.slice(0, file.path.lastIndexOf("/") + 1) : "",
|
|
name: file.path.slice(file.path.lastIndexOf("/") + 1),
|
|
threads: own.length, looseThreads: own.filter((t) => !placed.has(t)) };
|
|
});
|
|
diffCache = { diff, threads, files };
|
|
return files;
|
|
};
|
|
state.prStats = () => state.prFiles().reduce((s, f) => ({ files: s.files + 1, additions: s.additions + f.additions, deletions: s.deletions + f.deletions }), { files: 0, additions: 0, deletions: 0 });
|
|
// GitHub's five-square bar: green for additions, red for deletions.
|
|
state.diffBar = (file) => {
|
|
const total = file.additions + file.deletions;
|
|
const add = total ? Math.round((file.additions / total) * 5) : 0;
|
|
const del = total ? Math.min(5 - add, Math.round((file.deletions / total) * 5)) : 0;
|
|
return [...Array(add).fill("add"), ...Array(del).fill("del"), ...Array(5 - add - del).fill("none")];
|
|
};
|
|
state.prState = () => stateOf(state.details);
|
|
state.prStateLabel = () => ({ merged: "Merged", draft: "Draft", closed: "Closed", open: "Open" })[state.prState()];
|
|
state.collapsedFiles = {};
|
|
state.toggleFile = (index) => { state.collapsedFiles = { ...state.collapsedFiles, [index]: !state.collapsedFiles[index] }; };
|
|
state.allCollapsed = () => state.prFiles().length > 0 && state.prFiles().every((f) => state.collapsedFiles[f.index]);
|
|
state.toggleAllFiles = () => {
|
|
const collapse = !state.allCollapsed();
|
|
state.collapsedFiles = Object.fromEntries(state.prFiles().map((f) => [f.index, collapse]));
|
|
};
|
|
state.reviewThreadCount = () => (state.details?.reviewComments || []).length;
|
|
state.conversationCount = () => (state.details?.comments?.length || 0) + state.reviewThreadCount();
|
|
// Comments and review threads in date order (undated items keep their order).
|
|
state.prTimeline = () => {
|
|
const items = [
|
|
...(state.details?.comments || []).map((c, i) => ({ key: "c" + i, kind: "comment", date: c.creationDate || c.updatedDate, comments: [c] })),
|
|
...(state.details?.reviewComments || []).map((t, i) => ({ key: "r" + i, kind: "review", date: t.comments?.[0]?.creationDate, thread: t, comments: t.comments || [],
|
|
file: state.prFiles().find((f) => f.path === t.path) })),
|
|
];
|
|
if (items.every((i) => i.date)) items.sort((a, b) => new Date(a.date) - new Date(b.date));
|
|
return items;
|
|
};
|
|
// Commits grouped by day like GitHub; no SHAs (they identify the repository).
|
|
state.commitGroups = () => {
|
|
const groups = [];
|
|
(state.details?.commits || []).forEach((commit, index) => {
|
|
const [headline, ...rest] = String(commit.message || "").split("\n");
|
|
const day = commit.date ? state.fmt?.date(commit.date) : "";
|
|
let group = groups[groups.length - 1];
|
|
if (!group || group.day !== day) groups.push((group = { day, commits: [] }));
|
|
group.commits.push({ ...commit, index: index + 1, headline, detail: rest.join("\n").trim() });
|
|
});
|
|
return groups;
|
|
};
|
|
state.showFileToc = () => state.tabState?.active === "files" && state.prFiles().length >= 2;
|
|
state.activeFileIndex = () => {
|
|
const hit = state.prFiles().find((f) => f.id === state.activeAnchor);
|
|
return hit ? hit.index : 0;
|
|
};
|
|
state.openTab = (tab) => { state.tabState = { active: tab }; state.tocOpen = false; };
|
|
// A review thread's "View in diff": switch tab, expand the file, scroll to it.
|
|
state.showInDiff = (file) => {
|
|
if (!file) return;
|
|
state.openTab("files");
|
|
state.collapsedFiles = { ...state.collapsedFiles, [file.index]: false };
|
|
nextTick(() => state.jumpToAnchor(file.id));
|
|
};
|
|
state.jumpToFile = (file) => {
|
|
state.collapsedFiles = { ...state.collapsedFiles, [file.index]: false };
|
|
state.jumpToAnchor(file.id);
|
|
};
|
|
setupOutline(state, () => (state.tabState?.active === "files" ? state.prFiles().map((f) => f.id) : []));
|
|
}
|
|
|
|
// The tab a pull request opens on: its conversation when there is one.
|
|
export function defaultPullRequestTab(details) {
|
|
if (details?.body || details?.comments?.length || details?.reviewComments?.length) return "conversation";
|
|
if (details?.diff) return "files";
|
|
return details?.commits?.length ? "commits" : "conversation";
|
|
}
|