An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
/* pandemic.js: The Pandemic's own pieces for the upright shorts, loaded after shorts.js. Pure functions of the beat
clock, like the kit. Episodes use these and do not edit this file: episode-only code goes in the episode's folder.
startPandemic() call in place of startShorts(): fonts, the globe (pglobe.js) and the paper grain
globeShot(p, D, view, dotsOn, arcsOn, { on }) the night globe in this panel; view(t) -> { lon, lat, H, dx, dy, roll,
gain, dotScale }; marks from Globe.clearMarks() / Globe.dot(lon, lat) / Globe.arc(a, b)
on: [t0, t1] the only stretch it is drawn in (default the whole beat): hand the
frame over and stop drawing what is covered, or Firefox pays for both
paperMap(p, D, view, opts) -> M the paper map on the SAME view(t) as the globe (fade it in over a globe shot and
nothing jumps); H is the film's: Earth radius 450 / H px (1.15 the whole world,
.3 a continent, .02 a province). opts, all optional:
lit(iso, t) -> 0..1 a country lit red (iso as in the film's GEO_W.countries: 'CHN', 'ITA', 'USA')
litFill: RED the lit()/prov() fill: MARK for what is not the virus (a stay-home order, a
vaccine), or (key) => colour to mix both on one map
prov(name, t) -> 0..1 a province of China lit red ('Hubei'); provinces: true draws their borders
dots: [[lon, lat, t0, r = 7]] red case dots, popping in at t0, r px
routes: [[[lon, lat], [lon, lat], t0, dur = .8]] a red arc drawn from a to b; a dot lands at b when it arrives
cities: [[name, t0, side]] an ink dot and a label (CITIES; side 'l' or 'r', default 'r'); labels keep
inside the safe area, and hide when their city is off it
on: [t0, t1] drawn only then, as for globeShot
M = { g, xy(ll, t) -> [x, y] screen px or null behind the globe, view(t) }; draw your own marks above M.g with M.xy
mapXY(ll, v) -> [x, y] a lon/lat to screen px for a view (globe and map alike)
seriesCard(s, t0, n, tLit) the six episodes, n (1-6) lit at tLit; endCard(s, t0, n): what comes next
found(g, name, source, t0, t1, opts) a full-bleed found photograph with its source tag (photo() tags 'AI illustration')
wide(g, name, keys) · plate(g, name, x, y, opts) · liChip(p, x, y, r, t0, opts) as in madness.js and the film
(series card rim, end card's 'Next' and liChip's ring are MARK: red is the virus only)
Colours: shorts.js's DARK (night), LIGHT (cream ink), RED (the virus only), MARK (yellow), MUTED; here MAPLAND, MAPSEA,
MAPINK, MAPLINE for the paper map. Needs ../img/art.js and ../img/geo-lite.js loaded before this file. */
'use strict';
const MAPLAND = '#ece3cd', MAPSEA = '#bfcac6', MAPINK = '#2b2520', MAPLINE = '#9a8a70', NIGHT = '#04060a';
const DEG = Math.PI / 180;
const EP_TITLES = ['The Warning', 'Too Late', 'The World Stops', 'The Race', 'The Count', 'The Origin'];
const EP_PICS = ['li-wenliang', 'comfort-nyc', 'street-glenview-24', 'ppe-nurses-faceshields', 'morgue-trucks-nyc', 'virus-sem-red'];
const CITIES = GEO_LITE.cities, WUHAN = CITIES.Wuhan;
// stage defs: the scene is cleared on every seek, the stage is not
const PDEFS = mk('defs', {}, document.getElementById('stage'));
mk('circle', { cx: .5, cy: .5, r: .5 }, mk('clipPath', { id: 'liclip', clipPathUnits: 'objectBoundingBox' }, PDEFS));
const PAPER = new Image();
const startPandemic = () => Promise.all([
...['600 40px Oswald', '500 40px Oswald', 'italic 400 40px "EB Garamond"', '400 40px "EB Garamond"', '500 40px "EB Garamond"'].map(f => document.fonts.load(f)),
import('./pglobe.js'), new Promise(r => { (function w() { window.GLOBE_READY ? r() : setTimeout(w, 30); })(); }),
new Promise(r => { PAPER.onload = PAPER.onerror = r; PAPER.src = '../img/paper.webp'; }),
]).then(boot);
/* ---------- the globe ---------- */
const within = (t, on) => !on || (t >= on[0] && t <= on[1]);
function globeShot(p, D, view, dotsOn, arcsOn, { on } = {}) {
const g = Globe.mount(p);
clockRun(t => within(t, on) && Globe.draw(view(t), dotsOn && (i => dotsOn(i, t)), arcsOn && (i => arcsOn(i, t))), D, { tail: true });
return g;
}
// a lon/lat to screen px for view v (orthographic, as the globe draws it); null on the far side
function mapXY([lon, lat], v) {
const k = 450 / v.H, dl = (lon - v.lon) * DEG, f = lat * DEG, f0 = v.lat * DEG;
if (Math.sin(f0) * Math.sin(f) + Math.cos(f0) * Math.cos(f) * Math.cos(dl) < 0) return null;
let x = Math.cos(f) * Math.sin(dl), y = Math.cos(f0) * Math.sin(f) - Math.sin(f0) * Math.cos(f) * Math.cos(dl);
if (v.roll) { const c = Math.cos(v.roll * DEG), s = Math.sin(v.roll * DEG); [x, y] = [x * c + y * s, y * c - x * s]; }
return [W / 2 + (v.dx || 0) + k * x, H / 2 + (v.dy || 0) - k * y];
}
/* ---------- the paper map ----------
A 2D canvas in a foreignObject, redrawn each frame from lon/lat rings (GEO_LITE): live orthographic projection, rings
off screen or under a pixel skipped, points closer than a pixel dropped, 110m data for wide views and 50m close up.
Labels are SVG on top (crisp, and safe.py reads them). */
const unpack = rs => rs.map(r => { // delta hundredths of a degree -> {lam, cphi, sphi, c: centre unit vector, rad}
const n = r.length / 2, lam = new Float32Array(n), cphi = new Float32Array(n), sphi = new Float32Array(n);
let x = 0, y = 0, cx = 0, cy = 0, cz = 0;
for (let i = 0; i < n; i++) {
x += r[2 * i]; y += r[2 * i + 1];
lam[i] = x / 100 * DEG; const f = y / 100 * DEG; cphi[i] = Math.cos(f); sphi[i] = Math.sin(f);
cx += cphi[i] * Math.cos(lam[i]); cy += cphi[i] * Math.sin(lam[i]); cz += sphi[i];
}
const l = Math.hypot(cx, cy, cz) || 1; cx /= l; cy /= l; cz /= l;
let rad = 0;
for (let i = 0; i < n; i++) rad = Math.max(rad, Math.acos(Math.min(1, cphi[i] * Math.cos(lam[i]) * cx + cphi[i] * Math.sin(lam[i]) * cy + sphi[i] * cz)));
return { n, lam, cphi, sphi, c: [cx, cy, cz], rad };
});
let GEO_UNPACKED;
const geoData = () => GEO_UNPACKED || (GEO_UNPACKED = {
lod: GEO_LITE.lod.map(L => Object.fromEntries(Object.entries(L).map(([k, rs]) => [k, unpack(rs)]))),
cn: Object.fromEntries(Object.entries(GEO_LITE.cn).map(([k, rs]) => [k, unpack(rs)])),
});
// a colour with the paper grain multiplied in, as a fill fixed to the screen (the film's static paperTop, without a
// full-frame blend every frame: that cost Firefox 7 ms a frame)
const GRAIN = {};
function grained(ctx, colour) {
if (!GRAIN[colour]) {
const c = document.createElement('canvas'); c.width = W; c.height = H;
const x = c.getContext('2d'); x.fillStyle = colour; x.fillRect(0, 0, W, H);
if (PAPER.naturalWidth) { x.globalCompositeOperation = 'multiply'; x.globalAlpha = .45; x.drawImage(PAPER, 0, 0, W, H); }
GRAIN[colour] = c;
}
return ctx.createPattern(GRAIN[colour], 'no-repeat');
}
const PX = 1; // canvas px per stage px (the export is 1080 wide: 1.2 is sharper and a fifth slower)
function paperMap(p, D, view, { lit, prov, litFill = RED, provinces = false, dots = [], routes = [], cities = [], on } = {}) {
const fillOf = typeof litFill === 'function' ? litFill : () => litFill || RED;
const geo = geoData();
const g = G(p, {}), fo = mk('foreignObject', { x: 0, y: 0, width: W, height: H }, g);
const cv = document.createElement('canvas'); cv.width = W * PX; cv.height = H * PX;
cv.style.cssText = `width:${W}px;height:${H}px;display:block`;
fo.appendChild(cv);
const ctx = cv.getContext('2d'), land = grained(ctx, MAPLAND), sea = grained(ctx, MAPSEA);
const lab = G(g, {});
const labels = cities.map(([name, t0, side = 'r']) => {
const e = G(lab, { o: 0 }), w = inkW(name.toUpperCase(), 30, SANS, 600);
const tx = T(e, name.toUpperCase(), { x: 0, y: 0, size: 30, fill: MAPINK, font: SANS, weight: 600, anchor: 'start' });
tx.setAttribute('stroke', MAPLAND); tx.setAttribute('stroke-width', 6); tx.setAttribute('paint-order', 'stroke'); tx.setAttribute('stroke-linejoin', 'round');
return { e, ll: CITIES[name], t0, side, w };
});
const vf = t => ({ lon: 0, lat: 0, H: 1.15, ...view(t) });
// project ring r into the current path; v: {l0, sf0, cf0, k, cx, cy}
function ring(r, v) {
const { l0, sf0, cf0, k, cx, cy } = v;
let lx = 1e9, ly = 1e9, first = true;
for (let i = 0; i < r.n; i++) {
const dl = r.lam[i] - l0, cdl = Math.cos(dl), cp = r.cphi[i], sp = r.sphi[i];
let x = cp * Math.sin(dl), y = cf0 * sp - sf0 * cp * cdl;
if (sf0 * sp + cf0 * cp * cdl < 0) { const l = Math.hypot(x, y) || 1; x /= l; y /= l; } // far side: onto the rim
const X = cx + k * x, Y = cy - k * y;
if (first) { ctx.moveTo(X, Y); first = false; lx = X; ly = Y; }
else if (Math.abs(X - lx) + Math.abs(Y - ly) > 1 || i === r.n - 1) { ctx.lineTo(X, Y); lx = X; ly = Y; }
}
ctx.closePath();
}
function visible(r, v) {
const cosd = r.c[0] * v.ex + r.c[1] * v.ey + r.c[2] * v.ez, d = Math.acos(Math.max(-1, Math.min(1, cosd)));
return d - r.rad < v.reach && r.rad * v.k > .6;
}
function shapes(set, keys, v) { for (const key of keys) for (const r of set[key] || []) if (visible(r, v)) ring(r, v); }
clockRun(t => {
if (!within(t, on)) return;
const s = vf(t), k = 450 / s.H, l0 = s.lon * DEG, f0 = s.lat * DEG;
const v = { l0, sf0: Math.sin(f0), cf0: Math.cos(f0), k, cx: W / 2 + (s.dx || 0), cy: H / 2 + (s.dy || 0),
ex: Math.cos(f0) * Math.cos(l0), ey: Math.cos(f0) * Math.sin(l0), ez: Math.sin(f0) };
const diag = Math.hypot(W / 2 + Math.abs(s.dx || 0), H / 2 + Math.abs(s.dy || 0));
v.reach = diag >= k ? Math.PI / 2 : Math.asin(diag / k);
const L = k > 900 ? geo.lod[1] : geo.lod[0], all = Object.keys(L);
ctx.setTransform(PX, 0, 0, PX, 0, 0);
ctx.fillStyle = NIGHT; ctx.fillRect(0, 0, W, H);
// roll: clockwise, as the globe's camera and mapXY turn it
if (s.roll) { ctx.translate(v.cx, v.cy); ctx.rotate(s.roll * DEG); ctx.translate(-v.cx, -v.cy); }
ctx.beginPath(); ctx.arc(v.cx, v.cy, k, 0, 2 * Math.PI); ctx.fillStyle = sea; ctx.fill();
ctx.save(); ctx.clip();
ctx.beginPath(); shapes(L, all, v);
ctx.fillStyle = land; ctx.fill(); ctx.strokeStyle = MAPLINE; ctx.lineWidth = 1; ctx.lineJoin = 'bevel'; ctx.stroke();
if (lit) for (const c of all) { const a = lit(c, t); if (a > 0) { ctx.beginPath(); shapes(L, [c], v); ctx.globalAlpha = a * .85; ctx.fillStyle = fillOf(c); ctx.fill(); ctx.globalAlpha = 1; } }
if (provinces || prov) {
const pk = Object.keys(geo.cn);
if (prov) for (const c of pk) { const a = prov(c, t); if (a > 0) { ctx.beginPath(); shapes(geo.cn, [c], v); ctx.globalAlpha = a * .85; ctx.fillStyle = fillOf(c); ctx.fill(); ctx.globalAlpha = 1; } }
if (provinces) { ctx.beginPath(); shapes(geo.cn, pk, v); ctx.setLineDash([4, 3]); ctx.lineWidth = .9; ctx.strokeStyle = MAPLINE; ctx.stroke(); ctx.setLineDash([]); }
}
ctx.restore();
// marks: routes, case dots, city dots (screen px, so they keep their size at every zoom)
const xy = ll => mapXY(ll, { ...s, roll: 0 });
ctx.save(); ctx.beginPath(); ctx.arc(v.cx, v.cy, k, 0, 2 * Math.PI); ctx.clip(); // arcs over the rim would float in space
ctx.strokeStyle = RED; ctx.lineWidth = 3.5; ctx.lineCap = 'round';
const pop = (t0, d = .25) => { const q = ramp01(t, t0, t0 + d); return q && back(q); };
for (const [a, b, t0, dur = .8] of routes) {
const q = ramp01(t, t0, t0 + dur), A = xy(a), B = xy(b);
if (!q || !A || !B) continue;
const lift = Math.hypot(B[0] - A[0], B[1] - A[1]) * .25, mx = (A[0] + B[0]) / 2, my = (A[1] + B[1]) / 2 - lift;
ctx.beginPath(); ctx.moveTo(...A);
for (let i = 1; i <= 24 * q; i++) { const u = i / 24; ctx.lineTo((1 - u) ** 2 * A[0] + 2 * u * (1 - u) * mx + u * u * B[0], (1 - u) ** 2 * A[1] + 2 * u * (1 - u) * my + u * u * B[1]); }
ctx.stroke();
if (q >= 1) dotAt(B, 7 * pop(t0 + dur));
}
ctx.restore();
for (const [lon, lat, t0, r = 7] of dots) { const P = xy([lon, lat]); if (P) dotAt(P, r * pop(t0)); }
ctx.fillStyle = MAPINK;
labels.forEach(l => {
const P = xy(l.ll), a = ramp01(t, l.t0, l.t0 + .3);
if (P && a) { ctx.globalAlpha = a; ctx.beginPath(); ctx.arc(P[0], P[1], 5, 0, 2 * Math.PI); ctx.fill(); ctx.globalAlpha = 1; }
const Q = s.roll ? mapXY(l.ll, s) : P; // the canvas is turned by the roll, the SVG labels are not
const inSafe = Q && Q[0] > 50 && P[0] < 810 && P[1] > 150 && P[1] < 1290;
if (!inSafe) return put(l.e, { o: 0 });
let x = l.side === 'l' ? Q[0] - 14 - l.w : Q[0] + 14;
if (x + l.w > 810) x = Q[0] - 14 - l.w; if (x < 50) x = Q[0] + 14;
put(l.e, { x: Math.max(50, Math.min(810 - l.w, x)), y: Math.max(160, Math.min(1290, Q[1] + 10)), o: a });
});
}, D, { tail: true });
function dotAt([x, y], r) {
if (r <= 0) return;
ctx.fillStyle = RED; ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI); ctx.fill();
ctx.globalAlpha = .25; ctx.beginPath(); ctx.arc(x, y, r * 2.2, 0, 2 * Math.PI); ctx.fill(); ctx.globalAlpha = 1;
}
return { g, view: vf, xy: (ll, t) => mapXY(ll, vf(t)) };
}
/* ---------- cards ---------- */
// the series card: six episodes in a 2 x 3 grid, n (1-6) lit at tLit, the rest dimmed
const EP_POS = [[255, 530], [605, 530], [255, 840], [605, 840], [255, 1150], [605, 1150]], EP_W = 320, EP_H = 280;
function epTile(s, i, x, y) {
const c = G(s, { x, y, o: 0 });
rect(c, -EP_W / 2 - 4, -EP_H / 2 - 4, EP_W + 8, EP_H + 8, { rx: 16, fill: '#15171c' });
clipImg(c, EP_PICS[i], -EP_W / 2, -EP_H / 2, EP_W, EP_H, 12);
rect(c, -EP_W / 2, EP_H / 2 - 74, EP_W, 74, { fill: DARK, opacity: .78 });
T(c, String(i + 1), { x: -EP_W / 2 + 18, y: -EP_H / 2 + 58, size: 56, fill: LIGHT, font: SANS, weight: 600 }).setAttribute('paint-order', 'stroke');
T(c, EP_TITLES[i].toUpperCase(), { x: 0, y: EP_H / 2 - 22, size: 40, fill: LIGHT, font: SANS, weight: 600, anchor: 'middle' });
return c;
}
function seriesCard(s, t0, n, tLit) {
word(s, 'The Pandemic', CX - 20, 290, t0, { size: 120, fill: LIGHT });
T(s, 'A SERIES IN SIX PARTS', { x: CX - 20, y: 360, size: 38, fill: MUTED, font: SANS, weight: 500, anchor: 'middle' }).setAttribute('letter-spacing', '.12em');
sfx(BEAT_ID, t0, 'thud', 1);
const tiles = EP_POS.map(([x, y], i) => { const c = epTile(s, i, x, y); tw(c, { o: 1 }, t0 + .25 + i * .1, .25); return c; });
const [x, y] = EP_POS[n - 1];
const rim = rect(s, x - EP_W / 2 - 10, y - EP_H / 2 - 10, EP_W + 20, EP_H + 20, { rx: 22, fill: 'none', stroke: MARK, 'stroke-width': 10, opacity: 0 });
show(rim, tLit, .15, lin); sfx(BEAT_ID, tLit, 'tick', 1.2);
tiles.forEach((c, i) => { if (i !== n - 1) tw(c, { o: .3 }, tLit, .3); else tw(c, { s: 1.06 }, tLit, .25, back); });
return tiles;
}
// the end card after episode n: the next episode's tile, big, with its number and title (the last one names the series)
function endCard(s, t0, n) {
if (n >= 6) { word(s, 'The Pandemic', CX - 20, 700, t0, { size: 130, fill: LIGHT }); word(s, 'Six parts · the end', CX - 20, 820, t0 + .3, { size: 56, fill: MUTED }); return; }
word(s, 'Next', CX - 20, 330, t0, { size: 90, fill: MARK });
const c = epTile(s, n, CX - 20, 720);
tw(c, { o: 1, s: 1.9 }, t0 + .15, .35, out);
sfx(BEAT_ID, t0 + .15, 'whoosh', .5);
return c;
}
/* ---------- pictures ---------- */
// a found photograph, full bleed with a slow push, tagged with its source (opts as photo(): s0, s1, dx, dy, dim)
function found(g, name, source, t0, t1, opts = {}) {
const im = photo(g, name, t0, t1, { ...opts, ai: false });
srcTag(g, source, 50, 150, t0);
return im;
}
// a picture sized by ART: centred on (x, y), h (or w) px; enters at t0 (rising from dy), or is there when t0 is undefined
function plate(g, name, x, y, { h, w, t0, dy = 60, r = 0 } = {}) {
const [iw, ih] = ART[name], k = w ? w / iw : h / ih, e = G(g, { x, y: t0 === undefined ? y : y + dy, r, o: t0 === undefined ? 1 : 0 });
mk('image', { href: `../img/${name}.webp`, x: -iw * k / 2, y: -ih * k / 2, width: iw * k, height: ih * k }, e);
if (t0 !== undefined) tw(e, { y, o: 1 }, t0, .35, out);
e._x = x; e._y = y;
return e;
}
// a landscape picture larger than the frame, moved by a camera: keys [t, fx, fy, s], the point (fx, fy) of the picture
// (fractions of its width and height) at the frame's centre at scale s; eased between keys, the first held from 0.
// No edge ever shows.
function wide(g, name, keys) {
const [iw, ih] = ART[name], k = Math.max(H / ih, W / iw), Ws = iw * k, Hs = ih * k;
const im = G(g, {});
mk('image', { href: `../img/${name}.webp`, x: -Ws / 2, y: -Hs / 2, width: Ws, height: Hs }, im);
const clamp = (v, size, frame) => size < frame ? frame / 2 : Math.min(size / 2, Math.max(frame - size / 2, v));
const at = ([, fx, fy, s]) => ({ x: clamp(CX - s * (fx - .5) * Ws, Ws * s, W), y: clamp(H / 2 - s * (fy - .5) * Hs, Hs * s, H), s });
put(im, at(keys[0]));
keys.slice(1).forEach((key, i) => { const t = keys[i][0]; tw(im, at(key), t, key[0] - t, io); });
return im;
}
// a doctor's chip: a toned portrait in a red ring. li-wenliang is his own selfie (fair use); doctor-1..7 are AI
// illustrations standing in for the seven others, who are not identified here (tag them)
function liChip(p, x, y, r, t0, { o = 1, img = 'li-wenliang', ring = MARK } = {}) {
const g = G(p, { x, y, s: 0, o: 0 }), k = r * .9;
mk('circle', { r, fill: ring }, g);
mk('image', { href: `../img/${img}.webp`, x: -k, y: -k, width: 2 * k, height: 2 * k, 'clip-path': 'url(#liclip)' }, g);
tw(g, { s: 1, o }, t0, .5, back);
return g;
}