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

main
js 439 lines 16.2 KB
Raw
1 // Runtime helpers for launch-video stories. capture.mjs seeks every animation on the page and in
2 // its beat iframes, including the Web Animations created here, so nothing may depend on real time.
3 //
4 // Targets: a CSS selector in the story ("#cur"), or "<beat> >> <selector>" for an element inside
5 // the frozen app page loaded as <iframe data-beat="<beat>">.
6 window.Kit = (() => {
7 const frames = () => [...document.querySelectorAll("iframe[data-beat]")];
8 const ready = Promise.all(
9 frames().map(
10 (f) =>
11 new Promise((resolve) => {
12 const done = async () => {
13 await f.contentDocument.fonts.ready;
14 resolve();
15 };
16 if (
17 f.contentDocument?.readyState === "complete" &&
18 f.contentDocument.body?.childElementCount
19 )
20 done();
21 else f.addEventListener("load", done, { once: true });
22 }),
23 ),
24 );
25
26 const beat = (name) => {
27 const f = document.querySelector(`iframe[data-beat="${name}"]`);
28 if (!f) throw new Error(`Kit: no beat named ${name}`);
29 return f;
30 };
31 // CSS plus a trailing `:text(words)`, which keeps the matches whose text contains `words`.
32 const query = (doc, selector) => {
33 const match = /^(.*?):text\((.+)\)$/.exec(selector.trim());
34 if (!match) return [...doc.querySelectorAll(selector)];
35 return [...doc.querySelectorAll(match[1] || "*")].filter(
36 (node) =>
37 node.textContent.includes(match[2]) &&
38 ![...node.children].some(
39 (c) => c.textContent.includes(match[2]) && c.matches(match[1] || "*"),
40 ),
41 );
42 };
43 const resolve = (target) => {
44 // Nodes from a beat belong to its iframe's realm, so `instanceof Element` misses them.
45 if (typeof target !== "string") {
46 const view = target.ownerDocument.defaultView;
47 return { el: target, frame: view === window ? null : view.frameElement };
48 }
49 const split = target.indexOf(" >> ");
50 if (split === -1) {
51 const [el] = query(document, target);
52 if (!el) throw new Error(`Kit: no element matches ${target}`);
53 return { el, frame: null };
54 }
55 const frame = beat(target.slice(0, split));
56 const sel = target.slice(split + 4);
57 const [el] = query(frame.contentDocument, sel);
58 if (!el) throw new Error(`Kit: no element matches ${sel} in beat ${frame.dataset.beat}`);
59 return { el, frame };
60 };
61 // "* >> <selector>" matches in every beat.
62 const all = (target) => {
63 const split = target.indexOf(" >> ");
64 if (split === -1) return query(document, target);
65 const name = target.slice(0, split);
66 const docs =
67 name === "*" ? frames().map((f) => f.contentDocument) : [beat(name).contentDocument];
68 return docs.flatMap((doc) => query(doc, target.slice(split + 4)));
69 };
70 // Extra CSS in beats ("*" for all), e.g. to uncap a scrolling modal so the whole page shows.
71 const css = (name, text) => {
72 for (const f of name === "*" ? frames() : [beat(name)]) {
73 const style = f.contentDocument.createElement("style");
74 style.textContent = text;
75 f.contentDocument.head.append(style);
76 }
77 };
78 // A static edit to the frozen page, e.g. a dev-only label. Say so when you hand the video back.
79 const text = (targets, value) => {
80 for (const node of all(targets)) node.textContent = value;
81 };
82 const el = (target) => resolve(target).el;
83
84 // Story-page coordinates of a target's box, through any iframe and its scale.
85 const rect = (target) => {
86 const { el: node, frame } = resolve(target);
87 const r = node.getBoundingClientRect();
88 if (!frame) return r;
89 const f = frame.getBoundingClientRect();
90 const s = f.width / frame.offsetWidth;
91 return new DOMRect(f.left + r.left * s, f.top + r.top * s, r.width * s, r.height * s);
92 };
93 const centerOf = (target, dx = 0, dy = 0) => {
94 if (Array.isArray(target)) return target;
95 const r = rect(target);
96 return [r.left + r.width / 2 + dx, r.top + r.height / 2 + dy];
97 };
98
99 // Measure with the camera at rest: capture.mjs seeks to window.layoutTime, then calls this.
100 const measure = (fn) => {
101 const cams = [...document.querySelectorAll(".cam")];
102 const scripted = cams.flatMap((cam) =>
103 cam.getAnimations().filter((a) => !(a instanceof CSSAnimation)),
104 );
105 for (const cam of cams) cam.style.animation = "none";
106 for (const a of scripted) a.cancel();
107 // Everything is measured with the camera at rest; camera moves start only afterwards.
108 measuring = true;
109 try {
110 for (const place of overlays.splice(0)) place();
111 return fn();
112 } finally {
113 measuring = false;
114 for (const start of afterMeasure.splice(0)) start();
115 for (const cam of cams) cam.style.animation = "";
116 }
117 };
118 let measuring = false;
119 const afterMeasure = [];
120 // Overlays drawn on the story page over a target (so the app's own overflow cannot clip
121 // them). They are measured and placed when placeCursor runs Kit.measure.
122 const overlays = [];
123 const overlay = (target, style, keyframes, timing) =>
124 overlays.push(() => {
125 const r = rect(target);
126 const node = resolve(target).el;
127 const radius = parseFloat(getComputedStyle(node).borderRadius) || 10;
128 const scale = r.width / node.getBoundingClientRect().width;
129 const box = document.createElement("div");
130 box.className = "kit-overlay";
131 Object.assign(box.style, {
132 position: "absolute",
133 left: `${r.left - 6}px`,
134 top: `${r.top - 6}px`,
135 width: `${r.width + 12}px`,
136 height: `${r.height + 12}px`,
137 borderRadius: `${radius * scale + 6}px`,
138 pointerEvents: "none",
139 zIndex: 15,
140 opacity: 0,
141 ...style,
142 });
143 (document.querySelector(".cam") ?? document.body).append(box);
144 anim(box, keyframes, timing);
145 });
146
147 // One Web Animation at an absolute time (animation seconds). fill "both" holds the first
148 // keyframe before `at` and the last after it ends.
149 const anim = (
150 target,
151 keyframes,
152 { at = 0, dur = 0.4, ease = "cubic-bezier(.2,.8,.2,1)", fill = "both" } = {},
153 ) => {
154 const node = typeof target === "string" ? el(target) : target;
155 return node.animate(keyframes, { delay: at * 1000, duration: dur * 1000, easing: ease, fill });
156 };
157 const SPRING = "linear(0, .25 7%, .7 16%, 1.03 28%, 1.08 34%, 1.04 44%, .99 58%, 1)";
158 // One visibility window per element: hidden, then shown from `from` (fading in over `fade`),
159 // then hidden again at `to`. Two separate show/hide animations on one element fight.
160 const visible = (target, from, to = Infinity, fade = 0) => {
161 const shown = from + fade;
162 const open = !Number.isFinite(to);
163 const end = open ? shown + 1 : to;
164 const keys = [
165 { offset: 0, opacity: 0 },
166 { offset: from / end, opacity: 0 },
167 { offset: shown / end, opacity: 1 },
168 // Every keyframe list ends at offset 1, or the fill falls back to the element's CSS.
169 ...(open
170 ? [{ offset: 1, opacity: 1 }]
171 : [
172 { offset: Math.max(shown, to - 0.001) / end, opacity: 1 },
173 { offset: 1, opacity: 0 },
174 ]),
175 ];
176 return anim(target, keys, { at: 0, dur: end, ease: "linear" });
177 };
178 // Captions in order: [[selector, from, to], ...]. Each fades in and out inside its window,
179 // and overlapping windows throw, since two captions on screen read as garbled text.
180 const captions = (list) =>
181 list.forEach(([target, from, to], i) => {
182 const next = list[i + 1];
183 if (next && next[1] < to) throw new Error(`Kit: caption ${target} overlaps ${next[0]}`);
184 anim(
185 target,
186 [
187 { opacity: 0, transform: "translateY(14px)" },
188 { opacity: 1, transform: "none", offset: 0.06 },
189 { opacity: 1, transform: "none", offset: 0.94 },
190 { opacity: 0, transform: "translateY(-8px)" },
191 ],
192 { at: from, dur: to - from, ease: "linear" },
193 );
194 });
195 // The beats in order: [[name, at, fade?], ...]. Each shows from its `at` until the next beat
196 // has finished fading in over it.
197 const beats = (sequence) =>
198 sequence.forEach(([name, at, fade = 0], i) => {
199 const next = sequence[i + 1];
200 visible(beat(name), at, next ? next[1] + (next[2] ?? 0) : Infinity, fade);
201 });
202
203 const motion = {
204 // Appear: at `at` the element is hidden until then.
205 show: (t, at) => anim(t, [{ opacity: 0 }, { opacity: 1 }], { at, dur: 0.01 }),
206 hide: (t, at) => anim(t, [{ opacity: 1 }, { opacity: 0 }], { at, dur: 0.01 }),
207 fadeIn: (t, at, dur = 0.3) =>
208 anim(t, [{ opacity: 0 }, { opacity: 1 }], { at, dur, ease: "ease-out" }),
209 fadeOut: (t, at, dur = 0.3) =>
210 anim(t, [{ opacity: 1 }, { opacity: 0 }], { at, dur, ease: "ease-in" }),
211 // Spring pop: scales up from `from` with an overshoot.
212 pop: (t, at, { from = 0.6, dur = 0.55, origin = "center" } = {}) => {
213 el(t).style.transformOrigin = origin;
214 return anim(
215 t,
216 [
217 { opacity: 0, transform: `scale(${from})` },
218 { opacity: 1, offset: 0.25 },
219 { opacity: 1, transform: "none" },
220 ],
221 { at, dur, ease: SPRING },
222 );
223 },
224 // Rise into place from below (or any offset), springy.
225 rise: (t, at, { y = 24, x = 0, dur = 0.6 } = {}) =>
226 anim(
227 t,
228 [
229 { opacity: 0, transform: `translate(${x}px, ${y}px)` },
230 { opacity: 1, offset: 0.3 },
231 { opacity: 1, transform: "none" },
232 ],
233 { at, dur, ease: SPRING },
234 ),
235 // Slide in from a side, e.g. a panel: { x: 400 } comes from the right.
236 slide: (t, at, { x = 0, y = 0, dur = 0.5 } = {}) =>
237 anim(t, [{ transform: `translate(${x}px, ${y}px)` }, { transform: "none" }], {
238 at,
239 dur,
240 ease: "cubic-bezier(.16,1,.3,1)",
241 }),
242 // The same entrance on each match, `step` seconds apart.
243 stagger: (targets, at, step = 0.07, fn = "rise", opts) =>
244 all(targets).map((node, i) => motion[fn](node, at + i * step, opts)),
245 // Typewriter: reveals the element left to right in `chars` steps.
246 type: (t, at, dur, chars = 30) =>
247 anim(t, [{ clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0 0 0)" }], {
248 at,
249 dur,
250 ease: `steps(${chars}, end)`,
251 }),
252 // Button squash on click.
253 press: (t, at) =>
254 anim(
255 t,
256 [{ transform: "none" }, { transform: "scale(.9)", offset: 0.35 }, { transform: "none" }],
257 { at, dur: 0.3, ease: "ease-out", fill: "none" },
258 ),
259 // Primary-blue glow ring that blooms and settles around the element (an overlay).
260 glow: (t, at, dur = 1.4) =>
261 overlay(
262 t,
263 {
264 border: "2px solid rgba(110,155,251,.95)",
265 boxShadow: "0 0 32px 6px rgba(52,107,241,.55), inset 0 0 18px rgba(52,107,241,.25)",
266 },
267 [
268 { opacity: 0, transform: "scale(1.06)" },
269 { opacity: 1, transform: "none", offset: 0.18 },
270 { opacity: 1, transform: "none", offset: 0.75 },
271 { opacity: 0, transform: "none" },
272 ],
273 { at, dur, ease: "ease-out" },
274 ),
275 // Draws solid SVG strokes in (dashed ones keep their dashes and just fade in).
276 draw: (targets, at, dur = 0.6, step = 0.08) =>
277 all(targets).map((path, i) => {
278 const start = at + i * step;
279 const view = path.ownerDocument.defaultView;
280 if (view.getComputedStyle(path).strokeDasharray !== "none" || !path.getTotalLength) {
281 return anim(path, [{ opacity: 0 }, { opacity: 1 }], { at: start, dur });
282 }
283 const length = path.getTotalLength();
284 path.style.strokeDasharray = `${length}`;
285 return anim(path, [{ strokeDashoffset: length }, { strokeDashoffset: 0 }], {
286 at: start,
287 dur,
288 ease: "cubic-bezier(.4,0,.2,1)",
289 });
290 }),
291 // Wipes an element in from one side (dashed lines, a drag line following the pointer).
292 reveal: (t, at, dur = 0.5, from = "left") => {
293 const start = {
294 left: "inset(0 100% 0 0)",
295 right: "inset(0 0 0 100%)",
296 top: "inset(0 0 100% 0)",
297 bottom: "inset(100% 0 0 0)",
298 }[from];
299 return anim(t, [{ clipPath: start }, { clipPath: "inset(0 0 0 0)" }], {
300 at,
301 dur,
302 ease: "linear",
303 });
304 },
305 // A punch: brief scale-up pulse that draws the eye.
306 punch: (t, at, scale = 1.06) =>
307 anim(
308 t,
309 [
310 { transform: "none" },
311 { transform: `scale(${scale})`, offset: 0.3 },
312 { transform: "none" },
313 ],
314 { at, dur: 0.45, ease: "ease-out", fill: "none" },
315 ),
316 };
317
318 // Click ripple drawn on the story page at a target's centre (call from setup or placeCursor).
319 const ripple = (target, at, { dx = 0, dy = 0 } = {}) => {
320 const [x, y] = centerOf(target, dx, dy);
321 const ring = document.createElement("div");
322 ring.className = "kit-ripple";
323 Object.assign(ring.style, {
324 position: "absolute",
325 left: `${x - 30}px`,
326 top: `${y - 30}px`,
327 width: "60px",
328 height: "60px",
329 borderRadius: "50%",
330 border: "3px solid rgba(110,155,251,.9)",
331 pointerEvents: "none",
332 zIndex: 25,
333 });
334 (document.querySelector(".cam") ?? document.body).append(ring);
335 return anim(
336 ring,
337 [
338 { opacity: 0, transform: "scale(.2)" },
339 { opacity: 1, offset: 0.15 },
340 { opacity: 0, transform: "scale(1.6)" },
341 ],
342 { at, dur: 0.55, ease: "ease-out" },
343 );
344 };
345
346 // Steps, in animation seconds:
347 // { t, at: [x, y] | target, dx, dy, click, hidden }
348 // at omitted = stay put (a hold). click = press at t. hidden = fade the cursor out by t.
349 const cursor = (selector, steps, { ease = "cubic-bezier(.45,0,.2,1)", ripples = true } = {}) => {
350 const node = document.querySelector(selector);
351 for (const a of node.getAnimations()) a.cancel();
352 const end = steps.at(-1).t;
353 const keys = [];
354 let pos = [0, 0];
355 let opacity = 0;
356 const push = (t, scale = 1) =>
357 keys.push({
358 offset: t / end,
359 transform: `translate(${pos[0] - 4}px, ${pos[1] - 3}px) scale(${scale})`,
360 opacity,
361 easing: ease,
362 });
363 steps.forEach((s, i) => {
364 if (s.at !== undefined) pos = centerOf(s.at, s.dx, s.dy);
365 if (i === 0) {
366 push(0);
367 opacity = s.hidden ? 0 : 1;
368 push(s.t);
369 return;
370 }
371 opacity = s.hidden ? 0 : 1;
372 push(s.t);
373 if (s.click) {
374 push(s.t + 0.07, 0.8);
375 push(s.t + 0.22, 1);
376 if (ripples) ripple(pos, s.t + 0.05);
377 }
378 });
379 keys.sort((a, b) => a.offset - b.offset);
380 for (const k of keys) k.offset = Math.min(1, Math.max(0, k.offset));
381 node.animate(keys, { duration: end * 1000, fill: "both" });
382 };
383
384 // Camera keyframes on .cam, in animation seconds: { t, on: target | [x, y] | "full", s, y, ease }.
385 // `on` is centred horizontally and placed at screen height `y` (default 420, clear of the
386 // captions); "full" is the whole canvas. Repeat a step at a later t to hold. Call it inside
387 // Kit.measure (placeCursor) so targets are measured with the camera at rest.
388 const camera = (steps, { selector = ".cam" } = {}) => {
389 const cam = document.querySelector(selector);
390 for (const a of cam.getAnimations()) a.cancel();
391 const end = steps.at(-1).t;
392 const keys = steps.map((step) => {
393 let transform = "none";
394 if (step.on !== "full") {
395 const s = step.s ?? 1.5;
396 const [x, y] = centerOf(step.on, step.dx, step.dy);
397 transform = `translate(${800 - s * x}px, ${(step.y ?? 420) - s * y}px) scale(${s})`;
398 }
399 return { offset: step.t / end, transform, easing: step.ease ?? "cubic-bezier(.65,0,.35,1)" };
400 });
401 const start = () => cam.animate(keys, { duration: end * 1000, fill: "both" });
402 if (measuring) afterMeasure.push(start);
403 else start();
404 };
405
406 // Segments: [realSeconds, animFrom, animTo]; animFrom == animTo holds the frame.
407 const timeline = (segments) => {
408 window.totalDuration = segments.reduce((n, [d]) => n + d, 0);
409 const last = segments.at(-1)[2];
410 window.warp = (t) => {
411 for (const [d, a, b] of segments) {
412 if (t <= d) return a + (b - a) * (t / d);
413 t -= d;
414 }
415 return last;
416 };
417 };
418
419 return {
420 ready,
421 beat,
422 beats,
423 visible,
424 el,
425 all,
426 css,
427 captions,
428 text,
429 rect,
430 centerOf,
431 measure,
432 anim,
433 ripple,
434 cursor,
435 camera,
436 timeline,
437 ...motion,
438 };
439 })();