code.test.tsx
This file
Path
apps/web/test/code.test.tsx
2,172 lines · 64.2 KiB · TypeScript
Last changed by
Merge web/code-tab-and-fixes into main, keeping both the hero's concurrency line and its second actionoscabrielbefore adoption2eaa076
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { Client, Contracts } from "@repo/protocol/contracts";3import type { Contract } from "@repo/protocol/contracts";4import {5 CommitDiff,6 CommitView as Commit,7 FileView,8 RefsView as Refs,9 TreeListing,10} from "@repo/protocol/domain/code";11import { Outcome } from "@repo/protocol/domain/outcome";12import {13 CommitSha,14 LandedSha,15 ProjectName,16 RepoPath,17} from "@repo/protocol/ids";18import {19 UnknownCommit,20 UnknownPath,21 UnknownProject,22 UnknownRevision,23} from "@repo/protocol/refusal";24import type { Refusal } from "@repo/protocol/refusal";25import { explain } from "@repo/protocol/render";26import { asTester, unanswered } from "@repo/protocol/testing";27import { isNotFound } from "@tanstack/react-router";28import { DateTime, Effect, Layer, Option, Ref, Schema, Struct } from "effect";29import { RpcTest } from "effect/rpc";30import type { Rpc } from "effect/rpc";31import type { ReactElement } from "react";32import { renderToStaticMarkup } from "react-dom/server";3334import { BlobView } from "../src/features/code/blob-view.tsx";35import { codeAddressOf } from "../src/features/code/code-address.ts";36import { checkoutCommand } from "../src/features/code/code-bar.tsx";37import { CommitView } from "../src/features/code/commit-view.tsx";38import { FileFacts } from "../src/features/code/file-facts.tsx";39import { filesMatching } from "../src/features/code/file-match.ts";40import { LOG_PAGE } from "../src/features/code/log-page.ts";41import { LogView, titleOf } from "../src/features/code/log-view.tsx";42import { CodeNotFound } from "../src/features/code/not-found.tsx";43import { SoftLanding } from "../src/features/code/soft-landing.ts";44import { TreeView } from "../src/features/code/tree-view.tsx";45import { ProjectFrame } from "../src/features/project/project-frame.tsx";46import { ProjectHeader } from "../src/features/project/project-header.tsx";47import { Refusals } from "../src/features/shared/refusals.ts";48import { projectTabOf } from "../src/features/shared/shell/sections.ts";49import { ProjectCodeBar } from "../src/routes/$owner/$project/-code-bar.tsx";50import { readBlobPage } from "../src/routes/$owner/$project/blob/$rev/$.tsx";51import { readCommitPage } from "../src/routes/$owner/$project/commit/$sha.tsx";52import { readLogPage } from "../src/routes/$owner/$project/commits/$rev.tsx";53import { readRefsPage } from "../src/routes/$owner/$project/refs.tsx";54import { readTreePage } from "../src/routes/$owner/$project/tree/$rev/$.tsx";55import {56 CodeColumn,57 CommitColumn,58} from "../src/routes/$owner/$project/tree/-code-column.tsx";59import { plainText } from "./ask-fixtures.ts";60import { elementWith, elementsWith } from "./records.ts";61import { renderAt } from "./render.tsx";62import { reachingTransport } from "./transport.ts";6364const markupOf = (element: ReactElement) => renderToStaticMarkup(element);6566const textOf = (element: ReactElement) =>67 markupOf(element)68 .replaceAll(/<[^>]+>/gu, " ")69 .replaceAll("'", "'")70 .replaceAll(""", '"')71 .replaceAll("<", "<")72 .replaceAll(">", ">")73 .replaceAll("&", "&")74 .replaceAll(/\s+/gu, " ");7576const hrefsOf = (markup: string) =>77 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map((match) =>78 (match.groups?.href ?? "").replaceAll("&", "&")79 );8081const slice = (markup: string, marker: string, value: string) => {82 const start = markup.indexOf(`${marker}="${value}"`);83 const next = markup.indexOf(`${marker}="`, start + 1);8485 return start === -186 ? ""87 : markup.slice(start, next === -1 ? undefined : next);88};8990const navOf = (markup: string, attribute: string) =>91 new RegExp(`<nav\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</nav>`, "u").exec(92 markup93 )?.[0] ?? "";9495const datekit = ProjectName.make("oscabriel/datekit");9697const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");9899const AT = "a".repeat(40);100101const decodeTree = Schema.decodeSync(TreeListing);102103const decodeFile = Schema.decodeSync(FileView);104105const root = decodeTree({106 at: AT,107 entries: [108 {109 mode: "040000",110 name: "src",111 path: "src",112 sha: "b".repeat(40),113 type: "tree",114 },115 {116 mode: "100644",117 name: "README.md",118 path: "README.md",119 sha: "c".repeat(40),120 type: "blob",121 },122 ],123 readme: { path: "README.md", sha: "c".repeat(40) },124});125126const readme = decodeFile({127 at: AT,128 binary: false,129 path: "README.md",130 sha: "c".repeat(40),131 size: 26,132 text: "# datekit\n\nDates, kept.\n",133 truncated: false,134});135136const nested = decodeTree({137 at: AT,138 entries: [139 {140 mode: "100644",141 name: "en.ts",142 path: "src/format/locale/en.ts",143 sha: "d".repeat(40),144 type: "blob",145 },146 ],147 path: "src/format/locale",148});149150const TAG = "@datekit/core@1.0.0";151152const TAG_SEGMENT = "%40datekit%2Fcore%401.0.0";153154const decodeCommits = Schema.decodeSync(Schema.Array(Commit));155156const signature = (name: string, at: string) => ({157 at,158 email: `${name}@example.com`,159 name,160});161162const LANDED = "1".repeat(40);163164const IMPORTED = "2".repeat(40);165166const OLDER = "3".repeat(40);167168const commits = decodeCommits([169 {170 author: signature("Bram", "2026-10-06T15:00:00.000Z"),171 body: "",172 committer: signature("platform", "2026-10-06T15:00:00.000Z"),173 landing: {174 ask: "parse-iso-week",175 assisted: [],176 author: "bram",177 credits: [178 { handle: "bram", role: "Signed-off-by" },179 { handle: "ines-v", role: "Asked-by" },180 ],181 landedAt: "2026-10-06T15:00:00.000Z",182 parent: IMPORTED,183 project: "datekit",184 sha: LANDED,185 },186 parents: [IMPORTED],187 sha: LANDED,188 subject: "Answer parse-iso-week",189 trailers: [190 { key: "Asked-by", value: "ines-v" },191 { key: "Signed-off-by", value: "bram" },192 ],193 tree: "4".repeat(40),194 },195 {196 author: signature("Lin", "2026-10-06T09:00:00.000Z"),197 body: "",198 committer: signature("Lin", "2026-10-06T09:00:00.000Z"),199 parents: [OLDER],200 sha: IMPORTED,201 subject: "Support week numbers",202 trailers: [],203 tree: "5".repeat(40),204 },205 {206 author: signature("Lin", "2026-10-04T09:00:00.000Z"),207 body: "",208 committer: signature("Lin", "2026-10-04T09:00:00.000Z"),209 parents: [],210 sha: OLDER,211 subject: "First commit",212 trailers: [],213 tree: "6".repeat(40),214 },215]);216217const decodeDiff = Schema.decodeSync(CommitDiff);218219const landedCommit: typeof Commit.Encoded = {220 author: signature("Bram", "2026-10-06T15:00:00.000Z"),221 body: "Parse ISO week dates.\n\nAsked-by: ines-v\nSigned-off-by: bram",222 committer: signature("platform", "2026-10-06T15:00:00.000Z"),223 landing: {224 ask: "parse-iso-week",225 assisted: [],226 author: "bram",227 credits: [228 { handle: "bram", role: "Signed-off-by" },229 { handle: "ines-v", role: "Asked-by" },230 ],231 landedAt: "2026-10-06T15:00:00.000Z",232 parent: IMPORTED,233 project: "datekit",234 sha: LANDED,235 verdict: {236 ask: "parse-iso-week",237 at: "2026-10-06T14:59:00.000Z",238 base: IMPORTED,239 checkVersion: "redThenGreen@0.0.0+abc",240 head: "7".repeat(40),241 heldBack: [],242 lanes: [243 {244 command: "bun test",245 durationMs: 1200,246 lane: "unit",247 result: "passed",248 },249 ],250 outcome: Schema.encodeSync(Outcome)(251 Outcome.cases.Landed.make({ sha: LandedSha.make(LANDED) })252 ),253 patchId: "8".repeat(64),254 project: "datekit",255 stage: "checks",256 tree: "4".repeat(40),257 verifier: "platform",258 },259 },260 parents: [IMPORTED],261 sha: LANDED,262 subject: "Answer parse-iso-week",263 trailers: [264 { key: "Asked-by", value: "ines-v <ines-v@users.example.com>" },265 { key: "Signed-off-by", value: "bram <bram@users.example.com>" },266 ],267 tree: "4".repeat(40),268};269270const diff = decodeDiff({271 commit: landedCommit,272 files: [273 {274 after: "9".repeat(40),275 binary: false,276 newText: "export const week = 1;\n",277 path: "src/week.ts",278 status: "added",279 },280 {281 after: "a".repeat(40),282 before: "b".repeat(40),283 binary: false,284 newText: "export const parse = fromIso;\n",285 oldText: "export const parse = Date;\n",286 path: "src/parse.ts",287 status: "modified",288 },289 {290 before: "c".repeat(40),291 binary: false,292 oldText: "export const legacy = true;\n",293 path: "src/legacy.ts",294 status: "deleted",295 },296 ],297 truncated: false,298});299300const factsOf = (markup: string) => elementWith(markup, 'data-facts="inline"');301302/** The main region without its facts, which sit inside it. */303const mainOf = (markup: string) => {304 const main = /<main\b[\s\S]*?<\/main>/u.exec(markup)?.[0] ?? "";305 const facts = factsOf(main);306307 return facts === "" ? main : main.replace(facts, "");308};309310const countIn = (text: string, part: string) => text.split(part).length - 1;311312const anchorOf = (markup: string, label: string) =>313 new RegExp(`<a\\b[^>]*>${label}</a>`, "u").exec(markup)?.[0];314315describe(TreeView, () => {316 const page = (317 <TreeView318 listing={root}319 now={now}320 project={datekit}321 readme={readme}322 rev="main"323 />324 );325326 it("lists folders before files, each linking its own page at the same revision", () => {327 const markup = markupOf(page);328329 expect(markup.indexOf('data-entry="src"')).toBeGreaterThan(-1);330 expect(markup.indexOf('data-entry="src"')).toBeLessThan(331 markup.indexOf('data-entry="README.md"')332 );333 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/tree/main/src");334 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/blob/main/README.md");335 });336337 it("lists the folder once", () => {338 const markup = markupOf(page);339340 expect(countIn(markup, 'data-entry="src"')).toBe(1);341 expect(countIn(markup, 'data-entry="README.md"')).toBe(1);342 expect(countIn(markup, "data-entries=")).toBe(1);343 });344345 it("says what last changed each entry, once it has been read", () => {346 const [last] = commits;347348 const markup = markupOf(349 <TreeView350 last={new Map(last === undefined ? [] : [["src", last]])}351 listing={root}352 now={now}353 project={datekit}354 rev="main"355 />356 );357358 expect(slice(markup, "data-entry", "src")).toContain("parse-iso-week");359 expect(slice(markup, "data-entry", "src")).toContain("ago");360 expect(slice(markup, "data-entry", "README.md")).not.toContain("ago");361 });362363 it("links each ancestor in its path at the same revision, and names the folder last", () => {364 const markup = markupOf(365 <TreeView listing={nested} now={now} project={datekit} rev={TAG} />366 );367368 const crumbs = hrefsOf(navOf(markup, 'aria-label="Path"'));369370 expect(crumbs).toStrictEqual([371 `/oscabriel/datekit/tree/${TAG_SEGMENT}`,372 `/oscabriel/datekit/tree/${TAG_SEGMENT}/src`,373 `/oscabriel/datekit/tree/${TAG_SEGMENT}/src/format`,374 ]);375 expect(376 textOf(377 <TreeView listing={nested} now={now} project={datekit} rev={TAG} />378 )379 ).toContain("locale");380 });381382 it("renders the folder's README below its entries", () => {383 const markup = markupOf(page);384385 expect(markup).toContain('data-readme="README.md"');386 expect(textOf(page)).toContain("Dates, kept.");387 expect(markup.indexOf("data-readme=")).toBeGreaterThan(388 markup.indexOf('data-entry="README.md"')389 );390 });391392 it("leaves the file tree to the browser", () => {393 expect(markupOf(page)).not.toContain("<file-tree-container");394 });395396 it.effect(397 "links the folder's history with its path as the search, current on that page",398 () =>399 Effect.gen(function* () {400 const markup = yield* renderAt(401 `/oscabriel/datekit/commits/${TAG_SEGMENT}?path=src%2Fformat%2Flocale`,402 <TreeView listing={nested} now={now} project={datekit} rev={TAG} />403 );404405 const history = anchorOf(markup, "History");406407 expect(history).toContain(408 `href="/oscabriel/datekit/commits/${TAG_SEGMENT}?path=src%2Fformat%2Flocale"`409 );410 expect(history).toContain('aria-current="page"');411 })412 );413});414415const permalink = (mode: "code" | "why") =>416 /href="(?<href>[^"]*)"[^>]*>Permalink</u.exec(417 markupOf(418 <FileFacts419 file={readme}420 mode={mode}421 now={now}422 project={datekit}423 rev="main"424 />425 )426 )?.groups?.href;427428describe("a file's facts", () => {429 it("link a permalink to the page they sit on: the code, or why", () => {430 expect(permalink("code")).toBe(`/oscabriel/datekit/blob/${AT}/README.md`);431 expect(permalink("why")).toBe(`/oscabriel/datekit/why/${AT}/README.md`);432 });433434 // The history's `?path=` is the address's search, not part of its path:435 // the router then reads `main` as the revision (a hover fetches the right436 // page) and marks the link on the history it leads to.437 it.effect(438 "link the file's history with its path as the search, current on that page",439 () =>440 Effect.gen(function* () {441 const markup = yield* renderAt(442 "/oscabriel/datekit/commits/main?path=README.md",443 <FileFacts file={readme} now={now} project={datekit} rev="main" />444 );445446 const history = anchorOf(markup, "History of this file");447448 expect(history).toContain(449 'href="/oscabriel/datekit/commits/main?path=README.md"'450 );451 expect(history).toContain('aria-current="page"');452 })453 );454});455456describe(BlobView, () => {457 const parse = decodeFile({458 at: AT,459 binary: false,460 path: "src/format/parse.ts",461 sha: "e".repeat(40),462 size: 14,463 text: "one\ntwo\nthree\n",464 truncated: false,465 });466467 const [lastLanding] = commits;468469 const page = (470 <BlobView471 file={parse}472 last={lastLanding}473 now={now}474 project={datekit}475 rev="main"476 />477 );478479 it("numbers each line of a text file with its own anchor, and draws no highlighting on the server", () => {480 const markup = markupOf(page);481482 const anchors = [...markup.matchAll(/id="(?<line>L\d+)"/gu)].map(483 (match) => match.groups?.line484 );485486 expect(markup).toContain("<pre");487 expect(anchors).toStrictEqual(["L1", "L2", "L3"]);488 expect(markup).not.toContain("<diffs-container");489 });490491 it("anchors each line on an element that draws a box, so `#L2` scrolls to it without script", () => {492 // A `display: contents` element draws no box, and a browser cannot493 // scroll to it.494 const anchored = /<(?<tag>\w+)\b(?<attributes>[^>]*)\bid="L2"[^>]*>/u.exec(495 markupOf(page)496 );497498 expect(anchored?.groups?.tag).toBe("span");499 expect(anchored?.groups?.attributes).not.toMatch(/\bcontents\b/u);500 });501502 it("sets the plain text at the drawing's measures: 20 px lines and Pierre's gutter", () => {503 const code = /<pre\b[^>]*>/u.exec(markupOf(page))?.[0] ?? "";504505 expect(code).toContain("leading-code");506 expect(code).toContain("text-mono");507 expect(markupOf(page)).toContain("min-w-[calc(6ch+2px)]");508 expect(markupOf(page)).toContain("pl-[2ch]");509 });510511 it("names the path once in the page, in its file header", () => {512 const main = mainOf(markupOf(page));513514 expect(515 countIn(main.replaceAll(/<[^>]+>/gu, ""), "src/format/parse.ts")516 ).toBe(1);517 expect(countIn(main, 'title="src/format/parse.ts"')).toBe(1);518 expect(countIn(main, 'aria-label="Path"')).toBe(1);519 expect(hrefsOf(navOf(main, 'aria-label="Path"'))).toStrictEqual([520 "/oscabriel/datekit/tree/main",521 "/oscabriel/datekit/tree/main/src",522 "/oscabriel/datekit/tree/main/src/format",523 ]);524 });525526 it("has the Code | Why toggle, Code current", () => {527 const toggle = navOf(markupOf(page), 'aria-label="Mode"');528529 expect(hrefsOf(toggle)).toStrictEqual([530 "/oscabriel/datekit/blob/main/src/format/parse.ts",531 "/oscabriel/datekit/why/main/src/format/parse.ts",532 ]);533 expect(toggle).toMatch(/aria-current="page"[^>]*>Code</u);534 expect(toggle).not.toMatch(/aria-current="page"[^>]*>Why</u);535 });536537 it("links raw at the commit and the permalink at the commit, and the history at the revision", () => {538 const markup = markupOf(page);539 const toolbar = navOf(markup, 'data-toolbar="file"');540541 expect(hrefsOf(toolbar)).toStrictEqual([542 `/oscabriel/datekit/raw/${AT}/src/format/parse.ts`,543 `/oscabriel/datekit/blob/${AT}/src/format/parse.ts`,544 ]);545 expect(hrefsOf(factsOf(markup))).toContain(546 "/oscabriel/datekit/commits/main?path=src%2Fformat%2Fparse.ts"547 );548 });549550 it("names the last landing's ask in This file, before its SHA", () => {551 const facts = factsOf(markupOf(page));552 const text = facts.replaceAll(/<[^>]+>/gu, "");553554 expect(facts).toContain("This file");555 expect(text.indexOf("parse-iso-week")).toBeGreaterThan(-1);556 expect(text.indexOf("parse-iso-week")).toBeLessThan(557 text.indexOf(LANDED.slice(0, 7))558 );559 expect(text).toContain("answered by bram");560 expect(hrefsOf(facts)).toStrictEqual(561 expect.arrayContaining([562 "/oscabriel/datekit/asks/parse-iso-week",563 "/oscabriel/datekit/answers/parse-iso-week",564 `/oscabriel/datekit/commit/${LANDED}`,565 ])566 );567 });568569 it("shows a binary file's size and a raw link, and no text", () => {570 const binary = decodeFile({571 at: AT,572 binary: true,573 path: "assets/fixture.bin",574 sha: "f".repeat(40),575 size: 2048,576 truncated: false,577 });578579 const element = (580 <BlobView file={binary} now={now} project={datekit} rev="main" />581 );582583 expect(markupOf(element)).not.toContain("<pre");584 expect(textOf(element)).toContain("2.0 KiB");585 expect(hrefsOf(markupOf(element))).toContain(586 `/oscabriel/datekit/raw/${AT}/assets/fixture.bin`587 );588 });589590 it("says a file past the cap is too large to show, with a raw link", () => {591 const large = decodeFile({592 at: AT,593 binary: false,594 path: "data/zones.json",595 sha: "f".repeat(40),596 size: 3_145_728,597 truncated: true,598 });599600 const element = (601 <BlobView file={large} now={now} project={datekit} rev="main" />602 );603604 expect(markupOf(element)).not.toContain("<pre");605 expect(textOf(element)).toContain("too large to show");606 expect(textOf(element)).toContain("3.0 MiB");607 expect(hrefsOf(markupOf(element))).toContain(608 `/oscabriel/datekit/raw/${AT}/data/zones.json`609 );610 });611612 it("shows an image inline from raw", () => {613 const logo = decodeFile({614 at: AT,615 binary: true,616 path: "docs/logo.png",617 sha: "f".repeat(40),618 size: 512,619 truncated: false,620 });621622 expect(623 markupOf(<BlobView file={logo} now={now} project={datekit} rev="main" />)624 ).toMatch(625 new RegExp(626 `<img\\b[^>]*src="/oscabriel/datekit/raw/${AT}/docs/logo.png"`,627 "u"628 )629 );630 });631632 it("renders a Markdown file, and its source on ?plain=1", () => {633 const guide = decodeFile({634 at: AT,635 binary: false,636 path: "docs/guide.md",637 sha: "f".repeat(40),638 size: 18,639 text: "# Guide\n\nRead me.\n",640 truncated: false,641 });642643 const rendered = markupOf(644 <BlobView file={guide} now={now} project={datekit} rev="main" />645 );646647 const plain = markupOf(648 <BlobView file={guide} now={now} plain project={datekit} rev="main" />649 );650651 expect(rendered).toContain('data-readme="docs/guide.md"');652 expect(rendered).not.toContain('id="L1"');653 expect(hrefsOf(rendered)).toContain(654 "/oscabriel/datekit/blob/main/docs/guide.md?plain=1"655 );656 expect(plain).toContain('id="L3"');657 expect(plain).not.toContain("data-readme=");658 });659});660661const platformUrl = "https://platform-test.example.workers.dev";662663/** A code page as the project's layout draws it: the frame, the project's header and its tab from the path, then the page. */664const inCodeTab = (url: string, page: ReactElement, head?: Commit) =>665 renderAt(666 url,667 <ProjectFrame668 header={669 <ProjectHeader670 current={projectTabOf(new URL(url, platformUrl).pathname)}671 header={{ now, project: datekit }}672 platformUrl={platformUrl}673 />674 }675 codeBar={<ProjectCodeBar platformUrl={platformUrl} />}676 >677 {page}678 </ProjectFrame>,679 {680 loaderData:681 head === undefined682 ? undefined683 : {684 head: Schema.encodeSync(Commit)(head),685 now: DateTime.formatIso(now),686 },687 }688 );689690const codeBarOf = (markup: string) => elementWith(markup, 'data-code-bar=""');691692const parseTs = decodeFile({693 at: AT,694 binary: false,695 path: "src/format/parse.ts",696 sha: "e".repeat(40),697 size: 14,698 text: "one\ntwo\nthree\n",699 truncated: false,700});701702const treeAndBlob = Effect.all([703 inCodeTab(704 "/oscabriel/datekit/tree/main/src/format/locale",705 <TreeView listing={nested} now={now} project={datekit} rev="main" />706 ),707 inCodeTab(708 "/oscabriel/datekit/blob/main/src/format/parse.ts",709 <BlobView file={parseTs} now={now} project={datekit} rev="main" />710 ),711]);712713/** Each link of a control, with whether it is marked as the page being read. */714const linksIn = (markup: string) =>715 [...markup.matchAll(/<a\b(?<attributes>[^>]*)>(?<text>[\s\S]*?)<\/a>/gu)].map(716 ({ groups }) => ({717 current: /aria-current="page"/u.test(groups?.attributes ?? ""),718 href: hrefsOf(groups?.attributes ?? "")[0],719 text: (groups?.text ?? "").replaceAll(/<[^>]+>/gu, "").trim(),720 })721 );722723describe("a code page in the Code tab", () => {724 it.effect(725 "keeps the project header, with Code its current tab, over the code bar",726 () =>727 Effect.gen(function* () {728 const pages = yield* treeAndBlob;729730 expect(731 pages.map(732 (markup) =>733 elementWith(markup, 'data-project-header=""') !== "" &&734 /aria-current="page"[^>]*>Code</u.test(735 elementWith(markup, 'data-project-tabs=""')736 )737 )738 ).toStrictEqual([true, true]);739 expect(740 pages.map(741 (markup) =>742 markup.indexOf('data-project-header=""') <743 markup.indexOf('data-code-bar=""')744 )745 ).toStrictEqual([true, true]);746 })747 );748749 it.effect(750 "has the Files/History toggle, Files current, and the revision picker reading At main",751 () =>752 Effect.gen(function* () {753 const bars = (yield* treeAndBlob).map(codeBarOf);754755 expect(756 bars.map((bar) =>757 linksIn(navOf(bar, 'aria-label="Files or history"'))758 )759 ).toStrictEqual(760 bars.map(() => [761 {762 current: true,763 href: "/oscabriel/datekit/tree/main",764 text: "Files",765 },766 {767 current: false,768 href: "/oscabriel/datekit/commits/main",769 text: "History",770 },771 ])772 );773 expect(774 bars.map((bar) => /<button\b[^>]*data-ref="main"[^>]*>/u.test(bar))775 ).toStrictEqual([true, true]);776 expect(777 bars.map((bar) =>778 plainText(elementWith(bar, 'data-ref="main"'))779 .replaceAll(/\s+/gu, " ")780 .trim()781 )782 ).toStrictEqual(["At main", "At main"]);783 expect(784 bars.map((bar) => elementWith(bar, 'data-ref="main"'))785 ).not.toContain("lucide-git-branch");786 })787 );788789 it.effect(790 "draws no Menu control: the top bar's links stay where they are",791 () =>792 Effect.gen(function* () {793 const pages = yield* treeAndBlob;794795 expect(796 pages.flatMap((markup) => [797 ...elementsWith(markup, '(?:aria-label|title)="[^"]*Menu'),798 ...[...markup.matchAll(/>\s*Menu\s*</gu)].map(([found]) => found),799 ])800 ).toStrictEqual([]);801 })802 );803804 it.effect(805 "shows the revision's head commit in the bar: its short id and subject linking it, then its author",806 () =>807 Effect.gen(function* () {808 const [head] = commits;809810 const bar = codeBarOf(811 yield* inCodeTab(812 "/oscabriel/datekit/tree/main",813 <TreeView listing={root} now={now} project={datekit} rev="main" />,814 head815 )816 );817818 const shown = elementWith(bar, `data-head-commit="${LANDED}"`);819820 expect(821 linksIn(shown).map(({ href, text }) => [href, text])822 ).toStrictEqual([823 [`/oscabriel/datekit/commit/${LANDED}`, LANDED.slice(0, 7)],824 [`/oscabriel/datekit/commit/${LANDED}`, "Answer parse-iso-week"],825 ]);826 expect(shown).toContain("Bram");827 })828 );829830 it.effect(831 "marks History on the history and on a commit, at the same revision, and nothing on the refs list",832 () =>833 Effect.gen(function* () {834 const pages = yield* Effect.forEach(835 [836 `/oscabriel/datekit/commits/${TAG_SEGMENT}`,837 `/oscabriel/datekit/commit/${LANDED}`,838 "/oscabriel/datekit/refs",839 ],840 (url) => inCodeTab(url, <main id="main" />)841 );842843 const toggles = pages.map((markup) =>844 linksIn(navOf(codeBarOf(markup), 'aria-label="Files or history"'))845 );846847 expect(848 toggles.map((links) =>849 links.flatMap(({ current, text }) => (current ? [text] : []))850 )851 ).toStrictEqual([["History"], ["History"], []]);852 expect(toggles[0]?.map(({ href }) => href)).toStrictEqual([853 `/oscabriel/datekit/tree/${TAG_SEGMENT}`,854 `/oscabriel/datekit/commits/${TAG_SEGMENT}`,855 ]);856 })857 );858859 it.effect("draws no code bar on a page of another tab", () =>860 Effect.gen(function* () {861 const pages = yield* Effect.forEach(862 ["/oscabriel/datekit", "/oscabriel/datekit/asks/parse-iso-week"],863 (url) => inCodeTab(url, <main id="main" />)864 );865866 expect(pages.map(codeBarOf)).toStrictEqual(["", ""]);867 })868 );869870 it.effect(871 "opens the file tree from the bar's Tree button below the columns, and offers Go to file and Clone",872 () =>873 Effect.gen(function* () {874 const [tree] = yield* treeAndBlob;875 const bar = codeBarOf(tree);876877 expect(bar).toMatch(878 /class="columns:hidden[^"]*"><button[^>]*aria-haspopup="dialog"[^>]*>[\s\S]*?Tree<\/button>/u879 );880 expect(bar).toMatch(/title="Go to file \(t\)"/u);881 expect(bar).toContain('data-action="clone-here"');882 })883 );884885 it.effect(886 "gives the blob page's file header a Why toggle to the why page for the same path and revision",887 () =>888 Effect.gen(function* () {889 const [, blob] = yield* treeAndBlob;890 const toggle = navOf(blob, 'aria-label="Mode"');891892 expect(linksIn(toggle).find(({ text }) => text === "Why")?.href).toBe(893 "/oscabriel/datekit/why/main/src/format/parse.ts"894 );895 expect(elementWith(blob, 'data-toolbar=""')).toContain(896 'aria-label="Mode"'897 );898 })899 );900});901902describe(codeAddressOf, () => {903 it.each([904 [905 "/oscabriel/datekit/tree/main",906 { page: "tree", path: undefined, rev: "main" },907 ],908 [909 `/oscabriel/datekit/blob/${TAG_SEGMENT}/src/a%20b.ts`,910 { page: "blob", path: "src/a b.ts", rev: TAG },911 ],912 [913 "/oscabriel/datekit/why/main/src/parse.ts",914 { page: "why", path: "src/parse.ts", rev: "main" },915 ],916 [917 `/oscabriel/datekit/commit/${LANDED}`,918 { page: "commit", path: undefined, rev: LANDED },919 ],920 ["/oscabriel/datekit/refs", { page: "refs", rev: "main" }],921 ])("reads %s", (pathname, address) => {922 expect(codeAddressOf(pathname)).toStrictEqual(Option.some(address));923 });924925 it("reads no address off the Code tab", () => {926 expect(927 [928 "/oscabriel/datekit",929 "/oscabriel/datekit/asks/parse-iso-week",930 "/oscabriel/datekit/tree",931 ].map((pathname) => Option.isNone(codeAddressOf(pathname)))932 ).toStrictEqual([true, true, true]);933 });934});935936describe(filesMatching, () => {937 const paths = [938 "src/format/locale/en.ts",939 "src/parse.ts",940 "test/parse.test.ts",941 "README.md",942 ];943944 it("keeps the paths holding every word, a match in the file's own name first", () => {945 expect(filesMatching(paths, "parse")).toStrictEqual([946 "src/parse.ts",947 "test/parse.test.ts",948 ]);949 expect(filesMatching(paths, "src ts")).toStrictEqual([950 "src/parse.ts",951 "src/format/locale/en.ts",952 ]);953 });954955 it("matches without regard to case, and stops at its limit", () => {956 expect(filesMatching(paths, "readme")).toStrictEqual(["README.md"]);957 expect(filesMatching(paths, "", 2)).toHaveLength(2);958 });959});960961describe(checkoutCommand, () => {962 it("checks out a tag or a commit as it is, and quotes anything else", () => {963 expect(checkoutCommand(TAG)).toBe(`git checkout ${TAG}`);964 expect(checkoutCommand(LANDED)).toBe(`git checkout ${LANDED}`);965 expect(checkoutCommand("v1;rm -rf ~")).toBe("git checkout 'v1;rm -rf ~'");966 expect(checkoutCommand("it's")).toBe(`git checkout 'it'\\''s'`);967 });968});969970describe(LogView, () => {971 const page = (972 <LogView973 commits={commits}974 from={0}975 next={30}976 now={now}977 project={datekit}978 rev="main"979 show="all"980 />981 );982983 /** The same page as main's history opens: no filter named, so the landings alone. */984 const landings = (985 <LogView986 commits={commits}987 from={0}988 next={30}989 now={now}990 project={datekit}991 rev="main"992 />993 );994995 it("groups the commits of one day under one sticky header", () => {996 const markup = markupOf(page);997998 const days = [...markup.matchAll(/data-day="(?<day>[^"]+)"/gu)].map(999 (match) => match.groups?.day1000 );10011002 expect(days).toStrictEqual(["2026-10-06", "2026-10-04"]);10031004 const first = slice(markup, "data-day", "2026-10-06");10051006 expect(1007 [LANDED, IMPORTED, OLDER].map((sha) =>1008 first.includes(`data-commit="${sha}"`)1009 )1010 ).toStrictEqual([true, true, false]);1011 expect(first).toMatch(/class="[^"]*\bsticky\b/u);1012 expect(textOf(page)).toContain("October 6, 2026");1013 });10141015 it("shows a landing's ask and credit in one line, and its short id over its age", () => {1016 const row = slice(markupOf(page), "data-commit", LANDED);10171018 expect(hrefsOf(row)).toStrictEqual(1019 expect.arrayContaining([1020 "/oscabriel/datekit/asks/parse-iso-week",1021 `/oscabriel/datekit/commit/${LANDED}`,1022 "/people/ines-v",1023 ])1024 );1025 expect(row).toContain("Asked by");1026 expect(row.indexOf(LANDED.slice(0, 7))).toBeGreaterThan(-1);1027 expect(row.indexOf(LANDED.slice(0, 7))).toBeLessThan(row.indexOf(" ago"));1028 });10291030 it("marks a landing judged by sealed checks held back, with its lock", () => {1031 const held = decodeCommits([1032 {1033 author: signature("Bram", "2026-10-06T15:00:00.000Z"),1034 body: "",1035 committer: signature("platform", "2026-10-06T15:00:00.000Z"),1036 landing: {1037 ask: "parse-iso-week",1038 assisted: [],1039 author: "bram",1040 credits: [{ handle: "bram", role: "Signed-off-by" }],1041 heldBackTrailer: "parser: 4 sealed checks by 3 people",1042 landedAt: "2026-10-06T15:00:00.000Z",1043 parent: IMPORTED,1044 project: "datekit",1045 sha: LANDED,1046 },1047 parents: [IMPORTED],1048 sha: LANDED,1049 subject: "Answer parse-iso-week",1050 trailers: [],1051 tree: "4".repeat(40),1052 },1053 ]);10541055 const row = slice(1056 markupOf(1057 <LogView1058 commits={held}1059 from={0}1060 now={now}1061 project={datekit}1062 rev="main"1063 />1064 ),1065 "data-commit",1066 LANDED1067 );10681069 expect(row).toContain("held back");1070 expect(row).toContain("text-sealed");1071 expect(row).toContain("lucide-lock-keyhole");1072 });10731074 it("links the ask an opening's landing opened, and reads it as an opening", () => {1075 const [opening] = decodeCommits([1076 {1077 author: signature("Okonkwo", "2026-10-06T15:00:00.000Z"),1078 body: "",1079 committer: signature("platform", "2026-10-06T15:00:00.000Z"),1080 landing: {1081 assisted: [],1082 author: "okonkwo",1083 credits: [{ handle: "okonkwo", role: "Decided-by" }],1084 landedAt: "2026-10-06T15:00:00.000Z",1085 opened: "parse-iso-week",1086 parent: IMPORTED,1087 project: "datekit",1088 sha: LANDED,1089 },1090 parents: [IMPORTED],1091 sha: LANDED,1092 subject: "Open ask parse-iso-week",1093 trailers: [{ key: "Decided-by", value: "okonkwo" }],1094 tree: "4".repeat(40),1095 },1096 ]);10971098 const row = slice(1099 markupOf(1100 <LogView1101 commits={opening === undefined ? [] : [opening]}1102 from={0}1103 now={now}1104 project={datekit}1105 rev="main"1106 />1107 ),1108 "data-commit",1109 LANDED1110 );11111112 expect(hrefsOf(row)).toContain("/oscabriel/datekit/asks/parse-iso-week");1113 expect(row).toContain("Opened");1114 });11151116 it("filters the page to the answers or the asks' openings", () => {1117 const answers = markupOf(1118 <LogView1119 commits={commits}1120 from={0}1121 now={now}1122 project={datekit}1123 rev="main"1124 show="answers"1125 />1126 );11271128 expect(answers).toContain(`data-commit="${LANDED}"`);1129 expect(answers).not.toContain(`data-commit="${IMPORTED}"`);11301131 const filters = navOf(markupOf(page), 'aria-label="Show"');11321133 expect(hrefsOf(filters)).toStrictEqual([1134 "/oscabriel/datekit/commits/main",1135 "/oscabriel/datekit/commits/main?show=answers",1136 "/oscabriel/datekit/commits/main?show=openings",1137 "/oscabriel/datekit/commits/main?show=all",1138 ]);1139 expect(filters).toMatch(/aria-current="page"[^>]*>Every commit</u);1140 expect(1141 [...filters.matchAll(/<a\b[^>]*>(?<label>[^<]*)</gu)].map(1142 ({ groups }) => groups?.label1143 )1144 ).toStrictEqual(["Landings", "Answers", "Ask openings", "Every commit"]);1145 });11461147 it("is titled History of main, of a fork, or at a tag", () => {1148 expect(1149 ["main", "@bram/parse-iso", TAG].map((rev) => titleOf(undefined, rev))1150 ).toStrictEqual([1151 "History of main",1152 "History of bram/parse-iso",1153 `History at ${TAG}`,1154 ]);1155 expect(titleOf(RepoPath.make("src/index.ts"), "main")).toBe(1156 "History of src/index.ts"1157 );1158 expect(markupOf(landings)).toMatch(/<h1\b[^>]*>History of main<\/h1>/u);1159 });11601161 it("shows main's landings alone by default, and counts them as landings", () => {1162 const markup = markupOf(landings);11631164 expect(markup).toContain(`data-commit="${LANDED}"`);1165 expect(markup).not.toContain(`data-commit="${IMPORTED}"`);1166 expect(navOf(markup, 'aria-label="Show"')).toMatch(1167 /aria-current="page"[^>]*>Landings</u1168 );1169 expect(plainText(markup)).toContain("1 landing");1170 expect(plainText(markup)).not.toContain("commits");1171 });11721173 it("pages the landings no further than the adoption, and a full page of them on", () => {1174 // The page holds a commit no landing records, so no older page holds one.1175 expect(markupOf(landings)).not.toContain('data-slot="pagination"');1176 // A full page of landings pages on, keeping the default out of the address.1177 const [landed] = commits;11781179 expect(1180 hrefsOf(1181 markupOf(1182 <LogView1183 commits={landed === undefined ? [] : [landed]}1184 from={0}1185 next={30}1186 now={now}1187 project={datekit}1188 rev="main"1189 />1190 )1191 )1192 ).toContain("/oscabriel/datekit/commits/main?from=30");1193 });11941195 it("marks the adoption once, over the first commit no landing records, in place of a word on every row", () => {1196 const markup = markupOf(page);11971198 expect(markup.match(/data-adopted="/gu)).toHaveLength(1);1199 expect(markup.indexOf(`data-adopted="${IMPORTED}"`)).toBeGreaterThan(1200 markup.indexOf(`data-commit="${LANDED}"`)1201 );1202 expect(markup.indexOf(`data-adopted="${IMPORTED}"`)).toBeLessThan(1203 markup.indexOf(`data-commit="${IMPORTED}"`)1204 );1205 expect(plainText(markup)).toContain(1206 "Adopted here. The commits below came with the import; no landing records them."1207 );1208 });12091210 it("says nothing on an imported commit's own row, which still opens the commit, and counts a mixed day as commits", () => {1211 const markup = markupOf(page);12121213 expect(plainText(markup)).not.toContain("before adoption");1214 expect(plainText(markup)).toContain("2 commits");1215 expect(hrefsOf(slice(markup, "data-commit", IMPORTED))).toContain(1216 `/oscabriel/datekit/commit/${IMPORTED}`1217 );1218 });12191220 it("marks no fork's own commit as the adoption: the first break after a landing is", () => {1221 const [own] = decodeCommits([1222 {1223 author: signature("Bob", "2026-10-07T09:00:00.000Z"),1224 body: "",1225 committer: signature("Bob", "2026-10-07T09:00:00.000Z"),1226 parents: [LANDED],1227 sha: "9".repeat(40),1228 subject: "Parse ISO weeks",1229 trailers: [],1230 tree: "a".repeat(40),1231 },1232 ]);12331234 const markup = markupOf(1235 <LogView1236 commits={own === undefined ? commits : [own, ...commits]}1237 from={0}1238 now={now}1239 project={datekit}1240 rev="@bob/parse-iso"1241 />1242 );12431244 expect(1245 [...markup.matchAll(/data-adopted="(?<sha>[^"]*)"/gu)].map(1246 ({ groups }) => groups?.sha1247 )1248 ).toStrictEqual([IMPORTED]);1249 expect(markup).toMatch(/<h1\b[^>]*>History of bob\/parse-iso<\/h1>/u);1250 expect(navOf(markup, 'aria-label="Show"')).toMatch(1251 /aria-current="page"[^>]*>Every commit</u1252 );1253 });12541255 it("links the older page from where this one ends, and no newer page from the first", () => {1256 const pager = navOf(markupOf(page), 'data-slot="pagination"');12571258 expect(hrefsOf(pager)).toStrictEqual([1259 "/oscabriel/datekit/commits/main?from=30&show=all",1260 ]);1261 });12621263 it("keeps the path on both pages of a path's history", () => {1264 const pager = navOf(1265 markupOf(1266 <LogView1267 commits={commits}1268 from={30}1269 next={60}1270 now={now}1271 path={RepoPath.make("src/parse.ts")}1272 project={datekit}1273 rev="main"1274 />1275 ),1276 'data-slot="pagination"'1277 );12781279 expect(hrefsOf(pager)).toStrictEqual([1280 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts",1281 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts&from=60",1282 ]);1283 });12841285 it("keeps the filter on both pages: Older and Newer show the same kind", () => {1286 const pager = navOf(1287 markupOf(1288 <LogView1289 commits={commits}1290 from={30}1291 next={60}1292 now={now}1293 project={datekit}1294 rev="main"1295 show="answers"1296 />1297 ),1298 'data-slot="pagination"'1299 );13001301 expect(hrefsOf(pager)).toStrictEqual([1302 "/oscabriel/datekit/commits/main?show=answers",1303 "/oscabriel/datekit/commits/main?from=60&show=answers",1304 ]);1305 });13061307 it("goes back to a path's newest commits from a later page, since a path's `from` counts commits scanned, not shown", () => {1308 // The platform scans 200 commits a call for a path, so the page that1309 // starts at 230 may follow one that started at 30 or at 0: only the1310 // first page is known to be newer.1311 const pager = navOf(1312 markupOf(1313 <LogView1314 commits={commits}1315 from={230}1316 next={430}1317 now={now}1318 path={RepoPath.make("src/parse.ts")}1319 project={datekit}1320 rev="main"1321 />1322 ),1323 'data-slot="pagination"'1324 );13251326 expect(hrefsOf(pager)).toStrictEqual([1327 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts",1328 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts&from=430",1329 ]);1330 });1331});13321333const linesUpTo = (count: number) =>1334 `${Array.from({ length: count }, (_, index) => `line ${index + 1}`).join(1335 "\n"1336 )}\n`;13371338const long = decodeDiff({1339 ...Schema.encodeSync(CommitDiff)(diff),1340 files: [1341 ...Schema.encodeSync(CommitDiff)(diff).files,1342 {1343 after: "d".repeat(40),1344 binary: false,1345 newText: linesUpTo(120),1346 path: "data/zones.ts",1347 status: "added",1348 },1349 ],1350});13511352describe(CommitView, () => {1353 const page = <CommitView diff={diff} now={now} project={datekit} />;13541355 it("names the people in its credit, each linking their page, and shows its trailers once", () => {1356 const markup = markupOf(page);1357 const hrefs = hrefsOf(markup);13581359 expect(hrefs).toStrictEqual(1360 expect.arrayContaining(["/people/ines-v", "/people/bram"])1361 );1362 expect(1363 ["Asked-by:", "Signed-off-by:", "data-body"].map((part) =>1364 countIn(markup, part)1365 )1366 ).toStrictEqual([1, 1, 1]);1367 expect(1368 /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markup)?.[0]1369 ).not.toContain("Asked-by");1370 });13711372 it("sets its body as prose in the sans, never in mono", () => {1373 const body =1374 /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markupOf(page))?.[0] ?? "";13751376 expect(body).toContain("Parse ISO week dates.");1377 expect(body).not.toContain("font-mono");1378 expect(body).toContain("text-body");1379 });13801381 it("links no one from an imported commit's trailers", () => {1382 const { landing: _landing, ...imported } = landedCommit;13831384 const markup = markupOf(1385 <CommitView1386 diff={decodeDiff({ commit: imported, files: [], truncated: false })}1387 now={now}1388 project={datekit}1389 />1390 );13911392 expect(hrefsOf(markup)).not.toContain("/people/bram");1393 expect(markup).toContain("bram@users.example.com");1394 expect(markup).toContain("Before adoption");1395 });13961397 it("leads with the landing's status line: landed as its id, and the ask it answered", () => {1398 const markup = markupOf(page);1399 const text = mainOf(markup).replaceAll(/<[^>]+>/gu, "");14001401 expect(text).toContain(`Landed as ${LANDED.slice(0, 7)}`);1402 expect(text).toContain("answered parse-iso-week");1403 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/asks/parse-iso-week");1404 expect(hrefsOf(markup)).toContain(1405 "/oscabriel/datekit/answers/parse-iso-week"1406 );1407 expect(markup).toContain('data-outcome="Landed"');1408 });14091410 it("links the ask an opening opened, and no answer, since it answers none", () => {1411 const markup = markupOf(1412 <CommitView1413 diff={decodeDiff({1414 commit: {1415 ...landedCommit,1416 landing: {1417 assisted: [],1418 author: "okonkwo",1419 credits: [{ handle: "okonkwo", role: "Decided-by" }],1420 landedAt: "2026-10-06T15:00:00.000Z",1421 opened: "parse-iso-week",1422 parent: IMPORTED,1423 project: "datekit",1424 sha: LANDED,1425 },1426 subject: "Open ask parse-iso-week",1427 },1428 files: [],1429 truncated: false,1430 })}1431 now={now}1432 project={datekit}1433 />1434 );14351436 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/asks/parse-iso-week");1437 expect(hrefsOf(markup)).not.toContain(1438 "/oscabriel/datekit/answers/parse-iso-week"1439 );1440 expect(markup).toContain("opened");1441 });14421443 it("puts git's own facts on one line: author, committer and parent, linked", () => {1444 const text = textOf(page);14451446 expect(hrefsOf(markupOf(page))).toContain(1447 `/oscabriel/datekit/commit/${IMPORTED}`1448 );1449 expect(text).toContain("authored by Bram");1450 expect(text).toContain("committed by the platform");1451 expect(text).toContain(`parent ${IMPORTED.slice(0, 7)}`);1452 });14531454 it("ends its head's meta line with the files and lines it changed, linking the diff", () => {1455 const markup = markupOf(page);14561457 const meta =1458 /<div class="text-ui text-muted-foreground">[\s\S]*?<\/div>/u.exec(1459 markup1460 )?.[0] ?? "";14611462 expect(1463 meta1464 .replaceAll(/<[^>]+>/gu, " ")1465 .replaceAll(/\s+/gu, " ")1466 .trim()1467 ).toMatch(/Browse files · \d+ files? · \+\d+ added −\d+ removed$/u);1468 expect(meta).toMatch(/<a\b[^>]*href="#diff"/u);1469 expect(meta).toContain("text-diff-add-sign");1470 expect(markup).toMatch(/<div\b[^>]*id="diff"/u);1471 });14721473 it("sends each changed file's diff as plain text, at the drawing's measures", () => {1474 const markup = markupOf(page);14751476 const plain =1477 /<div\b[^>]*data-diff="plain"[\s\S]*$/u.exec(markup)?.[0] ?? "";14781479 expect(1480 ["leading-code", "min-w-[calc(6ch+2px)]", "pl-[2ch]"].filter(1481 (measure) => !plain.includes(measure)1482 )1483 ).toStrictEqual([]);1484 expect(1485 ["src/week.ts", "src/parse.ts", "src/legacy.ts"].filter(1486 (path) =>1487 !slice(plain, "data-file", path).includes('data-diffs-header=""')1488 )1489 ).toStrictEqual([]);1490 expect(1491 [1492 ["src/parse.ts", "export const parse = fromIso;"],1493 ["src/parse.ts", "export const parse = Date;"],1494 ["src/week.ts", "export const week = 1;"],1495 ].filter(1496 ([path = "", line = ""]) =>1497 !slice(plain, "data-file", path).includes(line)1498 )1499 ).toStrictEqual([]);1500 expect(markup).not.toMatch(/<(?:diffs|file-tree)-container/u);1501 });15021503 it("keeps each file's header at the top of the pane while its lines scroll", () => {1504 const header =1505 /<summary\b[^>]*data-diffs-header=""[^>]*>/u.exec(markupOf(page))?.[0] ??1506 "";15071508 expect(header).toContain("sticky");1509 expect(header).toContain("top-0");1510 expect(header).toContain("h-11");1511 });15121513 it("starts an added or deleted file past 80 lines folded", () => {1514 const markup = markupOf(1515 <CommitView diff={long} now={now} project={datekit} />1516 );15171518 expect(slice(markup, "data-file", "data/zones.ts")).toContain(1519 'data-folded="true"'1520 );1521 expect(slice(markup, "data-file", "data/zones.ts")).not.toMatch(1522 /<details\b[^>]*\bopen=/u1523 );1524 expect(slice(markup, "data-file", "src/parse.ts")).toContain(1525 'data-folded="false"'1526 );1527 });15281529 it("counts the diff in the inspector: files, additions and deletions, split by path", () => {1530 const facts = factsOf(1531 markupOf(1532 <CommitView1533 diff={long}1534 now={now}1535 project={datekit}1536 territory={["src/**"]}1537 />1538 )1539 );15401541 const stats =1542 /<section\b[^>]*aria-label="Diff stats"[\s\S]*?<\/section>/u.exec(1543 facts1544 )?.[0] ?? "";15451546 const text = stats.replaceAll(/<[^>]+>/gu, " ").replaceAll(/\s+/gu, " ");15471548 expect(text).toContain("4 files");1549 expect(text).toContain("+122 added");1550 expect(text).toContain("−2 removed");1551 expect(slice(stats, "data-part", "territory")).toContain("+2");1552 expect(slice(stats, "data-part", "other")).toContain("+120");1553 });15541555 it("says when the commit is too large to show whole", () => {1556 const truncated = decodeDiff({1557 commit: landedCommit,1558 files: [{ binary: false, path: "data/zones.json", status: "modified" }],1559 truncated: true,1560 });15611562 expect(1563 textOf(<CommitView diff={truncated} now={now} project={datekit} />)1564 ).toContain("too large to show whole");1565 expect(textOf(page)).not.toContain("too large to show whole");1566 });1567});15681569type Sent = Rpc.Payload<Contract>;15701571const knownProject = (name: ProjectName) =>1572 name === datekit1573 ? Effect.void1574 : Effect.fail(new UnknownProject({ project: name }));15751576const knownRevision = (at: string | undefined) =>1577 at === undefined || at === "main" || at === AT1578 ? Effect.void1579 : Effect.fail(new UnknownRevision({ rev: at }));15801581const landedOnly = Schema.decodeSync(Refs)({1582 forks: [],1583 landed: LANDED,1584 project: "datekit",1585 tags: [],1586});15871588const noPath = (path: RepoPath) =>1589 new UnknownPath({ commit: CommitSha.make(AT), path });15901591const platformOf = (calls: Ref.Ref<readonly Sent[]>) => {1592 const sent = (payload: Sent) => Ref.update(calls, (all) => [...all, payload]);15931594 return Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(1595 Layer.provide([1596 Layer.mergeAll(1597 unanswered,1598 Contracts.toLayerHandler("readTree", (payload) =>1599 Effect.gen(function* () {1600 yield* sent(payload);1601 yield* knownProject(payload.project);1602 yield* knownRevision(payload.at);16031604 if (payload.path === undefined) {1605 return root;1606 }16071608 if (payload.path === nested.path) {1609 return nested;1610 }16111612 return yield* noPath(payload.path);1613 })1614 ),1615 Contracts.toLayerHandler("readFile", (payload) =>1616 Effect.gen(function* () {1617 yield* sent(payload);1618 yield* knownProject(payload.project);1619 yield* knownRevision(payload.at);16201621 if (payload.path === readme.path) {1622 return readme;1623 }16241625 return yield* noPath(payload.path);1626 })1627 ),1628 Contracts.toLayerHandler("log", (payload) =>1629 Effect.gen(function* () {1630 yield* sent(payload);1631 yield* knownProject(payload.project);1632 yield* knownRevision(payload.at);16331634 return { commits, next: (payload.from ?? 0) + LOG_PAGE };1635 })1636 ),1637 Contracts.toLayerHandler("showCommit", (payload) =>1638 Effect.gen(function* () {1639 yield* sent(payload);1640 yield* knownProject(payload.project);16411642 if (payload.at !== undefined) {1643 return payload.at === "@bob/parse-iso"1644 ? { ...diff, commit: Struct.omit(diff.commit, ["landing"]) }1645 : yield* new UnknownRevision({ rev: payload.at });1646 }16471648 if (payload.sha !== LANDED) {1649 return yield* new UnknownCommit({ sha: payload.sha });1650 }16511652 return diff;1653 })1654 ),1655 Contracts.toLayerHandler("listRefs", (payload) =>1656 Effect.gen(function* () {1657 yield* sent(payload);1658 yield* knownProject(payload.project);16591660 return landedOnly;1661 })1662 )1663 ),1664 asTester,1665 ])1666 );1667};16681669interface Refused {1670 readonly calls: readonly Sent[];1671 readonly refused: Option.Option<readonly string[]>;1672}16731674const refusedBy = <A, E>(1675 read: Effect.Effect<A, E, Client>1676): Effect.Effect<Refused> =>1677 Effect.gen(function* () {1678 const calls = yield* Ref.make<readonly Sent[]>([]);16791680 const failed = yield* Effect.flip(1681 read.pipe(Effect.provide(platformOf(calls)))1682 );16831684 expect(isNotFound(failed)).toBeTruthy();16851686 const data: unknown = isNotFound(failed) ? failed.data : undefined;16871688 const carried = Option.orElse(1689 Schema.decodeUnknownOption(Refusals)(data),1690 () =>1691 Option.map(1692 Schema.decodeUnknownOption(SoftLanding)(data),1693 ({ refusals }) => refusals1694 )1695 );16961697 return {1698 calls: yield* Ref.get(calls),1699 refused: Option.map(carried, explain),1700 };1701 }).pipe(Effect.orDie);17021703describe("the code pages' reads", () => {1704 it.effect(1705 "read a folder, its README and the revision's head for the folder's page, and no entry's last change",1706 () =>1707 Effect.gen(function* () {1708 const calls = yield* Ref.make<readonly Sent[]>([]);17091710 const read = yield* readTreePage({1711 project: "datekit",1712 rev: "main",1713 }).pipe(Effect.provide(platformOf(calls)));17141715 expect(read.listing.entries.map((entry) => entry.path)).toStrictEqual([1716 "src",1717 "README.md",1718 ]);1719 expect(read.readme?.text).toBe(readme.text);1720 expect(read.head?.sha).toBe(LANDED);1721 // The entries' last changes are the browser's to read, after the page is up.1722 expect(1723 (yield* Ref.get(calls)).filter((call) => "limit" in call)1724 ).toStrictEqual([1725 { at: "main", limit: 1, project: "oscabriel/datekit" },1726 ]);1727 })1728 );17291730 it.effect(1731 "pass a tag's name to the platform decoded, and carry back its refusal",1732 () =>1733 Effect.gen(function* () {1734 const { calls, refused } = yield* refusedBy(1735 readTreePage({1736 _splat: "src/format/locale",1737 project: "oscabriel/datekit",1738 rev: TAG_SEGMENT,1739 })1740 );17411742 expect(calls).toStrictEqual([1743 { at: TAG, path: "src/format/locale", project: "oscabriel/datekit" },1744 ]);1745 expect(refused).toStrictEqual(1746 Option.some(explain([new UnknownRevision({ rev: TAG })]))1747 );1748 })1749 );17501751 it.effect(1752 "are a not-found carrying the platform's refusal for a project, folder, file, revision or commit it lacks",1753 () =>1754 Effect.gen(function* () {1755 const cases: readonly (readonly [Effect.Effect<Refused>, Refusal])[] = [1756 [1757 refusedBy(readRefsPage("oscabriel/no-such-project")),1758 new UnknownProject({1759 project: ProjectName.make("oscabriel/no-such-project"),1760 }),1761 ],1762 [1763 refusedBy(1764 readTreePage({1765 _splat: "nope",1766 project: "oscabriel/datekit",1767 rev: "main",1768 })1769 ),1770 noPath(RepoPath.make("nope")),1771 ],1772 [1773 refusedBy(1774 readBlobPage({1775 _splat: "nope.ts",1776 project: "oscabriel/datekit",1777 rev: "main",1778 })1779 ),1780 noPath(RepoPath.make("nope.ts")),1781 ],1782 [1783 refusedBy(readLogPage({ project: "oscabriel/datekit", rev: "v9" })),1784 new UnknownRevision({ rev: "v9" }),1785 ],1786 [1787 refusedBy(1788 readCommitPage({ project: "oscabriel/datekit", sha: OLDER })1789 ),1790 new UnknownCommit({ sha: CommitSha.make(OLDER) }),1791 ],1792 ];17931794 for (const [read, refusal] of cases) {1795 const { refused } = yield* read;17961797 expect(refused).toStrictEqual(Option.some(explain([refusal])));1798 }1799 })1800 );18011802 it.effect(1803 "are a not-found with no refusal, and ask nothing, for an address that can name nothing",1804 () =>1805 Effect.gen(function* () {1806 const reads: readonly Effect.Effect<Refused>[] = [1807 refusedBy(readRefsPage("Not_A-Project")),1808 refusedBy(1809 readTreePage({ project: "oscabriel/datekit", rev: "%E0%A4%A" })1810 ),1811 refusedBy(1812 readBlobPage({ project: "oscabriel/datekit", rev: "main" })1813 ),1814 refusedBy(readLogPage({ project: "oscabriel/datekit", rev: "%" })),1815 refusedBy(1816 readCommitPage({ project: "oscabriel/datekit", sha: "abc1234" })1817 ),1818 ];18191820 for (const read of reads) {1821 expect(yield* read).toStrictEqual({1822 calls: [],1823 refused: Option.none(),1824 });1825 }1826 })1827 );18281829 it.effect("read the log page at `from`, a path's history only", () =>1830 Effect.gen(function* () {1831 const calls = yield* Ref.make<readonly Sent[]>([]);18321833 const read = yield* readLogPage({1834 from: 30,1835 path: "src/parse.ts",1836 project: "oscabriel/datekit",1837 rev: "main",1838 }).pipe(Effect.provide(platformOf(calls)));18391840 // The page, and the revision's head for the code bar beside it.1841 expect(1842 (yield* Ref.get(calls)).toSorted((one, other) =>1843 JSON.stringify(one).localeCompare(JSON.stringify(other))1844 )1845 ).toStrictEqual([1846 {1847 at: "main",1848 from: 30,1849 limit: LOG_PAGE,1850 path: "src/parse.ts",1851 project: "oscabriel/datekit",1852 },1853 { at: "main", limit: 1, project: "oscabriel/datekit" },1854 ]);1855 expect([read.from, read.next, read.path]).toStrictEqual([1856 30,1857 60,1858 "src/parse.ts",1859 ]);1860 })1861 );1862});18631864const landingOf = <A, E>(read: Effect.Effect<A, E, Client>) =>1865 Effect.gen(function* () {1866 const calls = yield* Ref.make<readonly Sent[]>([]);18671868 const failed = yield* Effect.flip(1869 read.pipe(Effect.provide(platformOf(calls)))1870 );18711872 return Schema.decodeUnknownOption(SoftLanding)(1873 isNotFound(failed) ? failed.data : undefined1874 );1875 }).pipe(Effect.orDie);18761877describe("a missing path", () => {1878 it.effect(1879 "lands on the nearest folder that exists at the commit, with the refusal as its notice",1880 () =>1881 Effect.gen(function* () {1882 const landing = yield* landingOf(1883 readBlobPage({1884 _splat: "src/format/locale/gone/x.ts",1885 project: "datekit",1886 rev: "main",1887 })1888 );18891890 expect(1891 Option.map(landing, ({ nearest }) => nearest.path)1892 ).toStrictEqual(Option.some("src/format/locale"));1893 expect(1894 Option.map(landing, ({ refusals }) => explain(refusals))1895 ).toStrictEqual(1896 Option.some(1897 explain([noPath(RepoPath.make("src/format/locale/gone/x.ts"))])1898 )1899 );19001901 const atRoot = yield* landingOf(1902 readTreePage({ _splat: "nope", project: "datekit", rev: "main" })1903 );19041905 expect(1906 Option.map(atRoot, ({ nearest }) => nearest.path === undefined)1907 ).toStrictEqual(Option.some(true));1908 })1909 );19101911 it("renders the nearest folder with UnknownPath's own words above it", () => {1912 const refusal = noPath(RepoPath.make("src/format/locale/gone/x.ts"));19131914 const markup = markupOf(1915 <CodeNotFound1916 data={Schema.encodeSync(SoftLanding)({1917 nearest: nested,1918 now,1919 project: datekit,1920 refusals: [refusal],1921 rev: "main",1922 })}1923 />1924 );19251926 const text = textOf(1927 <CodeNotFound1928 data={Schema.encodeSync(SoftLanding)({1929 nearest: nested,1930 now,1931 project: datekit,1932 refusals: [refusal],1933 rev: "main",1934 })}1935 />1936 );19371938 for (const line of explain([refusal])) {1939 expect(text).toContain(line.trim());1940 }19411942 expect(markup).toContain('data-refusal="UnknownPath"');1943 expect(markup).toContain('data-entry="src/format/locale/en.ts"');1944 expect(markup.indexOf('data-refusal="UnknownPath"')).toBeLessThan(1945 markup.indexOf('data-entry="src/format/locale/en.ts"')1946 );1947 });19481949 it.effect(1950 "keeps the code bar's Tree button over the folder it lands on, so a phone still reaches the tree",1951 () =>1952 Effect.gen(function* () {1953 const data = yield* Schema.encodeEffect(SoftLanding)({1954 nearest: nested,1955 now,1956 project: datekit,1957 refusals: [noPath(RepoPath.make("src/format/locale/gone/x.ts"))],1958 rev: "main",1959 });19601961 const pages = yield* Effect.forEach(1962 ["tree", "blob", "why"] as const,1963 (page) =>1964 inCodeTab(1965 `/oscabriel/datekit/${page}/main/src/format/locale/gone/x.ts`,1966 <CodeNotFound data={data} />1967 )1968 );19691970 expect(1971 pages.map((markup) =>1972 /aria-haspopup="dialog"[^>]*>[\s\S]*?Tree<\/button>/u.test(1973 codeBarOf(markup)1974 )1975 )1976 ).toStrictEqual([true, true, true]);1977 })1978 );19791980 it("keeps any other refusal verbatim, with a way onward", () => {1981 const refusal = new UnknownRevision({ rev: "v9" });19821983 const element = (1984 <CodeNotFound data={Schema.encodeSync(Refusals)([refusal])} />1985 );19861987 expect(markupOf(element)).toContain('data-refusal="UnknownRevision"');1988 expect(hrefsOf(markupOf(element))).toContain("/asks");1989 });1990});19911992const HEADERS_LINE = "headers: () => branchPage";19931994describe("a code page's caching", () => {1995 // A commit's page carries its landing, recorded after main has moved, and times reckoned from the read,1996 // so it is never kept for good.1997 const routes: Readonly<Record<string, string>> = import.meta.glob(1998 "../src/routes/$owner/$project/{tree,blob,why}/$rev/$.tsx",1999 { eager: true, import: "default", query: "?raw" }2000 );The first 2,000 of 2,172 lines.