Merge build/1211-code-browser
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 1d75a0d, 4592d84 · Browse files · 51 files·+5709 added−1639 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
51 files+5709 added−1639 removed
- tests:+1193 added−271 removed
- other:+4516 added−1368 removed
Provenance
- Commit
a6808d3- Tree
5f52cf3- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
1d75a0d- Parent 2
4592d84
51 files changed+5709 added−1639 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+401 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 { useMemo } from "react";23 import type { ReactNode } from "react";24 23-import { ProjectNav } from "../project/project-nav.tsx";24-import { ID, LABEL, LINK } from "../shared/classes.ts";25+import { Button } from "@/components/ui/button";26+27+import { CreditFacts, FactBlock, ProvenanceFacts } from "../shared/facts.tsx";28+import type { ProvenanceEntry } from "../shared/facts.tsx";29 import { HandleLink } from "../shared/handle.tsx";26-import { PageShell } from "../shared/layout.tsx";27-import { OutcomeView } from "../shared/outcome.tsx";30+import { AppLink } from "../shared/link.tsx";31+import { StateMarkIcon } from "../shared/marks.tsx";32 import { answerPath, askPath } from "../shared/paths.ts";33+import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";34 import { When } from "../shared/time.tsx";35 import { askOf } from "../why/rows.ts";36+import { drawnFiles, statsOf } from "./diff-model.ts";37+import type { DiffStats, DrawnFile } from "./diff-model.ts";38+import { DiffPane, PANE_SCROLLER } from "./diff-pane.tsx";31-import { blobHref, commitHref, shortSha, treeHref } from "./paths.ts";39+import { commitHref, shortSha, treeHref } from "./paths.ts";40+import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";41 33-const isRole = Schema.is(CreditRole);42+const LINK = "decoration-rule underline hover:decoration-current";43 35-const isHandle = Schema.is(Handle);44+/** A trailer line: `Key: value`, the key one word of letters and dashes. */45+const TRAILER = /^[A-Za-z][\w-]*:\s/u;46 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-);47+/**48+ * The body without its trailers, which the Credit block shows: git's49+ * trailer block is the last paragraph when every line of it is a50+ * `Key: value`.51+ */52+export const bodyWithoutTrailers = (commit: Commit) => {53+ const paragraphs = commit.body.trim().split(/\n\s*\n/u);54+ const last = paragraphs.at(-1) ?? "";55 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- );56+ const trailers =57+ commit.trailers.length > 0 &&58+ last.split("\n").every((line) => TRAILER.test(line.trim()));59 51- return commit.body52- .split("\n")53- .filter((line) => !trailers.has(line.trim()))54- .join("\n")55- .trim();60+ return (trailers ? paragraphs.slice(0, -1) : paragraphs).join("\n\n").trim();61 };62 58-const Person = ({59- label,63+/** Where the commit stands, in one line: landed as its SHA, and the ask it answered or opened. */64+export const LandingStatus = ({65+ commit,66+ project,67+}: {68+ readonly commit: Commit;69+ readonly project: ProjectName;70+}) => {71+ const { landing } = commit;72+73+ if (landing === undefined) {74+ return (75+ <p className="text-want text-muted-foreground flex items-start gap-2">76+ <StateMarkIcon className="mt-1" mark="notNeeded" />77+ <span>78+ Before adoption: this commit came in with the history the project79+ adopted, so no landing records it.80+ </span>81+ </p>82+ );83+ }84+85+ const linked = Option.getOrUndefined(askOf(landing));86+87+ return (88+ <p className="text-want flex items-start gap-2" data-outcome="Landed">89+ <StateMarkIcon className="mt-1" mark="landed" />90+ <span className="min-w-0 [overflow-wrap:anywhere]">91+ <strong className="text-landed font-semibold">Landed</strong> as{" "}92+ <AppLink93+ className={`text-mono font-mono ${LINK}`}94+ to={commitHref(project, commit.sha)}95+ >96+ {shortSha(commit.sha)}97+ </AppLink>98+ {linked === undefined ? null : (99+ <>100+ <span aria-hidden="true" className="text-muted-foreground">101+ {" · "}102+ </span>103+ {linked.kind === "opened" ? "opened " : "answered "}104+ <AppLink105+ className={`text-mono font-mono ${LINK}`}106+ to={askPath(project, linked.ask)}107+ >108+ {linked.ask}109+ </AppLink>110+ </>111+ )}112+ </span>113+ </p>114+ );115+};116+117+/** Git's own metadata, on one line: who wrote it, who committed it, its parents. */118+const GitLine = ({119+ commit,120 now,61- signature,121+ project,122 }: {63- readonly label: string;123+ readonly commit: Commit;124 readonly now: DateTime.Utc;65- readonly signature: Signature;125+ readonly project: ProjectName;126 }) => (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} />127+ <span className="[overflow-wrap:anywhere]">128+ authored by {commit.author.name} <When at={commit.author.at} now={now} />129+ {" · "}130+ committed by{" "}131+ {commit.landing === undefined ? commit.committer.name : "the platform"}132+ {" · "}133+ {commit.parents.length === 0 ? (134+ "the first commit"135+ ) : (136+ <>137+ {commit.parents.length === 1 ? "parent" : "parents"}{" "}138+ {commit.parents.map((parent, index) => (139+ <span key={parent}>140+ {index === 0 ? null : ", "}141+ <AppLink142+ className={`text-mono font-mono ${LINK}`}143+ to={commitHref(project, parent)}144+ >145+ {shortSha(parent)}146+ </AppLink>147+ </span>148+ ))}149+ </>150+ )}151+ {" · "}152+ <AppLink className={LINK} to={treeHref(project, commit.sha)}>153+ Browse files154+ </AppLink>155+ </span>156+);157+158+const PART_WORDS = {159+ other: "other",160+ territory: "territory",161+ tests: "tests",162+} as const;163+164+/** The diff in numbers: files, lines added and removed, then split by path. */165+export const DiffStatsFacts = ({ stats }: { readonly stats: DiffStats }) => (166+ <FactBlock label="Diff stats">167+ <p168+ className="text-ui flex flex-wrap items-center gap-x-3 gap-y-1"169+ data-stats=""170+ >171+ <span>172+ {stats.files} {stats.files === 1 ? "file" : "files"}173 </span>74- </dd>75- </div>174+ <ChangeCounts additions={stats.additions} deletions={stats.deletions} />175+ </p>176+ {stats.parts.length === 0 ? null : (177+ <ul className="text-ui flex flex-col gap-1">178+ {stats.parts.map((part) => (179+ <li180+ className="flex items-center justify-between gap-3"181+ data-part={part.label}182+ key={part.label}183+ >184+ <span className="text-muted-foreground">185+ {PART_WORDS[part.label]}186+ <span className="sr-only">:</span>187+ </span>188+ <ChangeCounts189+ additions={part.additions}190+ deletions={part.deletions}191+ />192+ </li>193+ ))}194+ </ul>195+ )}196+ </FactBlock>197 );198 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, "");199+/** The trailers of a commit the platform did not land, as written, linking no one. */200+const WrittenTrailers = ({ commit }: { readonly commit: Commit }) =>201+ commit.trailers.length === 0 ? null : (202+ <FactBlock label="Trailers">203+ <ul className="text-mono leading-terminal flex flex-col gap-1 font-mono">204+ {commit.trailers.map(({ key, value }) => (205+ <li className="[overflow-wrap:anywhere]" key={`${key}:${value}`}>206+ <span className="text-muted-foreground">{key}:</span> {value}207+ </li>208+ ))}209+ </ul>210+ </FactBlock>211+ );212 87- return landed && isRole(name) && isHandle(handle) ? handle : undefined;88-};213+/** A landing's credit from the record; a commit the platform did not land, its trailers as written. */214+const LandingCredit = ({ commit }: { readonly commit: Commit }) =>215+ commit.landing === undefined ? (216+ <WrittenTrailers commit={commit} />217+ ) : (218+ <CreditFacts219+ assisted={commit.landing.assisted}220+ credits={commit.landing.credits}221+ heldBack={commit.landing.heldBackTrailer}222+ />223+ );224 90-/** A trailer: a landing's credit links the person; any other reads as written. */91-const Trailer = ({92- landed,93- name,94- value,225+/** Where the commit comes from: its id, its tree, its people and parents, and the landing's request. */226+const provenanceOf = (commit: Commit): readonly ProvenanceEntry[] => [227+ { label: "Commit", value: commit.sha },228+ { label: "Tree", value: commit.tree },229+ { label: "Author", value: `${commit.author.name} <${commit.author.email}>` },230+ {231+ label: "Committer",232+ value: `${commit.committer.name} <${commit.committer.email}>`,233+ },234+ ...commit.parents.map((parent, index) => ({235+ label: commit.parents.length === 1 ? "Parent" : `Parent ${index + 1}`,236+ value: parent,237+ })),238+ ...(commit.landing?.verdict === undefined239+ ? []240+ : [{ label: "Patch id", value: commit.landing.verdict.patchId }]),241+ ...(commit.landing?.requestId === undefined242+ ? []243+ : [{ label: "Request-Id", value: commit.landing.requestId }]),244+];245+246+/** The inspector's facts for a commit. */247+const CommitFacts = ({248+ commit,249+ project,250+ stats,251 }: {96- readonly landed: boolean;97- readonly name: string;98- readonly value: string;252+ readonly commit: Commit;253+ readonly project: ProjectName;254+ readonly stats: DiffStats;255 }) => {100- const person = personIn(landed, name, value);256+ const linked =257+ commit.landing === undefined258+ ? undefined259+ : Option.getOrUndefined(askOf(commit.landing));260 261 return (103- <li className="[overflow-wrap:anywhere]">104- <span className="text-muted-foreground">{name}:</span>{" "}105- {person === undefined ? value : <HandleLink handle={person} />}106- </li>262+ <>263+ <FactBlock label="State">264+ <LandingStatus commit={commit} project={project} />265+ {commit.landing === undefined ? null : (266+ <p className="text-ui text-muted-foreground">267+ By <HandleLink handle={commit.landing.author} />268+ {linked === undefined || linked.kind === "opened" ? null : (269+ <>270+ {" · "}271+ <AppLink className={LINK} to={answerPath(project, linked.ask)}>272+ the answer and its checks273+ </AppLink>274+ </>275+ )}276+ </p>277+ )}278+ </FactBlock>279+ <LandingCredit commit={commit} />280+ <DiffStatsFacts stats={stats} />281+ <ProvenanceFacts entries={provenanceOf(commit)} />282+ </>283 );284 };285 110-/** The changed files by path, each linking its new version (or its old one, deleted). */111-export const ChangedList = ({112- commit,286+/** A segmented pair of buttons, the pressed one in ink. */287+const SEGMENT =288+ "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";289+290+/** The diff's toolbar: unified or split, fold or unfold every file, and the counts. */291+export const DiffToolbar = ({292+ allFolded,293 files,114- project,294+ onFoldAll,295+ onSplit,296+ split,297+ stats,298 }: {116- readonly commit: Commit;117- readonly files: readonly ChangedFile[];118- readonly project: ProjectName;299+ readonly split: boolean;300+ readonly onSplit?: ((split: boolean) => void) | undefined;301+ /** Whether every file is folded now. */302+ readonly allFolded: boolean;303+ readonly onFoldAll?: ((folded: boolean) => void) | undefined;304+ readonly stats: DiffStats;305+ /** The Files button, below the shell's width. */306+ readonly files?: ReactNode;307 }) => (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>308+ <>309+ {files === undefined ? null : (310+ <div className="shell:hidden flex shrink-0">{files}</div>311+ )}312+ <fieldset className="border-input diffsplit:flex m-0 hidden min-w-0 border p-0">313+ <legend className="sr-only">Diff layout</legend>314+ <button315+ aria-pressed={!split}316+ className={SEGMENT}317+ onClick={() => onSplit?.(false)}318+ type="button"319+ >320+ <Rows3 aria-hidden="true" strokeWidth={1.75} />321+ Unified322+ </button>323+ <button324+ aria-pressed={split}325+ className={SEGMENT}326+ onClick={() => onSplit?.(true)}327+ type="button"328+ >329+ <Columns2 aria-hidden="true" strokeWidth={1.75} />330+ Split331+ </button>332+ </fieldset>333+ <span className="text-muted-foreground">334+ <Button onClick={() => onFoldAll?.(!allFolded)} size="sm" variant="ghost">335+ {allFolded ? (336+ <UnfoldVertical aria-hidden="true" strokeWidth={1.75} />337+ ) : (338+ <FoldVertical aria-hidden="true" strokeWidth={1.75} />339+ )}340+ {allFolded ? "Unfold all" : "Collapse all"}341+ </Button>342+ </span>343+ <p className="text-ui text-muted-foreground ml-auto flex items-center gap-3 tabular-nums">344+ <span>345+ {stats.files} {stats.files === 1 ? "file" : "files"}346+ <span className="tablet:inline hidden"> changed</span>347+ </span>348+ <ChangeCounts additions={stats.additions} deletions={stats.deletions} />349+ </p>350+ </>351 );352 353+export interface CommitViewProps {354+ readonly diff: CommitDiff;355+ readonly now: DateTime.Utc;356+ readonly project: ProjectName;357+ /** The ask's territory, when the commit landed an answer: the stats split by it. */358+ readonly territory?: readonly string[] | undefined;359+ /** Old and new side by side. */360+ readonly split?: boolean;361+ readonly onSplit?: ((split: boolean) => void) | undefined;362+ /** The files folded now; each file's default when absent. */363+ readonly folded?: ReadonlySet<string> | undefined;364+ readonly onFold?: ((path: string, folded: boolean) => void) | undefined;365+ readonly onFoldAll?: ((folded: boolean) => void) | undefined;366+ /** The browser's drawing of the diff, holding `PlainDiff` as its fallback. */367+ readonly drawing?: ReactNode;368+ /** The Files button, below the shell's width. */369+ readonly files?: ReactNode;370+ /** The diff's files already parsed (`drawnFiles`), so a page parses each once. */371+ readonly drawn?: readonly DrawnFile[] | undefined;372+}373+374 export const CommitView = ({375 diff,376 drawing,377+ drawn: parsed,378+ files: filesButton,379+ folded,380 now,381+ onFold,382+ onFoldAll,383+ onSplit,384 project,385 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-}) => {386+ territory,387+}: CommitViewProps) => {388 const { commit, files, truncated } = diff;173- const { landing } = commit;174-175- const linked =176- landing === undefined ? undefined : Option.getOrUndefined(askOf(landing));177-389 const body = bodyWithoutTrailers(commit);179- const here = commitHref(project, commit.sha);390+ const drawn = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);391+ const stats = useMemo(() => statsOf(drawn, territory), [drawn, territory]);392 393+ const allFolded = drawn.every((file) =>394+ folded === undefined ? file.folded : folded.has(file.file.path)395+ );396+397 return (182- <PageShell398+ <Workspace399+ facts={<CommitFacts commit={commit} project={project} stats={stats} />}400+ factsHeading={401+ commit.landing === undefined ? "This commit" : "This landing"402+ }403+ meta={<GitLine commit={commit} now={now} project={project} />}404+ state={405+ commit.landing === undefined ? undefined : (406+ <span className="flex items-center gap-1.5">407+ <StateMarkIcon mark="landed" />408+ <strong className="text-landed font-semibold">Landed</strong>409+ </span>410+ )411+ }412+ status={413+ <div className="flex flex-col gap-4">414+ <LandingStatus commit={commit} project={project} />415+ {body === "" ? null : (416+ <p417+ className="text-body max-w-[70ch] [overflow-wrap:anywhere] whitespace-pre-wrap"418+ data-body=""419+ >420+ {body}421+ </p>422+ )}423+ </div>424+ }425 title={426 commit.subject === ""427 ? `Commit ${shortSha(commit.sha)}`428 : commit.subject429 }430+ toolbar={431+ <DiffToolbar432+ allFolded={allFolded}433+ files={filesButton}434+ onFoldAll={onFoldAll}435+ onSplit={onSplit}436+ split={split}437+ stats={stats}438+ />439+ }440+ variant="code"441 >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">442+ {truncated ? (443+ <div className={`${GUTTER} ${MEASURE}`}>444+ <p className="border-rule text-ui border border-dashed px-4 py-3">445 This commit is too large to show whole: its files are listed by446 path, without their changes.447 </p>326- ) : null}327- {drawing === undefined || truncated ? (328- <ChangedList commit={commit} files={files} project={project} />329- ) : (330- drawing448+ </div>449+ ) : null}450+ <DiffPane>451+ {drawing ?? (452+ <div className={PANE_SCROLLER}>453+ <PlainDiff454+ drawn={drawn}455+ files={files}456+ folded={folded}457+ onFold={onFold}458+ split={split}459+ />460+ </div>461 )}332- </section>333- </PageShell>462+ </DiffPane>463+ </Workspace>464 );465 };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+331 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+ // The folds as they are now, read when the address moves: a fold the192+ // reader makes later must neither unfold the named file again nor193+ // scroll back to it.194+ const folds = useRef({ folded, onFold });195+196+ useEffect(() => {197+ folds.current = { folded, onFold };198+ });199+200+ // An address naming a file scrolls to it, and its lines are selected.201+ useEffect(() => {202+ const named = parseDiffHash(hash);203+204+ if (Option.isNone(named) || !byPath.has(named.value.path)) {205+ return;206+ }207+208+ const { lines, path } = named.value;209+210+ if (folds.current.folded?.has(path) === true) {211+ folds.current.onFold?.(path, false);212+ }213+214+ reveal(handle.current, container.current, path);215+216+ if (Option.isSome(lines)) {217+ handle.current?.setSelectedLines({218+ id: path,219+ range: {220+ end: lines.value.end,221+ side: lines.value.side,222+ start: lines.value.start,223+ },224+ });225+ handle.current?.scrollTo({226+ align: "center",227+ id: path,228+ lineNumber: lines.value.start,229+ side: lines.value.side,230+ type: "line",231+ });232+ }233+ }, [byPath, hash]);234+235+ const options = useMemo(236+ (): CodeViewReactOptions<DiffAnnotation, undefined> => ({237+ ...diffsOptions,238+ diffIndicators: split ? "bars" : "classic",239+ diffStyle: split ? "split" : "unified",240+ enableLineSelection: true,241+ hunkSeparators: "line-info",242+ layout: { gap: 0, paddingBottom: 16, paddingTop: 0 },243+ lineDiffType: "word-line",244+ lineHoverHighlight: "both",245+ overflow: "scroll",246+ stickyHeaders: true,247+ unsafeCSS: HEADER_CSS,248+ }),249+ [split]250+ );251+252+ // A view drawn with no router around it (its own test) follows no address.253+ const router = useRouter({ warn: false });254+255+ return (256+ <CodePool>257+ {Predicate.isNotNullish(router) ? (258+ <HashFollower onHash={setHash} />259+ ) : null}260+ <div className="contents" data-diff="pierre">261+ <CodeView<DiffAnnotation>262+ className={PANE_SCROLLER}263+ containerRef={container}264+ items={items}265+ onSelectedLinesChange={(selection) => {266+ const url = `${globalThis.location.pathname}${globalThis.location.search}`;267+268+ globalThis.history.replaceState(269+ globalThis.history.state,270+ "",271+ selection === null272+ ? url273+ : `${url}#${diffLinesHash({274+ end: Math.max(selection.range.start, selection.range.end),275+ path: selection.id,276+ side: selection.range.side ?? "additions",277+ start: Math.min(selection.range.start, selection.range.end),278+ })}`279+ );280+ }}281+ options={options}282+ ref={handle}283+ renderAnnotation={(annotation) => annotation.metadata?.render()}284+ renderHeaderMetadata={(item) => {285+ const file = byPath.get(item.id);286+ const slot = slotOf(item.id);287+288+ return (289+ // Pierre prints the counts itself; what it cannot say is here.290+ <span className="flex items-center gap-3 font-sans">291+ {file === undefined || Option.isSome(file.diff) ? null : (292+ <span className="text-muted-foreground">293+ {file.file.binary ? "binary" : "not shown"}294+ </span>295+ )}296+ {slot?.header}297+ </span>298+ );299+ }}300+ renderHeaderPrefix={(item) => {301+ const closed = item.collapsed === true;302+303+ return (304+ <button305+ aria-expanded={!closed}306+ aria-label={`${closed ? "Unfold" : "Fold"} ${item.id}`}307+ className="text-muted-foreground hover:text-foreground -ml-1 flex size-6 items-center justify-center"308+ onClick={() => {309+ onFold?.(item.id, !closed);310+ }}311+ type="button"312+ >313+ <ChevronDown314+ aria-hidden="true"315+ className={`size-4 transition-transform duration-150 ${closed ? "-rotate-90" : ""}`}316+ strokeWidth={1.75}317+ />318+ </button>319+ );320+ }}321+ renderHeaderFilenameSuffix={(item) => {322+ const status = slotOf(item.id)?.status;323+324+ if (status === "refused") {325+ return (326+ <span className="text-refused flex items-center gap-1 font-sans">327+ <OctagonX328+ aria-hidden="true"329+ className="size-3.5"330+ strokeWidth={1.75}331+ />332+ <span className="sr-only">refused here</span>333+ </span>334+ );335+ }336+337+ return status === "read" ? (338+ <span className="text-muted-foreground flex items-center gap-1 font-sans">339+ <Check340+ aria-hidden="true"341+ className="size-3.5"342+ strokeWidth={1.75}343+ />344+ <span className="sr-only">read</span>345+ </span>346+ ) : null;347+ }}348+ />349+ </div>350+ </CodePool>351+ );352 };353 354 // `React.lazy` takes a module's default export.355 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+351 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 { useKeys } from "../shared/keys.tsx";22+import type { KeyPress } from "../shared/keys.tsx";23+import { AppLink } from "../shared/link.tsx";24+import { CopyButton } from "./copy.tsx";25+import {26+ ancestorsOf,27+ blobHref,28+ rawHref,29+ sizeInWords,30+ treeHref,31+ whyHref,32+} from "./paths.ts";33+34+/** A text's lines, without the empty one after its last newline. */35+export const linesOf = (text: string): readonly string[] => {36+ const lines = text.split("\n");37+38+ return lines.at(-1) === "" ? lines.slice(0, -1) : lines;39+};40+41+/** The language a file is written in, by its name; none for one this list does not know. */42+const LANGUAGES: readonly (readonly [RegExp, string])[] = [43+ [/\.(?:c|m)?tsx?$/u, "TypeScript"],44+ [/\.(?:c|m)?jsx?$/u, "JavaScript"],45+ [/\.json$/u, "JSON"],46+ [/\.(?:md|markdown|mdown)$/u, "Markdown"],47+ [/\.ya?ml$/u, "YAML"],48+ [/\.toml$/u, "TOML"],49+ [/\.css$/u, "CSS"],50+ [/\.html?$/u, "HTML"],51+ [/\.rs$/u, "Rust"],52+ [/\.go$/u, "Go"],53+ [/\.py$/u, "Python"],54+ [/\.(?:sh|bash|zsh)$/u, "Shell"],55+ [/(?:^|\/)Dockerfile$/u, "Dockerfile"],56+ [/\.sql$/u, "SQL"],57+ [/\.rb$/u, "Ruby"],58+ [/\.java$/u, "Java"],59+ [/\.kt$/u, "Kotlin"],60+ [/\.swift$/u, "Swift"],61+ [/\.c$|\.h$/u, "C"],62+ [/\.(?:cc|cpp|hpp)$/u, "C++"],63+];64+65+export const languageOf = (path: string) =>66+ LANGUAGES.find(([pattern]) => pattern.test(path))?.[1];67+68+/** A file in words: its lines, its size, its language. */69+export const fileWords = (file: FileView): readonly string[] => [70+ ...(file.text === undefined71+ ? []72+ : [73+ `${linesOf(file.text).length.toLocaleString("en")} ${74+ linesOf(file.text).length === 1 ? "line" : "lines"75+ }`,76+ ]),77+ sizeInWords(file.size),78+ ...(file.binary ? ["binary"] : []),79+ ...(languageOf(file.path) === undefined ? [] : [languageOf(file.path) ?? ""]),80+];81+82+/**83+ * Whether `press` asks for the permalink: `y`, with no modifier, outside a84+ * field, and only while the single keys are on (the switch in the keys85+ * dialog turns this one off too).86+ */87+export const permalinkPress = (press: KeyPress, on: boolean) =>88+ on &&89+ press.key === "y" &&90+ !press.inField &&91+ !press.altKey &&92+ !press.ctrlKey &&93+ !press.metaKey;94+95+/** `y` rewrites the address to the page at its commit, keeping the line anchor. */96+export const PermalinkKey = ({ href }: { readonly href: string }) => {97+ const on = useKeys()?.on ?? true;98+99+ useEffect(() => {100+ const onKey = (event: KeyboardEvent) => {101+ const [target] = event.composedPath();102+103+ const inField =104+ target instanceof HTMLElement &&105+ (target.isContentEditable ||106+ target.closest("input, select, textarea, [role=combobox]") !== null);107+108+ if (109+ permalinkPress(110+ {111+ altKey: event.altKey,112+ ctrlKey: event.ctrlKey,113+ inField,114+ key: event.key,115+ metaKey: event.metaKey,116+ },117+ on118+ )119+ ) {120+ globalThis.history.replaceState(121+ globalThis.history.state,122+ "",123+ `${href}${globalThis.location.search}${globalThis.location.hash}`124+ );125+ }126+ };127+128+ globalThis.addEventListener("keydown", onKey);129+130+ return () => {131+ globalThis.removeEventListener("keydown", onKey);132+ };133+ }, [href, on]);134+135+ return null;136+};137+138+const CRUMB =139+ "text-muted-foreground hover:text-foreground min-w-0 truncate no-underline transition-colors duration-[120ms]";140+141+/** A button that copies `text` with only its mark showing; its name says what it copies. */142+const CopyMark = ({143+ label,144+ text,145+}: {146+ readonly label: string;147+ readonly text: string;148+}) => {149+ const { copied, copy } = useCopy(text);150+151+ return (152+ <button153+ aria-label={154+ copied ? `Copied ${label.toLowerCase().replace(/^copy /u, "")}` : label155+ }156+ className="text-muted-foreground hover:text-foreground hover:bg-surface flex size-7 shrink-0 cursor-pointer items-center justify-center"157+ onClick={copy}158+ title={label}159+ type="button"160+ >161+ {copied ? (162+ <Check aria-hidden="true" className="size-3.5" strokeWidth={1.75} />163+ ) : (164+ <Copy aria-hidden="true" className="size-3.5" strokeWidth={1.75} />165+ )}166+ </button>167+ );168+};169+170+/** The path as links: the project, each folder at `rev`, then the name itself. */171+export const PathTrail = ({172+ path,173+ project,174+ rev,175+}: {176+ readonly path: string | undefined;177+ readonly project: ProjectName;178+ readonly rev: string;179+}) => {180+ const here = path === undefined || path === "" ? undefined : path;181+ const name = here?.split("/").at(-1);182+183+ return (184+ <nav185+ aria-label="Path"186+ className="flex min-w-0 items-center gap-1"187+ data-slot="breadcrumb"188+ >189+ <ol className="text-mono flex min-w-0 items-center gap-1 font-mono">190+ {/* On a phone the toolbar has room for the name alone: the folders191+ above it are the Files sheet's. */}192+ <li193+ className={`${here === undefined ? "flex" : "tablet:flex hidden"} min-w-0 shrink-0 items-center`}194+ >195+ {here === undefined ? (196+ <span aria-current="page" className="text-foreground font-medium">197+ {project}198+ </span>199+ ) : (200+ <AppLink className={CRUMB} to={treeHref(project, rev)}>201+ {project}202+ </AppLink>203+ )}204+ </li>205+ {here === undefined206+ ? null207+ : ancestorsOf(here).map((folder) => (208+ <Fragment key={folder}>209+ <li210+ aria-hidden="true"211+ className="text-muted-foreground tablet:block hidden"212+ >213+ /214+ </li>215+ <li className="tablet:flex hidden min-w-0 items-center">216+ <AppLink217+ className={CRUMB}218+ to={treeHref(project, rev, folder)}219+ >220+ {folder.split("/").at(-1)}221+ </AppLink>222+ </li>223+ </Fragment>224+ ))}225+ {name === undefined ? null : (226+ <>227+ <li228+ aria-hidden="true"229+ className="text-muted-foreground tablet:block hidden"230+ >231+ /232+ </li>233+ <li className="flex min-w-0 items-center">234+ <span235+ aria-current="page"236+ className="text-foreground min-w-0 truncate font-medium"237+ title={here}238+ >239+ {name}240+ </span>241+ </li>242+ </>243+ )}244+ </ol>245+ {here === undefined ? null : <CopyMark label="Copy path" text={here} />}246+ </nav>247+ );248+};249+250+const SEGMENT =251+ "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";252+253+/** Code | Why: the file, or why each of its lines is there; one page, two addresses. */254+export const ModeToggle = ({255+ mode,256+ path,257+ project,258+ rev,259+}: {260+ readonly mode: "code" | "why";261+ readonly path: string;262+ readonly project: ProjectName;263+ readonly rev: string;264+}) => (265+ <nav aria-label="Mode" className="border-input flex shrink-0 border">266+ <AppLink267+ aria-current={mode === "code" ? "page" : undefined}268+ className={SEGMENT}269+ to={blobHref(project, rev, path)}270+ >271+ Code272+ </AppLink>273+ <AppLink274+ aria-current={mode === "why" ? "page" : undefined}275+ className={SEGMENT}276+ to={whyHref(project, rev, path)}277+ >278+ Why279+ </AppLink>280+ </nav>281+);282+283+const TOOL = buttonVariants({284+ className: "no-underline",285+ size: "sm",286+ variant: "ghost",287+});288+289+/** The file header, as the page's toolbar. */290+export const FileHeader = ({291+ file,292+ files,293+ mode,294+ path,295+ project,296+ rev,297+}: {298+ readonly project: ProjectName;299+ readonly rev: string;300+ /** The folder or file the page is about; the root when absent. */301+ readonly path?: string | undefined;302+ /** Code or Why, on a file's page; nothing on a folder's. */303+ readonly mode?: "code" | "why";304+ /** The file, read: its size in words, its bytes and its text to copy. */305+ readonly file?: FileView;306+ /** The Files button, below the shell's width. */307+ readonly files?: ReactNode;308+}) => (309+ <>310+ {files === undefined ? null : (311+ <div className="shell:hidden flex shrink-0">{files}</div>312+ )}313+ <div className="flex min-w-0 flex-1 items-center gap-3">314+ <PathTrail path={path} project={project} rev={rev} />315+ {file === undefined ? null : (316+ <p className="text-ui text-muted-foreground diffsplit:block hidden shrink-0 truncate tabular-nums">317+ {fileWords(file).join(" · ")}318+ </p>319+ )}320+ </div>321+ {mode === undefined || path === undefined ? null : (322+ <ModeToggle mode={mode} path={path} project={project} rev={rev} />323+ )}324+ {file === undefined ? null : (325+ <nav326+ aria-label="File"327+ className="shell:flex hidden shrink-0 items-center gap-0.5"328+ data-toolbar="file"329+ >330+ <a className={TOOL} href={rawHref(project, file.at, file.path)}>331+ Raw332+ </a>333+ <AppLink334+ className={TOOL}335+ title="Permalink (y)"336+ to={(mode === "why" ? whyHref : blobHref)(337+ project,338+ file.at,339+ file.path340+ )}341+ >342+ <Link2 aria-hidden="true" strokeWidth={1.75} />343+ Permalink344+ </AppLink>345+ {file.text === undefined ? null : (346+ <CopyButton label="Copy" text={file.text} />347+ )}348+ </nav>349+ )}350+ </>351+);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+205 added-130 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+ // The pager keeps the kind the page shows.225+ const kind = show === "all" ? {} : { show };226+ const shown = commits.filter((commit) => shows(show, commit));227+ const base = commitsHref(project, rev, filter);228+ const [to, query = ""] = base.split("?");229 230 return (170- <PageShell171- title={172- path === undefined173- ? `Commits on ${revLabel(rev)}`174- : `History of ${path} on ${revLabel(rev)}`231+ <Workspace232+ title={titleOf(path, rev)}233+ toolbar={234+ <nav aria-label="Show" className="flex h-full items-center gap-4">235+ {FILTERS.map(({ label, show: each }) => (236+ <AppLink237+ aria-current={show === each ? "page" : undefined}238+ className={FILTER}239+ key={each}240+ search={searchFor(query, each)}241+ to={to ?? base}242+ >243+ {label}244+ </AppLink>245+ ))}246+ </nav>247 }248+ variant="list"249 >177- <ProjectNav current="landings" project={project} />250 {path === undefined ? null : (179- <p className="text-sm">180- <a className={LINK} href={blobHref(project, rev, path)}>251+ <p className="text-ui">252+ <AppLink className={LINK} to={blobHref(project, rev, path)}>253 Back to {path}182- </a>254+ </AppLink>255 </p>256 )}185- {commits.length === 0 ? (186- <EmptyState title="No commits on this page." />257+ {shown.length === 0 ? (258+ <EmptyState259+ title={260+ commits.length === 0261+ ? "No commits on this page."262+ : "None of this page's commits are of this kind."263+ }264+ />265 ) : (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- ))266+ <div className="flex flex-col">267+ {byDay(shown).map(({ commits: ofDay, day }) => (268+ <div data-day={day} key={day}>269+ <RowGroup270+ counts={`${ofDay.length} ${ofDay.length === 1 ? "commit" : "commits"}`}271+ label={day}272+ name={dayWords.format(273+ DateTime.toDateUtc(ofDay[0]?.committer.at ?? now)274+ )}275+ >276+ {ofDay.map((commit) => (277+ <CommitRow278+ commit={commit}279+ key={commit.sha}280+ now={now}281+ project={project}282+ />283+ ))}284+ </RowGroup>285+ </div>286+ ))}287+ </div>288 )}289 <Pager290 newer={291 from > 0217- ? commitsHref(project, rev, newerPage(from, path))292+ ? commitsHref(project, rev, { ...newerPage(from, path), ...kind })293 : undefined294 }295 older={296 next === undefined297 ? undefined223- : commitsHref(project, rev, { ...filter, from: next })298+ : commitsHref(project, rev, { ...filter, ...kind, from: next })299 }300 />226- </PageShell>301+ </Workspace>302 );303 };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+62 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+import type { ReactNode } from "react";13 9-import { NotFoundView } from "../ask/refused.tsx";14+import { EmptyState } from "../shared/empty.tsx";15+import { AppLink } from "../shared/link.tsx";16+import { RefusalView } from "../shared/refusal.tsx";17 import { Refusals } from "../shared/refusals.ts";18+import { Workspace } from "../shared/shell/workspace.tsx";19+import { SoftLanding } from "./soft-landing.ts";20+import { TreeView } from "./tree-view.tsx";21 22+const decodeLanding = Schema.decodeUnknownOption(SoftLanding);23+24 const decodeRefusals = Schema.decodeUnknownOption(Refusals);25 26+const LINK = "decoration-rule underline hover:decoration-current";27+14-const NOTHING =28+export const NOTHING =29 "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.";30 17-export const CodeNotFound = ({ data }: { readonly data?: unknown }) => (18- <NotFoundView19- nothing={NOTHING}20- refusals={Option.getOrUndefined(decodeRefusals(data))}21- title="Not found"22- />31+/** A refusal with no folder to land on: verbatim, then the ways onward. */32+const Refused = ({33+ refusals,34+}: {35+ readonly refusals: Array.NonEmptyReadonlyArray<Refusal> | undefined;36+}) => (37+ <Workspace title="Not found">38+ {refusals === undefined ? (39+ <EmptyState title={NOTHING} />40+ ) : (41+ <RefusalView refusals={refusals} />42+ )}43+ <p className="text-ui flex flex-wrap gap-x-4 gap-y-1">44+ <AppLink className={LINK} to="/">45+ Open asks46+ </AppLink>47+ </p>48+ </Workspace>49 );50+51+export const CodeNotFound = ({52+ data,53+ files,54+}: {55+ readonly data?: unknown;56+ /** The Files button, below the shell's width, on the folder a missing path lands on. */57+ readonly files?: ReactNode;58+}) =>59+ Option.match(decodeLanding(data), {60+ onNone: () => (61+ <Refused refusals={Option.getOrUndefined(decodeRefusals(data))} />62+ ),63+ onSome: (landing) => (64+ <TreeView65+ files={files}66+ listing={landing.nearest}67+ notice={<RefusalView refusals={landing.refusals} />}68+ now={landing.now}69+ project={landing.project}70+ rev={landing.rev}71+ />72+ ),73+ });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+};modified:apps/web/src/features/code/paths.ts+14 added-1 removed
36 unmodified lines37 /** The log from `rev`: only the commits that changed `path` when given, from the `from`th. */38 export const commitsHref = (39 project: ProjectName,40 rev: string,41- { from, path }: { readonly from?: number; readonly path?: string } = {}41+ {42+ from,43+ path,44+ show,45+ }: {46+ readonly from?: number;47+ readonly path?: string;48+ /** Only the answers or the asks' openings; every commit when absent. */49+ readonly show?: "answers" | "openings";50+ } = {}51 ) => {52 const query = new URLSearchParams();53 54 if (path !== undefined) {3 unmodified lines58 if (from !== undefined && from > 0) {59 query.set("from", String(from));60 }61 62+ if (show !== undefined) {63+ query.set("show", show);64+ }65+66 const search = query.toString();67 68 return `/${project}/commits/${revSegment(rev)}${search === "" ? "" : `?${search}`}`;69 };50 unmodified linesadded:apps/web/src/features/code/plain-diff.tsx+326 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 { useMemo } from "react";22+import type { ReactNode } from "react";23+24+import { drawnFiles, splitRows, unifiedRows } from "./diff-model.ts";25+import type { DrawnFile, PlainRow, SplitRow } from "./diff-model.ts";26+import { diffAnchor } from "./paths.ts";27+28+/** One numbered line: its text, and which side it is on. */29+type Line = Extract<PlainRow, { readonly number: number }>;30+31+/** A line's ground and its number's colour, by what it is. */32+const TONES = {33+ addition: {34+ line: "bg-diff-add-bg",35+ number: "bg-diff-add-bg text-diff-add-sign",36+ },37+ context: { line: "", number: "text-muted-foreground" },38+ deletion: {39+ line: "bg-diff-del-bg",40+ number: "bg-diff-del-bg text-diff-del-sign",41+ },42+} as const satisfies Record<43+ Line["kind"],44+ { readonly line: string; readonly number: string }45+>;46+47+/** Each line's sign in a unified diff, the mark that reads without colour. */48+const SIGNS = { addition: "+", context: " ", deletion: "-" } as const;49+50+/** Pierre's gutter: at least three figures, two before them and one after, then a 2 px gap. */51+const GUTTER =52+ "border-background min-w-[calc(6ch+2px)] border-r-2 pr-[1ch] pl-[2ch] text-right tabular-nums select-none";53+54+/** An unchanged run between hunks: a 32 px bar saying how many lines it skips. */55+const Separator = ({56+ lines,57+ span,58+}: {59+ readonly lines: number;60+ readonly span: number;61+}) => (62+ <div63+ className="bg-surface text-muted-foreground my-2 flex h-8 items-center px-[2ch] font-sans first:mt-0 last:mb-0"64+ data-separator="line-info"65+ style={{ gridColumn: `span ${span} / span ${span}` }}66+ >67+ {lines} unmodified {lines === 1 ? "line" : "lines"}68+ </div>69+);70+71+/** One line of a unified diff: its number, then its sign and text. */72+const UnifiedLine = ({ line }: { readonly line: Line }) => (73+ <>74+ <span className={`${GUTTER} ${TONES[line.kind].number}`}>75+ {line.number}76+ </span>77+ <span78+ className={`pr-[1ch] whitespace-pre ${TONES[line.kind].line}`}79+ data-line={line.number}80+ data-line-type={line.kind}81+ >82+ <span aria-hidden="true" className="inline-block w-[2ch] select-none">83+ {SIGNS[line.kind]}84+ </span>85+ {line.text}86+ </span>87+ </>88+);89+90+/** One side of a split diff's row: its number with the side's bar, then its text; empty when the side has none. */91+const SplitSide = ({ line }: { readonly line: Line | undefined }) =>92+ line === undefined ? (93+ <>94+ <span className={`${GUTTER} bg-surface`} />95+ <span className="bg-surface" />96+ </>97+ ) : (98+ <>99+ <span100+ className={`${GUTTER} relative ${TONES[line.kind].number} ${101+ line.kind === "context"102+ ? ""103+ : `before:absolute before:inset-y-0 before:left-0 before:w-1 ${104+ line.kind === "addition"105+ ? "before:bg-diff-add-sign"106+ : "before:bg-[repeating-linear-gradient(0deg,var(--diff-del-sign)_0_2px,transparent_2px_4px)]"107+ }`108+ }`}109+ >110+ {line.number}111+ </span>112+ <span113+ className={`pr-[1ch] pl-[1ch] whitespace-pre ${TONES[line.kind].line}`}114+ data-line={line.number}115+ data-line-type={line.kind}116+ >117+ {line.text}118+ </span>119+ </>120+ );121+122+/** A file's lines, unified: one grid of gutter and code, scrolling sideways in itself. */123+const UnifiedBody = ({ rows }: { readonly rows: readonly PlainRow[] }) => (124+ <div className="overflow-x-auto pb-2">125+ <code className="grid min-w-full grid-cols-[min-content_1fr]">126+ {rows.map((row, index) =>127+ row.kind === "separator" ? (128+ <Separator key={`s${index}`} lines={row.lines} span={2} />129+ ) : (130+ <UnifiedLine key={`${row.kind}${row.number}:${index}`} line={row} />131+ )132+ )}133+ </code>134+ </div>135+);136+137+/** A file's lines, split: old on the left, new on the right, row beside row. */138+const SplitBody = ({ rows }: { readonly rows: readonly SplitRow[] }) => (139+ <div className="overflow-x-auto pb-2">140+ <code className="grid min-w-full grid-cols-[min-content_1fr_min-content_1fr]">141+ {rows.map((row, index) =>142+ row.kind === "separator" ? (143+ <Separator key={`s${index}`} lines={row.lines} span={4} />144+ ) : (145+ <span className="contents" key={`p${index}`}>146+ <SplitSide line={row.left} />147+ <SplitSide line={row.right} />148+ </span>149+ )150+ )}151+ </code>152+ </div>153+);154+155+/** What a file changed, in counts: `+n −m`, each in its tint, with words for a screen reader. */156+export const ChangeCounts = ({157+ additions,158+ deletions,159+ header = false,160+}: {161+ readonly additions: number;162+ readonly deletions: number;163+ /** As a diff's file header prints them: a hyphen, and no count of nothing. */164+ readonly header?: boolean;165+}) => (166+ <span className="text-mono flex shrink-0 items-center gap-[1ch] font-mono tabular-nums">167+ {header && additions === 0 ? null : (168+ <span className="text-diff-add-sign">169+ +{additions}170+ <span className="sr-only"> added</span>171+ </span>172+ )}173+ {header && deletions === 0 ? null : (174+ <span className="text-diff-del-sign">175+ {header ? "-" : "−"}176+ {deletions}177+ <span className="sr-only"> removed</span>178+ </span>179+ )}180+ </span>181+);182+183+/** Why a file has no lines to show: binary, or its text not sent. */184+const Unshown = ({ file }: { readonly file: ChangedFile }) => (185+ <p className="text-ui text-muted-foreground px-4 pb-3 font-sans">186+ {file.binary ? "A binary file" : "Its text is not shown"}, {file.status}.187+ </p>188+);189+190+/** A file's lines, unified or split; why it has none when it has none. */191+const FileBody = ({192+ file,193+ split,194+}: {195+ readonly file: DrawnFile;196+ readonly split: boolean;197+}) => {198+ const diff = Option.getOrUndefined(file.diff);199+200+ if (diff === undefined) {201+ return <Unshown file={file.file} />;202+ }203+204+ return split ? (205+ <SplitBody rows={splitRows(diff)} />206+ ) : (207+ <UnifiedBody rows={unifiedRows(diff)} />208+ );209+};210+211+/** Each kind of change as the drawing's header marks it, in the diff's tints. */212+const CHANGE_MARKS = {213+ added: { icon: SquarePlus, tone: "text-diff-add-sign" },214+ deleted: { icon: SquareMinus, tone: "text-diff-del-sign" },215+ modified: { icon: SquareDot, tone: "text-muted-foreground" },216+} as const satisfies Record<217+ ChangedFile["status"],218+ { readonly icon: LucideIcon; readonly tone: string }219+>;220+221+/**222+ * A file's header as the drawing draws it: the fold's chevron, the mark of223+ * its change (with its word for a screen reader), its path, then its224+ * counts and anything the page adds.225+ */226+export const FileHeaderLine = ({227+ end,228+ file,229+}: {230+ readonly file: DrawnFile;231+ /** Anything a page puts at the header's end (a "Mark read" button). */232+ readonly end?: ReactNode;233+}) => {234+ const { icon: Icon, tone } = CHANGE_MARKS[file.file.status];235+236+ return (237+ <>238+ <ChevronDown239+ aria-hidden="true"240+ className="text-muted-foreground size-4 shrink-0 -rotate-90 transition-transform duration-150 group-open/file:rotate-0"241+ strokeWidth={1.75}242+ />243+ <Icon244+ aria-hidden="true"245+ className={`size-4 shrink-0 ${tone}`}246+ strokeWidth={1.75}247+ />248+ <span className="sr-only">{file.file.status}:</span>249+ <span className="min-w-0 flex-1 truncate" title={file.file.path}>250+ {file.file.path}251+ </span>252+ {Option.isNone(file.diff) ? (253+ <span className="text-muted-foreground shrink-0">254+ {file.file.binary ? "binary" : "not shown"}255+ </span>256+ ) : (257+ <ChangeCounts {...file.counts} header />258+ )}259+ {end}260+ </>261+ );262+};263+264+export interface PlainDiffProps {265+ readonly files: readonly ChangedFile[];266+ /** Old and new side by side; unified when absent. */267+ readonly split?: boolean;268+ /** The files folded now; each file's own default (`folded`) when absent. */269+ readonly folded?: ReadonlySet<string> | undefined;270+ /** A header's fold was pressed. */271+ readonly onFold?: ((path: string, folded: boolean) => void) | undefined;272+ /** `files` already parsed (`drawnFiles`), so a page parses each once. */273+ readonly drawn?: readonly DrawnFile[] | undefined;274+}275+276+/**277+ * The diff of `files`, plain, in the order a tree lists them. Server278+ * markup: one `section[data-file]` per file, its header sticky at the top279+ * of the pane that scrolls it.280+ */281+export const PlainDiff = ({282+ drawn: parsed,283+ files,284+ folded,285+ onFold,286+ split = false,287+}: PlainDiffProps) => {288+ const drawnList = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);289+290+ return (291+ <div className="text-mono leading-code font-mono" data-diff="plain">292+ {drawnList.map((drawn) => {293+ const { file } = drawn;294+295+ const closed =296+ folded === undefined ? drawn.folded : folded.has(file.path);297+298+ return (299+ <section300+ aria-label={file.path}301+ data-file={file.path}302+ data-folded={closed}303+ id={diffAnchor(file.path)}304+ key={file.path}305+ >306+ <details307+ className="group/file"308+ onToggle={(event) => {309+ onFold?.(file.path, !event.currentTarget.open);310+ }}311+ open={!closed}312+ >313+ <summary314+ 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"315+ data-diffs-header=""316+ >317+ <FileHeaderLine file={drawn} />318+ </summary>319+ <FileBody file={drawn} split={split} />320+ </details>321+ </section>322+ );323+ })}324+ </div>325+ );326+};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+150 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+ // A no-break space: the row lays its parts out as boxes, where a67+ // plain space between them collapses to nothing.68+ { text: "\u00A0" },69+ { color: "var(--diff-del-sign)", text: `−${counts.deletions}` },70+ ],71+ text: `+${counts.additions} −${counts.deletions}`,72+ title: `${counts.additions} added, ${counts.deletions} removed`,73+});74+75+/** The tree's options for `props`: its look, the page's path open and selected. */76+export const treeOptionsFor = (77+ props: Omit<RepoTreeProps, "onOpen">,78+ preparedInput = prepareFileTreeInput(props.paths)79+): FileTreeOptions => {80+ const { counts, current, open = false, status = NO_STATUS } = props;81+82+ const options: FileTreeOptions = {83 ...treesOptions,84 fileTreeSearchMode: "hide-non-matches",85+ flattenEmptyDirectories: true,86+ gitStatus: status,87 id: "repo-tree",44- initialExpandedPaths:45- current === undefined46- ? []47- : [...ancestorsOf(current), current].map((folder) => `${folder}/`),88+ initialExpandedPaths: openFor(current),89+ initialExpansion: open ? "open" : "closed",90 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- },91 preparedInput,92 search: true,58- gitStatus: status,93+ stickyFolders: true,94+ // The selected row's fill is faint on paper: its name in ink at 60095+ // says it too.96+ unsafeCSS: SELECTED_CSS,97+ };98+99+ if (counts !== undefined) {100+ options.renderRowDecoration = ({ item }) => {101+ const changed = counts.get(item.path);102+103+ return changed === undefined ? null : decorationOf(changed);104+ };105+ }106+107+ return options;108+};109+110+/**111+ * Hand the page each file the reader chooses in `tree` (never a folder,112+ * never the page's own file); the returned function stops.113+ */114+export const followChoices = (115+ tree: Pick<FileTree, "getSelectedPaths" | "subscribe">,116+ current: string | undefined,117+ onOpen: (path: string) => void118+) =>119+ tree.subscribe(() => {120+ const path = tree.getSelectedPaths().at(-1);121+122+ if (path !== undefined && !path.endsWith("/") && path !== current) {123+ onOpen(path);124+ }125 });126 61- // Keep the page's own path in view.127+/** Whether a tree item is a folder, which opens. */128+const isFolder = (item: FileTreeItemHandle): item is FileTreeDirectoryHandle =>129+ item.isDirectory();130+131+export const RepoTree = (props: RepoTreeProps) => {132+ const { current, onOpen } = props;133+134+ // The tree is made from its first options: the page keys it by project135+ // and revision, so a new set of paths is a new tree.136+ const preparedInput = useMemo(137+ () => prepareFileTreeInput(props.paths),138+ [props.paths]139+ );140+141+ const { model } = useFileTree(treeOptionsFor(props, preparedInput));142+143+ useEffect(144+ () => followChoices(model, current, onOpen),145+ [model, current, onOpen]146+ );147+148+ // Follow the page: open the folders above its path, select it alone,149+ // and bring it into view.150 useEffect(() => {63- if (current !== undefined) {64- model.scrollToPath(current, { focus: false, offset: "nearest" });151+ if (current === undefined || current === "") {152+ return;153 }154+155+ for (const folder of openFor(current)) {156+ const item = model.getItem(folder);157+158+ if (item !== null && isFolder(item)) {159+ item.expand();160+ }161+ }162+163+ for (const selected of model.getSelectedPaths()) {164+ if (selected !== current) {165+ model.getItem(selected)?.deselect();166+ }167+ }168+169+ const here = model.getItem(current) ?? model.getItem(folderId(current));170+171+ if (here !== null && !here.isSelected()) {172+ here.select();173+ }174+175+ model.scrollToPath(current, { focus: false, offset: "nearest" });176 }, [model, current]);177 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- );178+ // The tree scrolls inside itself, so it takes the height its box gives.179+ return <FileTreeView className="block h-full min-h-0" model={model} />;180 };181 182 // `React.lazy` takes a module's default export.183 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+71 added-26 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: ({ loaderData, params }) =>154+ codePageHeaders(params.rev, loaderData !== undefined),155 head: ({ params: { _splat, project, rev } }) =>156 pageHead({ title: `${_splat ?? project} at ${rev}` }),157 component: BlobPage,115- notFoundComponent: CodeNotFound,158+ notFoundComponent: ({ data }) => (159+ <CodeNotFound data={data} files={<FilesButton />} />160+ ),161 });modified:apps/web/src/routes/$project/commit/$sha.tsx+121 added-39 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 { serverClient } from "../../../server/client.ts";19+import { CommitRail } from "../tree/-code-rail.tsx";20+import { CommitPageData } from "../tree/-commit-files.ts";21+import { FilesButton } from "../tree/-files-button.tsx";22+import { codePageHeaders } from "../tree/-headers.ts";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 (a 404 only29+// briefly), and the router 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)(68- Route.useLoaderData()81+ const loaded = Route.useLoaderData();82+83+ // Decoded once per read: the diff's files keep one identity while the84+ // reader folds, splits and moves, so nothing is parsed or drawn again.85+ const { diff, now, project, territory } = useMemo(86+ () => Schema.decodeSync(CommitPageData)(loaded),87+ [loaded]88 );89 90+ const router = useRouter();71- const split = Route.useSearch().style === "split";91+ const asked = Route.useSearch().style === "split";92+ const [chosen, setChosen] = useState(asked);93+ const roomy = useMedia(SPLIT_QUERY);94+ // Split only where the screen has room for two sides.95+ const split = chosen && roomy;96 97+ // Each file parsed once for the page: the head's stats, the plain text98+ // and the folds all read this.99+ const drawn = useMemo(() => drawnFiles(diff.files), [diff.files]);100+101+ const defaults = useMemo(102+ () =>103+ new Set(104+ drawn.filter(({ folded }) => folded).map(({ file }) => file.path)105+ ),106+ [drawn]107+ );108+109+ const [folded, setFolded] = useState<ReadonlySet<string>>(defaults);110+111+ const onFold = useCallback((path: string, fold: boolean) => {112+ setFolded((was) => {113+ if (was.has(path) === fold) {114+ return was;115+ }116+117+ const next = new Set(was);118+119+ if (fold) {120+ next.add(path);121+ } else {122+ next.delete(path);123+ }124+125+ return next;126+ });127+ }, []);128+129+ const onFoldAll = useCallback(130+ (fold: boolean) => {131+ setFolded(fold ? new Set(diff.files.map(({ path }) => path)) : new Set());132+ },133+ [diff.files]134+ );135+136+ // The layout is the reader's: kept in the address, with no read again.137+ const onSplit = (next: boolean) => {138+ setChosen(next);139+140+ const { hash, pathname } = router.state.location;141+142+ router.history.replace(143+ `${pathname}${next ? "?style=split" : ""}${hash === "" ? "" : `#${hash}`}`144+ );145+ };146+147 return (148 <CommitView149 diff={diff}150 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>151+ diff.truncated ? undefined : (152 <ClientDiffs153 fallback={90- <ChangedList91- commit={diff.commit}92- files={diff.files}93- project={project}94- />154+ <div className={PANE_SCROLLER}>155+ <PlainDiff156+ drawn={drawn}157+ files={diff.files}158+ folded={folded}159+ onFold={onFold}160+ split={split}161+ />162+ </div>163 }164 files={diff.files}165+ folded={folded}166+ onFold={onFold}167 split={split}168 />99- </div>169+ )170 }171+ drawn={drawn}172+ files={<FilesButton commit />}173+ folded={folded}174 now={now}175+ onFold={onFold}176+ onFoldAll={onFoldAll}177+ onSplit={onSplit}178 project={project}179 split={split}180+ territory={territory}181 />182 );183 };184 185 export const Route = createFileRoute("/$project/commit/$sha")({186+ staticData: { rail: CommitRail },187 // The router writes back what this returns, dropping only `undefined`,188 // so a unified diff's address carries no `style`.189 validateSearch: (search: { readonly style?: unknown }) => ({190 style: search.style === "split" ? ("split" as const) : undefined,191 }),192 loader: ({ params }) => commitPage({ data: params }),193+ // A commit never changes: what was read stays fresh for good.194+ staleTime: Number.POSITIVE_INFINITY,195+ headers: ({ loaderData, params }) =>196+ codePageHeaders(params.sha, loaderData !== undefined),197 head: ({ params: { project, sha } }) =>198 pageHead({ title: `${project}: commit ${sha.slice(0, 7)}` }),199 component: CommitPage,200 notFoundComponent: CodeNotFound,1 unmodified linemodified:apps/web/src/routes/$project/commits/$rev.tsx+16 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: ({ loaderData, params }) =>120+ codePageHeaders(params.rev, loaderData !== undefined),121 head: ({ params: { project, rev } }) =>110- pageHead({ title: `${project}: commits on ${rev}` }),122+ pageHead({ title: `${project}: landings on ${rev}` }),123 component: LogPage,124 notFoundComponent: CodeNotFound,125 });modified:apps/web/src/routes/$project/tree/$rev/$.tsx+42 added-18 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: ({ loaderData, params }) =>123+ codePageHeaders(params.rev, loaderData !== undefined),124 head: ({ params: { _splat, project, rev } }) =>125 pageHead({126 title: `${_splat === undefined || _splat === "" ? project : _splat} at ${rev}`,127 }),128 component: TreePage,107- notFoundComponent: CodeNotFound,129+ notFoundComponent: ({ data }) => (130+ <CodeNotFound data={data} files={<FilesButton />} />131+ ),132 });added: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+19 added
1+/**2+ * The `Cache-Control` a code page answers with, by what its address names3+ * and whether it found anything: a page at a whole commit id shows what4+ * can never change, so a browser keeps it for good; a page at `main` or a5+ * tag moves with the next landing, so it is kept briefly and read again6+ * behind it. A page that found nothing (no such project, commit or path:7+ * its loader read no data) is kept briefly too, even at a whole commit8+ * id: a landing or an import may bring what it named. Not a route: the9+ * `-` prefix keeps the router from reading it as one.10+ */11+import { isCommitId } from "../../../features/code/headers.ts";12+import { branchPage, immutablePage } from "../../../server/cache-headers.ts";13+14+/** A code page's headers at `rev`, given whether its loader found what it names. */15+export const codePageHeaders = (16+ rev: string,17+ found: boolean18+): Readonly<Record<string, string>> =>19+ found && 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+259 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+import { useMemo } from "react";25+26+import { pathsAtom, refsAtom } from "../../../client/code.ts";27+import { ClientTree } from "../../../features/code/client-tree.tsx";28+import { drawnFiles, treeOrder } from "../../../features/code/diff-model.ts";29+import { useCodeFileKeys } from "../../../features/code/file-keys.ts";30+import { parseDiffHash } from "../../../features/code/line-hash.ts";31+import { SHELL_QUERY, useMedia } from "../../../features/code/media.ts";32+import {33+ blobHref,34+ diffAnchor,35+ treeHref,36+ whyHref,37+} from "../../../features/code/paths.ts";38+import { RefSwitcher } from "../../../features/code/ref-switcher.tsx";39+import { CommitPageData } from "./-commit-files.ts";40+41+const isProject = Schema.is(ProjectName);42+43+const decode = Schema.decodeUnknownOption(CommitPageData);44+45+const NONE: readonly ChangedFile[] = [];46+47+/** The files the commit on the page changed; none while its data is not there. */48+const useCommitFiles = (): readonly ChangedFile[] => {49+ const data: unknown = useMatch({50+ from: "/$project/commit/$sha",51+ select: (match) => match.loaderData,52+ shouldThrow: false,53+ });54+55+ // Decoded once per read, not on every move between files.56+ return useMemo(57+ () =>58+ Option.match(decode(data), {59+ onNone: () => NONE,60+ onSome: ({ diff }) => diff.files,61+ }),62+ [data]63+ );64+};65+66+/** Which page of a file the address is: its folder, its code, or why. */67+type Kind = "blob" | "tree" | "why";68+69+/** Where the reader is in the code: the project, the revision and the path, and which page. */70+const useCodeAddress = () => {71+ const params = useParams({ strict: false });72+73+ const kind = useLocation({74+ select: ({ pathname }): Kind => {75+ const second = pathname.split("/").at(2);76+77+ return second === "blob" || second === "why" ? second : "tree";78+ },79+ });80+81+ const project = isProject(params.project) ? params.project : undefined;82+ const rev = params.rev ?? "main";83+84+ const path =85+ params._splat === undefined || params._splat === ""86+ ? undefined87+ : params._splat;88+89+ return { kind, path, project, rev };90+};91+92+/** The page of `kind` for `path` at `rev`. */93+const hrefFor = (94+ project: ProjectName,95+ kind: Kind,96+ rev: string,97+ path: string | undefined98+) => {99+ if (path === undefined || kind === "tree") {100+ return treeHref(project, rev, path);101+ }102+103+ return (kind === "why" ? whyHref : blobHref)(project, rev, path);104+};105+106+/** The ref line: the revision, and the switcher to the same page at another. */107+const RefLine = ({108+ kind,109+ path,110+ project,111+ rev,112+}: {113+ readonly kind: Kind;114+ readonly path: string | undefined;115+ readonly project: ProjectName;116+ readonly rev: string;117+}) => {118+ const refs = useAtomValue(refsAtom(project));119+120+ return (121+ <div className="border-rule flex h-12 shrink-0 items-center gap-2 border-b px-3">122+ <RefSwitcher123+ hrefAt={(at) => hrefFor(project, kind, at, path)}124+ refs={Option.getOrUndefined(AsyncResult.value(refs))}125+ rev={rev}126+ />127+ </div>128+ );129+};130+131+/** The tree of every path at the revision, and the keys between its files. */132+const ProjectTree = ({133+ kind,134+ path,135+ project,136+ rev,137+ shown,138+}: {139+ readonly kind: Kind;140+ readonly path: string | undefined;141+ readonly project: ProjectName;142+ readonly rev: string;143+ /** Whether the tree is on screen here (the rail is not below the shell's width). */144+ readonly shown: boolean;145+}) => {146+ const router = useRouter();147+ const read = useAtomValue(pathsAtom({ at: rev, project }));148+149+ // Past the platform's cap on paths the page works from its own list.150+ const paths = Option.getOrUndefined(151+ Option.flatMap(AsyncResult.value(read), (listed) =>152+ listed.truncated ? Option.none() : Option.some(listed.paths)153+ )154+ );155+156+ const open = (file: string) => {157+ router.history.push(158+ hrefFor(project, kind === "tree" ? "blob" : kind, rev, file)159+ );160+ };161+162+ const ordered = useMemo(() => (paths ?? []).toSorted(treeOrder), [paths]);163+164+ useCodeFileKeys(ordered, path, open);165+166+ return shown && paths !== undefined ? (167+ <ClientTree168+ current={path}169+ key={`${project}@${rev}`}170+ onOpen={open}171+ paths={paths}172+ />173+ ) : null;174+};175+176+/** A folder's, a file's or a why page's files: the ref line, then the tree. */177+export const CodeFiles = ({178+ always = false,179+}: {180+ readonly always?: boolean;181+}) => {182+ const { kind, path, project, rev } = useCodeAddress();183+ const wide = useMedia(SHELL_QUERY);184+185+ return project === undefined ? null : (186+ <div className="flex min-h-0 flex-1 flex-col">187+ <RefLine kind={kind} path={path} project={project} rev={rev} />188+ <div className="min-h-0 flex-1 pt-1">189+ <ClientOnly fallback={null}>190+ <ProjectTree191+ kind={kind}192+ path={path}193+ project={project}194+ rev={rev}195+ shown={always || wide}196+ />197+ </ClientOnly>198+ </div>199+ </div>200+ );201+};202+203+/** A commit's changed files, marked by how, and the keys between them. */204+export const CommitFiles = ({205+ always = false,206+}: {207+ readonly always?: boolean;208+}) => {209+ const router = useRouter();210+ const wide = useMedia(SHELL_QUERY);211+ const files = useCommitFiles();212+ const hash = useLocation({ select: (location) => location.hash });213+214+ const current = Option.getOrUndefined(215+ Option.map(parseDiffHash(hash), ({ path }) => path)216+ );217+218+ const drawn = useMemo(() => drawnFiles(files), [files]);219+ const paths = useMemo(() => drawn.map(({ file }) => file.path), [drawn]);220+221+ const counts = useMemo(222+ () => new Map(drawn.map(({ counts: each, file }) => [file.path, each])),223+ [drawn]224+ );225+226+ const status = useMemo(227+ () => drawn.map(({ file }) => ({ path: file.path, status: file.status })),228+ [drawn]229+ );230+231+ const open = (path: string) => {232+ const { pathname, searchStr } = router.state.location;233+234+ router.history.replace(`${pathname}${searchStr}#${diffAnchor(path)}`);235+ };236+237+ useCodeFileKeys(paths, current, open);238+239+ return always || wide ? (240+ <div className="min-h-0 flex-1 pt-1">241+ <ClientTree242+ counts={counts}243+ current={current}244+ key={paths.join("\n")}245+ onOpen={open}246+ open247+ paths={paths}248+ status={status}249+ />250+ </div>251+ ) : null;252+};253+254+/** The rail's body: a commit's changed files, or the project's. */255+const RailBody = ({ commit }: { readonly commit: boolean }) =>256+ commit ? <CommitFiles /> : <CodeFiles />;257+258+// `React.lazy` takes a module's default export.259+export default RailBody;added:apps/web/src/routes/$project/tree/-soft-landing.ts+74 added
1+/**2+ * The soft landing for a missing path (the nearest folder, with the3+ * 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+58 added-19 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: ({ loaderData, params }) =>150+ codePageHeaders(params.rev, loaderData !== undefined),151 loader: ({ params }) => whyPage({ data: params }),152 head: ({ params: { _splat, project, rev } }) =>153 pageHead({ title: `Why ${_splat ?? project} at ${rev}` }),154 component: WhyPage,118- notFoundComponent: CodeNotFound,155+ notFoundComponent: ({ data }) => (156+ <CodeNotFound data={data} files={<FilesButton />} />157+ ),158 });modified: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+231 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 { permalinkPress } from "../src/features/code/file-header.tsx";24+import { stepFrom } from "../src/features/code/file-keys.ts";25+26+const decode = Schema.decodeSync(ChangedFile);27+28+/** Lines `from` to `to`, as a file's text. */29+const lines = (from: number, to: number) =>30+ `${Array.from(31+ { length: to - from + 1 },32+ (_, index) => `line ${from + index}`33+ ).join("\n")}\n`;34+35+const thirty = lines(1, 30);36+37+const changed = decode({38+ after: "a".repeat(40),39+ before: "b".repeat(40),40+ binary: false,41+ newText: thirty.replace("line 15\n", "line fifteen\nline 15b\n"),42+ oldText: thirty,43+ path: "src/parse.ts",44+ status: "modified",45+});46+47+describe("a changed file's diff", () => {48+ it("is parsed into the hunks the drawing draws, keyed by both blobs", () => {49+ const diff = fileDiffOf(changed);50+51+ expect(Option.map(diff, ({ hunks }) => hunks.length)).toStrictEqual(52+ Option.some(1)53+ );54+ expect(Option.map(diff, ({ cacheKey }) => cacheKey)).toStrictEqual(55+ Option.some(`diff:${"b".repeat(40)}:${"a".repeat(40)}`)56+ );57+ expect(countsOf(diff)).toStrictEqual({ additions: 2, deletions: 1 });58+ });59+60+ it("reads as unified rows: the unchanged lines skipped before and after, each line numbered on its side", () => {61+ const rows = Option.match(fileDiffOf(changed), {62+ onNone: () => [],63+ onSome: unifiedRows,64+ });65+66+ expect(rows[0]).toStrictEqual({ kind: "separator", lines: 10 });67+ expect(rows.at(-1)).toStrictEqual({ kind: "separator", lines: 11 });68+ expect(69+ rows.filter((row) => row.kind !== "separator" && row.kind !== "context")70+ ).toStrictEqual([71+ { kind: "deletion", number: 15, text: "line 15" },72+ { kind: "addition", number: 15, text: "line fifteen" },73+ { kind: "addition", number: 16, text: "line 15b" },74+ ]);75+ });76+77+ it("reads as split rows: the deletion beside the first addition, the second against nothing", () => {78+ const rows = Option.match(fileDiffOf(changed), {79+ onNone: () => [],80+ onSome: splitRows,81+ });82+83+ const pairs = rows.filter(84+ (row) =>85+ row.kind === "pair" &&86+ (row.left?.kind !== "context" || row.right === undefined)87+ );88+89+ expect(pairs).toStrictEqual([90+ {91+ kind: "pair",92+ left: { kind: "deletion", number: 15, text: "line 15" },93+ right: { kind: "addition", number: 15, text: "line fifteen" },94+ },95+ {96+ kind: "pair",97+ right: { kind: "addition", number: 16, text: "line 15b" },98+ },99+ ]);100+ });101+102+ it("has no lines for a binary file, or one whose text was not sent", () => {103+ expect(104+ fileDiffOf(decode({ binary: true, path: "logo.png", status: "added" }))105+ ).toStrictEqual(Option.none());106+ expect(107+ fileDiffOf(108+ decode({ binary: false, path: "big.json", status: "modified" })109+ )110+ ).toStrictEqual(Option.none());111+ });112+});113+114+describe("a commit's files", () => {115+ const files = [116+ decode({117+ binary: false,118+ newText: lines(1, 81),119+ path: "data/zones.ts",120+ status: "added",121+ }),122+ decode({123+ binary: false,124+ oldText: lines(1, 80),125+ path: "data/old.ts",126+ status: "deleted",127+ }),128+ changed,129+ decode({130+ binary: false,131+ newText: "it\n",132+ path: "test/parse.test.ts",133+ status: "added",134+ }),135+ decode({136+ binary: false,137+ newText: "x\n",138+ path: "README.md",139+ status: "added",140+ }),141+ ];142+143+ it("are listed in the tree's order: folders before files, then by name", () => {144+ expect(drawnFiles(files).map(({ file }) => file.path)).toStrictEqual([145+ "data/old.ts",146+ "data/zones.ts",147+ "src/parse.ts",148+ "test/parse.test.ts",149+ "README.md",150+ ]);151+ expect(["b", "a/z", "a/b/c"].toSorted(treeOrder)).toStrictEqual([152+ "a/b/c",153+ "a/z",154+ "b",155+ ]);156+ });157+158+ it("start folded when added or deleted past 80 lines", () => {159+ expect(160+ drawnFiles(files)161+ .filter(({ folded }) => folded)162+ .map(({ file }) => file.path)163+ ).toStrictEqual(["data/zones.ts"]);164+ });165+166+ it("count by path: the ask's territory, its tests, the rest", () => {167+ const stats = statsOf(drawnFiles(files), ["src/**"]);168+169+ expect([stats.files, stats.additions, stats.deletions]).toStrictEqual([170+ 5, 85, 81,171+ ]);172+ expect(stats.parts).toStrictEqual([173+ { additions: 2, deletions: 1, files: 1, label: "territory" },174+ { additions: 1, deletions: 0, files: 1, label: "tests" },175+ { additions: 82, deletions: 80, files: 3, label: "other" },176+ ]);177+ });178+179+ it("read a territory's globs as git paths", () => {180+ expect(globTest("src/**")("src/a/b.ts")).toBeTruthy();181+ expect(globTest("src/*.ts")("src/a/b.ts")).toBeFalsy();182+ expect(globTest("packages/parse")("packages/parse/index.ts")).toBeTruthy();183+ expect(globTest("**/*.ts")("a.ts")).toBeTruthy();184+ });185+186+ it("know a test file by its folder or its name", () => {187+ expect(isTestPath("src/parse.test.ts")).toBeTruthy();188+ expect(isTestPath("test/asks/x.ts")).toBeTruthy();189+ expect(isTestPath("src/testing.ts")).toBeFalsy();190+ });191+});192+193+describe("the keys between files", () => {194+ const paths = ["a.ts", "b.ts", "c.ts"];195+196+ it("move from the page's own file, and stop at either end", () => {197+ expect(stepFrom(paths, "b.ts", 1)).toBe("c.ts");198+ expect(stepFrom(paths, "b.ts", -1)).toBe("a.ts");199+ expect(stepFrom(paths, "c.ts", 1)).toBe("c.ts");200+ expect(stepFrom(paths, "a.ts", -1)).toBe("a.ts");201+ });202+203+ it("start at the first file, or the last going back, from none", () => {204+ expect(stepFrom(paths, undefined, 1)).toBe("a.ts");205+ expect(stepFrom(paths, undefined, -1)).toBe("c.ts");206+ expect(stepFrom([], undefined, 1)).toBeUndefined();207+ });208+});209+210+describe("the permalink key", () => {211+ const press = {212+ altKey: false,213+ ctrlKey: false,214+ inField: false,215+ key: "y",216+ metaKey: false,217+ };218+219+ it("takes y to the page at its commit while the single keys are on", () => {220+ expect(permalinkPress(press, true)).toBeTruthy();221+ });222+223+ it("does nothing once the single keys are switched off, in a field, or with a modifier", () => {224+ expect([225+ permalinkPress(press, false),226+ permalinkPress({ ...press, inField: true }, true),227+ permalinkPress({ ...press, ctrlKey: true }, true),228+ permalinkPress({ ...press, key: "Y" }, true),229+ ]).toStrictEqual([false, false, false, false]);230+ });231+});modified:apps/web/test/code.test.tsx+715 added-186 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 {56+ readBlobPage,57+ Route as BlobRoute,51-import { readBlobPage } from "../src/routes/$project/blob/$rev/$.tsx";58+} from "../src/routes/$project/blob/$rev/$.tsx";59 import { readCommitPage } from "../src/routes/$project/commit/$sha.tsx";60 import { readLogPage } from "../src/routes/$project/commits/$rev.tsx";61 import { readRefsPage } from "../src/routes/$project/refs.tsx";62+import {63+ readTreePage,64+ Route as TreeRoute,55-import { readTreePage } from "../src/routes/$project/tree/$rev/$.tsx";65+} from "../src/routes/$project/tree/$rev/$.tsx";66+import { codePageHeaders } from "../src/routes/$project/tree/-headers.ts";67+import { Route as WhyRoute } from "../src/routes/$project/why/$rev/$.tsx";68+import { branchPage, immutablePage } from "../src/server/cache-headers.ts";69 import { reachingTransport } from "./transport.ts";70 71 const markupOf = (element: ReactElement) => renderToStaticMarkup(element);72 89 unmodified lines162 const TAG = "@datekit/core@1.0.0";163 164 const TAG_SEGMENT = "%40datekit%2Fcore%401.0.0";165 166+const decodeCommits = Schema.decodeSync(Schema.Array(Commit));167+168+const signature = (name: string, at: string) => ({169+ at,170+ email: `${name}@example.com`,171+ name,172+});173+174+const LANDED = "1".repeat(40);175+176+const IMPORTED = "2".repeat(40);177+178+const OLDER = "3".repeat(40);179+180+const commits = decodeCommits([181+ {182+ author: signature("Bram", "2026-10-06T15:00:00.000Z"),183+ body: "",184+ committer: signature("platform", "2026-10-06T15:00:00.000Z"),185+ landing: {186+ ask: "parse-iso-week",187+ assisted: [],188+ author: "bram",189+ credits: [190+ { handle: "bram", role: "Signed-off-by" },191+ { handle: "ines-v", role: "Asked-by" },192+ ],193+ landedAt: "2026-10-06T15:00:00.000Z",194+ parent: IMPORTED,195+ project: "datekit",196+ sha: LANDED,197+ },198+ parents: [IMPORTED],199+ sha: LANDED,200+ subject: "Answer parse-iso-week",201+ trailers: [202+ { key: "Asked-by", value: "ines-v" },203+ { key: "Signed-off-by", value: "bram" },204+ ],205+ tree: "4".repeat(40),206+ },207+ {208+ author: signature("Lin", "2026-10-06T09:00:00.000Z"),209+ body: "",210+ committer: signature("Lin", "2026-10-06T09:00:00.000Z"),211+ parents: [OLDER],212+ sha: IMPORTED,213+ subject: "Support week numbers",214+ trailers: [],215+ tree: "5".repeat(40),216+ },217+ {218+ author: signature("Lin", "2026-10-04T09:00:00.000Z"),219+ body: "",220+ committer: signature("Lin", "2026-10-04T09:00:00.000Z"),221+ parents: [],222+ sha: OLDER,223+ subject: "First commit",224+ trailers: [],225+ tree: "6".repeat(40),226+ },227+]);228+229+const decodeDiff = Schema.decodeSync(CommitDiff);230+231+const landedCommit: typeof Commit.Encoded = {232+ author: signature("Bram", "2026-10-06T15:00:00.000Z"),233+ body: "Parse ISO week dates.\n\nAsked-by: ines-v\nSigned-off-by: bram",234+ committer: signature("platform", "2026-10-06T15:00:00.000Z"),235+ landing: {236+ ask: "parse-iso-week",237+ assisted: [],238+ author: "bram",239+ credits: [240+ { handle: "bram", role: "Signed-off-by" },241+ { handle: "ines-v", role: "Asked-by" },242+ ],243+ landedAt: "2026-10-06T15:00:00.000Z",244+ parent: IMPORTED,245+ project: "datekit",246+ sha: LANDED,247+ verdict: {248+ ask: "parse-iso-week",249+ at: "2026-10-06T14:59:00.000Z",250+ base: IMPORTED,251+ checkVersion: "redThenGreen@0.0.0+abc",252+ head: "7".repeat(40),253+ heldBack: [],254+ lanes: [255+ {256+ command: "bun test",257+ durationMs: 1200,258+ lane: "unit",259+ result: "passed",260+ },261+ ],262+ outcome: Schema.encodeSync(Outcome)(263+ Outcome.cases.Landed.make({ sha: LandedSha.make(LANDED) })264+ ),265+ patchId: "8".repeat(64),266+ project: "datekit",267+ stage: "checks",268+ tree: "4".repeat(40),269+ verifier: "platform",270+ },271+ },272+ parents: [IMPORTED],273+ sha: LANDED,274+ subject: "Answer parse-iso-week",275+ trailers: [276+ { key: "Asked-by", value: "ines-v <ines-v@users.example.com>" },277+ { key: "Signed-off-by", value: "bram <bram@users.example.com>" },278+ ],279+ tree: "4".repeat(40),280+};281+282+const diff = decodeDiff({283+ commit: landedCommit,284+ files: [285+ {286+ after: "9".repeat(40),287+ binary: false,288+ newText: "export const week = 1;\n",289+ path: "src/week.ts",290+ status: "added",291+ },292+ {293+ after: "a".repeat(40),294+ before: "b".repeat(40),295+ binary: false,296+ newText: "export const parse = fromIso;\n",297+ oldText: "export const parse = Date;\n",298+ path: "src/parse.ts",299+ status: "modified",300+ },301+ {302+ before: "c".repeat(40),303+ binary: false,304+ oldText: "export const legacy = true;\n",305+ path: "src/legacy.ts",306+ status: "deleted",307+ },308+ ],309+ truncated: false,310+});311+312+/** The markup of `<main>` alone: the page, without its inspector. */313+const mainOf = (markup: string) =>314+ /<main\b[\s\S]*?<\/main>/u.exec(markup)?.[0] ?? "";315+316+/** The markup of the inspector alone. */317+const inspectorOf = (markup: string) =>318+ /<aside\b[^>]*data-facts="inspector"[\s\S]*?<\/aside>/u.exec(markup)?.[0] ??319+ "";320+321+/** How many times `part` appears in `text`. */322+const countIn = (text: string, part: string) => text.split(part).length - 1;323+324 describe(TreeView, () => {325 const page = (155- <TreeView listing={root} project={datekit} readme={readme} rev="main" />326+ <TreeView327+ listing={root}328+ now={now}329+ project={datekit}330+ readme={readme}331+ rev="main"332+ />333 );334 335 it("lists folders before files, each linking its own page at the same revision", () => {336 const markup = markupOf(page);5 unmodified lines342 expect(hrefsOf(markup)).toContain("/datekit/tree/main/src");343 expect(hrefsOf(markup)).toContain("/datekit/blob/main/README.md");344 });345 169- it("links each ancestor in its breadcrumb at the same revision, and names the folder last", () => {346+ it("lists the folder once", () => {347+ const markup = markupOf(page);348+349+ expect(countIn(markup, 'data-entry="src"')).toBe(1);350+ expect(countIn(markup, 'data-entry="README.md"')).toBe(1);351+ expect(countIn(markup, "data-entries=")).toBe(1);352+ });353+354+ it("says what last changed each entry, once it has been read", () => {355+ const [last] = commits;356+357 const markup = markupOf(171- <TreeView listing={nested} project={datekit} rev={TAG} />358+ <TreeView359+ last={new Map(last === undefined ? [] : [["src", last]])}360+ listing={root}361+ now={now}362+ project={datekit}363+ rev="main"364+ />365 );366 174- const crumbs = hrefsOf(navOf(markup, 'data-slot="breadcrumb"'));367+ expect(slice(markup, "data-entry", "src")).toContain("parse-iso-week");368+ expect(slice(markup, "data-entry", "src")).toContain("ago");369+ expect(slice(markup, "data-entry", "README.md")).not.toContain("ago");370+ });371 372+ it("links each ancestor in its path at the same revision, and names the folder last", () => {373+ const markup = markupOf(374+ <TreeView listing={nested} now={now} project={datekit} rev={TAG} />375+ );376+377+ const crumbs = hrefsOf(navOf(markup, 'aria-label="Path"'));378+379 expect(crumbs).toStrictEqual([380 `/datekit/tree/${TAG_SEGMENT}`,381 `/datekit/tree/${TAG_SEGMENT}/src`,382 `/datekit/tree/${TAG_SEGMENT}/src/format`,383 ]);384 expect(182- textOf(<TreeView listing={nested} project={datekit} rev={TAG} />)385+ textOf(386+ <TreeView listing={nested} now={now} project={datekit} rev={TAG} />387+ )388 ).toContain("locale");389 });390 391 it("renders the folder's README below its entries", () => {14 unmodified lines406 describe(BlobView, () => {407 const parse = decodeFile({408 at: AT,409 binary: false,205- path: "src/parse.ts",410+ path: "src/format/parse.ts",411 sha: "e".repeat(40),412 size: 14,413 text: "one\ntwo\nthree\n",414 truncated: false,415 });416 212- const page = <BlobView file={parse} project={datekit} rev="main" />;417+ const [lastLanding] = commits;418 419+ const page = (420+ <BlobView421+ file={parse}422+ last={lastLanding}423+ now={now}424+ project={datekit}425+ rev="main"426+ />427+ );428+429 it("numbers each line of a text file with its own anchor, and draws no highlighting on the server", () => {430 const markup = markupOf(page);431 432 const anchors = [...markup.matchAll(/id="(?<line>L\d+)"/gu)].map(15 unmodified lines448 expect(anchored?.groups?.tag).toBe("span");449 expect(anchored?.groups?.attributes).not.toMatch(/\bcontents\b/u);450 });451 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"');452+ it("sets the plain text at the drawing's measures: 20 px lines and Pierre's gutter", () => {453+ const code = /<pre\b[^>]*>/u.exec(markupOf(page))?.[0] ?? "";454 455+ expect(code).toContain("leading-code");456+ expect(code).toContain("text-mono");457+ expect(markupOf(page)).toContain("min-w-[calc(6ch+2px)]");458+ expect(markupOf(page)).toContain("pl-[2ch]");459+ });460+461+ it("names the path once in the page, in its file header", () => {462+ const main = mainOf(markupOf(page));463+464+ // The trail's segments, read as text, spell the path: once.465+ expect(466+ countIn(main.replaceAll(/<[^>]+>/gu, ""), "src/format/parse.ts")467+ ).toBe(1);468+ expect(countIn(main, 'title="src/format/parse.ts"')).toBe(1);469+ expect(countIn(main, 'aria-label="Path"')).toBe(1);470+ expect(hrefsOf(navOf(main, 'aria-label="Path"'))).toStrictEqual([471+ "/datekit/tree/main",472+ "/datekit/tree/main/src",473+ "/datekit/tree/main/src/format",474+ ]);475+ });476+477+ it("has the Code | Why toggle, Code current", () => {478+ const toggle = navOf(markupOf(page), 'aria-label="Mode"');479+480+ expect(hrefsOf(toggle)).toStrictEqual([481+ "/datekit/blob/main/src/format/parse.ts",482+ "/datekit/why/main/src/format/parse.ts",483+ ]);484+ expect(toggle).toMatch(/aria-current="page"[^>]*>Code</u);485+ expect(toggle).not.toMatch(/aria-current="page"[^>]*>Why</u);486+ });487+488+ it("links raw at the commit and the permalink at the commit, and the history at the revision", () => {489+ const markup = markupOf(page);490+ const toolbar = navOf(markup, 'data-toolbar="file"');491+492 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`,493+ `/datekit/raw/${AT}/src/format/parse.ts`,494+ `/datekit/blob/${AT}/src/format/parse.ts`,495 ]);496+ expect(hrefsOf(inspectorOf(markup))).toContain(497+ "/datekit/commits/main?path=src%2Fformat%2Fparse.ts"498+ );499 });500 501+ it("names the last landing's ask in This file, before its SHA", () => {502+ const facts = inspectorOf(markupOf(page));503+ const text = facts.replaceAll(/<[^>]+>/gu, "");504+505+ expect(facts).toContain("This file");506+ expect(text.indexOf("parse-iso-week")).toBeGreaterThan(-1);507+ expect(text.indexOf("parse-iso-week")).toBeLessThan(508+ text.indexOf(LANDED.slice(0, 7))509+ );510+ expect(text).toContain("answered by bram");511+ expect(hrefsOf(facts)).toStrictEqual(512+ expect.arrayContaining([513+ "/datekit/asks/parse-iso-week",514+ "/datekit/answers/parse-iso-week",515+ `/datekit/commit/${LANDED}`,516+ ])517+ );518+ });519+520 it("shows a binary file's size and a raw link, and no text", () => {521 const binary = decodeFile({522 at: AT,523 binary: true,2 unmodified lines526 size: 2048,527 truncated: false,528 });529 258- const element = <BlobView file={binary} project={datekit} rev="main" />;530+ const element = (531+ <BlobView file={binary} now={now} project={datekit} rev="main" />532+ );533 534 expect(markupOf(element)).not.toContain("<pre");535 expect(textOf(element)).toContain("2.0 KiB");536 expect(hrefsOf(markupOf(element))).toContain(10 unmodified lines547 size: 3_145_728,548 truncated: true,549 });550 277- const element = <BlobView file={large} project={datekit} rev="main" />;551+ const element = (552+ <BlobView file={large} now={now} project={datekit} rev="main" />553+ );554 555 expect(markupOf(element)).not.toContain("<pre");556 expect(textOf(element)).toContain("too large to show");557 expect(textOf(element)).toContain("3.0 MiB");12 unmodified lines570 truncated: false,571 });572 573 expect(298- markupOf(<BlobView file={logo} project={datekit} rev="main" />)574+ markupOf(<BlobView file={logo} now={now} project={datekit} rev="main" />)575 ).toMatch(576 new RegExp(`<img\\b[^>]*src="/datekit/raw/${AT}/docs/logo.png"`, "u")577 );578 });9 unmodified lines588 truncated: false,589 });590 591 const rendered = markupOf(316- <BlobView file={guide} project={datekit} rev="main" />592+ <BlobView file={guide} now={now} project={datekit} rev="main" />593 );594 595 const plain = markupOf(320- <BlobView file={guide} plain project={datekit} rev="main" />596+ <BlobView file={guide} now={now} plain project={datekit} rev="main" />597 );598 599 expect(rendered).toContain('data-readme="docs/guide.md"');600 expect(rendered).not.toContain('id="L1"');4 unmodified lines605 expect(plain).not.toContain("data-readme=");606 });607 });608 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-609 describe(LogView, () => {610 const page = (611 <LogView612 commits={commits}4 unmodified lines617 rev="main"618 />619 );620 408- it("groups the commits of one day under one heading", () => {621+ it("groups the commits of one day under one sticky header", () => {622 const markup = markupOf(page);623 624 const days = [...markup.matchAll(/data-day="(?<day>[^"]+)"/gu)].map(625 (match) => match.groups?.day2 unmodified lines628 expect(days).toStrictEqual(["2026-10-06", "2026-10-04"]);629 630 const first = slice(markup, "data-day", "2026-10-06");631 419- expect(first).toContain(`data-commit="${LANDED}"`);420- expect(first).toContain(`data-commit="${IMPORTED}"`);421- expect(first).not.toContain(`data-commit="${OLDER}"`);632+ expect(633+ [LANDED, IMPORTED, OLDER].map((sha) =>634+ first.includes(`data-commit="${sha}"`)635+ )636+ ).toStrictEqual([true, true, false]);637+ expect(first).toMatch(/class="[^"]*\bsticky\b/u);638+ expect(textOf(page)).toContain("October 6, 2026");639 });640 424- it("shows a landing's ask and credit, and links the commit", () => {641+ it("shows a landing's ask and credit in one line, and its short id over its age", () => {642 const row = slice(markupOf(page), "data-commit", LANDED);643 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");644+ expect(hrefsOf(row)).toStrictEqual(645+ expect.arrayContaining([646+ "/datekit/asks/parse-iso-week",647+ `/datekit/commit/${LANDED}`,648+ "/people/ines-v",649+ ])650+ );651+ expect(row).toContain("Asked by");652+ expect(row.indexOf(LANDED.slice(0, 7))).toBeGreaterThan(-1);653+ expect(row.indexOf(LANDED.slice(0, 7))).toBeLessThan(row.indexOf(" ago"));654 });655 656+ it("marks a landing judged by sealed checks held back, with its lock", () => {657+ const held = decodeCommits([658+ {659+ author: signature("Bram", "2026-10-06T15:00:00.000Z"),660+ body: "",661+ committer: signature("platform", "2026-10-06T15:00:00.000Z"),662+ landing: {663+ ask: "parse-iso-week",664+ assisted: [],665+ author: "bram",666+ credits: [{ handle: "bram", role: "Signed-off-by" }],667+ heldBackTrailer: "parser: 4 sealed checks by 3 people",668+ landedAt: "2026-10-06T15:00:00.000Z",669+ parent: IMPORTED,670+ project: "datekit",671+ sha: LANDED,672+ },673+ parents: [IMPORTED],674+ sha: LANDED,675+ subject: "Answer parse-iso-week",676+ trailers: [],677+ tree: "4".repeat(40),678+ },679+ ]);680+681+ const row = slice(682+ markupOf(683+ <LogView684+ commits={held}685+ from={0}686+ now={now}687+ project={datekit}688+ rev="main"689+ />690+ ),691+ "data-commit",692+ LANDED693+ );694+695+ expect(row).toContain("held back");696+ expect(row).toContain("text-sealed");697+ expect(row).toContain("lucide-lock-keyhole");698+ });699+700 it("links the ask an opening's landing opened, and reads it as an opening", () => {701 const [opening] = decodeCommits([702 {703 author: signature("Okonkwo", "2026-10-06T15:00:00.000Z"),32 unmodified lines736 );737 738 expect(hrefsOf(row)).toContain("/datekit/asks/parse-iso-week");739 expect(row).toContain("Opened");473- expect(row).not.toContain(">Ask<");740 });741 742+ it("filters the page to the answers or the asks' openings", () => {743+ const answers = markupOf(744+ <LogView745+ commits={commits}746+ from={0}747+ now={now}748+ project={datekit}749+ rev="main"750+ show="answers"751+ />752+ );753+754+ expect(answers).toContain(`data-commit="${LANDED}"`);755+ expect(answers).not.toContain(`data-commit="${IMPORTED}"`);756+757+ const filters = navOf(markupOf(page), 'aria-label="Show"');758+759+ expect(hrefsOf(filters)).toStrictEqual([760+ "/datekit/commits/main",761+ "/datekit/commits/main?show=answers",762+ "/datekit/commits/main?show=openings",763+ ]);764+ expect(filters).toMatch(/aria-current="page"[^>]*>All</u);765+ });766+767 it("says an imported commit came before adoption", () => {768 const row = slice(markupOf(page), "data-commit", IMPORTED);769 770 expect(row).toContain("before adoption");30 unmodified lines801 "/datekit/commits/main?path=src%2Fparse.ts&from=60",802 ]);803 });804 805+ it("keeps the filter on both pages: Older and Newer show the same kind", () => {806+ const pager = navOf(807+ markupOf(808+ <LogView809+ commits={commits}810+ from={30}811+ next={60}812+ now={now}813+ project={datekit}814+ rev="main"815+ show="answers"816+ />817+ ),818+ 'data-slot="pagination"'819+ );820+821+ expect(hrefsOf(pager)).toStrictEqual([822+ "/datekit/commits/main?show=answers",823+ "/datekit/commits/main?from=60&show=answers",824+ ]);825+ });826+827 it("goes back to a path's newest commits from a later page, since a path's `from` counts commits scanned, not shown", () => {828 // The platform scans 200 commits a call for a path, so the page that829 // starts at 230 may follow one that started at 30 or at 0: only the830 // first page is known to be newer.18 unmodified lines849 ]);850 });851 });852 540-const decodeDiff = Schema.decodeSync(CommitDiff);853+/** Lines `1` to `count`, as a file's text. */854+const linesUpTo = (count: number) =>855+ `${Array.from({ length: count }, (_, index) => `line ${index + 1}`).join(856+ "\n"857+ )}\n`;858 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,859+/** `diff`, with an added file of 120 lines: long enough to start folded. */860+const long = decodeDiff({861+ ...Schema.encodeSync(CommitDiff)(diff),862 files: [863+ ...Schema.encodeSync(CommitDiff)(diff).files,864 {597- after: "9".repeat(40),865+ after: "d".repeat(40),866 binary: false,599- newText: "export const week = 1;\n",600- path: "src/week.ts",867+ newText: linesUpTo(120),868+ path: "data/zones.ts",869 status: "added",870 },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- },871 ],620- truncated: false,872 });873 874 describe(CommitView, () => {875 const page = <CommitView diff={diff} now={now} project={datekit} />;876 626- it("names the people in its trailers, each linking their page", () => {627- const hrefs = hrefsOf(markupOf(page));877+ it("names the people in its credit, each linking their page, and shows its trailers once", () => {878+ const markup = markupOf(page);879+ const hrefs = hrefsOf(markup);880 629- expect(hrefs).toContain("/people/ines-v");630- expect(hrefs).toContain("/people/bram");881+ expect(hrefs).toStrictEqual(882+ expect.arrayContaining(["/people/ines-v", "/people/bram"])883+ );884+ expect(885+ ["Asked-by:", "Signed-off-by:", "data-body"].map((part) =>886+ countIn(markup, part)887+ )888+ ).toStrictEqual([1, 1, 1]);889+ expect(890+ /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markup)?.[0]891+ ).not.toContain("Asked-by");892 });893 894+ it("sets its body as prose in the sans, never in mono", () => {895+ const body =896+ /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markupOf(page))?.[0] ?? "";897+898+ expect(body).toContain("Parse ISO week dates.");899+ expect(body).not.toContain("font-mono");900+ expect(body).toContain("text-body");901+ });902+903 it("links no one from an imported commit's trailers", () => {904 const { landing: _landing, ...imported } = landedCommit;905 906 const markup = markupOf(5 unmodified lines912 );913 914 expect(hrefsOf(markup)).not.toContain("/people/bram");915 expect(markup).toContain("bram@users.example.com");916+ expect(markup).toContain("Before adoption");917 });918 648- it("shows the landing's ask, its answer and its verdict", () => {919+ it("leads with the landing's status line: landed as its id, and the ask it answered", () => {920 const markup = markupOf(page);921+ const text = mainOf(markup).replaceAll(/<[^>]+>/gu, "");922 923+ expect(text).toContain(`Landed as ${LANDED.slice(0, 7)}`);924+ expect(text).toContain("answered parse-iso-week");925 expect(hrefsOf(markup)).toContain("/datekit/asks/parse-iso-week");926 expect(hrefsOf(markup)).toContain("/datekit/answers/parse-iso-week");927 expect(markup).toContain('data-outcome="Landed"');928 });25 unmodified lines954 );955 956 expect(hrefsOf(markup)).toContain("/datekit/asks/parse-iso-week");957 expect(hrefsOf(markup)).not.toContain("/datekit/answers/parse-iso-week");684- expect(markup).toContain("Opened");958+ expect(markup).toContain("opened");959 });960 687- it("links its parent, and counts and names the files it changed", () => {961+ it("puts git's own facts on one line: author, committer and parent, linked", () => {962 const text = textOf(page);963 964 expect(hrefsOf(markupOf(page))).toContain(`/datekit/commit/${IMPORTED}`);691- expect(text).toContain("3 files changed");965+ expect(text).toContain("authored by Bram");966+ expect(text).toContain("committed by the platform");967+ expect(text).toContain(`parent ${IMPORTED.slice(0, 7)}`);968+ });969 693- for (const path of ["src/week.ts", "src/parse.ts", "src/legacy.ts"]) {694- expect(text).toContain(path);695- }970+ it("sends each changed file's diff as plain text, at the drawing's measures", () => {971+ const markup = markupOf(page);972 697- expect(markupOf(page)).not.toContain("<diffs-container");698- expect(markupOf(page)).not.toContain("<file-tree-container");973+ const plain =974+ /<div\b[^>]*data-diff="plain"[\s\S]*$/u.exec(markup)?.[0] ?? "";975+976+ expect(977+ ["leading-code", "min-w-[calc(6ch+2px)]", "pl-[2ch]"].filter(978+ (measure) => !plain.includes(measure)979+ )980+ ).toStrictEqual([]);981+ expect(982+ ["src/week.ts", "src/parse.ts", "src/legacy.ts"].filter(983+ (path) =>984+ !slice(plain, "data-file", path).includes('data-diffs-header=""')985+ )986+ ).toStrictEqual([]);987+ expect(988+ [989+ ["src/parse.ts", "export const parse = fromIso;"],990+ ["src/parse.ts", "export const parse = Date;"],991+ ["src/week.ts", "export const week = 1;"],992+ ].filter(993+ ([path = "", line = ""]) =>994+ !slice(plain, "data-file", path).includes(line)995+ )996+ ).toStrictEqual([]);997+ expect(markup).not.toMatch(/<(?:diffs|file-tree)-container/u);998 });999 1000+ it("keeps each file's header at the top of the pane while its lines scroll", () => {1001+ const header =1002+ /<summary\b[^>]*data-diffs-header=""[^>]*>/u.exec(markupOf(page))?.[0] ??1003+ "";1004+1005+ expect(header).toContain("sticky");1006+ expect(header).toContain("top-0");1007+ expect(header).toContain("h-11");1008+ });1009+1010+ it("starts an added or deleted file past 80 lines folded", () => {1011+ const markup = markupOf(1012+ <CommitView diff={long} now={now} project={datekit} />1013+ );1014+1015+ expect(slice(markup, "data-file", "data/zones.ts")).toContain(1016+ 'data-folded="true"'1017+ );1018+ expect(slice(markup, "data-file", "data/zones.ts")).not.toMatch(1019+ /<details\b[^>]*\bopen=/u1020+ );1021+ expect(slice(markup, "data-file", "src/parse.ts")).toContain(1022+ 'data-folded="false"'1023+ );1024+ });1025+1026+ it("counts the diff in the inspector: files, additions and deletions, split by path", () => {1027+ const facts = inspectorOf(1028+ markupOf(1029+ <CommitView1030+ diff={long}1031+ now={now}1032+ project={datekit}1033+ territory={["src/**"]}1034+ />1035+ )1036+ );1037+1038+ const stats =1039+ /<section\b[^>]*aria-label="Diff stats"[\s\S]*?<\/section>/u.exec(1040+ facts1041+ )?.[0] ?? "";1042+1043+ const text = stats.replaceAll(/<[^>]+>/gu, " ").replaceAll(/\s+/gu, " ");1044+1045+ expect(text).toContain("4 files");1046+ expect(text).toContain("+122 added");1047+ expect(text).toContain("−2 removed");1048+ expect(slice(stats, "data-part", "territory")).toContain("+2");1049+ expect(slice(stats, "data-part", "other")).toContain("+120");1050+ });1051+1052 it("says when the commit is too large to show whole", () => {1053 const truncated = decodeDiff({1054 commit: landedCommit,1055 files: [{ binary: false, path: "data/zones.json", status: "modified" }],342 unmodified lines1398 );1399 1400 expect(isNotFound(failed)).toBeTruthy();1401 1051- const carried = Schema.decodeUnknownOption(Refusals)(1052- isNotFound(failed) ? failed.data : undefined1402+ const data: unknown = isNotFound(failed) ? failed.data : undefined;1403+1404+ // A missing path lands on its nearest folder, its refusal beside it.1405+ const carried = Option.orElse(1406+ Schema.decodeUnknownOption(Refusals)(data),1407+ () =>1408+ Option.map(1409+ Schema.decodeUnknownOption(SoftLanding)(data),1410+ ({ refusals }) => refusals1411+ )1412 );1413 1414 return {1415 calls: yield* Ref.get(calls),135 unmodified lines1551 })1552 );1553 });1554 1555+/** The soft landing a page's read ended in. */1556+const landingOf = <A, E>(read: Effect.Effect<A, E, Client>) =>1557+ Effect.gen(function* () {1558+ const calls = yield* Ref.make<readonly Sent[]>([]);1559+1560+ const failed = yield* Effect.flip(1561+ read.pipe(Effect.provide(platformOf(calls)))1562+ );1563+1564+ return Schema.decodeUnknownOption(SoftLanding)(1565+ isNotFound(failed) ? failed.data : undefined1566+ );1567+ }).pipe(Effect.orDie);1568+1569+describe("a missing path", () => {1570+ it.effect(1571+ "lands on the nearest folder that exists at the commit, with the refusal as its notice",1572+ () =>1573+ Effect.gen(function* () {1574+ const landing = yield* landingOf(1575+ readBlobPage({1576+ _splat: "src/format/locale/gone/x.ts",1577+ project: "datekit",1578+ rev: "main",1579+ })1580+ );1581+1582+ expect(1583+ Option.map(landing, ({ nearest }) => nearest.path)1584+ ).toStrictEqual(Option.some("src/format/locale"));1585+ expect(1586+ Option.map(landing, ({ refusals }) => explain(refusals))1587+ ).toStrictEqual(1588+ Option.some(1589+ explain([noPath(RepoPath.make("src/format/locale/gone/x.ts"))])1590+ )1591+ );1592+1593+ const atRoot = yield* landingOf(1594+ readTreePage({ _splat: "nope", project: "datekit", rev: "main" })1595+ );1596+1597+ expect(1598+ Option.map(atRoot, ({ nearest }) => nearest.path === undefined)1599+ ).toStrictEqual(Option.some(true));1600+ })1601+ );1602+1603+ it("renders the nearest folder with UnknownPath's own words above it", () => {1604+ const refusal = noPath(RepoPath.make("src/format/locale/gone/x.ts"));1605+1606+ const markup = markupOf(1607+ <CodeNotFound1608+ data={Schema.encodeSync(SoftLanding)({1609+ nearest: nested,1610+ now,1611+ project: datekit,1612+ refusals: [refusal],1613+ rev: "main",1614+ })}1615+ />1616+ );1617+1618+ const text = textOf(1619+ <CodeNotFound1620+ data={Schema.encodeSync(SoftLanding)({1621+ nearest: nested,1622+ now,1623+ project: datekit,1624+ refusals: [refusal],1625+ rev: "main",1626+ })}1627+ />1628+ );1629+1630+ for (const line of explain([refusal])) {1631+ expect(text).toContain(line.trim());1632+ }1633+1634+ expect(markup).toContain('data-refusal="UnknownPath"');1635+ expect(markup).toContain('data-entry="src/format/locale/en.ts"');1636+ expect(markup.indexOf('data-refusal="UnknownPath"')).toBeLessThan(1637+ markup.indexOf('data-entry="src/format/locale/en.ts"')1638+ );1639+ });1640+1641+ it("keeps the Files button on the folder it lands on, so a phone still reaches the tree", () => {1642+ const data = Schema.encodeSync(SoftLanding)({1643+ nearest: nested,1644+ now,1645+ project: datekit,1646+ refusals: [noPath(RepoPath.make("src/format/locale/gone/x.ts"))],1647+ rev: "main",1648+ });1649+1650+ const pages = [1651+ ["tree", TreeRoute],1652+ ["blob", BlobRoute],1653+ ["why", WhyRoute],1654+ ] as const;1655+1656+ const withoutFiles = pages.flatMap(([page, route]) => {1657+ const Landing = route.options.notFoundComponent;1658+1659+ return Landing !== undefined &&1660+ /aria-haspopup="dialog"[^>]*>[\s\S]*?Files<\/button>/u.test(1661+ markupOf(<Landing data={data} isNotFound routeId={route.id} />)1662+ )1663+ ? []1664+ : [page];1665+ });1666+1667+ expect(withoutFiles).toStrictEqual([]);1668+ });1669+1670+ it("keeps any other refusal verbatim, with a way onward", () => {1671+ const refusal = new UnknownRevision({ rev: "v9" });1672+1673+ const element = (1674+ <CodeNotFound data={Schema.encodeSync(Refusals)([refusal])} />1675+ );1676+1677+ expect(markupOf(element)).toContain('data-refusal="UnknownRevision"');1678+ expect(hrefsOf(markupOf(element))).toContain("/");1679+ });1680+});1681+1682+/** The line a code page's route answers its headers with. */1683+const headersLine = (path: string) =>1684+ `headers: ({ loaderData, params }) => codePageHeaders(params.${1685+ path.includes("/commit/") ? "sha" : "rev"1686+ }, loaderData !== undefined)`;1687+1688+describe("a code page's caching", () => {1689+ it("keeps a page at a whole commit id for good, and a page at main or a tag briefly", () => {1690+ expect(1691+ [AT, "main", TAG].map((rev) => codePageHeaders(rev, true))1692+ ).toStrictEqual([immutablePage, branchPage, branchPage]);1693+ });1694+1695+ it("keeps a page that found nothing only briefly, even at a whole commit id, since a later landing or import may fill it", () => {1696+ expect(1697+ [AT, "main"].map((rev) => codePageHeaders(rev, false))1698+ ).toStrictEqual([branchPage, branchPage]);1699+ });1700+1701+ const routes: Readonly<Record<string, string>> = import.meta.glob(1702+ "../src/routes/$project/{tree,blob,why}/$rev/$.tsx",1703+ { eager: true, import: "default", query: "?raw" }1704+ );1705+1706+ const logs: Readonly<Record<string, string>> = import.meta.glob(1707+ "../src/routes/$project/{commits/$rev,commit/$sha}.tsx",1708+ { eager: true, import: "default", query: "?raw" }1709+ );1710+1711+ it("answers each code page with the headers its revision earns, and a commit's for good", () => {1712+ const pages = { ...routes, ...logs };1713+1714+ expect(Object.keys(pages)).toHaveLength(5);1715+ expect(1716+ Object.entries(pages).flatMap(([path, source]) =>1717+ source.replaceAll(/\s+/gu, " ").includes(headersLine(path))1718+ ? []1719+ : [path]1720+ )1721+ ).toStrictEqual([]);1722+ });1723+});1724+1725 describe("the code browser's views", () => {1726 const sources: Readonly<Record<string, string>> = import.meta.glob(1727 "../src/features/code/**/*.{ts,tsx}",1728 { 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