code.test.tsx
This file
Path
apps/web/test/code.test.tsx
2,044 lines · 60.0 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
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 } 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 { elementWith, elementsWith } from "./records.ts";60import { renderAt } from "./render.tsx";61import { reachingTransport } from "./transport.ts";6263const markupOf = (element: ReactElement) => renderToStaticMarkup(element);6465const textOf = (element: ReactElement) =>66 markupOf(element)67 .replaceAll(/<[^>]+>/gu, " ")68 .replaceAll("'", "'")69 .replaceAll(""", '"')70 .replaceAll("<", "<")71 .replaceAll(">", ">")72 .replaceAll("&", "&")73 .replaceAll(/\s+/gu, " ");7475const hrefsOf = (markup: string) =>76 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map((match) =>77 (match.groups?.href ?? "").replaceAll("&", "&")78 );7980const slice = (markup: string, marker: string, value: string) => {81 const start = markup.indexOf(`${marker}="${value}"`);82 const next = markup.indexOf(`${marker}="`, start + 1);8384 return start === -185 ? ""86 : markup.slice(start, next === -1 ? undefined : next);87};8889const navOf = (markup: string, attribute: string) =>90 new RegExp(`<nav\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</nav>`, "u").exec(91 markup92 )?.[0] ?? "";9394const datekit = ProjectName.make("oscabriel/datekit");9596const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");9798const AT = "a".repeat(40);99100const decodeTree = Schema.decodeSync(TreeListing);101102const decodeFile = Schema.decodeSync(FileView);103104const root = decodeTree({105 at: AT,106 entries: [107 {108 mode: "040000",109 name: "src",110 path: "src",111 sha: "b".repeat(40),112 type: "tree",113 },114 {115 mode: "100644",116 name: "README.md",117 path: "README.md",118 sha: "c".repeat(40),119 type: "blob",120 },121 ],122 readme: { path: "README.md", sha: "c".repeat(40) },123});124125const readme = decodeFile({126 at: AT,127 binary: false,128 path: "README.md",129 sha: "c".repeat(40),130 size: 26,131 text: "# datekit\n\nDates, kept.\n",132 truncated: false,133});134135const nested = decodeTree({136 at: AT,137 entries: [138 {139 mode: "100644",140 name: "en.ts",141 path: "src/format/locale/en.ts",142 sha: "d".repeat(40),143 type: "blob",144 },145 ],146 path: "src/format/locale",147});148149const TAG = "@datekit/core@1.0.0";150151const TAG_SEGMENT = "%40datekit%2Fcore%401.0.0";152153const decodeCommits = Schema.decodeSync(Schema.Array(Commit));154155const signature = (name: string, at: string) => ({156 at,157 email: `${name}@example.com`,158 name,159});160161const LANDED = "1".repeat(40);162163const IMPORTED = "2".repeat(40);164165const OLDER = "3".repeat(40);166167const commits = decodeCommits([168 {169 author: signature("Bram", "2026-10-06T15:00:00.000Z"),170 body: "",171 committer: signature("platform", "2026-10-06T15:00:00.000Z"),172 landing: {173 ask: "parse-iso-week",174 assisted: [],175 author: "bram",176 credits: [177 { handle: "bram", role: "Signed-off-by" },178 { handle: "ines-v", role: "Asked-by" },179 ],180 landedAt: "2026-10-06T15:00:00.000Z",181 parent: IMPORTED,182 project: "datekit",183 sha: LANDED,184 },185 parents: [IMPORTED],186 sha: LANDED,187 subject: "Answer parse-iso-week",188 trailers: [189 { key: "Asked-by", value: "ines-v" },190 { key: "Signed-off-by", value: "bram" },191 ],192 tree: "4".repeat(40),193 },194 {195 author: signature("Lin", "2026-10-06T09:00:00.000Z"),196 body: "",197 committer: signature("Lin", "2026-10-06T09:00:00.000Z"),198 parents: [OLDER],199 sha: IMPORTED,200 subject: "Support week numbers",201 trailers: [],202 tree: "5".repeat(40),203 },204 {205 author: signature("Lin", "2026-10-04T09:00:00.000Z"),206 body: "",207 committer: signature("Lin", "2026-10-04T09:00:00.000Z"),208 parents: [],209 sha: OLDER,210 subject: "First commit",211 trailers: [],212 tree: "6".repeat(40),213 },214]);215216const decodeDiff = Schema.decodeSync(CommitDiff);217218const landedCommit: typeof Commit.Encoded = {219 author: signature("Bram", "2026-10-06T15:00:00.000Z"),220 body: "Parse ISO week dates.\n\nAsked-by: ines-v\nSigned-off-by: bram",221 committer: signature("platform", "2026-10-06T15:00:00.000Z"),222 landing: {223 ask: "parse-iso-week",224 assisted: [],225 author: "bram",226 credits: [227 { handle: "bram", role: "Signed-off-by" },228 { handle: "ines-v", role: "Asked-by" },229 ],230 landedAt: "2026-10-06T15:00:00.000Z",231 parent: IMPORTED,232 project: "datekit",233 sha: LANDED,234 verdict: {235 ask: "parse-iso-week",236 at: "2026-10-06T14:59:00.000Z",237 base: IMPORTED,238 checkVersion: "redThenGreen@0.0.0+abc",239 head: "7".repeat(40),240 heldBack: [],241 lanes: [242 {243 command: "bun test",244 durationMs: 1200,245 lane: "unit",246 result: "passed",247 },248 ],249 outcome: Schema.encodeSync(Outcome)(250 Outcome.cases.Landed.make({ sha: LandedSha.make(LANDED) })251 ),252 patchId: "8".repeat(64),253 project: "datekit",254 stage: "checks",255 tree: "4".repeat(40),256 verifier: "platform",257 },258 },259 parents: [IMPORTED],260 sha: LANDED,261 subject: "Answer parse-iso-week",262 trailers: [263 { key: "Asked-by", value: "ines-v <ines-v@users.example.com>" },264 { key: "Signed-off-by", value: "bram <bram@users.example.com>" },265 ],266 tree: "4".repeat(40),267};268269const diff = decodeDiff({270 commit: landedCommit,271 files: [272 {273 after: "9".repeat(40),274 binary: false,275 newText: "export const week = 1;\n",276 path: "src/week.ts",277 status: "added",278 },279 {280 after: "a".repeat(40),281 before: "b".repeat(40),282 binary: false,283 newText: "export const parse = fromIso;\n",284 oldText: "export const parse = Date;\n",285 path: "src/parse.ts",286 status: "modified",287 },288 {289 before: "c".repeat(40),290 binary: false,291 oldText: "export const legacy = true;\n",292 path: "src/legacy.ts",293 status: "deleted",294 },295 ],296 truncated: false,297});298299const factsOf = (markup: string) => elementWith(markup, 'data-facts="inline"');300301/** The main region without its facts, which sit inside it. */302const mainOf = (markup: string) => {303 const main = /<main\b[\s\S]*?<\/main>/u.exec(markup)?.[0] ?? "";304 const facts = factsOf(main);305306 return facts === "" ? main : main.replace(facts, "");307};308309const countIn = (text: string, part: string) => text.split(part).length - 1;310311const anchorOf = (markup: string, label: string) =>312 new RegExp(`<a\\b[^>]*>${label}</a>`, "u").exec(markup)?.[0];313314describe(TreeView, () => {315 const page = (316 <TreeView317 listing={root}318 now={now}319 project={datekit}320 readme={readme}321 rev="main"322 />323 );324325 it("lists folders before files, each linking its own page at the same revision", () => {326 const markup = markupOf(page);327328 expect(markup.indexOf('data-entry="src"')).toBeGreaterThan(-1);329 expect(markup.indexOf('data-entry="src"')).toBeLessThan(330 markup.indexOf('data-entry="README.md"')331 );332 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/tree/main/src");333 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/blob/main/README.md");334 });335336 it("lists the folder once", () => {337 const markup = markupOf(page);338339 expect(countIn(markup, 'data-entry="src"')).toBe(1);340 expect(countIn(markup, 'data-entry="README.md"')).toBe(1);341 expect(countIn(markup, "data-entries=")).toBe(1);342 });343344 it("says what last changed each entry, once it has been read", () => {345 const [last] = commits;346347 const markup = markupOf(348 <TreeView349 last={new Map(last === undefined ? [] : [["src", last]])}350 listing={root}351 now={now}352 project={datekit}353 rev="main"354 />355 );356357 expect(slice(markup, "data-entry", "src")).toContain("parse-iso-week");358 expect(slice(markup, "data-entry", "src")).toContain("ago");359 expect(slice(markup, "data-entry", "README.md")).not.toContain("ago");360 });361362 it("links each ancestor in its path at the same revision, and names the folder last", () => {363 const markup = markupOf(364 <TreeView listing={nested} now={now} project={datekit} rev={TAG} />365 );366367 const crumbs = hrefsOf(navOf(markup, 'aria-label="Path"'));368369 expect(crumbs).toStrictEqual([370 `/oscabriel/datekit/tree/${TAG_SEGMENT}`,371 `/oscabriel/datekit/tree/${TAG_SEGMENT}/src`,372 `/oscabriel/datekit/tree/${TAG_SEGMENT}/src/format`,373 ]);374 expect(375 textOf(376 <TreeView listing={nested} now={now} project={datekit} rev={TAG} />377 )378 ).toContain("locale");379 });380381 it("renders the folder's README below its entries", () => {382 const markup = markupOf(page);383384 expect(markup).toContain('data-readme="README.md"');385 expect(textOf(page)).toContain("Dates, kept.");386 expect(markup.indexOf("data-readme=")).toBeGreaterThan(387 markup.indexOf('data-entry="README.md"')388 );389 });390391 it("leaves the file tree to the browser", () => {392 expect(markupOf(page)).not.toContain("<file-tree-container");393 });394395 it.effect(396 "links the folder's history with its path as the search, current on that page",397 () =>398 Effect.gen(function* () {399 const markup = yield* renderAt(400 `/oscabriel/datekit/commits/${TAG_SEGMENT}?path=src%2Fformat%2Flocale`,401 <TreeView listing={nested} now={now} project={datekit} rev={TAG} />402 );403404 const history = anchorOf(markup, "History");405406 expect(history).toContain(407 `href="/oscabriel/datekit/commits/${TAG_SEGMENT}?path=src%2Fformat%2Flocale"`408 );409 expect(history).toContain('aria-current="page"');410 })411 );412});413414const permalink = (mode: "code" | "why") =>415 /href="(?<href>[^"]*)"[^>]*>Permalink</u.exec(416 markupOf(417 <FileFacts418 file={readme}419 mode={mode}420 now={now}421 project={datekit}422 rev="main"423 />424 )425 )?.groups?.href;426427describe("a file's facts", () => {428 it("link a permalink to the page they sit on: the code, or why", () => {429 expect(permalink("code")).toBe(`/oscabriel/datekit/blob/${AT}/README.md`);430 expect(permalink("why")).toBe(`/oscabriel/datekit/why/${AT}/README.md`);431 });432433 // The history's `?path=` is the address's search, not part of its path:434 // the router then reads `main` as the revision (a hover fetches the right435 // page) and marks the link on the history it leads to.436 it.effect(437 "link the file's history with its path as the search, current on that page",438 () =>439 Effect.gen(function* () {440 const markup = yield* renderAt(441 "/oscabriel/datekit/commits/main?path=README.md",442 <FileFacts file={readme} now={now} project={datekit} rev="main" />443 );444445 const history = anchorOf(markup, "History of this file");446447 expect(history).toContain(448 'href="/oscabriel/datekit/commits/main?path=README.md"'449 );450 expect(history).toContain('aria-current="page"');451 })452 );453});454455describe(BlobView, () => {456 const parse = decodeFile({457 at: AT,458 binary: false,459 path: "src/format/parse.ts",460 sha: "e".repeat(40),461 size: 14,462 text: "one\ntwo\nthree\n",463 truncated: false,464 });465466 const [lastLanding] = commits;467468 const page = (469 <BlobView470 file={parse}471 last={lastLanding}472 now={now}473 project={datekit}474 rev="main"475 />476 );477478 it("numbers each line of a text file with its own anchor, and draws no highlighting on the server", () => {479 const markup = markupOf(page);480481 const anchors = [...markup.matchAll(/id="(?<line>L\d+)"/gu)].map(482 (match) => match.groups?.line483 );484485 expect(markup).toContain("<pre");486 expect(anchors).toStrictEqual(["L1", "L2", "L3"]);487 expect(markup).not.toContain("<diffs-container");488 });489490 it("anchors each line on an element that draws a box, so `#L2` scrolls to it without script", () => {491 // A `display: contents` element draws no box, and a browser cannot492 // scroll to it.493 const anchored = /<(?<tag>\w+)\b(?<attributes>[^>]*)\bid="L2"[^>]*>/u.exec(494 markupOf(page)495 );496497 expect(anchored?.groups?.tag).toBe("span");498 expect(anchored?.groups?.attributes).not.toMatch(/\bcontents\b/u);499 });500501 it("sets the plain text at the drawing's measures: 20 px lines and Pierre's gutter", () => {502 const code = /<pre\b[^>]*>/u.exec(markupOf(page))?.[0] ?? "";503504 expect(code).toContain("leading-code");505 expect(code).toContain("text-mono");506 expect(markupOf(page)).toContain("min-w-[calc(6ch+2px)]");507 expect(markupOf(page)).toContain("pl-[2ch]");508 });509510 it("names the path once in the page, in its file header", () => {511 const main = mainOf(markupOf(page));512513 expect(514 countIn(main.replaceAll(/<[^>]+>/gu, ""), "src/format/parse.ts")515 ).toBe(1);516 expect(countIn(main, 'title="src/format/parse.ts"')).toBe(1);517 expect(countIn(main, 'aria-label="Path"')).toBe(1);518 expect(hrefsOf(navOf(main, 'aria-label="Path"'))).toStrictEqual([519 "/oscabriel/datekit/tree/main",520 "/oscabriel/datekit/tree/main/src",521 "/oscabriel/datekit/tree/main/src/format",522 ]);523 });524525 it("has the Code | Why toggle, Code current", () => {526 const toggle = navOf(markupOf(page), 'aria-label="Mode"');527528 expect(hrefsOf(toggle)).toStrictEqual([529 "/oscabriel/datekit/blob/main/src/format/parse.ts",530 "/oscabriel/datekit/why/main/src/format/parse.ts",531 ]);532 expect(toggle).toMatch(/aria-current="page"[^>]*>Code</u);533 expect(toggle).not.toMatch(/aria-current="page"[^>]*>Why</u);534 });535536 it("links raw at the commit and the permalink at the commit, and the history at the revision", () => {537 const markup = markupOf(page);538 const toolbar = navOf(markup, 'data-toolbar="file"');539540 expect(hrefsOf(toolbar)).toStrictEqual([541 `/oscabriel/datekit/raw/${AT}/src/format/parse.ts`,542 `/oscabriel/datekit/blob/${AT}/src/format/parse.ts`,543 ]);544 expect(hrefsOf(factsOf(markup))).toContain(545 "/oscabriel/datekit/commits/main?path=src%2Fformat%2Fparse.ts"546 );547 });548549 it("names the last landing's ask in This file, before its SHA", () => {550 const facts = factsOf(markupOf(page));551 const text = facts.replaceAll(/<[^>]+>/gu, "");552553 expect(facts).toContain("This file");554 expect(text.indexOf("parse-iso-week")).toBeGreaterThan(-1);555 expect(text.indexOf("parse-iso-week")).toBeLessThan(556 text.indexOf(LANDED.slice(0, 7))557 );558 expect(text).toContain("answered by bram");559 expect(hrefsOf(facts)).toStrictEqual(560 expect.arrayContaining([561 "/oscabriel/datekit/asks/parse-iso-week",562 "/oscabriel/datekit/answers/parse-iso-week",563 `/oscabriel/datekit/commit/${LANDED}`,564 ])565 );566 });567568 it("shows a binary file's size and a raw link, and no text", () => {569 const binary = decodeFile({570 at: AT,571 binary: true,572 path: "assets/fixture.bin",573 sha: "f".repeat(40),574 size: 2048,575 truncated: false,576 });577578 const element = (579 <BlobView file={binary} now={now} project={datekit} rev="main" />580 );581582 expect(markupOf(element)).not.toContain("<pre");583 expect(textOf(element)).toContain("2.0 KiB");584 expect(hrefsOf(markupOf(element))).toContain(585 `/oscabriel/datekit/raw/${AT}/assets/fixture.bin`586 );587 });588589 it("says a file past the cap is too large to show, with a raw link", () => {590 const large = decodeFile({591 at: AT,592 binary: false,593 path: "data/zones.json",594 sha: "f".repeat(40),595 size: 3_145_728,596 truncated: true,597 });598599 const element = (600 <BlobView file={large} now={now} project={datekit} rev="main" />601 );602603 expect(markupOf(element)).not.toContain("<pre");604 expect(textOf(element)).toContain("too large to show");605 expect(textOf(element)).toContain("3.0 MiB");606 expect(hrefsOf(markupOf(element))).toContain(607 `/oscabriel/datekit/raw/${AT}/data/zones.json`608 );609 });610611 it("shows an image inline from raw", () => {612 const logo = decodeFile({613 at: AT,614 binary: true,615 path: "docs/logo.png",616 sha: "f".repeat(40),617 size: 512,618 truncated: false,619 });620621 expect(622 markupOf(<BlobView file={logo} now={now} project={datekit} rev="main" />)623 ).toMatch(624 new RegExp(625 `<img\\b[^>]*src="/oscabriel/datekit/raw/${AT}/docs/logo.png"`,626 "u"627 )628 );629 });630631 it("renders a Markdown file, and its source on ?plain=1", () => {632 const guide = decodeFile({633 at: AT,634 binary: false,635 path: "docs/guide.md",636 sha: "f".repeat(40),637 size: 18,638 text: "# Guide\n\nRead me.\n",639 truncated: false,640 });641642 const rendered = markupOf(643 <BlobView file={guide} now={now} project={datekit} rev="main" />644 );645646 const plain = markupOf(647 <BlobView file={guide} now={now} plain project={datekit} rev="main" />648 );649650 expect(rendered).toContain('data-readme="docs/guide.md"');651 expect(rendered).not.toContain('id="L1"');652 expect(hrefsOf(rendered)).toContain(653 "/oscabriel/datekit/blob/main/docs/guide.md?plain=1"654 );655 expect(plain).toContain('id="L3"');656 expect(plain).not.toContain("data-readme=");657 });658});659660const platformUrl = "https://platform-test.example.workers.dev";661662/** 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. */663const inCodeTab = (url: string, page: ReactElement, head?: Commit) =>664 renderAt(665 url,666 <ProjectFrame667 header={668 <ProjectHeader669 current={projectTabOf(new URL(url, platformUrl).pathname)}670 header={{ now, project: datekit }}671 platformUrl={platformUrl}672 />673 }674 codeBar={<ProjectCodeBar platformUrl={platformUrl} />}675 >676 {page}677 </ProjectFrame>,678 {679 loaderData:680 head === undefined681 ? undefined682 : {683 head: Schema.encodeSync(Commit)(head),684 now: DateTime.formatIso(now),685 },686 }687 );688689const codeBarOf = (markup: string) => elementWith(markup, 'data-code-bar=""');690691const parseTs = decodeFile({692 at: AT,693 binary: false,694 path: "src/format/parse.ts",695 sha: "e".repeat(40),696 size: 14,697 text: "one\ntwo\nthree\n",698 truncated: false,699});700701const treeAndBlob = Effect.all([702 inCodeTab(703 "/oscabriel/datekit/tree/main/src/format/locale",704 <TreeView listing={nested} now={now} project={datekit} rev="main" />705 ),706 inCodeTab(707 "/oscabriel/datekit/blob/main/src/format/parse.ts",708 <BlobView file={parseTs} now={now} project={datekit} rev="main" />709 ),710]);711712/** Each link of a control, with whether it is marked as the page being read. */713const linksIn = (markup: string) =>714 [...markup.matchAll(/<a\b(?<attributes>[^>]*)>(?<text>[\s\S]*?)<\/a>/gu)].map(715 ({ groups }) => ({716 current: /aria-current="page"/u.test(groups?.attributes ?? ""),717 href: hrefsOf(groups?.attributes ?? "")[0],718 text: (groups?.text ?? "").replaceAll(/<[^>]+>/gu, "").trim(),719 })720 );721722describe("a code page in the Code tab", () => {723 it.effect(724 "keeps the project header, with Code its current tab, over the code bar",725 () =>726 Effect.gen(function* () {727 const pages = yield* treeAndBlob;728729 expect(730 pages.map(731 (markup) =>732 elementWith(markup, 'data-project-header=""') !== "" &&733 /aria-current="page"[^>]*>Code</u.test(734 elementWith(markup, 'data-project-tabs=""')735 )736 )737 ).toStrictEqual([true, true]);738 expect(739 pages.map(740 (markup) =>741 markup.indexOf('data-project-header=""') <742 markup.indexOf('data-code-bar=""')743 )744 ).toStrictEqual([true, true]);745 })746 );747748 it.effect(749 "has the Files/Commits toggle, Files current, and the ref switcher on main",750 () =>751 Effect.gen(function* () {752 const bars = (yield* treeAndBlob).map(codeBarOf);753754 expect(755 bars.map((bar) =>756 linksIn(navOf(bar, 'aria-label="Files or commits"'))757 )758 ).toStrictEqual(759 bars.map(() => [760 {761 current: true,762 href: "/oscabriel/datekit/tree/main",763 text: "Files",764 },765 {766 current: false,767 href: "/oscabriel/datekit/commits/main",768 text: "Commits",769 },770 ])771 );772 expect(773 bars.map((bar) => /<button\b[^>]*data-ref="main"[^>]*>/u.test(bar))774 ).toStrictEqual([true, true]);775 })776 );777778 it.effect(779 "draws no Menu control: the top bar's links stay where they are",780 () =>781 Effect.gen(function* () {782 const pages = yield* treeAndBlob;783784 expect(785 pages.flatMap((markup) => [786 ...elementsWith(markup, '(?:aria-label|title)="[^"]*Menu'),787 ...[...markup.matchAll(/>\s*Menu\s*</gu)].map(([found]) => found),788 ])789 ).toStrictEqual([]);790 })791 );792793 it.effect(794 "shows the revision's head commit in the bar: its short id and subject linking it, then its author",795 () =>796 Effect.gen(function* () {797 const [head] = commits;798799 const bar = codeBarOf(800 yield* inCodeTab(801 "/oscabriel/datekit/tree/main",802 <TreeView listing={root} now={now} project={datekit} rev="main" />,803 head804 )805 );806807 const shown = elementWith(bar, `data-head-commit="${LANDED}"`);808809 expect(810 linksIn(shown).map(({ href, text }) => [href, text])811 ).toStrictEqual([812 [`/oscabriel/datekit/commit/${LANDED}`, LANDED.slice(0, 7)],813 [`/oscabriel/datekit/commit/${LANDED}`, "Answer parse-iso-week"],814 ]);815 expect(shown).toContain("Bram");816 })817 );818819 it.effect(820 "marks Commits on the history and on a commit, at the same revision, and nothing on the refs list",821 () =>822 Effect.gen(function* () {823 const pages = yield* Effect.forEach(824 [825 `/oscabriel/datekit/commits/${TAG_SEGMENT}`,826 `/oscabriel/datekit/commit/${LANDED}`,827 "/oscabriel/datekit/refs",828 ],829 (url) => inCodeTab(url, <main id="main" />)830 );831832 const toggles = pages.map((markup) =>833 linksIn(navOf(codeBarOf(markup), 'aria-label="Files or commits"'))834 );835836 expect(837 toggles.map((links) =>838 links.flatMap(({ current, text }) => (current ? [text] : []))839 )840 ).toStrictEqual([["Commits"], ["Commits"], []]);841 expect(toggles[0]?.map(({ href }) => href)).toStrictEqual([842 `/oscabriel/datekit/tree/${TAG_SEGMENT}`,843 `/oscabriel/datekit/commits/${TAG_SEGMENT}`,844 ]);845 })846 );847848 it.effect("draws no code bar on a page of another tab", () =>849 Effect.gen(function* () {850 const pages = yield* Effect.forEach(851 ["/oscabriel/datekit", "/oscabriel/datekit/asks/parse-iso-week"],852 (url) => inCodeTab(url, <main id="main" />)853 );854855 expect(pages.map(codeBarOf)).toStrictEqual(["", ""]);856 })857 );858859 it.effect(860 "opens the file tree from the bar's Tree button below the columns, and offers Go to file and Clone",861 () =>862 Effect.gen(function* () {863 const [tree] = yield* treeAndBlob;864 const bar = codeBarOf(tree);865866 expect(bar).toMatch(867 /class="columns:hidden[^"]*"><button[^>]*aria-haspopup="dialog"[^>]*>[\s\S]*?Tree<\/button>/u868 );869 expect(bar).toMatch(/title="Go to file \(t\)"/u);870 expect(bar).toContain('data-action="clone-here"');871 })872 );873874 it.effect(875 "gives the blob page's file header a Why toggle to the why page for the same path and revision",876 () =>877 Effect.gen(function* () {878 const [, blob] = yield* treeAndBlob;879 const toggle = navOf(blob, 'aria-label="Mode"');880881 expect(linksIn(toggle).find(({ text }) => text === "Why")?.href).toBe(882 "/oscabriel/datekit/why/main/src/format/parse.ts"883 );884 expect(elementWith(blob, 'data-toolbar=""')).toContain(885 'aria-label="Mode"'886 );887 })888 );889});890891describe(codeAddressOf, () => {892 it.each([893 [894 "/oscabriel/datekit/tree/main",895 { page: "tree", path: undefined, rev: "main" },896 ],897 [898 `/oscabriel/datekit/blob/${TAG_SEGMENT}/src/a%20b.ts`,899 { page: "blob", path: "src/a b.ts", rev: TAG },900 ],901 [902 "/oscabriel/datekit/why/main/src/parse.ts",903 { page: "why", path: "src/parse.ts", rev: "main" },904 ],905 [906 `/oscabriel/datekit/commit/${LANDED}`,907 { page: "commit", path: undefined, rev: LANDED },908 ],909 ["/oscabriel/datekit/refs", { page: "refs", rev: "main" }],910 ])("reads %s", (pathname, address) => {911 expect(codeAddressOf(pathname)).toStrictEqual(Option.some(address));912 });913914 it("reads no address off the Code tab", () => {915 expect(916 [917 "/oscabriel/datekit",918 "/oscabriel/datekit/asks/parse-iso-week",919 "/oscabriel/datekit/tree",920 ].map((pathname) => Option.isNone(codeAddressOf(pathname)))921 ).toStrictEqual([true, true, true]);922 });923});924925describe(filesMatching, () => {926 const paths = [927 "src/format/locale/en.ts",928 "src/parse.ts",929 "test/parse.test.ts",930 "README.md",931 ];932933 it("keeps the paths holding every word, a match in the file's own name first", () => {934 expect(filesMatching(paths, "parse")).toStrictEqual([935 "src/parse.ts",936 "test/parse.test.ts",937 ]);938 expect(filesMatching(paths, "src ts")).toStrictEqual([939 "src/parse.ts",940 "src/format/locale/en.ts",941 ]);942 });943944 it("matches without regard to case, and stops at its limit", () => {945 expect(filesMatching(paths, "readme")).toStrictEqual(["README.md"]);946 expect(filesMatching(paths, "", 2)).toHaveLength(2);947 });948});949950describe(checkoutCommand, () => {951 it("checks out a tag or a commit as it is, and quotes anything else", () => {952 expect(checkoutCommand(TAG)).toBe(`git checkout ${TAG}`);953 expect(checkoutCommand(LANDED)).toBe(`git checkout ${LANDED}`);954 expect(checkoutCommand("v1;rm -rf ~")).toBe("git checkout 'v1;rm -rf ~'");955 expect(checkoutCommand("it's")).toBe(`git checkout 'it'\\''s'`);956 });957});958959describe(LogView, () => {960 const page = (961 <LogView962 commits={commits}963 from={0}964 next={30}965 now={now}966 project={datekit}967 rev="main"968 />969 );970971 it("groups the commits of one day under one sticky header", () => {972 const markup = markupOf(page);973974 const days = [...markup.matchAll(/data-day="(?<day>[^"]+)"/gu)].map(975 (match) => match.groups?.day976 );977978 expect(days).toStrictEqual(["2026-10-06", "2026-10-04"]);979980 const first = slice(markup, "data-day", "2026-10-06");981982 expect(983 [LANDED, IMPORTED, OLDER].map((sha) =>984 first.includes(`data-commit="${sha}"`)985 )986 ).toStrictEqual([true, true, false]);987 expect(first).toMatch(/class="[^"]*\bsticky\b/u);988 expect(textOf(page)).toContain("October 6, 2026");989 });990991 it("shows a landing's ask and credit in one line, and its short id over its age", () => {992 const row = slice(markupOf(page), "data-commit", LANDED);993994 expect(hrefsOf(row)).toStrictEqual(995 expect.arrayContaining([996 "/oscabriel/datekit/asks/parse-iso-week",997 `/oscabriel/datekit/commit/${LANDED}`,998 "/people/ines-v",999 ])1000 );1001 expect(row).toContain("Asked by");1002 expect(row.indexOf(LANDED.slice(0, 7))).toBeGreaterThan(-1);1003 expect(row.indexOf(LANDED.slice(0, 7))).toBeLessThan(row.indexOf(" ago"));1004 });10051006 it("marks a landing judged by sealed checks held back, with its lock", () => {1007 const held = decodeCommits([1008 {1009 author: signature("Bram", "2026-10-06T15:00:00.000Z"),1010 body: "",1011 committer: signature("platform", "2026-10-06T15:00:00.000Z"),1012 landing: {1013 ask: "parse-iso-week",1014 assisted: [],1015 author: "bram",1016 credits: [{ handle: "bram", role: "Signed-off-by" }],1017 heldBackTrailer: "parser: 4 sealed checks by 3 people",1018 landedAt: "2026-10-06T15:00:00.000Z",1019 parent: IMPORTED,1020 project: "datekit",1021 sha: LANDED,1022 },1023 parents: [IMPORTED],1024 sha: LANDED,1025 subject: "Answer parse-iso-week",1026 trailers: [],1027 tree: "4".repeat(40),1028 },1029 ]);10301031 const row = slice(1032 markupOf(1033 <LogView1034 commits={held}1035 from={0}1036 now={now}1037 project={datekit}1038 rev="main"1039 />1040 ),1041 "data-commit",1042 LANDED1043 );10441045 expect(row).toContain("held back");1046 expect(row).toContain("text-sealed");1047 expect(row).toContain("lucide-lock-keyhole");1048 });10491050 it("links the ask an opening's landing opened, and reads it as an opening", () => {1051 const [opening] = decodeCommits([1052 {1053 author: signature("Okonkwo", "2026-10-06T15:00:00.000Z"),1054 body: "",1055 committer: signature("platform", "2026-10-06T15:00:00.000Z"),1056 landing: {1057 assisted: [],1058 author: "okonkwo",1059 credits: [{ handle: "okonkwo", role: "Decided-by" }],1060 landedAt: "2026-10-06T15:00:00.000Z",1061 opened: "parse-iso-week",1062 parent: IMPORTED,1063 project: "datekit",1064 sha: LANDED,1065 },1066 parents: [IMPORTED],1067 sha: LANDED,1068 subject: "Open ask parse-iso-week",1069 trailers: [{ key: "Decided-by", value: "okonkwo" }],1070 tree: "4".repeat(40),1071 },1072 ]);10731074 const row = slice(1075 markupOf(1076 <LogView1077 commits={opening === undefined ? [] : [opening]}1078 from={0}1079 now={now}1080 project={datekit}1081 rev="main"1082 />1083 ),1084 "data-commit",1085 LANDED1086 );10871088 expect(hrefsOf(row)).toContain("/oscabriel/datekit/asks/parse-iso-week");1089 expect(row).toContain("Opened");1090 });10911092 it("filters the page to the answers or the asks' openings", () => {1093 const answers = markupOf(1094 <LogView1095 commits={commits}1096 from={0}1097 now={now}1098 project={datekit}1099 rev="main"1100 show="answers"1101 />1102 );11031104 expect(answers).toContain(`data-commit="${LANDED}"`);1105 expect(answers).not.toContain(`data-commit="${IMPORTED}"`);11061107 const filters = navOf(markupOf(page), 'aria-label="Show"');11081109 expect(hrefsOf(filters)).toStrictEqual([1110 "/oscabriel/datekit/commits/main",1111 "/oscabriel/datekit/commits/main?show=answers",1112 "/oscabriel/datekit/commits/main?show=openings",1113 ]);1114 expect(filters).toMatch(/aria-current="page"[^>]*>All</u);1115 });11161117 it("says an imported commit came before adoption", () => {1118 const row = slice(markupOf(page), "data-commit", IMPORTED);11191120 expect(row).toContain("before adoption");1121 expect(hrefsOf(row)).toContain(`/oscabriel/datekit/commit/${IMPORTED}`);1122 expect(slice(markupOf(page), "data-commit", LANDED)).not.toContain(1123 "before adoption"1124 );1125 });11261127 it("links the older page from where this one ends, and no newer page from the first", () => {1128 const pager = navOf(markupOf(page), 'data-slot="pagination"');11291130 expect(hrefsOf(pager)).toStrictEqual([1131 "/oscabriel/datekit/commits/main?from=30",1132 ]);1133 });11341135 it("keeps the path on both pages of a path's history", () => {1136 const pager = navOf(1137 markupOf(1138 <LogView1139 commits={commits}1140 from={30}1141 next={60}1142 now={now}1143 path={RepoPath.make("src/parse.ts")}1144 project={datekit}1145 rev="main"1146 />1147 ),1148 'data-slot="pagination"'1149 );11501151 expect(hrefsOf(pager)).toStrictEqual([1152 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts",1153 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts&from=60",1154 ]);1155 });11561157 it("keeps the filter on both pages: Older and Newer show the same kind", () => {1158 const pager = navOf(1159 markupOf(1160 <LogView1161 commits={commits}1162 from={30}1163 next={60}1164 now={now}1165 project={datekit}1166 rev="main"1167 show="answers"1168 />1169 ),1170 'data-slot="pagination"'1171 );11721173 expect(hrefsOf(pager)).toStrictEqual([1174 "/oscabriel/datekit/commits/main?show=answers",1175 "/oscabriel/datekit/commits/main?from=60&show=answers",1176 ]);1177 });11781179 it("goes back to a path's newest commits from a later page, since a path's `from` counts commits scanned, not shown", () => {1180 // The platform scans 200 commits a call for a path, so the page that1181 // starts at 230 may follow one that started at 30 or at 0: only the1182 // first page is known to be newer.1183 const pager = navOf(1184 markupOf(1185 <LogView1186 commits={commits}1187 from={230}1188 next={430}1189 now={now}1190 path={RepoPath.make("src/parse.ts")}1191 project={datekit}1192 rev="main"1193 />1194 ),1195 'data-slot="pagination"'1196 );11971198 expect(hrefsOf(pager)).toStrictEqual([1199 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts",1200 "/oscabriel/datekit/commits/main?path=src%2Fparse.ts&from=430",1201 ]);1202 });1203});12041205const linesUpTo = (count: number) =>1206 `${Array.from({ length: count }, (_, index) => `line ${index + 1}`).join(1207 "\n"1208 )}\n`;12091210const long = decodeDiff({1211 ...Schema.encodeSync(CommitDiff)(diff),1212 files: [1213 ...Schema.encodeSync(CommitDiff)(diff).files,1214 {1215 after: "d".repeat(40),1216 binary: false,1217 newText: linesUpTo(120),1218 path: "data/zones.ts",1219 status: "added",1220 },1221 ],1222});12231224describe(CommitView, () => {1225 const page = <CommitView diff={diff} now={now} project={datekit} />;12261227 it("names the people in its credit, each linking their page, and shows its trailers once", () => {1228 const markup = markupOf(page);1229 const hrefs = hrefsOf(markup);12301231 expect(hrefs).toStrictEqual(1232 expect.arrayContaining(["/people/ines-v", "/people/bram"])1233 );1234 expect(1235 ["Asked-by:", "Signed-off-by:", "data-body"].map((part) =>1236 countIn(markup, part)1237 )1238 ).toStrictEqual([1, 1, 1]);1239 expect(1240 /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markup)?.[0]1241 ).not.toContain("Asked-by");1242 });12431244 it("sets its body as prose in the sans, never in mono", () => {1245 const body =1246 /<p\b[^>]*data-body=""[^>]*>[^<]*<\/p>/u.exec(markupOf(page))?.[0] ?? "";12471248 expect(body).toContain("Parse ISO week dates.");1249 expect(body).not.toContain("font-mono");1250 expect(body).toContain("text-body");1251 });12521253 it("links no one from an imported commit's trailers", () => {1254 const { landing: _landing, ...imported } = landedCommit;12551256 const markup = markupOf(1257 <CommitView1258 diff={decodeDiff({ commit: imported, files: [], truncated: false })}1259 now={now}1260 project={datekit}1261 />1262 );12631264 expect(hrefsOf(markup)).not.toContain("/people/bram");1265 expect(markup).toContain("bram@users.example.com");1266 expect(markup).toContain("Before adoption");1267 });12681269 it("leads with the landing's status line: landed as its id, and the ask it answered", () => {1270 const markup = markupOf(page);1271 const text = mainOf(markup).replaceAll(/<[^>]+>/gu, "");12721273 expect(text).toContain(`Landed as ${LANDED.slice(0, 7)}`);1274 expect(text).toContain("answered parse-iso-week");1275 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/asks/parse-iso-week");1276 expect(hrefsOf(markup)).toContain(1277 "/oscabriel/datekit/answers/parse-iso-week"1278 );1279 expect(markup).toContain('data-outcome="Landed"');1280 });12811282 it("links the ask an opening opened, and no answer, since it answers none", () => {1283 const markup = markupOf(1284 <CommitView1285 diff={decodeDiff({1286 commit: {1287 ...landedCommit,1288 landing: {1289 assisted: [],1290 author: "okonkwo",1291 credits: [{ handle: "okonkwo", role: "Decided-by" }],1292 landedAt: "2026-10-06T15:00:00.000Z",1293 opened: "parse-iso-week",1294 parent: IMPORTED,1295 project: "datekit",1296 sha: LANDED,1297 },1298 subject: "Open ask parse-iso-week",1299 },1300 files: [],1301 truncated: false,1302 })}1303 now={now}1304 project={datekit}1305 />1306 );13071308 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/asks/parse-iso-week");1309 expect(hrefsOf(markup)).not.toContain(1310 "/oscabriel/datekit/answers/parse-iso-week"1311 );1312 expect(markup).toContain("opened");1313 });13141315 it("puts git's own facts on one line: author, committer and parent, linked", () => {1316 const text = textOf(page);13171318 expect(hrefsOf(markupOf(page))).toContain(1319 `/oscabriel/datekit/commit/${IMPORTED}`1320 );1321 expect(text).toContain("authored by Bram");1322 expect(text).toContain("committed by the platform");1323 expect(text).toContain(`parent ${IMPORTED.slice(0, 7)}`);1324 });13251326 it("ends its head's meta line with the files and lines it changed, linking the diff", () => {1327 const markup = markupOf(page);13281329 const meta =1330 /<div class="text-ui text-muted-foreground">[\s\S]*?<\/div>/u.exec(1331 markup1332 )?.[0] ?? "";13331334 expect(1335 meta1336 .replaceAll(/<[^>]+>/gu, " ")1337 .replaceAll(/\s+/gu, " ")1338 .trim()1339 ).toMatch(/Browse files · \d+ files? · \+\d+ added −\d+ removed$/u);1340 expect(meta).toMatch(/<a\b[^>]*href="#diff"/u);1341 expect(meta).toContain("text-diff-add-sign");1342 expect(markup).toMatch(/<div\b[^>]*id="diff"/u);1343 });13441345 it("sends each changed file's diff as plain text, at the drawing's measures", () => {1346 const markup = markupOf(page);13471348 const plain =1349 /<div\b[^>]*data-diff="plain"[\s\S]*$/u.exec(markup)?.[0] ?? "";13501351 expect(1352 ["leading-code", "min-w-[calc(6ch+2px)]", "pl-[2ch]"].filter(1353 (measure) => !plain.includes(measure)1354 )1355 ).toStrictEqual([]);1356 expect(1357 ["src/week.ts", "src/parse.ts", "src/legacy.ts"].filter(1358 (path) =>1359 !slice(plain, "data-file", path).includes('data-diffs-header=""')1360 )1361 ).toStrictEqual([]);1362 expect(1363 [1364 ["src/parse.ts", "export const parse = fromIso;"],1365 ["src/parse.ts", "export const parse = Date;"],1366 ["src/week.ts", "export const week = 1;"],1367 ].filter(1368 ([path = "", line = ""]) =>1369 !slice(plain, "data-file", path).includes(line)1370 )1371 ).toStrictEqual([]);1372 expect(markup).not.toMatch(/<(?:diffs|file-tree)-container/u);1373 });13741375 it("keeps each file's header at the top of the pane while its lines scroll", () => {1376 const header =1377 /<summary\b[^>]*data-diffs-header=""[^>]*>/u.exec(markupOf(page))?.[0] ??1378 "";13791380 expect(header).toContain("sticky");1381 expect(header).toContain("top-0");1382 expect(header).toContain("h-11");1383 });13841385 it("starts an added or deleted file past 80 lines folded", () => {1386 const markup = markupOf(1387 <CommitView diff={long} now={now} project={datekit} />1388 );13891390 expect(slice(markup, "data-file", "data/zones.ts")).toContain(1391 'data-folded="true"'1392 );1393 expect(slice(markup, "data-file", "data/zones.ts")).not.toMatch(1394 /<details\b[^>]*\bopen=/u1395 );1396 expect(slice(markup, "data-file", "src/parse.ts")).toContain(1397 'data-folded="false"'1398 );1399 });14001401 it("counts the diff in the inspector: files, additions and deletions, split by path", () => {1402 const facts = factsOf(1403 markupOf(1404 <CommitView1405 diff={long}1406 now={now}1407 project={datekit}1408 territory={["src/**"]}1409 />1410 )1411 );14121413 const stats =1414 /<section\b[^>]*aria-label="Diff stats"[\s\S]*?<\/section>/u.exec(1415 facts1416 )?.[0] ?? "";14171418 const text = stats.replaceAll(/<[^>]+>/gu, " ").replaceAll(/\s+/gu, " ");14191420 expect(text).toContain("4 files");1421 expect(text).toContain("+122 added");1422 expect(text).toContain("−2 removed");1423 expect(slice(stats, "data-part", "territory")).toContain("+2");1424 expect(slice(stats, "data-part", "other")).toContain("+120");1425 });14261427 it("says when the commit is too large to show whole", () => {1428 const truncated = decodeDiff({1429 commit: landedCommit,1430 files: [{ binary: false, path: "data/zones.json", status: "modified" }],1431 truncated: true,1432 });14331434 expect(1435 textOf(<CommitView diff={truncated} now={now} project={datekit} />)1436 ).toContain("too large to show whole");1437 expect(textOf(page)).not.toContain("too large to show whole");1438 });1439});14401441type Sent = Rpc.Payload<Contract>;14421443const knownProject = (name: ProjectName) =>1444 name === datekit1445 ? Effect.void1446 : Effect.fail(new UnknownProject({ project: name }));14471448const knownRevision = (at: string | undefined) =>1449 at === undefined || at === "main" || at === AT1450 ? Effect.void1451 : Effect.fail(new UnknownRevision({ rev: at }));14521453const landedOnly = Schema.decodeSync(Refs)({1454 forks: [],1455 landed: LANDED,1456 project: "datekit",1457 tags: [],1458});14591460const noPath = (path: RepoPath) =>1461 new UnknownPath({ commit: CommitSha.make(AT), path });14621463const platformOf = (calls: Ref.Ref<readonly Sent[]>) => {1464 const sent = (payload: Sent) => Ref.update(calls, (all) => [...all, payload]);14651466 return Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(1467 Layer.provide([1468 Layer.mergeAll(1469 unanswered,1470 Contracts.toLayerHandler("readTree", (payload) =>1471 Effect.gen(function* () {1472 yield* sent(payload);1473 yield* knownProject(payload.project);1474 yield* knownRevision(payload.at);14751476 if (payload.path === undefined) {1477 return root;1478 }14791480 if (payload.path === nested.path) {1481 return nested;1482 }14831484 return yield* noPath(payload.path);1485 })1486 ),1487 Contracts.toLayerHandler("readFile", (payload) =>1488 Effect.gen(function* () {1489 yield* sent(payload);1490 yield* knownProject(payload.project);1491 yield* knownRevision(payload.at);14921493 if (payload.path === readme.path) {1494 return readme;1495 }14961497 return yield* noPath(payload.path);1498 })1499 ),1500 Contracts.toLayerHandler("log", (payload) =>1501 Effect.gen(function* () {1502 yield* sent(payload);1503 yield* knownProject(payload.project);1504 yield* knownRevision(payload.at);15051506 return { commits, next: (payload.from ?? 0) + LOG_PAGE };1507 })1508 ),1509 Contracts.toLayerHandler("showCommit", (payload) =>1510 Effect.gen(function* () {1511 yield* sent(payload);1512 yield* knownProject(payload.project);15131514 if (payload.at !== undefined) {1515 return payload.at === "@bob/parse-iso"1516 ? { ...diff, commit: Struct.omit(diff.commit, ["landing"]) }1517 : yield* new UnknownRevision({ rev: payload.at });1518 }15191520 if (payload.sha !== LANDED) {1521 return yield* new UnknownCommit({ sha: payload.sha });1522 }15231524 return diff;1525 })1526 ),1527 Contracts.toLayerHandler("listRefs", (payload) =>1528 Effect.gen(function* () {1529 yield* sent(payload);1530 yield* knownProject(payload.project);15311532 return landedOnly;1533 })1534 )1535 ),1536 asTester,1537 ])1538 );1539};15401541interface Refused {1542 readonly calls: readonly Sent[];1543 readonly refused: Option.Option<readonly string[]>;1544}15451546const refusedBy = <A, E>(1547 read: Effect.Effect<A, E, Client>1548): Effect.Effect<Refused> =>1549 Effect.gen(function* () {1550 const calls = yield* Ref.make<readonly Sent[]>([]);15511552 const failed = yield* Effect.flip(1553 read.pipe(Effect.provide(platformOf(calls)))1554 );15551556 expect(isNotFound(failed)).toBeTruthy();15571558 const data: unknown = isNotFound(failed) ? failed.data : undefined;15591560 const carried = Option.orElse(1561 Schema.decodeUnknownOption(Refusals)(data),1562 () =>1563 Option.map(1564 Schema.decodeUnknownOption(SoftLanding)(data),1565 ({ refusals }) => refusals1566 )1567 );15681569 return {1570 calls: yield* Ref.get(calls),1571 refused: Option.map(carried, explain),1572 };1573 }).pipe(Effect.orDie);15741575describe("the code pages' reads", () => {1576 it.effect(1577 "read a folder, its README and the revision's head for the folder's page, and no entry's last change",1578 () =>1579 Effect.gen(function* () {1580 const calls = yield* Ref.make<readonly Sent[]>([]);15811582 const read = yield* readTreePage({1583 project: "datekit",1584 rev: "main",1585 }).pipe(Effect.provide(platformOf(calls)));15861587 expect(read.listing.entries.map((entry) => entry.path)).toStrictEqual([1588 "src",1589 "README.md",1590 ]);1591 expect(read.readme?.text).toBe(readme.text);1592 expect(read.head?.sha).toBe(LANDED);1593 // The entries' last changes are the browser's to read, after the page is up.1594 expect(1595 (yield* Ref.get(calls)).filter((call) => "limit" in call)1596 ).toStrictEqual([1597 { at: "main", limit: 1, project: "oscabriel/datekit" },1598 ]);1599 })1600 );16011602 it.effect(1603 "pass a tag's name to the platform decoded, and carry back its refusal",1604 () =>1605 Effect.gen(function* () {1606 const { calls, refused } = yield* refusedBy(1607 readTreePage({1608 _splat: "src/format/locale",1609 project: "oscabriel/datekit",1610 rev: TAG_SEGMENT,1611 })1612 );16131614 expect(calls).toStrictEqual([1615 { at: TAG, path: "src/format/locale", project: "oscabriel/datekit" },1616 ]);1617 expect(refused).toStrictEqual(1618 Option.some(explain([new UnknownRevision({ rev: TAG })]))1619 );1620 })1621 );16221623 it.effect(1624 "are a not-found carrying the platform's refusal for a project, folder, file, revision or commit it lacks",1625 () =>1626 Effect.gen(function* () {1627 const cases: readonly (readonly [Effect.Effect<Refused>, Refusal])[] = [1628 [1629 refusedBy(readRefsPage("oscabriel/no-such-project")),1630 new UnknownProject({1631 project: ProjectName.make("oscabriel/no-such-project"),1632 }),1633 ],1634 [1635 refusedBy(1636 readTreePage({1637 _splat: "nope",1638 project: "oscabriel/datekit",1639 rev: "main",1640 })1641 ),1642 noPath(RepoPath.make("nope")),1643 ],1644 [1645 refusedBy(1646 readBlobPage({1647 _splat: "nope.ts",1648 project: "oscabriel/datekit",1649 rev: "main",1650 })1651 ),1652 noPath(RepoPath.make("nope.ts")),1653 ],1654 [1655 refusedBy(readLogPage({ project: "oscabriel/datekit", rev: "v9" })),1656 new UnknownRevision({ rev: "v9" }),1657 ],1658 [1659 refusedBy(1660 readCommitPage({ project: "oscabriel/datekit", sha: OLDER })1661 ),1662 new UnknownCommit({ sha: CommitSha.make(OLDER) }),1663 ],1664 ];16651666 for (const [read, refusal] of cases) {1667 const { refused } = yield* read;16681669 expect(refused).toStrictEqual(Option.some(explain([refusal])));1670 }1671 })1672 );16731674 it.effect(1675 "are a not-found with no refusal, and ask nothing, for an address that can name nothing",1676 () =>1677 Effect.gen(function* () {1678 const reads: readonly Effect.Effect<Refused>[] = [1679 refusedBy(readRefsPage("Not_A-Project")),1680 refusedBy(1681 readTreePage({ project: "oscabriel/datekit", rev: "%E0%A4%A" })1682 ),1683 refusedBy(1684 readBlobPage({ project: "oscabriel/datekit", rev: "main" })1685 ),1686 refusedBy(readLogPage({ project: "oscabriel/datekit", rev: "%" })),1687 refusedBy(1688 readCommitPage({ project: "oscabriel/datekit", sha: "abc1234" })1689 ),1690 ];16911692 for (const read of reads) {1693 expect(yield* read).toStrictEqual({1694 calls: [],1695 refused: Option.none(),1696 });1697 }1698 })1699 );17001701 it.effect("read the log page at `from`, a path's history only", () =>1702 Effect.gen(function* () {1703 const calls = yield* Ref.make<readonly Sent[]>([]);17041705 const read = yield* readLogPage({1706 from: 30,1707 path: "src/parse.ts",1708 project: "oscabriel/datekit",1709 rev: "main",1710 }).pipe(Effect.provide(platformOf(calls)));17111712 // The page, and the revision's head for the code bar beside it.1713 expect(1714 (yield* Ref.get(calls)).toSorted((one, other) =>1715 JSON.stringify(one).localeCompare(JSON.stringify(other))1716 )1717 ).toStrictEqual([1718 {1719 at: "main",1720 from: 30,1721 limit: LOG_PAGE,1722 path: "src/parse.ts",1723 project: "oscabriel/datekit",1724 },1725 { at: "main", limit: 1, project: "oscabriel/datekit" },1726 ]);1727 expect([read.from, read.next, read.path]).toStrictEqual([1728 30,1729 60,1730 "src/parse.ts",1731 ]);1732 })1733 );1734});17351736const landingOf = <A, E>(read: Effect.Effect<A, E, Client>) =>1737 Effect.gen(function* () {1738 const calls = yield* Ref.make<readonly Sent[]>([]);17391740 const failed = yield* Effect.flip(1741 read.pipe(Effect.provide(platformOf(calls)))1742 );17431744 return Schema.decodeUnknownOption(SoftLanding)(1745 isNotFound(failed) ? failed.data : undefined1746 );1747 }).pipe(Effect.orDie);17481749describe("a missing path", () => {1750 it.effect(1751 "lands on the nearest folder that exists at the commit, with the refusal as its notice",1752 () =>1753 Effect.gen(function* () {1754 const landing = yield* landingOf(1755 readBlobPage({1756 _splat: "src/format/locale/gone/x.ts",1757 project: "datekit",1758 rev: "main",1759 })1760 );17611762 expect(1763 Option.map(landing, ({ nearest }) => nearest.path)1764 ).toStrictEqual(Option.some("src/format/locale"));1765 expect(1766 Option.map(landing, ({ refusals }) => explain(refusals))1767 ).toStrictEqual(1768 Option.some(1769 explain([noPath(RepoPath.make("src/format/locale/gone/x.ts"))])1770 )1771 );17721773 const atRoot = yield* landingOf(1774 readTreePage({ _splat: "nope", project: "datekit", rev: "main" })1775 );17761777 expect(1778 Option.map(atRoot, ({ nearest }) => nearest.path === undefined)1779 ).toStrictEqual(Option.some(true));1780 })1781 );17821783 it("renders the nearest folder with UnknownPath's own words above it", () => {1784 const refusal = noPath(RepoPath.make("src/format/locale/gone/x.ts"));17851786 const markup = markupOf(1787 <CodeNotFound1788 data={Schema.encodeSync(SoftLanding)({1789 nearest: nested,1790 now,1791 project: datekit,1792 refusals: [refusal],1793 rev: "main",1794 })}1795 />1796 );17971798 const text = textOf(1799 <CodeNotFound1800 data={Schema.encodeSync(SoftLanding)({1801 nearest: nested,1802 now,1803 project: datekit,1804 refusals: [refusal],1805 rev: "main",1806 })}1807 />1808 );18091810 for (const line of explain([refusal])) {1811 expect(text).toContain(line.trim());1812 }18131814 expect(markup).toContain('data-refusal="UnknownPath"');1815 expect(markup).toContain('data-entry="src/format/locale/en.ts"');1816 expect(markup.indexOf('data-refusal="UnknownPath"')).toBeLessThan(1817 markup.indexOf('data-entry="src/format/locale/en.ts"')1818 );1819 });18201821 it.effect(1822 "keeps the code bar's Tree button over the folder it lands on, so a phone still reaches the tree",1823 () =>1824 Effect.gen(function* () {1825 const data = yield* Schema.encodeEffect(SoftLanding)({1826 nearest: nested,1827 now,1828 project: datekit,1829 refusals: [noPath(RepoPath.make("src/format/locale/gone/x.ts"))],1830 rev: "main",1831 });18321833 const pages = yield* Effect.forEach(1834 ["tree", "blob", "why"] as const,1835 (page) =>1836 inCodeTab(1837 `/oscabriel/datekit/${page}/main/src/format/locale/gone/x.ts`,1838 <CodeNotFound data={data} />1839 )1840 );18411842 expect(1843 pages.map((markup) =>1844 /aria-haspopup="dialog"[^>]*>[\s\S]*?Tree<\/button>/u.test(1845 codeBarOf(markup)1846 )1847 )1848 ).toStrictEqual([true, true, true]);1849 })1850 );18511852 it("keeps any other refusal verbatim, with a way onward", () => {1853 const refusal = new UnknownRevision({ rev: "v9" });18541855 const element = (1856 <CodeNotFound data={Schema.encodeSync(Refusals)([refusal])} />1857 );18581859 expect(markupOf(element)).toContain('data-refusal="UnknownRevision"');1860 expect(hrefsOf(markupOf(element))).toContain("/asks");1861 });1862});18631864const HEADERS_LINE = "headers: () => branchPage";18651866describe("a code page's caching", () => {1867 // A commit's page carries its landing, recorded after main has moved, and times reckoned from the read,1868 // so it is never kept for good.1869 const routes: Readonly<Record<string, string>> = import.meta.glob(1870 "../src/routes/$owner/$project/{tree,blob,why}/$rev/$.tsx",1871 { eager: true, import: "default", query: "?raw" }1872 );18731874 const logs: Readonly<Record<string, string>> = import.meta.glob(1875 "../src/routes/$owner/$project/{commits/$rev,commit/$sha}.tsx",1876 { eager: true, import: "default", query: "?raw" }1877 );18781879 it("keeps each code page briefly, even at a whole commit id, and reads it again behind it", () => {1880 const pages = { ...routes, ...logs };18811882 expect(Object.keys(pages)).toHaveLength(5);1883 expect(1884 Object.entries(pages).flatMap(([path, source]) =>1885 source.replaceAll(/\s+/gu, " ").includes(HEADERS_LINE) &&1886 !source.includes("immutable")1887 ? []1888 : [path]1889 )1890 ).toStrictEqual([]);1891 });1892});18931894describe("the code browser's views", () => {1895 const sources: Readonly<Record<string, string>> = import.meta.glob(1896 "../src/features/code/**/*.{ts,tsx}",1897 { eager: true, import: "default", query: "?raw" }1898 );18991900 it("import no transport", () => {1901 expect(Object.keys(sources).length).toBeGreaterThanOrEqual(3);1902 expect(reachingTransport(sources)).toStrictEqual([]);1903 });1904});19051906const FORK = "@bob/parse-iso";19071908const FORK_SEGMENT = "%40bob%2Fparse-iso";19091910/** A commit read in bob's fork, as one address segment. */1911const inFork = (sha: string) => `${FORK_SEGMENT}%3A${sha}`;19121913describe("an answer fork in the Code tab", () => {1914 it("pins raw and the permalink to the commit inside the fork, and keeps the history at the fork", () => {1915 const markup = markupOf(1916 <BlobView file={parseTs} now={now} project={datekit} rev={FORK} />1917 );19181919 expect(hrefsOf(navOf(markup, 'data-toolbar="file"'))).toStrictEqual([1920 `/oscabriel/datekit/raw/${inFork(AT)}/src/format/parse.ts`,1921 `/oscabriel/datekit/blob/${inFork(AT)}/src/format/parse.ts`,1922 ]);1923 expect(hrefsOf(factsOf(markup))).toContain(1924 `/oscabriel/datekit/commits/${FORK_SEGMENT}?path=src%2Fformat%2Fparse.ts`1925 );1926 });19271928 it("links each commit of the fork's log to its page inside the fork", () => {1929 const markup = markupOf(1930 <LogView1931 commits={commits}1932 from={0}1933 now={now}1934 project={datekit}1935 rev={FORK}1936 />1937 );19381939 expect(hrefsOf(markup)).toContain(1940 `/oscabriel/datekit/commit/${inFork(LANDED)}`1941 );1942 expect(hrefsOf(markup)).not.toContain(1943 `/oscabriel/datekit/commit/${LANDED}`1944 );1945 });19461947 it("links a fork commit's parent and its files inside the fork", () => {1948 const hrefs = hrefsOf(1949 markupOf(<CommitView at={FORK} diff={diff} now={now} project={datekit} />)1950 );19511952 expect(hrefs).toContain(`/oscabriel/datekit/commit/${inFork(IMPORTED)}`);1953 expect(hrefs).toContain(`/oscabriel/datekit/tree/${inFork(LANDED)}`);1954 expect(hrefs).not.toContain(`/oscabriel/datekit/tree/${LANDED}`);1955 });19561957 it("reads a fork's address, and a commit inside it, off the path", () => {1958 expect(1959 [1960 `/oscabriel/datekit/tree/${FORK_SEGMENT}/src`,1961 `/oscabriel/datekit/commit/${inFork(LANDED)}`,1962 ].map(codeAddressOf)1963 ).toStrictEqual([1964 Option.some({ page: "tree", path: "src", rev: FORK }),1965 Option.some({1966 page: "commit",1967 path: undefined,1968 rev: `${FORK}:${LANDED}`,1969 }),1970 ]);1971 });19721973 it.effect(1974 "names the fork in the ref switcher, with Files and Commits kept at the fork",1975 () =>1976 Effect.gen(function* () {1977 const bar = codeBarOf(1978 yield* inCodeTab(1979 `/oscabriel/datekit/tree/${FORK_SEGMENT}`,1980 <TreeView listing={root} now={now} project={datekit} rev={FORK} />1981 )1982 );19831984 expect(elementWith(bar, `data-ref="${FORK}"`)).toContain(1985 "bob/parse-iso"1986 );1987 expect(1988 linksIn(navOf(bar, 'aria-label="Files or commits"')).map(1989 ({ href }) => href1990 )1991 ).toStrictEqual([1992 `/oscabriel/datekit/tree/${FORK_SEGMENT}`,1993 `/oscabriel/datekit/commits/${FORK_SEGMENT}`,1994 ]);1995 })1996 );19971998 it.effect(1999 "reads a commit in the fork its address names, and carries back a fork the project does not list",2000 () =>The first 2,000 of 2,044 lines.