Setting the file. One moment. Animation Map · Hyperframes Animation · heygen-com/hyperframes · Skills DocsBlueprints Index
This file
- Number
- 18.4
- Position
- 4 of 121
- Type
- JavaScript
- Size
- 23 KB
- Lines
- 659
scripts/animation-map.mjs
JavaScript·659 lines·23 KB
15// @latest with a warning otherwise).
16
17import { mkdir, writeFile } from "node:fs/promises";
18import { resolve, join } from "node:path";
19import { sampleTweenBboxes } from "./animation-map-sampling.mjs";
20import {
21 bundleCompositionForCapture,
22 hyperframesPackageSpec,
23 importPackagesOrBootstrap,
24 initializeSessionWithRetry,
25} from "./package-loader.mjs";
26
27const packages = await importPackagesOrBootstrap(
28 ["@hyperframes/producer", "@hyperframes/core", "@hyperframes/core/compiler"],
29 {
30 npmPackages: [
31 hyperframesPackageSpec("@hyperframes/producer"),
32 hyperframesPackageSpec("@hyperframes/core"),
33 ],
34 },
35);
36const { createFileServer, createCaptureSession, closeCaptureSession, getCompositionDuration } =
37 packages["@hyperframes/producer"];
38const { parseFps } = packages["@hyperframes/core"];
39
40// ─── CLI ─────────────────────────────────────────────────────────────────────
41
42const args = parseArgs(process.argv.slice(2));
43if (!args.composition) die("missing <composition-dir>");
44
45const FRAMES = Number(args.frames ?? 6);
46const OUT_DIR = resolve(args.out ?? ".hyperframes/anim-map");
47const MIN_DUR = Number(args["min-duration"] ?? 0.15);
48const WIDTH = Number(args.width ?? 1920);
49const HEIGHT = Number(args.height ?? 1080);
50const parsedFps = parseFps(args.fps ?? 30);
51if (!parsedFps.ok) die(`Invalid --fps "${args.fps ?? ""}": ${parsedFps.reason}`);
52const FPS = parsedFps.value;
53const COMP_DIR = resolve(args.composition);
54
55await mkdir(OUT_DIR, { recursive: true });
56
57// ─── Main ────────────────────────────────────────────────────────────────────
58
59// Raw modular hosts do not mount child compositions in the capture helper.
60// Bundle first so duration/timeline discovery sees the same DOM as render/check.
61const bundle = await bundleCompositionForCapture(packages["@hyperframes/core/compiler"], COMP_DIR);
62let server;
63let session;
64try {
65 server = await createFileServer({
66 projectDir: COMP_DIR,
67 compiledDir: bundle.compiledDir,
68 port: 0,
69 });
70 // Canonical transient-init retry/cleanup (mirrors the render pipeline's
71 // probeStage): a valid modular project's sub-composition timelines register
72 // asynchronously, so the first attempt can time out as transient
73 // "zero duration / Runtime ready: false" — retry once with a fresh browser
74 // instead of false-failing the project.
75 session = await initializeSessionWithRetry(
76 packages["@hyperframes/producer"],
77 () =>
78 createCaptureSession(
79 server.url,
80 OUT_DIR,
81 { width: WIDTH, height: HEIGHT, fps: FPS, format: "png" },
82 null,
83 ),
84 { log: (message) => console.error(`animation-map: ${message}`) },
85 );
86
87 const duration = await getCompositionDuration(session);
88 const tweens = await enumerateTweens(session);
89 const kept = tweens.filter((tw) => tw.end - tw.start >= MIN_DUR);
90
91 const report = {
92 composition: COMP_DIR,
93 duration,
94 totalTweens: tweens.length,
95 mappedTweens: kept.length,
96 skippedMicroTweens: tweens.length - kept.length,
97 tweens: [],
98 };
99
100 for (let i = 0; i < kept.length; i++) {
101 const tw = kept[i];
102 const times = Array.from(
103 { length: FRAMES },
104 (_, k) => +(tw.start + ((k + 0.5) / FRAMES) * (tw.end - tw.start)).toFixed(3),
105 );
106
107 // No selector means no element to measure (an onUpdate driver). Sampling anyway
108 // would hand querySelector an unmatchable string.
109 const bboxes = tw.selectorHint
110 ? await sampleTweenBboxes(session.page, tw.selectorHint, times)
111 : [];
112
113 const animProps = tw.props.filter(
114 (p) => !["parent", "overwrite", "immediateRender", "startAt", "runBackwards"].includes(p),
115 );
116 const flags = computeFlags(tw, bboxes, { width: WIDTH, height: HEIGHT });
117 const summary = describeTween(tw, animProps, bboxes, flags);
118
119 report.tweens.push({
120 index: i + 1,
121 selector: tw.selectorHint ?? "(onUpdate driver)",
122 driver: tw.driver,
123 targets: tw.targetCount,
124 props: animProps,
125 start: +tw.start.toFixed(3),
126 end: +tw.end.toFixed(3),
127 duration: +(tw.end - tw.start).toFixed(3),
128 ease: tw.ease,
129 bboxes,
130 flags,
131 summary,
132 });
133 }
134
135 markCollisions(report.tweens);
136
137 for (const tw of report.tweens) {
138 if (tw.flags.includes("collision") && !tw.summary.includes("collision")) {
139 tw.summary += " Overlaps another animated element.";
140 }
141 }
142
143 // ── Composition-level analysis ──
144 report.choreography = buildTimeline(report.tweens, duration);
145 report.density = computeDensity(report.tweens, duration);
146 // Staggers and lifecycles are per-ELEMENT, and a driver tween has none. Keyed on
147 // tw.selector they would collapse every driver in the composition into one
148 // "(onUpdate driver)" pseudo-element with null geometry, and let three same-duration
149 // drivers read as a stagger no element performs. Density, dead zones and the timeline
150 // still count them — those are per-SPAN, which is what a driver does have.
151 const elementTweens = report.tweens.filter((tw) => tw.driver !== "onUpdate");
152 report.staggers = detectStaggers(elementTweens);
153 report.elements = buildElementLifecycles(elementTweens);
154 report.deadZones = findDeadZones(report.density, duration);
155 report.snapshots = await captureSnapshots(session, report.tweens, duration);
156
157 await writeFile(join(OUT_DIR, "animation-map.json"), JSON.stringify(report, null, 2));
158
159 printSummary(report);
160} finally {
161 if (session) await closeCaptureSession(session).catch(() => {});
162 server?.close();
163 bundle.cleanup();
164}
165
166// ─── Seek helper ────────────────────────────────────────────────────────────
167
168async function seekTo(session, t) {
169 await session.page.evaluate((time) => {
170 if (window.__hf && typeof window.__hf.seek === "function") {
171 window.__hf.seek(time);
172 return;
173 }
174 const tls = window.__timelines;
175 if (tls) {
176 for (const tl of Object.values(tls)) {
177 if (typeof tl.seek === "function") tl.seek(time);
178 }
179 }
180 }, t);
181 await new Promise((r) => setTimeout(r, 100));
182}
183
184// ─── Timeline introspection ──────────────────────────────────────────────────
185
186async function enumerateTweens(session) {
187 return await session.page.evaluate(() => {
188 const results = [];
189 const registry = window.__timelines || {};
190
191 const selectorOf = (el) => {
192 if (!el || !(el instanceof Element)) return null;
193 if (el.id) return `#${el.id}`;
194 const cls = [...el.classList].slice(0, 2).join(".");
195 return cls ? `${el.tagName.toLowerCase()}.${cls}` : el.tagName.toLowerCase();
196 };
197
198 const walk = (node, parentOffset = 0, parentDriven = false) => {
199 if (!node) return;
200 if (typeof node.getChildren === "function") {
201 const offset = parentOffset + (node.startTime?.() ?? 0);
202 // A TIMELINE can own the driver instead of the tween. The WebGL/uniform idiom is
203 // gsap.timeline({ onUpdate: renderFrame }) over children that tween plain uniform
204 // objects; those children carry no onUpdate of their own, so the driver has to
205 // reach them from above or their motion reads as a dead zone all the same.
206 const driven = parentDriven || typeof node.vars?.onUpdate === "function";
207 for (const child of node.getChildren(true, true, true)) {
208 walk(child, offset, driven);
209 }
210 return;
211 }
212 const targets = (node.targets?.() ?? []).filter((t) => t instanceof Element);
213 const vars = node.vars ?? {};
214 const props = Object.keys(vars).filter(
215 (k) =>
216 ![
217 "duration",
218 "ease",
219 "delay",
220 "repeat",
221 "yoyo",
222 "onStart",
223 "onUpdate",
224 "onComplete",
225 "stagger",
226 ].includes(k),
227 );
228 // The proxy-driver idiom tweens a plain object and applies the motion in onUpdate,
229 // so targets() holds no Element. Dropping those tweens hid real motion from the
230 // map: computeDensity saw zero active tweens over their span and findDeadZones
231 // reported it as dead. There is no element to select or measure here, but the span
232 // is real, so keep the tween and mark why it carries no geometry.
233 //
234 // Under an inherited driver the tween must also CHANGE something. Its own onUpdate is
235 // proof of work by itself (a repaint loop need not animate a property), but a parent's
236 // is not: a bare `tl.to({}, { duration: D })` spacer inside a driven timeline advances
237 // the playhead without altering any value, so counting it would mask a genuine dead
238 // zone — the exact false positive the tween-local rule was careful to avoid.
239 const isProxyDriver =
240 targets.length === 0 &&
241 (typeof vars.onUpdate === "function" || (parentDriven && props.length > 0));
242 if (!targets.length && !isProxyDriver) return;
243 const start = parentOffset + (node.startTime?.() ?? 0);
244 const end = start + (node.duration?.() ?? 0);
245 results.push({
246 // null, not a placeholder string: this feeds document.querySelector downstream,
247 // so it must be absent rather than unmatchable.
248 selectorHint: isProxyDriver ? null : (selectorOf(targets[0]) ?? "(unknown)"),
249 driver: isProxyDriver ? "onUpdate" : "target",
250 targetCount: targets.length,
251 props,
252 start,
253 end,
254 ease: typeof vars.ease === "string" ? vars.ease : (vars.ease?.toString?.() ?? "none"),
255 });
256 };
257
258 for (const tl of Object.values(registry)) walk(tl, 0);
259 results.sort((a, b) => a.start - b.start);
260 return results;
261 });
262}
263
264// ─── Tween description (the key output for agents) ──────────────────────────
265
266function describeTween(tw, props, bboxes, flags) {
267 const dur = (tw.end - tw.start).toFixed(2);
268 const parts = [];
269
270 if (tw.selectorHint) {
271 parts.push(`${tw.selectorHint} animates ${props.join("+")} over ${dur}s (${tw.ease})`);
272 } else {
273 // An onUpdate driver: the span and props are known, the affected element is not.
274 parts.push(
275 `an onUpdate driver animates ${props.join("+")} over ${dur}s (${tw.ease}) — ` +
276 `motion is applied in JS, so no element geometry was measured`,
277 );
278 }
279
280 // Movement
281 const first = bboxes[0];
282 const last = bboxes[bboxes.length - 1];
283 if (first && last) {
284 const dx = last.x - first.x;
285 const dy = last.y - first.y;
286 if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {
287 const dirs = [];
288 if (Math.abs(dy) > 3) dirs.push(dy < 0 ? `${Math.abs(dy)}px up` : `${Math.abs(dy)}px down`);
289 if (Math.abs(dx) > 3)
290 dirs.push(dx < 0 ? `${Math.abs(dx)}px left` : `${Math.abs(dx)}px right`);
291 parts.push(`moves ${dirs.join(" and ")}`);
292 }
293 }
294
295 // Opacity
296 if (first && last && first.opacity !== undefined && last.opacity !== undefined) {
297 const o1 = first.opacity;
298 const o2 = last.opacity;
299 if (Math.abs(o2 - o1) > 0.1) {
300 if (o1 < 0.1 && o2 > 0.5) parts.push("fades in");
301 else if (o1 > 0.5 && o2 < 0.1) parts.push("fades out");
302 else parts.push(`opacity ${o1.toFixed(1)}→${o2.toFixed(1)}`);
303 }
304 }
305
306 // Scale (from props)
307 if (props.includes("scale") || props.includes("scaleX") || props.includes("scaleY")) {
308 parts.push("scales");
309 }
310
311 // Size changes
312 if (first && last) {
313 const dw = last.w - first.w;
314 const dh = last.h - first.h;
315 if (Math.abs(dw) > 5) parts.push(`width ${first.w}→${last.w}px`);
316 if (Math.abs(dh) > 5) parts.push(`height ${first.h}→${last.h}px`);
317 }
318
319 // Visibility
320 if (first && last && first.visible !== last.visible) {
321 parts.push(last.visible ? "becomes visible" : "becomes hidden");
322 }
323
324 // Final position
325 if (last && !last.missing) {
326 parts.push(`ends at (${last.x}, ${last.y}) ${last.w}×${last.h}px`);
327 }
328
329 // Flags
330 if (flags.length > 0) {
331 parts.push(`FLAGS: ${flags.join(", ")}`);
332 }
333
334 return parts.join(". ") + ".";
335}
336
337// ─── Flag computation ───────────────────────────────────────────────────────
338
339function computeFlags(tw, bboxes, { width, height }) {
340 const flags = [];
341 const dur = tw.end - tw.start;
342
343 // No samples at all (an onUpdate driver has no element to measure) is not evidence of
344 // a degenerate or invisible box — `[].every()` is vacuously true, so guard the
345 // geometry-derived flags. The pacing flags below read only start/end and still apply.
346 if (bboxes.length && bboxes.every((b) => b.w === 0 || b.h === 0)) flags.push("degenerate");
347
348 const anyOffscreen = bboxes.some(
349 (b) =>
350 b.x + b.w <= 0 ||
351 b.y + b.h <= 0 ||
352 b.x >= width ||
353 b.y >= height ||
354 b.x < -b.w * 0.5 ||
355 b.y < -b.h * 0.5 ||
356 b.x + b.w > width + b.w * 0.5 ||
357 b.y + b.h > height + b.h * 0.5,
358 );
359 if (anyOffscreen) flags.push("offscreen");
360
361 if (
362 bboxes.length &&
363 bboxes.every((b) => b.opacity !== undefined && b.opacity < 0.01 && b.visible)
364 ) {
365 flags.push("invisible");
366 }
367
368 if (dur < 0.2 && tw.props.some((p) => ["y", "x", "opacity", "scale"].includes(p))) {
369 flags.push("paced-fast");
370 }
371 if (dur > 2.0) flags.push("paced-slow");
372
373 return flags;
374}
375
376function markCollisions(tweens) {
377 for (let i = 0; i < tweens.length; i++) {
378 for (let j = i + 1; j < tweens.length; j++) {
379 const a = tweens[i];
380 const b = tweens[j];
381 if (a.end <= b.start || b.end <= a.start) continue;
382 for (const ba of a.bboxes) {
383 const bb = b.bboxes.find((x) => Math.abs(x.t - ba.t) < 0.05);
384 if (!bb) continue;
385 const overlap = rectOverlapArea(ba, bb);
386 const aArea = ba.w * ba.h;
387 if (aArea > 0 && overlap / aArea > 0.3) {
388 if (!a.flags.includes("collision")) a.flags.push("collision");
389 if (!b.flags.includes("collision")) b.flags.push("collision");
390 break;
391 }
392 }
393 }
394 }
395}
396
397function rectOverlapArea(a, b) {
398 const x1 = Math.max(a.x, b.x);
399 const y1 = Math.max(a.y, b.y);
400 const x2 = Math.min(a.x + a.w, b.x + b.w);
401 const y2 = Math.min(a.y + a.h, b.y + b.h);
402 return Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
403}
404
405// ─── Composition-level analysis ─────────────────────────────────────────────
406
407function buildTimeline(tweens, duration) {
408 const cols = 60;
409 const lines = [];
410 const secPerCol = duration / cols;
411
412 lines.push("Timeline (" + duration.toFixed(1) + "s, each char ≈ " + secPerCol.toFixed(2) + "s):");
413 lines.push(" " + "0s" + " ".repeat(cols - 8) + duration.toFixed(0) + "s");
414 lines.push(" " + "┼" + "─".repeat(cols - 1) + "┤");
415
416 for (const tw of tweens) {
417 const startCol = Math.floor(tw.start / secPerCol);
418 const endCol = Math.min(cols, Math.ceil(tw.end / secPerCol));
419 const bar =
420 " ".repeat(startCol) +
421 "█".repeat(Math.max(1, endCol - startCol)) +
422 " ".repeat(Math.max(0, cols - endCol));
423 const label = tw.selector + " " + tw.props.join("+");
424 lines.push(" " + bar + " " + label);
425 }
426
427 return lines.join("\n");
428}
429
430function computeDensity(tweens, duration) {
431 const buckets = [];
432 for (let t = 0; t < duration; t += 0.5) {
433 const active = tweens.filter((tw) => tw.start <= t + 0.5 && tw.end >= t);
434 buckets.push({ t: +t.toFixed(1), activeTweens: active.length });
435 }
436 return buckets;
437}
438
439function findDeadZones(density, duration) {
440 const zones = [];
441 let zoneStart = null;
442 for (const d of density) {
443 if (d.activeTweens === 0) {
444 if (zoneStart === null) zoneStart = d.t;
445 } else {
446 if (zoneStart !== null) {
447 const zoneEnd = d.t;
448 if (zoneEnd - zoneStart >= 1.0) {
449 zones.push({
450 start: zoneStart,
451 end: zoneEnd,
452 duration: +(zoneEnd - zoneStart).toFixed(1),
453 note:
454 "No animation for " +
455 (zoneEnd - zoneStart).toFixed(1) +
456 "s. Intentional hold or missing entrance?",
457 });
458 }
459 zoneStart = null;
460 }
461 }
462 }
463 if (zoneStart !== null && duration - zoneStart >= 1.0) {
464 zones.push({
465 start: zoneStart,
466 end: +duration.toFixed(1),
467 duration: +(duration - zoneStart).toFixed(1),
468 note:
469 "No animation for " +
470 (duration - zoneStart).toFixed(1) +
471 "s at end. Final hold or missing outro?",
472 });
473 }
474 return zones;
475}
476
477function detectStaggers(tweens) {
478 const groups = [];
479 const used = new Set();
480
481 for (let i = 0; i < tweens.length; i++) {
482 if (used.has(i)) continue;
483 const tw = tweens[i];
484 const group = [tw];
485 used.add(i);
486
487 for (let j = i + 1; j < tweens.length; j++) {
488 if (used.has(j)) continue;
489 const other = tweens[j];
490 const sameProps = tw.props.join(",") === other.props.join(",");
491 const sameDuration = Math.abs(tw.duration - other.duration) < 0.05;
492 const closeInTime = other.start - tw.start < tw.duration * 4;
493 if (sameProps && sameDuration && closeInTime) {
494 group.push(other);
495 used.add(j);
496 }
497 }
498
499 if (group.length >= 3) {
500 const intervals = [];
501 for (let k = 1; k < group.length; k++) {
502 intervals.push(+(group[k].start - group[k - 1].start).toFixed(3));
503 }
504 const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
505 const maxDrift = Math.max(...intervals.map((iv) => Math.abs(iv - avgInterval)));
506 const consistent = maxDrift < avgInterval * 0.3;
507
508 groups.push({
509 elements: group.map((g) => g.selector),
510 props: tw.props,
511 count: group.length,
512 intervals,
513 avgInterval: +avgInterval.toFixed(3),
514 consistent,
515 note: consistent
516 ? group.length +
517 " elements stagger at " +
518 (avgInterval * 1000).toFixed(0) +
519 "ms intervals"
520 : group.length +
521 " elements stagger with uneven intervals (" +
522 intervals.map((iv) => (iv * 1000).toFixed(0) + "ms").join(", ") +
523 ")",
524 });
525 }
526 }
527
528 return groups;
529}
530
531function buildElementLifecycles(tweens) {
532 const elements = {};
533 for (const tw of tweens) {
534 const sel = tw.selector;
535 if (!elements[sel]) {
536 elements[sel] = { firstTween: tw.start, lastTween: tw.end, tweenCount: 0, props: new Set() };
537 }
538 elements[sel].firstTween = Math.min(elements[sel].firstTween, tw.start);
539 elements[sel].lastTween = Math.max(elements[sel].lastTween, tw.end);
540 elements[sel].tweenCount++;
541 tw.props.forEach((p) => elements[sel].props.add(p));
542 }
543
544 const result = {};
545 for (const [sel, data] of Object.entries(elements)) {
546 const lastBbox = findLastBbox(tweens, sel);
547 result[sel] = {
548 firstAppears: +data.firstTween.toFixed(3),
549 lastAnimates: +data.lastTween.toFixed(3),
550 tweenCount: data.tweenCount,
551 props: [...data.props],
552 endsVisible: lastBbox ? lastBbox.opacity > 0.1 && lastBbox.visible : null,
553 finalPosition: lastBbox
554 ? { x: lastBbox.x, y: lastBbox.y, w: lastBbox.w, h: lastBbox.h }
555 : null,
556 };
557 }
558 return result;
559}
560
561function findLastBbox(tweens, selector) {
562 for (let i = tweens.length - 1; i >= 0; i--) {
563 if (tweens[i].selector === selector && tweens[i].bboxes?.length > 0) {
564 return tweens[i].bboxes[tweens[i].bboxes.length - 1];
565 }
566 }
567 return null;
568}
569
570async function captureSnapshots(session, tweens, duration) {
571 const times = [0, duration * 0.25, duration * 0.5, duration * 0.75, duration - 0.1];
572 const snapshots = [];
573
574 for (const t of times) {
575 await seekTo(session, t);
576 const visible = await session.page.evaluate(() => {
577 const out = [];
578 const els = document.querySelectorAll("[id]");
579 for (const el of els) {
580 const cs = getComputedStyle(el);
581 if (cs.display === "none") continue;
582 const opacity = parseFloat(cs.opacity);
583 if (opacity < 0.01) continue;
584 const rect = el.getBoundingClientRect();
585 if (rect.width < 1 || rect.height < 1) continue;
586 out.push({
587 id: el.id,
588 x: Math.round(rect.x),
589 y: Math.round(rect.y),
590 w: Math.round(rect.width),
591 h: Math.round(rect.height),
592 opacity: +opacity.toFixed(2),
593 });
594 }
595 return out;
596 });
597
598 const activeTweens = tweens
599 .filter((tw) => tw.start <= t && tw.end >= t)
600 .map((tw) => tw.selector);
601
602 snapshots.push({
603 t: +t.toFixed(2),
604 visibleElements: visible.length,
605 animatingNow: activeTweens,
606 elements: visible,
607 });
608 }
609
610 return snapshots;
611}
612
613// ─── Output ─────────────────────────────────────────────────────────────────
614
615function printSummary(report) {
616 console.log(
617 `\nAnimation map: ${report.mappedTweens}/${report.totalTweens} tweens (skipped ${report.skippedMicroTweens} micro-tweens)`,
618 );
619
620 const flagCounts = {};
621 for (const tw of report.tweens) {
622 for (const f of tw.flags) flagCounts[f] = (flagCounts[f] ?? 0) + 1;
623 }
624 if (Object.keys(flagCounts).length > 0) {
625 for (const [f, n] of Object.entries(flagCounts)) console.log(` ${f}: ${n}`);
626 }
627 if (report.staggers?.length > 0) {
628 console.log(` staggers: ${report.staggers.map((s) => s.note).join("; ")}`);
629 }
630 if (report.deadZones?.length > 0) {
631 console.log(
632 ` dead zones: ${report.deadZones.map((z) => z.start + "-" + z.end + "s").join(", ")}`,
633 );
634 }
635
636 console.log(report.choreography);
637}
638
639function parseArgs(argv) {
640 const out = {};
641 let positional = 0;
642 for (let i = 0; i < argv.length; i++) {
643 const a = argv[i];
644 if (a.startsWith("--")) {
645 const k = a.slice(2);
646 const v = argv[i + 1]?.startsWith("--") ? true : argv[++i];
647 out[k] = v;
648 } else if (positional === 0) {
649 out.composition = a;
650 positional++;
651 }
652 }
653 return out;
654}
655
656function die(msg) {
657 console.error(`animation-map: ${msg}`);
658 process.exit(2);
659}