claude-scriptorium 0.1.3

Render Claude Code sessions as self-contained HTML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// illumination: the folio's own behaviour, inlined into every written file.
//
// This is the trusted app script (distinct from the dev-only live-reload
// snippet `serve` injects). Transcript content is always escaped, never run;
// this code is the one script the artifact carries deliberately. Keep it small
// and dependency-free so a folio stays a single portable file.
(() => {
  "use strict";

  // --- Theme: light / dark / system -------------------------------------
  //
  // Every colour is a light-dark() pair resolved by `color-scheme`. Forcing a
  // side is just pinning color-scheme via [data-theme] on <html>; "system"
  // clears the attribute and falls back to the OS preference. The choice
  // persists in localStorage and is applied before first paint (this script
  // sits in <head>) so a forced theme never flashes the system one.

  const THEME_KEY = "scriptorium-theme";
  const THEMES = ["system", "light", "dark"];
  const FOLD_KEY = "scriptorium-folds";
  const TAIL_KEY = "scriptorium-tail";

  // Keys whose default action scrolls the page, so pressing one counts as the
  // reader taking over from follow mode (unless focus is in a control).
  const SCROLL_KEYS = new Set([
    "ArrowUp",
    "ArrowDown",
    "PageUp",
    "PageDown",
    "Home",
    "End",
    " ",
  ]);

  const readTheme = () => {
    try {
      const stored = localStorage.getItem(THEME_KEY);
      return THEMES.includes(stored) ? stored : "system";
    } catch {
      return "system";
    }
  };

  const applyTheme = (theme) => {
    const root = document.documentElement;
    if (theme === "system") {
      delete root.dataset.theme;
    } else {
      root.dataset.theme = theme;
    }
  };

  applyTheme(readTheme());

  const wireThemeToggle = () => {
    const toggle = document.querySelector(".theme-toggle");
    if (!toggle) return;
    const buttons = toggle.querySelectorAll("[data-theme-choice]");
    const sync = (theme) => {
      buttons.forEach((button) => {
        const active = button.dataset.themeChoice === theme;
        button.setAttribute("aria-pressed", String(active));
      });
    };
    sync(readTheme());
    buttons.forEach((button) => {
      button.addEventListener("click", () => {
        const theme = button.dataset.themeChoice;
        applyTheme(theme);
        try {
          localStorage.setItem(THEME_KEY, theme);
        } catch {}
        sync(theme);
      });
    });
  };

  // --- Search: highlight every match, step through with next / prev -------
  //
  // Non-destructive to the layout: nothing is hidden. Each query marks all
  // matches inside the conversation, keeps a running index, and scrolls the
  // current one into view, opening any collapsed marginalia (and revealing the
  // meta panels) that hold it so the match is actually visible.

  const HIT = "search__hit";
  const CURRENT = "is-current";

  const clearHits = (container) => {
    container.querySelectorAll("mark." + HIT).forEach((mark) => {
      mark.replaceWith(document.createTextNode(mark.textContent));
    });
    container.normalize();
  };

  // Which kind of message a text node belongs to, judged by the block it sits
  // in rather than its panel's label: a tool call folded into an assistant
  // panel is still "tool", and reasoning is "thinking", so scoping is precise.
  const scopeOf = (node) => {
    const el = node.parentElement;
    if (!el) return "assistant";
    if (el.closest(".marginalia")) return "tool";
    if (el.closest(".block--thinking")) return "thinking";
    const turn = el.closest(".turn");
    if (turn && turn.classList.contains("turn--user")) return "user";
    return "assistant";
  };

  const markHits = (container, query, scopes) => {
    const needle = query.toLowerCase();
    const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
    const nodes = [];
    while (walker.nextNode()) {
      const node = walker.currentNode;
      if (!node.nodeValue.trim()) continue;
      // Copy-button labels are chrome, not transcript; don't match them.
      if (node.parentElement && node.parentElement.closest(".copy-button")) {
        continue;
      }
      // Harness-note panels are hidden with no way to reveal them, so a hit
      // inside one could never be scrolled into view; skip them.
      if (node.parentElement && node.parentElement.closest("[data-meta]")) {
        continue;
      }
      // Restrict to the kinds of message the reader left enabled.
      if (scopes && !scopes.has(scopeOf(node))) {
        continue;
      }
      nodes.push(node);
    }
    const hits = [];
    for (const node of nodes) {
      const text = node.nodeValue;
      const hay = text.toLowerCase();
      let from = hay.indexOf(needle);
      if (from === -1) continue;
      const frag = document.createDocumentFragment();
      let pos = 0;
      while (from !== -1) {
        if (from > pos) {
          frag.appendChild(document.createTextNode(text.slice(pos, from)));
        }
        const mark = document.createElement("mark");
        mark.className = HIT;
        mark.textContent = text.slice(from, from + query.length);
        frag.appendChild(mark);
        hits.push(mark);
        pos = from + query.length;
        from = hay.indexOf(needle, pos);
      }
      if (pos < text.length) {
        frag.appendChild(document.createTextNode(text.slice(pos)));
      }
      node.parentNode.replaceChild(frag, node);
    }
    return hits;
  };

  const revealHit = (hit) => {
    for (let node = hit.parentElement; node; node = node.parentElement) {
      if (node.tagName === "DETAILS") node.open = true;
    }
  };

  const wireSearch = () => {
    const search = document.querySelector(".search");
    const container = document.querySelector("main.folio");
    if (!search || !container) return;
    const input = search.querySelector(".search__input");
    const count = search.querySelector(".search__count");
    const prev = search.querySelector('[data-search-nav="prev"]');
    const next = search.querySelector('[data-search-nav="next"]');
    const scopeButtons = search.querySelectorAll(".search__scope");

    const enabledScopes = () => {
      const scopes = new Set();
      scopeButtons.forEach((button) => {
        if (button.getAttribute("aria-pressed") === "true") {
          scopes.add(button.dataset.scope);
        }
      });
      return scopes;
    };

    let hits = [];
    let index = -1;

    const paint = () => {
      hits.forEach((hit) => hit.classList.remove(CURRENT));
      const nav = hits.length > 0;
      prev.disabled = !nav;
      next.disabled = !nav;
      if (!input.value) {
        count.textContent = "";
        return;
      }
      if (!nav) {
        count.textContent = "no matches";
        return;
      }
      const hit = hits[index];
      hit.classList.add(CURRENT);
      revealHit(hit);
      hit.scrollIntoView({ block: "center", behavior: "smooth" });
      count.textContent = index + 1 + "/" + hits.length;
    };

    const run = () => {
      clearHits(container);
      const query = input.value;
      hits = query ? markHits(container, query, enabledScopes()) : [];
      index = hits.length ? 0 : -1;
      paint();
    };

    const step = (delta) => {
      if (!hits.length) return;
      index = (index + delta + hits.length) % hits.length;
      paint();
    };

    input.addEventListener("input", run);
    input.addEventListener("keydown", (event) => {
      if (event.key !== "Enter") return;
      event.preventDefault();
      step(event.shiftKey ? -1 : 1);
    });
    prev.addEventListener("click", () => step(-1));
    next.addEventListener("click", () => step(1));
    scopeButtons.forEach((button) => {
      button.addEventListener("click", () => {
        const active = button.getAttribute("aria-pressed") === "true";
        button.setAttribute("aria-pressed", String(!active));
        run();
      });
    });
  };

  // --- Copy: a button on every code block and every message --------------

  const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      return;
    } catch {
      // file:// or a denied permission: fall back to a throwaway textarea.
    }
    const scratch = document.createElement("textarea");
    scratch.value = text;
    scratch.style.position = "fixed";
    scratch.style.opacity = "0";
    document.body.appendChild(scratch);
    scratch.select();
    try {
      document.execCommand("copy");
    } catch {}
    scratch.remove();
  };

  const makeCopyButton = (getText) => {
    const button = document.createElement("button");
    button.type = "button";
    button.className = "copy-button";
    button.textContent = "copy";
    button.setAttribute("aria-label", "copy to clipboard");
    button.addEventListener("click", async (event) => {
      event.stopPropagation();
      await copyToClipboard(getText());
      button.textContent = "copied";
      button.classList.add("is-done");
      setTimeout(() => {
        button.textContent = "copy";
        button.classList.remove("is-done");
      }, 1200);
    });
    return button;
  };

  const wireCopy = () => {
    const container = document.querySelector("main.folio");
    if (!container) return;

    // Every code / diff / JSON / output block copies its own text.
    container.querySelectorAll("pre").forEach((pre) => {
      const code = pre.querySelector("code") || pre;
      pre.appendChild(makeCopyButton(() => code.textContent));
    });

    // Every turn copies its readable prose (text and thinking, not tool JSON).
    container.querySelectorAll(".turn").forEach((turn) => {
      const prose = turn.querySelectorAll(".block--text, .block--thinking");
      if (!prose.length) return;
      const meta = turn.querySelector(".turn__meta");
      if (!meta) return;
      const button = makeCopyButton(() =>
        Array.from(prose)
          .map((block) => block.textContent.trim())
          .filter(Boolean)
          .join("\n\n"),
      );
      button.classList.add("copy-button--meta");
      meta.appendChild(button);
    });
  };

  // --- Dock: jump between messages, fold every marginalia ---------------

  const wireDock = () => {
    const dock = document.querySelector(".dock");
    const container = document.querySelector("main.folio");
    if (!dock || !container) return;
    // Step between the substantive messages, skipping tool-call and thinking
    // panels: those are the noise a reader wants to jump over. Only visible
    // ones, since a hidden meta panel reports top 0 and would hijack "current".
    // Scoped to one speaker when a role is given, otherwise every message.
    const messages = (role) =>
      Array.from(
        container.querySelectorAll(
          role
            ? `.turn[data-kind="${role}"]`
            : '.turn[data-kind="user"], .turn[data-kind="assistant"]',
        ),
      ).filter((turn) => turn.getClientRects().length > 0);

    const jump = (direction, role) => {
      // The message at the top of the viewport is the last one whose top has
      // scrolled to or above the threshold; the threshold clears a turn's own
      // scroll-margin so the one just navigated to counts as current, not next.
      const threshold = 40;
      const panels = messages(role);
      let current = -1;
      panels.forEach((turn, index) => {
        if (turn.getBoundingClientRect().top <= threshold) current = index;
      });
      const next = Math.min(Math.max(current + direction, 0), panels.length - 1);
      const target = panels[next];
      if (target) target.scrollIntoView({ behavior: "smooth", block: "start" });
    };

    const fold = (open) => {
      container.querySelectorAll("details").forEach((details) => {
        details.open = open;
      });
    };

    // --- Follow (tail -f): keep the newest message's start pinned across the
    // reloads a live session drives, until the reader scrolls away.
    const tailButton = dock.querySelector('[data-tail="toggle"]');

    const visible = () =>
      Array.from(container.querySelectorAll(".turn")).filter(
        (turn) => turn.getClientRects().length > 0,
      );

    const firstMessage = () => visible()[0] || null;

    const lastMessage = () => {
      const panels = visible();
      return panels[panels.length - 1] || null;
    };

    const readTail = () => {
      try {
        return localStorage.getItem(TAIL_KEY) === "1";
      } catch {
        return false;
      }
    };

    let tailing = readTail();

    const paintTail = () => {
      if (tailButton) tailButton.setAttribute("aria-pressed", String(tailing));
    };

    const scrollToEnd = (behavior) => {
      const target = lastMessage();
      if (target) target.scrollIntoView({ behavior, block: "start" });
    };

    const scrollToTop = (behavior) => {
      const target = firstMessage();
      if (target) target.scrollIntoView({ behavior, block: "start" });
    };

    const setTail = (on, behavior) => {
      tailing = on;
      try {
        localStorage.setItem(TAIL_KEY, on ? "1" : "0");
      } catch {}
      paintTail();
      if (on) scrollToEnd(behavior);
    };

    // A programmatic scrollIntoView never emits wheel/touch/keydown, so those
    // are unambiguous reader input: any of them hands control back.
    const releaseTail = () => {
      if (tailing) setTail(false);
    };
    window.addEventListener("wheel", releaseTail, { passive: true });
    window.addEventListener("touchmove", releaseTail, { passive: true });
    window.addEventListener("keydown", (event) => {
      const tag = event.target.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || tag === "BUTTON") return;
      if (SCROLL_KEYS.has(event.key)) releaseTail();
    });

    // A deep link (#turn-N) names the panel the reader came for, so it releases
    // follow like a wheel or arrow key does, rather than losing the landing to
    // a snap to the end. Releasing (not just skipping this load's snap) because
    // the hash survives the reloads a live session drives, and a suppression
    // that didn't persist would fight the anchor on every one.
    //
    // The hash is arbitrary text off the end of a shared URL, so it need be
    // neither a valid selector (hence getElementById, as querySelector throws)
    // nor validly escaped (hence the guard, as a stray "%" throws).
    const anchorId = () => {
      const raw = location.hash.slice(1);
      try {
        return decodeURIComponent(raw);
      } catch {
        return raw;
      }
    };
    const anchored = location.hash ? document.getElementById(anchorId()) : null;
    const deepLink = anchored && container.contains(anchored) ? anchored : null;
    if (deepLink) releaseTail();

    // On load, if still following, snap to the newest message at once; a second
    // pass after layout settles (web fonts shift it) lands it precisely. A
    // deep-linked turn needs that second pass too, since the browser's own
    // anchor scroll happens before the fonts land.
    paintTail();
    if (tailing) {
      scrollToEnd("auto");
      requestAnimationFrame(() => {
        if (tailing) scrollToEnd("auto");
      });
    } else if (deepLink) {
      requestAnimationFrame(() => {
        deepLink.scrollIntoView({ behavior: "auto", block: "start" });
      });
    }

    dock.addEventListener("click", (event) => {
      const button = event.target.closest("button");
      if (!button) return;
      const { nav, role, fold: foldTo, tail } = button.dataset;
      if (nav === "prev") jump(-1, role);
      else if (nav === "next") jump(1, role);
      // Leaping to the top is the reader taking control, so it releases follow
      // the way a wheel or arrow key does: otherwise the next reload of a live
      // session would snap straight back to the end.
      else if (nav === "top") {
        releaseTail();
        scrollToTop("smooth");
      } else if (nav === "end") setTail(true, "smooth");
      else if (tail === "toggle") setTail(!tailing, "smooth");
      else if (foldTo === "expand") fold(true);
      else if (foldTo === "collapse") fold(false);
    });

    // Remember each marginalia's open/closed state across reloads, keyed per
    // message so a live session that grows keeps the folds a reader set: the
    // raw stream is append-only, so a panel's turn number and a marginalia's
    // index within it stay stable as new turns arrive. Only open keys are
    // stored; the markup default is collapsed.
    const foldKey = (details) => {
      const turn = details.closest(".turn");
      const marginalia = turn ? turn.querySelectorAll("details") : [details];
      const index = Array.prototype.indexOf.call(marginalia, details);
      return `${turn ? turn.dataset.turn : "?"}:${index}`;
    };

    const readOpenFolds = () => {
      try {
        const stored = JSON.parse(localStorage.getItem(FOLD_KEY) || "[]");
        return new Set(Array.isArray(stored) ? stored : []);
      } catch {
        return new Set();
      }
    };

    const open = readOpenFolds();
    container.querySelectorAll("details").forEach((details) => {
      if (open.has(foldKey(details))) details.open = true;
    });

    // `toggle` fires on both a reader's click and the fold-all buttons, and does
    // not bubble, so listen in the capture phase.
    container.addEventListener(
      "toggle",
      (event) => {
        const details = event.target;
        if (!(details instanceof HTMLDetailsElement)) return;
        const folds = readOpenFolds();
        if (details.open) folds.add(foldKey(details));
        else folds.delete(foldKey(details));
        try {
          localStorage.setItem(FOLD_KEY, JSON.stringify([...folds]));
        } catch {}
      },
      true,
    );
  };

  const onReady = (fn) => {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", fn);
    } else {
      fn();
    }
  };

  onReady(() => {
    wireThemeToggle();
    wireSearch();
    wireCopy();
    wireDock();
  });
})();