The best way to control Claude Code, Codex and more from any computer or phone

main
ts 755 lines 27.8 KB
Raw
1 /**
2 * Resolves `intro/steps.ts` into `out/capture/intro/intro.json` for Remotion:
3 *
4 * - type-checks every file in `snippets/` with the real compiler: normal
5 * files must pass; `*.error.ts` files must fail, and their error is shown
6 * - cuts each snippet down to its `// #region` blocks
7 * - highlights code with Shiki (VS Code's Dark+ colours)
8 * - turns text anchors for marks, tints and errors into line/column ranges
9 *
10 * pnpm intro:build
11 */
12 import { cp, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
13 import path from "node:path";
14 import { diffArrays } from "diff";
15 import { createHighlighter } from "shiki";
16 import { API } from "tsgo/unstable/sync";
17 import type {
18 CodeError,
19 CodeStep,
20 IntroJson,
21 IntroStep,
22 Mark,
23 RollStep,
24 Token,
25 } from "../shared/intro.ts";
26 import type { CodeSpec, Find, StepSpec } from "./steps.ts";
27
28 /** Which deck to build: `intro` (intro/steps.ts) or `loop` (intro/loop.ts). */
29 const deckName = process.argv[2] ?? "intro";
30 const decks: Record<string, () => Promise<StepSpec[]>> = {
31 intro: async () => (await import("./steps.ts")).steps,
32 loop: async () => (await import("./loop.ts")).steps,
33 };
34 if (!decks[deckName])
35 throw new Error(`unknown deck ${deckName}: expected ${Object.keys(decks).join(" | ")}`);
36 const steps = await decks[deckName]();
37
38 const root = path.resolve(import.meta.dirname, "..");
39 const snippetsDir = path.join(import.meta.dirname, "snippets");
40 /** Snippet diagnostics and shared assets live with the intro deck. */
41 const shared = path.join(root, "out", "capture", "intro");
42 const out = path.join(root, "out", "capture", deckName);
43
44 // ── type-check the snippets ──────────────────────────────────────────────
45 // With the tsgo 7.1 nightly's API: open the snippets project in a snapshot
46 // and read each file's diagnostics (needs Node; the API's sync channel
47 // doesn't run under Bun).
48 interface Diagnostic {
49 line: number;
50 col: number;
51 code: string;
52 message: string[];
53 }
54 interface Chain {
55 text: string;
56 messageChain?: Chain[];
57 }
58 const flatten = (chain: Chain, depth = 0): string[] => [
59 chain.text,
60 ...(chain.messageChain ?? []).flatMap((child) => flatten(child, depth + 1)),
61 ];
62
63 // Type-checking is the slow part; skip it when no snippet changed since the last build.
64 const cacheFile = path.join(shared, "diagnostics.json");
65 /** Sub-projects with their own tsconfig (e.g. the demo's `shorty/` app), checked as a unit. */
66 const projects = [
67 "",
68 ...(await readdir(snippetsDir, { withFileTypes: true }))
69 .filter((d) => d.isDirectory())
70 .map((d) => d.name),
71 ];
72 const listTs = async (dir: string) =>
73 (await readdir(path.join(snippetsDir, dir)))
74 .filter((f) => f.endsWith(".ts"))
75 .map((f) => (dir ? `${dir}/${f}` : f));
76 const snippetNames = [
77 ...(await Promise.all(projects.map(listTs))).flat(),
78 ...projects.map((p) => (p ? `${p}/tsconfig.json` : "tsconfig.json")),
79 ];
80 const stamp = (
81 await Promise.all(
82 snippetNames.map(async (f) => `${f}:${(await stat(path.join(snippetsDir, f))).mtimeMs}`),
83 )
84 ).join("|");
85 const cached = await readFile(cacheFile, "utf8").then(
86 (t) => JSON.parse(t) as { stamp: string; diagnostics: [string, Diagnostic[]][] },
87 () => undefined,
88 );
89 const diagnostics = new Map<string, Diagnostic[]>(
90 cached?.stamp === stamp ? cached.diagnostics : [],
91 );
92 if (cached?.stamp !== stamp) {
93 console.log("● type-checking intro/snippets (tsgo)");
94 const api = new API({ cwd: snippetsDir });
95 const configs = projects.map((p) => path.join(snippetsDir, p, "tsconfig.json"));
96 const snapshot = api.createSnapshot({ openProjects: configs });
97 for (const [i, dir] of projects.entries()) {
98 const project = snapshot.getConfiguredProject(configs[i]!);
99 if (!project) throw new Error(`could not open ${configs[i]}`);
100 for (const file of await listTs(dir)) {
101 const full = path.join(snippetsDir, file);
102 const list = [
103 ...project.program.getSyntacticDiagnostics(full),
104 ...project.program.getSemanticDiagnostics(full),
105 ] as unknown as (Chain & {
106 code: number;
107 startPosition: { line: number; character: number };
108 })[];
109 diagnostics.set(
110 file,
111 list.map((d) => ({
112 line: d.startPosition.line,
113 col: d.startPosition.character,
114 code: `TS${d.code}`,
115 message: flatten(d),
116 })),
117 );
118 }
119 }
120 api.close();
121 await mkdir(shared, { recursive: true });
122 await writeFile(cacheFile, JSON.stringify({ stamp, diagnostics: [...diagnostics] }));
123 }
124
125 const snippetFiles = (await Promise.all(projects.map(listTs))).flat();
126 for (const file of snippetFiles) {
127 const list = diagnostics.get(file) ?? [];
128 const errorFile = file.endsWith(".error.ts");
129 if (errorFile && list.length === 0)
130 throw new Error(`${file} is expected to fail type-checking, but it passes`);
131 if (!errorFile && list.length > 0) {
132 throw new Error(
133 `${file} must type-check:\n${list.map((d) => ` ${d.line + 1}:${d.col + 1} ${d.message.join("\n ")}`).join("\n")}`,
134 );
135 }
136 }
137
138 // ── snippets: keep only the named regions ────────────────────────────────
139 const REGION = /^\s*\/\/ #(end)?region\b/;
140 /** Code that must be there to type-check but isn't worth showing: `/*hide*\/ … /*end*\/`. */
141 const HIDDEN = /\/\*hide\*\/.*?\/\*end\*\//g;
142 /** `// @slide code` is a comment in the real file and `code` on the slide (e.g. a stand-in closing line). */
143 const SLIDE_ONLY = /^(\s*)\/\/ @slide (.*)$/;
144 interface Cut {
145 code: string;
146 /** Snippet line (0-based) of each kept line. */
147 origin: number[];
148 regions: Map<string, [number, number]>;
149 }
150 const cut = (text: string, keep?: string[], omit: string[] = [], fold: string[] = []): Cut => {
151 const lines = text.split("\n");
152 const open: string[] = [];
153 const kept: string[] = [];
154 const origin: number[] = [];
155 const regions = new Map<string, [number, number]>();
156 const starts = new Map<string, number>();
157 /** Lines of a folded region, collapsed to one line (like an editor fold) when it closes. */
158 let folding: { name: string; lines: [string, number][] } | undefined;
159 lines.forEach((line, i) => {
160 const marker = line.match(/^\s*\/\/ #(end)?region\s+(\S+)/);
161 if (marker) {
162 const name = marker[2]!;
163 if (marker[1] && folding?.name === name) {
164 const body = folding.lines.filter(([l]) => l.trim());
165 for (const [l, o] of folding.lines) {
166 if (l.trim()) break;
167 kept.push(l);
168 origin.push(o);
169 }
170 if (body.length) {
171 const first = body[0]![0].replace(/\s+$/, "");
172 const last = body.at(-1)![0].trim();
173 kept.push(body.length > 1 ? `${first} … ${last}` : first);
174 origin.push(body[0]![1]);
175 }
176 folding = undefined;
177 } else if (!marker[1] && fold.includes(name) && !omit.some((n) => open.includes(n))) {
178 folding = { name, lines: [] };
179 }
180 if (marker[1]) {
181 open.splice(open.lastIndexOf(name), 1);
182 regions.set(name, [starts.get(name)!, kept.length - 1]);
183 } else {
184 open.push(name);
185 starts.set(name, kept.length);
186 }
187 return;
188 }
189 if (REGION.test(line)) return;
190 // Not written yet: gone without a trace.
191 if (omit.some((name) => open.includes(name))) return;
192 if (keep && !keep.some((name) => open.includes(name))) {
193 // Skipped code shows as one "…" line, indented like the code it stands for.
194 // Only inside `show` (the whole excerpt): code outside it is never on screen.
195 if (line.trim() && open.includes("show") && kept.at(-1)?.trim() !== "…") {
196 kept.push(`${line.match(/^\s*/)![0]}…`);
197 origin.push(i);
198 }
199 return;
200 }
201 if (folding) {
202 folding.lines.push([line.replace(SLIDE_ONLY, "$1$2").replace(HIDDEN, ""), i]);
203 return;
204 }
205 kept.push(line.replace(SLIDE_ONLY, "$1$2").replace(HIDDEN, ""));
206 origin.push(i);
207 });
208 // Drop the shared indentation and blank edges, and a "…" standing for the file's tail.
209 while (kept.length && !kept[0]!.trim()) (kept.shift(), origin.shift());
210 while (kept.length && (!kept.at(-1)!.trim() || kept.at(-1)!.trim() === "…"))
211 (kept.pop(), origin.pop());
212 return { code: kept.join("\n"), origin, regions };
213 };
214
215 // ── highlighting ─────────────────────────────────────────────────────────
216 const highlighter = await createHighlighter({
217 themes: ["dark-plus"],
218 langs: ["typescript", "yaml", "shellscript", "json"],
219 });
220 const PSEUDO_KEYWORDS: Record<string, string> = { construct: "#a3c473", runtime: "#e0a86b" };
221 const tokenize = (
222 code: string,
223 pseudo: boolean,
224 lang: "typescript" | "yaml" | "ansi" | "shellscript" | "json" = "typescript",
225 ): Token[][] =>
226 highlighter.codeToTokens(code, { lang, theme: "dark-plus" }).tokens.map((line) =>
227 line.flatMap((token) => {
228 // Shiki's FontStyle.Bold is bit 2 (terminal output uses it).
229 const bold = ((token.fontStyle ?? 0) & 2) !== 0 || undefined;
230 if (!pseudo)
231 return [
232 { text: token.content, color: token.color ?? "#d4d4d4", ...(bold ? { bold } : {}) },
233 ];
234 // The imagined language's own keywords.
235 return token.content
236 .split(/\b(construct|runtime)\b/)
237 .flatMap((text, i) =>
238 text
239 ? [{ text, color: i % 2 ? PSEUDO_KEYWORDS[text]! : (token.color ?? "#d4d4d4") }]
240 : [],
241 );
242 }),
243 );
244
245 // ── anchors ──────────────────────────────────────────────────────────────
246 const locate = (code: string, find: Find, title: string) => {
247 const { text, nth = 1 } = typeof find === "string" ? { text: find } : find;
248 let at = -1;
249 for (let i = 0; i < nth; i++) {
250 at = code.indexOf(text, at + 1);
251 if (at < 0)
252 throw new Error(`step "${title}": ${JSON.stringify(text)} not found (occurrence ${i + 1})`);
253 }
254 const before = code.slice(0, at);
255 const line = before.split("\n").length - 1;
256 return { line, col: at - (before.lastIndexOf("\n") + 1), len: text.length };
257 };
258
259 /** `split`: shown as one of two side-by-side panes, so it gets half the width. */
260 const resolveCode = async (spec: CodeSpec, split = false): Promise<CodeStep> => {
261 let code: string;
262 let raw: string | undefined;
263 let regions = new Map<string, [number, number]>();
264 let error: CodeError | undefined;
265 if ("snippet" in spec.src) {
266 const file = path.join(snippetsDir, spec.src.snippet);
267 const text = await readFile(file, "utf8");
268 const c = cut(text, spec.src.regions, spec.src.omit, spec.src.fold);
269 code = c.code;
270 regions = c.regions;
271 const list = diagnostics.get(spec.src.snippet) ?? [];
272 if (spec.src.snippet.endsWith(".error.ts") && !spec.error?.hide) {
273 // The diagnostic to show: the first whose message `pick` keeps anything from.
274 const d =
275 (spec.error?.pick && list.find((x) => spec.error!.pick!(x.message).length > 0)) || list[0]!;
276 const line = c.origin.indexOf(d.line);
277 if (line < 0) throw new Error(`step "${spec.title}": the error is outside the shown regions`);
278 const shown = spec.error?.pick ? spec.error.pick(d.message) : d.message.slice(0, 2);
279 // Underline to the end of the error's line, like the editor's squiggle.
280 const lineText = code.split("\n")[line]!;
281 const indent =
282 text.split("\n")[d.line]!.length -
283 text.split("\n")[d.line]!.trimStart().length -
284 (lineText.length - lineText.trimStart().length);
285 const col = Math.max(0, d.col - indent);
286 error = {
287 line,
288 col,
289 len: Math.max(1, lineText.length - col),
290 code: d.code,
291 message: shown,
292 below: spec.error?.below,
293 };
294 }
295 } else {
296 code = spec.src.code;
297 }
298 // Terminal output: marks and sizing work on the text as shown, without escapes.
299 if (spec.lang === "ansi") {
300 raw = code;
301 code = code.replace(/\x1b\[[0-9;]*m/g, "");
302 }
303 const lineOf = (find: Find) => locate(code, find, spec.title).line;
304 const tints = (spec.tints ?? []).map((tint) => {
305 if ("region" in tint) {
306 const r = regions.get(tint.region);
307 if (!r) throw new Error(`step "${spec.title}": no region ${tint.region}`);
308 return { from: r[0], to: r[1], tone: tint.tone };
309 }
310 const from = lineOf(tint.from);
311 return { from, to: tint.to ? lineOf(tint.to) : from, tone: tint.tone };
312 });
313 const marks: Mark[] = (spec.marks ?? []).map((mark) => {
314 const at = locate(code, mark.find, spec.title);
315 return {
316 kind: mark.kind,
317 ...at,
318 ...(mark.to ? { toLine: lineOf(mark.to) } : {}),
319 label: mark.label,
320 side: mark.side,
321 tone: mark.tone,
322 arrow: mark.arrow,
323 };
324 });
325 const lines = tokenize(raw ?? code, !!spec.pseudo, spec.lang);
326 const beside = spec.beside
327 ? await resolveCode(
328 { kind: "code", title: spec.title, group: spec.group, ...spec.beside },
329 true,
330 )
331 : undefined;
332 const besideCode = beside?.lines.map((l) => l.map((t) => t.text).join("")).join("\n") ?? "";
333 const links = (spec.links ?? []).map((link) => ({
334 from: locate(code, link.from, spec.title),
335 to: locate(besideCode, link.to, spec.title),
336 tone: link.tone,
337 }));
338 const underStep = spec.under
339 ? await resolveCode(
340 {
341 kind: "code",
342 title: spec.title,
343 group: `${spec.group}-under`,
344 file: spec.under.file,
345 src: spec.under.src,
346 lang: spec.under.lang,
347 marks: spec.under.marks,
348 fontSize: spec.fontSize,
349 },
350 true,
351 )
352 : undefined;
353 const underCode = underStep?.lines.map((l) => l.map((t) => t.text).join("")).join("\n") ?? "";
354 const under =
355 spec.under && underStep
356 ? {
357 step: underStep,
358 label: spec.under.label,
359 links: spec.under.links?.map((link) => ({
360 from: locate(underCode, link.from, spec.title),
361 to: locate(besideCode, link.to, spec.title),
362 tone: link.tone,
363 })),
364 }
365 : undefined;
366 const longest = Math.max(...code.split("\n").map((l) => l.length));
367 // Fit the code: at most 30px, smaller for long files, larger for short snippets.
368 const erroring =
369 "snippet" in spec.src &&
370 spec.src.snippet.endsWith(".error.ts") &&
371 !spec.error?.hide &&
372 !spec.error?.below;
373 const available =
374 split || spec.beside
375 ? 760
376 : spec.panel || spec.drill || spec.req || spec.bundle || erroring
377 ? 1060
378 : 1560;
379 const fontSize =
380 spec.fontSize ??
381 Math.max(
382 18,
383 Math.min(
384 34,
385 Math.floor(available / (longest * 0.6)),
386 Math.floor(780 / (lines.length * 1.55)),
387 ),
388 );
389 widthFor.set(lines, available);
390 return {
391 kind: "code",
392 title: spec.title,
393 notes: spec.notes ?? "",
394 group: spec.group,
395 file: spec.file,
396 pseudo: spec.pseudo,
397 lines,
398 fontSize,
399 tints,
400 focus: spec.focus
401 ? { from: lineOf(spec.focus.from), to: lineOf(spec.focus.to ?? spec.focus.from) }
402 : undefined,
403 marks,
404 error,
405 panel: spec.panel,
406 diagram: spec.diagram,
407 timeline: spec.timeline,
408 drill: spec.drill,
409 req: spec.req,
410 bundle: spec.bundle,
411 beside,
412 links: links.length ? links : undefined,
413 under,
414 aside: spec.aside,
415 cross: spec.cross,
416 diagramLinks: spec.diagramLinks?.map((link) => ({
417 ...link,
418 from: locate(code, link.from, spec.title),
419 })),
420 quiet: spec.quiet,
421 reel: spec.reel,
422 layer: spec.layer,
423 frames: spec.frames ?? 30,
424 };
425 };
426
427 /** The width each code block was fitted to, so it can be refitted after removed lines are added. */
428 const widthFor = new WeakMap<Token[][], number>();
429
430 const resolved: IntroStep[] = [];
431 for (const spec of steps) {
432 if (spec.kind === "code") resolved.push(await resolveCode(spec));
433 else if (spec.kind === "slide") {
434 resolved.push({
435 kind: "slide",
436 title: spec.title,
437 notes: spec.notes ?? "",
438 layout: spec.layout ?? "section",
439 eyebrow: spec.eyebrow,
440 heading: spec.heading,
441 subtitle: spec.subtitle,
442 footer: spec.footer,
443 frames: spec.frames ?? 60,
444 });
445 } else if (spec.kind === "terminal") {
446 const lines = tokenize(spec.lines, false, "ansi");
447 resolved.push({
448 kind: "terminal",
449 title: spec.title,
450 notes: spec.notes ?? "",
451 group: spec.group ?? "terminal",
452 tabs: spec.tabs,
453 active: spec.active,
454 lines,
455 fresh: spec.fresh ?? lines.length,
456 progress: spec.progress
457 ? {
458 rows: spec.progress.rows,
459 done: tokenize(spec.progress.done, false, "ansi"),
460 at: spec.progress.at,
461 }
462 : undefined,
463 // New lines appear two frames apart; hold until the last one has faded in (or the deploy finishes).
464 frames:
465 spec.frames ??
466 Math.max(
467 24,
468 (spec.fresh ?? lines.length) * 2 + 8,
469 spec.progress ? spec.progress.at + 12 : 0,
470 ),
471 });
472 } else if (spec.kind === "roll") {
473 const fill = (values: string[]) =>
474 spec.template.replace(/⟨(\d+)⟩/g, (_, i) => values[Number(i)]!);
475 const verify = async (values: string[], check: string) => {
476 const shown = cut(await readFile(path.join(snippetsDir, check), "utf8"), ["show"]).code;
477 if (shown.trim() !== fill(values).trim()) {
478 throw new Error(
479 `roll "${spec.title}": template doesn't match ${check}\n--- roll\n${fill(values)}\n--- snippet\n${shown}`,
480 );
481 }
482 if ((diagnostics.get(check) ?? []).length)
483 throw new Error(`roll "${spec.title}": ${check} has type errors`);
484 };
485 for (const value of spec.spin?.through ?? []) {
486 if (!spec.spin!.check) continue;
487 const values = [...spec.values];
488 values[spec.spin!.slot] = value;
489 await verify(values, spec.spin!.check(value));
490 }
491 let code = "";
492 const slots: { line: number; start: number; end: number }[] = [];
493 for (const part of spec.template.split(/(⟨\d+⟩)/)) {
494 const m = /^⟨(\d+)⟩$/.exec(part);
495 if (!m) {
496 code += part;
497 continue;
498 }
499 const value = spec.values[Number(m[1])];
500 if (value === undefined || value.includes("\n"))
501 throw new Error(`roll "${spec.title}": bad value for slot ${m[1]}`);
502 const lines = code.split("\n");
503 const start = lines.at(-1)!.length;
504 slots[Number(m[1])] = { line: lines.length - 1, start, end: start + value.length };
505 code += value;
506 }
507 if (spec.check) await verify(spec.values, spec.check);
508 resolved.push({
509 kind: "roll",
510 title: spec.title,
511 notes: spec.notes ?? "",
512 group: spec.group,
513 file: spec.file,
514 fontSize: spec.fontSize ?? 30,
515 lines: tokenize(code, false),
516 slots,
517 beside: spec.beside
518 ? {
519 file: spec.beside.file,
520 lines: tokenize(spec.beside.code, false, spec.beside.lang ?? "yaml"),
521 }
522 : undefined,
523 reel: spec.reel,
524 spin: spec.spin
525 ? {
526 slot: spec.spin.slot,
527 through: spec.spin.through,
528 reelFrom: spec.reel ? spec.reel.at - spec.spin.through.length : 0,
529 }
530 : undefined,
531 frames: spec.frames ?? (spec.spin ? 30 + spec.spin.through.length * 6 : 24),
532 });
533 } else if (spec.kind === "browser") {
534 resolved.push({
535 kind: "browser",
536 title: spec.title,
537 notes: spec.notes ?? "",
538 url: spec.url,
539 image: spec.image,
540 frames: spec.frames ?? 20,
541 });
542 } else if (spec.kind === "pyramid") {
543 const side = spec.side?.map((note) =>
544 note.code ? { ...note, tokens: tokenize(note.text, false) } : note,
545 );
546 resolved.push({ ...spec, side, notes: spec.notes ?? "", frames: spec.frames ?? 60 });
547 } else {
548 resolved.push({ ...spec, notes: spec.notes ?? "", frames: spec.frames ?? 60 });
549 }
550 }
551
552 // Diffs: when a file comes back changed, show what changed as -/+ lines.
553 {
554 const lastOf = new Map<string, CodeStep>();
555 const textOf = (line: Token[]) => line.map((t) => t.text).join("");
556 steps.forEach((spec, i) => {
557 const step = resolved[i]!;
558 if (spec.kind !== "code" || step.kind !== "code") return;
559 const key = `${step.group}|${step.file ?? ""}`;
560 const prev = lastOf.get(key);
561 lastOf.set(key, step);
562 if (!prev || step.quiet || step.tints.length > 0 || step.beside) return;
563 const before = prev.lines.filter(
564 (l) =>
565 !prev.diff?.[prev.lines.indexOf(l)] || prev.diff[prev.lines.indexOf(l)]!.kind !== "del",
566 );
567 const parts = diffArrays(before.map(textOf), step.lines.map(textOf), {
568 comparator: (a: string, b: string) => a.trim() === b.trim(),
569 });
570 const same = parts
571 .filter((p) => !p.added && !p.removed)
572 .reduce((n, p) => n + p.value.filter((l: string) => l.trim()).length, 0);
573 const changes = parts.some(
574 (p) => (p.added || p.removed) && p.value.some((l: string) => l.trim()),
575 );
576 // Only an edit: when most of the code is new, it's a different snippet.
577 if (!changes || same < before.filter((l) => textOf(l).trim()).length / 2) return;
578 const lines: Token[][] = [];
579 const diff: NonNullable<CodeStep["diff"]> = [];
580 const remap = new Map<number, number>();
581 let b = 0;
582 let a = 0;
583 for (let k = 0; k < parts.length; k++) {
584 const part = parts[k]!;
585 if (!part.added && !part.removed) {
586 for (let n = 0; n < part.count!; n++)
587 (remap.set(a, lines.length), lines.push(step.lines[a++]!), diff.push(null), b++);
588 } else if (part.removed) {
589 const next = parts[k + 1];
590 const rewritten = next?.added && next.count === part.count ? next : undefined;
591 const spans: { start: number; end: number }[] = [];
592 for (let n = 0; n < part.count!; n++) {
593 const old = before[b + n]!;
594 if (rewritten) {
595 // The part of the line that changed, when it's a small edit.
596 const x = textOf(old);
597 const y = textOf(step.lines[a + n]!);
598 let pre = 0;
599 while (pre < x.length && pre < y.length && x[pre] === y[pre]) pre++;
600 let suf = 0;
601 while (
602 suf < x.length - pre &&
603 suf < y.length - pre &&
604 x[x.length - 1 - suf] === y[y.length - 1 - suf]
605 )
606 suf++;
607 spans.push({ start: pre, end: y.length - suf });
608 const small = pre + suf >= Math.max(x.length, y.length) * 0.4;
609 void small;
610 }
611 // Removed lines are only shown when a step asks for them.
612 if (spec.showRemoved && textOf(old).trim()) {
613 const x = textOf(old);
614 const y = rewritten ? textOf(step.lines[a + n]!) : "";
615 let pre = 0;
616 while (pre < x.length && pre < y.length && x[pre] === y[pre]) pre++;
617 let suf = 0;
618 while (
619 suf < x.length - pre &&
620 suf < y.length - pre &&
621 x[x.length - 1 - suf] === y[y.length - 1 - suf]
622 )
623 suf++;
624 const cut =
625 rewritten && x.length - suf > pre ? { start: pre, end: x.length - suf } : {};
626 lines.push(old);
627 diff.push({ kind: "del", ...cut });
628 }
629 }
630 b += part.count!;
631 if (rewritten) {
632 for (let n = 0; n < rewritten.count!; n++) {
633 const x = textOf(before[b - part.count! + n]!);
634 const y = textOf(step.lines[a]!);
635 const { start, end } = spans[n]!;
636 const small = y.length - (end - start) >= Math.max(x.length, y.length) * 0.4;
637 remap.set(a, lines.length);
638 lines.push(step.lines[a++]!);
639 diff.push({ kind: "add", ...(small ? { start, end } : {}) });
640 }
641 k++;
642 }
643 } else {
644 for (let n = 0; n < part.count!; n++) {
645 const line = step.lines[a]!;
646 remap.set(a++, lines.length);
647 lines.push(line);
648 diff.push(/[A-Za-z0-9]/.test(textOf(line)) ? { kind: "add" } : null);
649 }
650 }
651 }
652 // Everything that points at a line now points at where that line moved.
653 const at = (n: number) => remap.get(n) ?? n;
654 const available = widthFor.get(step.lines) ?? 1560;
655 step.marks = step.marks.map((m) => ({
656 ...m,
657 line: at(m.line),
658 ...(m.toLine !== undefined ? { toLine: at(m.toLine) } : {}),
659 }));
660 if (step.focus) step.focus = { from: at(step.focus.from), to: at(step.focus.to) };
661 if (step.error) step.error = { ...step.error, line: at(step.error.line) };
662 step.links = step.links?.map((l) => ({ ...l, from: { ...l.from, line: at(l.from.line) } }));
663 step.diagramLinks = step.diagramLinks?.map((l) => ({
664 ...l,
665 from: { ...l.from, line: at(l.from.line) },
666 }));
667 step.lines = lines;
668 step.diff = diff;
669 if (!spec.fontSize) {
670 const longest = Math.max(...lines.map((l) => textOf(l).length));
671 step.fontSize = Math.min(
672 step.fontSize,
673 Math.floor(available / (longest * 0.6)),
674 Math.floor(780 / (lines.length * 1.55)),
675 );
676 }
677 });
678 }
679
680 // Hand-picked emphasis wins over the automatic diff.
681 steps.forEach((spec, i) => {
682 const step = resolved[i]!;
683 if (spec.kind !== "code" || step.kind !== "code" || !spec.emphasize) return;
684 step.diff = step.lines.map((line) => {
685 const text = line.map((t) => t.text).join("");
686 return spec.emphasize!.some((e) => text.includes(e)) ? { kind: "add" as const } : null;
687 });
688 });
689
690 // One size per sequence: a snippet keeps its size as panels and marks come and go.
691 const groupSize = new Map<string, number>();
692 steps.forEach((spec, i) => {
693 const step = resolved[i]!;
694 if (spec.kind !== "code" || step.kind !== "code" || spec.fontSize) return;
695 groupSize.set(
696 step.group,
697 Math.min(
698 groupSize.get(step.group) ?? Infinity,
699 step.fontSize,
700 step.beside?.fontSize ?? Infinity,
701 ),
702 );
703 });
704 steps.forEach((spec, i) => {
705 const step = resolved[i]!;
706 if (spec.kind === "code" && step.kind === "code" && !spec.fontSize) {
707 step.fontSize = groupSize.get(step.group)!;
708 if (step.beside) step.beside.fontSize = step.fontSize;
709 }
710 if (step.kind === "code" && step.under) step.under.step.fontSize = step.fontSize;
711 });
712 // Side panels in a sequence share one size too, so consecutive panels line up.
713 const besideSize = new Map<string, number>();
714 for (const step of resolved) {
715 if (step.kind !== "code" || !step.beside) continue;
716 besideSize.set(
717 step.group,
718 Math.min(besideSize.get(step.group) ?? Infinity, step.beside.fontSize),
719 );
720 }
721 for (const step of resolved) {
722 if (step.kind === "code" && step.beside) step.beside.fontSize = besideSize.get(step.group)!;
723 }
724
725 await mkdir(out, { recursive: true });
726 // A roll slot is lit only on the steps it rolls into or out of, so the eye goes to what changes.
727 {
728 const value = (step: RollStep, k: number) => {
729 const slot = step.slots[k]!;
730 return step.lines[slot.line]!.map((t) => t.text)
731 .join("")
732 .slice(slot.start, slot.end);
733 };
734 for (const [i, step] of resolved.entries()) {
735 if (step.kind !== "roll") continue;
736 const before = resolved[i - 1];
737 const after = resolved[i + 1];
738 const prev = before?.kind === "roll" && before.group === step.group ? before : undefined;
739 const next = after?.kind === "roll" && after.group === step.group ? after : undefined;
740 step.slots = step.slots.map((slot, k) => ({
741 ...slot,
742 active:
743 (!!prev && value(prev, k) !== value(step, k)) ||
744 (!!next && value(next, k) !== value(step, k)),
745 }));
746 }
747 }
748
749 const json: IntroJson = { steps: resolved };
750 // Images the steps reference (e.g. an aside's photo), served next to intro.json.
751 await cp(path.join(import.meta.dirname, "assets"), path.join(shared, "assets"), {
752 recursive: true,
753 });
754 await writeFile(path.join(out, "intro.json"), `${JSON.stringify(json, null, 2)}\n`);
755 console.log(`✔ ${resolved.length} ${deckName} steps → out/capture/${deckName}/intro.json`);