Skip to content
Myr

code-prerender.test.tsx

This file

Path

apps/web/test/code-prerender.test.tsx

369 lines · 10.6 KiB · TypeScript

Last changed by

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

History of this file

Take it

Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2

lines 1–369why, one step back
1/**
2 * Code the server sends highlighted (ADR 0027): a blob page's file and a3 * commit page's first files, drawn by `@pierre/diffs/ssr` into a4 * declarative shadow root, in a fixed set of languages and within the5 * server's own limit; anything else is sent as plain text, as before.6 *7 * Each page is rendered as its route renders it on the server: the loader8 * draws the code ahead (`drawFileAhead`, `drawDiffAhead`), then the page9 * renders with the browser's drawing (`ClientFile`, `ClientDiffs`) holding10 * the server's fallback, which is all a server render shows.11 */12import { describe, expect, it } from "@effect/vitest";13import { ChangedFile, CommitDiff, FileView } from "@repo/protocol/domain/code";14import { ProjectName } from "@repo/protocol/ids";15import { DateTime, Effect, Schema } from "effect";16import { renderToStaticMarkup } from "react-dom/server";1718import { BlobView } from "../src/features/code/blob-view.tsx";19import { ClientDiffs, ClientFile } from "../src/features/code/client-code.tsx";20import { CommitView } from "../src/features/code/commit-view.tsx";21import { drawnFiles } from "../src/features/code/diff-model.ts";22import { PlainDiff } from "../src/features/code/plain-diff.tsx";23import { prerenderFile } from "../src/features/code/prerender-server.ts";24import {25 drawDiffAhead,26 drawFileAhead,27 prerenderedPaths,28 prerendersFile,29 SERVER_FILES,30 SERVER_LINES,31} from "../src/features/code/prerender.ts";32import { FileFallback } from "../src/features/code/server-code.tsx";3334const datekit = ProjectName.make("datekit");3536const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");3738const AT = "a".repeat(40);3940const decodeFile = Schema.decodeSync(FileView);4142const decodeFiles = Schema.decodeSync(Schema.Array(ChangedFile));4344/** A highlighted token, as Pierre draws one in the token theme. */45const TOKEN = /--diffs-token-light:var\(--diffs-token-[a-z-]+/gu;4647/** How many highlighted tokens `markup` holds. */48const tokensIn = (markup: string) => [...markup.matchAll(TOKEN)].length;4950/** How many server drawings `markup` holds. */51const shadowRootsIn = (markup: string) =>52 [...markup.matchAll(/<template shadowrootmode="open">/gu)].length;5354const TYPESCRIPT = [55 'import { fromIso } from "./iso.ts";',56 "",57 "/** A date from an ISO week string. */",58 "export const parse = (text: string): Date => fromIso(text);",59 "",60].join("\n");6162/** `count` lines of TypeScript. */63const linesOf = (count: number) =>64 Array.from(65 { length: count },66 (_, index) => `export const n${index} = ${index};`67 ).join("\n");6869let blobs = 0;7071/** A file at `path`, with a blob id of its own, so no drawing is shared. */72const fileAt = (path: string, text: string) => {73 blobs += 1;7475 return decodeFile({76 at: AT,77 binary: false,78 path,79 sha: blobs.toString(16).padStart(40, "0"),80 size: text.length,81 text,82 truncated: false,83 });84};8586/** The blob page's markup for `file`, as the server renders it once its loader has drawn the file. */87const blobPage = (file: FileView) =>88 Effect.gen(function* () {89 yield* Effect.promise(() => drawFileAhead(file));9091 const text = file.text ?? "";9293 return renderToStaticMarkup(94 <BlobView95 code={96 <ClientFile97 fallback={98 <FileFallback path={file.path} sha={file.sha} text={text} />99 }100 path={file.path}101 sha={file.sha}102 text={text}103 />104 }105 file={file}106 now={now}107 project={datekit}108 rev="main"109 />110 );111 });112113const signature = {114 at: "2026-10-06T15:00:00.000Z",115 email: "lin@example.com",116 name: "Lin",117};118119/** A commit changing `files`, imported (no landing). */120const commitOf = (files: readonly (typeof ChangedFile.Encoded)[]) =>121 Schema.decodeSync(CommitDiff)({122 commit: {123 author: signature,124 body: "",125 committer: signature,126 parents: ["2".repeat(40)],127 sha: "1".repeat(40),128 subject: "Parse ISO weeks",129 trailers: [],130 tree: "4".repeat(40),131 },132 files,133 truncated: false,134 });135136/** The commit page's markup, as the server renders it once its loader has drawn the first files. */137const commitPage = (diff: CommitDiff) =>138 Effect.gen(function* () {139 const drawn = drawnFiles(diff.files);140141 yield* Effect.promise(() => drawDiffAhead(diff.files));142143 return renderToStaticMarkup(144 <CommitView145 diff={diff}146 drawing={147 <ClientDiffs148 fallback={149 <PlainDiff150 drawn={drawn}151 files={diff.files}152 prerendered={prerenderedPaths(drawn)}153 />154 }155 files={diff.files}156 split={false}157 />158 }159 drawn={drawn}160 now={now}161 project={datekit}162 />163 );164 });165166/** The markup of one file's section of a diff. */167const sectionOf = (markup: string, path: string) =>168 new RegExp(169 `<section aria-label="${path.replaceAll(".", "\\.")}"[\\s\\S]*?</section>`,170 "u"171 ).exec(markup)?.[0] ?? "";172173/** An added file at `path`, `lines` long, with a blob id of its own. */174const added = (path: string, lines: number) => {175 blobs += 1;176177 return {178 after: blobs.toString(16).padStart(40, "0"),179 binary: false,180 newText: linesOf(lines),181 path,182 status: "added" as const,183 };184};185186describe("a blob page's code, as the server sends it", () => {187 it.effect(188 "holds a TypeScript file highlighted, in a declarative shadow root",189 () =>190 Effect.gen(function* () {191 const markup = yield* blobPage(fileAt("src/parse.ts", TYPESCRIPT));192193 expect(shadowRootsIn(markup)).toBe(1);194 expect(markup).toContain('data-code="prerendered"');195 expect(markup).toContain("<diffs-container");196 expect(tokensIn(markup)).toBeGreaterThan(5);197 expect(markup).not.toContain('data-code="plain"');198 })199 );200201 it.effect(202 "holds a file in a language the server does not highlight as numbered plain text",203 () =>204 Effect.gen(function* () {205 const markup = yield* blobPage(206 fileAt("src/parse.rs", "fn parse() -> u32 {\n 1\n}\n")207 );208209 expect(shadowRootsIn(markup)).toBe(0);210 expect(tokensIn(markup)).toBe(0);211 expect(markup).toContain('data-code="plain"');212 expect(markup).toContain('id="L1"');213 })214 );215216 it.effect(217 "holds a file past the server's limit as plain text: too many lines, or a line too long",218 () =>219 Effect.gen(function* () {220 const long = yield* blobPage(221 fileAt("src/long.ts", linesOf(SERVER_LINES + 1))222 );223224 const wide = yield* blobPage(225 fileAt("src/wide.ts", `export const wide = "${"x".repeat(1000)}";\n`)226 );227228 const within = yield* blobPage(229 fileAt("src/within.ts", linesOf(SERVER_LINES))230 );231232 expect([long, wide, within].map(shadowRootsIn)).toStrictEqual([233 0, 0, 1,234 ]);235 expect(long).toContain('data-code="plain"');236 expect(wide).toContain('data-code="plain"');237 })238 );239});240241describe("a commit page's diff, as the server sends it", () => {242 it.effect(243 "holds a TypeScript file's changes highlighted, and an unknown language's as plain lines",244 () =>245 Effect.gen(function* () {246 const markup = yield* commitPage(247 commitOf([248 {249 after: "a".repeat(40),250 before: "b".repeat(40),251 binary: false,252 newText: TYPESCRIPT.replace(253 "fromIso(text)",254 "fromIso(text.trim())"255 ),256 oldText: TYPESCRIPT,257 path: "src/parse.ts",258 status: "modified",259 },260 {261 after: "c".repeat(40),262 binary: false,263 newText: "fn week() -> u32 {\n 1\n}\n",264 path: "src/week.rs",265 status: "added",266 },267 ])268 );269270 const typescript = sectionOf(markup, "src/parse.ts");271 const rust = sectionOf(markup, "src/week.rs");272273 expect(shadowRootsIn(typescript)).toBe(1);274 expect(tokensIn(typescript)).toBeGreaterThan(5);275 expect(shadowRootsIn(rust)).toBe(0);276 expect(rust).toContain('data-line-type="addition"');277 expect(rust).toContain("fn week() -&gt; u32 {");278 })279 );280});281282describe("which code the server highlights", () => {283 it("highlights its languages by Pierre's names for them, and no other", () => {284 const highlighted = [285 "a.ts",286 "a.tsx",287 "a.js",288 "a.mjs",289 "a.cjs",290 "a.jsx",291 "a.json",292 "a.md",293 "a.yaml",294 "a.yml",295 "a.toml",296 "a.sh",297 "a.css",298 "a.html",299 ];300301 expect(302 highlighted.filter((path) => !prerendersFile({ path, text: "x" }))303 ).toStrictEqual([]);304 expect(305 ["a.rs", "a.py", "Makefile", "a.go", "a.txt"].filter((path) =>306 prerendersFile({ path, text: "x" })307 )308 ).toStrictEqual([]);309 });310311 it.effect("has a grammar for each of its languages, aliases included", () =>312 Effect.gen(function* () {313 const samples = {314 "a.css": "a { color: red; }",315 "a.html": '<p class="x">hi</p>',316 "a.js": "const a = 1;",317 "a.json": '{ "a": 1 }',318 "a.jsx": "const a = <p>hi</p>;",319 "a.md": "See [the docs](https://example.com).",320 "a.sh": 'echo "hi"',321 "a.toml": 'a = "b"',322 "a.ts": "const a: number = 1;",323 "a.tsx": "const a = <p>{1}</p>;",324 "a.yaml": "a: b",325 "a.yml": "a: b",326 };327328 const drawn = yield* Effect.forEach(329 Object.entries(samples),330 ([path, text]) =>331 prerenderFile({ path, sha: `grammar:${path}`, text }).pipe(332 Effect.map((html) => [path, tokensIn(html ?? "") > 0] as const)333 )334 );335336 expect(drawn.filter(([, highlighted]) => !highlighted)).toStrictEqual([]);337 })338 );339340 it("highlights a diff's first open files within its lines, never a folded one", () => {341 // `a` is folded (an added file past 80 lines starts so); `b` and `c`342 // fit together; `d` would pass the limit; `e` still fits after it.343 const drawn = drawnFiles(344 decodeFiles([345 added("a.ts", 90),346 added("b.ts", 60),347 added("c.ts", 60),348 added("d.ts", SERVER_LINES),349 added("e.ts", 10),350 ])351 );352353 expect([...prerenderedPaths(drawn)]).toStrictEqual([354 "b.ts",355 "c.ts",356 "e.ts",357 ]);358359 const many = drawnFiles(360 decodeFiles(361 Array.from({ length: SERVER_FILES + 2 }, (_, index) =>362 added(`f${index}.ts`, 1)363 )364 )365 );366367 expect(prerenderedPaths(many).size).toBe(SERVER_FILES);368 });369});