|
| 1 | +import { prisma_highlighter } from "@/lib/shiki_prisma"; |
| 2 | +import type { HighlightedCode } from "codehike/code"; |
| 3 | +import type { CSSProperties } from "react"; |
| 4 | +import { journeySteps, type JourneyStep } from "./journey-steps"; |
| 5 | + |
| 6 | +/** Code Hike token: plain text, or [text, color, style?]. */ |
| 7 | +type CodeToken = string | [string, string, CSSProperties?]; |
| 8 | + |
| 9 | +/** |
| 10 | + * Tokenize with the site's shiki `prisma-dark` theme (CSS-variable colors, so |
| 11 | + * it adapts to both themes) and re-shape into Code Hike's token format. Tokens |
| 12 | + * are split per word because Code Hike's transitions move tokens |
| 13 | + * independently; coarser tokens make the animation lurch. |
| 14 | + */ |
| 15 | +function toCodeTokens(text: string, color: string, out: CodeToken[]) { |
| 16 | + for (const part of text.split(/(\s+)/)) { |
| 17 | + if (!part) continue; |
| 18 | + if (/^\s+$/.test(part)) { |
| 19 | + out.push(part); |
| 20 | + } else { |
| 21 | + out.push([part, color]); |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +async function highlightStep(code: string, lang: JourneyStep["lang"]): Promise<HighlightedCode> { |
| 27 | + const tokens: CodeToken[] = []; |
| 28 | + if (lang === "text") { |
| 29 | + // Plain-text steps (the project tree): names in the normal code color, |
| 30 | + // trailing `# …` annotations dimmed like comments. |
| 31 | + code.split("\n").forEach((line, index) => { |
| 32 | + if (index > 0) tokens.push("\n"); |
| 33 | + const hash = line.indexOf("# "); |
| 34 | + if (hash > -1) { |
| 35 | + toCodeTokens(line.slice(0, hash), "var(--color-foreground-neutral-weak)", tokens); |
| 36 | + toCodeTokens(line.slice(hash), "var(--color-disabled)", tokens); |
| 37 | + } else { |
| 38 | + toCodeTokens(line, "var(--color-foreground-neutral-weak)", tokens); |
| 39 | + } |
| 40 | + }); |
| 41 | + } else { |
| 42 | + const highlighter = await prisma_highlighter(); |
| 43 | + const lines = highlighter.codeToTokensBase(code, { |
| 44 | + lang, |
| 45 | + theme: highlighter.getTheme("prisma-dark"), |
| 46 | + }); |
| 47 | + lines.forEach((line, index) => { |
| 48 | + if (index > 0) tokens.push("\n"); |
| 49 | + for (const token of line) { |
| 50 | + toCodeTokens(token.content, token.color ?? "currentColor", tokens); |
| 51 | + } |
| 52 | + }); |
| 53 | + } |
| 54 | + return { |
| 55 | + tokens, |
| 56 | + code, |
| 57 | + lang, |
| 58 | + meta: "", |
| 59 | + themeName: "prisma-dark", |
| 60 | + style: {}, |
| 61 | + annotations: [], |
| 62 | + } as unknown as HighlightedCode; |
| 63 | +} |
| 64 | + |
| 65 | +/** Highlight every journey step on the server; the player receives plain data. */ |
| 66 | +export async function highlightJourney(): Promise<HighlightedCode[]> { |
| 67 | + return Promise.all(journeySteps.map((step) => highlightStep(step.code, step.lang))); |
| 68 | +} |
0 commit comments