@phil65/demoreel 0.3.1 → 0.4.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.
Files changed (37) hide show
  1. package/THIRD_PARTY_NOTICES.md +1 -1
  2. package/dist/args.js +12 -0
  3. package/dist/cli.js +31 -2
  4. package/dist/compose.d.ts +4 -0
  5. package/dist/compose.js +4 -0
  6. package/dist/gif.d.ts +16 -0
  7. package/dist/gif.js +19 -0
  8. package/dist/index.d.ts +3 -2
  9. package/dist/index.js +2 -1
  10. package/dist/openscreen/project.js +3 -3
  11. package/dist/project.d.ts +51 -1
  12. package/dist/project.js +89 -1
  13. package/dist/record.d.ts +6 -1
  14. package/dist/record.js +2 -1
  15. package/dist/renderer/assets/CanvasPool-PBu3bHFZ.js +1 -0
  16. package/dist/renderer/assets/CanvasRenderer-HmF-4gyW.js +1 -0
  17. package/dist/renderer/assets/RenderTargetSystem-Dk1U4wDJ.js +184 -0
  18. package/dist/renderer/assets/WebGLRenderer-C0v9HBel.js +149 -0
  19. package/dist/renderer/assets/WebGPURenderer-Ce0-U9Q1.js +95 -0
  20. package/dist/renderer/assets/{browserAll-aHn2isHo.js → browserAll-DhvWQ7nM.js} +2 -2
  21. package/dist/renderer/assets/canvasUtils-KRroregW.js +1 -0
  22. package/dist/renderer/assets/{getTexelRangeRects-yD6MQ0xy.js → getTexelRangeRects-D3pwCyRt.js} +3 -3
  23. package/dist/renderer/assets/index-CE-lli1m.js +556 -0
  24. package/dist/renderer/assets/init-DfmWKarH.js +83 -0
  25. package/dist/renderer/assets/webworkerAll-B41hok0-.js +1 -0
  26. package/dist/renderer/index.html +1 -6
  27. package/dist/scene.d.ts +24 -4
  28. package/dist/scene.js +74 -5
  29. package/dist/types.d.ts +4 -0
  30. package/package.json +1 -1
  31. package/dist/renderer/assets/CanvasPool-CHSHS1-v.js +0 -23
  32. package/dist/renderer/assets/RenderTargetSystem-EAUH9iQk.js +0 -404
  33. package/dist/renderer/assets/canvasUtils-n5g2f3_X.js +0 -1
  34. package/dist/renderer/assets/getTextureBatchBindGroup-Bwvgbco6.js +0 -1
  35. package/dist/renderer/assets/index-BwP6rH7I.js +0 -556
  36. package/dist/renderer/assets/init-C2Za5NQh.js +0 -83
  37. package/dist/renderer/assets/webworkerAll-JSSmbaR2.js +0 -1
@@ -19,7 +19,7 @@ are listed in `vendor/openscreen/VENDORED.md` in the demoreel repository.
19
19
  | eventemitter3 | 5.0.4 | MIT | [licenses/eventemitter3.txt](licenses/eventemitter3.txt) | git://github.com/primus/eventemitter3 |
20
20
  | gif.js | 0.2.0 | MIT | [licenses/gif.js.txt](licenses/gif.js.txt) | https://github.com/jnordberg/gif.js |
21
21
  | ismobilejs | 1.1.1 | MIT | [licenses/ismobilejs.txt](licenses/ismobilejs.txt) | https://github.com/kaimallea/isMobile |
22
- | mediabunny | 1.66.2 | MPL-2.0 | [licenses/mediabunny.txt](licenses/mediabunny.txt) | https://github.com/Vanilagy/mediabunny |
22
+ | mediabunny | 1.66.5 | MPL-2.0 | [licenses/mediabunny.txt](licenses/mediabunny.txt) | https://github.com/Vanilagy/mediabunny |
23
23
  | motion-dom | 12.43.0 | MIT | [licenses/motion-dom.txt](licenses/motion-dom.txt) | https://github.com/motiondivision/motion |
24
24
  | motion-utils | 12.39.0 | MIT | [licenses/motion-utils.txt](licenses/motion-utils.txt) | https://github.com/motiondivision/motion |
25
25
  | parse-svg-path | 0.2.0 | MIT | [licenses/parse-svg-path.txt](licenses/parse-svg-path.txt) | git://github.com/jkroso/parse-svg-path |
package/dist/args.js CHANGED
@@ -14,6 +14,7 @@ export const COMMANDS = {
14
14
  flags: {
15
15
  out: { type: "string", alias: "o", value: "DIR", description: "output directory (default out/<name>)" },
16
16
  render: { type: "boolean", description: "render the MP4 (default; --no-render to only record)" },
17
+ gif: { type: "boolean", description: "also export a palette-optimised GIF next to the MP4" },
17
18
  sheet: { type: "boolean", description: "write a contact sheet after rendering (default)" },
18
19
  gpu,
19
20
  fps,
@@ -53,6 +54,7 @@ export const COMMANDS = {
53
54
  "auto-zoom": { type: "boolean", description: "automatic zooms (--no-auto-zoom: only scene.zoom())" },
54
55
  "trim-idle": trimIdle,
55
56
  "idle-options": { type: "string", value: "JSON", description: 'e.g. \'{"minMs":1500,"keepMs":800,"mode":"speed"}\'' },
57
+ "show-keys": { type: "boolean", description: "toggle keycap HUD overlays for scene.press() shortcuts" },
56
58
  render: { type: "boolean", description: "render the MP4 afterwards" },
57
59
  gpu,
58
60
  fps,
@@ -77,6 +79,16 @@ export const COMMANDS = {
77
79
  framesheet,
78
80
  },
79
81
  },
82
+ gif: {
83
+ usage: "gif <video.mp4|outdir>",
84
+ description: "export a palette-optimised GIF from a rendered MP4 (for READMEs and docs)",
85
+ positionals: { min: 1, max: 1 },
86
+ flags: {
87
+ out: { type: "string", alias: "o", value: "FILE", description: "output GIF path (default: next to the MP4)" },
88
+ fps: { type: "number", value: "N", description: "GIF frame rate (default 12)" },
89
+ width: { type: "number", value: "PX", description: "GIF width in px, height auto (default 960; 0 = source)" },
90
+ },
91
+ },
80
92
  inspect: {
81
93
  usage: "inspect <url|scenario.ts|js>",
82
94
  description: "print a page's ARIA snapshot (or dry-run a scenario and inspect its end state)",
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
6
6
  import { COMMANDS, gpuMode, helpText, parseArgs, parseJsonFlag, parseSize, UsageError } from "./args.js";
7
7
  import { readTimeline, rezoom } from "./compose.js";
8
8
  import { checkFfmpeg, DemoreelError, detectGpu, launchChromium } from "./env.js";
9
+ import { exportGif } from "./gif.js";
9
10
  import { initProject } from "./init.js";
10
11
  import { loadScenario } from "./load.js";
11
12
  import { PACKAGE_ROOT } from "./openscreen.js";
@@ -104,11 +105,16 @@ async function cmdRun({ positionals, flags }) {
104
105
  const r = await renderProject({
105
106
  projectPath: rec.projectPath,
106
107
  outputPath: mp4,
108
+ cursor: scenario.cursor,
107
109
  ...renderFlags(flags),
108
110
  log,
109
111
  onProgress: progressPrinter(true),
110
112
  });
111
113
  printRender(r);
114
+ if (flags.gif) {
115
+ const g = await exportGif(mp4);
116
+ log(` gif: ${g.outputPath} (${(g.bytes / 1e6).toFixed(1)} MB, ${g.width}px @ ${g.fps}fps)`);
117
+ }
112
118
  if (flags.sheet === false)
113
119
  return;
114
120
  const sheet = await reviewSheet(mp4, {
@@ -147,12 +153,19 @@ async function cmdRezoom({ positionals, flags }) {
147
153
  zoom.auto = Boolean(flags["auto-zoom"]);
148
154
  const idle = parseJsonFlag("idle-options", flags["idle-options"]);
149
155
  const trimIdle = flags["trim-idle"] === false ? false : flags["trim-idle"] || Object.keys(idle).length ? { ...idle } : undefined;
150
- const res = rezoom(dir, { zoom, trimIdle });
156
+ const look = flags["show-keys"] !== undefined ? { showKeys: Boolean(flags["show-keys"]) } : undefined;
157
+ const res = rezoom(dir, { zoom, trimIdle, look });
151
158
  const t = res.timeline;
152
159
  log(`rezoomed ${t.scenario}: ${t.zoomRegions.length} zoom regions, ${t.trimRegions.length} trims, ${t.speedRegions.length} speed regions; output ${fmt(t.outputDurationMs)}`);
153
160
  console.log(JSON.stringify({ zoomRegions: t.zoomRegions, trimRegions: t.trimRegions, speedRegions: t.speedRegions }, null, 1));
154
161
  if (flags.render) {
155
- const r = await renderProject({ projectPath: res.projectPath, ...renderFlags(flags), log, onProgress: progressPrinter(true) });
162
+ const r = await renderProject({
163
+ projectPath: res.projectPath,
164
+ cursor: t.options?.cursor,
165
+ ...renderFlags(flags),
166
+ log,
167
+ onProgress: progressPrinter(true),
168
+ });
156
169
  printRender(r);
157
170
  }
158
171
  }
@@ -195,6 +208,21 @@ async function cmdSheet({ positionals, flags }) {
195
208
  if (sheet.report)
196
209
  console.log(sheet.report);
197
210
  }
211
+ async function cmdGif({ positionals, flags }) {
212
+ let target = path.resolve(positionals[0]);
213
+ if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
214
+ const tl = readTimeline(target);
215
+ target = path.join(target, tl.files?.video ?? `${tl.scenario}.mp4`);
216
+ }
217
+ if (!fs.existsSync(target))
218
+ throw new DemoreelError(`video not found: ${target}`, "render it first: demoreel render <project>");
219
+ const g = await exportGif(target, flags.out ? path.resolve(String(flags.out)) : undefined, {
220
+ fps: flags.fps !== undefined ? Number(flags.fps) : undefined,
221
+ width: flags.width !== undefined ? Number(flags.width) : undefined,
222
+ });
223
+ log(`gif: ${g.outputPath} (${(g.bytes / 1e6).toFixed(1)} MB, ${g.width || "source"}px @ ${g.fps}fps)`);
224
+ console.log(g.outputPath);
225
+ }
198
226
  async function cmdLogin({ positionals, flags }) {
199
227
  const url = positionals[0];
200
228
  const statePath = path.resolve(String(flags.state ?? path.join(".demoreel", "auth.json")));
@@ -432,6 +460,7 @@ export async function main(argv = process.argv.slice(2)) {
432
460
  rezoom: cmdRezoom,
433
461
  validate: cmdValidate,
434
462
  sheet: cmdSheet,
463
+ gif: cmdGif,
435
464
  inspect: cmdInspect,
436
465
  login: cmdLogin,
437
466
  init: cmdInit,
package/dist/compose.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type IdleOptions } from "./idle.ts";
2
2
  import { type Marks } from "./marks.ts";
3
3
  import { buildProject, type LookOptions } from "./project.ts";
4
+ import type { CursorStyle } from "./render.ts";
4
5
  import type { ActionRecord, Caption, CursorSample, SpeedRegion, TrimRegion, Viewport, ZoomRegion } from "./types.ts";
5
6
  import { type ZoomOptions } from "./zoom.ts";
6
7
  export declare const TIMELINE_VERSION = 1;
@@ -19,6 +20,7 @@ export interface Timeline {
19
20
  zoom: Partial<ZoomOptions>;
20
21
  look: Partial<LookOptions>;
21
22
  trimIdle: Partial<IdleOptions> | false;
23
+ cursor?: CursorStyle;
22
24
  };
23
25
  actions: ActionRecord[];
24
26
  zoomRegions: ZoomRegion[];
@@ -52,6 +54,7 @@ export interface ComposeInput {
52
54
  zoom?: Partial<ZoomOptions>;
53
55
  look?: Partial<LookOptions>;
54
56
  trimIdle?: Partial<IdleOptions> | boolean;
57
+ cursor?: CursorStyle;
55
58
  }
56
59
  export interface ComposeResult {
57
60
  timeline: Timeline;
@@ -70,4 +73,5 @@ export declare function rezoom(dir: string, overrides?: {
70
73
  zoom?: Partial<ZoomOptions>;
71
74
  trimIdle?: Partial<IdleOptions> | boolean;
72
75
  look?: Partial<LookOptions>;
76
+ cursor?: CursorStyle;
73
77
  }): ComposeResult;
package/dist/compose.js CHANGED
@@ -32,6 +32,7 @@ export function compose(input, opts = {}) {
32
32
  videoPath: input.videoPath,
33
33
  zoomRegions,
34
34
  captions,
35
+ actions: input.actions,
35
36
  trimRegions,
36
37
  speedRegions,
37
38
  look,
@@ -73,6 +74,7 @@ export function compose(input, opts = {}) {
73
74
  zoom: input.zoom ?? {},
74
75
  look: input.look ?? {},
75
76
  trimIdle: idleOpts ?? false,
77
+ ...(input.cursor ? { cursor: input.cursor } : {}),
76
78
  },
77
79
  actions: input.actions.map(roundAction),
78
80
  zoomRegions,
@@ -124,6 +126,7 @@ export function rezoom(dir, overrides = {}) {
124
126
  ? { ...(tl.options?.trimIdle || {}) }
125
127
  : overrides.trimIdle;
126
128
  const projectPath = path.join(dir, `${tl.scenario}.openscreen`);
129
+ const cursor = overrides.cursor ?? tl.options?.cursor;
127
130
  return compose({
128
131
  name: tl.scenario,
129
132
  outDir: dir,
@@ -140,5 +143,6 @@ export function rezoom(dir, overrides = {}) {
140
143
  zoom: { ...tl.options?.zoom, ...overrides.zoom },
141
144
  look: { ...tl.options?.look, ...overrides.look },
142
145
  trimIdle: trimIdle ?? false,
146
+ cursor,
143
147
  }, { keepProjectFrom: overrides.look ? undefined : projectPath });
144
148
  }
package/dist/gif.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export interface GifOptions {
2
+ /** Output frame rate (default 12). */
3
+ fps?: number;
4
+ /** Output width in px, height preserves aspect ratio (default 960; 0 keeps source width). */
5
+ width?: number;
6
+ /** Loop count: 0 = infinite (default), -1 = no loop, N = loop N times. */
7
+ loop?: number;
8
+ }
9
+ export interface GifResult {
10
+ outputPath: string;
11
+ bytes: number;
12
+ fps: number;
13
+ width: number;
14
+ }
15
+ /** Converts an MP4 video into a crisp palette-optimised GIF suitable for READMEs and docs. */
16
+ export declare function exportGif(videoPath: string, outPath?: string, opts?: GifOptions): Promise<GifResult>;
package/dist/gif.js ADDED
@@ -0,0 +1,19 @@
1
+ /** Two-pass palette-optimised GIF export from a rendered MP4 via ffmpeg. */
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { checkFfmpeg, ffmpegBin, run } from "./env.js";
5
+ /** Converts an MP4 video into a crisp palette-optimised GIF suitable for READMEs and docs. */
6
+ export async function exportGif(videoPath, outPath, opts = {}) {
7
+ checkFfmpeg();
8
+ const src = path.resolve(videoPath);
9
+ const dst = path.resolve(outPath ?? src.replace(/\.\w+$/, ".gif"));
10
+ const fps = Math.max(1, Math.min(30, Math.round(opts.fps ?? 12)));
11
+ const width = opts.width === 0 ? 0 : Math.max(120, Math.round(opts.width ?? 960));
12
+ const loop = opts.loop ?? 0;
13
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
14
+ const scale = width > 0 ? `,scale=${width}:-2:flags=lanczos` : "";
15
+ const filter = `fps=${fps}${scale},split[s0][s1];[s0]palettegen=stats_mode=diff[p];[s1][p]paletteuse=dither=bayer:bayer_scale=3`;
16
+ await run(ffmpegBin(), ["-y", "-loglevel", "error", "-i", src, "-vf", filter, "-loop", String(loop), dst]);
17
+ const { size } = fs.statSync(dst);
18
+ return { outputPath: dst, bytes: size, fps, width };
19
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  /** demoreel: scripted product demo videos (videos as code), rendered by OpenScreen's exporter. */
2
2
  export { type DryRunError, type DryRunOptions, type DryRunResult, type RecordOptions, type RecordResult, type Scenario, type ScenarioContext, defineScenario, dryRunScenario, recordScenario, resolveStorageState, } from "./record.ts";
3
- export { type ActionOptions, applyZoomAnchor, DEFAULT_PACING, describeTarget, type HighlightOptions, type PacingOptions, resolveTarget, Scene, type SceneClock, type Target, type TargetSpec, ZOOM_ATTRIBUTE, type ZoomOptions as SceneZoomOptions, } from "./scene.ts";
3
+ export { type ActionOptions, applyZoomAnchor, type ClickRippleOptions, DEFAULT_PACING, describeTarget, type HighlightOptions, type PacingOptions, type PressOptions, resolveTarget, Scene, type SceneClock, type Target, type TargetSpec, ZOOM_ATTRIBUTE, type ZoomOptions as SceneZoomOptions, } from "./scene.ts";
4
4
  export { DEFAULT_ZOOM_OPTIONS, DEPTH_SCALES, deriveZoomRegions, depthForBox, normalizeDepth, type ZoomOptions } from "./zoom.ts";
5
5
  export { DEFAULT_IDLE_OPTIONS, deriveIdleRegions, idleIntervals, type IdleOptions, sourceToOutputMs } from "./idle.ts";
6
- export { buildCursorData, buildProject, type BuildProjectOptions, captionAnnotations, DEFAULT_LOOK, type LookOptions, normalizeSamples, type OpenScreenProject, writeProject, } from "./project.ts";
6
+ export { buildCursorData, buildProject, type BuildProjectOptions, captionAnnotations, DEFAULT_LOOK, formatKeycap, keycapAnnotations, type KeyHudOptions, type KeyHudPosition, keycapRect, type LookOptions, normalizeSamples, type OpenScreenProject, writeProject, } from "./project.ts";
7
+ export { exportGif, type GifOptions, type GifResult } from "./gif.ts";
7
8
  export { buildMarks, type Marks, type MarkPoint, type MarkRegion, type MarkSpan, type MarksInput } from "./marks.ts";
8
9
  export { stageLayout, type StageLayout } from "./layout.ts";
9
10
  export { compose, rezoom, readTimeline, type Timeline, TIMELINE_VERSION } from "./compose.ts";
package/dist/index.js CHANGED
@@ -3,7 +3,8 @@ export { defineScenario, dryRunScenario, recordScenario, resolveStorageState, }
3
3
  export { applyZoomAnchor, DEFAULT_PACING, describeTarget, resolveTarget, Scene, ZOOM_ATTRIBUTE, } from "./scene.js";
4
4
  export { DEFAULT_ZOOM_OPTIONS, DEPTH_SCALES, deriveZoomRegions, depthForBox, normalizeDepth } from "./zoom.js";
5
5
  export { DEFAULT_IDLE_OPTIONS, deriveIdleRegions, idleIntervals, sourceToOutputMs } from "./idle.js";
6
- export { buildCursorData, buildProject, captionAnnotations, DEFAULT_LOOK, normalizeSamples, writeProject, } from "./project.js";
6
+ export { buildCursorData, buildProject, captionAnnotations, DEFAULT_LOOK, formatKeycap, keycapAnnotations, keycapRect, normalizeSamples, writeProject, } from "./project.js";
7
+ export { exportGif } from "./gif.js";
7
8
  export { buildMarks } from "./marks.js";
8
9
  export { stageLayout } from "./layout.js";
9
10
  export { compose, rezoom, readTimeline, TIMELINE_VERSION } from "./compose.js";
@@ -548,9 +548,9 @@ function getAspectRatioValue(aspectRatio) {
548
548
  case "9:16": return 9 / 16;
549
549
  case "1:1": return 1;
550
550
  case "4:3": return 4 / 3;
551
- case "4:5": return 4 / 5;
552
- case "16:10": return 16 / 10;
553
- case "10:16": return 10 / 16;
551
+ case "4:5": return .8;
552
+ case "16:10": return 1.6;
553
+ case "10:16": return .625;
554
554
  case "native": return NATIVE_ASPECT_RATIO_FALLBACK;
555
555
  default: return aspectRatio;
556
556
  }
package/dist/project.d.ts CHANGED
@@ -1,6 +1,15 @@
1
- import type { Caption, CursorSample, SpeedRegion, TrimRegion, ZoomRegion } from "./types.ts";
1
+ import type { ActionRecord, Caption, CursorSample, SpeedRegion, TrimRegion, ZoomRegion } from "./types.ts";
2
2
  export declare const PROJECT_VERSION = 2;
3
3
  export declare const CURSOR_TELEMETRY_VERSION = 2;
4
+ export type KeyHudPosition = "bottom-right" | "top-right" | "bottom-left" | "top-left";
5
+ export interface KeyHudOptions {
6
+ /** Corner where shortcut keycap badges appear (default "bottom-right"). */
7
+ position?: KeyHudPosition;
8
+ /** How long each keycap stays visible (ms, default 1100). */
9
+ durationMs?: number;
10
+ /** Font size in px (default 24). */
11
+ fontSize?: number;
12
+ }
4
13
  export interface LookOptions {
5
14
  /** Wallpaper: "#hex", CSS gradient, or one of OpenScreen's "/wallpapers/wallpaperN.jpg". */
6
15
  wallpaper: string;
@@ -14,6 +23,8 @@ export interface LookOptions {
14
23
  /** Where captions sit; "auto" (default) = bottom, unless that covers an active target. */
15
24
  captionPosition: "auto" | "bottom" | "top";
16
25
  captionFontSize: number;
26
+ /** Show floating keycap pills for `scene.press()` shortcuts (default false). */
27
+ showKeys?: boolean | KeyHudOptions;
17
28
  }
18
29
  export declare const DEFAULT_LOOK: LookOptions;
19
30
  /** Caption box in percent of the output canvas (OpenScreen annotation position/size). */
@@ -23,6 +34,44 @@ export declare function captionRect(position: LookOptions["captionPosition"] | u
23
34
  width: number;
24
35
  height: number;
25
36
  };
37
+ /** Formats a Playwright key chord (e.g. "Control+Shift+K") into a compact keycap label ("Ctrl + ⇧ + K"). */
38
+ export declare function formatKeycap(key: string): string;
39
+ /** Keycap HUD box in percent of the output canvas (sits clear of top/bottom captions). */
40
+ export declare function keycapRect(position?: KeyHudPosition, text?: string): {
41
+ x: number;
42
+ y: number;
43
+ width: number;
44
+ height: number;
45
+ };
46
+ /** Builds OpenScreen text annotations for `scene.press()` actions when enabled globally or per-action. */
47
+ export declare function keycapAnnotations(actions: ActionRecord[], look?: LookOptions, startZIndex?: number): {
48
+ id: string;
49
+ startMs: number;
50
+ endMs: number;
51
+ type: string;
52
+ content: string;
53
+ textContent: string;
54
+ position: {
55
+ x: number;
56
+ y: number;
57
+ };
58
+ size: {
59
+ width: number;
60
+ height: number;
61
+ };
62
+ style: {
63
+ color: string;
64
+ backgroundColor: string;
65
+ fontSize: number;
66
+ fontFamily: string;
67
+ fontWeight: string;
68
+ fontStyle: string;
69
+ textDecoration: string;
70
+ textAlign: string;
71
+ textAnimation: string;
72
+ };
73
+ zIndex: number;
74
+ }[];
26
75
  export declare function captionAnnotations(captions: Caption[], look?: LookOptions): {
27
76
  id: string;
28
77
  startMs: number;
@@ -55,6 +104,7 @@ export interface BuildProjectOptions {
55
104
  videoPath: string;
56
105
  zoomRegions: ZoomRegion[];
57
106
  captions: Caption[];
107
+ actions?: ActionRecord[];
58
108
  trimRegions?: TrimRegion[];
59
109
  speedRegions?: SpeedRegion[];
60
110
  look?: Partial<LookOptions>;
package/dist/project.js CHANGED
@@ -16,11 +16,97 @@ export const DEFAULT_LOOK = {
16
16
  aspectRatio: "16:9",
17
17
  captionPosition: "auto",
18
18
  captionFontSize: 30,
19
+ showKeys: false,
19
20
  };
20
21
  /** Caption box in percent of the output canvas (OpenScreen annotation position/size). */
21
22
  export function captionRect(position) {
22
23
  return { x: 15, y: position === "top" ? 3.5 : 88.5, width: 70, height: 8 };
23
24
  }
25
+ const KEY_LABELS = {
26
+ meta: "⌘",
27
+ cmd: "⌘",
28
+ command: "⌘",
29
+ control: "Ctrl",
30
+ ctrl: "Ctrl",
31
+ controlormeta: "⌘",
32
+ shift: "⇧",
33
+ alt: "Alt",
34
+ option: "⌥",
35
+ enter: "↵",
36
+ return: "↵",
37
+ escape: "Esc",
38
+ esc: "Esc",
39
+ backspace: "⌫",
40
+ delete: "Del",
41
+ tab: "⇥",
42
+ space: "Space",
43
+ " ": "Space",
44
+ arrowup: "↑",
45
+ arrowdown: "↓",
46
+ arrowleft: "←",
47
+ arrowright: "→",
48
+ };
49
+ /** Formats a Playwright key chord (e.g. "Control+Shift+K") into a compact keycap label ("Ctrl + ⇧ + K"). */
50
+ export function formatKeycap(key) {
51
+ return key
52
+ .split("+")
53
+ .map((part) => {
54
+ const trimmed = part.trim();
55
+ const mapped = KEY_LABELS[trimmed.toLowerCase()];
56
+ if (mapped)
57
+ return mapped;
58
+ return trimmed.length === 1 ? trimmed.toUpperCase() : trimmed;
59
+ })
60
+ .filter(Boolean)
61
+ .join(" + ");
62
+ }
63
+ /** Keycap HUD box in percent of the output canvas (sits clear of top/bottom captions). */
64
+ export function keycapRect(position = "bottom-right", text = "") {
65
+ const width = Math.min(34, Math.max(12, 8 + text.length * 1.5));
66
+ const height = 6.5;
67
+ const x = position.endsWith("left") ? 4 : 95 - width;
68
+ const y = position.startsWith("top") ? 13 : 77.5;
69
+ return { x: Math.round(x * 10) / 10, y, width: Math.round(width * 10) / 10, height };
70
+ }
71
+ /** Builds OpenScreen text annotations for `scene.press()` actions when enabled globally or per-action. */
72
+ export function keycapAnnotations(actions, look = DEFAULT_LOOK, startZIndex = 1) {
73
+ const globalOn = Boolean(look.showKeys);
74
+ const opts = typeof look.showKeys === "object" && look.showKeys ? look.showKeys : {};
75
+ const position = opts.position ?? "bottom-right";
76
+ const defaultDur = opts.durationMs ?? 1100;
77
+ const fontSize = opts.fontSize ?? 24;
78
+ const presses = actions.filter((a) => a.kind === "press" && (a.showKey ?? globalOn) && (a.text ?? a.label));
79
+ return presses.map((a, i) => {
80
+ const raw = a.text ?? a.label ?? "";
81
+ const text = formatKeycap(raw);
82
+ const r = keycapRect(position, text);
83
+ const nextStart = presses[i + 1]?.startMs;
84
+ const desiredEnd = a.startMs + (a.keyDurationMs ?? defaultDur);
85
+ const endMs = nextStart !== undefined ? Math.max(a.startMs + 250, Math.min(desiredEnd, nextStart - 60)) : desiredEnd;
86
+ return {
87
+ id: `keycap-${i + 1}`,
88
+ startMs: Math.round(a.startMs),
89
+ endMs: Math.round(endMs),
90
+ type: "text",
91
+ content: text,
92
+ textContent: text,
93
+ position: { x: r.x, y: r.y },
94
+ size: { width: r.width, height: r.height },
95
+ style: {
96
+ color: "#f8fafc",
97
+ backgroundColor: "rgba(15, 18, 32, 0.88)",
98
+ fontSize,
99
+ fontFamily: "'JetBrains Mono', ui-monospace, 'DejaVu Sans Mono', monospace",
100
+ fontWeight: "bold",
101
+ fontStyle: "normal",
102
+ textDecoration: "none",
103
+ textAlign: "center",
104
+ textAnimation: "none",
105
+ },
106
+ zIndex: startZIndex + i,
107
+ };
108
+ });
109
+ }
24
110
  export function captionAnnotations(captions, look = DEFAULT_LOOK) {
25
111
  return captions.map((c, i) => {
26
112
  const r = captionRect(c.position ?? look.captionPosition);
@@ -51,6 +137,8 @@ export function captionAnnotations(captions, look = DEFAULT_LOOK) {
51
137
  export function buildProject(opts) {
52
138
  const look = { ...DEFAULT_LOOK, ...opts.look };
53
139
  const videoPath = path.resolve(opts.videoPath);
140
+ const captions = captionAnnotations(opts.captions, look);
141
+ const keycaps = keycapAnnotations(opts.actions ?? [], look, captions.length + 1);
54
142
  return {
55
143
  version: PROJECT_VERSION,
56
144
  // Legacy field: OpenScreen <= 1.2 (v1 projects) only reads `videoPath`; >= 1.3 prefers `media`.
@@ -73,7 +161,7 @@ export function buildProject(opts) {
73
161
  autoFocusAll: false,
74
162
  trimRegions: opts.trimRegions ?? [],
75
163
  speedRegions: opts.speedRegions ?? [],
76
- annotationRegions: captionAnnotations(opts.captions, look),
164
+ annotationRegions: [...captions, ...keycaps],
77
165
  aspectRatio: look.aspectRatio,
78
166
  webcamLayoutPreset: "picture-in-picture",
79
167
  webcamMaskShape: "rectangle",
package/dist/record.d.ts CHANGED
@@ -2,7 +2,8 @@ import type { Page } from "playwright";
2
2
  import { type ComposeResult } from "./compose.ts";
3
3
  import type { IdleOptions } from "./idle.ts";
4
4
  import type { LookOptions } from "./project.ts";
5
- import { type PacingOptions, Scene } from "./scene.ts";
5
+ import type { CursorStyle } from "./render.ts";
6
+ import { type ClickRippleOptions, type PacingOptions, Scene } from "./scene.ts";
6
7
  import type { ActionRecord, RecordingResult, Viewport } from "./types.ts";
7
8
  import type { ZoomOptions } from "./zoom.ts";
8
9
  export interface ScenarioContext {
@@ -31,6 +32,10 @@ export interface Scenario {
31
32
  pacing?: Partial<PacingOptions>;
32
33
  zoom?: Partial<ZoomOptions>;
33
34
  look?: Partial<LookOptions>;
35
+ /** Optional OpenScreen cursor styling (size, clickBounce, smoothing, motionBlur, show). */
36
+ cursor?: CursorStyle;
37
+ /** Draw an expanding translucent ring at each click (default false). */
38
+ clickRipple?: boolean | ClickRippleOptions;
34
39
  /** Cut (or speed up) idle stretches with OpenScreen trim/speed regions. */
35
40
  trimIdle?: boolean | Partial<IdleOptions>;
36
41
  run(scene: Scene, ctx: ScenarioContext): Promise<void>;
package/dist/record.js CHANGED
@@ -92,7 +92,7 @@ export async function recordScenario(input, opts = {}) {
92
92
  });
93
93
  await recorder.start();
94
94
  return recorder;
95
- }, { seed: session.scenario.seed, pacing: session.scenario.pacing });
95
+ }, { seed: session.scenario.seed, pacing: session.scenario.pacing, clickRipple: session.scenario.clickRipple });
96
96
  const tRun = Date.now();
97
97
  await session.scenario.run(scene, { baseUrl: session.baseUrl });
98
98
  // Hold the last frame so the final zoom-out and captions finish.
@@ -134,6 +134,7 @@ export async function recordScenario(input, opts = {}) {
134
134
  zoom: session.scenario.zoom,
135
135
  look: session.scenario.look,
136
136
  trimIdle: session.scenario.trimIdle,
137
+ cursor: session.scenario.cursor,
137
138
  });
138
139
  const result = {
139
140
  videoPath,
@@ -0,0 +1 @@
1
+ import{Q as e,_t as t,ct as n,ht as r,mt as i,q as a,st as o,yt as s}from"./index-CE-lli1m.js";var c=32767;function l(e,t){return(e<<17)+(t<<2)}var u=new class{constructor(t){this._buckets=new Map,this._screens=new e,this._enableFullScreen=!1,this.canvasOptions=t||{}}get enableFullScreen(){return t(s,`CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize.`),this._enableFullScreen}set enableFullScreen(e){t(s,`CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize.`),this._enableFullScreen=e}_createCanvasAndContext(e,t){let n=a.get().createCanvas();return n.width=e,n.height=t,{canvas:n,context:n.getContext(`2d`)}}getOptimalCanvasAndContext(e,t,r=1){let{width:i,height:a}=this.getOptimalSize(e,t,r);(i>c||a>c)&&n(`CanvasPool: ${i}x${a} is larger than the ${c}px pool key limit, canvases of this size may be pooled together`);let o=l(i,a),s=this._buckets.get(o);s||(s=[],this._buckets.set(o,s));let u=s.pop();return u||=this._createCanvasAndContext(i,a),u}getOptimalSize(e,t,n=1){let i=Math.ceil(e*n-1e-6),a=Math.ceil(t*n-1e-6),o=r(i),s=this._screens.getFittingWidth(i),c=r(a),l=this._screens.getFittingHeight(a);return{width:s===void 0?o:Math.min(s,o),height:l===void 0?c:Math.min(l,c)}}returnCanvasAndContext(e){let{width:t,height:n}=e.canvas,r=this._buckets.get(l(t,n));r&&(e.context.resetTransform(),e.context.clearRect(0,0,t,n),r.push(e))}setScreenSize(e,t,n){this._screens.set(e,t,n)&&this._pruneScreenCanvases()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenCanvases()}clear(){this._buckets.clear()}_pruneScreenCanvases(){for(let[e]of this._buckets){let t=e>>>17,n=e>>>2&32767;(!i(t)&&!this._screens.hasWidth(t)||!i(n)&&!this._screens.hasHeight(n))&&this._buckets.delete(e)}}};o.register(u);export{u as t};
@@ -0,0 +1 @@
1
+ import{Ct as e,Dt as t,Et as n,K as r,L as i,O as a,St as o,a as s,ct as c,dt as l,et as u,i as d,lt as f,nt as p,o as m,q as h,r as g,s as _,t as v}from"./index-CE-lli1m.js";import{a as y,c as b,i as x,l as S,o as C,r as w,s as T,t as E}from"./RenderTargetSystem-Dk1U4wDJ.js";import{n as D,t as O}from"./canvasUtils-KRroregW.js";var k=class e{static _getPatternRepeat(e,t){let n=e&&e!==`clamp-to-edge`,r=t&&t!==`clamp-to-edge`;return n&&r?`repeat`:n?`repeat-x`:r?`repeat-y`:`no-repeat`}start(e,t,n){}execute(t,n){let r=n.elements;if(!r||!r.length)return;let i=t.renderer,a=i.canvasContext,s=a.activeContext;for(let t=0;t<r.length;t++){let c=r[t];if(!c.packAsQuad)continue;let l=c,d=l.texture,f=d?O.getCanvasSource(d):null;if(!f)continue;let m=d.source.style,h=a.smoothProperty,g=m.scaleMode!==`nearest`;s[h]!==g&&(s[h]=g),a.setBlendMode(n.blendMode);let _=i.globalUniforms.globalUniformData?.worldColor??0xffffffff,v=l.color,y=(_>>>24&255)/255,b=(v>>>24&255)/255,x=i.filter?.alphaMultiplier??1,S=y*b*x;if(S<=0)continue;s.globalAlpha=S;let C=_&0xffffff,w=v&0xffffff,T=u(p(w,C)),E=d.frame,D=m.addressModeU??m.addressMode,k=m.addressModeV??m.addressMode,A=e._getPatternRepeat(D,k),j=d.source._resolution??d.source.resolution??1,M=l.renderable?.renderGroup?.isCachedAsTexture,N=E.x*j,P=E.y*j,F=E.width*j,I=E.height*j,L=l.bounds,R=i.renderTarget.renderTarget.isRoot,z=L.minX,B=L.minY,V=L.maxX-L.minX,H=L.maxY-L.minY,U=d.rotate,W=d.uvs,G=Math.min(W.x0,W.x1,W.x2,W.x3,W.y0,W.y1,W.y2,W.y3),K=Math.max(W.x0,W.x1,W.x2,W.x3,W.y0,W.y1,W.y2,W.y3),q=A!==`no-repeat`&&(G<0||K>1),J=U&&(!!q||T===0xffffff&&!U);J?(e._tempPatternMatrix.copyFrom(l.transform),o.matrixAppendRotationInv(e._tempPatternMatrix,U,z,B,V,H),a.setContextTransform(e._tempPatternMatrix,l.roundPixels===1,void 0,M&&R)):a.setContextTransform(l.transform,l.roundPixels===1,void 0,M&&R);let Y=V,X=H,Z=J?0:z,Q=J?0:B;if(!J&&l.roundPixels===1&&(Z|=0,Q|=0),q){let t=f,n=T!==0xffffff&&!U,r=E.width<=d.source.width&&E.height<=d.source.height;n&&r&&(t=O.getTintedCanvas({texture:d},T));let i=s.createPattern(t,A);if(!i)continue;let a=Y,o=X;if(a===0||o===0)continue;let c=1/a,l=1/o,u=(W.x1-W.x0)*c,p=(W.y1-W.y0)*c,m=(W.x3-W.x0)*l,h=(W.y3-W.y0)*l,g=W.x0-u*Z-m*Q,_=W.y0-p*Z-h*Q,v=d.source.pixelWidth,y=d.source.pixelHeight;e._tempPatternMatrix.set(u*v,p*y,m*v,h*y,g*v,_*y),O.applyPatternTransform(i,e._tempPatternMatrix),s.fillStyle=i,s.fillRect(Z,Q,Y,X)}else{let e=T!==0xffffff||U?O.getTintedCanvas({texture:d},T):f,t=e!==f;s.drawImage(e,t?0:N,t?0:P,t?e.width:F,t?e.height:I,Z,Q,Y,X)}}}};k._tempPatternMatrix=new e,k.extension={type:[n.CanvasPipesAdaptor],name:`batch`};var A=k,j=class{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;let i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;this._colorStackIndex--;let i=r[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}};j.extension={type:[n.CanvasPipes],name:`colorMask`};function M(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function N(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;M(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.moveTo(n.x+n.radius,n.y),e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?(e.moveTo(n.x+n.halfWidth,n.y),e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2)):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.moveTo(1,0),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function P(e,t,n){let r=[],i=[],a=[];if(!d[t.type]?.build(t,r))return!1;let o=t.closePath??!0;_(r,n,!1,o,i,a);for(let t=0;t<a.length;t+=3){let n=a[t]*2,r=a[t+1]*2,o=a[t+2]*2;e.moveTo(i[n],i[n+1]),e.lineTo(i[r],i[r+1]),e.lineTo(i[o],i[o+1]),e.closePath()}return!0}function F(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),N(e,r.shape),a&&e.restore()}return!0}var I=class{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`popMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!==`pushMaskBegin`&&e.action!==`popMaskEnd`)return;let t=this._renderer,n=t.canvasContext,r=n?.activeContext;if(!r)return;if(e.action===`popMaskEnd`){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce(`inverse`,`CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.`);let i=e.mask.mask;if(!(i instanceof v)){this._warnOnce(`nonGraphics`,`CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask.`),this._canvasMaskStack.push(!1);return}let a=i,o=a.context?.instructions;if(!o?.length){this._canvasMaskStack.push(!1);return}r.save(),n.setContextTransform(a.groupTransform,(t._roundPixels|a._roundPixels)===1),r.beginPath();let s=!1,c=!1;for(let e=0;e<o.length;e++){let t=o[e],n=t.action;if(n!==`fill`&&n!==`stroke`)continue;let i=t.data,a=i?.path?.shapePath;if(!a?.shapePrimitives?.length)continue;let l=n===`stroke`,u=a.shapePrimitives;for(let e=0;e<u.length;e++){let t=u[e];if(!t?.shape)continue;let n=t.transform,a=n&&!n.isIdentity();a&&(r.save(),r.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),l&&i.style?s=P(r,t.shape,i.style)||s:(N(r,t.shape),c=F(r,t.holes)||c,s=!0),a&&r.restore()}}s?(c?r.clip(`evenodd`):r.clip(),this._canvasMaskStack.push(!0)):(r.restore(),this._canvasMaskStack.push(!1))}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),c(t))}};I.extension={type:[n.CanvasPipes],name:`stencilMask`};var L=`source-over`;function R(){let e=D(),t=Object.create(null);return t.inherit=L,t.none=L,t.normal=`source-over`,t.add=`lighter`,t.multiply=e?`multiply`:L,t.screen=e?`screen`:L,t.overlay=e?`overlay`:L,t.darken=e?`darken`:L,t.lighten=e?`lighten`:L,t[`color-dodge`]=e?`color-dodge`:L,t[`color-burn`]=e?`color-burn`:L,t[`hard-light`]=e?`hard-light`:L,t[`soft-light`]=e?`soft-light`:L,t.difference=e?`difference`:L,t.exclusion=e?`exclusion`:L,t.saturation=e?`saturation`:L,t.color=e?`color`:L,t.luminosity=e?`luminosity`:L,t[`linear-burn`]=e?`color-burn`:L,t[`linear-dodge`]=e?`color-dodge`:L,t[`linear-light`]=e?`hard-light`:L,t[`pin-light`]=e?`hard-light`:L,t[`vivid-light`]=e?`hard-light`:L,t[`hard-mix`]=L,t.negation=e?`difference`:L,t[`normal-npm`]=t.normal,t[`add-npm`]=t.add,t[`screen-npm`]=t.screen,t.erase=`destination-out`,t.subtract=L,t.divide=L,t.min=L,t.max=L,t}var z=new e,B=class{constructor(e){this.activeResolution=1,this.smoothProperty=`imageSmoothingEnabled`,this.blendModes=R(),this._activeBlendMode=`normal`,this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){let e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext(`2d`,{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){let e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty=`webkitImageSmoothingEnabled`:e.mozImageSmoothingEnabled?this.smoothProperty=`mozImageSmoothingEnabled`:e.oImageSmoothingEnabled?this.smoothProperty=`oImageSmoothingEnabled`:e.msImageSmoothingEnabled&&(this.smoothProperty=`msImageSmoothingEnabled`)}}setContextTransform(t,n,r,i){let a=i?e.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||e.IDENTITY,o=z;o.copyFrom(a),o.append(t);let s=this._projTransform,c=this.activeResolution;if(r||=c,s){let t=e.shared;t.copyFrom(o),t.prepend(s),o=t}n?this.activeContext.setTransform(o.a*r,o.b*r,o.c*r,o.d*r,o.tx*c|0,o.ty*c|0):this.activeContext.setTransform(o.a*r,o.b*r,o.c*r,o.d*r,o.tx*c,o.ty*c)}clear(e,t){let n=this.activeContext,r=this._renderer;if(n.clearRect(0,0,r.width,r.height),e){let i=f.shared.setValue(e);n.globalAlpha=t??i.alpha,n.fillStyle=i.toHex(),n.fillRect(0,0,r.width,r.height),n.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;let t=this.blendModes[e];t?this.activeContext.globalCompositeOperation=t:(this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation=`source-over`)}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}};B.extension={type:[n.CanvasSystem],name:`canvasContext`};var V=class{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0,this.minUniformBufferOffsetAlignment=0}init(){}};V.extension={type:[n.CanvasSystem],name:`limits`};var H=`#808080`,U=new e,W=new e,G=new e,K=new e,q=new e;function J(e,t,n){e.beginPath();for(let r=0;r<n.length;r+=3){let i=n[r]*2,a=n[r+1]*2,o=n[r+2]*2;e.moveTo(t[i],t[i+1]),e.lineTo(t[a],t[a+1]),e.lineTo(t[o],t[o+1]),e.closePath()}e.fill()}function Y(e){return`#${(e&0xffffff).toString(16).padStart(6,`0`)}`}function X(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function Z(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;X(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function Q(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),Z(e,r.shape),a&&e.restore()}return!0}function ee(e,t,n,r){let i=e.fill;if(i instanceof m){i.buildGradient();let a=i.texture;if(a){let o=O.getTintedPattern(a,t),s=n?K.copyFrom(n).scale(a.source.pixelWidth,a.source.pixelHeight):K.copyFrom(i.transform);return r&&!e.textureSpace&&s.append(r),O.applyPatternTransform(o,s),o}}if(i instanceof g){let e=O.getTintedPattern(i.texture,t);return O.applyPatternTransform(e,i.transform,!1),e}let a=e.texture;if(a&&a!==l.WHITE){if(!a.source.resource)return H;let r=O.getTintedPattern(a,t),i=e.matrix;if(n){let{resolution:e}=a.source;if(i=K.copyFrom(n),a.rotate){let{uvs:t,orig:n}=a;i.prepend(q.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0).invert()).scale(n.width*e,n.height*e)}else i.scale(a.source.pixelWidth,a.source.pixelHeight).translate(-a.frame.x*e,-a.frame.y*e)}return O.applyPatternTransform(r,i),r}return Y(t)}var $=class{constructor(){this.shader=null}contextChange(e){}execute(e,t){let n=e.renderer,r=n.canvasContext,i=r.activeContext,a=t.groupTransform,c=n.globalUniforms.globalUniformData?.worldColor??0xffffffff,f=t.groupColorAlpha,m=(c>>>24&255)/255,h=(f>>>24&255)/255,g=n.filter?.alphaMultiplier??1,v=m*h*g;if(v<=0)return;let y=c&0xffffff,b=f&0xffffff,x=u(p(b,y)),S=n._roundPixels|t._roundPixels;i.save(),r.setContextTransform(a,S===1),r.setBlendMode(t.groupBlendMode);let C=t.context.instructions;for(let e=0;e<C.length;e++){let t=C[e];if(t.action===`texture`){let e=t.data,n=e.image,s=n?O.getCanvasSource(n):null;if(!s)continue;let c=e.alpha*v;if(c<=0)continue;let l=p(e.style,x);i.globalAlpha=c;let u=s;l!==0xffffff&&(u=O.getTintedCanvas({texture:n},l));let d=n.frame,f=n.source._resolution??n.source.resolution??1,m=d.x*f,h=d.y*f,g=d.width*f,_=d.height*f;u!==s&&(m=0,h=0);let y=e.transform,b=y&&!y.isIdentity(),C=n.rotate;b||C?(U.copyFrom(a),b&&U.append(y),C&&o.matrixAppendRotationInv(U,C,e.dx,e.dy,e.dw,e.dh),r.setContextTransform(U,S===1)):r.setContextTransform(a,S===1),i.drawImage(u,m,h,u===s?g:u.width,u===s?_:u.height,C?0:e.dx,C?0:e.dy,e.dw,e.dh),(b||C)&&r.setContextTransform(a,S===1);continue}let n=t.data,c=n?.path?.shapePath;if(!c?.shapePrimitives?.length)continue;let u=n.style,f=p(u.color,x),m=u.alpha*v;if(m<=0)continue;let h=t.action===`stroke`;if(i.globalAlpha=m,h){let e=u;i.lineWidth=e.width,i.lineCap=e.cap,i.lineJoin=e.join,i.miterLimit=e.miterLimit}let g=c.shapePrimitives;if(!h&&n.hole?.shapePath?.shapePrimitives?.length){let e=g[g.length-1];e.holes=n.hole.shapePath.shapePrimitives}for(let e=0;e<g.length;e++){let t=g[e];if(!t?.shape)continue;let n=t.transform,r=n&&!n.isIdentity(),o=u.texture&&u.texture!==l.WHITE,c=u.textureSpace===`global`?n:null,p=ee(u,f,o?s(W,u,t.shape,c):null,r?G.copyFrom(a).append(n):a);if(r&&(i.save(),i.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),h){let e=u;if(e.alignment!==.5&&!e.pixelLine){let n=[],r=[],a=[];if(d[t.shape.type]?.build(t.shape,n)){let o=t.shape.closePath??!0;_(n,e,!1,o,r,a),i.fillStyle=p,J(i,r,a)}else i.strokeStyle=p,i.beginPath(),Z(i,t.shape),i.stroke()}else i.strokeStyle=p,i.beginPath(),Z(i,t.shape),i.stroke()}else i.fillStyle=p,i.beginPath(),Z(i,t.shape),Q(i,t.holes)?i.fill(`evenodd`):i.fill();r&&i.restore()}}i.restore()}destroy(){this.shader=null}};$.extension={type:[n.CanvasPipesAdaptor],name:`graphics`};var te=class{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){let t=e.colorTexture,{canvas:n,context:r}=this._ensureCanvas(t);return{canvas:n,context:r,width:n.width,height:n.height}}resizeGpuRenderTarget(e){let t=e.colorTexture,{canvas:n}=this._ensureCanvas(t);n.width=e.pixelWidth,n.height=e.pixelHeight}startRenderPass(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=i.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,n,r)}clear(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(i.setTransform(1,0,0,1,0,0),i.clearRect(a.x,a.y,a.width,a.height),n){let e=f.shared.setValue(n);e.alpha>0&&(i.globalAlpha=e.alpha,i.fillStyle=e.toHex(),i.fillRect(a.x,a.y,a.width,a.height),i.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,n,r,i){let a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,o=t.source,{context:s}=this._ensureCanvas(o),c=i?.x??0,l=i?.y??0;return s.drawImage(a,n.x,n.y,r.width,r.height,c,l,r.width,r.height),o.update(),t}copyDepthTexture(e,t,n,r,i){c(`[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer`)}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;t&&r.test(t)||(t=h.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);let n=t.getContext(`2d`);return{canvas:t,context:n}}},ne=class extends E{constructor(e){super(e),this.adaptor=new te,this.adaptor.init(e,this)}};ne.extension={type:[n.CanvasSystem],name:`renderTarget`};var re=class{constructor(e){}init(){}initSource(e){}generateCanvas(e){let t=h.get().createCanvas(),n=t.getContext(`2d`),r=O.getCanvasSource(e);if(!r)return t;let i=e.frame,a=e.source._resolution??e.source.resolution??1,o=i.x*a,s=i.y*a,c=i.width*a,l=i.height*a;return t.width=Math.ceil(c),t.height=Math.ceil(l),n.drawImage(r,o,s,c,l,0,0,c,l),t}getPixels(e){let t=this.generateCanvas(e);return{pixels:t.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}};re.extension={type:[n.CanvasSystem],name:`texture`};var ie=[...w,B,V,re,ne],ae=[x,S,y,C,b,I,j,T],oe=[A,$],se=[],ce=[],le=[],ue=[];t.handleByNamedList(n.CanvasSystem,se),t.handleByNamedList(n.CanvasPipes,ce),t.handleByNamedList(n.CanvasPipesAdaptor,le),t.handleByNamedList(n.CanvasLoader,ue),t.add(...ie,...ae,...oe);var de=class extends a{constructor(){let e={name:`canvas`,type:i.CANVAS,systems:se,renderPipes:ce,renderPipeAdaptors:le,loaders:ue};super(e)}};export{de as CanvasRenderer};