Turn the code browser into a full-viewport app: tree in the rail, Code | Why, plain-text diffs at Pierre's measures
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- The code routes name the rail's slot (`staticData.rail`): one tree stays mounted across tree, blob and why; a commit's rail lists its changed files open, A/M/D in the diff tints with `+n −m`. The slot's module is light (a route's staticData loads on every page); its body (ref switcher over listRefs, the tree, J/K) loads lazily in the browser. The tree moves the page with the router, never `location.assign`; Files opens it as a sheet below 1120 px. - Blob and why are one page in two modes; the file header is the sticky toolbar (path trail with copy, words, Code | Why, Raw, Permalink, Copy). "This file" names the last change, ask and answer first, SHA second (`log` limit 1 read beside the file). - Why groups consecutive lines from one commit into one band (same band in the server's plain lines and Pierre's annotations), with "why, one step back"; no credit count, no age colour. - Tree page lists the directory once as rows, with what last changed each entry read after the page (at most 30 entries, three reads at a time). - Landings: sticky day groups, ask, compact credit, sealed "held back", short SHA over age, All / Answers / Ask openings. - Commit: status line, body as prose, git's line; Credit (trailers once), Diff stats split by the answered ask's territory, Provenance. The diff is Pierre's CodeView in a sticky pane that scrolls only once stuck, over the server's PlainDiff, which parses with the drawing's own parser so the hunks match. Unified | Split is client state; split from 48 rem; added or deleted files past 80 lines start folded; Collapse all. - DiffCode takes annotations, header slots and read/refused status for the finish and waiver pages. - Highlighting runs in Pierre's worker pool (one per tab); a hover's preload warms a file's highlighting. A missing path lands on the nearest folder with UnknownPath as its notice. Code pages answer immutable headers at a SHA, branch headers at main or a tag. - Tests: rewritten code, code-client and why cases (each old assertion kept or replaced by a stronger one), new code-diff tests (hunks, counts, folding, stats, keys) and diff-anchor tests; e2e selectors updated. - Tree SSR left out: 465,281 bytes unminified against 234,742 of headroom (ready-for-human with the sizes). J/K use the code pages' own listener because the shared useFileKeys starts from no file. - ASSUMPTION: Vite resolves `new URL("@pierre/diffs/worker/worker.js", import.meta.url)` in production as in dev (the build passes; not seen deployed).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
50 files+5503 added−1630 removed
- tests:+1103 added−269 removed
- other:+4400 added−1361 removed
Provenance
- Commit
f63aa3b- Tree
b5afea7- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
bbace25
50 files changed+5503 added−1630 removed
modified:apps/web/e2e/imports.e2e.ts+6 added-3 removed
324 unmodified lines325 326 test(`${project}'s log groups its commits by day`, ({ page: browser }) =>327 Effect.runPromise(328 visit(browser, project, `/${project}/commits/main`, "commits", {329- selectors: [`a[href^="/${project}/commit/"]`],330- texts: ["Commits on"],329+ selectors: [`a[href^="/${project}/commit/"]`, "[data-day]"],330+ texts: ["Landings"],331 })332 ));333 334 test(`${project}'s newest commit shows what it changed`, ({2 unmodified lines337 Effect.runPromise(338 Effect.gen(function* () {339 const href = yield* newestCommit(browser, project);340 341- yield* visit(browser, project, href, "commit", { texts: ["changed"] });341+ yield* visit(browser, project, href, "commit", {342+ selectors: ["[data-diffs-header]"],343+ texts: ["changed"],344+ });345 })346 ));347 348 test(`${project}'s refs show main and its tags`, ({ page: browser }) =>261 unmodified linesmodified:apps/web/e2e/why.e2e.ts+2 added-2 removed
67 unmodified lines68697071727372737475767712 unmodified lines67 unmodified lines );
expect(response?.status()).toBe(200);
// A range's row, in the server's table or above the drawn lines, // linking the ask its landing answered or opened. // A group's band, among the server's lines or above the drawn // ones, linking the ask its landing answered or opened. yield* Effect.promise(() => expect( browser.locator(`[data-range] a[href^="/${project}/asks/"]`).first() ).toBeVisible()12 unmodified linesmodified:apps/web/src/client/code.ts+52 added-2 removed
6 unmodified lines7891011121112131415161764 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331346 unmodified lines * path for the file tree, `pathsAtom`) or keeps live: the project page's * root folder and README (`projectCodeAtom`), which its loader also read. */import type { Contract } from "@repo/protocol/contracts";import type { ProjectName } from "@repo/protocol/ids";import { Effect } from "effect";import type { CommitView } from "@repo/protocol/domain/code";import type { ProjectName, RepoPath } from "@repo/protocol/ids";import { Array, Effect, Option } from "effect";import { Atom } from "effect/reactivity";import type { Rpc } from "effect/rpc";
import { ContractsClient } from "../surfaces.ts";64 unmodified lines ) ) ));
/** At most this many of a folder's entries have what last changed them read. */export const LAST_CHANGES_CAP = 30;
/** * What last changed each of a folder's entries at a commit, by path: one * `log` of one commit per entry (the platform keeps a path's history once * walked), three at a time, read after the page and only in the browser. * An entry whose read fails is left out; a folder of more than * `LAST_CHANGES_CAP` entries reads none, to spare the platform the walks. */export const lastChangesAtom = Atom.family( (key: { readonly at: string; readonly paths: readonly RepoPath[]; readonly project: ProjectName; }) => Atom.withServerValueInitial( ContractsClient.runtime.atom( Effect.gen(function* () { const client = yield* ContractsClient;
if (key.paths.length > LAST_CHANGES_CAP) { return new Map<string, CommitView>(); }
const found = yield* Effect.forEach( key.paths, (path) => client("log", { at: key.at, limit: 1, path, project: key.project, }).pipe( Effect.map(({ commits }) => Option.fromUndefinedOr(commits[0])), Effect.orElseSucceed(() => Option.none<CommitView>()), Effect.map((commit) => Option.map(commit, (last) => [path, last] as const) ) ), { concurrency: 3 } );
return new Map<string, CommitView>(Array.getSomes(found)); }) ) ));modified:apps/web/src/features/code/blob-view.tsx+92 added-182 removed
1 /**2- * One file of a project at a revision. The server sends its text as a3- * `<pre>` with one numbered, anchored line each (`#L42` scrolls there with4- * no script), capped at `FALLBACK_LINES`; the browser then draws it with5- * `@pierre/diffs` (`code`, from `client-code.tsx`), keeping the `#L10-L20`6- * selection in the address. A Markdown file is rendered (its source on7- * `?plain=1`), an image is shown from raw, and a binary file or one past8- * the read cap says its size and links its raw bytes.2+ * One file of a project at a revision, in Code mode (its Why mode is3+ * `why/why-view.tsx`, the same page). The file header stays under the4+ * context bar: the path once, the file in words, Code | Why, Raw,5+ * Permalink (`y`) and Copy. The code takes the pane's whole width and6+ * scrolls sideways inside itself, never wrapping: the server sends it as7+ * numbered, anchored plain text (`NumberedLines`), which the browser's8+ * highlighted drawing (`code`, from `client-code.tsx`) replaces in place.9 *10- * The toolbar: Raw (at the commit the page resolved, so it caches for11- * good), Why and History (at the page's revision), Permalink (the page at12- * that commit; `y` rewrites the address to it) and Copy.10+ * A Markdown file is rendered (its source on `?plain=1`), an image is shown11+ * from raw, and a binary file or one past the read cap says its size and12+ * links its bytes. The inspector holds "This file".13 */14-import type { FileView } from "@repo/protocol/domain/code";14+import type { CommitView, FileView } from "@repo/protocol/domain/code";15 import type { ProjectName } from "@repo/protocol/ids";16-import { useEffect } from "react";16+import type { DateTime } from "effect";17 import type { ReactNode } from "react";18 19-import { buttonVariants } from "@/components/ui/button";20-19 import { ReadmeSection } from "../project/readme-section.tsx";22-import { LINK } from "../shared/classes.ts";23-import { CopyButton } from "./copy.tsx";20+import { AppLink } from "../shared/link.tsx";21+import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";22+import { FileFacts } from "./file-facts.tsx";23+import { FileHeader, PermalinkKey } from "./file-header.tsx";24+import { NumberedLines } from "./numbered-lines.tsx";25 import {26 blobHref,26- commitsHref,27 isImage,28 isMarkdown,29 rawHref,30 sizeInWords,31- whyHref,31 } from "./paths.ts";33-import { revLabel } from "./rev.ts";34-import { CodeBreadcrumb, CodeLayout } from "./tree-view.tsx";32 36-/** How many lines the server sends; the browser's drawing shows them all. */37-export const FALLBACK_LINES = 2000;33+const LINK = "decoration-rule underline hover:decoration-current";34 39-const TOOL = buttonVariants({40- className: "no-underline",41- size: "sm",42- variant: "ghost",43-});44-45-/** A text's lines, without the empty one after its last newline. */46-export const linesOf = (text: string): readonly string[] => {47- const lines = text.split("\n");48-49- return lines.at(-1) === "" ? lines.slice(0, -1) : lines;50-};51-52-/** The file as plain text: each line numbered and anchored `L<n>`. */53-export const NumberedLines = ({ text }: { readonly text: string }) => {54- const lines = linesOf(text);55- const shown = lines.slice(0, FALLBACK_LINES);56-57- return (58- <div className="flex min-w-0 flex-col gap-2">59- <pre className="border-rule bg-surface overflow-x-auto border py-2 font-mono text-[0.8125rem] leading-5">60- <code className="grid grid-cols-[auto_1fr]">61- {shown.map((line, index) => {62- const number = index + 1;63-64- // The anchor sits on the line's text: the row around it is65- // `display: contents`, which draws no box to scroll to.66- return (67- <span className="contents" key={number}>68- <a69- className="text-muted-foreground hover:text-foreground pr-4 pl-3 text-right no-underline select-none"70- href={`#L${number}`}71- >72- {number}73- </a>74- <span className="pr-3 whitespace-pre" id={`L${number}`}>75- {line}76- </span>77- </span>78- );79- })}80- </code>81- </pre>82- {lines.length > shown.length ? (83- <p className="text-muted-foreground text-sm">84- The first {FALLBACK_LINES.toLocaleString("en")} of{" "}85- {lines.length.toLocaleString("en")} lines.86- </p>87- ) : null}88- </div>89- );90-};91-92-/** `y` rewrites the address to the page at its commit, keeping the line anchor. */93-const PermalinkKey = ({ href }: { readonly href: string }) => {94- useEffect(() => {95- const onKey = (event: KeyboardEvent) => {96- const typing =97- event.target instanceof HTMLElement &&98- (event.target.isContentEditable ||99- ["INPUT", "SELECT", "TEXTAREA"].includes(event.target.tagName));100-101- if (102- event.key === "y" &&103- !typing &&104- !event.metaKey &&105- !event.ctrlKey &&106- !event.altKey107- ) {108- globalThis.history.replaceState(109- globalThis.history.state,110- "",111- `${href}${globalThis.location.search}${globalThis.location.hash}`112- );113- }114- };115-116- globalThis.addEventListener("keydown", onKey);117-118- return () => {119- globalThis.removeEventListener("keydown", onKey);120- };121- }, [href]);122-123- return null;124-};125-35 /** What the server shows of a file that has no text to number. */36 const Bytes = ({37 file,38 project,2 unmodified lines41 readonly file: FileView;42 readonly project: ProjectName;43 readonly words: string;44 }) => (45+ <div className={`${GUTTER} ${MEASURE} pt-6`}>136- <p className="border-rule border border-dashed px-4 py-5 text-sm">137- {words} ({sizeInWords(file.size)}).{" "}138- <a className={LINK} href={rawHref(project, file.at, file.path)}>139- View raw140- </a>141- </p>46+ <p className="border-rule text-ui border border-dashed px-4 py-5">47+ {words} ({sizeInWords(file.size)}).{" "}48+ <a className={LINK} href={rawHref(project, file.at, file.path)}>49+ View raw50+ </a>51+ </p>52+ </div>53 );54 55 /** The file's body: an image, Markdown, numbered text, or its size. */56 const Body = ({10 unmodified lines67 readonly rev: string;68 }) => {69 if (isImage(file.path) && !plain) {70 return (71+ <div className={`${GUTTER} pt-6`}>160- <img161- alt={file.path}162- className="border-rule max-w-full border"163- src={rawHref(project, file.at, file.path)}164- />72+ <img73+ alt={file.path}74+ className="border-rule max-w-full border"75+ src={rawHref(project, file.at, file.path)}76+ />77+ </div>78 );79 }80 81 if (file.binary) {11 unmodified lines93 }94 95 if (isMarkdown(file.path) && !plain) {96 return (184- <>185- <p className="text-sm">97+ <div className={`${GUTTER} ${MEASURE} flex flex-col gap-4 pt-6`}>98+ <p className="text-ui">99+ {/* A plain link: the router would write the 1 as a quoted string. */}100 <a101 className={LINK}102 href={`${blobHref(project, rev, file.path)}?plain=1`}103 >104 Show the source105 </a>106 </p>107 <ReadmeSection file={file} project={project} />194- </>108+ </div>109 );110 }111 112 return (113 <>114 {isMarkdown(file.path) ? (201- <p className="text-sm">202- <a className={LINK} href={blobHref(project, rev, file.path)}>115+ <p className={`${GUTTER} text-ui pt-4`}>116+ <AppLink className={LINK} to={blobHref(project, rev, file.path)}>117 Show it rendered204- </a>118+ </AppLink>119 </p>120 ) : null}121 {code ?? <NumberedLines text={file.text} />}122 </>123 );124 };125 126+export interface BlobViewProps {127+ readonly file: FileView;128+ readonly project: ProjectName;129+ readonly rev: string;130+ /** The browser's drawing of the text, holding `NumberedLines` as its fallback. */131+ readonly code?: ReactNode;132+ /** `?plain=1`: a Markdown file's source, not its rendering. */133+ readonly plain?: boolean;134+ /** The commit that last changed the file. */135+ readonly last?: CommitView | undefined;136+ readonly now: DateTime.Utc;137+ /** The Files button, below the shell's width. */138+ readonly files?: ReactNode;139+}140+141 export const BlobView = ({142 code,143 file,144+ files,145+ last,146+ now,147 plain = false,148 project,149 rev,218- sidebar,219-}: {220- /**221- * The browser's drawing of the text, holding `NumberedLines` as its222- * fallback; the numbered lines alone when absent.223- */224- readonly code?: ReactNode;225- readonly file: FileView;226- /** `?plain=1`: a Markdown file's source, not its rendering. */227- readonly plain?: boolean;228- readonly project: ProjectName;229- readonly rev: string;230- /** The file tree, drawn in the browser. */231- readonly sidebar?: ReactNode;232-}) => {233- const permalink = blobHref(project, file.at, file.path);234-235- return (236- <CodeLayout237- project={project}238- sidebar={sidebar}239- title={`${file.path} at ${revLabel(rev)}`}240- >241- <PermalinkKey href={permalink} />242- <CodeBreadcrumb path={file.path} project={project} rev={rev} />243- <div className="text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">244- <span>{sizeInWords(file.size)}</span>245- <nav246- aria-label="File"247- className="flex flex-wrap gap-1"248- data-toolbar="file"249- >250- <a className={TOOL} href={rawHref(project, file.at, file.path)}>251- Raw252- </a>253- <a className={TOOL} href={whyHref(project, rev, file.path)}>254- Why255- </a>256- <a257- className={TOOL}258- href={commitsHref(project, rev, { path: file.path })}259- >260- History261- </a>262- <a className={TOOL} href={permalink} title="Permalink (y)">263- Permalink264- </a>265- </nav>266- {file.text === undefined ? null : (267- <CopyButton label="Copy" text={file.text} />268- )}269- </div>270- <Body code={code} file={file} plain={plain} project={project} rev={rev} />271- </CodeLayout>272- );273-};150+}: BlobViewProps) => (151+ <Workspace152+ crumbs={[153+ { label: project, to: `/${project}` },154+ { label: "Code", to: `/${project}/tree/main` },155+ { label: file.path.split("/").at(-1) ?? file.path, mono: true },156+ ]}157+ facts={158+ <FileFacts159+ file={file}160+ last={last}161+ now={now}162+ project={project}163+ rev={rev}164+ />165+ }166+ factsHeading="This file"167+ title={file.path.split("/").at(-1) ?? file.path}168+ toolbar={169+ <FileHeader170+ file={file}171+ files={files}172+ mode="code"173+ path={file.path}174+ project={project}175+ rev={rev}176+ />177+ }178+ variant="code"179+ >180+ <PermalinkKey href={blobHref(project, file.at, file.path)} />181+ <Body code={code} file={file} plain={plain} project={project} rev={rev} />182+ </Workspace>183+);modified:apps/web/src/features/code/client-code.tsx+1 added-1 removed
1 /**2 * A file and a commit's diff, drawn in the browser only. `@pierre/diffs`3 * and Shiki's grammars are megabytes, and the drawing needs the DOM, so the4- * server renders `fallback` (numbered lines, or the changed files by name)4+ * server renders `fallback` (numbered lines, or the plain-text diff)5 * and the browser loads the drawing after hydration. `import.meta.env.SSR`6 * is `true` in the Worker's build, so the dynamic imports below are dead7 * code there and the Worker bundles none of it (`bytes:check`), as8 * `features/finish/client-diff.tsx` does.44 unmodified linesmodified:apps/web/src/features/code/client-tree.tsx+3 added-3 removed
1 /**2 * The project's file tree, drawn in the browser only (`repo-tree.tsx`,3- * `@pierre/trees`). The server renders `fallback` (nothing, or the commit's4- * list of changed files), and the browser loads the tree after hydration;5- * the Worker bundles none of it, as `client-code.tsx` explains.3+ * `@pierre/trees`), in the rail's slot or the Files sheet. The server4+ * renders `fallback` (nothing), and the browser loads the tree after5+ * hydration; the Worker bundles none of it, as `client-code.tsx` explains.6 */7 import { ClientOnly } from "@tanstack/react-router";8 import { lazy, Suspense } from "react";9 import type { ReactNode } from "react";20 unmodified linesmodified:apps/web/src/features/code/code-view.tsx+16 added-17 removed
3 unmodified lines4 * the address as `#L10` or `#L10-L20` (`line-hash.ts`) and scrolled to on5 * load. Its lines live in a shadow root, where a native `#L` fragment6 * cannot reach, so the drawing scrolls to the anchored line itself.7 *8- * It is Pierre's `File`, not its virtualized `CodeView`, which draws9- * nothing until it mounts; a file is capped at 1 MiB, and past10- * `HIGHLIGHT_LIMIT` characters it is drawn without highlighting.8+ * It is Pierre's `File`, not its virtualized `CodeView`: a file is capped9+ * at 1 MiB, it flows in the page's own scroll under the file header (so it10+ * draws no header of its own), and past the shared limits (`pierre.ts`) it is11+ * drawn without highlighting. Highlighting runs in the worker pool.12 *13 * The library and Shiki's grammars are megabytes, so only the browser14 * loads this module (`client-code.tsx`); the Worker never bundles it.15 */4 unmodified lines20 21 import { lineHash, parseLineHash } from "./line-hash.ts";22 import type { LineRange } from "./line-hash.ts";23 import { diffsOptions, registerCodeTheme } from "./pierre.ts";24+import { CodePool } from "./pool.tsx";25 26 registerCodeTheme();27 26-/** Past this many characters a file is drawn without highlighting. */27-const HIGHLIGHT_LIMIT = 300_000;28-28 export interface FileCodeProps {29 readonly path: string;30 /** The blob's id: the drawing's cache key. */31 readonly sha: string;21 unmodified lines53 line === undefined54 ? null55 : node?.shadowRoot?.querySelector(`[data-line="${line}"]`);56 58- if (row !== null && row !== undefined) {59- // The page scrolls, not the drawing, and only up or down:60- // `scrollIntoView` would also slide a wide line sideways under the61- // line numbers.62- globalThis.scrollBy({63- top: row.getBoundingClientRect().top - globalThis.innerHeight / 2,64- });57+ if (row instanceof HTMLElement) {58+ // Whichever scrolls the code (main from the shell's width, the page59+ // below it) brings the line to its middle, and only up or down: the60+ // code's own sideways scroll stays where it is.61+ row.scrollIntoView({ block: "center", inline: "nearest" });62 pending.line = undefined;63 }64 };65 49 unmodified lines115 onPostRender: (node: HTMLElement) => {116 pending.current.node = node;117 reveal(pending.current);118 },119+ disableFileHeader: true,120 overflow: "scroll",123- tokenizeMaxLength: HIGHLIGHT_LIMIT,121 }),122 []123 );124 125 return (126+ <CodePool>129- <div className="border-rule min-w-0 border" data-code="pierre">130- <File file={file} options={options} selectedLines={selected} />131- </div>127+ <div className="min-w-0" data-code="pierre">128+ <File file={file} options={options} selectedLines={selected} />129+ </div>130+ </CodePool>131 );132 };133 134 // `React.lazy` takes a module's default export.1 unmodified linemodified:apps/web/src/features/code/commit-view.tsx+396 added-271 removed
1 /**2- * One commit: its message, who wrote and committed it, its parents, the3- * people its trailers name (each a link to their page), and, when the4- * platform landed it, the landing's ask, answer and verdict. Below, the5- * files it changed against its first parent: a plain list from the6- * server, which the browser replaces with the file tree and the diffs7- * (`drawing`, from `client-code.tsx`). Unified by default; `?style=split`8- * sets the sides apart.2+ * One commit, read as a landing first and a diff second. The head: the3+ * subject, the landing's status line ("Landed as 9b1c3e5 · answered4+ * format-ordinal", the SHA and the ask linked), the body as prose, and5+ * git's own metadata on one muted line. The inspector holds the typed6+ * facts: this landing's state, its credit (the trailers, once), the diff's7+ * stats split by path, and its provenance. Then the diff, file by file, in8+ * a pane of its own: the server's plain text (`PlainDiff`), which the9+ * browser's drawing (`drawing`, from `client-code.tsx`) replaces in place.10+ *11+ * A commit the platform did not land came in with the history the project12+ * adopted, and says so; its trailers are listed as written, linking no one.13 */14 import type {11- ChangedFile,15 CommitDiff,16 CommitView as Commit,14- Signature,17 } from "@repo/protocol/domain/code";16-import { CreditRole } from "@repo/protocol/domain/credit";17-import { Handle } from "@repo/protocol/ids";18 import type { ProjectName } from "@repo/protocol/ids";19-import { Match, Option, Schema } from "effect";19+import { Option } from "effect";20 import type { DateTime } from "effect";21+import { Columns2, FoldVertical, Rows3, UnfoldVertical } from "lucide-react";22 import type { ReactNode } from "react";23 23-import { ProjectNav } from "../project/project-nav.tsx";24-import { ID, LABEL, LINK } from "../shared/classes.ts";24+import { Button } from "@/components/ui/button";25+26+import { CreditFacts, FactBlock, ProvenanceFacts } from "../shared/facts.tsx";27+import type { ProvenanceEntry } from "../shared/facts.tsx";28 import { HandleLink } from "../shared/handle.tsx";26-import { PageShell } from "../shared/layout.tsx";27-import { OutcomeView } from "../shared/outcome.tsx";29+import { AppLink } from "../shared/link.tsx";30+import { StateMarkIcon } from "../shared/marks.tsx";31 import { answerPath, askPath } from "../shared/paths.ts";32+import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";33 import { When } from "../shared/time.tsx";34 import { askOf } from "../why/rows.ts";35+import { drawnFiles, statsOf } from "./diff-model.ts";36+import type { DiffStats } from "./diff-model.ts";37+import { DiffPane, PANE_SCROLLER } from "./diff-pane.tsx";31-import { blobHref, commitHref, shortSha, treeHref } from "./paths.ts";38+import { commitHref, shortSha, treeHref } from "./paths.ts";39+import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";40 33-const isRole = Schema.is(CreditRole);41+const LINK = "decoration-rule underline hover:decoration-current";42 35-const isHandle = Schema.is(Handle);43+/** A trailer line: `Key: value`, the key one word of letters and dashes. */44+const TRAILER = /^[A-Za-z][\w-]*:\s/u;45 37-/** Each change as its mark says it. */38-const statusWords = Match.type<ChangedFile["status"]>().pipe(39- Match.when("added", () => ({ mark: "A", words: "added" })),40- Match.when("modified", () => ({ mark: "M", words: "modified" })),41- Match.when("deleted", () => ({ mark: "D", words: "deleted" })),42- Match.exhaustive43-);46+/**47+ * The body without its trailers, which the Credit block shows: git's48+ * trailer block is the last paragraph when every line of it is a49+ * `Key: value`.50+ */51+export const bodyWithoutTrailers = (commit: Commit) => {52+ const paragraphs = commit.body.trim().split(/\n\s*\n/u);53+ const last = paragraphs.at(-1) ?? "";54 45-/** The body without the trailer lines shown apart below it. */46-const bodyWithoutTrailers = (commit: Commit) => {47- const trailers = new Set(48- commit.trailers.map(({ key, value }) => `${key}: ${value}`)49- );55+ const trailers =56+ commit.trailers.length > 0 &&57+ last.split("\n").every((line) => TRAILER.test(line.trim()));58 51- return commit.body52- .split("\n")53- .filter((line) => !trailers.has(line.trim()))54- .join("\n")55- .trim();59+ return (trailers ? paragraphs.slice(0, -1) : paragraphs).join("\n\n").trim();60 };61 58-const Person = ({59- label,62+/** Where the commit stands, in one line: landed as its SHA, and the ask it answered or opened. */63+export const LandingStatus = ({64+ commit,65+ project,66+}: {67+ readonly commit: Commit;68+ readonly project: ProjectName;69+}) => {70+ const { landing } = commit;71+72+ if (landing === undefined) {73+ return (74+ <p className="text-want text-muted-foreground flex items-start gap-2">75+ <StateMarkIcon className="mt-1" mark="notNeeded" />76+ <span>77+ Before adoption: this commit came in with the history the project78+ adopted, so no landing records it.79+ </span>80+ </p>81+ );82+ }83+84+ const linked = Option.getOrUndefined(askOf(landing));85+86+ return (87+ <p className="text-want flex items-start gap-2" data-outcome="Landed">88+ <StateMarkIcon className="mt-1" mark="landed" />89+ <span className="min-w-0 [overflow-wrap:anywhere]">90+ <strong className="text-landed font-semibold">Landed</strong> as{" "}91+ <AppLink92+ className={`text-mono font-mono ${LINK}`}93+ to={commitHref(project, commit.sha)}94+ >95+ {shortSha(commit.sha)}96+ </AppLink>97+ {linked === undefined ? null : (98+ <>99+ <span aria-hidden="true" className="text-muted-foreground">100+ {" · "}101+ </span>102+ {linked.kind === "opened" ? "opened " : "answered "}103+ <AppLink104+ className={`text-mono font-mono ${LINK}`}105+ to={askPath(project, linked.ask)}106+ >107+ {linked.ask}108+ </AppLink>109+ </>110+ )}111+ </span>112+ </p>113+ );114+};115+116+/** Git's own metadata, on one line: who wrote it, who committed it, its parents. */117+const GitLine = ({118+ commit,119 now,61- signature,120+ project,121 }: {63- readonly label: string;122+ readonly commit: Commit;123 readonly now: DateTime.Utc;65- readonly signature: Signature;124+ readonly project: ProjectName;125 }) => (67- <div className="flex min-w-0 flex-col">68- <dt className={LABEL}>{label}</dt>69- <dd className="[overflow-wrap:anywhere]">70- {signature.name}{" "}71- <span className="text-muted-foreground">72- <When at={signature.at} now={now} />126+ <span className="[overflow-wrap:anywhere]">127+ authored by {commit.author.name} <When at={commit.author.at} now={now} />128+ {" · "}129+ committed by{" "}130+ {commit.landing === undefined ? commit.committer.name : "the platform"}131+ {" · "}132+ {commit.parents.length === 0 ? (133+ "the first commit"134+ ) : (135+ <>136+ {commit.parents.length === 1 ? "parent" : "parents"}{" "}137+ {commit.parents.map((parent, index) => (138+ <span key={parent}>139+ {index === 0 ? null : ", "}140+ <AppLink141+ className={`text-mono font-mono ${LINK}`}142+ to={commitHref(project, parent)}143+ >144+ {shortSha(parent)}145+ </AppLink>146+ </span>147+ ))}148+ </>149+ )}150+ {" · "}151+ <AppLink className={LINK} to={treeHref(project, commit.sha)}>152+ Browse files153+ </AppLink>154+ </span>155+);156+157+const PART_WORDS = {158+ other: "other",159+ territory: "territory",160+ tests: "tests",161+} as const;162+163+/** The diff in numbers: files, lines added and removed, then split by path. */164+export const DiffStatsFacts = ({ stats }: { readonly stats: DiffStats }) => (165+ <FactBlock label="Diff stats">166+ <p167+ className="text-ui flex flex-wrap items-center gap-x-3 gap-y-1"168+ data-stats=""169+ >170+ <span>171+ {stats.files} {stats.files === 1 ? "file" : "files"}172 </span>74- </dd>75- </div>173+ <ChangeCounts additions={stats.additions} deletions={stats.deletions} />174+ </p>175+ {stats.parts.length === 0 ? null : (176+ <ul className="text-ui flex flex-col gap-1">177+ {stats.parts.map((part) => (178+ <li179+ className="flex items-center justify-between gap-3"180+ data-part={part.label}181+ key={part.label}182+ >183+ <span className="text-muted-foreground">184+ {PART_WORDS[part.label]}185+ <span className="sr-only">:</span>186+ </span>187+ <ChangeCounts188+ additions={part.additions}189+ deletions={part.deletions}190+ />191+ </li>192+ ))}193+ </ul>194+ )}195+ </FactBlock>196 );197 78-/**79- * The person a credit trailer names on a landing: its value's handle,80- * before any ` <email>` (`Asked-by: ines-v <ines-v@users.…>`). Only the81- * platform's own landings name its people; an imported commit's82- * `Signed-off-by:` names someone elsewhere, never a page here.83- */84-const personIn = (landed: boolean, name: string, value: string) => {85- const handle = value.replace(/\s*<[^>]*>$/u, "");198+/** The trailers of a commit the platform did not land, as written, linking no one. */199+const WrittenTrailers = ({ commit }: { readonly commit: Commit }) =>200+ commit.trailers.length === 0 ? null : (201+ <FactBlock label="Trailers">202+ <ul className="text-mono leading-terminal flex flex-col gap-1 font-mono">203+ {commit.trailers.map(({ key, value }) => (204+ <li className="[overflow-wrap:anywhere]" key={`${key}:${value}`}>205+ <span className="text-muted-foreground">{key}:</span> {value}206+ </li>207+ ))}208+ </ul>209+ </FactBlock>210+ );211 87- return landed && isRole(name) && isHandle(handle) ? handle : undefined;88-};212+/** A landing's credit from the record; a commit the platform did not land, its trailers as written. */213+const LandingCredit = ({ commit }: { readonly commit: Commit }) =>214+ commit.landing === undefined ? (215+ <WrittenTrailers commit={commit} />216+ ) : (217+ <CreditFacts218+ assisted={commit.landing.assisted}219+ credits={commit.landing.credits}220+ heldBack={commit.landing.heldBackTrailer}221+ />222+ );223 90-/** A trailer: a landing's credit links the person; any other reads as written. */91-const Trailer = ({92- landed,93- name,94- value,224+/** Where the commit comes from: its id, its tree, its people and parents, and the landing's request. */225+const provenanceOf = (commit: Commit): readonly ProvenanceEntry[] => [226+ { label: "Commit", value: commit.sha },227+ { label: "Tree", value: commit.tree },228+ { label: "Author", value: `${commit.author.name} <${commit.author.email}>` },229+ {230+ label: "Committer",231+ value: `${commit.committer.name} <${commit.committer.email}>`,232+ },233+ ...commit.parents.map((parent, index) => ({234+ label: commit.parents.length === 1 ? "Parent" : `Parent ${index + 1}`,235+ value: parent,236+ })),237+ ...(commit.landing?.verdict === undefined238+ ? []239+ : [{ label: "Patch id", value: commit.landing.verdict.patchId }]),240+ ...(commit.landing?.requestId === undefined241+ ? []242+ : [{ label: "Request-Id", value: commit.landing.requestId }]),243+];244+245+/** The inspector's facts for a commit. */246+const CommitFacts = ({247+ commit,248+ project,249+ stats,250 }: {96- readonly landed: boolean;97- readonly name: string;98- readonly value: string;251+ readonly commit: Commit;252+ readonly project: ProjectName;253+ readonly stats: DiffStats;254 }) => {100- const person = personIn(landed, name, value);255+ const linked =256+ commit.landing === undefined257+ ? undefined258+ : Option.getOrUndefined(askOf(commit.landing));259 260 return (103- <li className="[overflow-wrap:anywhere]">104- <span className="text-muted-foreground">{name}:</span>{" "}105- {person === undefined ? value : <HandleLink handle={person} />}106- </li>261+ <>262+ <FactBlock label="State">263+ <LandingStatus commit={commit} project={project} />264+ {commit.landing === undefined ? null : (265+ <p className="text-ui text-muted-foreground">266+ By <HandleLink handle={commit.landing.author} />267+ {linked === undefined || linked.kind === "opened" ? null : (268+ <>269+ {" · "}270+ <AppLink className={LINK} to={answerPath(project, linked.ask)}>271+ the answer and its checks272+ </AppLink>273+ </>274+ )}275+ </p>276+ )}277+ </FactBlock>278+ <LandingCredit commit={commit} />279+ <DiffStatsFacts stats={stats} />280+ <ProvenanceFacts entries={provenanceOf(commit)} />281+ </>282 );283 };284 110-/** The changed files by path, each linking its new version (or its old one, deleted). */111-export const ChangedList = ({112- commit,285+/** A segmented pair of buttons, the pressed one in ink. */286+const SEGMENT =287+ "text-ui hover:bg-surface aria-pressed:bg-foreground aria-pressed:text-background aria-pressed:hover:bg-foreground flex h-7 cursor-pointer items-center gap-1.5 px-2.5 font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:size-3.5";288+289+/** The diff's toolbar: unified or split, fold or unfold every file, and the counts. */290+export const DiffToolbar = ({291+ allFolded,292 files,114- project,293+ onFoldAll,294+ onSplit,295+ split,296+ stats,297 }: {116- readonly commit: Commit;117- readonly files: readonly ChangedFile[];118- readonly project: ProjectName;298+ readonly split: boolean;299+ readonly onSplit?: ((split: boolean) => void) | undefined;300+ /** Whether every file is folded now. */301+ readonly allFolded: boolean;302+ readonly onFoldAll?: ((folded: boolean) => void) | undefined;303+ readonly stats: DiffStats;304+ /** The Files button, below the shell's width. */305+ readonly files?: ReactNode;306 }) => (120- <ul className={`flex flex-col gap-1 ${ID}`}>121- {files.map((file) => {122- const { mark, words } = statusWords(file.status);123- const at = file.status === "deleted" ? commit.parents[0] : commit.sha;124-125- return (126- <li127- className="flex min-w-0 items-baseline gap-2"128- data-file={file.path}129- key={file.path}130- >131- <span132- aria-label={words}133- className="text-muted-foreground w-3 shrink-0"134- title={words}135- >136- {mark}137- </span>138- {at === undefined ? (139- <span className="[overflow-wrap:anywhere]">{file.path}</span>140- ) : (141- <a142- className={`${LINK} [overflow-wrap:anywhere]`}143- href={blobHref(project, at, file.path)}144- >145- {file.path}146- </a>147- )}148- </li>149- );150- })}151- </ul>307+ <>308+ {files === undefined ? null : (309+ <div className="shell:hidden flex shrink-0">{files}</div>310+ )}311+ <fieldset className="border-input diffsplit:flex m-0 hidden min-w-0 border p-0">312+ <legend className="sr-only">Diff layout</legend>313+ <button314+ aria-pressed={!split}315+ className={SEGMENT}316+ onClick={() => onSplit?.(false)}317+ type="button"318+ >319+ <Rows3 aria-hidden="true" strokeWidth={1.75} />320+ Unified321+ </button>322+ <button323+ aria-pressed={split}324+ className={SEGMENT}325+ onClick={() => onSplit?.(true)}326+ type="button"327+ >328+ <Columns2 aria-hidden="true" strokeWidth={1.75} />329+ Split330+ </button>331+ </fieldset>332+ <span className="text-muted-foreground">333+ <Button onClick={() => onFoldAll?.(!allFolded)} size="sm" variant="ghost">334+ {allFolded ? (335+ <UnfoldVertical aria-hidden="true" strokeWidth={1.75} />336+ ) : (337+ <FoldVertical aria-hidden="true" strokeWidth={1.75} />338+ )}339+ {allFolded ? "Unfold all" : "Collapse all"}340+ </Button>341+ </span>342+ <p className="text-ui text-muted-foreground ml-auto flex items-center gap-3 tabular-nums">343+ <span>344+ {stats.files} {stats.files === 1 ? "file" : "files"}345+ <span className="tablet:inline hidden"> changed</span>346+ </span>347+ <ChangeCounts additions={stats.additions} deletions={stats.deletions} />348+ </p>349+ </>350 );351 352+export interface CommitViewProps {353+ readonly diff: CommitDiff;354+ readonly now: DateTime.Utc;355+ readonly project: ProjectName;356+ /** The ask's territory, when the commit landed an answer: the stats split by it. */357+ readonly territory?: readonly string[] | undefined;358+ /** Old and new side by side. */359+ readonly split?: boolean;360+ readonly onSplit?: ((split: boolean) => void) | undefined;361+ /** The files folded now; each file's default when absent. */362+ readonly folded?: ReadonlySet<string> | undefined;363+ readonly onFold?: ((path: string, folded: boolean) => void) | undefined;364+ readonly onFoldAll?: ((folded: boolean) => void) | undefined;365+ /** The browser's drawing of the diff, holding `PlainDiff` as its fallback. */366+ readonly drawing?: ReactNode;367+ /** The Files button, below the shell's width. */368+ readonly files?: ReactNode;369+}370+371 export const CommitView = ({372 diff,373 drawing,374+ files: filesButton,375+ folded,376 now,377+ onFold,378+ onFoldAll,379+ onSplit,380 project,381 split = false,160-}: {161- readonly diff: CommitDiff;162- /**163- * The browser's file tree and diffs, holding `ChangedList` as their164- * fallback; the list alone when absent.165- */166- readonly drawing?: ReactNode;167- readonly now: DateTime.Utc;168- readonly project: ProjectName;169- /** `?style=split`: old and new side by side. */170- readonly split?: boolean;171-}) => {382+ territory,383+}: CommitViewProps) => {384 const { commit, files, truncated } = diff;173- const { landing } = commit;174-175- const linked =176- landing === undefined ? undefined : Option.getOrUndefined(askOf(landing));177-385 const body = bodyWithoutTrailers(commit);179- const here = commitHref(project, commit.sha);386+ const drawn = drawnFiles(files);387+ const stats = statsOf(drawn, territory);388 389+ const allFolded = drawn.every((file) =>390+ folded === undefined ? file.folded : folded.has(file.file.path)391+ );392+393 return (182- <PageShell394+ <Workspace395+ facts={<CommitFacts commit={commit} project={project} stats={stats} />}396+ factsHeading={397+ commit.landing === undefined ? "This commit" : "This landing"398+ }399+ meta={<GitLine commit={commit} now={now} project={project} />}400+ state={401+ commit.landing === undefined ? undefined : (402+ <span className="flex items-center gap-1.5">403+ <StateMarkIcon mark="landed" />404+ <strong className="text-landed font-semibold">Landed</strong>405+ </span>406+ )407+ }408+ status={409+ <div className="flex flex-col gap-4">410+ <LandingStatus commit={commit} project={project} />411+ {body === "" ? null : (412+ <p413+ className="text-body max-w-[70ch] [overflow-wrap:anywhere] whitespace-pre-wrap"414+ data-body=""415+ >416+ {body}417+ </p>418+ )}419+ </div>420+ }421 title={422 commit.subject === ""423 ? `Commit ${shortSha(commit.sha)}`424 : commit.subject425 }426+ toolbar={427+ <DiffToolbar428+ allFolded={allFolded}429+ files={filesButton}430+ onFoldAll={onFoldAll}431+ onSplit={onSplit}432+ split={split}433+ stats={stats}434+ />435+ }436+ variant="code"437 >189- <ProjectNav current="landings" project={project} />190- <section aria-label="Commit" className="flex flex-col gap-4">191- <p className={`${ID} text-muted-foreground [overflow-wrap:anywhere]`}>192- commit {commit.sha} ·{" "}193- <a className={LINK} href={treeHref(project, commit.sha)}>194- Browse files195- </a>196- </p>197- {body === "" ? null : (198- <pre className="max-w-[80ch] font-mono text-[0.8125rem] leading-6 [overflow-wrap:anywhere] whitespace-pre-wrap">199- {body}200- </pre>201- )}202- <dl className="grid gap-x-8 gap-y-2 text-sm sm:grid-cols-3">203- <Person label="Author" now={now} signature={commit.author} />204- <Person label="Committer" now={now} signature={commit.committer} />205- <div className="flex min-w-0 flex-col">206- <dt className={LABEL}>207- {commit.parents.length === 1 ? "Parent" : "Parents"}208- </dt>209- <dd className={`flex flex-wrap gap-2 ${ID}`}>210- {commit.parents.length === 0211- ? "none: the first commit"212- : commit.parents.map((parent) => (213- <a214- className={LINK}215- href={commitHref(project, parent)}216- key={parent}217- >218- {shortSha(parent)}219- </a>220- ))}221- </dd>222- </div>223- </dl>224- {commit.trailers.length === 0 ? null : (225- <section aria-label="Trailers" className="flex flex-col gap-1.5">226- <h2 className={LABEL}>Trailers</h2>227- <ul className={`flex flex-col gap-1 ${ID}`}>228- {commit.trailers.map(({ key, value }) => (229- <Trailer230- key={`${key}:${value}`}231- landed={landing !== undefined}232- name={key}233- value={value}234- />235- ))}236- </ul>237- </section>238- )}239- </section>240- {landing === undefined ? (241- <p className="text-muted-foreground text-sm">242- The platform did not land this commit: it came in with the history the243- project adopted (before adoption).244- </p>245- ) : (246- <section247- aria-label="Landing"248- className="border-rule flex flex-col gap-3 border-t pt-4"249- >250- <h2 className="text-lg font-semibold">Landing</h2>251- <dl className="flex flex-wrap gap-x-8 gap-y-2 text-sm">252- {linked === undefined ? null : (253- <>254- <div>255- <dt className={LABEL}>256- {linked.kind === "opened" ? "Opened" : "Ask"}257- </dt>258- <dd>259- <a260- className={`${ID} ${LINK}`}261- href={askPath(project, linked.ask)}262- >263- {linked.ask}264- </a>265- </dd>266- </div>267- {linked.kind === "opened" ? null : (268- <div>269- <dt className={LABEL}>Answer</dt>270- <dd>271- <a272- className={LINK}273- href={answerPath(project, linked.ask)}274- >275- The answer and its checks276- </a>277- </dd>278- </div>279- )}280- </>281- )}282- <div>283- <dt className={LABEL}>Author</dt>284- <dd>285- <HandleLink handle={landing.author} />286- </dd>287- </div>288- <div>289- <dt className={LABEL}>Landed</dt>290- <dd>291- <When at={landing.landedAt} now={now} />292- </dd>293- </div>294- </dl>295- {landing.verdict === undefined ? null : (296- <OutcomeView outcome={landing.verdict.outcome} />297- )}298- </section>299- )}300- <section301- aria-label="Changes"302- className="flex min-w-0 flex-col gap-3"303- data-files=""304- >305- <div className="flex flex-wrap items-baseline justify-between gap-2">306- <h2 className="text-lg font-semibold">307- {files.length} {files.length === 1 ? "file" : "files"} changed308- </h2>309- <p className="text-sm">310- {split ? (311- <a className={LINK} href={here}>312- Unified313- </a>314- ) : (315- <a className={LINK} href={`${here}?style=split`}>316- Split317- </a>318- )}319- </p>320- </div>321- {truncated ? (322- <p className="border-rule border border-dashed px-4 py-3 text-sm">438+ {truncated ? (439+ <div className={`${GUTTER} ${MEASURE}`}>440+ <p className="border-rule text-ui border border-dashed px-4 py-3">441 This commit is too large to show whole: its files are listed by442 path, without their changes.443 </p>326- ) : null}327- {drawing === undefined || truncated ? (328- <ChangedList commit={commit} files={files} project={project} />329- ) : (330- drawing444+ </div>445+ ) : null}446+ <DiffPane>447+ {drawing ?? (448+ <div className={PANE_SCROLLER}>449+ <PlainDiff450+ files={files}451+ folded={folded}452+ onFold={onFold}453+ split={split}454+ />455+ </div>456 )}332- </section>333- </PageShell>457+ </DiffPane>458+ </Workspace>459 );460 };added:apps/web/src/features/code/diff-model.ts+396 added
1+/**2+ * A commit's changed files as the diff draws them, worked out once by the3+ * same parser the drawing uses (`@pierre/diffs`' `parseDiffFromFile`), so4+ * the server's plain-text diff and the highlighted one the browser draws5+ * over it hold the same hunks, line for line: the swap moves nothing.6+ *7+ * Also here: each file's `+n −m`, which files start folded (an added or8+ * deleted file past `LONG_FILE` lines), the order a tree lists paths in,9+ * and a commit's stats split by path (the ask's territory, its tests, the10+ * rest), counted by rule, never by a model.11+ *12+ * No React and no DOM: the server's render and the browser's both read it.13+ */14+import { parseDiffFromFile } from "@pierre/diffs";15+import type { FileDiffMetadata } from "@pierre/diffs";16+import type { ChangedFile } from "@repo/protocol/domain/code";17+import { Option } from "effect";18+19+/** Past this many lines an added or deleted file starts folded. */20+export const LONG_FILE = 80;21+22+/** A file's diff, parsed from both its texts; none for a binary or unsent file. */23+export const fileDiffOf = (24+ file: ChangedFile25+): Option.Option<FileDiffMetadata> => {26+ if (27+ file.binary ||28+ (file.oldText === undefined && file.newText === undefined)29+ ) {30+ return Option.none();31+ }32+33+ const before =34+ file.status === "added" || file.oldText === undefined35+ ? null36+ : { contents: file.oldText, name: file.path };37+38+ const after =39+ file.status === "deleted" || file.newText === undefined40+ ? null41+ : { contents: file.newText, name: file.path };42+43+ const diff = parseDiffFromFile(before, after);44+45+ // Keyed by both blobs, so a file drawn once is never highlighted again.46+ diff.cacheKey = `diff:${file.before ?? "none"}:${file.after ?? "none"}`;47+48+ return Option.some(diff);49+};50+51+/** Each kind of change as the drawing names it. */52+const CHANGE_TYPES = {53+ added: "new",54+ deleted: "deleted",55+ modified: "change",56+} as const satisfies Record<ChangedFile["status"], FileDiffMetadata["type"]>;57+58+/** A diff with no lines: a header alone, for a file whose lines are not shown. */59+export const emptyDiffOf = (file: ChangedFile): FileDiffMetadata => ({60+ additionLines: [],61+ cacheKey: `diff:${file.before ?? "none"}:${file.after ?? "none"}`,62+ deletionLines: [],63+ hunks: [],64+ isPartial: false,65+ name: file.path,66+ splitLineCount: 0,67+ type: CHANGE_TYPES[file.status],68+ unifiedLineCount: 0,69+});70+71+/** Lines a file's diff adds and removes. */72+export interface Counts {73+ readonly additions: number;74+ readonly deletions: number;75+}76+77+const NONE: Counts = { additions: 0, deletions: 0 };78+79+/** What `diff` adds and removes, line by line. */80+export const countsOf = (diff: Option.Option<FileDiffMetadata>): Counts => {81+ if (Option.isNone(diff)) {82+ return NONE;83+ }84+85+ let additions = 0;86+ let deletions = 0;87+88+ for (const hunk of diff.value.hunks) {89+ additions += hunk.additionLines;90+ deletions += hunk.deletionLines;91+ }92+93+ return { additions, deletions };94+};95+96+/** A changed file with its parsed diff and counts. */97+export interface DrawnFile {98+ readonly file: ChangedFile;99+ readonly diff: Option.Option<FileDiffMetadata>;100+ readonly counts: Counts;101+ /** Whether it starts folded: added or deleted, past `LONG_FILE` lines. */102+ readonly folded: boolean;103+}104+105+/**106+ * The order a file tree lists paths in: segment by segment, a folder107+ * before a file at the same level, then by name.108+ */109+export const treeOrder = (left: string, right: string) => {110+ const a = left.split("/");111+ const b = right.split("/");112+113+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) {114+ const x = a[index] ?? "";115+ const y = b[index] ?? "";116+117+ if (x !== y) {118+ const xFolder = index < a.length - 1;119+ const yFolder = index < b.length - 1;120+121+ if (xFolder !== yFolder) {122+ return xFolder ? -1 : 1;123+ }124+125+ return x.localeCompare(y, "en");126+ }127+ }128+129+ return a.length - b.length;130+};131+132+/** `files` in tree order, each parsed and counted. */133+export const drawnFiles = (134+ files: readonly ChangedFile[]135+): readonly DrawnFile[] =>136+ files137+ .toSorted((a, b) => treeOrder(a.path, b.path))138+ .map((file) => {139+ const diff = fileDiffOf(file);140+ const counts = countsOf(diff);141+142+ return {143+ counts,144+ diff,145+ file,146+ folded:147+ file.status !== "modified" &&148+ counts.additions + counts.deletions > LONG_FILE,149+ };150+ });151+152+/** A test file, by its path: a test folder, or a `.test.` or `.spec.` name. */153+export const isTestPath = (path: string) =>154+ /(?:^|\/)(?:tests?|__tests__|spec)\//u.test(path) ||155+ /\.(?:test|spec)\.[^/]+$/u.test(path);156+157+/** A territory glob (`src/format/**`, `src/*.ts`) as a test on a path. */158+export const globTest = (glob: string): ((path: string) => boolean) => {159+ const pattern = glob160+ .replaceAll(/[.+^${}()|[\]\\]/gu, "\\$&")161+ .replaceAll("**/", "\u0000")162+ .replaceAll("**", "\u0001")163+ .replaceAll("*", "[^/]*")164+ .replaceAll("?", "[^/]")165+ .replaceAll("\u0000", "(?:.*/)?")166+ .replaceAll("\u0001", ".*");167+168+ // A folder named without a pattern covers what is inside it.169+ const whole = new RegExp(`^${pattern}(?:/.*)?$`, "u");170+171+ return (path) => whole.test(path);172+};173+174+/** One part of a commit's stats: what its paths add and remove. */175+export interface StatsPart extends Counts {176+ readonly label: "other" | "territory" | "tests";177+ readonly files: number;178+}179+180+/** A commit's stats: files, lines added and removed, and the parts by path. */181+export interface DiffStats extends Counts {182+ readonly files: number;183+ readonly parts: readonly StatsPart[];184+}185+186+/**187+ * The stats of `files`. With the ask's territory, a path it covers is the188+ * territory's, a test file the tests', anything else the rest; without189+ * one, a test file is the tests' and the rest is the rest. Empty parts are190+ * left out.191+ */192+export const statsOf = (193+ files: readonly DrawnFile[],194+ territory: readonly string[] = []195+): DiffStats => {196+ const inTerritory = territory.map(globTest);197+198+ const labelOf = (path: string): StatsPart["label"] => {199+ if (isTestPath(path)) {200+ return "tests";201+ }202+203+ return inTerritory.some((test) => test(path)) ? "territory" : "other";204+ };205+206+ const parts = (["territory", "tests", "other"] as const).flatMap(207+ (label): readonly StatsPart[] => {208+ const mine = files.filter(({ file }) => labelOf(file.path) === label);209+210+ return mine.length === 0211+ ? []212+ : [213+ {214+ additions: mine.reduce(215+ (sum, { counts }) => sum + counts.additions,216+ 0217+ ),218+ deletions: mine.reduce(219+ (sum, { counts }) => sum + counts.deletions,220+ 0221+ ),222+ files: mine.length,223+ label,224+ },225+ ];226+ }227+ );228+229+ return {230+ additions: parts.reduce((sum, part) => sum + part.additions, 0),231+ deletions: parts.reduce((sum, part) => sum + part.deletions, 0),232+ files: files.length,233+ parts,234+ };235+};236+237+/** One row of a plain diff, as unified or split draws it. */238+export type PlainRow =239+ | { readonly kind: "separator"; readonly lines: number }240+ | {241+ readonly kind: "context" | "addition" | "deletion";242+ readonly number: number;243+ readonly text: string;244+ };245+246+/** A line as the diff stores it, without its line ending. */247+const bare = (line: string | undefined) => (line ?? "").replace(/\r?\n$/u, "");248+249+/**250+ * `diff` as unified rows: before each hunk the unchanged lines it skips251+ * as one separator, then its lines (deletions before additions in a252+ * change, each numbered on its own side), and after the last hunk the253+ * unchanged lines left.254+ */255+export const unifiedRows = (diff: FileDiffMetadata): readonly PlainRow[] => {256+ const rows: PlainRow[] = [];257+ let lastAddition = 0;258+259+ for (const hunk of diff.hunks) {260+ if (hunk.collapsedBefore > 0) {261+ rows.push({ kind: "separator", lines: hunk.collapsedBefore });262+ }263+264+ for (const content of hunk.hunkContent) {265+ if (content.type === "context") {266+ for (let line = 0; line < content.lines; line += 1) {267+ const index = content.additionLineIndex + line;268+269+ rows.push({270+ kind: "context",271+ number: index + 1,272+ text: bare(diff.additionLines[index]),273+ });274+ }275+ } else {276+ for (let line = 0; line < content.deletions; line += 1) {277+ const index = content.deletionLineIndex + line;278+279+ rows.push({280+ kind: "deletion",281+ number: index + 1,282+ text: bare(diff.deletionLines[index]),283+ });284+ }285+286+ for (let line = 0; line < content.additions; line += 1) {287+ const index = content.additionLineIndex + line;288+289+ rows.push({290+ kind: "addition",291+ number: index + 1,292+ text: bare(diff.additionLines[index]),293+ });294+ }295+ }296+ }297+298+ lastAddition = hunk.additionStart - 1 + hunk.additionCount;299+ }300+301+ const after = diff.isPartial ? 0 : diff.additionLines.length - lastAddition;302+303+ if (diff.hunks.length > 0 && after > 0 && diff.type !== "deleted") {304+ rows.push({ kind: "separator", lines: after });305+ }306+307+ return rows;308+};309+310+/** One numbered line of a plain diff. */311+type Line = Extract<PlainRow, { readonly number: number }>;312+313+/** One row of a split diff: the old side and the new, either empty. */314+export type SplitRow =315+ | { readonly kind: "separator"; readonly lines: number }316+ | {317+ readonly kind: "pair";318+ readonly left?: Line;319+ readonly right?: Line;320+ };321+322+/**323+ * `diff` as split rows: a context line on both sides, and in a change the324+ * deletions beside the additions, row for row, the longer side's rest325+ * against nothing.326+ */327+export const splitRows = (diff: FileDiffMetadata): readonly SplitRow[] => {328+ const rows: SplitRow[] = [];329+ let lastAddition = 0;330+331+ for (const hunk of diff.hunks) {332+ if (hunk.collapsedBefore > 0) {333+ rows.push({ kind: "separator", lines: hunk.collapsedBefore });334+ }335+336+ for (const content of hunk.hunkContent) {337+ if (content.type === "context") {338+ for (let line = 0; line < content.lines; line += 1) {339+ const old = content.deletionLineIndex + line;340+ const index = content.additionLineIndex + line;341+342+ rows.push({343+ kind: "pair",344+ left: {345+ kind: "context",346+ number: old + 1,347+ text: bare(diff.deletionLines[old]),348+ },349+ right: {350+ kind: "context",351+ number: index + 1,352+ text: bare(diff.additionLines[index]),353+ },354+ });355+ }356+ } else {357+ const span = Math.max(content.deletions, content.additions);358+359+ for (let line = 0; line < span; line += 1) {360+ const old = content.deletionLineIndex + line;361+ const index = content.additionLineIndex + line;362+363+ const left: Line = {364+ kind: "deletion",365+ number: old + 1,366+ text: bare(diff.deletionLines[old]),367+ };368+369+ const right: Line = {370+ kind: "addition",371+ number: index + 1,372+ text: bare(diff.additionLines[index]),373+ };374+375+ if (line < content.deletions && line < content.additions) {376+ rows.push({ kind: "pair", left, right });377+ } else if (line < content.deletions) {378+ rows.push({ kind: "pair", left });379+ } else {380+ rows.push({ kind: "pair", right });381+ }382+ }383+ }384+ }385+386+ lastAddition = hunk.additionStart - 1 + hunk.additionCount;387+ }388+389+ const after = diff.isPartial ? 0 : diff.additionLines.length - lastAddition;390+391+ if (diff.hunks.length > 0 && after > 0 && diff.type !== "deleted") {392+ rows.push({ kind: "separator", lines: after });393+ }394+395+ return rows;396+};added:apps/web/src/features/code/diff-pane.tsx+92 added
1+/**2+ * Where a commit's diff scrolls: a box the height of the screen below the3+ * bars, which sticks under the toolbar once the page head has scrolled4+ * away. The diff scrolls inside it (Pierre's `CodeView` needs a scroller5+ * of its own to draw only what is in view), and its file headers stick at6+ * its top.7+ *8+ * Until the box has reached the toolbar, the box does not scroll: a wheel9+ * or a swipe over the diff moves the page instead, so the head scrolls10+ * away first and nothing traps the reader. Once stuck, it scrolls; at its11+ * top a further scroll up moves the page back. Without script it always12+ * scrolls.13+ */14+import { useEffect, useRef, useState } from "react";15+import type { ReactNode } from "react";16+17+/** The box's place: under the toolbar, as tall as the screen below it (and above a phone's bottom bar). */18+const PANE =19+ "group/pane sticky top-[5.1875rem] h-[calc(100dvh-5.1875rem-3.5rem-env(safe-area-inset-bottom))] scroll-mt-[5.1875rem] tablet:top-[5.4375rem] tablet:h-[calc(100dvh-5.4375rem)] tablet:scroll-mt-[5.4375rem] shell:top-[5.1875rem] shell:h-[calc(100dvh-5.1875rem)] shell:scroll-mt-[5.1875rem] -mt-6 -mb-16 flex min-h-0 flex-col";20+21+/** What a scroller inside the box puts on itself: all the box's height, scrolling only once the box is stuck. */22+export const PANE_SCROLLER =23+ "min-h-0 flex-1 overflow-auto overscroll-y-auto group-data-[stuck=false]/pane:overflow-y-hidden";24+25+/** Pixels from a computed length (`83px`); nothing, none. */26+const pixels = (length: string) => Number(/^-?[\d.]+/u.exec(length)?.[0] ?? 0);27+28+/**29+ * Follow whether `box` has reached its sticky place, read on every scroll30+ * (of main, or of the page below the shell's width), telling `stuck`; the31+ * returned function stops.32+ */33+const followStuck = (box: HTMLElement, stuck: (now: boolean) => void) => {34+ let frame = 0;35+36+ const read = () => {37+ frame = 0;38+ stuck(39+ box.getBoundingClientRect().top <=40+ pixels(globalThis.getComputedStyle(box).top) + 141+ );42+ };43+44+ const onScroll = () => {45+ if (frame === 0) {46+ frame = globalThis.requestAnimationFrame(read);47+ }48+ };49+50+ read();51+ document.addEventListener("scroll", onScroll, {52+ capture: true,53+ passive: true,54+ });55+ globalThis.addEventListener("resize", onScroll, { passive: true });56+57+ return () => {58+ globalThis.cancelAnimationFrame(frame);59+ document.removeEventListener("scroll", onScroll, { capture: true });60+ globalThis.removeEventListener("resize", onScroll);61+ };62+};63+64+/** Whether the box has reached its sticky place; none before the page runs. */65+const useStuck = () => {66+ const pane = useRef<HTMLDivElement>(null);67+ const [stuck, setStuck] = useState<boolean>();68+69+ useEffect(() => {70+ const box = pane.current;71+72+ return box === null ? undefined : followStuck(box, setStuck);73+ }, []);74+75+ return { pane, stuck };76+};77+78+export const DiffPane = ({ children }: { readonly children: ReactNode }) => {79+ const { pane, stuck } = useStuck();80+81+ return (82+ <div83+ className={PANE}84+ data-diff-pane=""85+ data-files=""86+ data-stuck={stuck}87+ ref={pane}88+ >89+ {children}90+ </div>91+ );92+};modified:apps/web/src/features/code/diff-view.tsx+322 added-47 removed
1 /**2- * A commit's changes, drawn by `@pierre/diffs`: one `MultiFileDiff` per3- * changed file, stacked, each from the file's old and new text, unified4- * unless `split`. (Pierre's virtualized `CodeView` draws nothing until it5- * mounts, so it cannot be seen rendered outside a browser; the stacked6- * views can, and a commit's diff is capped at 300 files.) A binary7- * file, or one whose text the platform did not send, says so in a line.8- * Each view's section is the file tree's jump target (`diffAnchor`).2+ * A set of changed files drawn by Pierre's `CodeView`: one scroller that3+ * draws only the files in view, each file's header sticky at its top4+ * (with a hairline only while it is stuck), unchanged runs folded into5+ * "N unmodified lines" bars, changed words marked inside changed lines,6+ * and highlighting done in the worker pool (`pool.tsx`). It sits in a7+ * `DiffPane`, over the server's `PlainDiff` (the same hunks, the same8+ * measures), which it replaces in place.9 *10+ * Unified diffs mark each line `+` or `-`, so a change reads without11+ * colour; split diffs mark the side with a bar. Each header has a chevron12+ * that folds the file; an added or deleted file past 80 lines starts13+ * folded. Lines can be selected, and the selection is kept in the address14+ * (`#diff-<path>:L4-L7`); an address naming a file (the tree, `J`/`K`)15+ * scrolls to its header.16+ *17+ * What a page adds, so the finish and waiver pages draw with it unedited:18+ * `annotations` (a row under a line, on one side), and per file a header19+ * slot (`slots[].header`, a "Mark read" button) and a status (`read`20+ * marks the header with a check, `refused` with the refused cross).21+ *22 * Only the browser loads this module (`client-code.tsx`).23 */12-import { MultiFileDiff } from "@pierre/diffs/react";13-import type { FileDiffOptions } from "@pierre/diffs/react";24+import type { CodeViewItem, DiffLineAnnotation } from "@pierre/diffs";25+import { CodeView } from "@pierre/diffs/react";26+import type { CodeViewHandle, CodeViewReactOptions } from "@pierre/diffs/react";27 import type { ChangedFile } from "@repo/protocol/domain/code";28+import { useLocation, useRouter } from "@tanstack/react-router";29+import { Option, Predicate } from "effect";30+import { Check, ChevronDown, OctagonX } from "lucide-react";31+import { useEffect, useMemo, useRef, useState } from "react";32+import type { ReactNode } from "react";33 16-import { diffAnchor } from "./paths.ts";34+import { drawnFiles, emptyDiffOf } from "./diff-model.ts";35+import type { DrawnFile } from "./diff-model.ts";36+import { PANE_SCROLLER } from "./diff-pane.tsx";37+import { diffLinesHash, parseDiffHash } from "./line-hash.ts";38 import { diffsOptions, registerCodeTheme } from "./pierre.ts";39+import { CodePool } from "./pool.tsx";40 41 registerCodeTheme();42 21-const optionsFor = (split: boolean): FileDiffOptions<undefined, undefined> => ({22- ...diffsOptions,23- diffStyle: split ? "split" : "unified",24- overflow: "wrap",25-});43+/** A row a page draws under one line of one file's diff, on one side. */44+export interface DiffAnnotation {45+ readonly path: string;46+ readonly line: number;47+ readonly side: "additions" | "deletions";48+ readonly render: () => ReactNode;49+}50 51+/** What a page adds to one file's header: a control, and the file's status. */52+export interface DiffFileSlot {53+ readonly path: string;54+ readonly header?: ReactNode;55+ readonly status?: "read" | "refused";56+}57+58 export interface DiffCodeProps {59 readonly files: readonly ChangedFile[];60 readonly split: boolean;61+ readonly annotations?: readonly DiffAnnotation[];62+ readonly slots?: readonly DiffFileSlot[];63+ /** The files folded now; each file's own default when absent. */64+ readonly folded?: ReadonlySet<string> | undefined;65+ /** A header's fold was pressed. */66+ readonly onFold?: ((path: string, folded: boolean) => void) | undefined;67 }68 32-/** Whether the platform sent the text of both sides it has. */33-const drawable = (file: ChangedFile) =>34- !file.binary && (file.oldText !== undefined || file.newText !== undefined);69+/**70+ * The header's hairline, only while it is stuck at the top (where the71+ * browser can tell); a plain one where it cannot. Each header also carries72+ * a hairline above it, parting one file from the next.73+ */74+const HEADER_CSS = `75+[data-diffs-header] { box-shadow: inset 0 1px var(--rule); container-type: scroll-state; }76+[data-diffs-header]::after { content: ""; position: absolute; inset-inline: 0; bottom: 0; height: 1px; background: transparent; }77+@container scroll-state(stuck: top) { [data-diffs-header]::after { background: var(--rule); } }78+@supports not (container-type: scroll-state) { [data-diffs-header]::after { background: var(--rule); } }79+`;80 36-export const DiffCode = ({ files, split }: DiffCodeProps) => {37- const options = optionsFor(split);81+const NO_ANNOTATIONS: readonly DiffAnnotation[] = [];82 39- return (40- <div className="flex min-w-0 flex-col gap-4" data-diff="pierre">41- {files.map((file) =>42- drawable(file) ? (43- <section44- aria-label={file.path}45- id={diffAnchor(file.path)}46- key={file.path}47- >48- <MultiFileDiff49- newFile={{ contents: file.newText ?? "", name: file.path }}50- oldFile={{ contents: file.oldText ?? "", name: file.path }}51- options={options}52- />53- </section>54- ) : (55- <section56- aria-label={file.path}57- className="border-rule text-mono border border-dashed px-4 py-3 font-mono"58- id={diffAnchor(file.path)}59- key={file.path}60- >61- {file.path}: {file.binary ? "a binary file" : "not shown"},{" "}62- {file.status}63- </section>83+const NO_SLOTS: readonly DiffFileSlot[] = [];84+85+/**86+ * An item's version: it changes whenever what the item draws does (folded87+ * or not, the lines its annotations sit on), so `CodeView` draws it again.88+ */89+const versionOf = (90+ folded: boolean,91+ annotations: readonly DiffLineAnnotation<DiffAnnotation>[]92+) => {93+ let hash = folded ? 1 : 0;94+95+ for (const { lineNumber, side } of annotations) {96+ hash =97+ (hash * 31 + lineNumber * 2 + (side === "additions" ? 1 : 0)) %98+ 2_147_483_647;99+ }100+101+ return hash * 2 + annotations.length;102+};103+104+/** One file as `CodeView` holds it; a binary or unsent file as a header with no lines. */105+const itemOf = (106+ drawn: DrawnFile,107+ folded: boolean,108+ annotations: readonly DiffAnnotation[]109+): CodeViewItem<DiffAnnotation> => {110+ const mine = annotations.flatMap((annotation) =>111+ annotation.path === drawn.file.path112+ ? [113+ {114+ lineNumber: annotation.line,115+ metadata: annotation,116+ side: annotation.side,117+ } satisfies DiffLineAnnotation<DiffAnnotation>,118+ ]119+ : []120+ );121+122+ return {123+ annotations: mine,124+ collapsed: folded,125+ fileDiff: Option.getOrElse(drawn.diff, () => emptyDiffOf(drawn.file)),126+ id: drawn.file.path,127+ type: "diff",128+ version: versionOf(folded, mine),129+ };130+};131+132+/** The address's fragment, handed up as it changes; only inside a router. */133+const HashFollower = ({134+ onHash,135+}: {136+ readonly onHash: (hash: string) => void;137+}) => {138+ const hash = useLocation({ select: (location) => location.hash });139+140+ useEffect(() => {141+ onHash(hash);142+ }, [hash, onHash]);143+144+ return null;145+};146+147+/** Scroll the pane into place, then the file's header to its top. */148+const reveal = (149+ handle: CodeViewHandle<DiffAnnotation, undefined> | null,150+ container: HTMLElement | null,151+ path: string152+) => {153+ container?.closest("[data-diff-pane]")?.scrollIntoView({ block: "start" });154+ handle?.scrollTo({ align: "start", id: path, type: "item" });155+};156+157+export const DiffCode = ({158+ annotations = NO_ANNOTATIONS,159+ files,160+ folded,161+ onFold,162+ slots = NO_SLOTS,163+ split,164+}: DiffCodeProps) => {165+ const handle = useRef<CodeViewHandle<DiffAnnotation, undefined>>(null);166+ const container = useRef<HTMLDivElement>(null);167+ const [hash, setHash] = useState("");168+169+ const drawn = useMemo(() => drawnFiles(files), [files]);170+171+ const items = useMemo(172+ () =>173+ drawn.map((file) =>174+ itemOf(175+ file,176+ folded === undefined ? file.folded : folded.has(file.file.path),177+ annotations178 )65- )}66- </div>179+ ),180+ [annotations, drawn, folded]181 );182+183+ const byPath = useMemo(184+ () =>185+ new Map<string, DrawnFile>(drawn.map((file) => [file.file.path, file])),186+ [drawn]187+ );188+189+ const slotOf = (path: string) => slots.find((slot) => slot.path === path);190+191+ // An address naming a file scrolls to it, and its lines are selected.192+ useEffect(() => {193+ const named = parseDiffHash(hash);194+195+ if (Option.isNone(named) || !byPath.has(named.value.path)) {196+ return;197+ }198+199+ const { lines, path } = named.value;200+201+ if (folded?.has(path) === true) {202+ onFold?.(path, false);203+ }204+205+ reveal(handle.current, container.current, path);206+207+ if (Option.isSome(lines)) {208+ handle.current?.setSelectedLines({209+ id: path,210+ range: {211+ end: lines.value.end,212+ side: lines.value.side,213+ start: lines.value.start,214+ },215+ });216+ handle.current?.scrollTo({217+ align: "center",218+ id: path,219+ lineNumber: lines.value.start,220+ side: lines.value.side,221+ type: "line",222+ });223+ }224+ }, [byPath, folded, hash, onFold]);225+226+ const options = useMemo(227+ (): CodeViewReactOptions<DiffAnnotation, undefined> => ({228+ ...diffsOptions,229+ diffIndicators: split ? "bars" : "classic",230+ diffStyle: split ? "split" : "unified",231+ enableLineSelection: true,232+ hunkSeparators: "line-info",233+ layout: { gap: 0, paddingBottom: 16, paddingTop: 0 },234+ lineDiffType: "word-line",235+ lineHoverHighlight: "both",236+ overflow: "scroll",237+ stickyHeaders: true,238+ unsafeCSS: HEADER_CSS,239+ }),240+ [split]241+ );242+243+ // A view drawn with no router around it (its own test) follows no address.244+ const router = useRouter({ warn: false });245+246+ return (247+ <CodePool>248+ {Predicate.isNotNullish(router) ? (249+ <HashFollower onHash={setHash} />250+ ) : null}251+ <div className="contents" data-diff="pierre">252+ <CodeView<DiffAnnotation>253+ className={PANE_SCROLLER}254+ containerRef={container}255+ items={items}256+ onSelectedLinesChange={(selection) => {257+ const url = `${globalThis.location.pathname}${globalThis.location.search}`;258+259+ globalThis.history.replaceState(260+ globalThis.history.state,261+ "",262+ selection === null263+ ? url264+ : `${url}#${diffLinesHash({265+ end: Math.max(selection.range.start, selection.range.end),266+ path: selection.id,267+ side: selection.range.side ?? "additions",268+ start: Math.min(selection.range.start, selection.range.end),269+ })}`270+ );271+ }}272+ options={options}273+ ref={handle}274+ renderAnnotation={(annotation) => annotation.metadata?.render()}275+ renderHeaderMetadata={(item) => {276+ const file = byPath.get(item.id);277+ const slot = slotOf(item.id);278+279+ return (280+ // Pierre prints the counts itself; what it cannot say is here.281+ <span className="flex items-center gap-3 font-sans">282+ {file === undefined || Option.isSome(file.diff) ? null : (283+ <span className="text-muted-foreground">284+ {file.file.binary ? "binary" : "not shown"}285+ </span>286+ )}287+ {slot?.header}288+ </span>289+ );290+ }}291+ renderHeaderPrefix={(item) => {292+ const closed = item.collapsed === true;293+294+ return (295+ <button296+ aria-expanded={!closed}297+ aria-label={`${closed ? "Unfold" : "Fold"} ${item.id}`}298+ className="text-muted-foreground hover:text-foreground -ml-1 flex size-6 items-center justify-center"299+ onClick={() => {300+ onFold?.(item.id, !closed);301+ }}302+ type="button"303+ >304+ <ChevronDown305+ aria-hidden="true"306+ className={`size-4 transition-transform duration-150 ${closed ? "-rotate-90" : ""}`}307+ strokeWidth={1.75}308+ />309+ </button>310+ );311+ }}312+ renderHeaderFilenameSuffix={(item) => {313+ const status = slotOf(item.id)?.status;314+315+ if (status === "refused") {316+ return (317+ <span className="text-refused flex items-center gap-1 font-sans">318+ <OctagonX319+ aria-hidden="true"320+ className="size-3.5"321+ strokeWidth={1.75}322+ />323+ <span className="sr-only">refused here</span>324+ </span>325+ );326+ }327+328+ return status === "read" ? (329+ <span className="text-muted-foreground flex items-center gap-1 font-sans">330+ <Check331+ aria-hidden="true"332+ className="size-3.5"333+ strokeWidth={1.75}334+ />335+ <span className="sr-only">read</span>336+ </span>337+ ) : null;338+ }}339+ />340+ </div>341+ </CodePool>342+ );343 };344 345 // `React.lazy` takes a module's default export.346 export default DiffCode;added:apps/web/src/features/code/file-facts.tsx+82 added
1+/**2+ * The inspector's "This file": the path, the file in words (lines, size,3+ * language), the landing that last touched it (ask and answer first, the4+ * commit second), and where to take it: raw, a permalink, a copy, its5+ * history. A file's page and its why page show the same block.6+ */7+import type { CommitView, FileView } from "@repo/protocol/domain/code";8+import type { ProjectName } from "@repo/protocol/ids";9+import { Option } from "effect";10+import type { DateTime } from "effect";11+12+import { FactBlock } from "../shared/facts.tsx";13+import { AppLink } from "../shared/link.tsx";14+import { LandingWords } from "../why/band.tsx";15+import { CopyButton } from "./copy.tsx";16+import { fileWords } from "./file-header.tsx";17+import { blobHref, commitsHref, rawHref } from "./paths.ts";18+19+const LINK = "decoration-rule underline hover:decoration-current";20+21+export const FileFacts = ({22+ file,23+ last,24+ now,25+ project,26+ rev,27+}: {28+ readonly file: FileView;29+ /** The commit that last changed the file, with its landing; none when the read found none. */30+ readonly last?: CommitView | undefined;31+ readonly now: DateTime.Utc;32+ readonly project: ProjectName;33+ readonly rev: string;34+}) => (35+ <>36+ <FactBlock label="Path">37+ <p className="text-mono font-mono [overflow-wrap:anywhere]">38+ {file.path}39+ </p>40+ <p className="text-ui text-muted-foreground">41+ {fileWords(file).join(" · ")}42+ </p>43+ </FactBlock>44+ <FactBlock label="Last changed by">45+ {last === undefined ? (46+ <p className="text-ui text-muted-foreground">Not known.</p>47+ ) : (48+ <p className="text-ui [overflow-wrap:anywhere]" data-last={last.sha}>49+ <LandingWords50+ commit={Option.some(last)}51+ landing={Option.fromUndefinedOr(last.landing)}52+ now={now}53+ project={project}54+ sha={last.sha}55+ />56+ </p>57+ )}58+ <AppLink59+ className={`text-ui ${LINK}`}60+ to={commitsHref(project, rev, { path: file.path })}61+ >62+ History of this file63+ </AppLink>64+ </FactBlock>65+ <FactBlock label="Take it">66+ <nav67+ aria-label="Take the file"68+ className="text-ui flex flex-wrap items-center gap-x-4 gap-y-1"69+ >70+ <a className={LINK} href={rawHref(project, file.at, file.path)}>71+ Raw72+ </a>73+ <AppLink className={LINK} to={blobHref(project, file.at, file.path)}>74+ Permalink75+ </AppLink>76+ {file.text === undefined ? null : (77+ <CopyButton label="Copy the file" text={file.text} />78+ )}79+ </nav>80+ </FactBlock>81+ </>82+);added:apps/web/src/features/code/file-header.tsx+329 added
1+/**2+ * The code pages' file header: the toolbar that stays under the context3+ * bar while the code scrolls. Left to right: the Files button (below the4+ * shell's width, where the tree is not in a rail), the path as a trail of5+ * links with a button that copies it, the file's size in words ("12 lines6+ * · 493 bytes · TypeScript"), the Code | Why toggle (one page, two modes,7+ * each its own address), then Raw, Permalink (`y`) and Copy.8+ *9+ * Also here: the `y` key, which rewrites the address to the page at its10+ * commit, and the words a file's facts are said in.11+ */12+import type { FileView } from "@repo/protocol/domain/code";13+import type { ProjectName } from "@repo/protocol/ids";14+import { Check, Copy, Link2 } from "lucide-react";15+import { Fragment, useEffect } from "react";16+import type { ReactNode } from "react";17+18+import { buttonVariants } from "@/components/ui/button";19+20+import { useCopy } from "../shared/copy-action.tsx";21+import { AppLink } from "../shared/link.tsx";22+import { CopyButton } from "./copy.tsx";23+import {24+ ancestorsOf,25+ blobHref,26+ rawHref,27+ sizeInWords,28+ treeHref,29+ whyHref,30+} from "./paths.ts";31+32+/** A text's lines, without the empty one after its last newline. */33+export const linesOf = (text: string): readonly string[] => {34+ const lines = text.split("\n");35+36+ return lines.at(-1) === "" ? lines.slice(0, -1) : lines;37+};38+39+/** The language a file is written in, by its name; none for one this list does not know. */40+const LANGUAGES: readonly (readonly [RegExp, string])[] = [41+ [/\.(?:c|m)?tsx?$/u, "TypeScript"],42+ [/\.(?:c|m)?jsx?$/u, "JavaScript"],43+ [/\.json$/u, "JSON"],44+ [/\.(?:md|markdown|mdown)$/u, "Markdown"],45+ [/\.ya?ml$/u, "YAML"],46+ [/\.toml$/u, "TOML"],47+ [/\.css$/u, "CSS"],48+ [/\.html?$/u, "HTML"],49+ [/\.rs$/u, "Rust"],50+ [/\.go$/u, "Go"],51+ [/\.py$/u, "Python"],52+ [/\.(?:sh|bash|zsh)$/u, "Shell"],53+ [/(?:^|\/)Dockerfile$/u, "Dockerfile"],54+ [/\.sql$/u, "SQL"],55+ [/\.rb$/u, "Ruby"],56+ [/\.java$/u, "Java"],57+ [/\.kt$/u, "Kotlin"],58+ [/\.swift$/u, "Swift"],59+ [/\.c$|\.h$/u, "C"],60+ [/\.(?:cc|cpp|hpp)$/u, "C++"],61+];62+63+export const languageOf = (path: string) =>64+ LANGUAGES.find(([pattern]) => pattern.test(path))?.[1];65+66+/** A file in words: its lines, its size, its language. */67+export const fileWords = (file: FileView): readonly string[] => [68+ ...(file.text === undefined69+ ? []70+ : [71+ `${linesOf(file.text).length.toLocaleString("en")} ${72+ linesOf(file.text).length === 1 ? "line" : "lines"73+ }`,74+ ]),75+ sizeInWords(file.size),76+ ...(file.binary ? ["binary"] : []),77+ ...(languageOf(file.path) === undefined ? [] : [languageOf(file.path) ?? ""]),78+];79+80+/** `y` rewrites the address to the page at its commit, keeping the line anchor. */81+export const PermalinkKey = ({ href }: { readonly href: string }) => {82+ useEffect(() => {83+ const onKey = (event: KeyboardEvent) => {84+ const [target] = event.composedPath();85+86+ const typing =87+ target instanceof HTMLElement &&88+ (target.isContentEditable ||89+ target.closest("input, select, textarea, [role=combobox]") !== null);90+91+ if (92+ event.key === "y" &&93+ !typing &&94+ !event.metaKey &&95+ !event.ctrlKey &&96+ !event.altKey97+ ) {98+ globalThis.history.replaceState(99+ globalThis.history.state,100+ "",101+ `${href}${globalThis.location.search}${globalThis.location.hash}`102+ );103+ }104+ };105+106+ globalThis.addEventListener("keydown", onKey);107+108+ return () => {109+ globalThis.removeEventListener("keydown", onKey);110+ };111+ }, [href]);112+113+ return null;114+};115+116+const CRUMB =117+ "text-muted-foreground hover:text-foreground min-w-0 truncate no-underline transition-colors duration-[120ms]";118+119+/** A button that copies `text` with only its mark showing; its name says what it copies. */120+const CopyMark = ({121+ label,122+ text,123+}: {124+ readonly label: string;125+ readonly text: string;126+}) => {127+ const { copied, copy } = useCopy(text);128+129+ return (130+ <button131+ aria-label={132+ copied ? `Copied ${label.toLowerCase().replace(/^copy /u, "")}` : label133+ }134+ className="text-muted-foreground hover:text-foreground hover:bg-surface flex size-7 shrink-0 cursor-pointer items-center justify-center"135+ onClick={copy}136+ title={label}137+ type="button"138+ >139+ {copied ? (140+ <Check aria-hidden="true" className="size-3.5" strokeWidth={1.75} />141+ ) : (142+ <Copy aria-hidden="true" className="size-3.5" strokeWidth={1.75} />143+ )}144+ </button>145+ );146+};147+148+/** The path as links: the project, each folder at `rev`, then the name itself. */149+export const PathTrail = ({150+ path,151+ project,152+ rev,153+}: {154+ readonly path: string | undefined;155+ readonly project: ProjectName;156+ readonly rev: string;157+}) => {158+ const here = path === undefined || path === "" ? undefined : path;159+ const name = here?.split("/").at(-1);160+161+ return (162+ <nav163+ aria-label="Path"164+ className="flex min-w-0 items-center gap-1"165+ data-slot="breadcrumb"166+ >167+ <ol className="text-mono flex min-w-0 items-center gap-1 font-mono">168+ {/* On a phone the toolbar has room for the name alone: the folders169+ above it are the Files sheet's. */}170+ <li171+ className={`${here === undefined ? "flex" : "tablet:flex hidden"} min-w-0 shrink-0 items-center`}172+ >173+ {here === undefined ? (174+ <span aria-current="page" className="text-foreground font-medium">175+ {project}176+ </span>177+ ) : (178+ <AppLink className={CRUMB} to={treeHref(project, rev)}>179+ {project}180+ </AppLink>181+ )}182+ </li>183+ {here === undefined184+ ? null185+ : ancestorsOf(here).map((folder) => (186+ <Fragment key={folder}>187+ <li188+ aria-hidden="true"189+ className="text-muted-foreground tablet:block hidden"190+ >191+ /192+ </li>193+ <li className="tablet:flex hidden min-w-0 items-center">194+ <AppLink195+ className={CRUMB}196+ to={treeHref(project, rev, folder)}197+ >198+ {folder.split("/").at(-1)}199+ </AppLink>200+ </li>201+ </Fragment>202+ ))}203+ {name === undefined ? null : (204+ <>205+ <li206+ aria-hidden="true"207+ className="text-muted-foreground tablet:block hidden"208+ >209+ /210+ </li>211+ <li className="flex min-w-0 items-center">212+ <span213+ aria-current="page"214+ className="text-foreground min-w-0 truncate font-medium"215+ title={here}216+ >217+ {name}218+ </span>219+ </li>220+ </>221+ )}222+ </ol>223+ {here === undefined ? null : <CopyMark label="Copy path" text={here} />}224+ </nav>225+ );226+};227+228+const SEGMENT =229+ "text-ui hover:bg-surface aria-[current]:bg-foreground aria-[current]:text-background aria-[current]:hover:bg-foreground flex h-7 items-center px-2.5 font-medium no-underline transition-colors duration-150";230+231+/** Code | Why: the file, or why each of its lines is there; one page, two addresses. */232+export const ModeToggle = ({233+ mode,234+ path,235+ project,236+ rev,237+}: {238+ readonly mode: "code" | "why";239+ readonly path: string;240+ readonly project: ProjectName;241+ readonly rev: string;242+}) => (243+ <nav aria-label="Mode" className="border-input flex shrink-0 border">244+ <AppLink245+ aria-current={mode === "code" ? "page" : undefined}246+ className={SEGMENT}247+ to={blobHref(project, rev, path)}248+ >249+ Code250+ </AppLink>251+ <AppLink252+ aria-current={mode === "why" ? "page" : undefined}253+ className={SEGMENT}254+ to={whyHref(project, rev, path)}255+ >256+ Why257+ </AppLink>258+ </nav>259+);260+261+const TOOL = buttonVariants({262+ className: "no-underline",263+ size: "sm",264+ variant: "ghost",265+});266+267+/** The file header, as the page's toolbar. */268+export const FileHeader = ({269+ file,270+ files,271+ mode,272+ path,273+ project,274+ rev,275+}: {276+ readonly project: ProjectName;277+ readonly rev: string;278+ /** The folder or file the page is about; the root when absent. */279+ readonly path?: string | undefined;280+ /** Code or Why, on a file's page; nothing on a folder's. */281+ readonly mode?: "code" | "why";282+ /** The file, read: its size in words, its bytes and its text to copy. */283+ readonly file?: FileView;284+ /** The Files button, below the shell's width. */285+ readonly files?: ReactNode;286+}) => (287+ <>288+ {files === undefined ? null : (289+ <div className="shell:hidden flex shrink-0">{files}</div>290+ )}291+ <div className="flex min-w-0 flex-1 items-center gap-3">292+ <PathTrail path={path} project={project} rev={rev} />293+ {file === undefined ? null : (294+ <p className="text-ui text-muted-foreground diffsplit:block hidden shrink-0 truncate tabular-nums">295+ {fileWords(file).join(" · ")}296+ </p>297+ )}298+ </div>299+ {mode === undefined || path === undefined ? null : (300+ <ModeToggle mode={mode} path={path} project={project} rev={rev} />301+ )}302+ {file === undefined ? null : (303+ <nav304+ aria-label="File"305+ className="shell:flex hidden shrink-0 items-center gap-0.5"306+ data-toolbar="file"307+ >308+ <a className={TOOL} href={rawHref(project, file.at, file.path)}>309+ Raw310+ </a>311+ <AppLink312+ className={TOOL}313+ title="Permalink (y)"314+ to={(mode === "why" ? whyHref : blobHref)(315+ project,316+ file.at,317+ file.path318+ )}319+ >320+ <Link2 aria-hidden="true" strokeWidth={1.75} />321+ Permalink322+ </AppLink>323+ {file.text === undefined ? null : (324+ <CopyButton label="Copy" text={file.text} />325+ )}326+ </nav>327+ )}328+ </>329+);added:apps/web/src/features/code/file-keys.ts+95 added
1+/**2+ * `J` and `K` on the code pages: the next or the previous file, from the3+ * one the page shows, in the tree's order (a file's page and its why page4+ * move to the next file's; a commit's page scrolls its diff to the next5+ * file's header). The keys mean what the shell's keys dialog says6+ * (`intentOf`), and the switch that turns the single keys off turns these7+ * off too. No key acts while focus is in a field or the tree's filter.8+ */9+import { useEffect, useRef } from "react";10+11+import { intentOf, useKeys } from "../shared/keys.tsx";12+13+/** Whether `event` was pressed inside something that takes typing. */14+const typing = (event: KeyboardEvent) => {15+ const [target] = event.composedPath();16+17+ return (18+ target instanceof HTMLElement &&19+ (target.isContentEditable ||20+ target.closest(21+ "input, textarea, select, [role=combobox], [role=searchbox], [role=textbox], [data-keys-off]"22+ ) !== null)23+ );24+};25+26+/** The file `step` away from `current` in `paths`; the first or last when the page shows none of them. */27+export const stepFrom = (28+ paths: readonly string[],29+ current: string | undefined,30+ step: 1 | -131+): string | undefined => {32+ const at = current === undefined ? -1 : paths.indexOf(current);33+34+ if (at === -1) {35+ return step === 1 ? paths[0] : paths.at(-1);36+ }37+38+ return paths[Math.min(Math.max(at + step, 0), paths.length - 1)];39+};40+41+export const useCodeFileKeys = (42+ paths: readonly string[],43+ current: string | undefined,44+ onMove: (path: string) => void45+) => {46+ const on = useKeys()?.on ?? true;47+ const latest = useRef({ current, on, onMove, paths });48+49+ useEffect(() => {50+ latest.current = { current, on, onMove, paths };51+ });52+53+ useEffect(() => {54+ const onKey = (event: KeyboardEvent) => {55+ const now = latest.current;56+57+ if (event.defaultPrevented || event.repeat) {58+ return;59+ }60+61+ const intent = intentOf(62+ {63+ altKey: event.altKey,64+ ctrlKey: event.ctrlKey,65+ inField: typing(event),66+ key: event.key,67+ metaKey: event.metaKey,68+ },69+ now.on70+ );71+72+ if (intent?.kind !== "nextFile" && intent?.kind !== "previousFile") {73+ return;74+ }75+76+ const next = stepFrom(77+ now.paths,78+ now.current,79+ intent.kind === "nextFile" ? 1 : -180+ );81+82+ if (next !== undefined && next !== now.current) {83+ event.preventDefault();84+ now.onMove(next);85+ }86+ };87+88+ // Before the tree's own keys, which take letters to find a row.89+ document.addEventListener("keydown", onKey, { capture: true });90+91+ return () => {92+ document.removeEventListener("keydown", onKey, { capture: true });93+ };94+ }, []);95+};added:apps/web/src/features/code/headers.ts+7 added
1+/**2+ * Whether a revision names one commit for good: a whole 40-hex id. A code3+ * page at one never changes, so it is cached for good4+ * (`routes/$project/tree/-headers.ts`); a page at `main` or a tag moves5+ * with the next landing.6+ */7+export const isCommitId = (rev: string) => /^[0-9a-f]{40}$/u.test(rev);modified:apps/web/src/features/code/line-hash.ts+56 added
33 unmodified lines34 35 /** The anchor for `range`: `#L<n>` for one line, `#L<a>-L<b>` for more. */36 export const lineHash = ({ end, start }: LineRange): string =>37 start === end ? `#L${start}` : `#L${start}-L${end}`;38+39+/** Lines on one side of one file's diff: the new side unless `deletions`. */40+export interface DiffLines extends LineRange {41+ readonly path: string;42+ readonly side: "additions" | "deletions";43+}44+45+const DIFF_ANCHOR =46+ /^#?diff-(?<path>[^:]+)(?::(?<lines>[DL]\d+(?:-[DL]\d+)?))?$/u;47+48+const decodePath = Option.liftThrowable(decodeURIComponent);49+50+/**51+ * The file a commit page's hash names (`#diff-src%2Fparse.ts`), and its52+ * lines when it names some (`…:L4-L7` on the new side, `…:D4` on the old).53+ */54+export const parseDiffHash = (55+ hash: string56+): Option.Option<{57+ readonly path: string;58+ readonly lines: Option.Option<DiffLines>;59+}> => {60+ const groups = DIFF_ANCHOR.exec(hash)?.groups;61+62+ return Option.flatMap(Option.fromUndefinedOr(groups?.path), (encoded) =>63+ Option.map(decodePath(encoded), (path) => ({64+ lines: Option.map(65+ Option.flatMap(Option.fromUndefinedOr(groups?.lines), (lines) =>66+ parseLineHash(lines.replaceAll("D", "L"))67+ ),68+ (range): DiffLines => ({69+ ...range,70+ path,71+ side:72+ groups?.lines?.startsWith("D") === true ? "deletions" : "additions",73+ })74+ ),75+ path,76+ }))77+ );78+};79+80+/** The hash naming `lines` of a file's diff, without the `#`. */81+export const diffLinesHash = ({82+ end,83+ path,84+ side,85+ start,86+}: DiffLines): string => {87+ const mark = side === "deletions" ? "D" : "L";88+89+ const lines =90+ start === end ? `${mark}${start}` : `${mark}${start}-${mark}${end}`;91+92+ return `diff-${encodeURIComponent(path)}:${lines}`;93+};modified:apps/web/src/features/code/log-view.tsx+201 added-128 removed
1 /**2- * The log from a revision along first parents, newest first, grouped by3- * the day each commit was committed (UTC), a page at a time. A landing4- * reads as the platform recorded it (`CommitView.landing`, never a5- * trailer): its ask, its author, its credit and its verdict. A commit with6- * no landing came in with the history the project adopted, and says so.2+ * The landings: the log from a revision along first parents, newest first,3+ * a page at a time, under a sticky header per day (UTC). One row per4+ * commit: its subject, then what it did (the ask it answered or opened),5+ * its credit in one line, and "held back" with its lock when sealed checks6+ * judged it; at the right its short id over its age. A commit the platform7+ * did not land came in with the history the project adopted, and says so.8+ *9+ * The toolbar filters the page: every commit, the answers, or the asks'10+ * openings. A landing reads as the platform recorded it11+ * (`CommitView.landing`), never from a trailer.12 */13 import type { CommitView } from "@repo/protocol/domain/code";9-import { Outcome } from "@repo/protocol/domain/outcome";14 import type { ProjectName, RepoPath } from "@repo/protocol/ids";15 import { DateTime, Option } from "effect";16+import { LockKeyhole } from "lucide-react";17+import type { ReactNode } from "react";18 13-import { ProjectNav } from "../project/project-nav.tsx";14-import { ID, LINK } from "../shared/classes.ts";15-import { CreditTrailers } from "../shared/credits.tsx";19+import { CompactCredit } from "../shared/credits.tsx";20 import { EmptyState } from "../shared/empty.tsx";17-import { HandleLink } from "../shared/handle.tsx";18-import { PageShell } from "../shared/layout.tsx";21+import { AppLink } from "../shared/link.tsx";22 import { askPath } from "../shared/paths.ts";23+import { MetaCode, MetaLine, Row, RowGroup } from "../shared/row.tsx";24+import { Workspace } from "../shared/shell/workspace.tsx";25 import { When } from "../shared/time.tsx";26 import { askOf } from "../why/rows.ts";27 import { LOG_PAGE } from "./log-page.ts";28 import { Pager } from "./pager.tsx";29 import { blobHref, commitHref, commitsHref, shortSha } from "./paths.ts";30 import { revLabel } from "./rev.ts";31 27-const isLanded = Outcome.isAnyOf(["Landed"]);32+/** Which commits the page shows: all of them, the answers, or the asks' openings. */33+export type LogShow = "all" | "answers" | "openings";34 29-/** A day as its heading says it: "October 6, 2026". */35+/** A day as its header says it: "October 6, 2026". */36 const dayWords = new Intl.DateTimeFormat("en", {37 dateStyle: "long",38 timeZone: "UTC",39 });15 unmodified lines55 56 return days;57 };58 59+/** What a commit did: the ask it answered or opened, when it is a landing that did. */60+const linkedOf = (commit: CommitView) =>61+ commit.landing === undefined62+ ? undefined63+ : Option.getOrUndefined(askOf(commit.landing));64+65+/** Whether `commit` belongs on the page `show` asks for. */66+export const shows = (show: LogShow, commit: CommitView) => {67+ if (show === "all") {68+ return true;69+ }70+71+ const linked = linkedOf(commit);72+73+ return show === "openings"74+ ? linked?.kind === "opened"75+ : linked?.kind === "answers";76+};77+78+const LINK = "decoration-rule underline hover:decoration-current";79+80+/** A part of a row's second line that holds links: above the row's own link, so it can be pressed. */81+const Raised = ({ children }: { readonly children: ReactNode }) => (82+ <span className="relative z-[1]">{children}</span>83+);84+85+/** One commit's row. */53-const Row = ({86+const CommitRow = ({87 commit,88 now,89 project,90 }: {1 unmodified line92 readonly now: DateTime.Utc;93 readonly project: ProjectName;94 }) => {95 const { landing } = commit;96+ const linked = linkedOf(commit);97 64- const linked =65- landing === undefined ? undefined : Option.getOrUndefined(askOf(landing));66-98 return (68- <li69- className="border-rule flex flex-col gap-2 border-t py-3"70- data-commit={commit.sha}71- >72- <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">73- <a74- className={`${LINK} font-medium [overflow-wrap:anywhere]`}75- href={commitHref(project, commit.sha)}76- >77- {commit.subject === "" ? "(no subject)" : commit.subject}78- </a>79- <p className="text-muted-foreground flex items-baseline gap-2 text-sm">80- <a className={`${ID} ${LINK}`} href={commitHref(project, commit.sha)}>81- {shortSha(commit.sha)}82- </a>83- <span aria-hidden="true">·</span>84- <When at={commit.committer.at} now={now} />85- </p>86- </div>87- {landing === undefined ? (88- <p className="text-muted-foreground text-sm">89- {commit.author.name}, before adoption90- </p>91- ) : (92- <div className="flex flex-col gap-2 text-sm">93- <p className="flex flex-wrap gap-x-4 gap-y-1">94- {linked === undefined ? null : (95- <span>96- <span className="text-muted-foreground text-xs font-medium">97- {linked.kind === "opened" ? "Opened" : "Ask"}98- </span>{" "}99- <a100- className={`${ID} ${LINK}`}101- href={askPath(project, linked.ask)}99+ <Row100+ action={101+ <span className="flex w-20 flex-col items-end leading-5">102+ <MetaCode>{shortSha(commit.sha)}</MetaCode>103+ <span className="text-label text-muted-foreground tabular-nums">104+ <When at={commit.committer.at} now={now} />105+ </span>106+ </span>107+ }108+ data={{ "data-commit": commit.sha }}109+ href={commitHref(project, commit.sha)}110+ id={commit.sha}111+ meta={112+ landing === undefined ? (113+ <MetaLine parts={[commit.author.name, "before adoption"]} />114+ ) : (115+ <MetaLine116+ parts={[117+ linked === undefined ? undefined : (118+ <Raised key="ask">119+ {linked.kind === "opened" ? "Opened " : null}120+ <AppLink121+ className={`text-mono font-mono ${LINK}`}122+ to={askPath(project, linked.ask)}123+ >124+ {linked.ask}125+ </AppLink>126+ </Raised>127+ ),128+ <Raised key="credit">129+ <CompactCredit credits={landing.credits} />130+ </Raised>,131+ landing.heldBackTrailer === undefined ? undefined : (132+ <span133+ className="text-sealed inline-flex items-center gap-1"134+ key="held"135+ title={landing.heldBackTrailer}136 >103- {linked.ask}104- </a>105- </span>106- )}107- <span>108- <span className="text-muted-foreground text-xs font-medium">109- Author110- </span>{" "}111- <HandleLink handle={landing.author} />112- </span>113- {landing.verdict === undefined ? null : (114- <span data-outcome={landing.verdict.outcome._tag}>115- <span className="text-muted-foreground text-xs font-medium">116- Verdict117- </span>{" "}118- {isLanded(landing.verdict.outcome)119- ? "checked and landed"120- : landing.verdict.outcome._tag}121- </span>122- )}123- </p>124- <CreditTrailers125- assisted={landing.assisted}126- credits={landing.credits}127- {...(landing.heldBackTrailer === undefined128- ? {}129- : { heldBack: landing.heldBackTrailer })}137+ <LockKeyhole138+ aria-hidden="true"139+ className="size-3.5"140+ strokeWidth={1.75}141+ />142+ held back143+ </span>144+ ),145+ ]}146 />131- </div>132- )}133- </li>147+ )148+ }149+ title={commit.subject === "" ? "(no subject)" : commit.subject}150+ />151 );152 };153 154 /**5 unmodified lines160 */161 const newerPage = (from: number, path: RepoPath | undefined) =>162 path === undefined ? { from: Math.max(0, from - LOG_PAGE) } : { path };163 147-export const LogView = ({148- commits,149- from,150- next,151- now,152- path,153- project,154- rev,155-}: {164+const FILTERS = [165+ { label: "All", show: "all" },166+ { label: "Answers", show: "answers" },167+ { label: "Ask openings", show: "openings" },168+] as const satisfies readonly {169+ readonly label: string;170+ readonly show: LogShow;171+}[];172+173+const FILTER =174+ "text-ui text-muted-foreground hover:text-foreground aria-[current]:text-foreground flex h-10 items-center border-b-2 border-transparent px-1 no-underline aria-[current]:border-current aria-[current]:font-semibold";175+176+/** The page's title: the landings at the revision, or one path's history. */177+const titleOf = (path: RepoPath | undefined, rev: string) => {178+ if (path !== undefined) {179+ return `History of ${path}`;180+ }181+182+ return rev === "main" ? "Landings" : `Landings on ${revLabel(rev)}`;183+};184+185+/** The page's search with `show`: none for every commit. */186+const searchFor = (query: string, show: LogShow) => {187+ const search: Record<string, string> = Object.fromEntries(188+ new URLSearchParams(query)189+ );190+191+ if (show !== "all") {192+ search.show = show;193+ }194+195+ return search;196+};197+198+export interface LogViewProps {199 readonly commits: readonly CommitView[];200 /** Where this page starts. */201 readonly from: number;202 /** Where the next (older) page starts; absent on the last. */2 unmodified lines205 /** Only the commits that changed this path. */206 readonly path?: RepoPath | undefined;207 readonly project: ProjectName;208 readonly rev: string;166-}) => {209+ /** Which commits of the page to show. */210+ readonly show?: LogShow;211+}212+213+export const LogView = ({214+ commits,215+ from,216+ next,217+ now,218+ path,219+ project,220+ rev,221+ show = "all",222+}: LogViewProps) => {223 const filter = path === undefined ? {} : { path };224+ const shown = commits.filter((commit) => shows(show, commit));225+ const base = commitsHref(project, rev, filter);226+ const [to, query = ""] = base.split("?");227 228 return (170- <PageShell171- title={172- path === undefined173- ? `Commits on ${revLabel(rev)}`174- : `History of ${path} on ${revLabel(rev)}`229+ <Workspace230+ title={titleOf(path, rev)}231+ toolbar={232+ <nav aria-label="Show" className="flex h-full items-center gap-4">233+ {FILTERS.map(({ label, show: each }) => (234+ <AppLink235+ aria-current={show === each ? "page" : undefined}236+ className={FILTER}237+ key={each}238+ search={searchFor(query, each)}239+ to={to ?? base}240+ >241+ {label}242+ </AppLink>243+ ))}244+ </nav>245 }246+ variant="list"247 >177- <ProjectNav current="landings" project={project} />248 {path === undefined ? null : (179- <p className="text-sm">180- <a className={LINK} href={blobHref(project, rev, path)}>249+ <p className="text-ui">250+ <AppLink className={LINK} to={blobHref(project, rev, path)}>251 Back to {path}182- </a>252+ </AppLink>253 </p>254 )}185- {commits.length === 0 ? (186- <EmptyState title="No commits on this page." />255+ {shown.length === 0 ? (256+ <EmptyState257+ title={258+ commits.length === 0259+ ? "No commits on this page."260+ : "None of this page's commits are of this kind."261+ }262+ />263 ) : (188- byDay(commits).map(({ commits: ofDay, day }) => (189- <section190- aria-label={day}191- className="flex flex-col gap-1"192- data-day={day}193- key={day}194- >195- <h2 className="text-muted-foreground text-sm font-medium">196- Commits on{" "}197- {dayWords.format(198- DateTime.toDateUtc(ofDay[0]?.committer.at ?? now)199- )}200- </h2>201- <ol className="border-rule flex flex-col border-b">202- {ofDay.map((commit) => (203- <Row204- commit={commit}205- key={commit.sha}206- now={now}207- project={project}208- />209- ))}210- </ol>211- </section>212- ))264+ <div className="flex flex-col">265+ {byDay(shown).map(({ commits: ofDay, day }) => (266+ <div data-day={day} key={day}>267+ <RowGroup268+ counts={`${ofDay.length} ${ofDay.length === 1 ? "commit" : "commits"}`}269+ label={day}270+ name={dayWords.format(271+ DateTime.toDateUtc(ofDay[0]?.committer.at ?? now)272+ )}273+ >274+ {ofDay.map((commit) => (275+ <CommitRow276+ commit={commit}277+ key={commit.sha}278+ now={now}279+ project={project}280+ />281+ ))}282+ </RowGroup>283+ </div>284+ ))}285+ </div>286 )}287 <Pager288 newer={289 from > 05 unmodified lines295 ? undefined296 : commitsHref(project, rev, { ...filter, from: next })297 }298 />226- </PageShell>299+ </Workspace>300 );301 };added:apps/web/src/features/code/media.ts+33 added
1+/**2+ * Whether the screen is at least a width, kept current as the window3+ * changes. The server and the page's first render say no, so the markup4+ * matches; the browser then says what the screen is.5+ */6+import { useMemo, useSyncExternalStore } from "react";7+8+const subscribe = (query: string) => (changed: () => void) => {9+ const list = globalThis.matchMedia(query);10+11+ list.addEventListener("change", changed);12+13+ return () => {14+ list.removeEventListener("change", changed);15+ };16+};17+18+/** Whether `query` matches now, in the browser; never on the server. */19+export const useMedia = (query: string): boolean =>20+ useSyncExternalStore(21+ useMemo(() => subscribe(query), [query]),22+ () => globalThis.matchMedia(query).matches,23+ () => false24+ );25+26+/** The shell's width, from which the rail holds the tree. */27+export const SHELL_QUERY = "(min-width: 70rem)";28+29+/** The width from which a diff may set its sides apart. */30+export const SPLIT_QUERY = "(min-width: 48rem)";31+32+/** A tablet's width and wider, where a sheet comes from the side rather than filling the screen. */33+export const TABLET_QUERY = "(min-width: 40rem)";modified:apps/web/src/features/code/not-found.tsx+53 added-12 removed
1+import type { Refusal } from "@repo/protocol/refusal";2 /**2- * A code page's 404: the refusal the platform gave (`UnknownProject`,3- * `UnknownRevision`, `UnknownPath`, `UnknownCommit`), as `git` would print4- * it, carried in the loader's not-found; or, for an address that can name5- * nothing, a sentence saying why.3+ * A code page's 404. A path missing at a revision that exists lands softly4+ * on the nearest folder that does, the platform's refusal (`UnknownPath`)5+ * as its notice, verbatim, above the folder's entries. Any other refusal6+ * (`UnknownProject`, `UnknownRevision`, `UnknownCommit`) is drawn as `git`7+ * would print it, with a way onward; an address that can name nothing8+ * says why in a sentence.9 */10 import { Option, Schema } from "effect";11+import type { Array } from "effect";12 9-import { NotFoundView } from "../ask/refused.tsx";13+import { EmptyState } from "../shared/empty.tsx";14+import { AppLink } from "../shared/link.tsx";15+import { RefusalView } from "../shared/refusal.tsx";16 import { Refusals } from "../shared/refusals.ts";17+import { Workspace } from "../shared/shell/workspace.tsx";18+import { SoftLanding } from "./soft-landing.ts";19+import { TreeView } from "./tree-view.tsx";20 21+const decodeLanding = Schema.decodeUnknownOption(SoftLanding);22+23 const decodeRefusals = Schema.decodeUnknownOption(Refusals);24 25+const LINK = "decoration-rule underline hover:decoration-current";26+14-const NOTHING =27+export const NOTHING =28 "Nothing is at this address: a code page names a project, then main, a whole 40-hex commit id or a tag, then a path in the project.";29 17-export const CodeNotFound = ({ data }: { readonly data?: unknown }) => (18- <NotFoundView19- nothing={NOTHING}20- refusals={Option.getOrUndefined(decodeRefusals(data))}21- title="Not found"22- />30+/** A refusal with no folder to land on: verbatim, then the ways onward. */31+const Refused = ({32+ refusals,33+}: {34+ readonly refusals: Array.NonEmptyReadonlyArray<Refusal> | undefined;35+}) => (36+ <Workspace title="Not found">37+ {refusals === undefined ? (38+ <EmptyState title={NOTHING} />39+ ) : (40+ <RefusalView refusals={refusals} />41+ )}42+ <p className="text-ui flex flex-wrap gap-x-4 gap-y-1">43+ <AppLink className={LINK} to="/">44+ Open asks45+ </AppLink>46+ </p>47+ </Workspace>48 );49+50+export const CodeNotFound = ({ data }: { readonly data?: unknown }) =>51+ Option.match(decodeLanding(data), {52+ onNone: () => (53+ <Refused refusals={Option.getOrUndefined(decodeRefusals(data))} />54+ ),55+ onSome: (landing) => (56+ <TreeView57+ listing={landing.nearest}58+ notice={<RefusalView refusals={landing.refusals} />}59+ now={landing.now}60+ project={landing.project}61+ rev={landing.rev}62+ />63+ ),64+ });added:apps/web/src/features/code/numbered-lines.tsx+80 added
1+/**2+ * A file as plain text, each line numbered and anchored (`#L42` scrolls3+ * there with no script): what the server sends of a file, and what a4+ * reader sees until the browser has drawn it highlighted over it. It takes5+ * Pierre's measures for a file drawn without a header: 8 px above and6+ * below the code, 13 px on 20 px lines, the gutter at least three figures7+ * wide with two before them and one after, the text one column in. So the8+ * highlighting arrives in place and nothing moves. Long lines scroll9+ * sideways inside the code, never wrap.10+ *11+ * `bands` puts a row above a line (the why page's groups), as the drawing12+ * puts its annotations.13+ */14+import type { ReactNode } from "react";15+16+import { linesOf } from "./file-header.tsx";17+18+/** How many lines the server sends; the browser's drawing shows them all. */19+export const FALLBACK_LINES = 2000;20+21+/** Pierre's gutter: at least three figures, two before them and one after, then a 2 px gap. */22+const GUTTER =23+ "border-background text-muted-foreground hover:text-foreground min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums no-underline select-none";24+25+export const NumberedLines = ({26+ bands,27+ text,28+}: {29+ readonly text: string;30+ /** A row to draw above each of these lines, by line number. */31+ readonly bands?: ReadonlyMap<number, ReactNode>;32+}) => {33+ const lines = linesOf(text);34+ const shown = lines.slice(0, FALLBACK_LINES);35+36+ return (37+ <div className="flex min-w-0 flex-col" data-code="plain">38+ <pre className="text-mono leading-code overflow-x-auto py-2 font-mono">39+ <code className="grid min-w-full grid-cols-[min-content_1fr]">40+ {shown.map((line, index) => {41+ const number = index + 1;42+ const band = bands?.get(number);43+44+ // The anchor sits on the line's text: the row around it is45+ // `display: contents`, which draws no box to scroll to.46+ return (47+ <span className="contents" key={number}>48+ {band === undefined ? null : (49+ <>50+ <span51+ aria-hidden="true"52+ className="border-background border-r-2"53+ />54+ <span className="font-sans whitespace-normal">{band}</span>55+ </>56+ )}57+ <a className={GUTTER} href={`#L${number}`}>58+ {number}59+ </a>60+ <span61+ className="px-[1ch] whitespace-pre"62+ data-line={number}63+ id={`L${number}`}64+ >65+ {line}66+ </span>67+ </span>68+ );69+ })}70+ </code>71+ </pre>72+ {lines.length > shown.length ? (73+ <p className="text-ui text-muted-foreground px-4 py-2">74+ The first {FALLBACK_LINES.toLocaleString("en")} of{" "}75+ {lines.length.toLocaleString("en")} lines.76+ </p>77+ ) : null}78+ </div>79+ );80+};added:apps/web/src/features/code/plain-diff.tsx+318 added
1+/**2+ * A commit's diff as plain text: what the server sends, and what a reader3+ * sees until the browser has drawn the highlighted diff over it. It holds4+ * the hunks the drawing holds (`diff-model.ts` parses both texts with the5+ * drawing's own parser) and takes Pierre's measures: a 44 px file header,6+ * 13 px code on 20 px lines, line numbers in a gutter of at least three7+ * figures with two before and one after, a sign in the first of two8+ * leading columns, unchanged runs as 32 px "N unmodified lines" bars. So9+ * the highlighting arrives in place and nothing moves.10+ *11+ * Each file is a disclosure whose summary is its header: folded, only the12+ * header shows (an added or deleted file past 80 lines starts folded).13+ * Additions and deletions take the diff's own tints, never the landed or14+ * refused colour; a unified diff marks each line `+` or `-`, a split one15+ * marks the side with a bar.16+ */17+import type { ChangedFile } from "@repo/protocol/domain/code";18+import { Option } from "effect";19+import { ChevronDown, SquareDot, SquareMinus, SquarePlus } from "lucide-react";20+import type { LucideIcon } from "lucide-react";21+import type { ReactNode } from "react";22+23+import { drawnFiles, splitRows, unifiedRows } from "./diff-model.ts";24+import type { DrawnFile, PlainRow, SplitRow } from "./diff-model.ts";25+import { diffAnchor } from "./paths.ts";26+27+/** One numbered line: its text, and which side it is on. */28+type Line = Extract<PlainRow, { readonly number: number }>;29+30+/** A line's ground and its number's colour, by what it is. */31+const TONES = {32+ addition: {33+ line: "bg-diff-add-bg",34+ number: "bg-diff-add-bg text-diff-add-sign",35+ },36+ context: { line: "", number: "text-muted-foreground" },37+ deletion: {38+ line: "bg-diff-del-bg",39+ number: "bg-diff-del-bg text-diff-del-sign",40+ },41+} as const satisfies Record<42+ Line["kind"],43+ { readonly line: string; readonly number: string }44+>;45+46+/** Each line's sign in a unified diff, the mark that reads without colour. */47+const SIGNS = { addition: "+", context: " ", deletion: "-" } as const;48+49+/** Pierre's gutter: at least three figures, two before them and one after, then a 2 px gap. */50+const GUTTER =51+ "border-background min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums select-none";52+53+/** An unchanged run between hunks: a 32 px bar saying how many lines it skips. */54+const Separator = ({55+ lines,56+ span,57+}: {58+ readonly lines: number;59+ readonly span: number;60+}) => (61+ <div62+ className="bg-surface text-muted-foreground my-2 flex h-8 items-center px-[2ch] font-sans first:mt-0 last:mb-0"63+ data-separator="line-info"64+ style={{ gridColumn: `span ${span} / span ${span}` }}65+ >66+ {lines} unmodified {lines === 1 ? "line" : "lines"}67+ </div>68+);69+70+/** One line of a unified diff: its number, then its sign and text. */71+const UnifiedLine = ({ line }: { readonly line: Line }) => (72+ <>73+ <span className={`${GUTTER} ${TONES[line.kind].number}`}>74+ {line.number}75+ </span>76+ <span77+ className={`pr-[1ch] whitespace-pre ${TONES[line.kind].line}`}78+ data-line={line.number}79+ data-line-type={line.kind}80+ >81+ <span aria-hidden="true" className="inline-block w-[2ch] select-none">82+ {SIGNS[line.kind]}83+ </span>84+ {line.text}85+ </span>86+ </>87+);88+89+/** One side of a split diff's row: its number with the side's bar, then its text; empty when the side has none. */90+const SplitSide = ({ line }: { readonly line: Line | undefined }) =>91+ line === undefined ? (92+ <>93+ <span className={`${GUTTER} bg-surface`} />94+ <span className="bg-surface" />95+ </>96+ ) : (97+ <>98+ <span99+ className={`${GUTTER} relative ${TONES[line.kind].number} ${100+ line.kind === "context"101+ ? ""102+ : `before:absolute before:inset-y-0 before:left-0 before:w-1 ${103+ line.kind === "addition"104+ ? "before:bg-diff-add-sign"105+ : "before:bg-[repeating-linear-gradient(0deg,var(--diff-del-sign)_0_2px,transparent_2px_4px)]"106+ }`107+ }`}108+ >109+ {line.number}110+ </span>111+ <span112+ className={`pr-[1ch] pl-[1ch] whitespace-pre ${TONES[line.kind].line}`}113+ data-line={line.number}114+ data-line-type={line.kind}115+ >116+ {line.text}117+ </span>118+ </>119+ );120+121+/** A file's lines, unified: one grid of gutter and code, scrolling sideways in itself. */122+const UnifiedBody = ({ rows }: { readonly rows: readonly PlainRow[] }) => (123+ <div className="overflow-x-auto pb-2">124+ <code className="grid min-w-full grid-cols-[min-content_1fr]">125+ {rows.map((row, index) =>126+ row.kind === "separator" ? (127+ <Separator key={`s${index}`} lines={row.lines} span={2} />128+ ) : (129+ <UnifiedLine key={`${row.kind}${row.number}:${index}`} line={row} />130+ )131+ )}132+ </code>133+ </div>134+);135+136+/** A file's lines, split: old on the left, new on the right, row beside row. */137+const SplitBody = ({ rows }: { readonly rows: readonly SplitRow[] }) => (138+ <div className="overflow-x-auto pb-2">139+ <code className="grid min-w-full grid-cols-[min-content_1fr_min-content_1fr]">140+ {rows.map((row, index) =>141+ row.kind === "separator" ? (142+ <Separator key={`s${index}`} lines={row.lines} span={4} />143+ ) : (144+ <span className="contents" key={`p${index}`}>145+ <SplitSide line={row.left} />146+ <SplitSide line={row.right} />147+ </span>148+ )149+ )}150+ </code>151+ </div>152+);153+154+/** What a file changed, in counts: `+n −m`, each in its tint, with words for a screen reader. */155+export const ChangeCounts = ({156+ additions,157+ deletions,158+ header = false,159+}: {160+ readonly additions: number;161+ readonly deletions: number;162+ /** As a diff's file header prints them: a hyphen, and no count of nothing. */163+ readonly header?: boolean;164+}) => (165+ <span className="text-mono flex shrink-0 items-center gap-[1ch] font-mono tabular-nums">166+ {header && additions === 0 ? null : (167+ <span className="text-diff-add-sign">168+ +{additions}169+ <span className="sr-only"> added</span>170+ </span>171+ )}172+ {header && deletions === 0 ? null : (173+ <span className="text-diff-del-sign">174+ {header ? "-" : "−"}175+ {deletions}176+ <span className="sr-only"> removed</span>177+ </span>178+ )}179+ </span>180+);181+182+/** Why a file has no lines to show: binary, or its text not sent. */183+const Unshown = ({ file }: { readonly file: ChangedFile }) => (184+ <p className="text-ui text-muted-foreground px-4 pb-3 font-sans">185+ {file.binary ? "A binary file" : "Its text is not shown"}, {file.status}.186+ </p>187+);188+189+/** A file's lines, unified or split; why it has none when it has none. */190+const FileBody = ({191+ file,192+ split,193+}: {194+ readonly file: DrawnFile;195+ readonly split: boolean;196+}) => {197+ const diff = Option.getOrUndefined(file.diff);198+199+ if (diff === undefined) {200+ return <Unshown file={file.file} />;201+ }202+203+ return split ? (204+ <SplitBody rows={splitRows(diff)} />205+ ) : (206+ <UnifiedBody rows={unifiedRows(diff)} />207+ );208+};209+210+/** Each kind of change as the drawing's header marks it, in the diff's tints. */211+const CHANGE_MARKS = {212+ added: { icon: SquarePlus, tone: "text-diff-add-sign" },213+ deleted: { icon: SquareMinus, tone: "text-diff-del-sign" },214+ modified: { icon: SquareDot, tone: "text-muted-foreground" },215+} as const satisfies Record<216+ ChangedFile["status"],217+ { readonly icon: LucideIcon; readonly tone: string }218+>;219+220+/**221+ * A file's header as the drawing draws it: the fold's chevron, the mark of222+ * its change (with its word for a screen reader), its path, then its223+ * counts and anything the page adds.224+ */225+export const FileHeaderLine = ({226+ end,227+ file,228+}: {229+ readonly file: DrawnFile;230+ /** Anything a page puts at the header's end (a "Mark read" button). */231+ readonly end?: ReactNode;232+}) => {233+ const { icon: Icon, tone } = CHANGE_MARKS[file.file.status];234+235+ return (236+ <>237+ <ChevronDown238+ aria-hidden="true"239+ className="text-muted-foreground size-4 shrink-0 -rotate-90 transition-transform duration-150 group-open/file:rotate-0"240+ strokeWidth={1.75}241+ />242+ <Icon243+ aria-hidden="true"244+ className={`size-4 shrink-0 ${tone}`}245+ strokeWidth={1.75}246+ />247+ <span className="sr-only">{file.file.status}:</span>248+ <span className="min-w-0 flex-1 truncate" title={file.file.path}>249+ {file.file.path}250+ </span>251+ {Option.isNone(file.diff) ? (252+ <span className="text-muted-foreground shrink-0">253+ {file.file.binary ? "binary" : "not shown"}254+ </span>255+ ) : (256+ <ChangeCounts {...file.counts} header />257+ )}258+ {end}259+ </>260+ );261+};262+263+export interface PlainDiffProps {264+ readonly files: readonly ChangedFile[];265+ /** Old and new side by side; unified when absent. */266+ readonly split?: boolean;267+ /** The files folded now; each file's own default (`folded`) when absent. */268+ readonly folded?: ReadonlySet<string> | undefined;269+ /** A header's fold was pressed. */270+ readonly onFold?: ((path: string, folded: boolean) => void) | undefined;271+}272+273+/**274+ * The diff of `files`, plain, in the order a tree lists them. Server275+ * markup: one `section[data-file]` per file, its header sticky at the top276+ * of the pane that scrolls it.277+ */278+export const PlainDiff = ({279+ files,280+ folded,281+ onFold,282+ split = false,283+}: PlainDiffProps) => (284+ <div className="text-mono leading-code font-mono" data-diff="plain">285+ {drawnFiles(files).map((drawn) => {286+ const { file } = drawn;287+288+ const closed =289+ folded === undefined ? drawn.folded : folded.has(file.path);290+291+ return (292+ <section293+ aria-label={file.path}294+ data-file={file.path}295+ data-folded={closed}296+ id={diffAnchor(file.path)}297+ key={file.path}298+ >299+ <details300+ className="group/file"301+ onToggle={(event) => {302+ onFold?.(file.path, !event.currentTarget.open);303+ }}304+ open={!closed}305+ >306+ <summary307+ className="border-rule bg-background text-mono hover:bg-surface sticky top-0 z-[1] flex h-11 cursor-pointer list-none items-center gap-2 border-y px-4 font-sans [&::-webkit-details-marker]:hidden"308+ data-diffs-header=""309+ >310+ <FileHeaderLine file={drawn} />311+ </summary>312+ <FileBody file={drawn} split={split} />313+ </details>314+ </section>315+ );316+ })}317+ </div>318+);added:apps/web/src/features/code/pool.tsx+56 added
1+/**2+ * Highlighting off the main thread: Pierre's worker pool, which every3+ * drawing of code under `CodePool` shares (`File`, `CodeView`). The pool is4+ * made once for the tab, the first time a page draws code, and kept: the5+ * next code page highlights in workers already warm, and a file drawn once6+ * is not highlighted again (each drawing keys its file by blob id).7+ *8+ * The worker is Pierre's own module, bundled by Vite as a module worker.9+ * Only the browser loads this file (through the lazy drawings).10+ */11+import { WorkerPoolContext } from "@pierre/diffs/react";12+import { getOrCreateWorkerPoolSingleton } from "@pierre/diffs/worker";13+import type { ReactNode } from "react";14+import { useMemo } from "react";15+16+import { diffsOptions, registerCodeTheme } from "./pierre.ts";17+18+/** Two workers: a page draws one file or one diff at a time, and grammars load once per worker. */19+const POOL_SIZE = 2;20+21+/** The tab's pool: made the first time code is drawn or warmed, the same after. */22+export const workerPool = () => {23+ registerCodeTheme();24+25+ return getOrCreateWorkerPoolSingleton({26+ highlighterOptions: {27+ lineDiffType: "word-line",28+ maxLineDiffLength: diffsOptions.maxLineDiffLength,29+ preferredHighlighter: diffsOptions.preferredHighlighter,30+ theme: diffsOptions.theme,31+ tokenizeMaxLineLength: diffsOptions.tokenizeMaxLineLength,32+ },33+ poolOptions: {34+ onWorkerError: () => {35+ // A worker that fails is Pierre's to replace; the code it was36+ // drawing stays as plain text, which is what the page sent.37+ },38+ poolSize: POOL_SIZE,39+ workerFactory: () =>40+ new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {41+ type: "module",42+ }),43+ },44+ });45+};46+47+/** The pool, for the drawings under it; none outside a browser. */48+export const CodePool = ({ children }: { readonly children: ReactNode }) => {49+ // Pierre keeps one pool for the tab: asking again hands back the same.50+ const pool = useMemo(51+ () => ("Worker" in globalThis ? workerPool() : undefined),52+ []53+ );54+55+ return <WorkerPoolContext value={pool}>{children}</WorkerPoolContext>;56+};added:apps/web/src/features/code/ref-switcher.tsx+153 added
1+/**2+ * The code pages' ref line: the revision being read (main, a tag, or a3+ * commit by its short id), and a switcher that opens the same page at4+ * main or at any tag. Each choice is a link, so it can be opened in a new5+ * tab, and the tags filter as the reader types. The list of tags arrives6+ * after the page; until it has, only main is offered.7+ */8+import type { RefsView } from "@repo/protocol/domain/code";9+import { GitBranch, GitCommitHorizontal, Tag } from "lucide-react";10+import { useState } from "react";11+12+import {13+ Popover,14+ PopoverContent,15+ PopoverTrigger,16+} from "@/components/ui/popover";17+18+import { AppLink } from "../shared/link.tsx";19+import { isCommitId } from "./headers.ts";20+import { revLabel } from "./rev.ts";21+22+/** At most this many tags listed at once; the filter finds the rest. */23+const SHOWN = 100;24+25+/** A ref's mark: a branch for main, a tag for a tag, a commit for a SHA. */26+const RefMark = ({ rev }: { readonly rev: string }) => {27+ if (rev === "main") {28+ return (29+ <GitBranch30+ aria-hidden="true"31+ className="size-4 shrink-0"32+ strokeWidth={1.75}33+ />34+ );35+ }36+37+ return isCommitId(rev) ? (38+ <GitCommitHorizontal39+ aria-hidden="true"40+ className="size-4 shrink-0"41+ strokeWidth={1.75}42+ />43+ ) : (44+ <Tag aria-hidden="true" className="size-4 shrink-0" strokeWidth={1.75} />45+ );46+};47+48+/** Under the list: that the tags are still being read, or how many the filter has left out. */49+const ListFoot = ({50+ count,51+ read,52+}: {53+ readonly count: number;54+ readonly read: boolean;55+}) => {56+ if (!read) {57+ return (58+ <p className="text-label text-muted-foreground px-2 pb-1">59+ Reading the tags…60+ </p>61+ );62+ }63+64+ return count > SHOWN ? (65+ <p className="text-label text-muted-foreground px-2 pb-1">66+ {count - SHOWN} more: type to find them.67+ </p>68+ ) : null;69+};70+71+const ROW =72+ "text-ui hover:bg-surface flex h-8 min-w-0 items-center gap-2 px-2 no-underline aria-[current]:bg-surface aria-[current]:font-semibold";73+74+export const RefSwitcher = ({75+ hrefAt,76+ refs,77+ rev,78+}: {79+ /** The revision the page reads. */80+ readonly rev: string;81+ /** Main and the tags, once read. */82+ readonly refs?: RefsView | undefined;83+ /** The same page at another revision. */84+ readonly hrefAt: (rev: string) => string;85+}) => {86+ const [filter, setFilter] = useState("");87+ const [open, setOpen] = useState(false);88+89+ const tags = (refs?.tags ?? [])90+ .map(({ name }) => name)91+ .filter((name) => name.toLowerCase().includes(filter.trim().toLowerCase()));92+93+ return (94+ <Popover onOpenChange={setOpen} open={open}>95+ <PopoverTrigger96+ aria-label={`Revision: ${revLabel(rev)}. Switch revision`}97+ className="text-ui hover:bg-surface border-input flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 border px-2"98+ data-ref={rev}99+ >100+ <RefMark rev={rev} />101+ <span102+ className={`min-w-0 truncate ${rev === "main" ? "" : "text-mono font-mono"}`}103+ >104+ {revLabel(rev)}105+ </span>106+ </PopoverTrigger>107+ <PopoverContent align="start" className="w-64 gap-2 p-1.5">108+ <input109+ aria-label="Find a tag"110+ className="border-input bg-background sm:text-ui h-9 w-full border px-2 text-base sm:h-8"111+ onChange={(event) => {112+ setFilter(event.currentTarget.value);113+ }}114+ placeholder="Find a tag"115+ value={filter}116+ />117+ <ul className="flex max-h-80 flex-col overflow-y-auto overscroll-contain">118+ <li>119+ <AppLink120+ aria-current={rev === "main" ? "true" : undefined}121+ className={ROW}122+ onClick={() => {123+ setOpen(false);124+ }}125+ to={hrefAt("main")}126+ >127+ <RefMark rev="main" />128+ main129+ </AppLink>130+ </li>131+ {tags.slice(0, SHOWN).map((name) => (132+ <li data-tag={name} key={name}>133+ <AppLink134+ aria-current={rev === name ? "true" : undefined}135+ className={ROW}136+ onClick={() => {137+ setOpen(false);138+ }}139+ to={hrefAt(name)}140+ >141+ <RefMark rev={name} />142+ <span className="text-mono min-w-0 truncate font-mono">143+ {name}144+ </span>145+ </AppLink>146+ </li>147+ ))}148+ </ul>149+ <ListFoot count={tags.length} read={refs !== undefined} />150+ </PopoverContent>151+ </Popover>152+ );153+};modified:apps/web/src/features/code/repo-tree.tsx+148 added-43 removed
1 /**2- * A project's files as a tree, drawn by `@pierre/trees`, with the current3- * path open and selected. Choosing a file opens `hrefOf(path)`: its page,4- * or on a commit's page its diff. Folders open in place. `status` marks the5- * files a commit changed (and their folders).2+ * A project's files as a tree, drawn by `@pierre/trees`, in the UI's own3+ * face: compact rows, plain grey icons, single-child folders flattened4+ * into one row, the folders above the visible rows kept at the top as the5+ * reader scrolls, and a filter. The current path is open, selected and in6+ * view; when it changes (the reader moved to another file and the tree7+ * stayed mounted), the tree follows.8 *7- * The paths arrive as plain strings and are prepared here, never on the8- * server (a prepared input's symbol key does not serialize). Only the9- * browser loads this module (`client-tree.tsx`).9+ * Choosing a file calls `onOpen`, which the page answers through the10+ * router: the document is never reloaded, so the tree stays where it is.11+ * On a commit's page the tree lists the changed files, open, each marked12+ * A, M or D and with its `+n −m`.13+ *14+ * Only the browser loads this module (`client-tree.tsx`): the paths arrive15+ * as plain strings and are prepared here.16 */17 import { prepareFileTreeInput } from "@pierre/trees";18+import type {19+ FileTree,20+ FileTreeDirectoryHandle,21+ FileTreeItemHandle,22+ FileTreeOptions,23+ FileTreeRowDecoration,24+ GitStatusEntry,12-import type { GitStatusEntry } from "@pierre/trees";13-import { FileTree, useFileTree } from "@pierre/trees/react";25+} from "@pierre/trees";26+import { FileTree as FileTreeView, useFileTree } from "@pierre/trees/react";27 import { useEffect, useMemo } from "react";28 29+import type { Counts } from "./diff-model.ts";30 import { ancestorsOf } from "./paths.ts";31 import { treesOptions } from "./pierre.ts";32 33 export interface RepoTreeProps {20- /** The path the page shows, a file or a folder. */21- readonly current?: string | undefined;22- /** Where choosing the file `path` goes. */23- readonly hrefOf: (path: string) => string;34 readonly paths: readonly string[];35+ /** The path the page shows, a file or a folder; none on a commit's page until one is chosen. */36+ readonly current?: string | undefined;37+ /** A file was chosen. */38+ readonly onOpen: (path: string) => void;25- /** The files a commit changed; none on a code page. */39+ /** The files a commit changed, marked by how. */40 readonly status?: readonly GitStatusEntry[];41+ /** What each changed file adds and removes, at its row's end. */42+ readonly counts?: ReadonlyMap<string, Counts>;43+ /** Every folder open from the start (a commit's few changed files). */44+ readonly open?: boolean;45 }46 29-/** A tree with no file marked. */47 const NO_STATUS: readonly GitStatusEntry[] = [];48 32-export const RepoTree = ({33- current,34- hrefOf,35- paths,36- status = NO_STATUS,37-}: RepoTreeProps) => {38- const preparedInput = useMemo(() => prepareFileTreeInput(paths), [paths]);49+/** The page's own row: its name set heavier than its neighbours'. */50+const SELECTED_CSS =51+ "[data-type='item'][aria-selected='true'] { font-weight: 600; color: var(--foreground); }";52 40- const { model } = useFileTree({53+/** A folder's id in the tree: its path and a slash. */54+const folderId = (path: string) => `${path}/`;55+56+/** What `current` opens: each folder above it, and itself when it is a folder. */57+const openFor = (current: string | undefined) =>58+ current === undefined || current === ""59+ ? []60+ : [...ancestorsOf(current), current].map(folderId);61+62+/** A changed file's `+n −m`, each part in the diff's own tint. */63+const decorationOf = (counts: Counts): FileTreeRowDecoration => ({64+ parts: [65+ { color: "var(--diff-add-sign)", text: `+${counts.additions}` },66+ { text: " " },67+ { color: "var(--diff-del-sign)", text: `−${counts.deletions}` },68+ ],69+ text: `+${counts.additions} −${counts.deletions}`,70+ title: `${counts.additions} added, ${counts.deletions} removed`,71+});72+73+/** The tree's options for `props`: its look, the page's path open and selected. */74+export const treeOptionsFor = (75+ props: Omit<RepoTreeProps, "onOpen">,76+ preparedInput = prepareFileTreeInput(props.paths)77+): FileTreeOptions => {78+ const { counts, current, open = false, status = NO_STATUS } = props;79+80+ const options: FileTreeOptions = {81 ...treesOptions,82 fileTreeSearchMode: "hide-non-matches",83+ flattenEmptyDirectories: true,84+ gitStatus: status,85 id: "repo-tree",44- initialExpandedPaths:45- current === undefined46- ? []47- : [...ancestorsOf(current), current].map((folder) => `${folder}/`),86+ initialExpandedPaths: openFor(current),87+ initialExpansion: open ? "open" : "closed",88 initialSelectedPaths: current === undefined ? [] : [current],49- onSelectionChange: (selected) => {50- const path = selected.at(-1);51-52- if (path !== undefined && !path.endsWith("/") && path !== current) {53- globalThis.location.assign(hrefOf(path));54- }55- },89 preparedInput,90 search: true,58- gitStatus: status,91+ stickyFolders: true,92+ // The selected row's fill is faint on paper: its name in ink at 60093+ // says it too.94+ unsafeCSS: SELECTED_CSS,95+ };96+97+ if (counts !== undefined) {98+ options.renderRowDecoration = ({ item }) => {99+ const changed = counts.get(item.path);100+101+ return changed === undefined ? null : decorationOf(changed);102+ };103+ }104+105+ return options;106+};107+108+/**109+ * Hand the page each file the reader chooses in `tree` (never a folder,110+ * never the page's own file); the returned function stops.111+ */112+export const followChoices = (113+ tree: Pick<FileTree, "getSelectedPaths" | "subscribe">,114+ current: string | undefined,115+ onOpen: (path: string) => void116+) =>117+ tree.subscribe(() => {118+ const path = tree.getSelectedPaths().at(-1);119+120+ if (path !== undefined && !path.endsWith("/") && path !== current) {121+ onOpen(path);122+ }123 });124 61- // Keep the page's own path in view.125+/** Whether a tree item is a folder, which opens. */126+const isFolder = (item: FileTreeItemHandle): item is FileTreeDirectoryHandle =>127+ item.isDirectory();128+129+export const RepoTree = (props: RepoTreeProps) => {130+ const { current, onOpen } = props;131+132+ // The tree is made from its first options: the page keys it by project133+ // and revision, so a new set of paths is a new tree.134+ const preparedInput = useMemo(135+ () => prepareFileTreeInput(props.paths),136+ [props.paths]137+ );138+139+ const { model } = useFileTree(treeOptionsFor(props, preparedInput));140+141+ useEffect(142+ () => followChoices(model, current, onOpen),143+ [model, current, onOpen]144+ );145+146+ // Follow the page: open the folders above its path, select it alone,147+ // and bring it into view.148 useEffect(() => {63- if (current !== undefined) {64- model.scrollToPath(current, { focus: false, offset: "nearest" });149+ if (current === undefined || current === "") {150+ return;151 }152+153+ for (const folder of openFor(current)) {154+ const item = model.getItem(folder);155+156+ if (item !== null && isFolder(item)) {157+ item.expand();158+ }159+ }160+161+ for (const selected of model.getSelectedPaths()) {162+ if (selected !== current) {163+ model.getItem(selected)?.deselect();164+ }165+ }166+167+ const here = model.getItem(current) ?? model.getItem(folderId(current));168+169+ if (here !== null && !here.isSelected()) {170+ here.select();171+ }172+173+ model.scrollToPath(current, { focus: false, offset: "nearest" });174 }, [model, current]);175 68- // The tree scrolls inside itself, so it needs a definite height: a69- // minimum leaves its rows clipped to nothing.70- return (71- <FileTree className="h-[40dvh] lg:h-[calc(100dvh-2rem)]" model={model} />72- );176+ // The tree scrolls inside itself, so it takes the height its box gives.177+ return <FileTreeView className="block h-full min-h-0" model={model} />;178 };179 180 // `React.lazy` takes a module's default export.181 export default RepoTree;added:apps/web/src/features/code/soft-landing.ts+23 added
1+/**2+ * What a code page's 404 carries when the path it named is missing at a3+ * revision that exists: the platform's refusal (`UnknownPath`), and the4+ * nearest folder above the path that does exist there, so the page lands5+ * softly on that folder with the refusal's own words as its notice. Any6+ * other refusal (no such project, revision or commit) travels alone, as7+ * `Refusals`.8+ */9+import { TreeListing } from "@repo/protocol/domain/code";10+import { ProjectName } from "@repo/protocol/ids";11+import { Schema } from "effect";12+13+import { Refusals } from "../shared/refusals.ts";14+15+export const SoftLanding = Schema.Struct({16+ nearest: TreeListing,17+ now: Schema.DateTimeUtcFromString,18+ project: ProjectName,19+ refusals: Refusals,20+ rev: Schema.String,21+});22+23+export type SoftLanding = typeof SoftLanding.Type;modified:apps/web/src/features/code/tree-view.tsx+161 added-163 removed
1 /**2- * One folder of a project at a revision: where it sits (a breadcrumb of3- * its ancestors, each a link at the same revision), its entries (folders4- * first, as `readTree` orders them) and its README below. Props in, markup5- * out: the server renders all of it, and the browser adds the file tree6- * (`sidebar`, client-only, from `client-tree.tsx`) beside it.2+ * One folder of a project at a revision. The tree in the rail is the3+ * navigation; main lists the folder once, as rows: each entry's name (a4+ * folder first, as `readTree` orders them), what last changed it (the ask5+ * its landing answered, or the commit's subject) and how long ago, then6+ * the folder's README below on the page's prose.7+ *8+ * What last changed each entry arrives after the page (`last`): its9+ * column holds its place until then, so nothing moves.10 */11 import type {12 CodeEntry,13+ CommitView,14 FileView,15 TreeListing,16 } from "@repo/protocol/domain/code";17 import type { ProjectName } from "@repo/protocol/ids";18 import { Match, Option } from "effect";19+import type { DateTime } from "effect";20 import { File, FileSymlink, Folder, FolderGit2 } from "lucide-react";21 import type { LucideIcon } from "lucide-react";17-import { Fragment } from "react";22 import type { ReactNode } from "react";23 20-import {21- Breadcrumb,22- BreadcrumbItem,23- BreadcrumbLink,24- BreadcrumbList,25- BreadcrumbPage,26- BreadcrumbSeparator,27-} from "@/components/ui/breadcrumb";28-import {29- Table,30- TableBody,31- TableCell,32- TableHead,33- TableHeader,34- TableRow,35-} from "@/components/ui/table";36-37-import { ProjectNav } from "../project/project-nav.tsx";24 import { ReadmeSection } from "../project/readme-section.tsx";39-import { LINK } from "../shared/classes.ts";40-import { PageShell } from "../shared/layout.tsx";41-import { ancestorsOf, blobHref, treeHref } from "./paths.ts";42-import { revLabel } from "./rev.ts";25+import { AppLink } from "../shared/link.tsx";26+import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";27+import { When } from "../shared/time.tsx";28+import { askOf } from "../why/rows.ts";29+import { FileHeader } from "./file-header.tsx";30+import { blobHref, commitsHref, treeHref } from "./paths.ts";31 32 /** Each kind of entry: its mark and the word a screen reader says for it. */33 const kinds = Match.type<CodeEntry["type"]>().pipe(34 Match.when("tree", () => ({ icon: Folder, word: "Folder" })),13 unmodified lines48 Match.when("submodule", () => Option.none<string>()),49 Match.orElse(() => Option.some(blobHref(project, rev, entry.path)))50 );51 64-/** A folder's entries, one row each, each linking its page at `rev`. */65-export const EntriesTable = ({66- entries,67- project,68- rev,69-}: {70- readonly entries: readonly CodeEntry[];71- readonly project: ProjectName;72- readonly rev: string;73-}) => (74- <Table className="font-mono text-[0.8125rem]">75- <TableHeader>76- <TableRow>77- <TableHead className="font-sans">Name</TableHead>78- </TableRow>79- </TableHeader>80- <TableBody>81- {entries.map((entry) => {82- const { icon: Icon, word } = kinds(entry.type);83- const href = Option.getOrUndefined(entryHref(project, rev, entry));52+/** What last changed an entry, in a few words: the ask its landing answered or opened, or the commit's subject. */53+const changeWords = (commit: CommitView) => {54+ const linked =55+ commit.landing === undefined56+ ? undefined57+ : Option.getOrUndefined(askOf(commit.landing));58 85- return (86- <TableRow data-entry={entry.path} key={entry.path}>87- <TableCell className="flex min-w-0 items-center gap-2 whitespace-normal">88- <Icon89- aria-hidden="true"90- className="text-muted-foreground size-4 shrink-0"91- />92- <span className="sr-only">{word}:</span>93- {href === undefined ? (94- <span className="[overflow-wrap:anywhere]">{entry.name}</span>95- ) : (96- <a className={`${LINK} [overflow-wrap:anywhere]`} href={href}>97- {entry.name}98- </a>99- )}100- </TableCell>101- </TableRow>102- );103- })}104- </TableBody>105- </Table>106-);59+ if (linked === undefined) {60+ return commit.subject === "" ? "(no subject)" : commit.subject;61+ }62 108-/**109- * Where `path` sits in the project at `rev`: the project, then each folder110- * above it, each a link to its folder at `rev`, then `path`'s own name.111- */112-export const CodeBreadcrumb = ({113- path,63+ return linked.kind === "opened" ? `opened ${linked.ask}` : linked.ask;64+};65+66+const LINK =67+ "text-foreground no-underline outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-ring focus-visible:after:outline-solid";68+69+/** One entry, one 40 px row: its mark, its name, what last changed it, and when. */70+const EntryRow = ({71+ entry,72+ last,73+ now,74 project,75 rev,76 }: {117- readonly path?: string | undefined;77+ readonly entry: CodeEntry;78+ readonly last?: CommitView | undefined;79+ readonly now?: DateTime.Utc | undefined;80 readonly project: ProjectName;81 readonly rev: string;82 }) => {121- const here = path === undefined || path === "" ? undefined : path;122- const name = here?.split("/").at(-1);83+ const { icon: Icon, word } = kinds(entry.type);84+ const href = Option.getOrUndefined(entryHref(project, rev, entry));85 86 return (125- <Breadcrumb>126- <BreadcrumbList className="font-mono text-[0.8125rem]">127- <BreadcrumbItem>128- {here === undefined ? (129- <BreadcrumbPage>{project}</BreadcrumbPage>130- ) : (131- <BreadcrumbLink href={treeHref(project, rev)}>132- {project}133- </BreadcrumbLink>134- )}135- </BreadcrumbItem>136- {here === undefined137- ? null138- : ancestorsOf(here).map((folder) => (139- <Fragment key={folder}>140- <BreadcrumbSeparator />141- <BreadcrumbItem>142- <BreadcrumbLink href={treeHref(project, rev, folder)}>143- {folder.split("/").at(-1)}144- </BreadcrumbLink>145- </BreadcrumbItem>146- </Fragment>147- ))}148- {name === undefined ? null : (149- <>150- <BreadcrumbSeparator />151- <BreadcrumbItem>152- <BreadcrumbPage>{name}</BreadcrumbPage>153- </BreadcrumbItem>154- </>87+ <li88+ className="group/row border-rule hover:bg-surface/50 relative isolate -mx-2 flex h-10 min-w-0 items-center gap-3 border-b px-2 transition-colors duration-[120ms]"89+ data-entry={entry.path}90+ >91+ <Icon92+ aria-hidden="true"93+ className="text-muted-foreground size-4 shrink-0"94+ strokeWidth={1.75}95+ />96+ <span className="sr-only">{word}:</span>97+ <span className="text-ui min-w-0 shrink-0 basis-[14rem] truncate font-medium">98+ {href === undefined ? (99+ entry.name100+ ) : (101+ <AppLink className={LINK} title={entry.name} to={href}>102+ {entry.name}103+ </AppLink>104 )}156- </BreadcrumbList>157- </Breadcrumb>105+ </span>106+ <span107+ className="text-ui text-muted-foreground tablet:block hidden min-w-0 flex-1 truncate"108+ data-last=""109+ >110+ {last === undefined ? null : changeWords(last)}111+ </span>112+ <span className="text-label text-muted-foreground ml-auto shrink-0 tabular-nums">113+ {last === undefined || now === undefined ? null : (114+ <When at={last.committer.at} now={now} />115+ )}116+ </span>117+ </li>118 );119 };120 161-/** A code page's frame: title, nav, and the file tree's column beside the content. */162-export const CodeLayout = ({163- children,121+/** A folder's entries as rows, each linking its page at `rev` (a project's home lists its root so). */122+export const EntriesTable = ({123+ entries,124 project,165- sidebar,166- title,125+ rev,126 }: {168- readonly children: ReactNode;127+ readonly entries: readonly CodeEntry[];128 readonly project: ProjectName;170- readonly sidebar?: ReactNode;171- readonly title: string;129+ readonly rev: string;130 }) => (173- <PageShell title={title}>174- <ProjectNav current="code" project={project} />175- <div className="grid min-w-0 gap-6 lg:grid-cols-[18rem_minmax(0,1fr)]">176- {sidebar === undefined ? null : (177- <aside178- aria-label="Files"179- className="max-h-[40dvh] min-w-0 overflow-hidden lg:sticky lg:top-4 lg:max-h-[calc(100dvh-2rem)] lg:self-start"180- >181- {sidebar}182- </aside>183- )}184- <div185- className={`flex min-w-0 flex-col gap-4 ${sidebar === undefined ? "lg:col-span-2" : ""}`}186- >187- {children}188- </div>189- </div>190- </PageShell>131+ <ul className="border-rule flex flex-col border-t" data-entries="">132+ {entries.map((entry) => (133+ <EntryRow entry={entry} key={entry.path} project={project} rev={rev} />134+ ))}135+ </ul>136 );137 138+export interface TreeViewProps {139+ readonly listing: TreeListing;140+ readonly project: ProjectName;141+ readonly rev: string;142+ /** The folder's README, read; absent when it has none. */143+ readonly readme?: FileView | undefined;144+ /** What last changed each entry, by path, once read. */145+ readonly last?: ReadonlyMap<string, CommitView>;146+ readonly now: DateTime.Utc;147+ /** The Files button, below the shell's width. */148+ readonly files?: ReactNode;149+ /** A notice above the folder (the refusal a missing path landed here with). */150+ readonly notice?: ReactNode;151+}152+153 export const TreeView = ({154+ files,155+ last,156 listing,157+ notice,158+ now,159 project,160 readme,161 rev,198- sidebar,199-}: {200- readonly listing: TreeListing;201- readonly project: ProjectName;202- /** The folder's README, read; absent when it has none or it is not read yet. */203- readonly readme?: FileView | undefined;204- readonly rev: string;205- /** The file tree, drawn in the browser. */206- readonly sidebar?: ReactNode;207-}) => (208- <CodeLayout209- project={project}210- sidebar={sidebar}211- title={212- listing.path === undefined213- ? `${project} at ${revLabel(rev)}`214- : `${listing.path} at ${revLabel(rev)}`215- }216- >217- <CodeBreadcrumb path={listing.path} project={project} rev={rev} />218- <EntriesTable entries={listing.entries} project={project} rev={rev} />219- {readme === undefined ? null : (220- <ReadmeSection file={readme} project={project} />221- )}222- </CodeLayout>223-);162+}: TreeViewProps) => {163+ const name = listing.path?.split("/").at(-1) ?? project;164+165+ return (166+ <Workspace167+ crumbs={[168+ { label: project, to: `/${project}` },169+ listing.path === undefined170+ ? { label: "Code" }171+ : { label: "Code", to: `/${project}/tree/main` },172+ ...(listing.path === undefined ? [] : [{ label: name, mono: true }]),173+ ]}174+ title={name}175+ toolbar={176+ <>177+ <FileHeader178+ files={files}179+ path={listing.path}180+ project={project}181+ rev={rev}182+ />183+ <AppLink184+ className="text-ui text-muted-foreground hover:text-foreground tablet:inline hidden shrink-0 no-underline"185+ to={commitsHref(186+ project,187+ rev,188+ listing.path === undefined ? {} : { path: listing.path }189+ )}190+ >191+ History192+ </AppLink>193+ </>194+ }195+ variant="code"196+ >197+ <div className={`${GUTTER} ${MEASURE} flex flex-col gap-8`}>198+ {notice}199+ <ul200+ aria-label={`${name}'s entries`}201+ className="border-rule flex flex-col border-t"202+ data-entries=""203+ >204+ {listing.entries.map((entry) => (205+ <EntryRow206+ entry={entry}207+ key={entry.path}208+ last={last?.get(entry.path)}209+ now={now}210+ project={project}211+ rev={rev}212+ />213+ ))}214+ </ul>215+ {readme === undefined ? null : (216+ <ReadmeSection file={readme} project={project} />217+ )}218+ </div>219+ </Workspace>220+ );221+};added:apps/web/src/features/code/warm.ts+29 added
1+/**2+ * Highlighting a file before its page opens: when a pointer rests on a3+ * link to a file, the router fetches the page's data ahead of the click4+ * (its intent preload), and the file is then highlighted in the worker5+ * pool, so the page draws it at once. Only a file under the highlighting6+ * limit is warmed; past it the page draws plain text anyway. Loaded in the7+ * browser only, on the first such hover.8+ */9+import { diffsOptions } from "./pierre.ts";10+import { workerPool } from "./pool.tsx";11+12+/**13+ * Highlight `file` in the pool ahead of its page, keyed as the page will14+ * draw it; settles once it has (at once for a file not warmed).15+ */16+export const warmFile = (file: {17+ readonly path: string;18+ readonly sha: string;19+ readonly text?: string | undefined;20+}): Promise<void> =>21+ "Worker" in globalThis &&22+ file.text !== undefined &&23+ file.text.length <= diffsOptions.tokenizeMaxLength24+ ? workerPool().primeFileHighlightCache({25+ cacheKey: file.sha,26+ contents: file.text,27+ name: file.path,28+ })29+ : Promise.resolve();added:apps/web/src/features/why/band.tsx+150 added
1+/**2+ * Who put lines there, in one line, ask and answer first and the commit3+ * second: "format-ordinal · answered by bram · 9b1c3e5 · 3 d ago". An4+ * ask's opening reads "opened format-ordinal · by ines-v · …"; a decider's5+ * own landing "landed by okonkwo · …"; a commit the project adopted, its6+ * subject and author, "before adoption". Each part is a link: the ask, the7+ * answer, the commit. No credit count and no colour by age: neither is a8+ * state.9+ *10+ * Used by a why group's band, and by a file's facts for the landing that11+ * last touched it.12+ */13+import type { CommitView } from "@repo/protocol/domain/code";14+import type { LandingView } from "@repo/protocol/domain/landing";15+import type { ProjectName } from "@repo/protocol/ids";16+import { Option } from "effect";17+import type { DateTime } from "effect";18+import { Fragment } from "react";19+import type { ReactElement } from "react";20+21+import { commitHref, shortSha } from "../code/paths.ts";22+import { AppLink } from "../shared/link.tsx";23+import { answerPath, askPath, personPath } from "../shared/paths.ts";24+import { When } from "../shared/time.tsx";25+import { askOf } from "./rows.ts";26+27+const LINK = "decoration-rule underline hover:decoration-current";28+29+const CODE_LINK = `text-mono font-mono ${LINK}`;30+31+/** Parts parted by a muted ` · `. */32+const Parted = ({ parts }: { readonly parts: readonly ReactElement[] }) =>33+ parts.map((part, index) => (34+ <Fragment key={String(part.key)}>35+ {index === 0 ? null : (36+ <span aria-hidden="true" className="text-muted-foreground">37+ {" · "}38+ </span>39+ )}40+ {part}41+ </Fragment>42+ ));43+44+/** What the landing did, ask first: answered, opened, or landed by a decider. */45+const landingParts = (46+ landing: LandingView,47+ project: ProjectName48+): readonly ReactElement[] => {49+ const linked = Option.getOrUndefined(askOf(landing));50+51+ if (linked === undefined) {52+ return [53+ <span key="by">54+ landed by{" "}55+ <AppLink className={LINK} to={personPath(landing.author)}>56+ {landing.author}57+ </AppLink>58+ </span>,59+ ];60+ }61+62+ if (linked.kind === "opened") {63+ return [64+ <span key="ask">65+ opened{" "}66+ <AppLink className={CODE_LINK} to={askPath(project, linked.ask)}>67+ {linked.ask}68+ </AppLink>69+ </span>,70+ <span key="by">71+ by{" "}72+ <AppLink className={LINK} to={personPath(landing.author)}>73+ {landing.author}74+ </AppLink>75+ </span>,76+ ];77+ }78+79+ return [80+ <AppLink className={CODE_LINK} key="ask" to={askPath(project, linked.ask)}>81+ {linked.ask}82+ </AppLink>,83+ <AppLink className={LINK} key="answer" to={answerPath(project, linked.ask)}>84+ answered by {landing.author}85+ </AppLink>,86+ ];87+};88+89+/** A commit the project adopted: its subject, its author, and that it came before adoption. */90+const adoptedParts = (91+ commit: CommitView | undefined92+): readonly ReactElement[] => {93+ const subject = commit?.subject ?? "";94+95+ return [96+ <span className="min-w-0" key="subject">97+ {subject === "" ? "(no subject)" : subject}98+ </span>,99+ <span key="author">{commit?.author.name ?? "unknown"}</span>,100+ <span className="text-muted-foreground" key="adopted">101+ before adoption102+ </span>,103+ ];104+};105+106+/** The line for a commit, and its landing when the platform landed it. */107+export const LandingWords = ({108+ commit,109+ landing,110+ now,111+ project,112+ sha,113+}: {114+ readonly project: ProjectName;115+ /** The commit's id (all a line has when the walk did not return the commit). */116+ readonly sha: string;117+ readonly commit: Option.Option<CommitView>;118+ readonly landing: Option.Option<LandingView>;119+ readonly now: DateTime.Utc;120+}) => {121+ const landed = Option.getOrUndefined(landing);122+ const adopted = Option.getOrUndefined(commit);123+ const at = landed?.landedAt ?? adopted?.committer.at;124+125+ const what =126+ landed === undefined127+ ? adoptedParts(adopted)128+ : landingParts(landed, project);129+130+ const when =131+ at === undefined132+ ? []133+ : [134+ <span className="text-muted-foreground tabular-nums" key="when">135+ <When at={at} now={now} />136+ </span>,137+ ];138+139+ return (140+ <Parted141+ parts={[142+ ...what,143+ <AppLink className={CODE_LINK} key="sha" to={commitHref(project, sha)}>144+ {shortSha(sha)}145+ </AppLink>,146+ ...when,147+ ]}148+ />149+ );150+};modified:apps/web/src/features/why/range-summary.tsx+69 added-162 removed
1 /**2- * One range's line of "why", shared by the server's table and the3- * browser's annotation rows: for a landing, "<subject> · <ask> answer ·4- * <author> · <n> credits · <verdict>", linking the commit, the ask, its5- * answer and the author (an ask's opening reads "Open ask <ask>" instead,6- * linking the ask alone: it answers nothing); for a commit the project7- * adopted, "<subject> · <author> · before adoption". Then where to go from here: the file before this commit, and8- * the propose form about the range's first line. `LandingDetails` is the9- * whole landing, for the line dialog.2+ * A why group's band, shared by the server's plain text and the browser's3+ * annotation rows: who put these lines there, ask and answer first4+ * (`band.tsx`), then where to go from here: why, one step back (the same5+ * page at the commit's parent) and a proposal about the group's first6+ * line. `LandingDetails` is the landing whole, for the line dialog.7 */8 import type { WhyView } from "@repo/protocol/domain/code";9 import type { LandingView } from "@repo/protocol/domain/landing";10 import type { ProjectName } from "@repo/protocol/ids";11 import { DateTime, Option } from "effect";12 13 import { commitHref, shortSha } from "../code/paths.ts";17-import { ID, LABEL, LINK } from "../shared/classes.ts";14 import { CreditTrailers } from "../shared/credits.tsx";15 import { HandleLink } from "../shared/handle.tsx";16+import { AppLink } from "../shared/link.tsx";17 import { answerPath, askPath } from "../shared/paths.ts";18+import { LandingWords } from "./band.tsx";19 import {20 askOf,23- creditWords,21+ linesWords,22 priorHref,23 proposeHref,24 verdictWords,25 } from "./rows.ts";28-import type { LandingAsk, WhyRow } from "./rows.ts";26+import type { WhyRow } from "./rows.ts";27 30-const DOT = (31- <span aria-hidden="true" className="text-muted-foreground">32- ·33- </span>34-);28+const LINK = "decoration-rule underline hover:decoration-current";29 36-/** The ask a landing links, as its id linking the ask's page. */37-const AskLink = ({38- linked,39- project,40-}: {41- readonly linked: LandingAsk;42- readonly project: ProjectName;43-}) => (44- <a className={`${ID} ${LINK}`} href={askPath(project, linked.ask)}>45- {linked.ask}46- </a>47-);30+const LABEL = "text-label text-muted-foreground";31 49-/** The words an opening's own commit subject says, which its row need not say again. */50-const openingWords = (ask: string) => `Open ask ${ask}`;51-52-/**53- * The ask a landing links: "<ask> answer" for the one it answers, with its54- * answer's page; "Open ask <ask>" for the one it opened, which has none, or55- * the ask alone when the commit's subject (`subject`) already says so.56- */57-const AskLinks = ({58- linked,32+/** Where to go from a group: why one step back, and a proposal about its first line. */33+export const BandLinks = ({34 project,60- subject,61-}: {62- readonly linked: LandingAsk;63- readonly project: ProjectName;64- readonly subject?: string;65-}) => {66- const ask = <AskLink linked={linked} project={project} />;67-68- if (linked.kind === "opened") {69- return subject === openingWords(linked.ask) ? (70- ask71- ) : (72- <span>Open ask {ask}</span>73- );74- }75-76- return (77- <>78- {ask}79- <a className={LINK} href={answerPath(project, linked.ask)}>80- answer81- </a>82- </>83- );84-};85-86-/** "· <author> · before adoption", for a commit the project adopted. */87-const Adopted = ({ author }: { readonly author: string }) => (88- <>89- {DOT}90- <span>{author}</span>91- {DOT}92- <span className="text-muted-foreground">before adoption</span>93- </>94-);95-96-/**97- * "· <ask> answer · <author> · <n> credits · <verdict>" for a landing, or98- * "· Open ask <ask> · …" for an ask's opening.99- */100-const Landed = ({101- landing,102- project,103- subject,104-}: {105- readonly landing: LandingView;106- readonly project: ProjectName;107- readonly subject: string;108-}) => {109- const verdict = Option.getOrUndefined(verdictWords(landing));110- const linked = Option.getOrUndefined(askOf(landing));111-112- return (113- <>114- {linked === undefined ? null : (115- <>116- {DOT}117- <AskLinks linked={linked} project={project} subject={subject} />118- </>119- )}120- {DOT}121- <HandleLink handle={landing.author} />122- {DOT}123- <span>{creditWords(landing.credits.length)}</span>124- {verdict === undefined ? null : (125- <>126- {DOT}127- <span data-outcome={landing.verdict?.outcome._tag}>{verdict}</span>128- </>129- )}130- </>131- );132-};133-134-/** "<subject> · <author> · …" for one range. */135-export const RangeSummary = ({136- project,35 row,138-}: {139- readonly project: ProjectName;140- readonly row: WhyRow;141-}) => {142- const commit = Option.getOrUndefined(row.commit);143- const landing = Option.getOrUndefined(row.landing);144- const subject = commit?.subject ?? shortSha(row.range.sha);145-146- return (147- <span className="flex flex-wrap items-baseline gap-x-2 gap-y-1">148- <a149- className={`${LINK} font-medium [overflow-wrap:anywhere]`}150- href={commitHref(project, row.range.sha)}151- >152- {subject === "" ? "(no subject)" : subject}153- </a>154- {landing === undefined ? (155- <Adopted author={commit?.author.name ?? "unknown"} />156- ) : (157- <Landed landing={landing} project={project} subject={subject} />158- )}159- </span>160- );161-};162-163-/** Where to go from a range: the file before its commit, and a proposal about its first line. */164-export const RangeLinks = ({165- line,166- project,167- row,36 view,37 }: {170- readonly line: number;38 readonly project: ProjectName;39 readonly row: WhyRow;40 readonly view: WhyView;41 }) => {3 unmodified lines45 )46 );47 48 return (182- <span className="flex flex-wrap gap-x-4 gap-y-1 text-xs">49+ <span className="text-label text-muted-foreground flex flex-wrap gap-x-4 gap-y-0.5 font-normal">50+ <a className={LINK} href={`#L${row.range.start}`}>51+ {linesWords(row.range)}52+ </a>53 {prior === undefined ? null : (184- <a className={LINK} href={prior}>185- {Option.isSome(row.landing)186- ? "Prior to this landing"187- : "Prior to this commit"}188- </a>54+ <AppLink className={LINK} to={prior}>55+ why, one step back56+ </AppLink>57 )}58 <a59 className={LINK}192- href={proposeHref(project, { at: view.at, line, path: view.path })}60+ href={proposeHref(project, {61+ at: view.at,62+ line: row.range.start,63+ path: view.path,64+ })}65 >66 Propose an ask about this line67 </a>68 </span>69 );70 };71 72+/** One group's band: who put its lines there, then where to go from here. */73+export const WhyBand = ({74+ now,75+ project,76+ row,77+ view,78+}: {79+ readonly now: DateTime.Utc;80+ readonly project: ProjectName;81+ readonly row: WhyRow;82+ readonly view: WhyView;83+}) => (84+ <div85+ className="border-rule bg-surface text-ui flex min-h-14 flex-col justify-center gap-0.5 border-y px-3 py-1.5 font-sans"86+ data-range={`${row.range.start}-${row.range.end}`}87+ >88+ <p className="min-w-0 [overflow-wrap:anywhere]">89+ <LandingWords90+ commit={row.commit}91+ landing={row.landing}92+ now={now}93+ project={project}94+ sha={row.range.sha}95+ />96+ </p>97+ <BandLinks project={project} row={row} view={view} />98+ </div>99+);100+101 /** A landing whole: its ask, author, verdict, when it landed, its credit and agents. */102 export const LandingDetails = ({103 landing,104 project,4 unmodified lines109 const verdict = verdictWords(landing);110 const linked = Option.getOrUndefined(askOf(landing));111 112 return (212- <div className="flex flex-col gap-3 text-sm">113+ <div className="text-ui flex flex-col gap-3">114 <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1">115 {linked === undefined ? null : (116 <>117 <dt className={LABEL}>118 {linked.kind === "opened" ? "Opened ask" : "Ask"}119 </dt>120 <dd className="flex gap-2">220- {linked.kind === "opened" ? (221- <AskLink linked={linked} project={project} />222- ) : (223- <AskLinks linked={linked} project={project} />121+ <AppLink122+ className={`text-mono font-mono ${LINK}`}123+ to={askPath(project, linked.ask)}124+ >125+ {linked.ask}126+ </AppLink>127+ {linked.kind === "opened" ? null : (128+ <AppLink className={LINK} to={answerPath(project, linked.ask)}>129+ answer130+ </AppLink>131 )}132 </dd>133 </>134 )}8 unmodified lines143 </>144 )}145 <dt className={LABEL}>Landed</dt>146 <dd>240- <a241- className={`${ID} ${LINK}`}242- href={commitHref(project, landing.sha)}147+ <AppLink148+ className={`text-mono font-mono ${LINK}`}149+ to={commitHref(project, landing.sha)}150 >151 {shortSha(landing.sha)}245- </a>{" "}152+ </AppLink>{" "}153 on {DateTime.formatIsoDateUtc(landing.landedAt)}154 </dd>155 </dl>156 <CreditTrailers9 unmodified linesmodified:apps/web/src/features/why/rows.ts+27 added-4 removed
33 unmodified lines34 range,35 }));36 };37 38+/**39+ * The view's lines grouped by what brought them: consecutive ranges from40+ * one commit form one group, so a landing's lines read as one band.41+ */42+export const groupsOf = (view: WhyView): readonly WhyRow[] => {43+ const groups: WhyRow[] = [];44+45+ for (const row of rowsOf(view)) {46+ const last = groups.at(-1);47+48+ if (49+ last !== undefined &&50+ last.range.sha === row.range.sha &&51+ last.range.end + 1 === row.range.start52+ ) {53+ groups[groups.length - 1] = {54+ ...last,55+ range: { ...last.range, end: row.range.end },56+ };57+ } else {58+ groups.push(row);59+ }60+ }61+62+ return groups;63+};64+65 /** The row holding line `line`, numbered from 1. */66 export const rowAt = (rows: readonly WhyRow[], line: number) =>67 Option.fromUndefinedOr(68 rows.find(({ range }) => range.start <= line && line <= range.end)23 unmodified lines92 (ask): LandingAsk => ({ ask, kind: "opened" })93 );94 };95 69-/** A count of credit as a reader says it. */70-export const creditWords = (count: number) =>71- `${count} ${count === 1 ? "credit" : "credits"}`;72-96 const isLanded = Outcome.isAnyOf(["Landed"]);97 98 /** A landing's verdict in a word or two; none when it carries none. */99 export const verdictWords = (landing: LandingView) =>27 unmodified linesmodified:apps/web/src/features/why/why-code.tsx+40 added-41 removed
1 /**2- * The file drawn by `@pierre/diffs`, with one annotation row above each3- * range of lines saying which landing (or adopted commit) brought it: an4- * annotation renders after its `lineNumber`, so a range starting at line5- * `n` sits at `n - 1`, and `0` is above line 1. Clicking a line number6- * opens a dialog with that line's landing whole.2+ * The file drawn by `@pierre/diffs`, with a band above each group of lines3+ * one commit brought (`WhyBand`, the same the server's plain lines carry):4+ * an annotation renders after its `lineNumber`, so a group starting at5+ * line `n` sits at `n - 1`, and `0` is above line 1. Highlighting runs in6+ * the worker pool. Clicking a line number opens a dialog with that line's7+ * landing whole.8 *9 * It is Pierre's `File` (as `code-view.tsx` draws a file), which renders10 * on the server too, so its markup can be checked; the page loads it only11 * in the browser (`client-why.tsx`), and the Worker never bundles it.2 unmodified lines14 import type { FileOptions, LineAnnotation } from "@pierre/diffs/react";15 import type { WhyView } from "@repo/protocol/domain/code";16 import type { ProjectName } from "@repo/protocol/ids";17 import { Option } from "effect";18+import type { DateTime } from "effect";19 import { useMemo, useState } from "react";20 21 import {22 Dialog,4 unmodified lines27 } from "@/components/ui/dialog";28 29 import { shortSha } from "../code/paths.ts";30 import { diffsOptions, registerCodeTheme } from "../code/pierre.ts";29-import { LandingDetails, RangeLinks, RangeSummary } from "./range-summary.tsx";30-import { linesWords, rowAt, rowsOf } from "./rows.ts";31+import { CodePool } from "../code/pool.tsx";32+import { BandLinks, LandingDetails, WhyBand } from "./range-summary.tsx";33+import { groupsOf, linesWords, rowAt, rowsOf } from "./rows.ts";34 import type { WhyRow } from "./rows.ts";35 36 registerCodeTheme();37 35-/** Past this many characters a file is drawn without highlighting. */36-const HIGHLIGHT_LIMIT = 300_000;37-38 export interface WhyCodeProps {39+ readonly now: DateTime.Utc;40 readonly project: ProjectName;41 /** The file's text at `view.at`. */42 readonly text: string;43 readonly view: WhyView;26 unmodified lines70 <DialogTitle>71 Line {line} ({linesWords(row.range)})72 </DialogTitle>73 <DialogDescription>73- <RangeSummary project={project} row={row} />74+ Who put this line there, and the landing whole.75 </DialogDescription>76 </DialogHeader>77 {Option.isSome(row.landing) ? (78 <LandingDetails landing={row.landing.value} project={project} />2 unmodified lines81 Commit {shortSha(row.range.sha)} came in with the history the project82 adopted, so no landing records who asked for it.83 </p>84 )}84- <RangeLinks line={line} project={project} row={row} view={view} />85+ <BandLinks project={project} row={row} view={view} />86 </DialogContent>87 </Dialog>88 );89 89-export const WhyCode = ({ project, text, view }: WhyCodeProps) => {90+export const WhyCode = ({ now, project, text, view }: WhyCodeProps) => {91 const [line, setLine] = useState<number | null>(null);92 const rows = useMemo(() => rowsOf(view), [view]);93+ const groups = useMemo(() => groupsOf(view), [view]);94 95 const file = useMemo(96 () => ({97 cacheKey: `why:${view.at}:${view.path}`,4 unmodified lines102 );103 104 const annotations = useMemo(105 (): LineAnnotation<WhyRow>[] =>104- rows.map((row) => ({ lineNumber: row.range.start - 1, metadata: row })),105- [rows]106+ groups.map((row) => ({ lineNumber: row.range.start - 1, metadata: row })),107+ [groups]108 );109 110 const options = useMemo(111 (): FileOptions<WhyRow, undefined> => ({112 ...diffsOptions,113+ disableFileHeader: true,114 lineHoverHighlight: "number",115 onLineNumberClick: ({ lineNumber }) => {116 setLine(lineNumber);117 },118 overflow: "scroll",116- tokenizeMaxLength: HIGHLIGHT_LIMIT,119 }),120 []121 );122 123 const clicked = line === null ? Option.none() : rowAt(rows, line);124 125 return (124- <div className="border-rule min-w-0 border" data-code="pierre">125- <File126- file={file}127- lineAnnotations={annotations}128- options={options}129- renderAnnotation={({ metadata }) => (130- <div131- className="border-rule bg-surface border-y px-3 py-1.5 text-xs"132- data-range={`${metadata.range.start}-${metadata.range.end}`}133- >134- <RangeSummary project={project} row={metadata} />135- </div>136- )}137- />138- {line === null || Option.isNone(clicked) ? null : (139- <LineDialog140- line={line}141- onClose={() => {142- setLine(null);143- }}144- project={project}145- row={clicked.value}146- view={view}126+ <CodePool>127+ <div className="min-w-0" data-code="pierre" data-why="ranges">128+ <File129+ file={file}130+ lineAnnotations={annotations}131+ options={options}132+ renderAnnotation={({ metadata }) => (133+ <WhyBand now={now} project={project} row={metadata} view={view} />134+ )}135 />136+ {line === null || Option.isNone(clicked) ? null : (137+ <LineDialog138+ line={line}139+ onClose={() => {140+ setLine(null);141+ }}142+ project={project}143+ row={clicked.value}144+ view={view}145+ />148- )}149- </div>146+ )}147+ </div>148+ </CodePool>149 );150 };151 152 // `React.lazy` takes a module's default export.1 unmodified linemodified:apps/web/src/features/why/why-view.tsx+131 added-124 removed
1 /**2- * Why each line of a file is there (ADR 0019). The server sends a table3- * of ranges (lines a–b → the landing or the commit that brought them)4- * beside the file's numbered lines; the browser then draws the file with5- * one row above each range (`code`, from `client-why.tsx`), where clicking6- * a line number opens that line's landing. A file the walk cannot read as7- * text (binary, or past 1 MiB) has no ranges, and the page says so.2+ * A file in Why mode (ADR 0019): the same page as its Code mode, the code3+ * with a band above each group of lines one commit brought, saying who4+ * put them there, ask and answer first and the commit second, with why,5+ * one step back. The server sends the bands among numbered plain lines;6+ * the browser draws the file highlighted with the same bands as Pierre's7+ * annotations (`code`, from `client-why.tsx`), where pressing a line8+ * number opens that line's landing whole.9+ *10+ * A file the walk cannot read as text (binary, or past 1 MiB) has no11+ * groups, and the page says so.12 */9-import type { WhyView } from "@repo/protocol/domain/code";13+import type { CommitView, FileView, WhyView } from "@repo/protocol/domain/code";14 import type { ProjectName } from "@repo/protocol/ids";15+import type { DateTime } from "effect";16 import type { ReactNode } from "react";17 13-import { buttonVariants } from "@/components/ui/button";18+import { FileFacts } from "../code/file-facts.tsx";19+import { FileHeader, PermalinkKey } from "../code/file-header.tsx";20+import { NumberedLines } from "../code/numbered-lines.tsx";21+import { blobHref, commitHref, shortSha, whyHref } from "../code/paths.ts";22+import { AppLink } from "../shared/link.tsx";23+import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";24+import { WhyBand } from "./range-summary.tsx";25+import { groupsOf } from "./rows.ts";26 15-import { NumberedLines } from "../code/blob-view.tsx";16-import { blobHref, commitHref, commitsHref, shortSha } from "../code/paths.ts";17-import { revLabel } from "../code/rev.ts";18-import { CodeBreadcrumb, CodeLayout } from "../code/tree-view.tsx";19-import { LINK } from "../shared/classes.ts";20-import { RangeLinks, RangeSummary } from "./range-summary.tsx";21-import { linesWords, rowsOf } from "./rows.ts";27+const LINK = "decoration-rule underline hover:decoration-current";28 23-const TOOL = buttonVariants({24- className: "no-underline",25- size: "sm",26- variant: "ghost",27-});28-29-/** The ranges as a table: lines a–b, then who and why. */30-export const WhyTable = ({29+/** The page's fallback: the numbered lines, each group's band above its first line. */30+export const WhyFallback = ({31+ now,32 project,33+ text,34 view,35 }: {36+ readonly now: DateTime.Utc;37 readonly project: ProjectName;38+ readonly text: string;39 readonly view: WhyView;40 }) => (37- <table className="w-full border-collapse text-sm" data-why="ranges">38- <thead className="sr-only">39- <tr>40- <th scope="col">Lines</th>41- <th scope="col">Brought by</th>42- </tr>43- </thead>44- <tbody>45- {rowsOf(view).map((row) => (46- <tr47- className="border-rule border-t align-top"48- data-range={`${row.range.start}-${row.range.end}`}49- key={row.range.start}50- >51- <td className="py-2 pr-4 whitespace-nowrap">52- <a className={LINK} href={`#L${row.range.start}`}>53- {linesWords(row.range)}54- </a>55- </td>56- <td className="flex flex-col gap-1 py-2">57- <RangeSummary project={project} row={row} />58- <RangeLinks59- line={row.range.start}41+ <div data-why="ranges">42+ <NumberedLines43+ bands={44+ new Map(45+ groupsOf(view).map((row) => [46+ row.range.start,47+ <WhyBand48+ key={row.range.start}49+ now={now}50 project={project}51 row={row}52 view={view}63- />64- </td>65- </tr>66- ))}67- </tbody>68- </table>53+ />,54+ ])55+ )56+ }57+ text={text}58+ />59+ </div>60 );61 71-/** The page's fallback: the table of ranges beside the numbered lines. */72-export const WhyFallback = ({73- project,74- text,75- view,76-}: {62+export interface WhyLinesProps {63 readonly project: ProjectName;78- readonly text: string;64+ readonly rev: string;65 readonly view: WhyView;80-}) => (81- <div className="grid min-w-0 gap-4 xl:grid-cols-[minmax(0,26rem)_minmax(0,1fr)]">82- <WhyTable project={project} view={view} />83- <NumberedLines text={text} />84- </div>85-);66+ readonly now: DateTime.Utc;67+ /** The file at `view.at`: its words, its bytes; absent when it could not be read. */68+ readonly file?: FileView | undefined;69+ /** The file's text at `view.at`; absent for a binary or too large file. */70+ readonly text?: string;71+ /** The browser's drawing, holding `WhyFallback` as its fallback. */72+ readonly code?: ReactNode;73+ /** The commit that last changed the file. */74+ readonly last?: CommitView | undefined;75+ /** The Files button, below the shell's width. */76+ readonly files?: ReactNode;77+}78 79 export const WhyLines = ({80 code,81+ file,82+ files,83+ last,84+ now,85 project,86 rev,87 text,88 view,93-}: {94- /** The browser's drawing, holding `WhyFallback` as its fallback. */95- readonly code?: ReactNode;96- readonly project: ProjectName;97- readonly rev: string;98- /** The file's text at `view.at`; absent for a binary or too large file. */99- readonly text?: string;100- readonly view: WhyView;101-}) => (102- <CodeLayout project={project} title={`Why ${view.path} at ${revLabel(rev)}`}>103- <CodeBreadcrumb path={view.path} project={project} rev={rev} />104- <div className="text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">105- <span>106- Why each line is there, at{" "}107- <a108- className={`font-mono text-[0.8125rem] ${LINK}`}109- href={commitHref(project, view.at)}110- >111- {shortSha(view.at)}112- </a>113- </span>114- <nav aria-label="File" className="flex flex-wrap gap-1">115- <a className={TOOL} href={blobHref(project, rev, view.path)}>116- File117- </a>118- <a119- className={TOOL}120- href={commitsHref(project, rev, { path: view.path })}121- >122- History123- </a>124- </nav>125- </div>126- {view.stoppedAt === undefined ? null : (127- <p className="text-muted-foreground text-sm">128- The walk stopped after 200 commits: lines older than{" "}129- <a130- className={`font-mono text-[0.8125rem] ${LINK}`}131- href={commitHref(project, view.stoppedAt)}132- >133- {shortSha(view.stoppedAt)}134- </a>{" "}135- point at it.136- </p>137- )}138- {view.ranges.length === 0 || text === undefined ? (139- <p className="border-rule border border-dashed px-4 py-5 text-sm">140- {text === ""141- ? "This file is empty."142- : "This file is binary or too large to say why each line is there."}{" "}143- <a className={LINK} href={blobHref(project, view.at, view.path)}>144- View the file145- </a>146- </p>147- ) : (148- (code ?? <WhyFallback project={project} text={text} view={view} />)149- )}150- </CodeLayout>151-);89+}: WhyLinesProps) => {90+ const name = view.path.split("/").at(-1) ?? view.path;91+92+ return (93+ <Workspace94+ crumbs={[95+ { label: project, to: `/${project}` },96+ { label: "Code", to: `/${project}/tree/main` },97+ { label: name, mono: true },98+ ]}99+ facts={100+ file === undefined ? undefined : (101+ <FileFacts102+ file={file}103+ last={last}104+ now={now}105+ project={project}106+ rev={rev}107+ />108+ )109+ }110+ factsHeading="This file"111+ title={name}112+ toolbar={113+ <FileHeader114+ files={files}115+ mode="why"116+ path={view.path}117+ project={project}118+ rev={rev}119+ {...(file === undefined ? {} : { file })}120+ />121+ }122+ variant="code"123+ >124+ <PermalinkKey href={whyHref(project, view.at, view.path)} />125+ {view.stoppedAt === undefined ? null : (126+ <p className={`${GUTTER} ${MEASURE} text-ui text-muted-foreground`}>127+ The walk stopped after 200 commits: lines older than{" "}128+ <AppLink129+ className={`text-mono font-mono ${LINK}`}130+ to={commitHref(project, view.stoppedAt)}131+ >132+ {shortSha(view.stoppedAt)}133+ </AppLink>{" "}134+ point at it.135+ </p>136+ )}137+ {view.ranges.length === 0 || text === undefined ? (138+ <div className={`${GUTTER} ${MEASURE}`}>139+ <p className="border-rule text-ui border border-dashed px-4 py-5">140+ {text === ""141+ ? "This file is empty."142+ : "This file is binary or too large to say why each line is there."}{" "}143+ <AppLink144+ className={LINK}145+ to={blobHref(project, view.at, view.path)}146+ >147+ View the file148+ </AppLink>149+ </p>150+ </div>151+ ) : (152+ (code ?? (153+ <WhyFallback now={now} project={project} text={text} view={view} />154+ ))155+ )}156+ </Workspace>157+ );158+};modified:apps/web/src/routes/$project/blob/$rev/$.tsx+67 added-25 removed
1 import { Client } from "@repo/protocol/contracts";2-import { FileView } from "@repo/protocol/domain/code";2+import { CommitView, FileView } from "@repo/protocol/domain/code";3 import { ProjectName } from "@repo/protocol/ids";4 import { createFileRoute, notFound } from "@tanstack/react-router";5 import { createServerFn } from "@tanstack/react-start";6 import { env } from "cloudflare:workers";7-import { Effect, Schema } from "effect";7+import { DateTime, Effect, Option, Schema } from "effect";8 9 import {10 projectOf,11 repoPathOf,12 revisionOf,13 } from "../../../../features/code/address.ts";14-import {15- BlobView,16- NumberedLines,17-} from "../../../../features/code/blob-view.tsx";14+import { BlobView } from "../../../../features/code/blob-view.tsx";15 import { ClientFile } from "../../../../features/code/client-code.tsx";16 import { CodeNotFound } from "../../../../features/code/not-found.tsx";17+import { NumberedLines } from "../../../../features/code/numbered-lines.tsx";18 import { pageHead } from "../../../../features/shared/head.ts";19 import { notFoundFor } from "../../../../features/shared/refusals.ts";20 import { serverClient } from "../../../../server/client.ts";23-import { PathsTree } from "../../tree/-paths-tree.tsx";21+import { CodeRail } from "../../tree/-code-rail.tsx";22+import { FilesButton } from "../../tree/-files-button.tsx";23+import { codePageHeaders } from "../../tree/-headers.ts";24+import { softLanding } from "../../tree/-soft-landing.ts";25 25-// A file at a revision, read on the server: its text arrives as numbered,26-// anchored lines, and the browser then draws it highlighted, with the27-// `#L10-L20` selection kept in the address. `?plain=1` shows a Markdown28-// file's source. An address naming no project, revision or file is a 40429-// showing the platform's refusal.26+// A file at a revision, read on the server with the commit that last27+// changed it: its text arrives as numbered, anchored lines, and the28+// browser then draws it highlighted, the `#L10-L20` selection kept in the29+// address. `?plain=1` shows a Markdown file's source. A path missing at a30+// revision that exists lands on the nearest folder above it; any other31+// address naming nothing is a 404 showing the platform's refusal.32 33 const BlobPageData = Schema.Struct({34 file: FileView,35+ last: Schema.optionalKey(CommitView),36+ now: Schema.DateTimeUtcFromString,37 project: ProjectName,38 rev: Schema.String,39 });40 10 unmodified lines51 const rev = yield* Effect.fromOption(revisionOf(params.rev));52 const path = yield* Effect.fromOption(repoPathOf(params._splat));53 const client = yield* Client;54 51- const file = yield* client.readFile({ at: rev, path, project }).pipe(55+ // The file and the commit that last changed it, at once; that commit56+ // is only a fact beside the file, so the page goes without it.57+ const [file, history] = yield* Effect.all(58+ [59+ client.readFile({ at: rev, path, project }),60+ client.log({ at: rev, limit: 1, path, project }).pipe(Effect.option),61+ ],62+ { concurrency: 2 }63+ ).pipe(64 Effect.catchTags({53- UnknownPath: notFoundFor,65+ UnknownPath: (refusal) => softLanding(refusal, project, rev),66 UnknownProject: notFoundFor,67 UnknownRevision: notFoundFor,68 })69 );70 71+ const last = Option.flatMap(history, ({ commits }) =>72+ Option.fromUndefinedOr(commits[0])73+ );74+59- return yield* Schema.encodeEffect(BlobPageData)({ file, project, rev });75+ return yield* Schema.encodeEffect(BlobPageData)({76+ file,77+ now: yield* DateTime.now,78+ project,79+ rev,80+ ...Option.match(last, {81+ onNone: () => ({}),82+ onSome: (commit) => ({ last: commit }),83+ }),84+ });85 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));86 87 const blobPage = createServerFn({ method: "GET" })88 .validator((params: BlobParams) => params)3 unmodified lines92 )93 );94 95 const BlobPage = () => {71- const { file, project, rev } = Schema.decodeSync(BlobPageData)(96+ const { file, last, now, project, rev } = Schema.decodeSync(BlobPageData)(97 Route.useLoaderData()98 );99 100 const plain = Route.useSearch().plain === 1;3 unmodified lines104 code={105 file.text === undefined ? undefined : (106 <ClientFile107 fallback={<NumberedLines text={file.text} />}108+ key={file.sha}109 path={file.path}110 sha={file.sha}111 text={file.text}112 />113 )114 }115 file={file}116+ files={<FilesButton />}117+ last={last}118+ now={now}119 plain={plain}120 project={project}121 rev={rev}93- sidebar={94- <PathsTree95- at={file.at}96- current={file.path}97- project={project}98- rev={rev}99- />100- }122 />123 );124 };125 126 export const Route = createFileRoute("/$project/blob/$rev/$")({127+ staticData: { rail: CodeRail },128 // The router writes back what this returns, dropping only `undefined`,129 // so a rendered file's address carries no `plain`.130 validateSearch: ({ plain }: { readonly plain?: unknown }) => ({131 plain: plain === 1 || plain === "1" ? (1 as const) : undefined,132 }),111- loader: ({ params }) => blobPage({ data: params }),133+ loader: ({ params, preload }) => {134+ const page = blobPage({ data: params });135+136+ // A hover's preload warms the file's highlighting too, so the click137+ // draws it at once; a failed read or warm-up changes nothing here.138+ if (preload && !import.meta.env.SSR) {139+ Effect.runFork(140+ Effect.tryPromise(() =>141+ Promise.all([page, import("../../../../features/code/warm.ts")])142+ ).pipe(143+ Effect.flatMap(([data, { warmFile }]) =>144+ Effect.tryPromise(() => warmFile(data.file))145+ ),146+ Effect.ignore147+ )148+ );149+ }150+151+ return page;152+ },153+ headers: ({ params }) => codePageHeaders(params.rev),154 head: ({ params: { _splat, project, rev } }) =>155 pageHead({ title: `${_splat ?? project} at ${rev}` }),156 component: BlobPage,157 notFoundComponent: CodeNotFound,1 unmodified linemodified:apps/web/src/routes/$project/commit/$sha.tsx+110 added-38 removed
1 import { Client } from "@repo/protocol/contracts";2-import { CommitDiff } from "@repo/protocol/domain/code";3-import { ProjectName } from "@repo/protocol/ids";4-import { createFileRoute, notFound } from "@tanstack/react-router";2+import { createFileRoute, notFound, useRouter } from "@tanstack/react-router";3 import { createServerFn } from "@tanstack/react-start";4 import { env } from "cloudflare:workers";7-import { DateTime, Effect, Schema } from "effect";5+import { DateTime, Effect, Option, Schema } from "effect";6+import { useCallback, useMemo, useState } from "react";7 8 import { commitOf, projectOf } from "../../../features/code/address.ts";9 import { ClientDiffs } from "../../../features/code/client-code.tsx";11-import { ClientTree } from "../../../features/code/client-tree.tsx";12-import {13- ChangedList,14- CommitView,15-} from "../../../features/code/commit-view.tsx";10+import { CommitView } from "../../../features/code/commit-view.tsx";11+import { drawnFiles } from "../../../features/code/diff-model.ts";12+import { PANE_SCROLLER } from "../../../features/code/diff-pane.tsx";13+import { SPLIT_QUERY, useMedia } from "../../../features/code/media.ts";14 import { CodeNotFound } from "../../../features/code/not-found.tsx";17-import { diffAnchor } from "../../../features/code/paths.ts";15+import { PlainDiff } from "../../../features/code/plain-diff.tsx";16 import { pageHead } from "../../../features/shared/head.ts";17 import { notFoundFor } from "../../../features/shared/refusals.ts";18+import { immutablePage } from "../../../server/cache-headers.ts";19 import { serverClient } from "../../../server/client.ts";20+import { CommitRail } from "../tree/-code-rail.tsx";21+import { CommitPageData } from "../tree/-commit-files.ts";22+import { FilesButton } from "../tree/-files-button.tsx";23 22-// One commit and what it changed, read on the server: the browser then23-// draws the changed files as a tree (marked added, modified or deleted)24-// beside their diffs, unified unless `?style=split`.24+// One commit and what it changed, read on the server, with the territory25+// of the ask it answered (the diff's stats split by it): the page arrives26+// with the landing and the diff as plain text, and the browser draws the27+// diff over it, the changed files as a tree in the rail. A commit never28+// changes, so neither does its page: it is kept for good, and the router29+// never reads it again.30 26-const CommitPageData = Schema.Struct({27- diff: CommitDiff,28- now: Schema.DateTimeUtcFromString,29- project: ProjectName,30-});31-31 interface CommitParams {32 readonly project: string;33 readonly sha: string;34 }11 unmodified lines46 UnknownProject: notFoundFor,47 })48 );49 50+ // The ask the landing answered, for its territory; a page without it51+ // splits its stats into tests and the rest.52+ const answered = Option.fromUndefinedOr(diff.commit.landing?.ask);53+54+ const territory = Option.isNone(answered)55+ ? Option.none()56+ : yield* client.showAsk({ ask: answered.value, project }).pipe(57+ Effect.map(({ ask }) => ask.territory.paths),58+ Effect.option59+ );60+61 return yield* Schema.encodeEffect(CommitPageData)({62 diff,63 now: yield* DateTime.now,64 project,65+ ...Option.match(territory, {66+ onNone: () => ({}),67+ onSome: (paths) => ({ territory: paths }),68+ }),69 });70 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));71 72 const commitPage = createServerFn({ method: "GET" })4 unmodified lines77 )78 );79 80 const CommitPage = () => {67- const { diff, now, project } = Schema.decodeSync(CommitPageData)(81+ const { diff, now, project, territory } = Schema.decodeSync(CommitPageData)(82 Route.useLoaderData()83 );84 85+ const router = useRouter();71- const split = Route.useSearch().style === "split";86+ const asked = Route.useSearch().style === "split";87+ const [chosen, setChosen] = useState(asked);88+ const roomy = useMedia(SPLIT_QUERY);89+ // Split only where the screen has room for two sides.90+ const split = chosen && roomy;91 92+ const defaults = useMemo(93+ () =>94+ new Set(95+ drawnFiles(diff.files)96+ .filter(({ folded }) => folded)97+ .map(({ file }) => file.path)98+ ),99+ [diff.files]100+ );101+102+ const [folded, setFolded] = useState<ReadonlySet<string>>(defaults);103+104+ const onFold = useCallback((path: string, fold: boolean) => {105+ setFolded((was) => {106+ if (was.has(path) === fold) {107+ return was;108+ }109+110+ const next = new Set(was);111+112+ if (fold) {113+ next.add(path);114+ } else {115+ next.delete(path);116+ }117+118+ return next;119+ });120+ }, []);121+122+ const onFoldAll = useCallback(123+ (fold: boolean) => {124+ setFolded(fold ? new Set(diff.files.map(({ path }) => path)) : new Set());125+ },126+ [diff.files]127+ );128+129+ // The layout is the reader's: kept in the address, with no read again.130+ const onSplit = (next: boolean) => {131+ setChosen(next);132+133+ const { hash, pathname } = router.state.location;134+135+ router.history.replace(136+ `${pathname}${next ? "?style=split" : ""}${hash === "" ? "" : `#${hash}`}`137+ );138+ };139+140 return (141 <CommitView142 diff={diff}143 drawing={77- <div className="grid min-w-0 gap-4 lg:grid-cols-[16rem_minmax(0,1fr)]">78- <div className="min-w-0 lg:sticky lg:top-4 lg:max-h-[calc(100dvh-2rem)] lg:self-start">79- <ClientTree80- hrefOf={(path) => `#${diffAnchor(path)}`}81- paths={diff.files.map((file) => file.path)}82- status={diff.files.map((file) => ({83- path: file.path,84- status: file.status,85- }))}86- />87- </div>144+ diff.truncated ? undefined : (145 <ClientDiffs146 fallback={90- <ChangedList91- commit={diff.commit}92- files={diff.files}93- project={project}94- />147+ <div className={PANE_SCROLLER}>148+ <PlainDiff149+ files={diff.files}150+ folded={folded}151+ onFold={onFold}152+ split={split}153+ />154+ </div>155 }156 files={diff.files}157+ folded={folded}158+ onFold={onFold}159 split={split}160 />99- </div>161+ )162 }163+ files={<FilesButton commit />}164+ folded={folded}165 now={now}166+ onFold={onFold}167+ onFoldAll={onFoldAll}168+ onSplit={onSplit}169 project={project}170 split={split}171+ territory={territory}172 />173 );174 };175 176 export const Route = createFileRoute("/$project/commit/$sha")({177+ staticData: { rail: CommitRail },178 // The router writes back what this returns, dropping only `undefined`,179 // so a unified diff's address carries no `style`.180 validateSearch: (search: { readonly style?: unknown }) => ({181 style: search.style === "split" ? ("split" as const) : undefined,182 }),183 loader: ({ params }) => commitPage({ data: params }),184+ // A commit never changes: what was read stays fresh for good.185+ staleTime: Number.POSITIVE_INFINITY,186+ headers: () => immutablePage,187 head: ({ params: { project, sha } }) =>188 pageHead({ title: `${project}: commit ${sha.slice(0, 7)}` }),189 component: CommitPage,190 notFoundComponent: CodeNotFound,1 unmodified linemodified:apps/web/src/routes/$project/commits/$rev.tsx+15 added-4 removed
12 unmodified lines13 revisionOf,14 } from "../../../features/code/address.ts";15 import { LOG_PAGE } from "../../../features/code/log-page.ts";16 import { LogView } from "../../../features/code/log-view.tsx";17+import type { LogShow } from "../../../features/code/log-view.tsx";18 import { CodeNotFound } from "../../../features/code/not-found.tsx";19 import { pageHead } from "../../../features/shared/head.ts";20 import { notFoundFor } from "../../../features/shared/refusals.ts";21 import { serverClient } from "../../../server/client.ts";22+import { codePageHeaders } from "../tree/-headers.ts";23 22-// The log from a revision, a page at a time (`?from=` is where the page23-// starts), only the commits that changed `?path=` when given; read on the24-// server, so the page arrives whole.24+// The landings: the log from a revision, a page at a time (`?from=` is25+// where the page starts), only the commits that changed `?path=` when26+// given, filtered to the answers or the asks' openings by `?show=`; read27+// on the server, so the page arrives whole.28 29 const LogPageData = Schema.Struct({30 commits: Schema.Array(CommitView),31 from: Schema.Int,3 unmodified lines35 project: ProjectName,36 rev: Schema.String,37 });38 39+/** The kinds of commit a page may be filtered to. */40+const SHOWS: readonly LogShow[] = ["answers", "openings"];41+42 interface LogParams {43 readonly from?: number | undefined;44 readonly path?: string | undefined;45 readonly project: string;41 unmodified lines87 );88 89 const LogPage = () => {90 const read = Schema.decodeSync(LogPageData)(Route.useLoaderData());91+ const { show } = Route.useSearch();92 93 return (94 <LogView95 commits={read.commits}2 unmodified lines98 now={read.now}99 path={read.path}100 project={read.project}101 rev={read.rev}102+ show={show ?? "all"}103 />104 );105 };106 107 export const Route = createFileRoute("/$project/commits/$rev")({108 validateSearch: (search: {109 readonly from?: unknown;110 readonly path?: unknown;111+ readonly show?: unknown;112 }) => ({113 from: Option.getOrUndefined(offsetOf(search.from)),114 path: Predicate.isString(search.path) ? search.path : undefined,115+ show: SHOWS.find((each) => each === search.show),116 }),117 loaderDeps: ({ search }) => ({ from: search.from, path: search.path }),118 loader: ({ deps, params }) => logPage({ data: { ...params, ...deps } }),119+ headers: ({ params }) => codePageHeaders(params.rev),120 head: ({ params: { project, rev } }) =>110- pageHead({ title: `${project}: commits on ${rev}` }),121+ pageHead({ title: `${project}: landings on ${rev}` }),122 component: LogPage,123 notFoundComponent: CodeNotFound,124 });modified:apps/web/src/routes/$project/tree/$rev/$.tsx+38 added-17 removed
1+import { useAtomValue } from "@effect/atom-react";2+import type { CommitView } from "@repo/protocol/domain/code";3 import { FileView, TreeListing } from "@repo/protocol/domain/code";4 import { ProjectName } from "@repo/protocol/ids";5 import { createFileRoute, notFound } from "@tanstack/react-router";6 import { createServerFn } from "@tanstack/react-start";7 import { env } from "cloudflare:workers";6-import { Effect, Option, Schema } from "effect";8+import { DateTime, Effect, Option, Schema } from "effect";9+import { AsyncResult } from "effect/reactivity";10 8-import { PathsTree } from "../-paths-tree.tsx";11+import { CodeRail } from "../-code-rail.tsx";12+import { FilesButton } from "../-files-button.tsx";13+import { codePageHeaders } from "../-headers.ts";14+import { softLanding } from "../-soft-landing.ts";15+import { lastChangesAtom } from "../../../../client/code.ts";16 import {17 projectOf,18 repoPathOf,19 revisionOf,4 unmodified lines24 import { notFoundFor } from "../../../../features/shared/refusals.ts";25 import { serverClient } from "../../../../server/client.ts";26 import { readFolderWithReadme } from "../../../../server/folder.ts";27 21-// A folder at a revision: its breadcrumb, its entries and its README, read22-// on the server, so the page arrives whole; the file tree beside it is the23-// browser's. An address naming no project, revision or folder is a 40424-// showing the platform's refusal.28+// A folder at a revision: its entries and its README, read on the server,29+// so the page arrives whole; the tree in the rail and what last changed30+// each entry are the browser's. A path missing at a revision that exists31+// lands on the nearest folder above it, the refusal as its notice; any32+// other address naming nothing is a 404 showing the platform's refusal.33 34 const TreePageData = Schema.Struct({35 listing: TreeListing,36+ now: Schema.DateTimeUtcFromString,37 project: ProjectName,38 readme: Schema.optionalKey(FileView),39 rev: Schema.String,40 });16 unmodified lines57 project,58 rev,59 }).pipe(60 Effect.catchTags({52- UnknownPath: notFoundFor,61+ UnknownPath: (refusal) => softLanding(refusal, project, rev),62 UnknownProject: notFoundFor,63 UnknownRevision: notFoundFor,64 })65 );66 67 return yield* Schema.encodeEffect(TreePageData)({68 listing,69+ now: yield* DateTime.now,70 project,71 rev,72 ...Option.match(readme, {73 onNone: () => ({}),9 unmodified lines83 readTreePage(data).pipe(Effect.provide(serverClient(env)))84 )85 );86 87+const NO_CHANGES: ReadonlyMap<string, CommitView> = new Map();88+89 const TreePage = () => {78- const { listing, project, readme, rev } = Schema.decodeSync(TreePageData)(79- Route.useLoaderData()90+ const { listing, now, project, readme, rev } = Schema.decodeSync(91+ TreePageData92+ )(Route.useLoaderData());93+94+ const last = useAtomValue(95+ lastChangesAtom({96+ at: listing.at,97+ paths: listing.entries.map(({ path }) => path),98+ project,99+ })100 );101 102 return (103 <TreeView104+ files={<FilesButton />}105+ last={AsyncResult.match(last, {106+ onFailure: () => NO_CHANGES,107+ onInitial: () => NO_CHANGES,108+ onSuccess: ({ value }) => value,109+ })}110 listing={listing}111+ now={now}112 project={project}113 readme={readme}114 rev={rev}88- sidebar={89- <PathsTree90- at={listing.at}91- current={listing.path}92- project={project}93- rev={rev}94- />95- }115 />116 );117 };118 119 export const Route = createFileRoute("/$project/tree/$rev/$")({120+ staticData: { rail: CodeRail },121 loader: ({ params }) => treePage({ data: params }),122+ headers: ({ params }) => codePageHeaders(params.rev),123 head: ({ params: { _splat, project, rev } }) =>124 pageHead({125 title: `${_splat === undefined || _splat === "" ? project : _splat} at ${rev}`,126 }),3 unmodified linesadded:apps/web/src/routes/$project/tree/-code-rail.tsx+50 added
1+/**2+ * The code pages' files: in the rail's slot from the shell's width, and in3+ * a sheet behind the Files button below it. A folder's, a file's and a why4+ * page name the same `CodeRail`, so one tree stays mounted while the5+ * reader moves between them; a commit's page names `CommitRail`.6+ *7+ * A route's `staticData` loads with every page, so this module stays8+ * light: the server draws the ref line's place, and the browser loads the9+ * tree, the switcher and the keys (`-rail-body.tsx`) once the page is up.10+ * Not a route: the `-` prefix keeps the router from reading it as one.11+ */12+import { ClientOnly } from "@tanstack/react-router";13+import { lazy, Suspense } from "react";14+15+import { RailSlot } from "../../../features/shared/shell/rail-slot.tsx";16+17+const Body = import.meta.env.SSR18+ ? undefined19+ : lazy(() => import("./-rail-body.tsx"));20+21+/** The ref line's place, the height the switcher will take. */22+const Placeholder = () => (23+ <div aria-hidden="true" className="border-rule h-12 shrink-0 border-b" />24+);25+26+/** The rail's body, once the browser has it. */27+const Later = ({ commit }: { readonly commit: boolean }) =>28+ Body === undefined ? (29+ <Placeholder />30+ ) : (31+ <ClientOnly fallback={<Placeholder />}>32+ <Suspense fallback={<Placeholder />}>33+ <Body commit={commit} />34+ </Suspense>35+ </ClientOnly>36+ );37+38+/** The rail's slot on a folder's, a file's and a why page. */39+export const CodeRail = () => (40+ <RailSlot label="Files">41+ <Later commit={false} />42+ </RailSlot>43+);44+45+/** The rail's slot on a commit's page. */46+export const CommitRail = () => (47+ <RailSlot label="Changed files">48+ <Later commit />49+ </RailSlot>50+);added:apps/web/src/routes/$project/tree/-commit-files.ts+17 added
1+/**2+ * A commit page's data, as its loader sends it: the rail reads the files3+ * it changed from the page's match (`-rail-body.tsx`), so the rail's tree4+ * and the page's diff come from one read. Not a route: the `-` prefix5+ * keeps the router from reading it as one.6+ */7+import { CommitDiff } from "@repo/protocol/domain/code";8+import { ProjectName } from "@repo/protocol/ids";9+import { Schema } from "effect";10+11+export const CommitPageData = Schema.Struct({12+ diff: CommitDiff,13+ now: Schema.DateTimeUtcFromString,14+ project: ProjectName,15+ /** The territory of the ask the commit answered, when it answered one. */16+ territory: Schema.optionalKey(Schema.Array(Schema.String)),17+});added:apps/web/src/routes/$project/tree/-files-button.tsx+43 added
1+/**2+ * The Files button on the code pages below the shell's width, where the3+ * rail is not drawn: it opens the files as a sheet from the left (the4+ * whole screen on a phone), loaded on the first press. Not a route: the5+ * `-` prefix keeps the router from reading it as one.6+ */7+import { FolderTree } from "lucide-react";8+import { lazy, Suspense, useState } from "react";9+10+import { Button } from "@/components/ui/button";11+12+const FilesSheet = import.meta.env.SSR13+ ? undefined14+ : lazy(() => import("./-files-sheet.tsx"));15+16+export const FilesButton = ({17+ commit = false,18+}: {19+ readonly commit?: boolean;20+}) => {21+ const [open, setOpen] = useState(false);22+23+ return (24+ <>25+ <Button26+ aria-haspopup="dialog"27+ onClick={() => {28+ setOpen(true);29+ }}30+ size="sm"31+ variant="outline"32+ >33+ <FolderTree aria-hidden="true" strokeWidth={1.75} />34+ Files35+ </Button>36+ {FilesSheet === undefined || !open ? null : (37+ <Suspense fallback={null}>38+ <FilesSheet commit={commit} onOpenChange={setOpen} open={open} />39+ </Suspense>40+ )}41+ </>42+ );43+};added:apps/web/src/routes/$project/tree/-files-sheet.tsx+54 added
1+/**2+ * The code pages' files below the shell's width: a sheet from the left on3+ * a tablet, the whole screen on a phone, holding the ref line and the4+ * tree (or a commit's changed files). Choosing a file moves the page, and5+ * the sheet closes. Loaded on the first press of Files. Not a route: the6+ * `-` prefix keeps the router from reading it as one.7+ */8+import { useLocation } from "@tanstack/react-router";9+import { useEffect, useRef } from "react";10+11+import { Sheet, SheetContent } from "@/components/ui/sheet";12+13+import { TABLET_QUERY, useMedia } from "../../../features/code/media.ts";14+import { CodeFiles, CommitFiles } from "./-rail-body.tsx";15+16+const FilesSheet = ({17+ commit,18+ onOpenChange,19+ open,20+}: {21+ readonly commit: boolean;22+ readonly onOpenChange: (open: boolean) => void;23+ readonly open: boolean;24+}) => {25+ const tablet = useMedia(TABLET_QUERY);26+27+ const href = useLocation({28+ select: ({ hash, pathname }) => `${pathname}#${hash}`,29+ });30+31+ const opened = useRef(href);32+33+ // The reader chose a file: the page moved, so the sheet has done its work.34+ useEffect(() => {35+ if (href !== opened.current) {36+ onOpenChange(false);37+ }38+ }, [href, onOpenChange]);39+40+ return (41+ <Sheet onOpenChange={onOpenChange} open={open}>42+ <SheetContent43+ side={tablet ? "left" : "full"}44+ title={commit ? "Changed files" : "Files"}45+ >46+ <div className="flex h-full min-h-0 flex-col">47+ {commit ? <CommitFiles always /> : <CodeFiles always />}48+ </div>49+ </SheetContent>50+ </Sheet>51+ );52+};53+54+export default FilesSheet;added:apps/web/src/routes/$project/tree/-headers.ts+15 added
1+/**2+ * The `Cache-Control` a code page answers with, by what its address names:3+ * a page at a whole commit id shows what can never change, so a browser4+ * keeps it for good; a page at `main` or a tag moves with the next5+ * landing, so it is kept briefly and read again behind it. Not a route:6+ * the `-` prefix keeps the router from reading it as one.7+ */8+import { isCommitId } from "../../../features/code/headers.ts";9+import { branchPage, immutablePage } from "../../../server/cache-headers.ts";10+11+/** A code page's headers at `rev`. */12+export const codePageHeaders = (13+ rev: string14+): Readonly<Record<string, string>> =>15+ isCommitId(rev) ? immutablePage : branchPage;deleted:apps/web/src/routes/$project/tree/-paths-tree.tsx-54 removed
1-import { useAtomValue } from "@effect/atom-react";2-import type { ProjectName } from "@repo/protocol/ids";3-import { ClientOnly } from "@tanstack/react-router";4-import { AsyncResult } from "effect/reactivity";5-6-import { pathsAtom } from "../../../client/code.ts";7-import { ClientTree } from "../../../features/code/client-tree.tsx";8-import { blobHref } from "../../../features/code/paths.ts";9-10-// The file tree beside a folder or a file: every path at the page's commit11-// (`listPaths`), read and drawn in the browser only. While it loads, when12-// the read fails, or past the platform's cap on paths, the column shows13-// nothing and the page works from its own table. Not a route: the `-`14-// prefix keeps the router from reading it as one.15-16-const Paths = ({17- at,18- current,19- project,20- rev,21-}: {22- readonly at: string;23- readonly current?: string | undefined;24- readonly project: ProjectName;25- readonly rev: string;26-}) => {27- const read = useAtomValue(pathsAtom({ at, project }));28-29- return AsyncResult.match(read, {30- onFailure: () => null,31- onInitial: () => null,32- onSuccess: ({ value }) =>33- value.truncated ? null : (34- <ClientTree35- current={current}36- hrefOf={(path) => blobHref(project, rev, path)}37- paths={value.paths}38- />39- ),40- });41-};42-43-export const PathsTree = (props: {44- /** The commit the page resolved: the paths are read there. */45- readonly at: string;46- readonly current?: string | undefined;47- readonly project: ProjectName;48- /** The revision the page's links keep. */49- readonly rev: string;50-}) => (51- <ClientOnly fallback={null}>52- <Paths {...props} />53- </ClientOnly>54-);added:apps/web/src/routes/$project/tree/-rail-body.tsx+244 added
1+/**2+ * What the code pages' rail and Files sheet hold, loaded in the browser3+ * only (`-code-rail.tsx`): the ref line (main, a tag or a commit, as a4+ * switcher), then the tree with its filter, filling the rest; choosing a5+ * file moves the page with the router, never reloading the document. On6+ * a commit's page, the files it changed, open, marked A, M or D with their7+ * `+n −m`; choosing one scrolls the diff to it.8+ *9+ * `J` and `K` move to the next or previous file, in the tree's order.10+ * Not a route: the `-` prefix keeps the router from reading it as one.11+ */12+import { useAtomValue } from "@effect/atom-react";13+import type { ChangedFile } from "@repo/protocol/domain/code";14+import { ProjectName } from "@repo/protocol/ids";15+import {16+ ClientOnly,17+ useLocation,18+ useMatch,19+ useParams,20+ useRouter,21+} from "@tanstack/react-router";22+import { Option, Schema } from "effect";23+import { AsyncResult } from "effect/reactivity";24+25+import { pathsAtom, refsAtom } from "../../../client/code.ts";26+import { ClientTree } from "../../../features/code/client-tree.tsx";27+import { drawnFiles, treeOrder } from "../../../features/code/diff-model.ts";28+import { useCodeFileKeys } from "../../../features/code/file-keys.ts";29+import { parseDiffHash } from "../../../features/code/line-hash.ts";30+import { SHELL_QUERY, useMedia } from "../../../features/code/media.ts";31+import {32+ blobHref,33+ diffAnchor,34+ treeHref,35+ whyHref,36+} from "../../../features/code/paths.ts";37+import { RefSwitcher } from "../../../features/code/ref-switcher.tsx";38+import { CommitPageData } from "./-commit-files.ts";39+40+const isProject = Schema.is(ProjectName);41+42+const decode = Schema.decodeUnknownOption(CommitPageData);43+44+const NONE: readonly ChangedFile[] = [];45+46+/** The files the commit on the page changed; none while its data is not there. */47+const useCommitFiles = (): readonly ChangedFile[] => {48+ const data: unknown = useMatch({49+ from: "/$project/commit/$sha",50+ select: (match) => match.loaderData,51+ shouldThrow: false,52+ });53+54+ return Option.match(decode(data), {55+ onNone: () => NONE,56+ onSome: ({ diff }) => diff.files,57+ });58+};59+60+/** Which page of a file the address is: its folder, its code, or why. */61+type Kind = "blob" | "tree" | "why";62+63+/** Where the reader is in the code: the project, the revision and the path, and which page. */64+const useCodeAddress = () => {65+ const params = useParams({ strict: false });66+67+ const kind = useLocation({68+ select: ({ pathname }): Kind => {69+ const second = pathname.split("/").at(2);70+71+ return second === "blob" || second === "why" ? second : "tree";72+ },73+ });74+75+ const project = isProject(params.project) ? params.project : undefined;76+ const rev = params.rev ?? "main";77+78+ const path =79+ params._splat === undefined || params._splat === ""80+ ? undefined81+ : params._splat;82+83+ return { kind, path, project, rev };84+};85+86+/** The page of `kind` for `path` at `rev`. */87+const hrefFor = (88+ project: ProjectName,89+ kind: Kind,90+ rev: string,91+ path: string | undefined92+) => {93+ if (path === undefined || kind === "tree") {94+ return treeHref(project, rev, path);95+ }96+97+ return (kind === "why" ? whyHref : blobHref)(project, rev, path);98+};99+100+/** The ref line: the revision, and the switcher to the same page at another. */101+const RefLine = ({102+ kind,103+ path,104+ project,105+ rev,106+}: {107+ readonly kind: Kind;108+ readonly path: string | undefined;109+ readonly project: ProjectName;110+ readonly rev: string;111+}) => {112+ const refs = useAtomValue(refsAtom(project));113+114+ return (115+ <div className="border-rule flex h-12 shrink-0 items-center gap-2 border-b px-3">116+ <RefSwitcher117+ hrefAt={(at) => hrefFor(project, kind, at, path)}118+ refs={Option.getOrUndefined(AsyncResult.value(refs))}119+ rev={rev}120+ />121+ </div>122+ );123+};124+125+/** The tree of every path at the revision, and the keys between its files. */126+const ProjectTree = ({127+ kind,128+ path,129+ project,130+ rev,131+ shown,132+}: {133+ readonly kind: Kind;134+ readonly path: string | undefined;135+ readonly project: ProjectName;136+ readonly rev: string;137+ /** Whether the tree is on screen here (the rail is not below the shell's width). */138+ readonly shown: boolean;139+}) => {140+ const router = useRouter();141+ const read = useAtomValue(pathsAtom({ at: rev, project }));142+143+ // Past the platform's cap on paths the page works from its own list.144+ const paths = Option.getOrUndefined(145+ Option.flatMap(AsyncResult.value(read), (listed) =>146+ listed.truncated ? Option.none() : Option.some(listed.paths)147+ )148+ );149+150+ const open = (file: string) => {151+ router.history.push(152+ hrefFor(project, kind === "tree" ? "blob" : kind, rev, file)153+ );154+ };155+156+ useCodeFileKeys((paths ?? []).toSorted(treeOrder), path, open);157+158+ return shown && paths !== undefined ? (159+ <ClientTree160+ current={path}161+ key={`${project}@${rev}`}162+ onOpen={open}163+ paths={paths}164+ />165+ ) : null;166+};167+168+/** A folder's, a file's or a why page's files: the ref line, then the tree. */169+export const CodeFiles = ({170+ always = false,171+}: {172+ readonly always?: boolean;173+}) => {174+ const { kind, path, project, rev } = useCodeAddress();175+ const wide = useMedia(SHELL_QUERY);176+177+ return project === undefined ? null : (178+ <div className="flex min-h-0 flex-1 flex-col">179+ <RefLine kind={kind} path={path} project={project} rev={rev} />180+ <div className="min-h-0 flex-1 pt-1">181+ <ClientOnly fallback={null}>182+ <ProjectTree183+ kind={kind}184+ path={path}185+ project={project}186+ rev={rev}187+ shown={always || wide}188+ />189+ </ClientOnly>190+ </div>191+ </div>192+ );193+};194+195+/** A commit's changed files, marked by how, and the keys between them. */196+export const CommitFiles = ({197+ always = false,198+}: {199+ readonly always?: boolean;200+}) => {201+ const router = useRouter();202+ const wide = useMedia(SHELL_QUERY);203+ const files = useCommitFiles();204+ const hash = useLocation({ select: (location) => location.hash });205+206+ const current = Option.getOrUndefined(207+ Option.map(parseDiffHash(hash), ({ path }) => path)208+ );209+210+ const drawn = drawnFiles(files);211+ const paths = drawn.map(({ file }) => file.path);212+213+ const open = (path: string) => {214+ const { pathname, searchStr } = router.state.location;215+216+ router.history.replace(`${pathname}${searchStr}#${diffAnchor(path)}`);217+ };218+219+ useCodeFileKeys(paths, current, open);220+221+ return always || wide ? (222+ <div className="min-h-0 flex-1 pt-1">223+ <ClientTree224+ counts={new Map(drawn.map(({ counts, file }) => [file.path, counts]))}225+ current={current}226+ key={paths.join("\n")}227+ onOpen={open}228+ open229+ paths={paths}230+ status={drawn.map(({ file }) => ({231+ path: file.path,232+ status: file.status,233+ }))}234+ />235+ </div>236+ ) : null;237+};238+239+/** The rail's body: a commit's changed files, or the project's. */240+const RailBody = ({ commit }: { readonly commit: boolean }) =>241+ commit ? <CommitFiles /> : <CodeFiles />;242+243+// `React.lazy` takes a module's default export.244+export default RailBody;added:apps/web/src/routes/$project/tree/-soft-landing.ts+74 added
1+/**2+ * The soft landing for a missing path (GitLab's: the nearest folder, with3+ * the refusal above it): when a code page's path is not at a revision4+ * that exists, the folders above it are read, nearest first, and the5+ * first that exists travels in the 404 with the platform's `UnknownPath`,6+ * so the page shows that folder with the refusal's own words as its7+ * notice. The root always exists where the revision does. Not a route:8+ * the `-` prefix keeps the router from reading it as one.9+ */10+import { Client } from "@repo/protocol/contracts";11+import type { TreeListing } from "@repo/protocol/domain/code";12+import { RepoPath } from "@repo/protocol/ids";13+import type { ProjectName } from "@repo/protocol/ids";14+import type { UnknownPath } from "@repo/protocol/refusal";15+import { notFound } from "@tanstack/react-router";16+import { DateTime, Effect, Option, Schema } from "effect";17+18+import { ancestorsOf } from "../../../features/code/paths.ts";19+import { SoftLanding } from "../../../features/code/soft-landing.ts";20+import { notFoundFor } from "../../../features/shared/refusals.ts";21+22+/** Each folder above `path`, nearest first, then the root (none). */23+const above = (path: string): readonly Option.Option<RepoPath>[] => [24+ ...ancestorsOf(path)25+ .toReversed()26+ .map((folder) => Option.some(RepoPath.make(folder))),27+ Option.none(),28+];29+30+/** A 404 for `refusal` that lands on the nearest folder above its path at its commit. */31+export const softLanding = (32+ refusal: UnknownPath,33+ project: ProjectName,34+ rev: string35+) =>36+ Effect.gen(function* () {37+ const client = yield* Client;38+39+ const read = (folder: Option.Option<RepoPath>) =>40+ client41+ .readTree({42+ at: refusal.commit,43+ project,44+ ...Option.match(folder, {45+ onNone: () => ({}),46+ onSome: (path) => ({ path }),47+ }),48+ })49+ .pipe(Effect.option);50+51+ let nearest = Option.none<TreeListing>();52+53+ for (const folder of above(refusal.path)) {54+ nearest = yield* read(folder);55+56+ if (Option.isSome(nearest)) {57+ break;58+ }59+ }60+61+ if (Option.isNone(nearest)) {62+ return yield* notFoundFor(refusal);63+ }64+65+ const data = yield* Schema.encodeEffect(SoftLanding)({66+ nearest: nearest.value,67+ now: yield* DateTime.now,68+ project,69+ refusals: [refusal],70+ rev,71+ });72+73+ return yield* Effect.fail(notFound({ data }));74+ });modified:apps/web/src/routes/$project/why/$rev/$.tsx+54 added-18 removed
1 import { Client } from "@repo/protocol/contracts";2-import { WhyView } from "@repo/protocol/domain/code";2+import { CommitView, FileView, WhyView } from "@repo/protocol/domain/code";3 import { ProjectName } from "@repo/protocol/ids";4+import type { UnknownPath } from "@repo/protocol/refusal";5 import { createFileRoute, notFound } from "@tanstack/react-router";6 import { createServerFn } from "@tanstack/react-start";7 import { env } from "cloudflare:workers";7-import { Effect, Schema } from "effect";8+import { DateTime, Effect, Option, Schema } from "effect";9 10 import {11 projectOf,12 repoPathOf,4 unmodified lines17 import { notFoundFor } from "../../../../features/shared/refusals.ts";18 import { ClientWhy } from "../../../../features/why/client-why.tsx";19 import { WhyFallback, WhyLines } from "../../../../features/why/why-view.tsx";20 import { serverClient } from "../../../../server/client.ts";21+import { CodeRail } from "../../tree/-code-rail.tsx";22+import { FilesButton } from "../../tree/-files-button.tsx";23+import { codePageHeaders } from "../../tree/-headers.ts";24+import { softLanding } from "../../tree/-soft-landing.ts";25 26 // Why each line of a file at a revision is there, read on the server: the22-// blame's ranges with their commits and landings, and the file's text at23-// the commit the blame resolved, so the two always agree (both asked for24-// at once, the text again only if the revision moved between them). The25-// browser then draws the file with a row above each range. An address26-// naming no project, revision or file is a 404 showing the platform's27-// refusal.27+// blame's ranges with their commits and landings, the file at the commit28+// the blame resolved, so the two always agree (all asked for at once, the29+// file again only if the revision moved between them), and the commit30+// that last changed it. The browser then draws the file with a band above31+// each group of lines. A path missing at a revision that exists lands on32+// the nearest folder above it; any other address naming nothing is a 40433+// showing the platform's refusal.34 35 const WhyPageData = Schema.Struct({36+ file: FileView,37+ last: Schema.optionalKey(CommitView),38+ now: Schema.DateTimeUtcFromString,39 project: ProjectName,40 rev: Schema.String,41 text: Schema.UndefinedOr(Schema.String),42 view: WhyView,13 unmodified lines56 const path = yield* Effect.fromOption(repoPathOf(params._splat));57 const client = yield* Client;58 59 const refused = {51- UnknownPath: notFoundFor,60+ UnknownPath: (refusal: UnknownPath) => softLanding(refusal, project, rev),61 UnknownProject: notFoundFor,62 UnknownRevision: notFoundFor,63 };64 56- // Both at once: a cold why takes seconds, and the file's text needs57- // none of it. Should the revision have moved between the two reads,58- // the text is read again at the why's own commit.59- const [view, read] = yield* Effect.all(65+ // All at once: a cold why takes seconds, and the file's text needs66+ // none of it. Should the revision have moved between the reads, the67+ // text is read again at the why's own commit. The last change is only68+ // a fact beside the file, so the page goes without it.69+ const [view, read, history] = yield* Effect.all(70 [71 client.why({ at: rev, path, project }),72 client.readFile({ at: rev, path, project }),73+ client.log({ at: rev, limit: 1, path, project }).pipe(Effect.option),74 ],64- { concurrency: 2 }75+ { concurrency: 3 }76 ).pipe(Effect.catchTags(refused));77 78 const file =79 read.at === view.at1 unmodified line81 : yield* client82 .readFile({ at: view.at, path, project })83 .pipe(Effect.catchTags(refused));84 85+ const last = Option.flatMap(history, ({ commits }) =>86+ Option.fromUndefinedOr(commits[0])87+ );88+89 return yield* Schema.encodeEffect(WhyPageData)({90+ file,91+ now: yield* DateTime.now,92 project,93 rev,94 text: file.text,95 view,96+ ...Option.match(last, {97+ onNone: () => ({}),98+ onSome: (commit) => ({ last: commit }),99+ }),100 });101 }).pipe(Effect.catchTag("NoSuchElementError", () => Effect.fail(notFound())));102 103 const whyPage = createServerFn({ method: "GET" })2 unmodified lines106 Effect.runPromise(readWhyPage(data).pipe(Effect.provide(serverClient(env))))107 );108 109 const WhyPage = () => {89- const { project, rev, text, view } = Schema.decodeSync(WhyPageData)(90- Route.useLoaderData()91- );110+ const { file, last, now, project, rev, text, view } = Schema.decodeSync(111+ WhyPageData112+ )(Route.useLoaderData());113 114 return (115 <WhyLines116 code={117 text === undefined ? undefined : (118 <ClientWhy98- fallback={<WhyFallback project={project} text={text} view={view} />}119+ fallback={120+ <WhyFallback121+ now={now}122+ project={project}123+ text={text}124+ view={view}125+ />126+ }127+ key={`${view.at}:${view.path}`}128+ now={now}129 project={project}130 text={text}131 view={view}132 />133 )134 }135+ file={file}136+ files={<FilesButton />}137+ last={last}138+ now={now}139 project={project}140 rev={rev}141 view={view}142 {...(text === undefined ? {} : { text })}1 unmodified line144 );145 };146 147 export const Route = createFileRoute("/$project/why/$rev/$")({148+ staticData: { rail: CodeRail },149+ headers: ({ params }) => codePageHeaders(params.rev),150 loader: ({ params }) => whyPage({ data: params }),151 head: ({ params: { _splat, project, rev } }) =>152 pageHead({ title: `Why ${_splat ?? project} at ${rev}` }),153 component: WhyPage,2 unmodified linesmodified:apps/web/test/code-client.test.tsx+76 added-16 removed
1 /**2 * The code browser's client-only drawings, rendered directly (as3- * `finish.test.tsx` renders `patch-diff.tsx`): a file and a commit's diff4- * are drawn by `@pierre/diffs` (`<diffs-container>`), and the repo's file5- * tree by `@pierre/trees` (`<file-tree-container>`). The pages import these6- * only behind `ClientOnly` and a lazy import, so the Worker never bundles7- * them (`code.test.tsx` holds the server side).3+ * `finish.test.tsx` renders `patch-diff.tsx`): a file is drawn by4+ * `@pierre/diffs` (`<diffs-container>`), a commit's diff by its `CodeView`5+ * (which draws nothing until it mounts, so its server markup is its6+ * marked host alone; `code.test.tsx` holds the plain text it replaces), and7+ * the repo's file tree by `@pierre/trees` (`<file-tree-container>`). The8+ * pages import these only behind `ClientOnly` and a lazy import, so the9+ * Worker never bundles them.10+ *11+ * The tree moves the page through the router: choosing a file calls the12+ * page's own `onOpen`, never `location.assign`, so the document stays.13 */14 import { describe, expect, it } from "@effect/vitest";15+import { FileTree } from "@pierre/trees";16 import { ChangedFile } from "@repo/protocol/domain/code";17 import { Schema } from "effect";18 import { renderToStaticMarkup } from "react-dom/server";19 20 import { FileCode } from "../src/features/code/code-view.tsx";21 import { DiffCode } from "../src/features/code/diff-view.tsx";22+import {23+ followChoices,24+ RepoTree,25+ treeOptionsFor,16-import { RepoTree } from "../src/features/code/repo-tree.tsx";26+} from "../src/features/code/repo-tree.tsx";27 28 const files = Schema.decodeSync(Schema.Array(ChangedFile))([29 {30 after: "a".repeat(40),12 unmodified lines43 status: "added",44 },45 ]);46 47+const PATHS = ["README.md", "src/parse.ts", "src/week.ts"];48+49 describe("the client-only drawings", () => {50 it("draw a file with @pierre/diffs", () => {51 const markup = renderToStaticMarkup(52 <FileCode3 unmodified lines56 />57 );58 59 expect(markup).toContain("<diffs-container");60+ expect(markup).toContain('data-code="pierre"');61 });62 50- it("draw a commit's diff with @pierre/diffs, one view per changed file, named", () => {63+ it("draw a commit's diff with one CodeView, which fills the pane and scrolls in it", () => {64 const markup = renderToStaticMarkup(65 <DiffCode files={files} split={false} />66 );67 55- const views = [56- ...markup.matchAll(57- /<section\b[^>]*aria-label="(?<file>[^"]+)"[^>]*><diffs-container\b/gu58- ),59- ].map((view) => view.groups?.file);60-61- expect(views).toStrictEqual(["src/parse.ts", "src/week.ts"]);68+ expect(markup).toContain('data-diff="pierre"');69+ expect(markup).toMatch(/class="[^"]*\bflex-1\b[^"]*\boverflow-auto\b/u);70 });71 72 it("draw the repo's file tree with @pierre/trees", () => {73 const markup = renderToStaticMarkup(74 <RepoTree75 current="src/parse.ts"68- hrefOf={(path) => `/datekit/blob/main/${path}`}69- paths={["README.md", "src/parse.ts", "src/week.ts"]}76+ onOpen={() => {77+ // Nothing is chosen in a server render.78+ }}79+ paths={PATHS}80 />81 );82 83 expect(markup).toContain("<file-tree-container");84 });85 });86+87+/** A tree over `PATHS` showing `current`, and the files it asked the page to open. */88+const treeAt = (current: string) => {89+ const opened: string[] = [];90+ const tree = new FileTree(treeOptionsFor({ current, paths: PATHS }));91+92+ followChoices(tree, current, (path) => {93+ opened.push(path);94+ });95+96+ return { opened, tree };97+};98+99+describe("the file tree", () => {100+ it("hands a chosen file to the page, which moves with the router", () => {101+ const { opened, tree } = treeAt("src/parse.ts");102+103+ tree.getItem("src/week.ts")?.select();104+105+ expect(opened).toStrictEqual(["src/week.ts"]);106+ });107+108+ it("asks nothing for the page's own file, or a folder", () => {109+ const { opened, tree } = treeAt("src/parse.ts");110+111+ tree.getItem("src/parse.ts")?.select();112+ tree.getItem("src/")?.select();113+114+ expect(opened).toStrictEqual([]);115+ });116+117+ it("opens the folders above the page's file, and selects it", () => {118+ const { tree } = treeAt("src/parse.ts");119+120+ expect(tree.getSelectedPaths()).toStrictEqual(["src/parse.ts"]);121+ expect(tree.getItem("src/")?.isDirectory()).toBeTruthy();122+ });123+124+ const sources: Readonly<Record<string, string>> = import.meta.glob(125+ "../src/features/code/repo-tree.tsx",126+ { eager: true, import: "default", query: "?raw" }127+ );128+129+ it("never reloads the document to open a file", () => {130+ const [source = ""] = Object.values(sources);131+132+ expect(source).toContain("onOpen");133+ expect(source).not.toMatch(/location\.(?:assign|href\s*=|replace)/u);134+ });135+});added:apps/web/test/code-diff.test.ts+207 added
1+/**2+ * A commit's diff as the server sends it and the browser draws it: both3+ * parse a file's two texts with the drawing's own parser, so the plain4+ * text holds the drawing's hunks line for line; a file's counts, which5+ * files start folded, the order a tree lists paths in, the stats split by6+ * the ask's territory, and the keys that move between files.7+ */8+import { describe, expect, it } from "@effect/vitest";9+import { ChangedFile } from "@repo/protocol/domain/code";10+import { Option, Schema } from "effect";11+12+import {13+ countsOf,14+ drawnFiles,15+ fileDiffOf,16+ globTest,17+ isTestPath,18+ splitRows,19+ statsOf,20+ treeOrder,21+ unifiedRows,22+} from "../src/features/code/diff-model.ts";23+import { stepFrom } from "../src/features/code/file-keys.ts";24+25+const decode = Schema.decodeSync(ChangedFile);26+27+/** Lines `from` to `to`, as a file's text. */28+const lines = (from: number, to: number) =>29+ `${Array.from(30+ { length: to - from + 1 },31+ (_, index) => `line ${from + index}`32+ ).join("\n")}\n`;33+34+const thirty = lines(1, 30);35+36+const changed = decode({37+ after: "a".repeat(40),38+ before: "b".repeat(40),39+ binary: false,40+ newText: thirty.replace("line 15\n", "line fifteen\nline 15b\n"),41+ oldText: thirty,42+ path: "src/parse.ts",43+ status: "modified",44+});45+46+describe("a changed file's diff", () => {47+ it("is parsed into the hunks the drawing draws, keyed by both blobs", () => {48+ const diff = fileDiffOf(changed);49+50+ expect(Option.map(diff, ({ hunks }) => hunks.length)).toStrictEqual(51+ Option.some(1)52+ );53+ expect(Option.map(diff, ({ cacheKey }) => cacheKey)).toStrictEqual(54+ Option.some(`diff:${"b".repeat(40)}:${"a".repeat(40)}`)55+ );56+ expect(countsOf(diff)).toStrictEqual({ additions: 2, deletions: 1 });57+ });58+59+ it("reads as unified rows: the unchanged lines skipped before and after, each line numbered on its side", () => {60+ const rows = Option.match(fileDiffOf(changed), {61+ onNone: () => [],62+ onSome: unifiedRows,63+ });64+65+ expect(rows[0]).toStrictEqual({ kind: "separator", lines: 10 });66+ expect(rows.at(-1)).toStrictEqual({ kind: "separator", lines: 11 });67+ expect(68+ rows.filter((row) => row.kind !== "separator" && row.kind !== "context")69+ ).toStrictEqual([70+ { kind: "deletion", number: 15, text: "line 15" },71+ { kind: "addition", number: 15, text: "line fifteen" },72+ { kind: "addition", number: 16, text: "line 15b" },73+ ]);74+ });75+76+ it("reads as split rows: the deletion beside the first addition, the second against nothing", () => {77+ const rows = Option.match(fileDiffOf(changed), {78+ onNone: () => [],79+ onSome: splitRows,80+ });81+82+ const pairs = rows.filter(83+ (row) =>84+ row.kind === "pair" &&85+ (row.left?.kind !== "context" || row.right === undefined)86+ );87+88+ expect(pairs).toStrictEqual([89+ {90+ kind: "pair",91+ left: { kind: "deletion", number: 15, text: "line 15" },92+ right: { kind: "addition", number: 15, text: "line fifteen" },93+ },94+ {95+ kind: "pair",96+ right: { kind: "addition", number: 16, text: "line 15b" },97+ },98+ ]);99+ });100+101+ it("has no lines for a binary file, or one whose text was not sent", () => {102+ expect(103+ fileDiffOf(decode({ binary: true, path: "logo.png", status: "added" }))104+ ).toStrictEqual(Option.none());105+ expect(106+ fileDiffOf(107+ decode({ binary: false, path: "big.json", status: "modified" })108+ )109+ ).toStrictEqual(Option.none());110+ });111+});112+113+describe("a commit's files", () => {114+ const files = [115+ decode({116+ binary: false,117+ newText: lines(1, 81),118+ path: "data/zones.ts",119+ status: "added",120+ }),121+ decode({122+ binary: false,123+ oldText: lines(1, 80),124+ path: "data/old.ts",125+ status: "deleted",126+ }),127+ changed,128+ decode({129+ binary: false,130+ newText: "it\n",131+ path: "test/parse.test.ts",132+ status: "added",133+ }),134+ decode({135+ binary: false,136+ newText: "x\n",137+ path: "README.md",138+ status: "added",139+ }),140+ ];141+142+ it("are listed in the tree's order: folders before files, then by name", () => {143+ expect(drawnFiles(files).map(({ file }) => file.path)).toStrictEqual([144+ "data/old.ts",145+ "data/zones.ts",146+ "src/parse.ts",147+ "test/parse.test.ts",148+ "README.md",149+ ]);150+ expect(["b", "a/z", "a/b/c"].toSorted(treeOrder)).toStrictEqual([151+ "a/b/c",152+ "a/z",153+ "b",154+ ]);155+ });156+157+ it("start folded when added or deleted past 80 lines", () => {158+ expect(159+ drawnFiles(files)160+ .filter(({ folded }) => folded)161+ .map(({ file }) => file.path)162+ ).toStrictEqual(["data/zones.ts"]);163+ });164+165+ it("count by path: the ask's territory, its tests, the rest", () => {166+ const stats = statsOf(drawnFiles(files), ["src/**"]);167+168+ expect([stats.files, stats.additions, stats.deletions]).toStrictEqual([169+ 5, 85, 81,170+ ]);171+ expect(stats.parts).toStrictEqual([172+ { additions: 2, deletions: 1, files: 1, label: "territory" },173+ { additions: 1, deletions: 0, files: 1, label: "tests" },174+ { additions: 82, deletions: 80, files: 3, label: "other" },175+ ]);176+ });177+178+ it("read a territory's globs as git paths", () => {179+ expect(globTest("src/**")("src/a/b.ts")).toBeTruthy();180+ expect(globTest("src/*.ts")("src/a/b.ts")).toBeFalsy();181+ expect(globTest("packages/parse")("packages/parse/index.ts")).toBeTruthy();182+ expect(globTest("**/*.ts")("a.ts")).toBeTruthy();183+ });184+185+ it("know a test file by its folder or its name", () => {186+ expect(isTestPath("src/parse.test.ts")).toBeTruthy();187+ expect(isTestPath("test/asks/x.ts")).toBeTruthy();188+ expect(isTestPath("src/testing.ts")).toBeFalsy();189+ });190+});191+192+describe("the keys between files", () => {193+ const paths = ["a.ts", "b.ts", "c.ts"];194+195+ it("move from the page's own file, and stop at either end", () => {196+ expect(stepFrom(paths, "b.ts", 1)).toBe("c.ts");197+ expect(stepFrom(paths, "b.ts", -1)).toBe("a.ts");198+ expect(stepFrom(paths, "c.ts", 1)).toBe("c.ts");199+ expect(stepFrom(paths, "a.ts", -1)).toBe("a.ts");200+ });201+202+ it("start at the first file, or the last going back, from none", () => {203+ expect(stepFrom(paths, undefined, 1)).toBe("a.ts");204+ expect(stepFrom(paths, undefined, -1)).toBe("c.ts");205+ expect(stepFrom([], undefined, 1)).toBeUndefined();206+ });207+});modified:apps/web/test/code.test.tsx+649 added-184 removed
1 /**2 * The code browser's pages, rendered to HTML with `react-dom/server` from3 * fixtures decoded with the protocol's own schemas: a folder (`TreeView`), a4- * file (`BlobView`), the log (`LogView`), one commit (`CommitView`) and the5- * refs (`RefsView`). Each is what the server sends before the browser6- * loads Pierre: the tree and the highlighted code are client-only, so none7- * of these pages carries a `<file-tree-container` or a `<diffs-container`.4+ * file (`BlobView`), the landings (`LogView`), one commit (`CommitView`), a5+ * missing path's soft landing and the refs (`RefsView`). Each is what the6+ * server sends before the browser loads Pierre: the tree and the7+ * highlighted code are client-only, so none of these pages carries a8+ * `<file-tree-container` or a `<diffs-container`; a commit's diff arrives as9+ * plain text at the drawing's measures.10 */11 import { describe, expect, it } from "@effect/vitest";12 import { Brand } from "@repo/brand";13 import { Client, Contracts } from "@repo/protocol/contracts";31 unmodified lines45 import { BlobView } from "../src/features/code/blob-view.tsx";46 import { CommitView } from "../src/features/code/commit-view.tsx";47 import { LOG_PAGE } from "../src/features/code/log-page.ts";48 import { LogView } from "../src/features/code/log-view.tsx";49+import { CodeNotFound } from "../src/features/code/not-found.tsx";50 import { packageParamOf } from "../src/features/code/refs-param.ts";51 import { RefsView, TAGS_PAGE } from "../src/features/code/refs-view.tsx";52+import { SoftLanding } from "../src/features/code/soft-landing.ts";53 import { TreeView } from "../src/features/code/tree-view.tsx";54 import { Refusals } from "../src/features/shared/refusals.ts";55 import { readBlobPage } from "../src/routes/$project/blob/$rev/$.tsx";56 import { readCommitPage } from "../src/routes/$project/commit/$sha.tsx";57 import { readLogPage } from "../src/routes/$project/commits/$rev.tsx";58 import { readRefsPage } from "../src/routes/$project/refs.tsx";59 import { readTreePage } from "../src/routes/$project/tree/$rev/$.tsx";60+import { codePageHeaders } from "../src/routes/$project/tree/-headers.ts";61+import { branchPage, immutablePage } from "../src/server/cache-headers.ts";62 import { reachingTransport } from "./transport.ts";63 64 const markupOf = (element: ReactElement) => renderToStaticMarkup(element);65 89 unmodified lines155 const TAG = "@datekit/core@1.0.0";156 157 const TAG_SEGMENT = "%40datekit%2Fcore%401.0.0";158 159+const decodeCommits = Schema.decodeSync(Schema.Array(Commit));160+161+const signature = (name: string, at: string) => ({162+ at,163+ email: `${name}@example.com`,164+ name,165+});166+167+const LANDED = "1".repeat(40);168+169+const IMPORTED = "2".repeat(40);170+171+const OLDER = "3".repeat(40);172+173+const commits = decodeCommits([174+ {175+ author: signature("Bram", "2026-10-06T15:00:00.000Z"),176+ body: "",177+ committer: signature("platform", "2026-10-06T15:00:00.000Z"),178+ landing: {179+ ask: "parse-iso-week",180+ assisted: [],181+ author: "bram",182+ credits: [183+ { handle: "bram", role: "Signed-off-by" },184+ { handle: "ines-v", role: "Asked-by" },185+ ],186+ landedAt: "2026-10-06T15:00:00.000Z",187+ parent: IMPORTED,188+ project: "datekit",189+ sha: LANDED,190+ },191+ parents: [IMPORTED],192+ sha: LANDED,193+ subject: "Answer parse-iso-week",194+ trailers: [195+ { key: "Asked-by", value: "ines-v" },196+ { key: "Signed-off-by", value: "bram" },197+ ],198+ tree: "4".repeat(40),199+ },200+ {201+ author: signature("Lin", "2026-10-06T09:00:00.000Z"),202+ body: "",203+ committer: signature("Lin", "2026-10-06T09:00:00.000Z"),204+ parents: [OLDER],205+ sha: IMPORTED,206+ subject: "Support week numbers",207+ trailers: [],208+ tree: "5".repeat(40),209+ },210+ {211+ author: signature("Lin", "2026-10-04T09:00:00.000Z"),212+ body: "",213+ committer: signature("Lin", "2026-10-04T09:00:00.000Z"),214+ parents: [],215+ sha: OLDER,216+ subject: "First commit",217+ trailers: [],218+ tree: "6".repeat(40),219+ },220+]);221+222+const decodeDiff = Schema.decodeSync(CommitDiff);223+224+const landedCommit: typeof Commit.Encoded = {225+ author: signature("Bram", "2026-10-06T15:00:00.000Z"),226+ body: "Parse ISO week dates.\n\nAsked-by: ines-v\nSigned-off-by: bram",227+ committer: signature("platform", "2026-10-06T15:00:00.000Z"),228+ landing: {229+ ask: "parse-iso-week",230+ assisted: [],231+ author: "bram",232+ credits: [233+ { handle: "bram", role: "Signed-off-by" },234+ { handle: "ines-v", role: "Asked-by" },235+ ],236+ landedAt: "2026-10-06T15:00:00.000Z",237+ parent: IMPORTED,238+ project: "datekit",239+ sha: LANDED,240+ verdict: {241+ ask: "parse-iso-week",242+ at: "2026-10-06T14:59:00.000Z",243+ base: IMPORTED,244+ checkVersion: "redThenGreen@0.0.0+abc",245+ head: "7".repeat(40),246+ heldBack: [],247+ lanes: [248+ {249+ command: "bun test",250+ durationMs: 1200,251+ lane: "unit",252+ result: "passed",253+ },254+ ],255+ outcome: Schema.encodeSync(Outcome)(256+ Outcome.cases.Landed.make({ sha: LandedSha.make(LANDED) })257+ ),258+ patchId: "8".repeat(64),259+ project: "datekit",260+ stage: "checks",261+ tree: "4".repeat(40),262+ verifier: "platform",263+ },264+ },265+ parents: [IMPORTED],266+ sha: LANDED,267+ subject: "Answer parse-iso-week",268+ trailers: [269+ { key: "Asked-by", value: "ines-v <ines-v@users.example.com>" },270+ { key: "Signed-off-by", value: "bram <bram@users.example.com>" },271+ ],272+ tree: "4".repeat(40),273+};274+275+const diff = decodeDiff({276+ commit: landedCommit,277+ files: [278+ {279+ after: "9".repeat(40),280+ binary: false,281+ newText: "export const week = 1;\n",282+ path: "src/week.ts",283+ status: "added",284+ },285+ {286+ after: "a".repeat(40),287+ before: "b".repeat(40),288+ binary: false,289+ newText: "export const parse = fromIso;\n",290+ oldText: "export const parse = Date;\n",291+ path: "src/parse.ts",292+ status: "modified",293+ },294+ {295+ before: "c".repeat(40),296+ binary: false,297+ oldText: "export const legacy = true;\n",298+ path: "src/legacy.ts",299+ status: "deleted",300+ },301+ ],302+ truncated: false,303+});304+305+/** The markup of `<main>` alone: the page, without its inspector. */306+const mainOf = (markup: string) =>307+ /<main\b[\s\S]*?<\/main>/u.exec(markup)?.[0] ?? "";308+309+/** The markup of the inspector alone. */310+const inspectorOf = (markup: string) =>311+ /<aside\b[^>]*data-facts="inspector"[\s\S]*?<\/aside>/u.exec(markup)?.[0] ??312+ "";313+314+/** How many times `part` appears in `text`. */315+const countIn = (text: string, part: string) => text.split(part).length - 1;316+317 describe(TreeView, () => {318 const page = (155- <TreeView listing={root} project={datekit} readme={readme} rev="main" />319+ <TreeView320+ listing={root}321+ now={now}322+ project={datekit}323+ readme={readme}324+ rev="main"325+ />326 );327 328 it("lists folders before files, each linking its own page at the same revision", () => {329 const markup = markupOf(page);5 unmodified lines335 expect(hrefsOf(markup)).toContain("/datekit/tree/main/src");336 expect(hrefsOf(markup)).toContain("/datekit/blob/main/README.md");337 });338 169- it("links each ancestor in its breadcrumb at the same revision, and names the folder last", () => {339+ it("lists the folder once", () => {340+ const markup = markupOf(page);341+342+ expect(countIn(markup, 'data-entry="src"')).toBe(1);343+ expect(countIn(markup, 'data-entry="README.md"')).toBe(1);344+ expect(countIn(markup, "data-entries=")).toBe(1);345+ });346+347+ it("says what last changed each entry, once it has been read", () => {348+ const [last] = commits;349+350 const markup = markupOf(171- <TreeView listing={nested} project={datekit} rev={TAG} />351+ <TreeView352+ last={new Map(last === undefined ? [] : [["src", last]])}353+ listing={root}354+ now={now}355+ project={datekit}356+ rev="main"357+ />358 );359 174- const crumbs = hrefsOf(navOf(markup, 'data-slot="breadcrumb"'));360+ expect(slice(markup, "data-entry", "src")).toContain("parse-iso-week");361+ expect(slice(markup, "data-entry", "src")).toContain("ago");362+ expect(slice(markup, "data-entry", "README.md")).not.toContain("ago");363+ });364 365+ it("links each ancestor in its path at the same revision, and names the folder last", () => {366+ const markup = markupOf(367+ <TreeView listing={nested} now={now} project={datekit} rev={TAG} />368+ );369+370+ const crumbs = hrefsOf(navOf(markup, 'aria-label="Path"'));371+372 expect(crumbs).toStrictEqual([373 `/datekit/tree/${TAG_SEGMENT}`,374 `/datekit/tree/${TAG_SEGMENT}/src`,375 `/datekit/tree/${TAG_SEGMENT}/src/format`,376 ]);377 expect(182- textOf(<TreeView listing={nested} project={datekit} rev={TAG} />)378+ textOf(379+ <TreeView listing={nested} now={now} project={datekit} rev={TAG} />380+ )381 ).toContain("locale");382 });383 384 it("renders the folder's README below its entries", () => {14 unmodified lines399 describe(BlobView, () => {400 const parse = decodeFile({401 at: AT,402 binary: false,205- path: "src/parse.ts",403+ path: "src/format/parse.ts",404 sha: "e".repeat(40),405 size: 14,406 text: "one\ntwo\nthree\n",407 truncated: false,408 });409 212- const page = <BlobView file={parse} project={datekit} rev="main" />;410+ const [lastLanding] = commits;411 412+ const page = (413+ <BlobView414+ file={parse}415+ last={lastLanding}416+ now={now}417+ project={datekit}418+ rev="main"419+ />420+ );421+422 it("numbers each line of a text file with its own anchor, and draws no highlighting on the server", () => {423 const markup = markupOf(page);424 425 const anchors = [...markup.matchAll(/id="(?<line>L\d+)"/gu)].map(15 unmodified lines441 expect(anchored?.groups?.tag).toBe("span");442 expect(anchored?.groups?.attributes).not.toMatch(/\bcontents\b/u);443 });444 237- it("links raw at the commit, why and history at the revision, and the permalink at the commit", () => {238- const toolbar = navOf(markupOf(page), 'data-toolbar="file"');445+ it("sets the plain text at the drawing's measures: 20 px lines and Pierre's gutter", () => {446+ const code = /<pre\b[^>]*>/u.exec(markupOf(page))?.[0] ?? "";447 448+ expect(code).toContain("leading-code");449+ expect(code).toContain("text-mono");450+ expect(markupOf(page)).toContain("min-w-[calc(6ch+2px)]");451+ expect(markupOf(page)).toContain("pl-[2ch]");452+ });453+454+ it("names the path once in the page, in its file header", () => {455+ const main = mainOf(markupOf(page));456+457+ // The trail's segments, read as text, spell the path: once.458+ expect(459+ countIn(main.replaceAll(/<[^>]+>/gu, ""), "src/format/parse.ts")460+ ).toBe(1);461+ expect(countIn(main, 'title="src/format/parse.ts"')).toBe(1);462+ expect(countIn(main, 'aria-label="Path"')).toBe(1);463+ expect(hrefsOf(navOf(main, 'aria-label="Path"'))).toStrictEqual([464+ "/datekit/tree/main",465+ "/datekit/tree/main/src",466+ "/datekit/tree/main/src/format",467+ ]);468+ });469+470+ it("has the Code | Why toggle, Code current", () => {471+ const toggle = navOf(markupOf(page), 'aria-label="Mode"');472+473+ expect(hrefsOf(toggle)).toStrictEqual([474+ "/datekit/blob/main/src/format/parse.ts",475+ "/datekit/why/main/src/format/parse.ts",476+ ]);477+ expect(toggle).toMatch(/aria-current="page"[^>]*>Code</u);478+ expect(toggle).not.toMatch(/aria-current="page"[^>]*>Why</u);479+ });480+481+ it("links raw at the commit and the permalink at the commit, and the history at the revision", () => {482+ const markup = markupOf(page);483+ const toolbar = navOf(markup, 'data-toolbar="file"');484+485 expect(hrefsOf(toolbar)).toStrictEqual([241- `/datekit/raw/${AT}/src/parse.ts`,242- "/datekit/why/main/src/parse.ts",243- "/datekit/commits/main?path=src%2Fparse.ts",244- `/datekit/blob/${AT}/src/parse.ts`,486+ `/datekit/raw/${AT}/src/format/parse.ts`,487+ `/datekit/blob/${AT}/src/format/parse.ts`,488 ]);489+ expect(hrefsOf(inspectorOf(markup))).toContain(490+ "/datekit/commits/main?path=src%2Fformat%2Fparse.ts"491+ );492 });493 494+ it("names the last landing's ask in This file, before its SHA", () => {495+ const facts = inspectorOf(markupOf(page));496+ const text = facts.replaceAll(/<[^>]+>/gu, "");497+498+ expect(facts).toContain("This file");499+ expect(text.indexOf("parse-iso-week")).toBeGreaterThan(-1);500+ expect(text.indexOf("parse-iso-week")).toBeLessThan(501+ text.indexOf(LANDED.slice(0, 7))502+ );503+ expect(text).toContain("answered by bram");504+ expect(hrefsOf(facts)).toStrictEqual(505+ expect.arrayContaining([506+ "/datekit/asks/parse-iso-week",507+ "/datekit/answers/parse-iso-week",508+ `/datekit/commit/${LANDED}`,509+ ])510+ );511+ });512+513 it("shows a binary file's size and a raw link, and no text", () => {514 const binary = decodeFile({515 at: AT,516 binary: true,2 unmodified lines519 size: 2048,520 truncated: false,521 });522 258- const element = <BlobView file={binary} project={datekit} rev="main" />;523+ const element = (524+ <BlobView file={binary} now={now} project={datekit} rev="main" />525+ );526 527 expect(markupOf(element)).not.toContain("<pre");528 expect(textOf(element)).toContain("2.0 KiB");529 expect(hrefsOf(markupOf(element))).toContain(10 unmodified lines540 size: 3_145_728,541 truncated: true,542 });543 277- const element = <BlobView file={large} project={datekit} rev="main" />;544+ const element = (545+ <BlobView file={large} now={now} project={datekit} rev="main" />546+ );547 548 expect(markupOf(element)).not.toContain("<pre");549 expect(textOf(element)).toContain("too large to show");550 expect(textOf(element)).toContain("3.0 MiB");12 unmodified lines563 truncated: false,564 });565 566 expect(298- markupOf(<BlobView file={logo} project={datekit} rev="main" />)567+ markupOf(<BlobView file={logo} now={now} project={datekit} rev="main" />)568 ).toMatch(569 new RegExp(`<img\\b[^>]*src="/datekit/raw/${AT}/docs/logo.png"`, "u")570 );571 });9 unmodified lines581 truncated: false,582 });583 584 const rendered = markupOf(316- <BlobView file={guide} project={datekit} rev="main" />585+ <BlobView file={guide} now={now} project={datekit} rev="main" />586 );587 588 const plain = markupOf(320- <BlobView file={guide} plain project={datekit} rev="main" />589+ <BlobView file={guide} now={now} plain project={datekit} rev="main" />590 );591 592 expect(rendered).toContain('data-readme="docs/guide.md"');593 expect(rendered).not.toContain('id="L1"');4 unmodified lines598 expect(plain).not.toContain("data-readme=");599 });600 });601 333-const decodeCommits = Schema.decodeSync(Schema.Array(Commit));334-335-const signature = (name: string, at: string) => ({336- at,337- email: `${name}@example.com`,338- name,339-});340-341-const LANDED = "1".repeat(40);342-343-const IMPORTED = "2".repeat(40);344-345-const OLDER = "3".repeat(40);346-347-const commits = decodeCommits([348- {349- author: signature("Bram", "2026-10-06T15:00:00.000Z"),350- body: "",351- committer: signature("platform", "2026-10-06T15:00:00.000Z"),352- landing: {353- ask: "parse-iso-week",354- assisted: [],355- author: "bram",356- credits: [357- { handle: "bram", role: "Signed-off-by" },358- { handle: "ines-v", role: "Asked-by" },359- ],360- landedAt: "2026-10-06T15:00:00.000Z",361- parent: IMPORTED,362- project: "datekit",363- sha: LANDED,364- },365- parents: [IMPORTED],366- sha: LANDED,367- subject: "Answer parse-iso-week",368- trailers: [369- { key: "Asked-by", value: "ines-v" },370- { key: "Signed-off-by", value: "bram" },371- ],372- tree: "4".repeat(40),373- },374- {375- author: signature("Lin", "2026-10-06T09:00:00.000Z"),376- body: "",377- committer: signature("Lin", "2026-10-06T09:00:00.000Z"),378- parents: [OLDER],379- sha: IMPORTED,380- subject: "Support week numbers",381- trailers: [],382- tree: "5".repeat(40),383- },384- {385- author: signature("Lin", "2026-10-04T09:00:00.000Z"),386- body: "",387- committer: signature("Lin", "2026-10-04T09:00:00.000Z"),388- parents: [],389- sha: OLDER,390- subject: "First commit",391- trailers: [],392- tree: "6".repeat(40),393- },394-]);395-602 describe(LogView, () => {603 const page = (604 <LogView605 commits={commits}4 unmodified lines610 rev="main"611 />612 );613 408- it("groups the commits of one day under one heading", () => {614+ it("groups the commits of one day under one sticky header", () => {615 const markup = markupOf(page);616 617 const days = [...markup.matchAll(/data-day="(?<day>[^"]+)"/gu)].map(618 (match) => match.groups?.day2 unmodified lines621 expect(days).toStrictEqual(["2026-10-06", "2026-10-04"]);622 623 const first = slice(markup, "data-day", "2026-10-06");624 419- expect(first).toContain(`data-commit="${LANDED}"`);420- expect(first).toContain(`data-commit="${IMPORTED}"`);421- expect(first).not.toContain(`data-commit="${OLDER}"`);625+ expect(626+ [LANDED, IMPORTED, OLDER].map((sha) =>627+ first.includes(`data-commit="${sha}"`)628+ )629+ ).toStrictEqual([true, true, false]);630+ expect(first).toMatch(/class="[^"]*\bsticky\b/u);631+ expect(textOf(page)).toContain("October 6, 2026");632 });633 424- it("shows a landing's ask and credit, and links the commit", () => {634+ it("shows a landing's ask and credit in one line, and its short id over its age", () => {635 const row = slice(markupOf(page), "data-commit", LANDED);636 427- expect(hrefsOf(row)).toContain("/datekit/asks/parse-iso-week");428- expect(hrefsOf(row)).toContain(`/datekit/commit/${LANDED}`);429- expect(row).toContain("Asked-by:");430- expect(hrefsOf(row)).toContain("/people/ines-v");637+ expect(hrefsOf(row)).toStrictEqual(638+ expect.arrayContaining([639+ "/datekit/asks/parse-iso-week",640+ `/datekit/commit/${LANDED}`,641+ "/people/ines-v",642+ ])643+ );644+ expect(row).toContain("Asked by");645+ expect(row.indexOf(LANDED.slice(0, 7))).toBeGreaterThan(-1);646+ expect(row.indexOf(LANDED.slice(0, 7))).toBeLessThan(row.indexOf(" ago"));647 });648 649+ it("marks a landing judged by sealed checks held back, with its lock", () => {650+ const held = decodeCommits([651+ {652+ author: signature("Bram", "2026-10-06T15:00:00.000Z"),653+ body: "",654+ committer: signature("platform", "2026-10-06T15:00:00.000Z"),655+ landing: {656+ ask: "parse-iso-week",657+ assisted: [],658+ author: "bram",659+ credits: [{ handle: "bram", role: "Signed-off-by" }],660+ heldBackTrailer: "parser: 4 sealed checks by 3 people",661+ landedAt: "2026-10-06T15:00:00.000Z",662+ parent: IMPORTED,663+ project: "datekit",664+ sha: LANDED,665+ },666+ parents: [IMPORTED],667+ sha: LANDED,668+ subject: "Answer parse-iso-week",669+ trailers: [],670+ tree: "4".repeat(40),671+ },672+ ]);673+674+ const row = slice(675+ markupOf(676+ <LogView677+ commits={held}678+ from={0}679+ now={now}680+ project={datekit}681+ rev="main"682+ />683+ ),684+ "data-commit",685+ LANDED686+ );687+688+ expect(row).toContain("held back");689+ expect(row).toContain("text-sealed");690+ expect(row).toContain("lucide-lock-keyhole");691+ });692+693 it("links the ask an opening's landing opened, and reads it as an opening", () => {694 const [opening] = decodeCommits([695 {696 author: signature("Okonkwo", "2026-10-06T15:00:00.000Z"),32 unmodified lines729 );730 731 expect(hrefsOf(row)).toContain("/datekit/asks/parse-iso-week");732 expect(row).toContain("Opened");473- expect(row).not.toContain(">Ask<");733 });734 735+ it("filters the page to the answers or the asks' openings", () => {736+ const answers = markupOf(737+ <LogView738+ commits={commits}739+ from={0}740+ now={now}741+ project={datekit}742+ rev="main"743+ show="answers"744+ />745+ );746+747+ expect(answers).toContain(`data-commit="${LANDED}"`);748+ expect(answers).not.toContain(`data-commit="${IMPORTED}"`);749+750+ const filters = navOf(markupOf(page), 'aria-label="Show"');751+752+ expect(hrefsOf(filters)).toStrictEqual([753+ "/datekit/commits/main",754+ "/datekit/commits/main?show=answers",755+ "/datekit/commits/main?show=openings",756+ ]);757+ expect(filters).toMatch(/aria-current="page"[^>]*>All</u);758+ });759+760 it("says an imported commit came before adoption", () => {761 const row = slice(markupOf(page), "data-commit", IMPORTED);762 763 expect(row).toContain("before adoption");56 unmodified lines820 ]);821 });822 });823 540-const decodeDiff = Schema.decodeSync(CommitDiff);824+/** Lines `1` to `count`, as a file's text. */825+const linesUpTo = (count: number) =>826+ `${Array.from({ length: count }, (_, index) => `line ${index + 1}`).join(827+ "\n"828+ )}\n`;829 542-const landedCommit: typeof Commit.Encoded = {543- author: signature("Bram", "2026-10-06T15:00:00.000Z"),544- body: "Parse ISO week dates.\n\nAsked-by: ines-v\nSigned-off-by: bram",545- committer: signature("platform", "2026-10-06T15:00:00.000Z"),546- landing: {547- ask: "parse-iso-week",548- assisted: [],549- author: "bram",550- credits: [551- { handle: "bram", role: "Signed-off-by" },552- { handle: "ines-v", role: "Asked-by" },553- ],554- landedAt: "2026-10-06T15:00:00.000Z",555- parent: IMPORTED,556- project: "datekit",557- sha: LANDED,558- verdict: {559- ask: "parse-iso-week",560- at: "2026-10-06T14:59:00.000Z",561- base: IMPORTED,562- checkVersion: "redThenGreen@0.0.0+abc",563- head: "7".repeat(40),564- heldBack: [],565- lanes: [566- {567- command: "bun test",568- durationMs: 1200,569- lane: "unit",570- result: "passed",571- },572- ],573- outcome: Schema.encodeSync(Outcome)(574- Outcome.cases.Landed.make({ sha: LandedSha.make(LANDED) })575- ),576- patchId: "8".repeat(64),577- project: "datekit",578- stage: "checks",579- tree: "4".repeat(40),580- verifier: "platform",581- },582- },583- parents: [IMPORTED],584- sha: LANDED,585- subject: "Answer parse-iso-week",586- trailers: [587- { key: "Asked-by", value: "ines-v <ines-v@users.example.com>" },588- { key: "Signed-off-by", value: "bram <bram@users.example.com>" },589- ],590- tree: "4".repeat(40),591-};592-593-const diff = decodeDiff({594- commit: landedCommit,830+/** `diff`, with an added file of 120 lines: long enough to start folded. */831+const long = decodeDiff({832+ ...Schema.encodeSync(CommitDiff)(diff),833 files: [834+ ...Schema.encodeSync(CommitDiff)(diff).files,835 {597- after: "9".repeat(40),836+ after: "d".repeat(40),837 binary: false,599- newText: "export const week = 1;\n",600- path: "src/week.ts",838+ newText: linesUpTo(120),839+ path: "data/zones.ts",840 status: "added",841 },603- {604- after: "a".repeat(40),605- before: "b".repeat(40),606- binary: false,607- newText: "export const parse = fromIso;\n",608- oldText: "export const parse = Date;\n",609- path: "src/parse.ts",610- status: "modified",611- },612- {613- before: "c".repeat(40),614- binary: false,615- oldText: "export const legacy = true;\n",616- path: "src/legacy.ts",617- status: "deleted",618- },842 ],620- truncated: false,843 });844 845 describe(CommitView, () => {846 const page = <CommitView diff={diff} now={now} project={datekit} />;847 626- it("names the people in its trailers, each linking their page", () => {627- const hrefs = hrefsOf(markupOf(page));848+ it("names the people in its credit, each linking their page, and shows its trailers once", () => {849+ const markup = markupOf(page);850+ const hrefs = hrefsOf(markup);851 629- expect(hrefs).toContain("/people/ines-v");630- expect(hrefs).toContain("/people/bram");852+ expect(hrefs).toStrictEqual(853+ expect.arrayContaining(["/people/ines-v", "/people/bram"])854+ );855+ expect(856+ ["Asked-by:", "Signed-off-by:", "data-body"].map((part) =>857+ countIn(markup, part)858+ )859+ ).toStrictEqual([1, 1, 1]);860+ expect(861+ /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markup)?.[0]862+ ).not.toContain("Asked-by");863 });864 865+ it("sets its body as prose in the sans, never in mono", () => {866+ const body =867+ /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markupOf(page))?.[0] ?? "";868+869+ expect(body).toContain("Parse ISO week dates.");870+ expect(body).not.toContain("font-mono");871+ expect(body).toContain("text-body");872+ });873+874 it("links no one from an imported commit's trailers", () => {875 const { landing: _landing, ...imported } = landedCommit;876 877 const markup = markupOf(5 unmodified lines883 );884 885 expect(hrefsOf(markup)).not.toContain("/people/bram");886 expect(markup).toContain("bram@users.example.com");887+ expect(markup).toContain("Before adoption");888 });889 648- it("shows the landing's ask, its answer and its verdict", () => {890+ it("leads with the landing's status line: landed as its id, and the ask it answered", () => {891 const markup = markupOf(page);892+ const text = mainOf(markup).replaceAll(/<[^>]+>/gu, "");893 894+ expect(text).toContain(`Landed as ${LANDED.slice(0, 7)}`);895+ expect(text).toContain("answered parse-iso-week");896 expect(hrefsOf(markup)).toContain("/datekit/asks/parse-iso-week");897 expect(hrefsOf(markup)).toContain("/datekit/answers/parse-iso-week");898 expect(markup).toContain('data-outcome="Landed"');899 });25 unmodified lines925 );926 927 expect(hrefsOf(markup)).toContain("/datekit/asks/parse-iso-week");928 expect(hrefsOf(markup)).not.toContain("/datekit/answers/parse-iso-week");684- expect(markup).toContain("Opened");929+ expect(markup).toContain("opened");930 });931 687- it("links its parent, and counts and names the files it changed", () => {932+ it("puts git's own facts on one line: author, committer and parent, linked", () => {933 const text = textOf(page);934 935 expect(hrefsOf(markupOf(page))).toContain(`/datekit/commit/${IMPORTED}`);691- expect(text).toContain("3 files changed");936+ expect(text).toContain("authored by Bram");937+ expect(text).toContain("committed by the platform");938+ expect(text).toContain(`parent ${IMPORTED.slice(0, 7)}`);939+ });940 693- for (const path of ["src/week.ts", "src/parse.ts", "src/legacy.ts"]) {694- expect(text).toContain(path);695- }941+ it("sends each changed file's diff as plain text, at the drawing's measures", () => {942+ const markup = markupOf(page);943 697- expect(markupOf(page)).not.toContain("<diffs-container");698- expect(markupOf(page)).not.toContain("<file-tree-container");944+ const plain =945+ /<div\b[^>]*data-diff="plain"[\s\S]*$/u.exec(markup)?.[0] ?? "";946+947+ expect(948+ ["leading-code", "min-w-[calc(6ch+2px)]", "pl-[2ch]"].filter(949+ (measure) => !plain.includes(measure)950+ )951+ ).toStrictEqual([]);952+ expect(953+ ["src/week.ts", "src/parse.ts", "src/legacy.ts"].filter(954+ (path) =>955+ !slice(plain, "data-file", path).includes('data-diffs-header=""')956+ )957+ ).toStrictEqual([]);958+ expect(959+ [960+ ["src/parse.ts", "export const parse = fromIso;"],961+ ["src/parse.ts", "export const parse = Date;"],962+ ["src/week.ts", "export const week = 1;"],963+ ].filter(964+ ([path = "", line = ""]) =>965+ !slice(plain, "data-file", path).includes(line)966+ )967+ ).toStrictEqual([]);968+ expect(markup).not.toMatch(/<(?:diffs|file-tree)-container/u);969 });970 971+ it("keeps each file's header at the top of the pane while its lines scroll", () => {972+ const header =973+ /<summary\b[^>]*data-diffs-header=""[^>]*>/u.exec(markupOf(page))?.[0] ??974+ "";975+976+ expect(header).toContain("sticky");977+ expect(header).toContain("top-0");978+ expect(header).toContain("h-11");979+ });980+981+ it("starts an added or deleted file past 80 lines folded", () => {982+ const markup = markupOf(983+ <CommitView diff={long} now={now} project={datekit} />984+ );985+986+ expect(slice(markup, "data-file", "data/zones.ts")).toContain(987+ 'data-folded="true"'988+ );989+ expect(slice(markup, "data-file", "data/zones.ts")).not.toMatch(990+ /<details\b[^>]*\bopen=/u991+ );992+ expect(slice(markup, "data-file", "src/parse.ts")).toContain(993+ 'data-folded="false"'994+ );995+ });996+997+ it("counts the diff in the inspector: files, additions and deletions, split by path", () => {998+ const facts = inspectorOf(999+ markupOf(1000+ <CommitView1001+ diff={long}1002+ now={now}1003+ project={datekit}1004+ territory={["src/**"]}1005+ />1006+ )1007+ );1008+1009+ const stats =1010+ /<section\b[^>]*aria-label="Diff stats"[\s\S]*?<\/section>/u.exec(1011+ facts1012+ )?.[0] ?? "";1013+1014+ const text = stats.replaceAll(/<[^>]+>/gu, " ").replaceAll(/\s+/gu, " ");1015+1016+ expect(text).toContain("4 files");1017+ expect(text).toContain("+122 added");1018+ expect(text).toContain("−2 removed");1019+ expect(slice(stats, "data-part", "territory")).toContain("+2");1020+ expect(slice(stats, "data-part", "other")).toContain("+120");1021+ });1022+1023 it("says when the commit is too large to show whole", () => {1024 const truncated = decodeDiff({1025 commit: landedCommit,1026 files: [{ binary: false, path: "data/zones.json", status: "modified" }],342 unmodified lines1369 );1370 1371 expect(isNotFound(failed)).toBeTruthy();1372 1051- const carried = Schema.decodeUnknownOption(Refusals)(1052- isNotFound(failed) ? failed.data : undefined1373+ const data: unknown = isNotFound(failed) ? failed.data : undefined;1374+1375+ // A missing path lands on its nearest folder, its refusal beside it.1376+ const carried = Option.orElse(1377+ Schema.decodeUnknownOption(Refusals)(data),1378+ () =>1379+ Option.map(1380+ Schema.decodeUnknownOption(SoftLanding)(data),1381+ ({ refusals }) => refusals1382+ )1383 );1384 1385 return {1386 calls: yield* Ref.get(calls),135 unmodified lines1522 })1523 );1524 });1525 1526+/** The soft landing a page's read ended in. */1527+const landingOf = <A, E>(read: Effect.Effect<A, E, Client>) =>1528+ Effect.gen(function* () {1529+ const calls = yield* Ref.make<readonly Sent[]>([]);1530+1531+ const failed = yield* Effect.flip(1532+ read.pipe(Effect.provide(platformOf(calls)))1533+ );1534+1535+ return Schema.decodeUnknownOption(SoftLanding)(1536+ isNotFound(failed) ? failed.data : undefined1537+ );1538+ }).pipe(Effect.orDie);1539+1540+describe("a missing path", () => {1541+ it.effect(1542+ "lands on the nearest folder that exists at the commit, with the refusal as its notice",1543+ () =>1544+ Effect.gen(function* () {1545+ const landing = yield* landingOf(1546+ readBlobPage({1547+ _splat: "src/format/locale/gone/x.ts",1548+ project: "datekit",1549+ rev: "main",1550+ })1551+ );1552+1553+ expect(1554+ Option.map(landing, ({ nearest }) => nearest.path)1555+ ).toStrictEqual(Option.some("src/format/locale"));1556+ expect(1557+ Option.map(landing, ({ refusals }) => explain(refusals))1558+ ).toStrictEqual(1559+ Option.some(1560+ explain([noPath(RepoPath.make("src/format/locale/gone/x.ts"))])1561+ )1562+ );1563+1564+ const atRoot = yield* landingOf(1565+ readTreePage({ _splat: "nope", project: "datekit", rev: "main" })1566+ );1567+1568+ expect(1569+ Option.map(atRoot, ({ nearest }) => nearest.path === undefined)1570+ ).toStrictEqual(Option.some(true));1571+ })1572+ );1573+1574+ it("renders the nearest folder with UnknownPath's own words above it", () => {1575+ const refusal = noPath(RepoPath.make("src/format/locale/gone/x.ts"));1576+1577+ const markup = markupOf(1578+ <CodeNotFound1579+ data={Schema.encodeSync(SoftLanding)({1580+ nearest: nested,1581+ now,1582+ project: datekit,1583+ refusals: [refusal],1584+ rev: "main",1585+ })}1586+ />1587+ );1588+1589+ const text = textOf(1590+ <CodeNotFound1591+ data={Schema.encodeSync(SoftLanding)({1592+ nearest: nested,1593+ now,1594+ project: datekit,1595+ refusals: [refusal],1596+ rev: "main",1597+ })}1598+ />1599+ );1600+1601+ for (const line of explain([refusal])) {1602+ expect(text).toContain(line.trim());1603+ }1604+1605+ expect(markup).toContain('data-refusal="UnknownPath"');1606+ expect(markup).toContain('data-entry="src/format/locale/en.ts"');1607+ expect(markup.indexOf('data-refusal="UnknownPath"')).toBeLessThan(1608+ markup.indexOf('data-entry="src/format/locale/en.ts"')1609+ );1610+ });1611+1612+ it("keeps any other refusal verbatim, with a way onward", () => {1613+ const refusal = new UnknownRevision({ rev: "v9" });1614+1615+ const element = (1616+ <CodeNotFound data={Schema.encodeSync(Refusals)([refusal])} />1617+ );1618+1619+ expect(markupOf(element)).toContain('data-refusal="UnknownRevision"');1620+ expect(hrefsOf(markupOf(element))).toContain("/");1621+ });1622+});1623+1624+/** The line a code page's route answers its headers with. */1625+const headersLine = (path: string) =>1626+ path.includes("/commit/")1627+ ? "headers: () => immutablePage"1628+ : "headers: ({ params }) => codePageHeaders(params.rev)";1629+1630+describe("a code page's caching", () => {1631+ it("keeps a page at a whole commit id for good, and a page at main or a tag briefly", () => {1632+ expect([AT, "main", TAG].map((rev) => codePageHeaders(rev))).toStrictEqual([1633+ immutablePage,1634+ branchPage,1635+ branchPage,1636+ ]);1637+ });1638+1639+ const routes: Readonly<Record<string, string>> = import.meta.glob(1640+ "../src/routes/$project/{tree,blob,why}/$rev/$.tsx",1641+ { eager: true, import: "default", query: "?raw" }1642+ );1643+1644+ const logs: Readonly<Record<string, string>> = import.meta.glob(1645+ "../src/routes/$project/{commits/$rev,commit/$sha}.tsx",1646+ { eager: true, import: "default", query: "?raw" }1647+ );1648+1649+ it("answers each code page with the headers its revision earns, and a commit's for good", () => {1650+ const pages = { ...routes, ...logs };1651+1652+ expect(Object.keys(pages)).toHaveLength(5);1653+ expect(1654+ Object.entries(pages).flatMap(([path, source]) =>1655+ source.includes(headersLine(path)) ? [] : [path]1656+ )1657+ ).toStrictEqual([]);1658+ });1659+});1660+1661 describe("the code browser's views", () => {1662 const sources: Readonly<Record<string, string>> = import.meta.glob(1663 "../src/features/code/**/*.{ts,tsx}",1664 { eager: true, import: "default", query: "?raw" }7 unmodified linesmodified:apps/web/test/line-hash.test.ts+53 added-1 removed
4 unmodified lines5 */6 import { describe, expect, it } from "@effect/vitest";7 import { Option } from "effect";8 9-import { lineHash, parseLineHash } from "../src/features/code/line-hash.ts";9+import {10+ diffLinesHash,11+ lineHash,12+ parseDiffHash,13+ parseLineHash,14+} from "../src/features/code/line-hash.ts";15 16 describe("a line anchor", () => {17 it("names one line", () => {18 expect(parseLineHash("#L10")).toStrictEqual(36 unmodified lines55 Option.some({ end: 42, start: 3 })56 );57 });58 });59+60+describe("a file in a commit's diff, by its anchor", () => {61+ it("names the file, its path decoded", () => {62+ expect(parseDiffHash("#diff-src%2Fparse.ts")).toStrictEqual(63+ Option.some({ lines: Option.none(), path: "src/parse.ts" })64+ );65+ });66+67+ it("names lines on the new side, or the old with D", () => {68+ expect(parseDiffHash("diff-src%2Fparse.ts:L4-L7")).toStrictEqual(69+ Option.some({70+ lines: Option.some({71+ end: 7,72+ path: "src/parse.ts",73+ side: "additions",74+ start: 4,75+ }),76+ path: "src/parse.ts",77+ })78+ );79+ expect(80+ Option.flatMap(parseDiffHash("#diff-a.ts:D3"), ({ lines }) => lines)81+ ).toStrictEqual(82+ Option.some({ end: 3, path: "a.ts", side: "deletions", start: 3 })83+ );84+ });85+86+ it("is written back as it is read", () => {87+ const lines = {88+ end: 9,89+ path: "src/a b.ts",90+ side: "additions",91+ start: 2,92+ } as const;93+94+ expect(95+ Option.flatMap(96+ parseDiffHash(diffLinesHash(lines)),97+ (named) => named.lines98+ )99+ ).toStrictEqual(Option.some(lines));100+ });101+102+ it("names nothing for another anchor", () => {103+ expect(parseDiffHash("#L4")).toStrictEqual(Option.none());104+ });105+});modified:apps/web/test/why.test.tsx+118 added-68 removed
1 /**2- * The "why" page, rendered to HTML with `react-dom/server` from a2+ * The file in Why mode, rendered to HTML with `react-dom/server` from a3 * `WhyView` decoded with the protocol's own schema: the server's fallback4- * is a table of ranges (lines a–b → the landing or the commit that brought5- * them) beside the numbered lines, each landing linking its ask, its6- * answer, its commit and its people; the browser's drawing is Pierre's7- * (`<diffs-container>`), loaded only there.4+ * is the numbered lines with a band above each group of lines one commit5+ * brought, ask and answer first and the commit second, each linked; the6+ * browser's drawing is Pierre's (`<diffs-container>`), loaded only there,7+ * with the same bands as its annotations.8 */9 import { describe, expect, it } from "@effect/vitest";10 import { Client, Contracts } from "@repo/protocol/contracts";11 import { CommitView, FileView, WhyView } from "@repo/protocol/domain/code";12 import { LandingView } from "@repo/protocol/domain/landing";13 import { Outcome } from "@repo/protocol/domain/outcome";14 import { LandedSha, ProjectName } from "@repo/protocol/ids";15 import { asTester, unanswered } from "@repo/protocol/testing";16-import { Duration, Effect, Layer, Ref, Schema } from "effect";16+import { DateTime, Duration, Effect, Layer, Ref, Schema } from "effect";17 import { RpcTest } from "effect/rpc";18 import type { ReactElement } from "react";19 import { renderToStaticMarkup } from "react-dom/server";20 18 unmodified lines39 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map((match) =>40 (match.groups?.href ?? "").replaceAll("&", "&")41 );42 43-/** The markup of the table row marked `data-range` with `value`. */44-const rowOf = (markup: string, value: string) =>45- new RegExp(`<tr\\b[^>]*data-range="${value}"[^>]*>[\\s\\S]*?</tr>`, "u").exec(46- markup47- )?.[0] ?? "";48-43 const datekit = ProjectName.make("datekit");44 45 const AT = "a".repeat(40);46 74 unmodified lines121 122 const TEXT =123 "export const iso = 1;\nexport const week = 2;\nexport const day = 3;\nexport const old = 4;\n";124 131-const page = <WhyLines project={datekit} rev="main" text={TEXT} view={view} />;125+const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");126 127+const page = (128+ <WhyLines now={now} project={datekit} rev="main" text={TEXT} view={view} />129+);130+131+/** The band of the group marked `data-range` with `value`, up to the next band or line. */132+const bandOf = (markup: string, value: string) => {133+ const start = markup.indexOf(`data-range="${value}"`);134+ const rest = markup.slice(start + 1);135+136+ const ends = [rest.indexOf("data-range="), rest.indexOf(' id="L')].filter(137+ (at) => at !== -1138+ );139+140+ return start === -1 ? "" : markup.slice(start, start + 1 + Math.min(...ends));141+};142+143 describe("the why page's fallback", () => {134- it("names the landing that brought lines 1–3, linking its ask, its answer, its commit and its people", () => {135- const row = rowOf(markupOf(page), "1-3");144+ it("names who brought lines 1–3, ask and answer first and the commit second, each linked", () => {145+ const band = bandOf(markupOf(page), "1-3");146+ const text = textOf(band);147 137- expect(textOf(row)).toContain("lines 1–3");138- expect(textOf(row)).toContain("Answer parse-iso-week");139- expect(textOf(row)).toContain("2 credits");140- expect(textOf(row)).toContain("checked and landed");141- expect(hrefsOf(row)).toStrictEqual(148+ expect(text).toContain("lines 1–3");149+ expect(text).toContain("parse-iso-week");150+ expect(text).toContain("answered by bram");151+ expect(152+ [text.indexOf("parse-iso-week"), text.indexOf("answered by bram")].every(153+ (at) => at > -1 && at < text.indexOf(LANDED.slice(0, 7))154+ )155+ ).toBeTruthy();156+ expect(hrefsOf(band)).toStrictEqual(157 expect.arrayContaining([158 "/datekit/asks/parse-iso-week",159 "/datekit/answers/parse-iso-week",160 `/datekit/commit/${LANDED}`,146- "/people/bram",161 ])162 );163 });164 165+ it("counts no credit and colours nothing by age", () => {166+ const markup = markupOf(page);167+168+ expect(textOf(markup)).not.toMatch(/\bcredits?\b/u);169+ expect(bandOf(markup, "1-3")).not.toMatch(170+ /text-(?:landed|waiting|refused|checking)/u171+ );172+ });173+174 it("says an imported commit's lines came before adoption", () => {152- const row = rowOf(markupOf(page), "4-4");175+ const band = bandOf(markupOf(page), "4-4");176 154- expect(textOf(row)).toContain("line 4");155- expect(textOf(row)).toContain("Add the formatter");156- expect(textOf(row)).toContain("Ada");157- expect(textOf(row)).toContain("before adoption");158- expect(hrefsOf(row)).toContain(`/datekit/commit/${IMPORTED}`);177+ expect(textOf(band)).toContain("line 4");178+ expect(textOf(band)).toContain("Add the formatter");179+ expect(textOf(band)).toContain("Ada");180+ expect(textOf(band)).toContain("before adoption");181+ expect(hrefsOf(band)).toContain(`/datekit/commit/${IMPORTED}`);182 });183 161- it("links the file as it was before each commit, and a proposal about each range's first line", () => {184+ it("offers why, one step back, and a proposal about each group's first line", () => {185 const markup = markupOf(page);186 const hrefs = hrefsOf(markup);187 188 expect(hrefs).toContain(`/datekit/why/${IMPORTED}/src/format.ts`);166- expect(textOf(markup)).toContain("Prior to this landing");189+ expect(textOf(markup)).toContain("why, one step back");190 expect(textOf(markup)).toContain("Propose an ask about this line");191 192 const proposal = hrefs193 .filter((href) => href.startsWith("/datekit/proposals/new?"))6 unmodified lines200 { about: "src/format.ts", at: AT, line: "4" },201 ]);202 });203 181- it("numbers every line beside the table, and leaves the drawing to the browser", () => {204+ it("puts each group's band above its first line, among the numbered lines, and leaves the drawing to the browser", () => {205 const markup = markupOf(page);206 207 expect(markup).toContain('id="L4"');208+ expect(markup).toContain('data-why="ranges"');209+ expect(markup.indexOf('data-range="4-4"')).toBeLessThan(210+ markup.indexOf('id="L4"')211+ );212+ expect(markup.indexOf('data-range="4-4"')).toBeGreaterThan(213+ markup.indexOf('id="L3"')214+ );215 expect(markup).not.toContain("<diffs-container");216 });217 218+ it("groups consecutive lines one commit brought into one band", () => {219+ const split = Schema.decodeSync(WhyView)({220+ ...Schema.encodeSync(WhyView)(view),221+ ranges: [222+ { end: 2, sha: LANDED, start: 1 },223+ { end: 3, sha: LANDED, start: 3 },224+ { end: 4, sha: IMPORTED, start: 4 },225+ ],226+ });227+228+ const markup = markupOf(229+ <WhyLines230+ now={now}231+ project={datekit}232+ rev="main"233+ text={TEXT}234+ view={split}235+ />236+ );237+238+ expect(239+ [...markup.matchAll(/data-range="(?<range>[^"]+)"/gu)].map(240+ (match) => match.groups?.range241+ )242+ ).toStrictEqual(["1-3", "4-4"]);243+ });244+245 it("says why a file without ranges has none", () => {246 const binary = Schema.decodeSync(WhyView)({247 at: AT,248 commits: [],2 unmodified lines251 ranges: [],252 });253 254 expect(198- textOf(markupOf(<WhyLines project={datekit} rev="main" view={binary} />))255+ textOf(256+ markupOf(257+ <WhyLines now={now} project={datekit} rev="main" view={binary} />258+ )259+ )260 ).toContain("binary or too large");261 });262+263+ it("is the same page as the file, in Why mode", () => {264+ const toggle =265+ /<nav\b[^>]*aria-label="Mode"[\s\S]*?<\/nav>/u.exec(266+ markupOf(page)267+ )?.[0] ?? "";268+269+ expect(hrefsOf(toggle)).toStrictEqual([270+ "/datekit/blob/main/src/format.ts",271+ "/datekit/why/main/src/format.ts",272+ ]);273+ expect(toggle).toMatch(/aria-current="page"[^>]*>Why</u);274+ });275 });276 277 const OPENED = "6".repeat(40);278 37 unmodified lines316 ],317 });318 319 const opened = (246- <WhyLines project={datekit} rev="main" text={TEXT} view={opening} />320+ <WhyLines now={now} project={datekit} rev="main" text={TEXT} view={opening} />321 );322 249-describe("the why page's row for an ask's opening", () => {250- it('links the ask it opened and reads "Open ask", with no answer link', () => {251- const row = rowOf(markupOf(opened), "2-3");323+describe("the why page's band for an ask's opening", () => {324+ it('links the ask it opened and reads "opened", with no answer link', () => {325+ const band = bandOf(markupOf(opened), "2-3");326 253- expect(textOf(row)).toContain("Open ask format-ordinal");254- expect(textOf(row)).toContain("ines-v");255- expect(textOf(row)).toContain("1 credit");256- expect(hrefsOf(row)).toContain("/datekit/asks/format-ordinal");327+ expect(textOf(band)).toContain("opened format-ordinal");328+ expect(textOf(band)).toContain("by ines-v");329+ expect(hrefsOf(band)).toContain("/datekit/asks/format-ordinal");330 expect(258- hrefsOf(row).filter((href) => href.includes("/answers/"))331+ hrefsOf(band).filter((href) => href.includes("/answers/"))332 ).toStrictEqual([]);333 });334 262- it('says "Open ask" once when the commit\'s subject already says it, still linking the ask', () => {263- const said = Schema.decodeSync(WhyView)({264- ...Schema.encodeSync(WhyView)(opening),265- commits: Schema.encodeSync(WhyView)(opening).commits.map((commit) =>266- commit.sha === OPENED267- ? { ...commit, subject: "Open ask format-ordinal" }268- : commit269- ),270- });271-272- const row = rowOf(273- markupOf(274- <WhyLines project={datekit} rev="main" text={TEXT} view={said} />275- ),276- "2-3"277- );278-279- expect(textOf(row).split("Open ask format-ordinal")).toHaveLength(2);280- expect(hrefsOf(row)).toContain("/datekit/asks/format-ordinal");281- expect(282- hrefsOf(row).filter((href) => href.includes("/answers/"))283- ).toStrictEqual([]);284- });285-335 it("keeps an answering landing's ask and answer links, and an adopted commit's words", () => {336 const markup = markupOf(opened);337 289- expect(hrefsOf(rowOf(markup, "1-1"))).toStrictEqual(338+ expect(hrefsOf(bandOf(markup, "1-1"))).toStrictEqual(339 expect.arrayContaining([340 "/datekit/asks/parse-iso-week",341 "/datekit/answers/parse-iso-week",342 ])343 );295- expect(textOf(rowOf(markup, "1-1"))).not.toContain("Open ask");296- expect(textOf(rowOf(markup, "4-4"))).toContain("before adoption");344+ expect(textOf(bandOf(markup, "1-1"))).not.toContain("opened");345+ expect(textOf(bandOf(markup, "4-4"))).toContain("before adoption");346 });347 });348 349 /** The line dialog's landing, rendered; nothing for no landing. */26 unmodified lines376 377 describe("the why page's drawing", () => {378 it("draws the file with @pierre/diffs", () => {379 expect(331- markupOf(<WhyCode project={datekit} text={TEXT} view={view} />)380+ markupOf(<WhyCode now={now} project={datekit} text={TEXT} view={view} />)381 ).toContain("<diffs-container");382 });383 });384 25 unmodified lines410 Layer.provide([411 Layer.mergeAll(412 unanswered,413 Contracts.toLayerHandler("why", () => during(Effect.succeed(view))),414+ Contracts.toLayerHandler("log", () => Effect.succeed({ commits: [] })),415 Contracts.toLayerHandler("readFile", (payload) =>416 during(417 Effect.gen(function* () {418 yield* Ref.update(asked, (was) => ({70 unmodified lines