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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349import { describe, expect, it } from "@effect/vitest";import { ChangedFile, CommitDiff, FileView } from "@repo/protocol/domain/code";import { ProjectName } from "@repo/protocol/ids";import { DateTime, Effect, Schema } from "effect";import { renderToStaticMarkup } from "react-dom/server";
import { BlobView } from "../src/features/code/blob-view.tsx";import { ClientDiffs, ClientFile } from "../src/features/code/client-code.tsx";import { CommitView } from "../src/features/code/commit-view.tsx";import { drawnFiles } from "../src/features/code/diff-model.ts";import { PlainDiff } from "../src/features/code/plain-diff.tsx";import { prerenderFile } from "../src/features/code/prerender-server.ts";import { drawDiffAhead, drawFileAhead, prerenderedPaths, prerendersFile, SERVER_FILES, SERVER_LINES,} from "../src/features/code/prerender.ts";import { FileFallback } from "../src/features/code/server-code.tsx";
const datekit = ProjectName.make("oscabriel/datekit");
const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");
const AT = "a".repeat(40);
const decodeFile = Schema.decodeSync(FileView);
const decodeFiles = Schema.decodeSync(Schema.Array(ChangedFile));
const TOKEN = /--diffs-token-light:var\(--diffs-token-[a-z-]+/gu;
const tokensIn = (markup: string) => [...markup.matchAll(TOKEN)].length;
const shadowRootsIn = (markup: string) => [...markup.matchAll(/<template shadowrootmode="open">/gu)].length;
const TYPESCRIPT = [ 'import { fromIso } from "./iso.ts";', "", "/** A date from an ISO week string. */", "export const parse = (text: string): Date => fromIso(text);", "",].join("\n");
const linesOf = (count: number) => Array.from( { length: count }, (_, index) => `export const n${index} = ${index};` ).join("\n");
let blobs = 0;
const fileAt = (path: string, text: string) => { blobs += 1;
return decodeFile({ at: AT, binary: false, path, sha: blobs.toString(16).padStart(40, "0"), size: text.length, text, truncated: false, });};
const blobPage = (file: FileView) => Effect.gen(function* () { yield* Effect.promise(() => drawFileAhead(file));
const text = file.text ?? "";
return renderToStaticMarkup( <BlobView code={ <ClientFile fallback={ <FileFallback path={file.path} sha={file.sha} text={text} /> } path={file.path} sha={file.sha} text={text} /> } file={file} now={now} project={datekit} rev="main" /> ); });
const signature = { at: "2026-10-06T15:00:00.000Z", email: "lin@example.com", name: "Lin",};
const commitOf = (files: readonly (typeof ChangedFile.Encoded)[]) => Schema.decodeSync(CommitDiff)({ commit: { author: signature, body: "", committer: signature, parents: ["2".repeat(40)], sha: "1".repeat(40), subject: "Parse ISO weeks", trailers: [], tree: "4".repeat(40), }, files, truncated: false, });
const commitPage = (diff: CommitDiff) => Effect.gen(function* () { const drawn = drawnFiles(diff.files);
yield* Effect.promise(() => drawDiffAhead(diff.files));
return renderToStaticMarkup( <CommitView diff={diff} drawing={ <ClientDiffs fallback={ <PlainDiff drawn={drawn} files={diff.files} prerendered={prerenderedPaths(drawn)} /> } files={diff.files} split={false} /> } drawn={drawn} now={now} project={datekit} /> ); });
const sectionOf = (markup: string, path: string) => new RegExp( `<section aria-label="${path.replaceAll(".", "\\.")}"[\\s\\S]*?</section>`, "u" ).exec(markup)?.[0] ?? "";
const added = (path: string, lines: number) => { blobs += 1;
return { after: blobs.toString(16).padStart(40, "0"), binary: false, newText: linesOf(lines), path, status: "added" as const, };};
describe("a blob page's code, as the server sends it", () => { it.effect( "holds a TypeScript file highlighted, in a declarative shadow root", () => Effect.gen(function* () { const markup = yield* blobPage(fileAt("src/parse.ts", TYPESCRIPT));
expect(shadowRootsIn(markup)).toBe(1); expect(markup).toContain('data-code="prerendered"'); expect(markup).toContain("<diffs-container"); expect(tokensIn(markup)).toBeGreaterThan(5); expect(markup).not.toContain('data-code="plain"'); }) );
it.effect( "holds a file in a language the server does not highlight as numbered plain text", () => Effect.gen(function* () { const markup = yield* blobPage( fileAt("src/parse.rs", "fn parse() -> u32 {\n 1\n}\n") );
expect(shadowRootsIn(markup)).toBe(0); expect(tokensIn(markup)).toBe(0); expect(markup).toContain('data-code="plain"'); expect(markup).toContain('id="L1"'); }) );
it.effect( "holds a file past the server's limit as plain text: too many lines, or a line too long", () => Effect.gen(function* () { const long = yield* blobPage( fileAt("src/long.ts", linesOf(SERVER_LINES + 1)) );
const wide = yield* blobPage( fileAt("src/wide.ts", `export const wide = "${"x".repeat(1000)}";\n`) );
const within = yield* blobPage( fileAt("src/within.ts", linesOf(SERVER_LINES)) );
expect([long, wide, within].map(shadowRootsIn)).toStrictEqual([ 0, 0, 1, ]); expect(long).toContain('data-code="plain"'); expect(wide).toContain('data-code="plain"'); }) );});
describe("a commit page's diff, as the server sends it", () => { it.effect( "holds a TypeScript file's changes highlighted, and an unknown language's as plain lines", () => Effect.gen(function* () { const markup = yield* commitPage( commitOf([ { after: "a".repeat(40), before: "b".repeat(40), binary: false, newText: TYPESCRIPT.replace( "fromIso(text)", "fromIso(text.trim())" ), oldText: TYPESCRIPT, path: "src/parse.ts", status: "modified", }, { after: "c".repeat(40), binary: false, newText: "fn week() -> u32 {\n 1\n}\n", path: "src/week.rs", status: "added", }, ]) );
const typescript = sectionOf(markup, "src/parse.ts"); const rust = sectionOf(markup, "src/week.rs");
expect(shadowRootsIn(typescript)).toBe(1); expect(tokensIn(typescript)).toBeGreaterThan(5); expect(shadowRootsIn(rust)).toBe(0); expect(rust).toContain('data-line-type="addition"'); expect(rust).toContain("fn week() -> u32 {"); }) );});
describe("which code the server highlights", () => { it("highlights its languages by Pierre's names for them, and no other", () => { const highlighted = [ "a.ts", "a.tsx", "a.js", "a.mjs", "a.cjs", "a.jsx", "a.json", "a.md", "a.yaml", "a.yml", "a.toml", "a.sh", "a.css", "a.html", ];
expect( highlighted.filter((path) => !prerendersFile({ path, text: "x" })) ).toStrictEqual([]); expect( ["a.rs", "a.py", "Makefile", "a.go", "a.txt"].filter((path) => prerendersFile({ path, text: "x" }) ) ).toStrictEqual([]); });
it.effect("has a grammar for each of its languages, aliases included", () => Effect.gen(function* () { const samples = { "a.css": "a { color: red; }", "a.html": '<p class="x">hi</p>', "a.js": "const a = 1;", "a.json": '{ "a": 1 }', "a.jsx": "const a = <p>hi</p>;", "a.md": "See [the docs](https://example.com).", "a.sh": 'echo "hi"', "a.toml": 'a = "b"', "a.ts": "const a: number = 1;", "a.tsx": "const a = <p>{1}</p>;", "a.yaml": "a: b", "a.yml": "a: b", };
const drawn = yield* Effect.forEach( Object.entries(samples), ([path, text]) => prerenderFile({ path, sha: `grammar:${path}`, text }).pipe( Effect.map((html) => [path, tokensIn(html ?? "") > 0] as const) ) );
expect(drawn.filter(([, highlighted]) => !highlighted)).toStrictEqual([]); }) );
it("highlights a diff's first open files within its lines, never a folded one", () => { // `a` is folded (an added file past 80 lines starts so); `b` and `c` // fit together; `d` would pass the limit; `e` still fits after it. const drawn = drawnFiles( decodeFiles([ added("a.ts", 90), added("b.ts", 60), added("c.ts", 60), added("d.ts", SERVER_LINES), added("e.ts", 10), ]) );
expect([...prerenderedPaths(drawn)]).toStrictEqual([ "b.ts", "c.ts", "e.ts", ]);
const many = drawnFiles( decodeFiles( Array.from({ length: SERVER_FILES + 2 }, (_, index) => added(`f${index}.ts`, 1) ) ) );
expect(prerenderedPaths(many).size).toBe(SERVER_FILES); });});