why.test.tsx
This file
Path
apps/web/test/why.test.tsx
520 lines · 15.2 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 { CommitView, FileView, WhyView } from "@repo/protocol/domain/code";4import { LandingView } from "@repo/protocol/domain/landing";5import { Outcome } from "@repo/protocol/domain/outcome";6import { LandedSha, ProjectName } from "@repo/protocol/ids";7import { asTester, unanswered } from "@repo/protocol/testing";8import { DateTime, Duration, Effect, Layer, Ref, Schema } from "effect";9import { RpcTest } from "effect/rpc";10import type { ReactElement } from "react";11import { renderToStaticMarkup } from "react-dom/server";1213import { LandingDetails } from "../src/features/why/range-summary.tsx";14import { WhyCode } from "../src/features/why/why-code.tsx";15import { WhyLines } from "../src/features/why/why-view.tsx";16import { readWhyPage } from "../src/routes/$owner/$project/why/$rev/$.tsx";1718const markupOf = (element: ReactElement) => renderToStaticMarkup(element);1920const textOf = (markup: string) =>21 markup22 .replaceAll(/<[^>]+>/gu, " ")23 .replaceAll("'", "'")24 .replaceAll(""", '"')25 .replaceAll("&", "&")26 .replaceAll(/\s+/gu, " ");2728const hrefsOf = (markup: string) =>29 [...markup.matchAll(/href="(?<href>[^"]*)"/gu)].map((match) =>30 (match.groups?.href ?? "").replaceAll("&", "&")31 );3233const datekit = ProjectName.make("oscabriel/datekit");3435const AT = "a".repeat(40);3637const LANDED = "1".repeat(40);3839const IMPORTED = "2".repeat(40);4041const ROOT = "3".repeat(40);4243const signature = (name: string, at: string) => ({44 at,45 email: `${name.toLowerCase()}@example.com`,46 name,47});4849const view = Schema.decodeSync(WhyView)({50 at: AT,51 commits: [52 {53 author: signature("Bram", "2026-10-06T15:00:00.000Z"),54 body: "",55 committer: signature("platform", "2026-10-06T15:00:00.000Z"),56 parents: [IMPORTED],57 sha: LANDED,58 subject: "Answer parse-iso-week",59 trailers: [],60 tree: "4".repeat(40),61 },62 {63 author: signature("Ada", "2026-09-01T09:00:00.000Z"),64 body: "",65 committer: signature("Ada", "2026-09-01T09:00:00.000Z"),66 parents: [ROOT],67 sha: IMPORTED,68 subject: "Add the formatter",69 trailers: [],70 tree: "5".repeat(40),71 },72 ],73 landings: [74 {75 ask: "parse-iso-week",76 assisted: [{ harness: "pi", model: "opus-4", verified: true }],77 author: "bram",78 credits: [79 { handle: "bram", role: "Signed-off-by" },80 { handle: "ines-v", role: "Asked-by" },81 ],82 landedAt: "2026-10-06T15:00:00.000Z",83 parent: IMPORTED,84 project: "datekit",85 sha: LANDED,86 verdict: {87 ask: "parse-iso-week",88 at: "2026-10-06T14:59:00.000Z",89 base: IMPORTED,90 checkVersion: "redThenGreen@0.0.0+abc",91 head: "7".repeat(40),92 heldBack: [],93 lanes: [],94 outcome: Schema.encodeSync(Outcome)(95 Outcome.cases.Landed.make({ sha: LandedSha.make(LANDED) })96 ),97 patchId: "8".repeat(64),98 project: "datekit",99 stage: "checks",100 tree: "4".repeat(40),101 verifier: "platform",102 },103 },104 ],105 path: "src/format.ts",106 ranges: [107 { end: 3, sha: LANDED, start: 1 },108 { end: 4, sha: IMPORTED, start: 4 },109 ],110});111112const TEXT =113 "export const iso = 1;\nexport const week = 2;\nexport const day = 3;\nexport const old = 4;\n";114115const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");116117const page = (118 <WhyLines now={now} project={datekit} rev="main" text={TEXT} view={view} />119);120121const bandOf = (markup: string, value: string) => {122 const start = markup.indexOf(`data-range="${value}"`);123 const rest = markup.slice(start + 1);124125 const ends = [rest.indexOf("data-range="), rest.indexOf(' id="L')].filter(126 (at) => at !== -1127 );128129 return start === -1 ? "" : markup.slice(start, start + 1 + Math.min(...ends));130};131132describe("the why page's fallback", () => {133 it("names who brought lines 1–3, ask and answer first and the commit second, each linked", () => {134 const band = bandOf(markupOf(page), "1-3");135 const text = textOf(band);136137 expect(text).toContain("lines 1–3");138 expect(text).toContain("parse-iso-week");139 expect(text).toContain("answered by bram");140 expect(141 [text.indexOf("parse-iso-week"), text.indexOf("answered by bram")].every(142 (at) => at > -1 && at < text.indexOf(LANDED.slice(0, 7))143 )144 ).toBeTruthy();145 expect(hrefsOf(band)).toStrictEqual(146 expect.arrayContaining([147 "/oscabriel/datekit/asks/parse-iso-week",148 "/oscabriel/datekit/answers/parse-iso-week",149 `/oscabriel/datekit/commit/${LANDED}`,150 ])151 );152 });153154 it("counts no credit and colours nothing by age", () => {155 const markup = markupOf(page);156157 expect(textOf(markup)).not.toMatch(/\bcredits?\b/u);158 expect(bandOf(markup, "1-3")).not.toMatch(159 /text-(?:landed|waiting|refused|checking)/u160 );161 });162163 it("says an imported commit's lines came before adoption", () => {164 const band = bandOf(markupOf(page), "4-4");165166 expect(textOf(band)).toContain("line 4");167 expect(textOf(band)).toContain("Add the formatter");168 expect(textOf(band)).toContain("Ada");169 expect(textOf(band)).toContain("before adoption");170 expect(hrefsOf(band)).toContain(`/oscabriel/datekit/commit/${IMPORTED}`);171 });172173 it("offers why, one step back, and a proposal about each group's first line", () => {174 const markup = markupOf(page);175 const hrefs = hrefsOf(markup);176177 expect(hrefs).toContain(`/oscabriel/datekit/why/${IMPORTED}/src/format.ts`);178 expect(textOf(markup)).toContain("why, one step back");179 expect(textOf(markup)).toContain("Propose an ask about this line");180181 const proposal = hrefs182 .filter((href) => href.startsWith("/oscabriel/datekit/proposals/new?"))183 .map((href) =>184 Object.fromEntries(new URL(href, "https://x").searchParams)185 );186187 expect(proposal).toStrictEqual([188 { about: "src/format.ts", at: AT, line: "1" },189 { about: "src/format.ts", at: AT, line: "4" },190 ]);191 });192193 it("puts each group's band above its first line, among the numbered lines, and leaves the drawing to the browser", () => {194 const markup = markupOf(page);195196 expect(markup).toContain('id="L4"');197 expect(markup).toContain('data-why="ranges"');198 expect(markup.indexOf('data-range="4-4"')).toBeLessThan(199 markup.indexOf('id="L4"')200 );201 expect(markup.indexOf('data-range="4-4"')).toBeGreaterThan(202 markup.indexOf('id="L3"')203 );204 expect(markup).not.toContain("<diffs-container");205 });206207 it("groups consecutive lines one commit brought into one band", () => {208 const split = Schema.decodeSync(WhyView)({209 ...Schema.encodeSync(WhyView)(view),210 ranges: [211 { end: 2, sha: LANDED, start: 1 },212 { end: 3, sha: LANDED, start: 3 },213 { end: 4, sha: IMPORTED, start: 4 },214 ],215 });216217 const markup = markupOf(218 <WhyLines219 now={now}220 project={datekit}221 rev="main"222 text={TEXT}223 view={split}224 />225 );226227 expect(228 [...markup.matchAll(/data-range="(?<range>[^"]+)"/gu)].map(229 (match) => match.groups?.range230 )231 ).toStrictEqual(["1-3", "4-4"]);232 });233234 it("says why a file without ranges has none", () => {235 const binary = Schema.decodeSync(WhyView)({236 at: AT,237 commits: [],238 landings: [],239 path: "logo.png",240 ranges: [],241 });242243 expect(244 textOf(245 markupOf(246 <WhyLines now={now} project={datekit} rev="main" view={binary} />247 )248 )249 ).toContain("binary or too large");250 });251252 it("is the same page as the file, in Why mode", () => {253 const toggle =254 /<nav\b[^>]*aria-label="Mode"[\s\S]*?<\/nav>/u.exec(255 markupOf(page)256 )?.[0] ?? "";257258 expect(hrefsOf(toggle)).toStrictEqual([259 "/oscabriel/datekit/blob/main/src/format.ts",260 "/oscabriel/datekit/why/main/src/format.ts",261 ]);262 expect(toggle).toMatch(/aria-current="page"[^>]*>Why</u);263 });264});265266const OPENED = "6".repeat(40);267268const opening = Schema.decodeSync(WhyView)({269 at: AT,270 commits: [271 {272 author: signature("Ines", "2026-10-07T10:00:00.000Z"),273 body: "",274 committer: signature("platform", "2026-10-07T10:00:00.000Z"),275 parents: [LANDED],276 sha: OPENED,277 subject: "Open format-ordinal",278 trailers: [],279 tree: "9".repeat(40),280 },281 ...view.commits.map((commit) => Schema.encodeSync(CommitView)(commit)),282 ],283 landings: [284 ...view.landings.map((landing) => Schema.encodeSync(LandingView)(landing)),285 {286 assisted: [],287 author: "ines-v",288 credits: [{ handle: "ines-v", role: "Signed-off-by" }],289 landedAt: "2026-10-07T10:00:00.000Z",290 opened: "format-ordinal",291 parent: LANDED,292 project: "datekit",293 sha: OPENED,294 },295 ],296 path: "src/format.ts",297 ranges: [298 { end: 1, sha: LANDED, start: 1 },299 { end: 3, sha: OPENED, start: 2 },300 { end: 4, sha: IMPORTED, start: 4 },301 ],302});303304const opened = (305 <WhyLines now={now} project={datekit} rev="main" text={TEXT} view={opening} />306);307308describe("the why page's band for an ask's opening", () => {309 it('links the ask it opened and reads "opened", with no answer link', () => {310 const band = bandOf(markupOf(opened), "2-3");311312 expect(textOf(band)).toContain("opened format-ordinal");313 expect(textOf(band)).toContain("by ines-v");314 expect(hrefsOf(band)).toContain("/oscabriel/datekit/asks/format-ordinal");315 expect(316 hrefsOf(band).filter((href) => href.includes("/answers/"))317 ).toStrictEqual([]);318 });319320 it("keeps an answering landing's ask and answer links, and an adopted commit's words", () => {321 const markup = markupOf(opened);322323 expect(hrefsOf(bandOf(markup, "1-1"))).toStrictEqual(324 expect.arrayContaining([325 "/oscabriel/datekit/asks/parse-iso-week",326 "/oscabriel/datekit/answers/parse-iso-week",327 ])328 );329 expect(textOf(bandOf(markup, "1-1"))).not.toContain("opened");330 expect(textOf(bandOf(markup, "4-4"))).toContain("before adoption");331 });332});333334const detailsOf = (landing: LandingView | undefined) =>335 landing === undefined336 ? ""337 : markupOf(<LandingDetails landing={landing} project={datekit} />);338339describe("a line's landing, in the line dialog", () => {340 it("names the ask an opening opened, linking it, and no answer", () => {341 const markup = detailsOf(342 opening.landings.find(({ sha }) => sha === OPENED)343 );344345 expect(textOf(markup)).toContain("Opened ask format-ordinal");346 expect(hrefsOf(markup)).toContain("/oscabriel/datekit/asks/format-ordinal");347 expect(348 hrefsOf(markup).filter((href) => href.includes("/answers/"))349 ).toStrictEqual([]);350 });351352 it("names the ask an answering landing answers, with its answer", () => {353 const markup = detailsOf(view.landings[0]);354355 expect(textOf(markup)).toContain("Ask parse-iso-week");356 expect(textOf(markup)).not.toContain("Opened ask");357 expect(hrefsOf(markup)).toContain(358 "/oscabriel/datekit/answers/parse-iso-week"359 );360 });361});362363describe("the why page's drawing", () => {364 it("draws the file with @pierre/diffs", () => {365 expect(366 markupOf(367 <WhyCode368 now={now}369 project={datekit}370 rev="main"371 text={TEXT}372 view={view}373 />374 )375 ).toContain("<diffs-container");376 });377});378379interface Asked {380 readonly files: readonly string[];381 readonly peak: number;382 readonly under: number;383}384385const whyPlatform = (asked: Ref.Ref<Asked>, mainAt: string) => {386 const during = <A, E>(answer: Effect.Effect<A, E>) =>387 Effect.acquireUseRelease(388 Ref.update(asked, (was) => ({389 ...was,390 peak: Math.max(was.peak, was.under + 1),391 under: was.under + 1,392 })),393 () => Effect.andThen(Effect.sleep(Duration.millis(30)), answer),394 () => Ref.update(asked, (was) => ({ ...was, under: was.under - 1 }))395 );396397 return Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(398 Layer.provide([399 Layer.mergeAll(400 unanswered,401 Contracts.toLayerHandler("why", () => during(Effect.succeed(view))),402 Contracts.toLayerHandler("log", () => Effect.succeed({ commits: [] })),403 Contracts.toLayerHandler("readFile", (payload) =>404 during(405 Effect.gen(function* () {406 yield* Ref.update(asked, (was) => ({407 ...was,408 files: [...was.files, payload.at ?? "main"],409 }));410411 const at =412 payload.at === undefined || payload.at === "main"413 ? mainAt414 : payload.at;415416 return yield* Schema.decodeEffect(FileView)({417 at,418 binary: false,419 path: "src/format.ts",420 sha: "5".repeat(40),421 size: 6,422 text: `at ${at.slice(0, 4)}\n`,423 truncated: false,424 }).pipe(Effect.orDie);425 })426 )427 )428 ),429 asTester,430 ])431 );432};433434const nothingAsked: Asked = { files: [], peak: 0, under: 0 };435436const whyAddress = { _splat: "src/format.ts", project: "datekit", rev: "main" };437438describe("the why page's read", () => {439 it.live("asks for the why and the file's text at once", () =>440 Effect.gen(function* () {441 const asked = yield* Ref.make(nothingAsked);442443 const read = yield* readWhyPage(whyAddress).pipe(444 // A not-found is TanStack's own error, typed `any`: neither case445 // here reads one.446 Effect.orDie,447 Effect.provide(whyPlatform(asked, AT))448 );449450 expect(read.text).toBe("at aaaa\n");451 expect(yield* Ref.get(asked)).toStrictEqual({452 files: ["main"],453 peak: 2,454 under: 0,455 });456 })457 );458459 it.live(460 "reads the file again at the why's commit when main moved between the two reads",461 () =>462 Effect.gen(function* () {463 const asked = yield* Ref.make(nothingAsked);464465 const read = yield* readWhyPage(whyAddress).pipe(466 // A not-found is TanStack's own error, typed `any`: neither case467 // here reads one.468 Effect.orDie,469 Effect.provide(whyPlatform(asked, "b".repeat(40)))470 );471472 expect(read.text).toBe("at aaaa\n");473 expect((yield* Ref.get(asked)).files).toStrictEqual(["main", AT]);474 })475 );476});477478const inFork = (sha: string) => `%40bob%2Fparse-iso%3A${sha}`;479480describe("why, in an answer fork", () => {481 const file = Schema.decodeSync(FileView)({482 at: AT,483 binary: false,484 path: "src/format.ts",485 sha: "c".repeat(40),486 size: TEXT.length,487 text: TEXT,488 truncated: false,489 });490491 it("links each line's commit, one step back and the permalink inside the fork", () => {492 const hrefs = hrefsOf(493 markupOf(494 <WhyLines495 file={file}496 now={now}497 project={datekit}498 rev="@bob/parse-iso"499 text={TEXT}500 view={view}501 />502 )503 );504505 expect(hrefs).toStrictEqual(506 expect.arrayContaining([507 `/oscabriel/datekit/commit/${inFork(LANDED)}`,508 `/oscabriel/datekit/why/${inFork(IMPORTED)}/src/format.ts`,509 `/oscabriel/datekit/why/${inFork(AT)}/src/format.ts`,510 ])511 );512 expect(513 hrefs.filter((href) =>514 [LANDED, IMPORTED, AT].some(515 (sha) => href.includes(`/${sha}`) && !href.includes("%3A")516 )517 )518 ).toStrictEqual([]);519 });520});