@shadevkumar/agent-wrapped 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1274 @@
1
+ // Agent Wrapped story player. Draws every card on one canvas, tall (9:16) on
2
+ // narrow screens and wide (16:9) on wide ones, so what you watch is exactly
3
+ // what gets saved as an image or a video.
4
+ //
5
+ // The same page plays two kinds of story: your own, built into the file on
6
+ // your computer, and one someone shared, packed into the link after "#v1.".
7
+
8
+ // ---------------------------------------------------------------- story data
9
+
10
+ const COMMAND = "npx @shadevkumar/agent-wrapped";
11
+
12
+ const toast = document.getElementById("toast");
13
+ let toastTimer = 0;
14
+ function notify(message, { stay = false } = {}) {
15
+ if (toast.textContent !== message) toast.textContent = message;
16
+ toast.classList.add("show");
17
+ clearTimeout(toastTimer);
18
+ if (!stay) toastTimer = setTimeout(() => toast.classList.remove("show"), 2800);
19
+ }
20
+
21
+ // Everything the home page needs is set up above the line where the script
22
+ // stops for a link with no story in it.
23
+ for (const btn of document.querySelectorAll("[data-copy-command]")) btn.addEventListener("click", async () => {
24
+ try {
25
+ await navigator.clipboard.writeText(COMMAND);
26
+ btn.textContent = "Copied";
27
+ setTimeout(() => (btn.textContent = "Copy"), 1800);
28
+ } catch {
29
+ notify(`Couldn't copy it. Type ${COMMAND} in your terminal.`);
30
+ }
31
+ });
32
+
33
+ const PLAYER_URL = JSON.parse(document.getElementById("player-url").textContent);
34
+ const OWN = JSON.parse(document.getElementById("data").textContent);
35
+ const SHARED = !OWN;
36
+ // A new link in the same tab, like "Watch Shadev's story", starts over.
37
+ if (SHARED) addEventListener("hashchange", () => location.reload());
38
+ const D = OWN ?? (await openLink());
39
+ if (!D) await new Promise(() => {}); // nothing to play; the page says why
40
+ const YEAR = D.range?.to.slice(0, 4) ?? "";
41
+
42
+ // The public page with no story in its link is the home page.
43
+ async function openLink() {
44
+ document.getElementById("player").hidden = true;
45
+ if (!location.hash) {
46
+ document.getElementById("home").hidden = false;
47
+ typeMoments();
48
+ return null;
49
+ }
50
+ try {
51
+ const d = await unpack(location.hash.replace(/^#v1\./, ""));
52
+ if (typeof d?.prompts === "number" && typeof d.personality?.name === "string") {
53
+ document.getElementById("player").hidden = false;
54
+ return d;
55
+ }
56
+ } catch {}
57
+ document.getElementById("missing").hidden = false;
58
+ return null;
59
+ }
60
+
61
+ // The home page's keys type moments from Shadev's story, the one its
62
+ // "Watch Shadev's story" link plays, so the two always match. Everything it
63
+ // uses lives inside it: it runs before the rest of the script.
64
+ async function typeMoments() {
65
+ const s = await unpack(document.getElementById("featured").hash.replace(/^#v1\./, ""));
66
+ const n = (x) => x.toLocaleString("en-US");
67
+ // The keys that differ from the right spelling stay lit.
68
+ const wrong = (typed, word) => {
69
+ const at = [...typed].flatMap((ch, i) => (ch === word[i] ? [] : [i]));
70
+ return typed.length === word.length ? at : at.slice(0, 1);
71
+ };
72
+ // [what gets typed, which keys stay lit, what it is]
73
+ const MOMENTS = [
74
+ s.topTypo && [s.topTypo.spelling, wrong(s.topTypo.spelling, s.topTypo.word), `Shadev typed this ${n(s.topTypo.count)} times`],
75
+ s.spellings && [s.spellings.spellings[0], wrong(s.spellings.spellings[0], s.spellings.word), `one of Shadev's ${s.spellings.spellings.length} ways to spell ${s.spellings.word}`],
76
+ s.topPrompts[0] && [s.topPrompts[0].text, [], "Shadev's most-sent prompt"],
77
+ s.catchphrase && [s.catchphrase.text, [], `Shadev said this in ${n(s.catchphrase.sessions)} sessions`],
78
+ s.night && [s.night.latest, [], "Shadev's latest prompt of the year"],
79
+ ].filter((m) => m && m[0].length <= 10);
80
+ const row = document.getElementById("home-keys");
81
+ const note = document.getElementById("home-note");
82
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
83
+ const key = (ch) => {
84
+ const k = document.createElement("span");
85
+ k.className = ch === " " ? "key space" : "key";
86
+ k.textContent = ch;
87
+ return k;
88
+ };
89
+ const show = ([word, lit, what]) => {
90
+ row.replaceChildren(...[...word].map(key));
91
+ for (const i of lit) row.children[i].classList.add("lit");
92
+ note.textContent = what;
93
+ };
94
+ if (matchMedia("(prefers-reduced-motion: reduce)").matches) return show(MOMENTS[0]);
95
+ for (let m = 0; ; m = (m + 1) % MOMENTS.length) {
96
+ const [word, lit, what] = MOMENTS[m];
97
+ for (const [i, ch] of [...word].entries()) {
98
+ const k = row.appendChild(key(ch));
99
+ k.classList.add("down");
100
+ await wait(70);
101
+ k.classList.remove("down");
102
+ if (lit.includes(i)) k.classList.add("lit");
103
+ await wait(60 + Math.random() * 90);
104
+ }
105
+ note.textContent = what;
106
+ note.classList.add("show");
107
+ await wait(2600);
108
+ note.classList.remove("show");
109
+ while (row.lastChild) {
110
+ row.lastChild.remove();
111
+ await wait(38);
112
+ }
113
+ await wait(450);
114
+ }
115
+ }
116
+
117
+ // JSON, compressed and written with link-safe characters.
118
+ async function pack(data) {
119
+ const stream = new Blob([JSON.stringify(data)]).stream().pipeThrough(new CompressionStream("deflate-raw"));
120
+ const bytes = new Uint8Array(await new Response(stream).arrayBuffer());
121
+ let bin = "";
122
+ for (const b of bytes) bin += String.fromCharCode(b);
123
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
124
+ }
125
+
126
+ async function unpack(text) {
127
+ const bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
128
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
129
+ return JSON.parse(await new Response(stream).text());
130
+ }
131
+ const REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;
132
+
133
+ // Each card has up to three parts: a heading, a visual (the keys) and words
134
+ // below. A shape decides where they go:
135
+ // - tall: stacked top to bottom, centred as one block
136
+ // - wide: the visual on the left, heading and words on the right
137
+ const SHAPES = {
138
+ tall: {
139
+ W: 1080, H: 1920, gap: 100, space: [150, 1700],
140
+ column: { x: 96, w: 888 }, single: { x: 96, w: 888 },
141
+ },
142
+ wide: {
143
+ W: 1920, H: 1080, gap: 56, space: [110, 930],
144
+ left: { x: 140, w: 780 }, right: { x: 1000, w: 780 }, single: { x: 260, w: 1400 },
145
+ },
146
+ };
147
+ let shape = SHAPES.tall; // the shape being drawn right now
148
+
149
+ // One graphite keyboard for every card. Dark keys with white legends; the one
150
+ // key that matters (a wrong key, a reveal) is the light one.
151
+ const KEYS = {
152
+ plate: "#1D1E21", ink: "#F1F1EF", soft: "#A4A6AC", faint: "#70737A",
153
+ cap: "#2C2E32", top: "#36383D", side: "#131416", legend: "#EDEDEB",
154
+ };
155
+ const LIT = { cap: "#E4E4E0", top: "#F6F6F3", side: "#8E8F8C", legend: "#1D1E21" };
156
+ const GHOST = { cap: "rgba(255,255,255,0.035)", top: "rgba(255,255,255,0.05)", side: "rgba(0,0,0,0.3)", legend: KEYS.legend, flat: true };
157
+
158
+ // ---------------------------------------------------------------- helpers
159
+
160
+ const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
161
+ const easeOut = (x) => 1 - Math.pow(1 - clamp(x), 3);
162
+ const easeBack = (x) => {
163
+ const c = 1.7;
164
+ const t = clamp(x) - 1;
165
+ return 1 + (c + 1) * t * t * t + c * t * t;
166
+ };
167
+ const fade = (t, at, dur = 0.45) => (REDUCED ? 1 : easeOut((t - at) / dur));
168
+ const num = (n) => Math.round(n).toLocaleString("en-US");
169
+ const day = (iso) =>
170
+ new Date(`${iso}T12:00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric" });
171
+
172
+ function font(size, { family = "Newsreader", weight = 400, style = "normal" } = {}) {
173
+ return `${style} ${weight} ${size}px "${family}"`;
174
+ }
175
+
176
+ // Draws wrapped text inside box `b`; returns the y below the last line.
177
+ function text(ctx, b, str, y, o = {}) {
178
+ const size = o.size ?? 46;
179
+ const lh = size * (o.lh ?? (o.family === "Geist" ? 1.1 : 1.3));
180
+ ctx.save();
181
+ ctx.font = font(size, o);
182
+ // Large sans headings sit tighter, like display type.
183
+ if (o.family === "Geist" && size >= 56) ctx.letterSpacing = `${-size * 0.03}px`;
184
+ ctx.fillStyle = o.color;
185
+ ctx.globalAlpha = o.alpha ?? 1;
186
+ ctx.textAlign = o.align ?? "left";
187
+ ctx.textBaseline = "alphabetic";
188
+ const x = o.align === "center" ? b.x + b.w / 2 : o.align === "right" ? b.x + b.w : b.x;
189
+ const lines = wrap(ctx, str, b.w);
190
+ if (!o.measure) lines.forEach((l, i) => ctx.fillText(l, x, y + size + i * lh));
191
+ ctx.restore();
192
+ return y + size + (lines.length - 1) * lh + size * 0.45;
193
+ }
194
+
195
+ function wrap(ctx, str, max) {
196
+ const lines = [];
197
+ for (const para of String(str).split("\n")) {
198
+ let line = "";
199
+ for (const word of para.split(" ")) {
200
+ const next = line ? `${line} ${word}` : word;
201
+ if (ctx.measureText(next).width > max && line) {
202
+ lines.push(line);
203
+ line = word;
204
+ } else line = next;
205
+ }
206
+ lines.push(line);
207
+ }
208
+ return lines;
209
+ }
210
+
211
+ function textWidth(ctx, str, size, o) {
212
+ ctx.save();
213
+ ctx.font = font(size, o);
214
+ const w = ctx.measureText(str).width;
215
+ ctx.restore();
216
+ return w;
217
+ }
218
+
219
+ function roundRect(ctx, x, y, w, h, r) {
220
+ ctx.beginPath();
221
+ ctx.roundRect(x, y, w, h, r);
222
+ }
223
+
224
+ // One low-profile keycap, centred on (cx, cy). `press` 0..1 pushes the top
225
+ // down and lights it from below, like a backlit key.
226
+ // `label` is a single centred legend; `lines` stacks several (left-aligned
227
+ // with `left: true`), and `right` sits at the far edge.
228
+ function cap(ctx, cx, cy, w, h, label, o) {
229
+ const scale = o.scale ?? 1;
230
+ if (scale <= 0 || w <= 0) return;
231
+ const s = Math.min(w, h);
232
+ const depth = Math.min(s * 0.07, 12);
233
+ const press = clamp(o.press ?? 0);
234
+ const r = Math.min(s * 0.14, 30);
235
+ ctx.save();
236
+ ctx.globalAlpha = o.alpha ?? 1;
237
+ ctx.translate(cx, cy);
238
+ ctx.scale(scale, scale);
239
+ ctx.translate(-w / 2, -h / 2);
240
+ roundRect(ctx, 0, 0, w, h, r);
241
+ if (!o.flat) {
242
+ ctx.shadowColor = press > 0 ? `rgba(255,255,255,${0.28 * press})` : "rgba(0,0,0,0.45)";
243
+ ctx.shadowBlur = press > 0 ? Math.min(s * 0.5, 90) : Math.min(s * 0.22, 44);
244
+ ctx.shadowOffsetY = press > 0 ? 0 : Math.min(s * 0.08, 16);
245
+ }
246
+ ctx.fillStyle = o.side;
247
+ ctx.fill();
248
+ ctx.shadowColor = "transparent";
249
+ const top = depth * 0.6 * press;
250
+ const faceH = h - depth;
251
+ roundRect(ctx, 1.5, top, w - 3, faceH, r * 0.92);
252
+ const face = ctx.createLinearGradient(0, top, 0, top + faceH);
253
+ face.addColorStop(0, o.top ?? o.cap);
254
+ face.addColorStop(1, o.cap);
255
+ ctx.fillStyle = face;
256
+ ctx.fill();
257
+ // A hairline of light along the top edge.
258
+ const edge = ctx.createLinearGradient(0, top, 0, top + faceH * 0.5);
259
+ edge.addColorStop(0, "rgba(255,255,255,0.16)");
260
+ edge.addColorStop(1, "rgba(255,255,255,0)");
261
+ ctx.strokeStyle = edge;
262
+ ctx.lineWidth = 1.5;
263
+ ctx.stroke();
264
+
265
+ const midY = top + faceH / 2;
266
+ ctx.fillStyle = o.legend;
267
+ ctx.textBaseline = "middle";
268
+ if (label) {
269
+ ctx.font = font(o.fontSize ?? s * 0.4, { family: "Geist", weight: o.weight ?? 500 });
270
+ ctx.textAlign = "center";
271
+ ctx.fillText(label, w / 2, midY + s * 0.02);
272
+ }
273
+ const pad = o.pad ?? 40;
274
+ if (o.lines) {
275
+ const gap = 14;
276
+ const total = o.lines.reduce((sum, l) => sum + l.size, 0) + gap * (o.lines.length - 1);
277
+ let y = midY - total / 2;
278
+ for (const l of o.lines) {
279
+ ctx.font = font(l.size, l);
280
+ ctx.globalAlpha = (o.alpha ?? 1) * (l.alpha ?? 1);
281
+ ctx.textAlign = o.left ? "left" : "center";
282
+ ctx.fillText(l.text, o.left ? pad : w / 2, y + l.size / 2);
283
+ y += l.size + gap;
284
+ }
285
+ ctx.globalAlpha = o.alpha ?? 1;
286
+ }
287
+ if (o.right) {
288
+ ctx.font = font(o.right.size, o.right);
289
+ ctx.textAlign = "right";
290
+ ctx.fillText(o.right.text, w - pad, midY);
291
+ }
292
+ ctx.restore();
293
+ }
294
+
295
+ const pressAt = (local) => (local >= 0 && local < 0.14 ? 1 - local / 0.14 : 0);
296
+
297
+ // Types `labels` onto a row of caps centred in box `b`, one key every `step` seconds.
298
+ function typeRow(ctx, b, labels, cy, size, t, t0, fx, cw, o = {}) {
299
+ const gap = size * 0.14;
300
+ const widths = labels.map((l) => (o.narrow?.(l) ? size * 0.55 : size));
301
+ let total = widths.reduce((a, c) => a + c, 0) + gap * (labels.length - 1);
302
+ const fit = Math.min(1, b.w / total);
303
+ total *= fit;
304
+ let x = b.x + b.w / 2 - total / 2;
305
+ const step = o.step ?? 0.1;
306
+ labels.forEach((label, i) => {
307
+ const w = widths[i] * fit;
308
+ const at = t0 + i * step;
309
+ fx.key(at);
310
+ const local = REDUCED ? 9 : t - at;
311
+ if (local >= 0) {
312
+ cap(ctx, x + w / 2, cy, w, size * fit, label, {
313
+ ...cw,
314
+ scale: 0.7 + 0.3 * easeBack(local / 0.2),
315
+ alpha: clamp(local / 0.08),
316
+ press: local < 0.16 ? 1 - local / 0.16 : 0,
317
+ });
318
+ }
319
+ x += w + gap * fit;
320
+ });
321
+ }
322
+
323
+ // "The Midnight Foreman" -> "MF"
324
+ function initials(name) {
325
+ return name
326
+ .replace(/^The /, "")
327
+ .split(/[\s-]+/)
328
+ .map((w) => w[0])
329
+ .join("")
330
+ .slice(0, 2)
331
+ .toUpperCase();
332
+ }
333
+
334
+ function watermark(ctx, cw) {
335
+ text(ctx, { x: 0, w: shape.W }, `made with ${COMMAND}`, shape.H - (shape === SHAPES.wide ? 84 : 124), {
336
+ family: "Geist", weight: 500, size: 26, color: cw.faint, align: "center",
337
+ });
338
+ }
339
+
340
+ // Graphite with one soft light from above.
341
+ function background(ctx) {
342
+ ctx.fillStyle = KEYS.plate;
343
+ ctx.fillRect(0, 0, shape.W, shape.H);
344
+ const light = ctx.createRadialGradient(shape.W / 2, -shape.H * 0.15, 0, shape.W / 2, -shape.H * 0.15, Math.max(shape.W, shape.H));
345
+ light.addColorStop(0, "rgba(255,255,255,0.07)");
346
+ light.addColorStop(1, "rgba(255,255,255,0)");
347
+ ctx.fillStyle = light;
348
+ ctx.fillRect(0, 0, shape.W, shape.H);
349
+ }
350
+
351
+ // ---------------------------------------------------------------- sound
352
+
353
+ // Synthesised clacks and a chime: no audio files, nothing downloaded.
354
+ const Sound = {
355
+ ctx: null,
356
+ master: null,
357
+ on: true,
358
+ noise: null,
359
+ init() {
360
+ if (this.ctx) return;
361
+ try {
362
+ this.ctx = new AudioContext();
363
+ } catch {
364
+ return;
365
+ }
366
+ this.master = this.ctx.createGain();
367
+ this.master.gain.value = 0.55;
368
+ this.master.connect(this.ctx.destination);
369
+ const len = Math.floor(this.ctx.sampleRate * 0.05);
370
+ this.noise = this.ctx.createBuffer(1, len, this.ctx.sampleRate);
371
+ const data = this.noise.getChannelData(0);
372
+ for (let i = 0; i < len; i++) data[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, 4);
373
+ },
374
+ key() {
375
+ if (!this.on || !this.ctx) return;
376
+ const c = this.ctx;
377
+ const now = c.currentTime;
378
+ const src = c.createBufferSource();
379
+ src.buffer = this.noise;
380
+ src.playbackRate.value = 0.8 + Math.random() * 0.5;
381
+ const band = c.createBiquadFilter();
382
+ band.type = "bandpass";
383
+ band.frequency.value = 1800 + Math.random() * 1400;
384
+ band.Q.value = 1.2;
385
+ const g = c.createGain();
386
+ g.gain.value = 0.9;
387
+ src.connect(band).connect(g).connect(this.master);
388
+ src.start(now);
389
+ // The low "thock" of the key bottoming out.
390
+ const osc = c.createOscillator();
391
+ const og = c.createGain();
392
+ osc.frequency.setValueAtTime(190 + Math.random() * 40, now);
393
+ osc.frequency.exponentialRampToValueAtTime(70, now + 0.05);
394
+ og.gain.setValueAtTime(0.35, now);
395
+ og.gain.exponentialRampToValueAtTime(0.001, now + 0.07);
396
+ osc.connect(og).connect(this.master);
397
+ osc.start(now);
398
+ osc.stop(now + 0.08);
399
+ },
400
+ ding() {
401
+ if (!this.on || !this.ctx) return;
402
+ const c = this.ctx;
403
+ const now = c.currentTime;
404
+ for (const [f, v] of [[880, 0.22], [1320, 0.12], [1760, 0.06]]) {
405
+ const osc = c.createOscillator();
406
+ const g = c.createGain();
407
+ osc.type = "sine";
408
+ osc.frequency.value = f;
409
+ g.gain.setValueAtTime(v, now);
410
+ g.gain.exponentialRampToValueAtTime(0.0005, now + 1.1);
411
+ osc.connect(g).connect(this.master);
412
+ osc.start(now);
413
+ osc.stop(now + 1.2);
414
+ }
415
+ },
416
+ };
417
+
418
+ // Fires sounds when playback crosses their moment, once per crossing.
419
+ function effects(prev, t, live) {
420
+ const crossed = (at) => live && prev < at && at <= t;
421
+ return {
422
+ key: (at) => crossed(at) && Sound.key(),
423
+ ding: (at) => crossed(at) && Sound.ding(),
424
+ };
425
+ }
426
+ const SILENT = { key() {}, ding() {} };
427
+
428
+ // ---------------------------------------------------------------- cards
429
+
430
+ // Every part is drawn as draw(ctx, t, fx, cw, b): `b` is its box ({ x, w }),
431
+ // and it starts at y = 0. The layout moves it into place afterwards.
432
+ function buildCards(D) {
433
+ const cards = [];
434
+ const add = (card) => cards.push({ cw: KEYS, ...card });
435
+ const chars = (s) => [...s];
436
+ const narrow = (l) => l === "," || l === ":" || l === ".";
437
+ const big = (size) => ({ family: "Geist", weight: 600, size });
438
+ const say = (size = 50) => ({ size, style: "italic" });
439
+
440
+ add({
441
+ id: "intro", name: "Intro", dur: 6,
442
+ alt: "Your agents have been talking about you.",
443
+ visual: (ctx, t, fx, cw, b) => typeRow(ctx, b, ["h", "e", "y"], 120, 210, t, 0.4, fx, cw, { step: 0.17 }),
444
+ words(ctx, t, fx, cw, b) {
445
+ const y = text(ctx, b, "Your agents have been talking about you.", 0, { ...big(78), color: cw.ink, alpha: fade(t, 1.3) });
446
+ if (D.range) {
447
+ text(ctx, b, `Here's what we noticed, ${day(D.range.from)} to ${day(D.range.to)}.`, y + 20, {
448
+ ...say(48), color: cw.soft, alpha: fade(t, 2.1),
449
+ });
450
+ }
451
+ },
452
+ });
453
+
454
+ add({
455
+ id: "prompts", name: "Prompts", dur: 6.5,
456
+ alt: `You sent your agents ${num(D.prompts)} prompts over ${num(D.activeDays)} days.`,
457
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "Prompts you sent us", 0, { ...say(54), color: cw.soft, alpha: fade(t, 0.2) }),
458
+ visual: (ctx, t, fx, cw, b) => typeRow(ctx, b, chars(num(D.prompts)), 100, 168, t, 0.7, fx, cw, { narrow, step: 0.13 }),
459
+ words: (ctx, t, fx, cw, b) =>
460
+ text(ctx, b, `Over ${num(D.activeDays)} days and ${num(D.sessions)} sessions.`, 0, {
461
+ ...big(72), color: cw.ink, alpha: fade(t, 1.8),
462
+ }),
463
+ });
464
+
465
+ if (D.topTypo) {
466
+ const tt = D.topTypo;
467
+ add({
468
+ id: "top-typo", name: "Top typo", dur: 6.5,
469
+ alt: `You typed ${tt.spelling} ${num(tt.count)} times. We read it as ${tt.word}.`,
470
+ visual: (ctx, t, fx, cw, b) => typeRow(ctx, b, chars(tt.spelling), 120, 220, t, 0.4, fx, cw, { step: 0.16 }),
471
+ words(ctx, t, fx, cw, b) {
472
+ const y = text(ctx, b, `You typed ${tt.spelling} ${num(tt.count)} times.`, 0, { ...big(76), color: cw.ink, alpha: fade(t, 1.3) });
473
+ text(ctx, b, `We read it as “${tt.word}”. Every single time.`, y + 16, { ...say(), color: cw.soft, alpha: fade(t, 2.2) });
474
+ },
475
+ });
476
+ }
477
+
478
+ if (D.spellings) {
479
+ const sp = D.spellings;
480
+ const list = sp.spellings.slice(0, 24);
481
+ const each = clamp(5 / list.length, 0.14, 0.4);
482
+ const t0 = 0.6;
483
+ const settle = t0 + list.length * each;
484
+ add({
485
+ id: "spellings", name: "Spellings", dur: settle + 4,
486
+ alt: `There are ${sp.spellings.length + 1} ways to spell ${sp.word}. You used all of them.`,
487
+ head: (ctx, t, fx, cw, b) => text(ctx, b, `How you spell ${sp.word}`, 0, { ...big(70), color: cw.ink }),
488
+ visual(ctx, t, fx, cw, b) {
489
+ const i = REDUCED ? list.length : Math.floor((t - t0) / each);
490
+ const done = i >= list.length;
491
+ list.forEach((_, k) => fx.key(t0 + k * each));
492
+ fx.ding(settle);
493
+ if (t < t0 && !REDUCED) return;
494
+ const word = done ? sp.word : list[clamp(i, 0, list.length - 1)];
495
+ const local = done ? t - settle : (t - t0) % each;
496
+ const size = Math.min(150, (b.w / word.length) * 0.86);
497
+ const gap = size * 0.14;
498
+ let x = b.x + b.w / 2 - (word.length * size + (word.length - 1) * gap) / 2;
499
+ for (const ch of word) {
500
+ cap(ctx, x + size / 2, 100, size, size, ch, {
501
+ ...(done ? cw : LIT), press: local < 0.1 && !REDUCED ? 1 - local / 0.1 : 0,
502
+ });
503
+ x += size + gap;
504
+ }
505
+ },
506
+ words(ctx, t, fx, cw, b) {
507
+ // Drawn invisibly before it settles, so the layout keeps its place.
508
+ const a = t >= settle || REDUCED ? 1 : 0;
509
+ const y = text(ctx, b, `${sp.spellings.length + 1} ways to spell it.`, 0, {
510
+ ...big(72), color: cw.ink, alpha: a * fade(t, settle + 0.2),
511
+ });
512
+ text(ctx, b, "We know, because you used all of them.", y + 16, { ...say(), color: cw.soft, alpha: a * fade(t, settle + 1) });
513
+ },
514
+ });
515
+ }
516
+
517
+ if (D.slip) {
518
+ const s = D.slip;
519
+ const rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"];
520
+ const taps = [1.4, 1.75, 2.1, 2.45];
521
+ add({
522
+ id: "slip", name: "Missed key", dur: 7,
523
+ alt: `You meant ${s.meant.toUpperCase()} and hit ${s.hit.toUpperCase()}, ${num(s.count)} times.`,
524
+ head: (ctx, t, fx, cw, b) =>
525
+ text(ctx, b, `You meant ${s.meant.toUpperCase()}.\nYou hit ${s.hit.toUpperCase()}.`, 0, { ...big(84), color: cw.ink }),
526
+ visual(ctx, t, fx, cw, b) {
527
+ const gap = 10;
528
+ const size = Math.min(82, (b.w - 9 * gap) / 10.6);
529
+ taps.forEach((at) => fx.key(at));
530
+ const sinceTap = Math.min(...taps.map((at) => (t >= at ? t - at : 9)));
531
+ rows.forEach((row, r) => {
532
+ const rowW = row.length * size + (row.length - 1) * gap;
533
+ const x0 = b.x + b.w / 2 - rowW / 2 + r * size * 0.3;
534
+ [...row].forEach((ch, c) => {
535
+ const cx = x0 + c * (size + gap) + size / 2;
536
+ const cy = size / 2 + 20 + r * (size + gap + 8);
537
+ const isHit = ch === s.hit && t >= taps[0];
538
+ if (ch === s.meant && t >= 0.8) {
539
+ ctx.save();
540
+ ctx.strokeStyle = KEYS.ink;
541
+ ctx.lineWidth = 3;
542
+ ctx.globalAlpha = 0.55 + 0.45 * Math.sin(t * 5) ** 2;
543
+ roundRect(ctx, cx - size / 2 - 10, cy - size / 2 - 10, size + 20, size + 26, 22);
544
+ ctx.stroke();
545
+ ctx.restore();
546
+ }
547
+ cap(ctx, cx, cy, size, size, ch, {
548
+ ...(isHit ? LIT : cw), fontSize: size * 0.42, press: isHit && sinceTap < 0.14 ? 1 - sinceTap / 0.14 : 0,
549
+ });
550
+ });
551
+ });
552
+ },
553
+ words: (ctx, t, fx, cw, b) =>
554
+ text(ctx, b, `${num(s.count)} times. They're neighbours, so we let it slide.`, 0, { ...say(), color: cw.soft, alpha: fade(t, 2.8) }),
555
+ });
556
+ }
557
+
558
+ if (D.topPrompts.length) {
559
+ const top = D.topPrompts;
560
+ const most = top[0].count;
561
+ const last = 0.6 + (top.length - 1) * 0.35;
562
+ add({
563
+ id: "top-prompts", name: "Favourite prompts", dur: 6.5,
564
+ alt: `Your favourite things to say to us: ${top.map((p) => `${p.text}, ${p.count} times`).join("; ")}.`,
565
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "Your favourite things to say to us", 0, { ...big(70), color: cw.ink }),
566
+ visual(ctx, t, fx, cw, b) {
567
+ top.forEach((p, i) => {
568
+ const at = 0.6 + i * 0.35;
569
+ fx.key(at);
570
+ const local = REDUCED ? 9 : t - at;
571
+ if (local < 0) return;
572
+ const label = { text: `“${p.text}”`, size: 44, family: "Geist", weight: 500 };
573
+ const right = { text: `${p.count}×`, size: 40, family: "Geist", weight: 400 };
574
+ const least = textWidth(ctx, label.text, 46, label) + textWidth(ctx, right.text, 46, right) + 140;
575
+ const w = Math.min(b.w, least + (b.w - least) * (p.count / most) * easeOut(local / 0.5));
576
+ cap(ctx, b.x + w / 2, 80 + i * 190, w, 140, "", { ...cw, left: true, lines: [label], right, press: pressAt(local) });
577
+ });
578
+ },
579
+ words: (ctx, t, fx, cw, b) =>
580
+ text(ctx, b, "Short, clear and a little bossy. We like it.", 0, { ...say(), color: cw.soft, alpha: fade(t, last + 0.5) }),
581
+ });
582
+ }
583
+
584
+ if (D.catchphrase) {
585
+ const c = D.catchphrase;
586
+ add({
587
+ id: "catchphrase", name: "Catchphrase", dur: 6,
588
+ alt: `Your catchphrase: ${c.text}. You said it in ${c.sessions} different sessions.`,
589
+ head(ctx, t, fx, cw, b) {
590
+ fx.ding(0.5);
591
+ const y = text(ctx, b, "Your catchphrase", 0, { ...say(54), color: cw.soft });
592
+ text(ctx, b, `“${c.text}”`, y + 30, { size: 150, weight: 600, style: "italic", color: cw.ink, lh: 1.02, alpha: fade(t, 0.5, 0.7) });
593
+ },
594
+ words: (ctx, t, fx, cw, b) =>
595
+ text(ctx, b, `You said it in ${num(c.sessions)} different sessions. It's basically your motto now.`, 0, {
596
+ ...say(), color: cw.soft, alpha: fade(t, 1.6),
597
+ }),
598
+ });
599
+ }
600
+
601
+ if (D.talk) {
602
+ const k = D.talk;
603
+ const word = k.nickname?.word ?? "please";
604
+ const lines = [
605
+ k.nickname ? `You called us “${k.nickname.word}” ${num(k.nickname.count)} times.` : `You said please ${num(k.please)} times.`,
606
+ k.nickname && k.please + k.thanks > 0 && `Please ${num(k.please)} times. Thanks ${num(k.thanks)}.${k.thanks * 3 < k.please ? " We noticed." : ""}`,
607
+ !k.nickname && `And thanks ${num(k.thanks)} times.`,
608
+ k.checkIns >= 20 && `And you asked “okay?” ${num(k.checkIns)} times.`,
609
+ ].filter(Boolean);
610
+ add({
611
+ id: "talk", name: "How you talk", dur: 7,
612
+ alt: `How you talk to us. ${lines.join(" ")}`,
613
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "How you talk to us", 0, { ...say(54), color: cw.soft }),
614
+ visual: (ctx, t, fx, cw, b) => typeRow(ctx, b, chars(word), 120, 210, t, 0.4, fx, cw, { step: 0.16 }),
615
+ words(ctx, t, fx, cw, b) {
616
+ let y = text(ctx, b, lines[0], 0, { ...big(72), color: cw.ink, alpha: fade(t, 1.4) });
617
+ lines.slice(1).forEach((line, i) => {
618
+ y = text(ctx, b, line, y + 18, { ...say(), color: cw.soft, alpha: fade(t, 2.2 + i * 0.8) });
619
+ });
620
+ },
621
+ });
622
+ }
623
+
624
+ if (D.night) {
625
+ const n = D.night;
626
+ add({
627
+ id: "night", name: "Late night", dur: 6.5,
628
+ alt: `Your latest prompt after midnight was at ${n.latest}. ${num(n.prompts)} prompts after midnight.`,
629
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "Your latest prompt after midnight", 0, { ...say(54), color: cw.soft }),
630
+ visual: (ctx, t, fx, cw, b) => typeRow(ctx, b, chars(n.latest), 110, 190, t, 0.6, fx, cw, { narrow, step: 0.15 }),
631
+ words: (ctx, t, fx, cw, b) =>
632
+ text(ctx, b, `${num(n.prompts)} prompts after 12 a.m. We were up too.`, 0, { ...big(68), color: cw.ink, alpha: fade(t, 1.8) }),
633
+ });
634
+ }
635
+
636
+ if (D.streak) {
637
+ const s = D.streak;
638
+ const shown = Math.min(s.days, 42);
639
+ const step = clamp(2.4 / shown, 0.04, 0.12);
640
+ const end = 0.4 + shown * step;
641
+ add({
642
+ id: "streak", name: "Streak", dur: 4 + shown * step,
643
+ alt: `${s.days} days in a row, ${day(s.from)} to ${day(s.to)}.`,
644
+ visual(ctx, t, fx, cw, b) {
645
+ const gap = 20;
646
+ const size = Math.min(104, (b.w - 6 * gap) / 7);
647
+ const x0 = b.x + b.w / 2 - (7 * size + 6 * gap) / 2;
648
+ for (let i = 0; i < shown; i++) {
649
+ const at = 0.4 + i * step;
650
+ fx.key(at);
651
+ const local = REDUCED ? 9 : t - at;
652
+ const lit = local >= 0;
653
+ cap(ctx, x0 + (i % 7) * (size + gap) + size / 2, size / 2 + 10 + Math.floor(i / 7) * (size + gap + 10), size, size,
654
+ lit ? String(i + 1) : "", {
655
+ ...(lit ? cw : GHOST),
656
+ fontSize: size * 0.33,
657
+ press: lit ? pressAt(local) : 0,
658
+ });
659
+ }
660
+ },
661
+ words(ctx, t, fx, cw, b) {
662
+ const y = text(ctx, b, `${s.days} days in a row.`, 0, { ...big(84), color: cw.ink, alpha: fade(t, end) });
663
+ text(ctx, b, `${day(s.from)} to ${day(s.to)}. Not one day off.`, y + 10, { ...say(), color: cw.soft, alpha: fade(t, end + 0.7) });
664
+ },
665
+ });
666
+ }
667
+
668
+ if (D.agents) {
669
+ const a = D.agents;
670
+ const parts = [["Codex", a.codex], ["Claude", a.claude]].filter(([, v]) => v > 0);
671
+ add({
672
+ id: "agents", name: "Your agents", dur: 6.5,
673
+ alt: `${num(a.hours)} hours of agent work. Codex ${Math.round(a.codex * 100)} percent, Claude ${Math.round(a.claude * 100)} percent.`,
674
+ head: (ctx, t, fx, cw, b) => text(ctx, b, `${num(a.hours)} hours of work, split between two of us.`, 0, { ...big(72), color: cw.ink }),
675
+ visual(ctx, t, fx, cw, b) {
676
+ parts.forEach(([name, share], i) => {
677
+ const at = 0.7 + i * 0.4;
678
+ fx.key(at);
679
+ const local = REDUCED ? 9 : t - at;
680
+ if (local < 0) return;
681
+ const label = { text: `${name} ${Math.round(share * 100)}%`, size: 48, family: "Geist", weight: 500 };
682
+ const least = textWidth(ctx, label.text, 52, label) + 100;
683
+ const w = Math.max(least, b.w * share) * easeOut(local / 0.6);
684
+ cap(ctx, b.x + w / 2, 95 + i * 230, w, 170, "", { ...cw, left: true, lines: [label], press: pressAt(local) });
685
+ });
686
+ },
687
+ words: (ctx, t, fx, cw, b) =>
688
+ a.bothDays > 0 &&
689
+ text(ctx, b, `Some days you needed both of us. ${num(a.bothDays)} of them, to be exact.`, 0, {
690
+ ...say(), color: cw.soft, alpha: fade(t, 2),
691
+ }),
692
+ });
693
+ }
694
+
695
+ if (D.work) {
696
+ const w = D.work;
697
+ const rows = [["ran your tests", w.tests], ["made commits", w.commits], ["got stopped by you", w.stops]].filter(([, n]) => n > 0);
698
+ const most = Math.max(...rows.map(([, n]) => n));
699
+ const last = 0.6 + (rows.length - 1) * 0.35;
700
+ add({
701
+ id: "work", name: "What we did", dur: 7,
702
+ alt: `What we got done, since ${day(w.since)}: ${rows.map(([what, n]) => `${what}, ${num(n)} times`).join("; ")}.${w.languages.length ? ` Mostly in ${w.languages.join(" and ")}.` : ""}`,
703
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "What we got done", 0, { ...big(70), color: cw.ink }),
704
+ visual(ctx, t, fx, cw, b) {
705
+ rows.forEach(([what, n], i) => {
706
+ const at = 0.6 + i * 0.35;
707
+ fx.key(at);
708
+ const local = REDUCED ? 9 : t - at;
709
+ if (local < 0) return;
710
+ const label = { text: what, size: 44, family: "Geist", weight: 500 };
711
+ const right = { text: `${num(n)}×`, size: 40, family: "Geist", weight: 400 };
712
+ const least = textWidth(ctx, label.text, 46, label) + textWidth(ctx, right.text, 46, right) + 140;
713
+ const width = Math.min(b.w, least + (b.w - least) * (n / most) * easeOut(local / 0.5));
714
+ cap(ctx, b.x + width / 2, 80 + i * 190, width, 140, "", { ...cw, left: true, lines: [label], right, press: pressAt(local) });
715
+ });
716
+ },
717
+ words(ctx, t, fx, cw, b) {
718
+ const y = w.languages.length
719
+ ? text(ctx, b, `Mostly in ${w.languages.join(" and ")}.`, 0, { ...say(), color: cw.soft, alpha: fade(t, last + 0.5) }) + 20
720
+ : 0;
721
+ text(ctx, b, `Counted from the logs your agents keep, since ${day(w.since)}.`, y, {
722
+ size: 34, color: cw.faint, alpha: fade(t, last + 1.2),
723
+ });
724
+ },
725
+ });
726
+ }
727
+
728
+ if (D.money) {
729
+ const m = D.money;
730
+ add({
731
+ id: "money", name: "API value", dur: 7,
732
+ alt: `At least ${num(m.atLeastUsd)} US dollars of agent work at public API prices.`,
733
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "Our work, at public API prices", 0, { ...say(54), color: cw.soft }),
734
+ visual: (ctx, t, fx, cw, b) => typeRow(ctx, b, chars(`$${num(m.atLeastUsd)}`), 100, 150, t, 0.6, fx, cw, { narrow, step: 0.12 }),
735
+ words(ctx, t, fx, cw, b) {
736
+ const y = text(ctx, b, "At least. We priced what we could count exactly, and the rest at the cheapest rate.", 0, {
737
+ ...say(), color: cw.soft, alpha: fade(t, 1.8),
738
+ });
739
+ text(ctx, b, `Public prices on ${day(m.pricesAsOf)}. Your plan probably cost a lot less.`, y + 20, {
740
+ size: 34, color: cw.faint, alpha: fade(t, 2.6),
741
+ });
742
+ },
743
+ });
744
+ }
745
+
746
+ const p = D.personality;
747
+ const reveal = 2.2;
748
+ add({
749
+ id: "personality", name: "Personality", dur: 8,
750
+ alt: `You are ${p.name}. ${p.line}`,
751
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "So, who are you?", 0, { ...say(54), color: cw.soft }),
752
+ visual(ctx, t, fx, cw, b) {
753
+ [0.5, 0.8, 1.05, 1.25, 1.42, 1.56, 1.68, 1.78].forEach((at) => fx.key(at));
754
+ fx.ding(reveal);
755
+ const revealed = t >= reveal || REDUCED;
756
+ cap(ctx, b.x + b.w / 2, 150, 280, 280, revealed ? initials(p.name) : "?", {
757
+ ...(revealed ? LIT : cw),
758
+ fontSize: 104,
759
+ weight: 600,
760
+ scale: revealed ? 0.9 + 0.1 * easeBack((t - reveal) / 0.3) : 1 + Math.sin(t * 40) * 0.04,
761
+ press: !revealed && (t * 6) % 1 < 0.3 ? 1 : 0,
762
+ });
763
+ },
764
+ words(ctx, t, fx, cw, b) {
765
+ const a = t >= reveal || REDUCED ? 1 : 0;
766
+ const y = text(ctx, b, p.name, 0, { family: "Geist", weight: 700, size: 104, color: cw.ink, lh: 1.05, alpha: a * fade(t, reveal, 0.3) });
767
+ const y2 = text(ctx, b, p.line, y + 30, { size: 52, style: "italic", color: cw.ink, alpha: a * fade(t, reveal + 0.8) });
768
+ if (p.traits.length) {
769
+ const traits = p.traits.map((name) => name.replace(/^The /, "the "));
770
+ text(ctx, b, `With a bit of ${traits.join(" and ")}.`, y2 + 30, { size: 40, color: cw.soft, alpha: a * fade(t, reveal + 1.6) });
771
+ }
772
+ },
773
+ });
774
+
775
+ const letterWords = D.letter?.text.split(/\s+/).length;
776
+ if (D.letter) add({
777
+ id: "letter", name: "Letter", dur: Math.max(10, letterWords * 0.28 + 3),
778
+ alt: `A note from your agents: ${D.letter.text}`,
779
+ head: (ctx, t, fx, cw, b) => text(ctx, b, "A note from your agents", 0, { family: "Geist", weight: 600, size: 60, color: cw.ink }),
780
+ words(ctx, t, fx, cw, b) {
781
+ const body = { size: 44, color: cw.ink, lh: 1.42 };
782
+ const inner = { x: b.x + 56, w: b.w - 112 };
783
+ const height = text(ctx, inner, D.letter.text, 0, { ...body, measure: true }) + 76;
784
+ // A quiet sheet, a shade lighter than the page.
785
+ ctx.save();
786
+ ctx.globalAlpha = REDUCED ? 1 : fade(t, 0, 0.5);
787
+ roundRect(ctx, b.x, -4, b.w, height, 28);
788
+ ctx.fillStyle = "rgba(255,255,255,0.04)";
789
+ ctx.fill();
790
+ ctx.strokeStyle = "rgba(255,255,255,0.1)";
791
+ ctx.lineWidth = 1.5;
792
+ ctx.stroke();
793
+ ctx.restore();
794
+ // Words appear at reading pace.
795
+ const shown = REDUCED ? letterWords : Math.floor(clamp((t - 0.6) / 0.22, 0, letterWords));
796
+ let n = 0;
797
+ const visible = D.letter.text
798
+ .split(/(\s+)/)
799
+ .filter((part) => (/\S/.test(part) ? ++n <= shown : n < shown))
800
+ .join("");
801
+ text(ctx, inner, visible, 20, body);
802
+ },
803
+ });
804
+
805
+ const tiles = [
806
+ [num(D.prompts), "prompts"],
807
+ D.agents ? [num(D.agents.hours), "hours of agent work"] : null,
808
+ D.topTypo ? [`${D.topTypo.spelling} ×${num(D.topTypo.count)}`, "my favourite typo"] : null,
809
+ D.night ? [D.night.latest, "latest prompt after midnight"] : D.streak ? [`${D.streak.days} days`, "longest streak"] : null,
810
+ ].filter(Boolean);
811
+ add({
812
+ id: "summary", name: "Summary", dur: 8,
813
+ alt: `Summary: ${p.name}. ${num(D.prompts)} prompts.`,
814
+ head(ctx, t, fx, cw, b) {
815
+ const y = text(ctx, b, `My ${YEAR || "year"} with AI agents`, 0, { ...say(), color: cw.soft });
816
+ text(ctx, b, p.name, y + 10, { family: "Geist", weight: 700, size: 92, color: cw.ink, lh: 1.05 });
817
+ },
818
+ visual(ctx, t, fx, cw, b) {
819
+ const tw = (b.w - 30) / 2;
820
+ const th = 300;
821
+ const bigFont = { family: "Geist", weight: 600 };
822
+ tiles.forEach(([value, label], i) => {
823
+ const at = 0.4 + i * 0.25;
824
+ fx.key(at);
825
+ const local = REDUCED ? 9 : t - at;
826
+ if (local < 0) return;
827
+ const fit = Math.min(64, (64 * (tw - 80)) / textWidth(ctx, value, 64, bigFont));
828
+ ctx.save();
829
+ ctx.font = font(34, { family: "Geist" });
830
+ const labelLines = wrap(ctx, label, tw - 80);
831
+ ctx.restore();
832
+ cap(ctx, b.x + (i % 2) * (tw + 30) + tw / 2, th / 2 + Math.floor(i / 2) * (th + 40), tw, th, "", {
833
+ ...cw,
834
+ left: true,
835
+ lines: [{ text: value, size: fit, ...bigFont }, ...labelLines.map((l) => ({ text: l, size: 34, family: "Geist", alpha: 0.55 }))],
836
+ scale: 0.85 + 0.15 * easeBack(local / 0.25),
837
+ press: pressAt(local),
838
+ });
839
+ });
840
+ },
841
+ });
842
+
843
+ return cards;
844
+ }
845
+
846
+ // ---------------------------------------------------------------- layout
847
+
848
+ // Finds the first and last rows a part draws on, by drawing its finished
849
+ // state small and looking for pixels that differ from the background.
850
+ const probe = document.createElement("canvas");
851
+ const PROBE_SCALE = 0.25;
852
+ const PROBE_PAD = 200; // room for anything drawn slightly above y = 0
853
+ function measure(card, part, b) {
854
+ probe.width = shape.W * PROBE_SCALE;
855
+ probe.height = shape.H * 2 * PROBE_SCALE;
856
+ const c = probe.getContext("2d", { willReadFrequently: true });
857
+ c.fillStyle = card.cw.plate;
858
+ c.fillRect(0, 0, probe.width, probe.height);
859
+ c.setTransform(PROBE_SCALE, 0, 0, PROBE_SCALE, 0, PROBE_PAD * PROBE_SCALE);
860
+ part(c, card.dur, SILENT, card.cw, b);
861
+ const { data, width, height } = c.getImageData(0, 0, probe.width, probe.height);
862
+ const bg = data.slice(0, 3);
863
+ let first = -1;
864
+ let last = -1;
865
+ for (let y = 0; y < height; y++) {
866
+ for (let x = 0; x < width; x++) {
867
+ const i = (y * width + x) * 4;
868
+ if (Math.abs(data[i] - bg[0]) + Math.abs(data[i + 1] - bg[1]) + Math.abs(data[i + 2] - bg[2]) > 24) {
869
+ if (first < 0) first = y;
870
+ last = y;
871
+ break;
872
+ }
873
+ }
874
+ }
875
+ if (first < 0) return null;
876
+ return { top: first / PROBE_SCALE - PROBE_PAD, bottom: last / PROBE_SCALE - PROBE_PAD };
877
+ }
878
+
879
+ // Places parts in a column, centred as one block in the shape's space.
880
+ function stack(card, parts, b) {
881
+ const placed = [];
882
+ const sized = parts.map((part) => ({ part, box: measure(card, part, b) })).filter((x) => x.box);
883
+ const total = sized.reduce((s, x) => s + (x.box.bottom - x.box.top), 0) + shape.gap * (sized.length - 1);
884
+ const [top, bottom] = shape.space;
885
+ let y = Math.max(top, (top + bottom) / 2 - total / 2);
886
+ for (const { part, box } of sized) {
887
+ placed.push({ part, b, dy: y - box.top });
888
+ y += box.bottom - box.top + shape.gap;
889
+ }
890
+ return placed;
891
+ }
892
+
893
+ function layout(card) {
894
+ card.layouts ??= {};
895
+ const key = shape === SHAPES.wide ? "wide" : "tall";
896
+ if (card.layouts[key]) return card.layouts[key];
897
+ const parts = [card.head, card.visual, card.words].filter(Boolean);
898
+ let placed;
899
+ if (key === "tall") placed = stack(card, parts, shape.column);
900
+ else if (!card.visual) placed = stack(card, parts, shape.single);
901
+ else placed = [...stack(card, [card.visual], shape.left), ...stack(card, [card.head, card.words].filter(Boolean), shape.right)];
902
+ return (card.layouts[key] = placed);
903
+ }
904
+
905
+ function withShape(s, fn) {
906
+ const before = shape;
907
+ shape = s;
908
+ try {
909
+ return fn();
910
+ } finally {
911
+ shape = before;
912
+ }
913
+ }
914
+
915
+ function paint(target, card, t, fx) {
916
+ const c = target.getContext("2d");
917
+ c.setTransform(1, 0, 0, 1, 0, 0);
918
+ background(c);
919
+ for (const { part, b, dy } of layout(card)) {
920
+ c.save();
921
+ c.translate(0, dy);
922
+ part(c, t, fx, card.cw, b);
923
+ c.restore();
924
+ }
925
+ watermark(c, card.cw);
926
+ }
927
+
928
+ // ---------------------------------------------------------------- player
929
+
930
+ const cards = buildCards(D);
931
+ const stage = document.getElementById("stage");
932
+ const frame = document.getElementById("frame");
933
+ const bars = document.getElementById("bars");
934
+ const live = document.getElementById("live");
935
+ bars.innerHTML = cards.map(() => "<span><i></i></span>").join("");
936
+
937
+ // Wide windows get the wide shape; phones and narrow windows the tall one.
938
+ function fitShape() {
939
+ const next = innerWidth / innerHeight > 1.15 ? SHAPES.wide : SHAPES.tall;
940
+ if (next === shape && stage.width === next.W) return;
941
+ shape = next;
942
+ stage.width = shape.W;
943
+ stage.height = shape.H;
944
+ frame.dataset.shape = shape === SHAPES.wide ? "wide" : "tall";
945
+ }
946
+
947
+ const state = { index: 0, started: 0, playing: false, holdPaused: false, pausedAt: 0, prevT: 0, mode: "player" };
948
+
949
+ function show(index) {
950
+ state.index = clamp(index, 0, cards.length - 1);
951
+ state.started = performance.now();
952
+ state.prevT = -1;
953
+ live.textContent = cards[state.index].alt;
954
+ }
955
+
956
+ function elapsed(now) {
957
+ return ((state.holdPaused ? state.pausedAt : now) - state.started) / 1000;
958
+ }
959
+
960
+ function tick(now) {
961
+ if (state.mode === "player") {
962
+ const card = cards[state.index];
963
+ // Before play, the first card shows finished behind the start button.
964
+ const t = state.playing ? elapsed(now) : card.dur;
965
+ paint(stage, card, t, effects(state.prevT, t, state.playing && !state.holdPaused));
966
+ state.prevT = t;
967
+ [...bars.children].forEach((bar, i) => {
968
+ bar.firstChild.style.width = `${i < state.index ? 100 : i > state.index ? 0 : clamp(t / card.dur) * 100}%`;
969
+ });
970
+ if (state.playing && !state.holdPaused && t >= card.dur) {
971
+ if (state.index === cards.length - 1) openShare();
972
+ else show(state.index + 1);
973
+ }
974
+ }
975
+ requestAnimationFrame(tick);
976
+ }
977
+
978
+ addEventListener("resize", () => {
979
+ if (state.mode === "player") fitShape();
980
+ });
981
+
982
+ document.getElementById("play").addEventListener("click", () => {
983
+ Sound.init();
984
+ document.getElementById("start").remove();
985
+ state.playing = true;
986
+ show(0);
987
+ });
988
+
989
+ // Tap right side: next. Tap left: back. Press and hold: pause.
990
+ let holdTimer = 0;
991
+ stage.addEventListener("pointerdown", () => {
992
+ if (!state.playing) return;
993
+ holdTimer = setTimeout(() => {
994
+ state.holdPaused = true;
995
+ state.pausedAt = performance.now();
996
+ }, 220);
997
+ });
998
+ stage.addEventListener("pointerup", (e) => {
999
+ if (!state.playing) return;
1000
+ clearTimeout(holdTimer);
1001
+ if (state.holdPaused) {
1002
+ state.started += performance.now() - state.pausedAt;
1003
+ state.holdPaused = false;
1004
+ return;
1005
+ }
1006
+ const rect = stage.getBoundingClientRect();
1007
+ show(state.index + (e.clientX - rect.left < rect.width * 0.3 ? -1 : 1));
1008
+ });
1009
+
1010
+ addEventListener("keydown", (e) => {
1011
+ if (state.mode !== "player") return;
1012
+ if (e.key.toLowerCase() === "s" && !e.metaKey && !e.ctrlKey && !e.altKey) {
1013
+ saveCurrent();
1014
+ return;
1015
+ }
1016
+ if (!state.playing) return;
1017
+ if (e.key === "ArrowRight" || e.key === " ") {
1018
+ e.preventDefault();
1019
+ if (state.index === cards.length - 1) openShare();
1020
+ else show(state.index + 1);
1021
+ } else if (e.key === "ArrowLeft") show(state.index - 1);
1022
+ else if (e.key === "Escape") openShare();
1023
+ });
1024
+
1025
+ const soundBtn = document.getElementById("sound");
1026
+ try {
1027
+ Sound.on = localStorage.getItem("agent-wrapped-sound") !== "off";
1028
+ } catch {}
1029
+ const renderSoundBtn = () => {
1030
+ soundBtn.setAttribute("aria-pressed", String(Sound.on));
1031
+ soundBtn.textContent = Sound.on ? "Sound on" : "Sound off";
1032
+ };
1033
+ renderSoundBtn();
1034
+ soundBtn.addEventListener("click", () => {
1035
+ Sound.on = !Sound.on;
1036
+ try {
1037
+ localStorage.setItem("agent-wrapped-sound", Sound.on ? "on" : "off");
1038
+ } catch {}
1039
+ renderSoundBtn();
1040
+ });
1041
+ document.getElementById("skip").addEventListener("click", openShare);
1042
+ document.getElementById("save-now").addEventListener("click", saveCurrent);
1043
+ if (SHARED) {
1044
+ document.getElementById("play").textContent = "Play the story";
1045
+ document.getElementById("start-note").textContent = "A year with AI coding agents, wrapped. Sound on for the full effect.";
1046
+ document.getElementById("skip").textContent = "Skip to the end";
1047
+ }
1048
+
1049
+ // The buttons fade away while you watch, so a screenshot shows only the card.
1050
+ const player = document.getElementById("player");
1051
+ let idleTimer = 0;
1052
+ function wake() {
1053
+ player.classList.remove("idle");
1054
+ clearTimeout(idleTimer);
1055
+ idleTimer = setTimeout(() => state.playing && state.mode === "player" && player.classList.add("idle"), 2200);
1056
+ }
1057
+ for (const ev of ["pointermove", "pointerdown", "keydown"]) addEventListener(ev, wake);
1058
+
1059
+ // Saves the card on screen as it looks when finished.
1060
+ async function saveCurrent() {
1061
+ const i = state.index;
1062
+ download(await pngOf(finalFrame(cards[i], shape)), fileName(i, shape));
1063
+ notify("Saved this card to your Downloads folder.");
1064
+ }
1065
+
1066
+
1067
+ // ---------------------------------------------------------------- sharing
1068
+
1069
+ const share = document.getElementById("share");
1070
+ const preview = document.getElementById("share-preview");
1071
+ const postX = document.getElementById("post-x");
1072
+ const postLinkedIn = document.getElementById("post-linkedin");
1073
+
1074
+ // Cards you can leave out, and the part of the story each one needs.
1075
+ const LEAVABLE = {
1076
+ "top-typo": "topTypo", spellings: "spellings", slip: "slip", "top-prompts": "topPrompts", catchphrase: "catchphrase",
1077
+ talk: "talk", night: "night", streak: "streak", agents: "agents", work: "work", money: "money", letter: "letter",
1078
+ };
1079
+ const left = new Set(); // ids of the cards left out
1080
+ let link = "";
1081
+ let linkFor = 0; // ignores a slower, older link if the choice changed meanwhile
1082
+
1083
+ // The story that goes in the link: a card left out is not in it at all.
1084
+ function sharedData() {
1085
+ const d = { ...D };
1086
+ for (const id of left) d[LEAVABLE[id]] = id === "top-prompts" ? [] : null;
1087
+ return d;
1088
+ }
1089
+
1090
+ const shareText = (d) => `My ${YEAR || "year"} with AI coding agents, wrapped. I'm ${d.personality.name}.`;
1091
+
1092
+ function finalFrame(card, s) {
1093
+ return withShape(s, () => {
1094
+ const c = document.createElement("canvas");
1095
+ c.width = s.W;
1096
+ c.height = s.H;
1097
+ paint(c, card, card.dur, SILENT);
1098
+ return c;
1099
+ });
1100
+ }
1101
+
1102
+ const pngOf = (canvas) => new Promise((r) => canvas.toBlob(r, "image/png"));
1103
+ const shapeName = (s) => (s === SHAPES.wide ? "wide" : "tall");
1104
+ const fileName = (i, s) => `agent-wrapped-${shapeName(s)}-${String(i + 1).padStart(2, "0")}-${cards[i].id}.png`;
1105
+
1106
+ function download(blob, name) {
1107
+ const a = document.createElement("a");
1108
+ a.href = URL.createObjectURL(blob);
1109
+ a.download = name;
1110
+ document.body.append(a);
1111
+ a.click();
1112
+ a.remove();
1113
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
1114
+ }
1115
+
1116
+ // The summary card stands for the whole story.
1117
+ function summaryCard() {
1118
+ return buildCards(sharedData()).find((c) => c.id === "summary");
1119
+ }
1120
+
1121
+ async function renderShare() {
1122
+ const mine = ++linkFor;
1123
+ const data = sharedData();
1124
+ preview.src = finalFrame(summaryCard(), shape).toDataURL("image/png");
1125
+ preview.dataset.shape = shapeName(shape);
1126
+ const next = PLAYER_URL ? `${PLAYER_URL}#v1.${await pack(data)}` : "";
1127
+ if (mine !== linkFor) return;
1128
+ link = next;
1129
+ const url = encodeURIComponent(link);
1130
+ postX.href = `https://x.com/intent/post?text=${encodeURIComponent(shareText(data))}&url=${url}`;
1131
+ postLinkedIn.href = `https://www.linkedin.com/sharing/share-offsite/?url=${url}`;
1132
+ for (const el of document.querySelectorAll("[data-needs-link]")) el.hidden = !link;
1133
+ document.getElementById("share-link").hidden = !link || typeof navigator.share !== "function";
1134
+ document.getElementById("offline").hidden = !!link;
1135
+ }
1136
+
1137
+ function renderChoices() {
1138
+ const list = document.getElementById("choices");
1139
+ list.replaceChildren(
1140
+ ...cards
1141
+ .filter((card) => card.id in LEAVABLE)
1142
+ .map((card) => {
1143
+ const btn = document.createElement("button");
1144
+ btn.className = "chip";
1145
+ btn.textContent = card.name;
1146
+ const render = () => btn.setAttribute("aria-pressed", String(!left.has(card.id)));
1147
+ btn.addEventListener("click", () => {
1148
+ if (left.has(card.id)) left.delete(card.id);
1149
+ else left.add(card.id);
1150
+ render();
1151
+ renderShare();
1152
+ });
1153
+ render();
1154
+ return btn;
1155
+ }),
1156
+ );
1157
+ }
1158
+
1159
+ // Your own story ends on sharing; a shared one ends on how to make your own.
1160
+ function openShare() {
1161
+ state.mode = "share";
1162
+ clearTimeout(idleTimer);
1163
+ player.hidden = true;
1164
+ if (SHARED) {
1165
+ document.getElementById("ending").hidden = false;
1166
+ document.getElementById("ending-title").focus();
1167
+ return;
1168
+ }
1169
+ share.hidden = false;
1170
+ renderChoices();
1171
+ renderShare();
1172
+ document.getElementById("share-title").focus();
1173
+ }
1174
+
1175
+ document.getElementById("copy-link").addEventListener("click", async () => {
1176
+ try {
1177
+ await navigator.clipboard.writeText(link);
1178
+ notify("Link copied. Paste it anywhere.");
1179
+ } catch {
1180
+ notify("Couldn't copy the link. Try Share instead.");
1181
+ }
1182
+ });
1183
+
1184
+ document.getElementById("share-link").addEventListener("click", async () => {
1185
+ try {
1186
+ await navigator.share({ title: "Agent Wrapped", text: shareText(sharedData()), url: link });
1187
+ } catch (err) {
1188
+ if (err?.name !== "AbortError") notify("Couldn't open sharing. Copy the link instead.");
1189
+ }
1190
+ });
1191
+
1192
+ document.getElementById("save-image").addEventListener("click", async () => {
1193
+ download(await pngOf(finalFrame(summaryCard(), shape)), `agent-wrapped-${shapeName(shape)}.png`);
1194
+ notify("Saved the card to your Downloads folder.");
1195
+ });
1196
+
1197
+
1198
+ // Plays the story in real time onto a hidden canvas and records it, for
1199
+ // places that take a video but not a link.
1200
+ document.getElementById("save-video").addEventListener("click", async (e) => {
1201
+ if (typeof MediaRecorder === "undefined") {
1202
+ notify("This browser can't record video. Try Chrome, Arc or Safari.");
1203
+ return;
1204
+ }
1205
+ const list = buildCards(sharedData());
1206
+ const button = e.currentTarget;
1207
+ button.disabled = true;
1208
+ Sound.init();
1209
+ const s = shape;
1210
+ const canvas = document.createElement("canvas");
1211
+ canvas.width = s.W;
1212
+ canvas.height = s.H;
1213
+ const stream = canvas.captureStream(30);
1214
+ if (Sound.ctx) {
1215
+ const dest = Sound.ctx.createMediaStreamDestination();
1216
+ Sound.master.connect(dest);
1217
+ dest.stream.getAudioTracks().forEach((tr) => stream.addTrack(tr));
1218
+ }
1219
+ const type = ["video/mp4;codecs=avc1", "video/mp4", "video/webm;codecs=vp9", "video/webm"].find((m) =>
1220
+ MediaRecorder.isTypeSupported(m),
1221
+ );
1222
+ const recorder = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: 8_000_000 });
1223
+ const chunks = [];
1224
+ recorder.ondataavailable = (ev) => ev.data.size && chunks.push(ev.data);
1225
+ const finished = new Promise((r) => (recorder.onstop = r));
1226
+ recorder.start(500);
1227
+
1228
+ const total = list.reduce((sum, c) => sum + c.dur, 0);
1229
+ let done = 0;
1230
+ for (const card of list) {
1231
+ await new Promise((resolve) => {
1232
+ const start = performance.now();
1233
+ let prev = -1;
1234
+ const step = (now) => {
1235
+ const t = (now - start) / 1000;
1236
+ withShape(s, () => paint(canvas, card, Math.min(t, card.dur), effects(prev, t, true)));
1237
+ prev = t;
1238
+ notify(`Recording your video, ${Math.floor(((done + Math.min(t, card.dur)) / total) * 100)}%. Keep this tab open.`, { stay: true });
1239
+ if (t >= card.dur) resolve();
1240
+ else requestAnimationFrame(step);
1241
+ };
1242
+ requestAnimationFrame(step);
1243
+ });
1244
+ done += card.dur;
1245
+ }
1246
+ recorder.stop();
1247
+ await finished;
1248
+ const ext = type.startsWith("video/mp4") ? "mp4" : "webm";
1249
+ download(new Blob(chunks, { type }), `agent-wrapped-${shapeName(s)}.${ext}`);
1250
+ notify(`Saved your video to your Downloads folder as agent-wrapped-${shapeName(s)}.${ext}.`);
1251
+ button.disabled = false;
1252
+ });
1253
+
1254
+ for (const btn of document.querySelectorAll("[data-replay]")) {
1255
+ btn.addEventListener("click", () => {
1256
+ share.hidden = true;
1257
+ document.getElementById("ending").hidden = true;
1258
+ player.hidden = false;
1259
+ state.mode = "player";
1260
+ fitShape();
1261
+ state.playing = true;
1262
+ show(0);
1263
+ });
1264
+ }
1265
+
1266
+ // Draw the first card once fonts are ready, so nothing flashes in a fallback font.
1267
+ Promise.all([
1268
+ document.fonts.load('600 80px "Geist"'),
1269
+ document.fonts.load('400 40px "Newsreader"'),
1270
+ document.fonts.load('italic 400 40px "Newsreader"'),
1271
+ ]).finally(() => {
1272
+ fitShape();
1273
+ requestAnimationFrame(tick);
1274
+ });