@gnawbit/tabretake 0.4.2 → 0.5.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.
@@ -1,34 +1,25 @@
1
1
  import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { parseCommand } from "./lib/options.mjs";
3
+ import { parseCommand, parseViewport } from "./lib/options.mjs";
4
4
  import {
5
5
  clickAndType,
6
6
  dragBy,
7
7
  hover,
8
8
  installCursor,
9
9
  launchBrowser,
10
+ loginAndSave,
10
11
  moveAndClick,
11
- newContext,
12
12
  openRecordedPage,
13
13
  resolveLocator,
14
+ selectOption,
14
15
  } from "./lib/browser.mjs";
15
- import { waitForEnter } from "./lib/tty.mjs";
16
16
  import { assertConfig, readConfig } from "./lib/config.mjs";
17
17
  import { commandError, createReporter, requireInteractiveLogin } from "./lib/report.mjs";
18
18
  import { navigate } from "./lib/navigation.mjs";
19
+ import { resolveTheme } from "./lib/themes.mjs";
19
20
 
20
- function parseViewport(value, fallback = { width: 1440, height: 810 }) {
21
- if (value === undefined) return fallback;
22
- if (!/^[1-9]\d*x[1-9]\d*$/.test(value)) throw new Error("--viewport must be WIDTHxHEIGHT with positive integers");
23
- const [width, height] = value.split("x").map(Number);
24
- return { width, height };
25
- }
26
-
27
- export async function record(argv, command = "record") {
21
+ export async function executeRecord(values, { command = "record", reporter = createReporter(command, Boolean(values?.json)) } = {}) {
28
22
  const preview = command === "preview";
29
- const { values } = parseCommand(command, argv);
30
- requireInteractiveLogin(values);
31
- const reporter = createReporter(command, values.json);
32
23
  const screenshots = [];
33
24
 
34
25
  if (!values.config && !values.url) {
@@ -48,11 +39,21 @@ export async function record(argv, command = "record") {
48
39
  width: 1440,
49
40
  height: 810,
50
41
  });
51
- assertConfig({ ...config, url, viewport }, { kind: "story" });
52
- const scale = 1;
42
+ const scaleInput = values.scale === undefined
43
+ ? (config.scale ?? 1)
44
+ : (String(values.scale).trim() === "" ? NaN : Number(values.scale));
45
+ if (scaleInput !== 1 && scaleInput !== 2) {
46
+ throw commandError("INVALID_CONFIG", "scale / --scale must be 1 or 2", {
47
+ hint: "Choose 1 (standard) or 2 (HiDPI Retina).",
48
+ });
49
+ }
50
+ const scale = scaleInput;
51
+ assertConfig({ ...config, url, viewport, scale }, { kind: "story" });
53
52
  const steps = config.steps || [];
54
53
  if (steps.length === 0) throw new Error("Config has no steps");
55
54
 
55
+ const theme = resolveTheme(config.brand, values.preset);
56
+
56
57
  const outDir = path.resolve(values.out || config.out || "demo");
57
58
  const rawDir = path.join(outDir, "raw");
58
59
  if (!preview) {
@@ -75,6 +76,7 @@ export async function record(argv, command = "record") {
75
76
  headless: preview ? values.headless : !values.headed,
76
77
  proxy: values.proxy,
77
78
  browser: values.browser,
79
+ scale,
78
80
  });
79
81
 
80
82
  let videoPath = null;
@@ -86,11 +88,12 @@ export async function record(argv, command = "record") {
86
88
  const videoStartedAt = Date.now();
87
89
  const { context, page } = await openRecordedPage(browser, {
88
90
  viewport,
91
+ scale,
89
92
  videoDir: preview ? undefined : rawDir,
90
93
  storageState,
91
94
  });
92
95
 
93
- await installCursor(page);
96
+ await installCursor(page, { accent: theme.accent });
94
97
 
95
98
  events = [];
96
99
 
@@ -154,6 +157,24 @@ export async function record(argv, command = "record") {
154
157
  break;
155
158
  }
156
159
 
160
+ case "select": {
161
+ const locator = await resolveLocator(page, step);
162
+ const value = String(step.value ?? step.text ?? "");
163
+ const point = await selectOption(page, locator, value, 0, Number(step.timeout ?? 20000));
164
+ events.push({
165
+ t,
166
+ tEnd: Date.now() - startedAt,
167
+ zoom: step.zoom !== false,
168
+ action: "select",
169
+ x: point.x,
170
+ y: point.y,
171
+ caption: step.caption || "",
172
+ label: value,
173
+ });
174
+ await page.waitForTimeout(Number(step.pause ?? 500));
175
+ break;
176
+ }
177
+
157
178
  case "hover": {
158
179
  const locator = await resolveLocator(page, step);
159
180
  const point = await hover(page, locator, 0);
@@ -303,8 +324,11 @@ export async function record(argv, command = "record") {
303
324
 
304
325
  if (preview) {
305
326
  reporter.log(`Preview completed ${steps.length} step(s).`);
306
- await reporter.success({ duration: timelineDuration, stepCount: steps.length, artifacts: screenshots });
307
- return;
327
+ return {
328
+ summary: { duration: timelineDuration, stepCount: steps.length, artifacts: screenshots },
329
+ record: null,
330
+ recordPath: null,
331
+ };
308
332
  }
309
333
 
310
334
  const recordingPath = path.join(outDir, "recording.webm");
@@ -329,26 +353,27 @@ export async function record(argv, command = "record") {
329
353
  reporter.log(`Record: ${recordPath}`);
330
354
  reporter.log(`\nNext: tabretake render --config ${path.relative(process.cwd(), recordPath)}`);
331
355
  reporter.log(` (or pass the original --config path)\n`);
332
- await reporter.success({ duration: timelineDuration, eventCount: events.length, artifacts: [
333
- { kind: "video", path: recordingPath }, { kind: "timeline", path: recordPath }, ...screenshots,
334
- ] });
335
356
 
336
- return record;
357
+ return {
358
+ summary: {
359
+ duration: timelineDuration,
360
+ eventCount: events.length,
361
+ artifacts: [
362
+ { kind: "video", path: recordingPath },
363
+ { kind: "timeline", path: recordPath },
364
+ ...screenshots,
365
+ ],
366
+ },
367
+ record,
368
+ recordPath,
369
+ };
337
370
  }
338
371
 
339
- async function loginAndSave(url, { proxy, viewport, browser: browserMode, statePath }) {
340
- const browser = await launchBrowser({ headless: false, proxy, browser: browserMode });
341
- try {
342
- const context = await newContext(browser, { viewport });
343
- const page = await context.newPage();
344
- await navigate(page, url, { allowAuthErrors: true });
345
- console.log("\nA browser window is open. Log in, then come back here.");
346
- await waitForEnter("Press Enter when you are logged in... ");
347
- await context.storageState({ path: statePath });
348
- console.log(`Saved login state to ${statePath}\n`);
349
- await context.close();
350
- return statePath;
351
- } finally {
352
- await browser.close();
353
- }
372
+ export async function record(argv, command = "record") {
373
+ const { values } = parseCommand(command, argv);
374
+ requireInteractiveLogin(values);
375
+ const reporter = createReporter(command, values.json);
376
+ const result = await executeRecord(values, { command, reporter });
377
+ await reporter.success(result.summary);
378
+ return result.record;
354
379
  }
@@ -58,15 +58,17 @@ function landscapeLayout(videoW, videoH) {
58
58
  };
59
59
  }
60
60
 
61
- function verticalLayout(videoW, videoH) {
61
+ function verticalLayout(videoW, videoH, frameMode = "auto") {
62
62
  const layout = LAYOUTS.vertical;
63
63
  // Fit the source between branding and captions instead of cropping a phone
64
64
  // recording into the landscape card. Keep the existing 16:9 card geometry.
65
- const fit = Math.min(layout.content.w / videoW, 900 / videoH);
65
+ const maxHeight = frameMode === "phone" ? 800 : 900;
66
+ const centerY = frameMode === "phone" ? 920 : layout.content.y + layout.content.h / 2;
67
+ const fit = Math.min(layout.content.w / videoW, maxHeight / videoH);
66
68
  const w = Math.max(2, Math.floor(videoW * fit / 2) * 2);
67
69
  const h = Math.max(2, Math.floor(videoH * fit / 2) * 2);
68
70
  const x = (layout.width - w) / 2;
69
- const y = layout.content.y + (layout.content.h - h) / 2;
71
+ const y = centerY - h / 2;
70
72
  return {
71
73
  ...layout,
72
74
  content: { x, y, w, h },
@@ -163,8 +165,10 @@ async function makeBackground(file, theme, layout) {
163
165
  async function makeBrowserFrame(file, hostname, layout, theme) {
164
166
  const url = escapeXml(hostname || "your-app.com");
165
167
  const { x, y, w, h } = layout.frame;
166
- const bar = layout.content.y - y;
168
+ const { x: cx, y: cy, w: cw, h: ch } = layout.content;
169
+ const bar = cy - y;
167
170
  const f = theme.frame;
171
+ const r = 8;
168
172
  const addressWidth = Math.max(0, Math.min(560, w - 128));
169
173
  const address = addressWidth >= 120 ? `
170
174
  <clipPath id="address-clip"><rect x="${x + 114}" y="${y + 13}" width="${addressWidth - 20}" height="26"/></clipPath>
@@ -179,11 +183,12 @@ async function makeBrowserFrame(file, hostname, layout, theme) {
179
183
  </filter>
180
184
  <mask id="content-cutout">
181
185
  <rect width="${layout.width}" height="${layout.height}" fill="white"/>
182
- <rect x="${layout.content.x}" y="${layout.content.y}" width="${layout.content.w}" height="${layout.content.h}" fill="black"/>
186
+ <path d="M${cx} ${cy}H${cx + cw}V${cy + ch - r}a${r} ${r} 0 0 1 -${r} ${r}H${cx + r}a${r} ${r} 0 0 1 -${r} -${r}Z" fill="black"/>
183
187
  </mask>
184
188
  </defs>
185
189
  <g mask="url(#content-cutout)">
186
190
  <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="18" fill="${f.bar}" filter="url(#shadow)" opacity="${theme.light ? 0.85 : 0.25}"/>
191
+ <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="18" fill="${f.bar}"/>
187
192
  <path d="M${x} ${y + 18}a18 18 0 0 1 18-18h${w - 36}a18 18 0 0 1 18 18v${bar - 18}H${x}z" fill="${f.bar}"/>
188
193
  <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="18" fill="none" stroke="${f.border}" stroke-width="1.5"/>
189
194
  <path d="M${x} ${y + bar}H${x + w}" stroke="${f.divider}" stroke-width="1"/>
@@ -200,6 +205,7 @@ async function makeBrowserFrame(file, hostname, layout, theme) {
200
205
 
201
206
  async function makeCardFrame(file, layout, theme) {
202
207
  const { x, y, w, h } = layout.frame;
208
+ const { x: cx, y: cy, w: cw, h: ch } = layout.content;
203
209
  const f = theme.frame;
204
210
 
205
211
  const svg = `
@@ -214,11 +220,12 @@ async function makeCardFrame(file, layout, theme) {
214
220
  </linearGradient>
215
221
  <mask id="content-cutout">
216
222
  <rect width="${layout.width}" height="${layout.height}" fill="white"/>
217
- <rect x="${layout.content.x}" y="${layout.content.y}" width="${layout.content.w}" height="${layout.content.h}" fill="black"/>
223
+ <rect x="${cx}" y="${cy}" width="${cw}" height="${ch}" rx="12" fill="black"/>
218
224
  </mask>
219
225
  </defs>
220
226
  <g mask="url(#content-cutout)">
221
227
  <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="22" fill="${f.bar}" filter="url(#shadow)" opacity="${theme.light ? 0.75 : 0.3}"/>
228
+ <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="22" fill="${f.bar}"/>
222
229
  <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="22" fill="none" stroke="${f.border}" stroke-width="1.5"/>
223
230
  <rect x="${x + 1.5}" y="${y + 1.5}" width="${w - 3}" height="${h - 3}" rx="20.5" fill="none" stroke="url(#edge)" stroke-width="1"/>
224
231
  <path d="M${x + 24} ${y + 1.5}H${x + w - 24}" stroke="#ffffff" stroke-opacity="0.10" stroke-width="1"/>
@@ -228,6 +235,43 @@ async function makeCardFrame(file, layout, theme) {
228
235
  await sharp(Buffer.from(svg)).png().toFile(file);
229
236
  }
230
237
 
238
+ async function makePhoneFrame(file, layout, theme) {
239
+ const { x: cx, y: cy, w: cw, h: ch } = layout.content;
240
+ const f = theme.frame;
241
+ const padX = 16;
242
+ const padTop = Math.min(34, Math.max(16, cy - 16));
243
+ const maxBottom = layout.caption ? Math.max(16, layout.caption.y - 12 - (cy + ch)) : 34;
244
+ const padBottom = Math.min(34, maxBottom);
245
+ const x = cx - padX;
246
+ const y = cy - padTop;
247
+ const w = cw + padX * 2;
248
+ const h = ch + padTop + padBottom;
249
+ const speakerW = Math.min(72, Math.max(36, Math.round(cw * 0.14)));
250
+
251
+ const svg = `
252
+ <svg xmlns="http://www.w3.org/2000/svg" width="${layout.width}" height="${layout.height}">
253
+ <defs>
254
+ <filter id="shadow" x="-30%" y="-30%" width="160%" height="160%">
255
+ <feDropShadow dx="0" dy="28" stdDeviation="36" flood-color="#000000" flood-opacity="${f.shadowAlpha}"/>
256
+ </filter>
257
+ <mask id="content-cutout">
258
+ <rect width="${layout.width}" height="${layout.height}" fill="white"/>
259
+ <rect x="${cx}" y="${cy}" width="${cw}" height="${ch}" rx="20" fill="black"/>
260
+ </mask>
261
+ </defs>
262
+ <g mask="url(#content-cutout)">
263
+ <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="38" fill="${f.bar}" filter="url(#shadow)" opacity="${theme.light ? 0.85 : 0.4}"/>
264
+ <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="38" fill="${f.bar}"/>
265
+ <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="38" fill="none" stroke="${f.border}" stroke-width="2"/>
266
+ <rect x="${cx - 1}" y="${cy - 1}" width="${cw + 2}" height="${ch + 2}" rx="20" fill="none" stroke="${f.divider}" stroke-width="1"/>
267
+ <rect x="${cx + (cw - speakerW) / 2}" y="${y + padTop / 2 - 2.5}" width="${speakerW}" height="5" rx="2.5" fill="${f.addressBorder}"/>
268
+ <circle cx="${cx + cw / 2 + speakerW / 2 + 12}" cy="${y + padTop / 2}" r="3" fill="${f.addressBorder}"/>
269
+ </g>
270
+ </svg>`;
271
+
272
+ await sharp(Buffer.from(svg)).png().toFile(file);
273
+ }
274
+
231
275
  function buildVerticalChrome(font, cjkFont, hostname, layout, vertical = {}, theme) {
232
276
  if (!font || !layout.title) return "";
233
277
 
@@ -321,12 +365,18 @@ async function renderLayout({
321
365
 
322
366
  const bgPath = path.join(assetsDir, `background-${layout.key}.png`);
323
367
  const framePath = path.join(assetsDir, `frame-${layout.key}.png`);
368
+ const frameMode = record.config?.brand?.frame || "auto";
369
+ const hasFrame = frameMode !== "none";
324
370
 
325
371
  await makeBackground(bgPath, theme, layout);
326
- if (layout.frame.type === "browser") {
327
- await makeBrowserFrame(framePath, hostname, layout, theme);
328
- } else {
329
- await makeCardFrame(framePath, layout, theme);
372
+ if (hasFrame) {
373
+ if (frameMode === "phone" && (layout.key === "vertical" || videoW <= videoH)) {
374
+ await makePhoneFrame(framePath, layout, theme);
375
+ } else if (frameMode === "browser" || (frameMode === "auto" && layout.frame.type === "browser")) {
376
+ await makeBrowserFrame(framePath, hostname, layout, theme);
377
+ } else {
378
+ await makeCardFrame(framePath, layout, theme);
379
+ }
330
380
  }
331
381
 
332
382
  const camera = buildCameraFilter({
@@ -356,12 +406,13 @@ async function renderLayout({
356
406
  const graph = [
357
407
  `[0:v]scale=${layout.width}:${layout.height}[bg]`,
358
408
  `[1:v]${camera.filter}[base]`,
359
- `[bg][base]overlay=${layout.content.x}:${layout.content.y}:format=auto[comp]`,
360
- `[comp][2:v]overlay=0:0[out]`,
409
+ `[bg][base]overlay=${layout.content.x}:${layout.content.y}:format=auto[${hasFrame ? "comp" : "out"}]`,
361
410
  ];
411
+ if (hasFrame) graph.push(`[comp][2:v]overlay=0:0[out]`);
412
+ const captionInputOffset = hasFrame ? 3 : 2;
362
413
  let lastLayer = "out";
363
414
  captions.forEach((caption, i) => {
364
- graph.push(`[${lastLayer}][${i + 3}:v]overlay=${caption.x}:${caption.y}:` +
415
+ graph.push(`[${lastLayer}][${i + captionInputOffset}:v]overlay=${caption.x}:${caption.y}:` +
365
416
  `enable='gte(t,${caption.start})*lt(t,${caption.end})'[caption${i}]`);
366
417
  lastLayer = `caption${i}`;
367
418
  });
@@ -371,7 +422,7 @@ async function renderLayout({
371
422
  await ffmpeg([
372
423
  "-loop", "1", "-framerate", "30", "-i", bgPath,
373
424
  "-i", videoPath,
374
- "-i", framePath,
425
+ ...(hasFrame ? ["-i", framePath] : []),
375
426
  ...captions.flatMap((caption) => ["-i", caption.file]),
376
427
  "-filter_complex", graph.join(";"),
377
428
  "-map", "[v]",
@@ -439,10 +490,7 @@ function marksToEvents(marks, videoW, videoH) {
439
490
  .sort((a, b) => a.t - b.t);
440
491
  }
441
492
 
442
- export async function render(argv) {
443
- const { values } = parseCommand("render", argv);
444
- const reporter = createReporter("render", values.json);
445
-
493
+ export async function executeRender(values, { reporter = createReporter("render", Boolean(values?.json)) } = {}) {
446
494
  if (!values.config) throw new Error("Missing --config");
447
495
 
448
496
  const configPath = path.resolve(values.config);
@@ -563,9 +611,10 @@ export async function render(argv) {
563
611
  }
564
612
 
565
613
  const theme = resolveTheme(record.config?.brand, values.preset);
614
+ const frameMode = record.config?.brand?.frame || "auto";
566
615
 
567
616
  const layouts = [landscapeLayout(videoW, videoH)];
568
- if (values.vertical) layouts.push(verticalLayout(videoW, videoH));
617
+ if (values.vertical) layouts.push(verticalLayout(videoW, videoH, frameMode));
569
618
 
570
619
  let last = null;
571
620
  const artifacts = [];
@@ -597,6 +646,16 @@ export async function render(argv) {
597
646
  (values.vertical ? ", 16:9 + 9:16" : "") +
598
647
  ".\n",
599
648
  );
600
- await reporter.success({ duration: durationSec, posterAt, artifacts });
601
- return last?.outputPath;
649
+ return {
650
+ summary: { duration: durationSec, posterAt, artifacts },
651
+ outputPath: last?.outputPath,
652
+ };
653
+ }
654
+
655
+ export async function render(argv) {
656
+ const { values } = parseCommand("render", argv);
657
+ const reporter = createReporter("render", values.json);
658
+ const result = await executeRender(values, { reporter });
659
+ await reporter.success(result.summary);
660
+ return result.outputPath;
602
661
  }
@@ -0,0 +1,55 @@
1
+ import path from "node:path";
2
+ import { parseCommand } from "./lib/options.mjs";
3
+ import { assertConfig, inspectConfig, readConfig } from "./lib/config.mjs";
4
+ import { createReporter, requireInteractiveLogin } from "./lib/report.mjs";
5
+ import { executeRecord } from "./record.mjs";
6
+ import { executeRender } from "./render.mjs";
7
+
8
+ export async function runPipeline(values, { reporter = createReporter("run", Boolean(values?.json)) } = {}) {
9
+ if (!values.config) {
10
+ throw new Error("Provide --config demo.json");
11
+ }
12
+ const configPath = path.resolve(values.config);
13
+ const raw = await readConfig(configPath);
14
+ const inspected = inspectConfig(raw);
15
+ if (!inspected.ok) {
16
+ assertConfig(raw);
17
+ }
18
+
19
+ const artifacts = [];
20
+ let eventCount;
21
+ let renderConfigPath = configPath;
22
+
23
+ if (inspected.kind === "story") {
24
+ const recordRes = await executeRecord(values, { command: "record", reporter });
25
+ artifacts.push(...recordRes.summary.artifacts);
26
+ eventCount = recordRes.summary.eventCount;
27
+ renderConfigPath = recordRes.recordPath;
28
+ }
29
+
30
+ const renderValues = {
31
+ ...values,
32
+ config: renderConfigPath,
33
+ out: values.out || (inspected.kind === "story" ? path.dirname(renderConfigPath) : undefined),
34
+ };
35
+ const renderRes = await executeRender(renderValues, { reporter });
36
+ artifacts.push(...renderRes.summary.artifacts);
37
+
38
+ return {
39
+ duration: renderRes.summary.duration,
40
+ posterAt: renderRes.summary.posterAt,
41
+ ...(eventCount !== undefined ? { eventCount } : {}),
42
+ artifacts,
43
+ outputPath: renderRes.outputPath,
44
+ };
45
+ }
46
+
47
+ export async function run(argv) {
48
+ const { values } = parseCommand("run", argv);
49
+ requireInteractiveLogin(values);
50
+ const reporter = createReporter("run", values.json);
51
+ const result = await runPipeline(values, { reporter });
52
+ const { outputPath, ...summary } = result;
53
+ await reporter.success(summary);
54
+ return outputPath;
55
+ }