prerender-server.ts
This file
Path
apps/web/src/features/code/prerender-server.ts
159 lines · 5.5 KiB · TypeScript
Last changed by
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
History of this fileTake it
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 1–159why, one step back1/**2 * Code highlighted on the server: a file, or one file of a diff, drawn by3 * `@pierre/diffs/ssr` with the browser's own options (`pierre.ts`) into4 * the HTML of the drawing's shadow root, which the page sends as a5 * declarative shadow root. The browser's drawing later takes its place6 * with the same highlighting, so the reader sees the code once.7 *8 * Shiki runs on its JavaScript engine (a Worker compiles no WebAssembly),9 * and only with the grammars named here: the Worker's build resolves10 * `shiki` to core alone (`vite.config.ts`), so no other grammar is11 * bundled. Pierre will not resolve a grammar or a theme by name in a12 * Worker's global scope, so each is loaded here and attached to its13 * highlighter directly, once per isolate.14 *15 * Loaded on the server only, by `prerender.ts`, on a page's first16 * highlighted code: the Worker's entry carries none of it.17 */18import {19 attachResolvedLanguages,20 attachResolvedThemes,21 getSharedHighlighter,22} from "@pierre/diffs";23import type {24 FileContents,25 FileDiffMetadata,26 LanguageRegistration,27} from "@pierre/diffs";28import { preloadDiffHTML, preloadFile } from "@pierre/diffs/ssr";29import { Effect, Option } from "effect";30import { normalizeTheme } from "shiki/core";3132import type { DrawnFile } from "./diff-model.ts";33import {34 codeTheme,35 diffOptionsFor,36 diffsOptions,37 fileOptions,38} from "./pierre.ts";39import { serverLanguageOf } from "./prerender.ts";40import type { ServerLanguage } from "./prerender.ts";4142type Grammar = () => Promise<{ readonly default: LanguageRegistration[] }>;4344/** Each server language's grammar, loaded on first use; `yml` and `zsh` are aliases Pierre names. */45const GRAMMARS: Record<ServerLanguage, Grammar> = {46 css: () => import("shiki/langs/css.mjs"),47 html: () => import("shiki/langs/html.mjs"),48 javascript: () => import("shiki/langs/javascript.mjs"),49 json: () => import("shiki/langs/json.mjs"),50 jsx: () => import("shiki/langs/jsx.mjs"),51 markdown: () => import("shiki/langs/markdown.mjs"),52 toml: () => import("shiki/langs/toml.mjs"),53 tsx: () => import("shiki/langs/tsx.mjs"),54 typescript: () => import("shiki/langs/typescript.mjs"),55 yaml: () => import("shiki/langs/yaml.mjs"),56 yml: () => import("shiki/langs/yaml.mjs"),57 zsh: () => import("shiki/langs/shellscript.mjs"),58};5960/** The shared highlighter, with the token theme and `language`'s grammar attached. */61const highlighterFor = (language: ServerLanguage) =>62 Effect.gen(function* () {63 const highlighter = yield* Effect.tryPromise(() =>64 getSharedHighlighter({65 langs: [],66 preferredHighlighter: "shiki-js",67 themes: [],68 })69 );7071 const grammar = yield* Effect.tryPromise(GRAMMARS[language]);7273 // Each is attached once; Pierre skips one already attached. The theme74 // is normalized as Pierre normalizes a registered one.75 yield* Effect.try(() => {76 attachResolvedThemes(normalizeTheme(codeTheme()), highlighter);77 attachResolvedLanguages(78 { data: grammar.default, name: language },79 highlighter80 );81 });82 });8384/**85 * A drawing in `language`; if it fails, the same drawing as plain text, so86 * the page still sends Pierre's markup; none if that fails too.87 */88const draw = <E1, E2>(89 language: Option.Option<ServerLanguage>,90 highlighted: Effect.Effect<string, E1>,91 plain: Effect.Effect<string, E2>92): Effect.Effect<string | undefined> =>93 Option.match(language, {94 onNone: () => plain,95 onSome: (name) =>96 highlighterFor(name).pipe(97 Effect.andThen(highlighted),98 Effect.catchCause(() => plain)99 ),100 }).pipe(Effect.orElseSucceed((): string | undefined => undefined));101102/** A file drawn as `FileCode` draws it. */103const fileHtml = (file: FileContents) =>104 Effect.tryPromise(() => preloadFile({ file, options: fileOptions })).pipe(105 Effect.map(({ prerenderedHTML }) => prerenderedHTML)106 );107108/** One file, as `FileCode` draws it. */109export const prerenderFile = (file: {110 readonly path: string;111 readonly sha: string;112 readonly text: string;113}) => {114 const contents = { cacheKey: file.sha, contents: file.text, name: file.path };115116 return draw(117 serverLanguageOf(file.path),118 fileHtml(contents),119 fileHtml({ ...contents, lang: "text" })120 );121};122123/**124 * A diff's body drawn without Pierre's header (the page's own sits above125 * it) sits as it does in the browser's drawing: Pierre drops the code's126 * top gap only after a header, so the lines would otherwise start 8 px127 * lower, and it takes a scrollbar's width from the bottom gap only once128 * its script has measured one, so the next file would start 6 px higher.129 */130const UNDER_HEADER_CSS =131 "[data-code] { padding-top: 0; padding-bottom: var(--diffs-gap-block, var(--diffs-gap-fallback)); }";132133/** A diff's body drawn unified, as `DiffCode` draws it, without a header. */134const diffHtml = (fileDiff: FileDiffMetadata) =>135 Effect.tryPromise(() =>136 preloadDiffHTML({137 fileDiff,138 options: {139 ...diffOptionsFor(false),140 disableFileHeader: true,141 unsafeCSS: `${diffsOptions.unsafeCSS}\n${UNDER_HEADER_CSS}`,142 },143 })144 );145146/**147 * One file of a diff's body, unified, as `DiffCode` draws it, under the148 * page's own header: none for a file with no lines.149 */150export const prerenderDiff = (file: DrawnFile) =>151 Option.match(file.diff, {152 onNone: () => Effect.sync((): string | undefined => undefined),153 onSome: (diff) =>154 draw(155 serverLanguageOf(file.file.path),156 diffHtml(diff),157 diffHtml({ ...diff, lang: "text" })158 ),159 });