Skip to main content

beecast_player/
lib.rs

1//! The first-party beecast player as a crate: clean-room, dependency-free
2//! asciicast (v1/v2/v3) player and VT100/xterm-subset terminal emulator. Consumers inline
3//! the two constants whole — a `<script>` element and a `<style>` element — and get the
4//! full player: parsing, emulation, headless controller, default controls, Web Component,
5//! chapter markers, keyboard control, and live-follow `append` for recordings that are
6//! still growing.
7//!
8//! The JS globals are `BeeCastVT` (DOM-free core), `BeeCastController` (headless playback),
9//! and `BeeCastPlayer` (DOM factory + `<beecast-player>`); this crate is the component's
10//! canonical home.
11
12/// The player bundle: `vt.js` (core) + `controller.js` (headless playback) + `player.js`
13/// (DOM view, Web Component, legacy factory). Inline it in one `<script>` element; it
14/// performs no network requests and loads no workers.
15pub const PLAYER_JS: &str =
16  concat!(include_str!("vt.js"), "\n", include_str!("controller.js"), "\n", include_str!("player.js"),);
17
18/// The player chrome and terminal palette. Semantic `--beecast-*` tokens are the stable
19/// theming surface; `--sp-*` is the terminal palette. Nothing is fetched (no fonts, no images).
20pub const PLAYER_CSS: &str = include_str!("player.css");
21
22#[cfg(test)]
23mod tests {
24  use super::*;
25
26  /// Every embedder's self-containment claim depends on the bundle itself: it must not
27  /// contain a literal `</script`, must not reference workers, and its CSS must not pull
28  /// fonts or images. Asserted here so a player change that breaks any of it fails loudly.
29  /// And the bundle must be the first-party clean-room player — no third-party code, and
30  /// therefore no third-party license, rides into any embedding page.
31  #[test]
32  fn player_bundle_is_inline_safe_and_first_party() {
33    assert!(!PLAYER_JS.contains("</script"), "bundle would terminate an inline <script>");
34    assert!(!PLAYER_JS.contains("<!--"), "bundle would enter the script double-escaped state");
35    assert!(!PLAYER_JS.to_lowercase().contains("worker"), "bundle must not load a worker sidecar");
36    assert!(!PLAYER_CSS.contains("url("), "player CSS must not fetch fonts/images");
37    assert!(PLAYER_JS.contains("BeeCastPlayer") && PLAYER_JS.contains("Clean-room implementation"));
38    assert!(PLAYER_JS.contains("BeeCastController"));
39    assert!(PLAYER_JS.contains("beecast-player"));
40    for banned in ["asciinema-player", "AsciinemaPlayer", "@license", "Apache"] {
41      assert!(!PLAYER_JS.contains(banned) && !PLAYER_CSS.contains(banned), "third-party marker '{banned}'");
42    }
43  }
44
45  /// `fit: 'both'` must never vertically scale against a content-sized mount: that path
46  /// was a ResizeObserver shrink ratchet (scsh's live dashboard). The definite-height
47  /// probe and the absence of the old `availH - 4` trigger pin the fix in the bundle.
48  #[test]
49  fn fit_both_refuses_the_content_sized_shrink_ratchet() {
50    assert!(
51      PLAYER_JS.contains("mountHeightIsDefinite"),
52      "layout must probe whether the mount's height is independent of the screen box"
53    );
54    assert!(
55      PLAYER_JS.contains("before > 0 && before === after"),
56      "definite-height probe must compare mount clientHeight before/after collapsing the box"
57    );
58    assert!(
59      !PLAYER_JS.contains("availH - 4"),
60      "the availH-4 trigger forced another shrink on every ResizeObserver tick"
61    );
62  }
63
64  /// Phase 0: the public surface must not shrink without an intentional change.
65  #[test]
66  fn public_api_surface_is_documented() {
67    for key in [
68      "BeeCastVT",
69      "BeeCastController",
70      "BeeCastPlayer",
71      "parseCast",
72      "appendCast",
73      "buildPacing",
74      "extendPacing",
75      "mapTime",
76      "create",
77      "getState",
78      "subscribe",
79      "setSpeed",
80      "publicMethods",
81      "supportedCssVariables",
82      "nonPublicFields",
83    ] {
84      assert!(PLAYER_JS.contains(key), "public surface missing {key}");
85    }
86    for token in
87      ["--beecast-color-surface", "--beecast-color-accent", "--beecast-color-focus", "--beecast-font-terminal"]
88    {
89      assert!(PLAYER_CSS.contains(token), "theme token missing {token}");
90    }
91  }
92
93  /// Behavior tests for the DOM-free core and headless controller, run under Node.
94  /// Skips silently when `node` is not installed — the structural assertions above still gate the bundle.
95  #[test]
96  fn vt_core_node_selftest() {
97    let dir = std::env::temp_dir().join(format!("beecast-vt-selftest-{}", std::process::id()));
98    std::fs::create_dir_all(&dir).unwrap();
99    let bundle = dir.join("player.js");
100    std::fs::write(&bundle, PLAYER_JS).unwrap();
101    let script = r#"
102const assert = require('assert');
103require(process.argv[2]);
104const VT = globalThis.BeeCastVT;
105const C = globalThis.BeeCastController;
106const P = globalThis.BeeCastPlayer;
107
108// ---- Phase 0: public keys --------------------------------------------------------------
109for (const k of ['parseCast','appendCast','buildPacing','extendPacing','mapTime','Term']) {
110  assert.strictEqual(typeof VT[k], 'function', 'BeeCastVT.' + k);
111}
112assert.strictEqual(typeof C.create, 'function');
113assert.strictEqual(typeof P.create, 'function');
114assert.ok(Array.isArray(P.publicMethods));
115for (const m of ['create','play','pause','toggle','seek','getCurrentTime','append','dispose']) {
116  assert.ok(P.publicMethods.includes(m), 'publicMethods missing ' + m);
117}
118assert.ok(P.nonPublicFields.includes('playing'));
119assert.ok(P.nonPublicFields.includes('pacedPos'));
120assert.ok(P.supportedCssVariables.includes('--beecast-color-accent'));
121
122// ---- VT core (existing coverage) -------------------------------------------------------
123let c = VT.parseCast('{"version":3,"term":{"cols":10,"rows":3}}\n# note\n[0.5,"o","hi"]\n[0.5,"m","chapter"]\n[1.0,"r","20x5"]\n');
124assert.strictEqual(c.cols, 10); assert.strictEqual(c.rows, 3);
125assert.strictEqual(c.events.length, 3);
126assert.strictEqual(c.duration, 2);
127
128c = VT.parseCast('{"version":2,"width":80,"height":24}\n[0.5,"o","a"]\n[2.0,"o","b"]\n');
129assert.strictEqual(c.duration, 2); assert.strictEqual(c.events[1].t, 2);
130
131c = VT.parseCast('{"version":1,"width":5,"height":2,"stdout":[[0.1,"x"],[0.2,"y"]]}');
132assert.strictEqual(c.cols, 5); assert.strictEqual(c.events.length, 2);
133
134c = VT.parseCast('{"version":3,"term":{"cols":10,"rows":3}}\n[1.0,"o","a"]\n');
135assert.strictEqual(VT.appendCast(c, '[0.5,"o",'), 0);
136assert.strictEqual(c.duration, 1);
137assert.strictEqual(VT.appendCast(c, '"b"]\n[0.5,"m","x"]\n'), 2);
138assert.strictEqual(c.duration, 2);
139assert.strictEqual(c.events.length, 3);
140assert.strictEqual(c.events[1].t, 1.5);
141
142c = VT.parseCast('{"version":2,"width":80,"height":24}\n[1.0,"o","a"]\n');
143VT.appendCast(c, '# noise\n{"version":2}\n[3.0,"o","b"]\n');
144assert.strictEqual(c.duration, 3); assert.strictEqual(c.events[1].t, 3);
145
146c = VT.parseCast('{"version":3,"term":{"cols":4,"rows":1}}\n[1.0,"o","hi"]\n[2.0,"o');
147assert.strictEqual(c.events.length, 1);
148VT.appendCast(c, '","yo"]\n');
149assert.strictEqual(c.events.length, 2); assert.strictEqual(c.duration, 3);
150
151c = VT.parseCast('{"version":1,"width":5,"height":2,"stdout":[[0.1,"x"]]}');
152assert.strictEqual(VT.appendCast(c, '[1.0,"o","y"]\n'), 0);
153
154const ev = [{t:1},{t:2}];
155const pacing = VT.buildPacing(ev, 2, null);
156ev.push({t:10});
157VT.extendPacing(pacing, ev, 2, 10);
158assert.strictEqual(pacing.pacedDuration, 10);
159assert.strictEqual(VT.mapTime(pacing.rec, pacing.paced, 10), 10);
160const limited = VT.buildPacing([{t:1}], 1, 2);
161VT.extendPacing(limited, [{t:1},{t:9}], 1, 9);
162assert.strictEqual(limited.pacedDuration, 3);
163assert.strictEqual(VT.mapTime(limited.paced, limited.rec, 3), 9);
164
165let t = new VT.Term(10, 3);
166t.write('hello\r\nworld');
167assert.deepStrictEqual(t.textLines(), ['hello', 'world', '']);
168t.write('\x1b[1;3Hga');
169assert.strictEqual(t.textLines()[0], 'hegao');
170t.write('\x1b[2J');
171assert.deepStrictEqual(t.textLines(), ['', '', '']);
172
173t = new VT.Term(10, 1);
174t.write('\x1b[31mred\x1b[0m ok');
175const runs = t.snapshot().rows[0];
176assert.strictEqual(runs[0].text, 'red'); assert.strictEqual(runs[0].fg, 1);
177t = new VT.Term(4, 1);
178t.write('\x1b[38;5;196mX\x1b[38;2;1;2;3mY');
179assert.strictEqual(t.snapshot().rows[0][0].fg, 196);
180assert.strictEqual(t.snapshot().rows[0][1].fg, '#010203');
181
182t = new VT.Term(3, 2);
183t.write('abc');
184assert.strictEqual(t.snapshot().cursor.y, 0);
185t.write('d');
186assert.deepStrictEqual(t.textLines(), ['abc', 'd']);
187
188t = new VT.Term(5, 4);
189t.write('aa\r\nbb\r\ncc\r\ndd');
190t.write('\x1b[2;3r\x1b[3;1H\n');
191assert.strictEqual(t.textLines()[0], 'aa');
192assert.strictEqual(t.textLines()[1], 'cc');
193assert.strictEqual(t.textLines()[3], 'dd');
194
195t = new VT.Term(5, 2);
196t.write('main');
197t.write('\x1b[?1049h\x1b[Halt');
198assert.strictEqual(t.textLines()[0], 'alt');
199t.write('\x1b[?1049l');
200assert.strictEqual(t.textLines()[0], 'main');
201
202t = new VT.Term(4, 1);
203t.write('\x1b(0qqx\x1b(B');
204assert.strictEqual(t.textLines()[0], '──│');
205t = new VT.Term(8, 1);
206t.write('\x1b]0;title\x07ok');
207assert.strictEqual(t.textLines()[0], 'ok');
208t.write('\x1b[?25l');
209assert.strictEqual(t.snapshot().cursor.visible, false);
210
211// ---- Phase 1: headless controller (no DOM) ---------------------------------------------
212function fakeClock() {
213  let now = 0;
214  const q = [];
215  return {
216    now: () => now,
217    requestAnimationFrame: (cb) => { q.push(cb); return q.length; },
218    cancelAnimationFrame: () => { q.length = 0; },
219    flush: (ms) => {
220      now += ms;
221      const batch = q.splice(0, q.length);
222      for (const cb of batch) cb(now);
223    },
224  };
225}
226
227const castText = '{"version":3,"term":{"cols":8,"rows":2}}\n[0,"o","hi"]\n[1.0,"o","!"]\n[1.0,"m","mid"]\n';
228const clock = fakeClock();
229const ctrl = C.create({
230  data: castText,
231  idleTimeLimit: 2,
232  speed: 1,
233  markers: [[0, 'start']],
234  clock: clock,
235});
236
237// Initial state
238let state = ctrl.getState();
239assert.strictEqual(state.status, 'idle');
240assert.strictEqual(state.currentTime, 0);
241assert.strictEqual(state.duration, 2);
242assert.strictEqual(state.speed, 1);
243assert.strictEqual(state.canAppend, true);
244assert.ok(state.markers.length >= 2); // sidecar + in-band
245assert.ok(state.markers.every(m => m.id && typeof m.time === 'number' && m.label != null));
246assert.ok(state.terminal.rows.length === 2);
247assert.strictEqual(state.dimensions.columns, 8);
248
249// Terminal snapshots are cached until output or resize dirties the terminal.
250let snapshotCalls = 0;
251const originalSnapshot = ctrl.term.snapshot;
252ctrl.term.snapshot = function () { snapshotCalls++; return originalSnapshot.call(this); };
253const cachedTerminal = ctrl.getState().terminal;
254assert.strictEqual(ctrl.getState().terminal, cachedTerminal);
255assert.strictEqual(snapshotCalls, 0, 'initial snapshot remains cached');
256ctrl.seek(1.5);
257const changedTerminal = ctrl.getState().terminal;
258assert.notStrictEqual(changedTerminal, cachedTerminal);
259assert.strictEqual(snapshotCalls, 1, 'events invalidate the cached snapshot once');
260assert.strictEqual(ctrl.getState().terminal, changedTerminal);
261assert.strictEqual(snapshotCalls, 1, 'unchanged state does not copy the terminal again');
262ctrl.seek(0);
263
264// subscribe delivers immediately and is removable
265const seen = [];
266const unsub = ctrl.subscribe((s, meta) => { seen.push(meta.type); });
267assert.ok(seen.includes('ready'));
268unsub();
269unsub(); // idempotent
270const n = seen.length;
271ctrl.setSpeed(2);
272// no more callbacks after unsubscribe
273assert.strictEqual(seen.length, n);
274
275// setSpeed does not rebuild terminal / changes state
276ctrl.setSpeed(1.5);
277assert.strictEqual(ctrl.getState().speed, 1.5);
278
279// play / pause / seek / getCurrentTime
280// First animation frame establishes lastTick (dt=0); the second advances the clock.
281ctrl.play();
282assert.strictEqual(ctrl.getState().status, 'playing');
283clock.flush(0);
284clock.flush(500); // 0.5s wall * 1.5 speed ≈ 0.75s paced
285assert.ok(ctrl.getCurrentTime() > 0);
286ctrl.pause();
287assert.strictEqual(ctrl.getState().status, 'paused');
288
289ctrl.seek(1.5);
290assert.ok(Math.abs(ctrl.getCurrentTime() - 1.5) < 1e-9);
291ctrl.seek(0);
292assert.ok(ctrl.getCurrentTime() < 1e-9);
293
294// toggle
295ctrl.toggle();
296assert.strictEqual(ctrl.getState().status, 'playing');
297ctrl.toggle();
298assert.strictEqual(ctrl.getState().status, 'paused');
299
300// replay after end
301ctrl.seek(2);
302ctrl.play();
303// playing from end rewinds
304assert.strictEqual(ctrl.getState().status, 'playing');
305assert.ok(ctrl.getCurrentTime() < 1e-6);
306
307// append live-follow at edge
308ctrl.pause();
309ctrl.seek(2);
310assert.ok(ctrl.getState().atLiveEdge);
311ctrl.append('[0.5,"o","more"]\n');
312assert.strictEqual(ctrl.getState().duration, 2.5);
313
314// Declared-live mode: parked mid-recording, setLive pins the playhead to the edge; an
315// append keeps it pinned (unconditionally — no positional check); a rewinding seek or
316// play() drops live; a seek TO the edge keeps it.
317ctrl.seek(1);
318ctrl.setLive(true);
319let live = ctrl.getState();
320assert.strictEqual(live.live, true);
321assert.ok(live.atLiveEdge, 'setLive parks at the edge');
322assert.ok(Math.abs(live.currentTime - live.duration) < 1e-9);
323ctrl.append('[0.5,"o","live"]\n');
324live = ctrl.getState();
325assert.strictEqual(live.live, true);
326assert.ok(Math.abs(live.currentTime - live.duration) < 1e-9, 'append keeps the pin');
327ctrl.seek(live.duration); // to the edge: still live
328assert.strictEqual(ctrl.getState().live, true);
329const liveEvents = [];
330const unsubLive = ctrl.subscribe((st, meta) => { liveEvents.push(meta.type); });
331ctrl.seek(0.5); // a rewind: live drops, with a livechange event
332assert.strictEqual(ctrl.getState().live, false);
333assert.ok(liveEvents.includes('livechange'));
334unsubLive();
335ctrl.setLive(true);
336ctrl.play(); // play from the parked edge is a rewind: live drops
337assert.strictEqual(ctrl.getState().live, false);
338ctrl.pause();
339
340// getState is a snapshot (mutating returned markers does not corrupt internal list)
341const s1 = ctrl.getState();
342s1.markers.push({ id: 'x', time: 99, type: 'chapter', label: 'x' });
343assert.ok(ctrl.getState().markers.every(m => m.id !== 'x'));
344
345// dispose makes commands no-ops
346ctrl.dispose();
347ctrl.play();
348ctrl.seek(1);
349ctrl.append('[1,"o","z"]\n');
350assert.strictEqual(ctrl.getState().status, 'idle');
351
352// Marker object form + tuple compatibility
353const c2 = C.create({
354  data: '{"version":3,"term":{"cols":4,"rows":1}}\n[0,"o","a"]\n',
355  markers: [{ time: 0, label: 'A', type: 'chapter' }, [1, 'B']],
356  clock: fakeClock(),
357});
358const marks = c2.getState().markers;
359assert.strictEqual(marks[0].label, 'A');
360assert.strictEqual(marks[1].label, 'B');
361c2.dispose();
362
363// Source type text
364const c3 = C.create({
365  source: { type: 'text', data: '{"version":3,"term":{"cols":4,"rows":1}}\n[0,"o","z"]\n' },
366  clock: fakeClock(),
367});
368assert.strictEqual(c3.getState().duration, 0);
369c3.dispose();
370
371// Discrete events survive playback: seek/speedchange/durationchange/markerchange emitted
372// WHILE PLAYING must each reach subscribers with their own meta type — timeupdate
373// coalescing must never swallow them.
374const clock4 = fakeClock();
375const c4 = C.create({ data: castText, idleTimeLimit: 2, clock: clock4 });
376const types = [];
377c4.subscribe(function (s, meta) { types.push(meta.type); });
378c4.play();
379clock4.flush(0);
380clock4.flush(200);
381assert.ok(types.includes('timeupdate'), 'timeupdate flows while playing');
382assert.strictEqual(c4.getState().status, 'playing');
383c4.seek(1.5, { origin: 'api' });
384assert.ok(types.includes('seek'), 'seek delivered while playing, saw: ' + types.join(','));
385c4.append('[5,"o","tail"]\n');
386assert.ok(types.includes('durationchange'), 'durationchange delivered while playing');
387c4.setSpeed(2);
388assert.ok(types.includes('speedchange'), 'speedchange delivered while playing');
389c4.setMarkers([[0.5, 'half']]);
390assert.ok(types.includes('markerchange'), 'markerchange delivered');
391assert.strictEqual(c4.getState().markers.filter(m => m.source === 'integration').length, 1);
392c4.dispose();
393
394// ---- fit:'both' scale rule: content-sized mounts must not ratchet -----------------
395// Mirrors layout()'s definite-height gate (vertical fit only when the mount's height
396// does not track the screen box). The old `availH - 4` trigger shrank forever on
397// content-sized embeds.
398function fitScale(naturalH, availH, definite) {
399  let scale = 1;
400  if (definite && availH > 40 && naturalH * scale > availH) {
401    scale = Math.min(scale, availH / naturalH);
402  }
403  return scale;
404}
405let contentH = 400;
406const natural = 400, bar = 32;
407for (let i = 0; i < 30; i++) {
408  // Content-sized: mount height tracks the box — vertical fit must stay off.
409  const s = fitScale(natural, contentH - bar, false);
410  assert.strictEqual(s, 1, 'content-sized mount must not vertically scale');
411  contentH = natural * s + bar;
412}
413const short = fitScale(400, 200 - 32, true);
414assert.ok(short < 1 && short > 0, 'definite short mount scales down once');
415assert.strictEqual(fitScale(400, 200 - 32, true), short, 'definite scale is stable');
416// The banned ratchet: subtracting 4 from availH forces another shrink every pass.
417let ratchetH = 400;
418for (let i = 0; i < 5; i++) {
419  const avail = ratchetH - bar;
420  if (natural > avail - 4) ratchetH = natural * ((avail - 4) / natural) + bar;
421}
422assert.ok(ratchetH < 390, 'sanity: the old availH-4 rule really does ratchet');
423
424console.log('vt selftest OK');
425"#;
426    let spawned = std::process::Command::new("node")
427      .arg("-")
428      .arg(&bundle)
429      .stdin(std::process::Stdio::piped())
430      .stdout(std::process::Stdio::piped())
431      .stderr(std::process::Stdio::piped())
432      .spawn();
433    let Ok(mut child) = spawned else {
434      let _ = std::fs::remove_dir_all(&dir);
435      return; // no node on this machine — the structural tests above still ran
436    };
437    use std::io::Write;
438    child.stdin.take().unwrap().write_all(script.as_bytes()).unwrap();
439    let out = child.wait_with_output().unwrap();
440    let _ = std::fs::remove_dir_all(&dir);
441    assert!(
442      out.status.success() && String::from_utf8_lossy(&out.stdout).contains("vt selftest OK"),
443      "vt selftest failed:\nstdout: {}\nstderr: {}",
444      String::from_utf8_lossy(&out.stdout),
445      String::from_utf8_lossy(&out.stderr)
446    );
447  }
448}