Skip to content

Commit 1cd086f

Browse files
authored
feat(cli): snapshot a time range or one composition (#5519)
1 parent e921645 commit 1cd086f

4 files changed

Lines changed: 179 additions & 13 deletions

File tree

‎docs/packages/cli.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,8 @@ npx hyperframes snapshot my-project --at 1.5,4.3 --against ref.mp4
853853
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
854854
| `--at` | Timestamps in seconds, comma-separated (`3.0,10.5,18.0`) |
855855
| `--frames` | Evenly spaced frames instead (default 5) |
856+
| `--range <start,end>` | Spread `--frames` across this interval only, in root-timeline seconds, with no end-of-timeline frame added |
857+
| `--composition <id>` | Spread `--frames` across the visible interval of the element with this `data-composition-id`. Use one of `--at`, `--range` or `--composition`. |
856858
| `--output, -o` | Where the PNGs go (default `<project>/snapshots`) |
857859
| `--end` / `--no-end` | Always add a readable end-of-timeline frame (default: on). `--no-end` captures only your `--at` times. |
858860
| `--zoom` | Crop to a CSS selector or an exact `x,y,w,h` region, using a raised device scale factor. Layout is untouched — never CSS zoom or a resized viewport. A selector that matches nothing is an error. |

‎packages/cli/src/commands/snapshot.ts‎

Lines changed: 63 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
import {
2+
parseSnapshotRange,
3+
sampleSnapshotRange,
4+
resolveSnapshotCompositionRange,
5+
type SnapshotRange,
6+
} from "./snapshotSampling.js";
17
import { failCommand } from "../utils/commandResult.js";
28
// fallow-ignore-file complexity
39
import { defineCommand } from "citty";
@@ -436,6 +442,8 @@ async function captureSnapshots(
436442
projectDir: string,
437443
opts: {
438444
frames?: number;
445+
range?: SnapshotRange;
446+
composition?: string;
439447
timeout?: number;
440448
at?: number[];
441449
outputDir?: string;
@@ -517,13 +525,38 @@ async function captureSnapshots(
517525
return [];
518526
}
519527

520-
// Calculate seek positions — explicit timestamps or evenly spaced, always
521-
// including a readable end-of-timeline frame (FINDING [7]).
522-
const { times: positions, appendedTail } = computeSnapshotTimes(duration, {
523-
frames: numFrames,
524-
at: opts.at,
525-
includeEnd: opts.includeEnd,
526-
});
528+
let range = opts.range;
529+
if (opts.composition) {
530+
const timing = await page.evaluate(() => ({
531+
html: document.documentElement.outerHTML,
532+
durations: Object.fromEntries(
533+
Object.entries((window as any).__timelines ?? {}).map(([id, timeline]) => [
534+
id,
535+
Number((timeline as any).duration?.()),
536+
]),
537+
),
538+
}));
539+
range = resolveSnapshotCompositionRange(
540+
timing.html,
541+
timing.durations,
542+
opts.composition,
543+
duration,
544+
);
545+
}
546+
const { times: positions, appendedTail } = range
547+
? {
548+
times: sampleSnapshotRange(range, numFrames, duration, !!opts.composition),
549+
appendedTail: false,
550+
}
551+
: computeSnapshotTimes(duration, {
552+
frames: numFrames,
553+
at: opts.at,
554+
includeEnd: opts.includeEnd,
555+
});
556+
if (range)
557+
console.log(
558+
` Sampling ${positions.length} frames within ${range[0]}–${range[1]}s${opts.composition ? ` (composition ${opts.composition})` : ""}`,
559+
);
527560
if (appendedTail) {
528561
console.log(
529562
` ${c.dim(`Note: added an end-of-timeline frame at ${positions[positions.length - 1]!.toFixed(2)}s. Short beats between your --at times may still be skipped — pass them explicitly.`)}`,
@@ -842,6 +875,16 @@ export default defineCommand({
842875
description:
843876
"Comma-separated timestamps in seconds (e.g., --at 3.0,10.5,18.0). Each is captured at that exact instant, not snapped to a frame.",
844877
},
878+
range: {
879+
type: "string",
880+
description:
881+
"Root-timeline range START,END in seconds; sample --frames evenly within it, without adding the full-video tail",
882+
},
883+
composition: {
884+
type: "string",
885+
description:
886+
"data-composition-id to sample; take --frames within its effective root-timeline interval, without adding the full-video tail",
887+
},
845888
timeout: {
846889
type: "string",
847890
description: "Ms to wait for runtime to initialize (default: 5000)",
@@ -892,6 +935,13 @@ export default defineCommand({
892935
},
893936
},
894937
async run({ args }) {
938+
if ([args.at, args.range, args.composition].filter((value) => value !== undefined).length > 1)
939+
throw new Error("Use only one of --at, --range, or --composition");
940+
const frames = parseInt(args.frames as string, 10) || 5;
941+
const range = args.range === undefined ? undefined : parseSnapshotRange(String(args.range));
942+
const composition =
943+
args.composition === undefined ? undefined : String(args.composition).trim();
944+
if (composition === "") throw new Error("--composition requires a composition ID");
895945
const project = resolveProject(args.dir);
896946
const lintResult = await lintProject(project.dir);
897947
if (hasDefinitiveEntryMismatch(lintResult)) {
@@ -920,7 +970,6 @@ export default defineCommand({
920970
console.log("");
921971
failCommand();
922972
}
923-
const frames = parseInt(args.frames as string, 10) || 5;
924973
const timeout = parseInt(args.timeout as string, 10) || 5000;
925974
const atTimestamps = args.at
926975
? String(args.at)
@@ -963,6 +1012,8 @@ export default defineCommand({
9631012
: join(project.dir, "snapshots");
9641013
const paths = await captureSnapshots(project.dir, {
9651014
frames,
1015+
range,
1016+
composition,
9661017
timeout,
9671018
at: atTimestamps,
9681019
outputDir: snapshotDir,
@@ -1001,10 +1052,8 @@ export default defineCommand({
10011052
snapshotDir,
10021053
join(snapshotDir, "contact-sheet.jpg"),
10031054
);
1004-
if (sheets.length > 0) {
1005-
const label =
1006-
sheets.length === 1 ? "contact-sheet.jpg" : `contact-sheet-1..${sheets.length}.jpg`;
1007-
console.log(` ${c.dim(label)} (grid view for AI review)`);
1055+
for (const sheet of sheets) {
1056+
console.log(` ${resolve(sheet)} (grid view for AI review)`);
10081057
}
10091058
} catch (err) {
10101059
console.warn(
@@ -1019,7 +1068,8 @@ export default defineCommand({
10191068
try {
10201069
const geminiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
10211070
if (!geminiKey) {
1022-
console.log(` ${c.dim("--describe: GEMINI_API_KEY not set, skipping")}`);
1071+
if (args.describe !== undefined)
1072+
console.log(` ${c.dim("--describe: GEMINI_API_KEY not set, skipping")}`);
10231073
} else if (paths.length > 0) {
10241074
console.log(` ${c.dim("Describing frames with Gemini vision...")}`);
10251075
const { GoogleGenAI } = await loadOptionalPackage("@google/genai", "--describe");
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { describe, it, expect } from "vitest";
2+
import {
3+
parseSnapshotRange,
4+
sampleSnapshotRange,
5+
resolveSnapshotCompositionRange,
6+
} from "./snapshotSampling.js";
7+
describe("snapshot scoped sampling", () => {
8+
it("samples only the requested range with exact count", () => {
9+
expect(sampleSnapshotRange([2, 4], 5, 10)).toEqual([2, 2.5, 3, 3.5, 4]);
10+
expect(sampleSnapshotRange([2, 4], 1, 10)).toEqual([3]);
11+
const samples = sampleSnapshotRange([2, 4], 8, 10, true);
12+
expect(samples).toHaveLength(8);
13+
expect(samples[0]).toBe(2);
14+
expect(samples[7]).toBeLessThan(4);
15+
});
16+
it("rejects malformed ranges and counts", () => {
17+
for (const v of ["1", "1:", ":2", "a:3", "3:2", "1:1", "-1:2", "0:Infinity"])
18+
expect(() => parseSnapshotRange(v)).toThrow();
19+
expect(parseSnapshotRange("1.8:2.5")).toEqual([1.8, 2.5]);
20+
expect(parseSnapshotRange("1.8,2.5")).toEqual([1.8, 2.5]);
21+
for (const n of [0, -1, 1.5, NaN]) expect(() => sampleSnapshotRange([1, 2], n, 5)).toThrow();
22+
expect(() => sampleSnapshotRange([1, 6], 5, 5)).toThrow();
23+
});
24+
const html = `<html><body><div data-composition-id="main" data-duration="12"><div id="parent" data-composition-id="parent" data-start="3" data-duration="4"><div data-composition-id="child" data-start="2" data-duration="5"></div></div><div data-composition-id="later" data-start="parent + 1" data-duration="2"></div></div></body></html>`;
25+
it("resolves nested offsets and clamps to ancestor visibility", () => {
26+
expect(resolveSnapshotCompositionRange(html, {}, "child", 12)).toEqual([5, 7]);
27+
expect(resolveSnapshotCompositionRange(html, {}, "later", 12)).toEqual([8, 10]);
28+
expect(resolveSnapshotCompositionRange(html, {}, "main", 12)).toEqual([0, 12]);
29+
});
30+
it("uses registered duration and rejects missing or ambiguous IDs", () => {
31+
const h =
32+
'<div data-composition-id="main" data-duration="10"><div data-composition-id="intro" data-start="2"></div></div>';
33+
expect(resolveSnapshotCompositionRange(h, { intro: 3 }, "intro", 10)).toEqual([2, 5]);
34+
expect(resolveSnapshotCompositionRange(h, {}, "intro", 10)).toEqual([2, 10]);
35+
expect(() => resolveSnapshotCompositionRange(h, {}, "absent", 10)).toThrow();
36+
expect(() => resolveSnapshotCompositionRange(h + h, {}, "intro", 10)).toThrow();
37+
});
38+
});
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { parseHTML } from "linkedom";
2+
import { createRuntimeStartTimeResolver } from "@hyperframes/core";
3+
export type SnapshotRange = [number, number];
4+
export function parseSnapshotRange(value: string): SnapshotRange {
5+
const parts = value.split(/[,:]/);
6+
const range = parts.map((part) => (part.trim() === "" ? NaN : Number(part)));
7+
if (
8+
parts.length !== 2 ||
9+
!range.every(Number.isFinite) ||
10+
range[0]! < 0 ||
11+
range[1]! <= range[0]!
12+
)
13+
throw new Error("--range must be START,END in seconds, with 0 <= START < END");
14+
return [range[0]!, range[1]!];
15+
}
16+
export function sampleSnapshotRange(
17+
[start, end]: SnapshotRange,
18+
frames: number,
19+
duration: number,
20+
exclusiveEnd = false,
21+
): number[] {
22+
if (!Number.isInteger(frames) || frames < 1)
23+
throw new Error("--frames must be a positive integer");
24+
if (
25+
!Number.isFinite(duration) ||
26+
duration <= 0 ||
27+
!Number.isFinite(start) ||
28+
!Number.isFinite(end) ||
29+
start < 0 ||
30+
end <= start ||
31+
end > duration
32+
)
33+
throw new Error(`Snapshot range must satisfy 0 <= START < END <= ${duration}s`);
34+
if (frames === 1) return [(start + end) / 2];
35+
// Clip ends are exclusive; keep the last sample inside the visible interval.
36+
const last =
37+
exclusiveEnd || end === duration ? end - Math.min(0.001, (end - start) / (frames * 2)) : end;
38+
return Array.from({ length: frames }, (_, i) => start + ((last - start) * i) / (frames - 1));
39+
}
40+
export function resolveSnapshotCompositionRange(
41+
html: string,
42+
durations: Record<string, number>,
43+
id: string,
44+
duration: number,
45+
): SnapshotRange {
46+
const { document } = parseHTML(html);
47+
const matches = Array.from(document.querySelectorAll("[data-composition-id]")).filter(
48+
(el) => el.getAttribute("data-composition-id") === id,
49+
);
50+
if (matches.length !== 1)
51+
throw new Error(
52+
`Composition ID ${JSON.stringify(id)} matched ${matches.length} elements; expected exactly one`,
53+
);
54+
const registry = Object.fromEntries(
55+
Object.entries(durations).map(([key, value]) => [key, { duration: () => value }]),
56+
);
57+
const resolver = createRuntimeStartTimeResolver({
58+
documentRef: document as unknown as Document,
59+
timelineRegistry: registry,
60+
includeAuthoredTimingAttrs: true,
61+
});
62+
let start = 0,
63+
end = duration;
64+
for (let el: Element | null = matches[0] as unknown as Element; el; el = el.parentElement) {
65+
if (!el.hasAttribute("data-composition-id") && !el.hasAttribute("data-start")) continue;
66+
const localStart = resolver.resolveStartForElement(el, 0);
67+
const length = resolver.resolveDurationForElement(el);
68+
if (!Number.isFinite(localStart))
69+
throw new Error(`Cannot resolve start of composition ${JSON.stringify(id)}`);
70+
start = Math.max(start, localStart);
71+
if (length != null) end = Math.min(end, localStart + length);
72+
}
73+
if (end <= start)
74+
throw new Error(`Composition ${JSON.stringify(id)} has no visible time interval`);
75+
return [start, end];
76+
}

0 commit comments

Comments
 (0)