code-prerender.test.tsx
This file
Path
apps/web/test/code-prerender.test.tsx
348 lines · 9.4 KiB · TypeScript
Last changed by
Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248
History of this fileTake it
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 1–22why, one step back1import { describe, expect, it } from "@effect/vitest";2import { ChangedFile, CommitDiff, FileView } from "@repo/protocol/domain/code";3import { ProjectName } from "@repo/protocol/ids";4import { DateTime, Effect, Schema } from "effect";5import { renderToStaticMarkup } from "react-dom/server";67import { BlobView } from "../src/features/code/blob-view.tsx";8import { ClientDiffs, ClientFile } from "../src/features/code/client-code.tsx";9import { CommitView } from "../src/features/code/commit-view.tsx";10import { drawnFiles } from "../src/features/code/diff-model.ts";11import { PlainDiff } from "../src/features/code/plain-diff.tsx";12import { prerenderFile } from "../src/features/code/prerender-server.ts";13import {14 drawDiffAhead,15 drawFileAhead,16 prerenderedPaths,17 prerendersFile,18 SERVER_FILES,19 SERVER_LINES,20} from "../src/features/code/prerender.ts";21import { FileFallback } from "../src/features/code/server-code.tsx";22Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 23why, one step back23const datekit = ProjectName.make("oscabriel/datekit");Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 24–348why, one step back2425const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");2627const AT = "a".repeat(40);2829const decodeFile = Schema.decodeSync(FileView);3031const decodeFiles = Schema.decodeSync(Schema.Array(ChangedFile));3233const TOKEN = /--diffs-token-light:var\(--diffs-token-[a-z-]+/gu;3435const tokensIn = (markup: string) => [...markup.matchAll(TOKEN)].length;3637const shadowRootsIn = (markup: string) =>38 [...markup.matchAll(/<template shadowrootmode="open">/gu)].length;3940const TYPESCRIPT = [41 'import { fromIso } from "./iso.ts";',42 "",43 "/** A date from an ISO week string. */",44 "export const parse = (text: string): Date => fromIso(text);",45 "",46].join("\n");4748const linesOf = (count: number) =>49 Array.from(50 { length: count },51 (_, index) => `export const n${index} = ${index};`52 ).join("\n");5354let blobs = 0;5556const fileAt = (path: string, text: string) => {57 blobs += 1;5859 return decodeFile({60 at: AT,61 binary: false,62 path,63 sha: blobs.toString(16).padStart(40, "0"),64 size: text.length,65 text,66 truncated: false,67 });68};6970const blobPage = (file: FileView) =>71 Effect.gen(function* () {72 yield* Effect.promise(() => drawFileAhead(file));7374 const text = file.text ?? "";7576 return renderToStaticMarkup(77 <BlobView78 code={79 <ClientFile80 fallback={81 <FileFallback path={file.path} sha={file.sha} text={text} />82 }83 path={file.path}84 sha={file.sha}85 text={text}86 />87 }88 file={file}89 now={now}90 project={datekit}91 rev="main"92 />93 );94 });9596const signature = {97 at: "2026-10-06T15:00:00.000Z",98 email: "lin@example.com",99 name: "Lin",100};101102const commitOf = (files: readonly (typeof ChangedFile.Encoded)[]) =>103 Schema.decodeSync(CommitDiff)({104 commit: {105 author: signature,106 body: "",107 committer: signature,108 parents: ["2".repeat(40)],109 sha: "1".repeat(40),110 subject: "Parse ISO weeks",111 trailers: [],112 tree: "4".repeat(40),113 },114 files,115 truncated: false,116 });117118const commitPage = (diff: CommitDiff) =>119 Effect.gen(function* () {120 const drawn = drawnFiles(diff.files);121122 yield* Effect.promise(() => drawDiffAhead(diff.files));123124 return renderToStaticMarkup(125 <CommitView126 diff={diff}127 drawing={128 <ClientDiffs129 fallback={130 <PlainDiff131 drawn={drawn}132 files={diff.files}133 prerendered={prerenderedPaths(drawn)}134 />135 }136 files={diff.files}137 split={false}138 />139 }140 drawn={drawn}141 now={now}142 project={datekit}143 />144 );145 });146147const sectionOf = (markup: string, path: string) =>148 new RegExp(149 `<section aria-label="${path.replaceAll(".", "\\.")}"[\\s\\S]*?</section>`,150 "u"151 ).exec(markup)?.[0] ?? "";152153const added = (path: string, lines: number) => {154 blobs += 1;155156 return {157 after: blobs.toString(16).padStart(40, "0"),158 binary: false,159 newText: linesOf(lines),160 path,161 status: "added" as const,162 };163};164165describe("a blob page's code, as the server sends it", () => {166 it.effect(167 "holds a TypeScript file highlighted, in a declarative shadow root",168 () =>169 Effect.gen(function* () {170 const markup = yield* blobPage(fileAt("src/parse.ts", TYPESCRIPT));171172 expect(shadowRootsIn(markup)).toBe(1);173 expect(markup).toContain('data-code="prerendered"');174 expect(markup).toContain("<diffs-container");175 expect(tokensIn(markup)).toBeGreaterThan(5);176 expect(markup).not.toContain('data-code="plain"');177 })178 );179180 it.effect(181 "holds a file in a language the server does not highlight as numbered plain text",182 () =>183 Effect.gen(function* () {184 const markup = yield* blobPage(185 fileAt("src/parse.rs", "fn parse() -> u32 {\n 1\n}\n")186 );187188 expect(shadowRootsIn(markup)).toBe(0);189 expect(tokensIn(markup)).toBe(0);190 expect(markup).toContain('data-code="plain"');191 expect(markup).toContain('id="L1"');192 })193 );194195 it.effect(196 "holds a file past the server's limit as plain text: too many lines, or a line too long",197 () =>198 Effect.gen(function* () {199 const long = yield* blobPage(200 fileAt("src/long.ts", linesOf(SERVER_LINES + 1))201 );202203 const wide = yield* blobPage(204 fileAt("src/wide.ts", `export const wide = "${"x".repeat(1000)}";\n`)205 );206207 const within = yield* blobPage(208 fileAt("src/within.ts", linesOf(SERVER_LINES))209 );210211 expect([long, wide, within].map(shadowRootsIn)).toStrictEqual([212 0, 0, 1,213 ]);214 expect(long).toContain('data-code="plain"');215 expect(wide).toContain('data-code="plain"');216 })217 );218});219220describe("a commit page's diff, as the server sends it", () => {221 it.effect(222 "holds a TypeScript file's changes highlighted, and an unknown language's as plain lines",223 () =>224 Effect.gen(function* () {225 const markup = yield* commitPage(226 commitOf([227 {228 after: "a".repeat(40),229 before: "b".repeat(40),230 binary: false,231 newText: TYPESCRIPT.replace(232 "fromIso(text)",233 "fromIso(text.trim())"234 ),235 oldText: TYPESCRIPT,236 path: "src/parse.ts",237 status: "modified",238 },239 {240 after: "c".repeat(40),241 binary: false,242 newText: "fn week() -> u32 {\n 1\n}\n",243 path: "src/week.rs",244 status: "added",245 },246 ])247 );248249 const typescript = sectionOf(markup, "src/parse.ts");250 const rust = sectionOf(markup, "src/week.rs");251252 expect(shadowRootsIn(typescript)).toBe(1);253 expect(tokensIn(typescript)).toBeGreaterThan(5);254 expect(shadowRootsIn(rust)).toBe(0);255 expect(rust).toContain('data-line-type="addition"');256 expect(rust).toContain("fn week() -> u32 {");257 })258 );259});260261describe("which code the server highlights", () => {262 it("highlights its languages by Pierre's names for them, and no other", () => {263 const highlighted = [264 "a.ts",265 "a.tsx",266 "a.js",267 "a.mjs",268 "a.cjs",269 "a.jsx",270 "a.json",271 "a.md",272 "a.yaml",273 "a.yml",274 "a.toml",275 "a.sh",276 "a.css",277 "a.html",278 ];279280 expect(281 highlighted.filter((path) => !prerendersFile({ path, text: "x" }))282 ).toStrictEqual([]);283 expect(284 ["a.rs", "a.py", "Makefile", "a.go", "a.txt"].filter((path) =>285 prerendersFile({ path, text: "x" })286 )287 ).toStrictEqual([]);288 });289290 it.effect("has a grammar for each of its languages, aliases included", () =>291 Effect.gen(function* () {292 const samples = {293 "a.css": "a { color: red; }",294 "a.html": '<p class="x">hi</p>',295 "a.js": "const a = 1;",296 "a.json": '{ "a": 1 }',297 "a.jsx": "const a = <p>hi</p>;",298 "a.md": "See [the docs](https://example.com).",299 "a.sh": 'echo "hi"',300 "a.toml": 'a = "b"',301 "a.ts": "const a: number = 1;",302 "a.tsx": "const a = <p>{1}</p>;",303 "a.yaml": "a: b",304 "a.yml": "a: b",305 };306307 const drawn = yield* Effect.forEach(308 Object.entries(samples),309 ([path, text]) =>310 prerenderFile({ path, sha: `grammar:${path}`, text }).pipe(311 Effect.map((html) => [path, tokensIn(html ?? "") > 0] as const)312 )313 );314315 expect(drawn.filter(([, highlighted]) => !highlighted)).toStrictEqual([]);316 })317 );318319 it("highlights a diff's first open files within its lines, never a folded one", () => {320 // `a` is folded (an added file past 80 lines starts so); `b` and `c`321 // fit together; `d` would pass the limit; `e` still fits after it.322 const drawn = drawnFiles(323 decodeFiles([324 added("a.ts", 90),325 added("b.ts", 60),326 added("c.ts", 60),327 added("d.ts", SERVER_LINES),328 added("e.ts", 10),329 ])330 );331332 expect([...prerenderedPaths(drawn)]).toStrictEqual([333 "b.ts",334 "c.ts",335 "e.ts",336 ]);337338 const many = drawnFiles(339 decodeFiles(340 Array.from({ length: SERVER_FILES + 2 }, (_, index) =>341 added(`f${index}.ts`, 1)342 )343 )344 );345346 expect(prerenderedPaths(many).size).toBe(SERVER_FILES);347 });348});