@scenar/core 0.9.1 → 0.11.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 (81) hide show
  1. package/embed/host-controller.d.ts +7 -0
  2. package/embed/host-controller.d.ts.map +1 -1
  3. package/embed/host-controller.js +1 -0
  4. package/embed/host-controller.js.map +1 -1
  5. package/embed/protocol.d.ts +35 -3
  6. package/embed/protocol.d.ts.map +1 -1
  7. package/embed/protocol.js +37 -4
  8. package/embed/protocol.js.map +1 -1
  9. package/index.d.ts +18 -2
  10. package/index.d.ts.map +1 -1
  11. package/index.js +9 -1
  12. package/index.js.map +1 -1
  13. package/package.json +1 -1
  14. package/presenter/derive-presenter-timeline.d.ts +36 -0
  15. package/presenter/derive-presenter-timeline.d.ts.map +1 -0
  16. package/presenter/derive-presenter-timeline.js +31 -0
  17. package/presenter/derive-presenter-timeline.js.map +1 -0
  18. package/presenter/presenter-opacity.d.ts +32 -0
  19. package/presenter/presenter-opacity.d.ts.map +1 -0
  20. package/presenter/presenter-opacity.js +40 -0
  21. package/presenter/presenter-opacity.js.map +1 -0
  22. package/presenter/types.d.ts +45 -0
  23. package/presenter/types.d.ts.map +1 -0
  24. package/presenter/types.js +16 -0
  25. package/presenter/types.js.map +1 -0
  26. package/scenario/apply-title-cards.d.ts +53 -0
  27. package/scenario/apply-title-cards.d.ts.map +1 -0
  28. package/scenario/apply-title-cards.js +113 -0
  29. package/scenario/apply-title-cards.js.map +1 -0
  30. package/scenario/bundle.d.ts +15 -0
  31. package/scenario/bundle.d.ts.map +1 -1
  32. package/scenario/soundtrack.d.ts +46 -0
  33. package/scenario/soundtrack.d.ts.map +1 -0
  34. package/scenario/soundtrack.js +11 -0
  35. package/scenario/soundtrack.js.map +1 -0
  36. package/scenario/title-cards.d.ts +64 -0
  37. package/scenario/title-cards.d.ts.map +1 -0
  38. package/scenario/title-cards.js +20 -0
  39. package/scenario/title-cards.js.map +1 -0
  40. package/scenario/types.d.ts +36 -2
  41. package/scenario/types.d.ts.map +1 -1
  42. package/src/embed/host-controller.test.ts +6 -0
  43. package/src/embed/host-controller.ts +8 -0
  44. package/src/embed/protocol.test.ts +53 -0
  45. package/src/embed/protocol.ts +76 -8
  46. package/src/index.ts +33 -1
  47. package/src/presenter/derive-presenter-timeline.test.ts +138 -0
  48. package/src/presenter/derive-presenter-timeline.ts +54 -0
  49. package/src/presenter/presenter-opacity.test.ts +47 -0
  50. package/src/presenter/presenter-opacity.ts +43 -0
  51. package/src/presenter/types.ts +46 -0
  52. package/src/scenario/apply-title-cards.test.ts +268 -0
  53. package/src/scenario/apply-title-cards.ts +141 -0
  54. package/src/scenario/bundle.ts +15 -0
  55. package/src/scenario/soundtrack.ts +47 -0
  56. package/src/scenario/title-cards.ts +67 -0
  57. package/src/scenario/types.ts +36 -2
  58. package/src/timeline/compute-step-timeline.test.ts +21 -0
  59. package/src/timeline/compute-step-timeline.ts +30 -7
  60. package/src/timeline/derive-action-events.test.ts +144 -0
  61. package/src/timeline/derive-action-events.ts +116 -0
  62. package/src/timeline/derive-sfx-timeline.test.ts +114 -0
  63. package/src/timeline/derive-sfx-timeline.ts +79 -0
  64. package/src/timeline/music-envelope.test.ts +141 -0
  65. package/src/timeline/music-envelope.ts +131 -0
  66. package/timeline/compute-step-timeline.d.ts +28 -3
  67. package/timeline/compute-step-timeline.d.ts.map +1 -1
  68. package/timeline/compute-step-timeline.js +11 -3
  69. package/timeline/compute-step-timeline.js.map +1 -1
  70. package/timeline/derive-action-events.d.ts +40 -0
  71. package/timeline/derive-action-events.d.ts.map +1 -0
  72. package/timeline/derive-action-events.js +71 -0
  73. package/timeline/derive-action-events.js.map +1 -0
  74. package/timeline/derive-sfx-timeline.d.ts +36 -0
  75. package/timeline/derive-sfx-timeline.d.ts.map +1 -0
  76. package/timeline/derive-sfx-timeline.js +49 -0
  77. package/timeline/derive-sfx-timeline.js.map +1 -0
  78. package/timeline/music-envelope.d.ts +69 -0
  79. package/timeline/music-envelope.d.ts.map +1 -0
  80. package/timeline/music-envelope.js +95 -0
  81. package/timeline/music-envelope.js.map +1 -0
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Card synthesis: expand a scenario's steps (and narration manifest)
3
+ * with its configured intro/outro title cards.
4
+ *
5
+ * This is THE one place card steps are constructed. It runs exactly
6
+ * once per playback surface, at bundle assembly — the generated render
7
+ * and pack entries, the CLI's `loadBundle`, and (for direct React
8
+ * integrators) one documented call between `createScenario()` and the
9
+ * player. Authoring surfaces (`createScenario`, `loadScenarioFromProto`)
10
+ * carry the `titleCards` config through untouched, exactly like
11
+ * `soundtrack` — so expanded output never carries the config and double
12
+ * expansion is impossible by data flow.
13
+ *
14
+ * The positional manifests stay keyed to AUTHORED steps everywhere
15
+ * (`scenar narrate` and `scenar presenter` never see cards); this
16
+ * function pads `null` entries at the injected positions — narration
17
+ * and presenter in the same single pass — so the expanded manifests
18
+ * line up with the expanded steps. Existing manifests therefore stay
19
+ * valid when an author adds cards later — no regeneration required.
20
+ */
21
+
22
+ import type { NarrationManifest } from "../narration/types.js";
23
+ import type { PresenterManifest } from "../presenter/types.js";
24
+ import { FINAL_DWELL_MS } from "../timeline/compute-step-timeline.js";
25
+ import type { ScenarioStep } from "./types.js";
26
+ import {
27
+ TITLE_CARD_DURATION_DEFAULT_MS,
28
+ type TitleCard,
29
+ type TitleCards,
30
+ } from "./title-cards.js";
31
+
32
+ /** The result of card expansion: steps and manifests, index-aligned. */
33
+ export interface AppliedTitleCards<T> {
34
+ readonly steps: readonly ScenarioStep<T>[];
35
+ readonly narrationManifest: NarrationManifest | undefined;
36
+ readonly presenterManifest: PresenterManifest | undefined;
37
+ }
38
+
39
+ /**
40
+ * A card step's `data` placeholder. Card steps are rendered by the
41
+ * player's built-in card component — the integrator's render callback
42
+ * (the only reader of `data`) is never invoked for them, so no real
43
+ * `T` value is ever needed. See the `ScenarioStep.card` doc contract.
44
+ */
45
+ function cardStepData<T>(): T {
46
+ return undefined as unknown as T;
47
+ }
48
+
49
+ /**
50
+ * Expand `steps` (and the index-parallel narration and presenter
51
+ * manifests, when they exist) with the configured intro/outro cards.
52
+ *
53
+ * - **Intro**: prepended at index 0 with `delayMs: 0`; the card's
54
+ * visible time is encoded as the following step's transition delay
55
+ * (`max(authored delayMs, card duration)`), which is exactly how
56
+ * `computeStepTimeline` reads step 0's duration.
57
+ * - **Outro**: appended with `delayMs: FINAL_DWELL_MS`, so the last
58
+ * authored step keeps precisely the closing dwell it has today (or
59
+ * its narration, whichever is longer) before the card appears. The
60
+ * card's own visible time is its `durationMs` — `computeStepTimeline`
61
+ * reads a final card step's duration as the closing dwell. The outro
62
+ * carries two housekeeping interactions at step entry (`clear_cursor`
63
+ * and a viewport reset) so a scenario ending with a visible cursor or
64
+ * an active zoom never leaks that state onto the card. Neither action
65
+ * maps to a sound effect.
66
+ *
67
+ * Pure and non-mutating. When `titleCards` configures no card, the
68
+ * inputs are returned as-is (byte-identical no-op).
69
+ */
70
+ export function applyTitleCards<T>(
71
+ steps: readonly ScenarioStep<T>[],
72
+ narrationManifest: NarrationManifest | undefined,
73
+ titleCards: TitleCards | undefined,
74
+ presenterManifest?: PresenterManifest,
75
+ ): AppliedTitleCards<T> {
76
+ const intro = titleCards?.intro;
77
+ const outro = titleCards?.outro;
78
+ if (!intro && !outro) {
79
+ return { steps, narrationManifest, presenterManifest };
80
+ }
81
+
82
+ const expandedSteps: ScenarioStep<T>[] = [...steps];
83
+ let manifestEntries = narrationManifest ? [...narrationManifest.steps] : undefined;
84
+ let presenterEntries = presenterManifest ? [...presenterManifest.steps] : undefined;
85
+
86
+ if (intro && expandedSteps.length > 0) {
87
+ const introDurationMs = intro.durationMs ?? TITLE_CARD_DURATION_DEFAULT_MS;
88
+ const firstAuthored = expandedSteps[0]!;
89
+ expandedSteps[0] = {
90
+ ...firstAuthored,
91
+ delayMs: Math.max(firstAuthored.delayMs, introDurationMs),
92
+ };
93
+ expandedSteps.unshift({
94
+ delayMs: 0,
95
+ data: cardStepData<T>(),
96
+ card: { kind: "intro", ...pickCardContent(intro) },
97
+ });
98
+ manifestEntries?.unshift(null);
99
+ presenterEntries?.unshift(null);
100
+ }
101
+
102
+ if (outro) {
103
+ expandedSteps.push({
104
+ delayMs: FINAL_DWELL_MS,
105
+ data: cardStepData<T>(),
106
+ card: { kind: "outro", ...pickCardContent(outro) },
107
+ interactions: [
108
+ { atPercent: 0, type: "clear_cursor" },
109
+ { atPercent: 0, type: "viewport_transition", viewportReset: true },
110
+ ],
111
+ });
112
+ manifestEntries?.push(null);
113
+ presenterEntries?.push(null);
114
+ }
115
+
116
+ return {
117
+ steps: expandedSteps,
118
+ narrationManifest: manifestEntries ? { steps: manifestEntries } : undefined,
119
+ presenterManifest: presenterEntries ? { steps: presenterEntries } : undefined,
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Copy only the known card fields, so a config object carrying strays
125
+ * (e.g. a loosely-typed steps.ts export) never smuggles them into the
126
+ * step list.
127
+ */
128
+ function pickCardContent(card: TitleCard): TitleCard {
129
+ const content: {
130
+ title: string;
131
+ subtitle?: string;
132
+ logoSrc?: string;
133
+ ctaText?: string;
134
+ durationMs?: number;
135
+ } = { title: card.title };
136
+ if (card.subtitle !== undefined) content.subtitle = card.subtitle;
137
+ if (card.logoSrc !== undefined) content.logoSrc = card.logoSrc;
138
+ if (card.ctaText !== undefined) content.ctaText = card.ctaText;
139
+ if (card.durationMs !== undefined) content.durationMs = card.durationMs;
140
+ return content;
141
+ }
@@ -8,6 +8,8 @@
8
8
  */
9
9
 
10
10
  import type { NarrationManifest } from "../narration/types.js";
11
+ import type { PresenterManifest } from "../presenter/types.js";
12
+ import type { Soundtrack } from "./soundtrack.js";
11
13
  import type { ScenarioStep } from "./types.js";
12
14
 
13
15
  /**
@@ -26,4 +28,17 @@ export interface ScenarioBundle<T> {
26
28
  * narration (timing is purely delay-based).
27
29
  */
28
30
  readonly narrationManifest?: NarrationManifest;
31
+ /**
32
+ * Audio treatment: background music with narration ducking and
33
+ * interaction sound effects. When `undefined`, the scenario plays
34
+ * silent apart from narration.
35
+ */
36
+ readonly soundtrack?: Soundtrack;
37
+ /**
38
+ * Pre-built presenter manifest mapping step indices to avatar clip
39
+ * URLs and durations (generated by `scenar presenter`). When
40
+ * `undefined`, the scenario plays without the presenter — zero
41
+ * presenter DOM, zero fetched bytes.
42
+ */
43
+ readonly presenterManifest?: PresenterManifest;
29
44
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The scenario's audio treatment beyond narration: optional background
3
+ * music with narration ducking, and optional interaction sound effects.
4
+ *
5
+ * Runtime mirror of the proto `SoundtrackConfig` (`ai.scenar.scenario.v1`),
6
+ * field for field, in camelCase — the same 1:1 relationship `StepAction`
7
+ * has with its proto message. Music and sound effects are independent:
8
+ * a scenario may use either without the other.
9
+ */
10
+ export interface Soundtrack {
11
+ /**
12
+ * Background music asset reference. Like narration clip srcs, a
13
+ * relative path resolves against the scenario's own location; an
14
+ * absolute URL passes through unchanged. MP3 is the supported format.
15
+ * When `undefined`, the scenario has no music.
16
+ */
17
+ readonly musicSrc?: string;
18
+ /**
19
+ * Base music level while no narration is playing (0–1).
20
+ * Defaults to {@link MUSIC_VOLUME_DEFAULT}.
21
+ */
22
+ readonly musicVolume?: number;
23
+ /**
24
+ * Absolute music level while a narration clip plays (0–1) — the level
25
+ * the music ducks to, not a multiplier of {@link musicVolume}.
26
+ * Defaults to {@link DUCKING_VOLUME_DEFAULT}.
27
+ */
28
+ readonly duckingVolume?: number;
29
+ /**
30
+ * Enables the engine's built-in interaction sound effects (click and
31
+ * keystroke). Requires an explicit `true` — adding music alone never
32
+ * introduces sound effects.
33
+ */
34
+ readonly sfx?: boolean;
35
+ }
36
+
37
+ /**
38
+ * Default base music level. Clearly audible under silence without
39
+ * competing with interface sound effects.
40
+ */
41
+ export const MUSIC_VOLUME_DEFAULT = 0.25;
42
+
43
+ /**
44
+ * Default ducked music level while narration plays. Present but firmly
45
+ * under the voice.
46
+ */
47
+ export const DUCKING_VOLUME_DEFAULT = 0.08;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Intro and outro title cards framing a scenario.
3
+ *
4
+ * Runtime mirror of the proto `TitleCardsConfig` / `TitleCard`
5
+ * (`ai.scenar.scenario.v1`), field for field, in camelCase — the same
6
+ * 1:1 relationship `Soundtrack` has with its proto message.
7
+ *
8
+ * Cards are synthesized steps: {@link applyTitleCards} injects them
9
+ * into the step list at bundle assembly, so chapter markers, scrubbing,
10
+ * video duration, and the music envelope account for them with no
11
+ * card-specific timing code. The player renders card steps with its
12
+ * built-in card component — the scenario's render function is never
13
+ * called for them.
14
+ */
15
+
16
+ /** One card's content — deliberately small; a card, not a page builder. */
17
+ export interface TitleCard {
18
+ /** Headline text. The one required field. */
19
+ readonly title: string;
20
+ /** Supporting line rendered under the title. */
21
+ readonly subtitle?: string;
22
+ /**
23
+ * Logo image asset reference. Like narration and music srcs, a
24
+ * relative path resolves against the scenario's own location; an
25
+ * absolute URL passes through unchanged. Raster web formats only
26
+ * (png, jpg/jpeg, gif, webp, avif) — the deploy contract excludes
27
+ * svg as active content.
28
+ */
29
+ readonly logoSrc?: string;
30
+ /**
31
+ * Call-to-action text rendered as a distinct pill. Display-only —
32
+ * not a link. Typically used on the outro.
33
+ */
34
+ readonly ctaText?: string;
35
+ /**
36
+ * How long the card stays on screen, in milliseconds.
37
+ * Defaults to {@link TITLE_CARD_DURATION_DEFAULT_MS}.
38
+ */
39
+ readonly durationMs?: number;
40
+ }
41
+
42
+ /**
43
+ * The scenario-level card configuration: an intro card, an outro card,
44
+ * or both. Either field may be set independently; neither set is a no-op.
45
+ */
46
+ export interface TitleCards {
47
+ /** Opening card shown before the first authored step. */
48
+ readonly intro?: TitleCard;
49
+ /** Closing card shown after the last authored step. */
50
+ readonly outro?: TitleCard;
51
+ }
52
+
53
+ /**
54
+ * The card marker carried by a synthesized card step
55
+ * ({@link ScenarioStep.card}). `kind` records which side of the
56
+ * scenario the card frames so the renderer can style intro and outro
57
+ * distinctly if it chooses.
58
+ */
59
+ export interface StepCard extends TitleCard {
60
+ readonly kind: "intro" | "outro";
61
+ }
62
+
63
+ /**
64
+ * Default card visible time. Long enough to read a title and subtitle,
65
+ * short enough to not delay the content.
66
+ */
67
+ export const TITLE_CARD_DURATION_DEFAULT_MS = 3_000;
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { StepAction } from "./step-action.js";
9
+ import type { StepCard } from "./title-cards.js";
9
10
 
10
11
  /**
11
12
  * A single step in a scenario timeline.
@@ -18,8 +19,12 @@ export interface ScenarioStep<T> {
18
19
  /** Data snapshot at this point in the timeline. */
19
20
  readonly data: T;
20
21
  /**
21
- * Narration script for TTS generation. Consumed by the build script
22
- * to produce audio files not rendered at runtime.
22
+ * Narration script for this step. Consumed by `scenar narrate` to
23
+ * produce audio files, and rendered at runtime as the step's caption
24
+ * when the player has captions enabled (a presentation preference —
25
+ * the `captions` player prop, the `?captions=1` embed param, or
26
+ * `scenar render --captions`). Steps without narration play
27
+ * uncaptioned.
23
28
  */
24
29
  readonly narration?: string;
25
30
  /**
@@ -31,6 +36,22 @@ export interface ScenarioStep<T> {
31
36
  * share the same atPercent, they fire in array order.
32
37
  */
33
38
  readonly interactions?: readonly StepAction[];
39
+ /**
40
+ * Marks this step for the presenter track. When true, `scenar presenter`
41
+ * generates an avatar clip lip-synced to this step's narration audio,
42
+ * and both outputs show the clip picture-in-picture while the step is
43
+ * active — the interactive embed and the exported video alike.
44
+ *
45
+ * Requires `narration`: the presenter clip is derived from the step's
46
+ * narration audio by definition, so a step without narration cannot
47
+ * opt in (validated at load time).
48
+ *
49
+ * Playback never calls an AI service. Like narration audio, presenter
50
+ * clips are generated at compile time by the CLI and consumed as fixed
51
+ * assets through a positional manifest; a scenario whose clips have
52
+ * not been generated yet simply plays without the presenter.
53
+ */
54
+ readonly presenter?: boolean;
34
55
  /**
35
56
  * Names this step as a still-capture point for `scenar shoot`.
36
57
  *
@@ -47,4 +68,17 @@ export interface ScenarioStep<T> {
47
68
  * bundle. Steps without a `shot` are simply walked through.
48
69
  */
49
70
  readonly shot?: string;
71
+ /**
72
+ * Marks this step as an engine-synthesized title card. Only
73
+ * `applyTitleCards` constructs card steps — authors configure cards
74
+ * through the scenario-level `titleCards` config, never by hand.
75
+ *
76
+ * The player renders card steps with its built-in card component and
77
+ * never calls the scenario's render function for them, so a card
78
+ * step's `data` is a placeholder that is never read. Card steps
79
+ * announce activation through the player's `onCardStepChange`
80
+ * callback instead of `onStepChange` — the engine cannot fabricate a
81
+ * real `T` for the latter.
82
+ */
83
+ readonly card?: StepCard;
50
84
  }
@@ -57,4 +57,25 @@ describe("computeStepTimeline", () => {
57
57
  expect(tl.stepStartTimesMs).toEqual([0]);
58
58
  expect(tl.totalDurationMs).toBe(3000);
59
59
  });
60
+
61
+ it("uses a final card step's duration as the closing dwell", () => {
62
+ const tl = computeStepTimeline(
63
+ [{ delayMs: 0 }, { delayMs: 3000, card: { durationMs: 5000 } }],
64
+ null,
65
+ );
66
+ expect(tl.totalDurationMs).toBe(3000 + 5000);
67
+ });
68
+
69
+ it("falls back to the default dwell for a final card step without a duration", () => {
70
+ const tl = computeStepTimeline([{ delayMs: 0 }, { delayMs: 3000, card: {} }], null);
71
+ expect(tl.totalDurationMs).toBe(3000 + 3000);
72
+ });
73
+
74
+ it("ignores a non-final card step's duration for the closing dwell", () => {
75
+ const tl = computeStepTimeline(
76
+ [{ delayMs: 0, card: { durationMs: 9000 } }, { delayMs: 2000 }],
77
+ null,
78
+ );
79
+ expect(tl.totalDurationMs).toBe(2000 + 3000);
80
+ });
60
81
  });
@@ -1,15 +1,34 @@
1
- import type { NarrationManifest } from "../narration/types.js";
2
-
3
1
  /**
4
2
  * Minimal step shape for timeline computation. Accepts any
5
- * ScenarioStep<T> without caring about the data payload.
3
+ * ScenarioStep<T> without caring about the data payload. The optional
4
+ * `card` marker participates because a synthesized outro card's
5
+ * duration IS the closing dwell (see below).
6
6
  */
7
7
  interface StepTiming {
8
8
  delayMs: number;
9
+ card?: { durationMs?: number };
9
10
  }
10
11
 
11
- /** Dwell time on the final step so viewers can absorb the result. */
12
- const FINAL_DWELL_MS = 3_000;
12
+ /**
13
+ * Minimal manifest shape for timeline computation: any positional
14
+ * manifest whose entries carry a duration. Accepts the narration
15
+ * manifest, and — while the player is muted with a presenter track —
16
+ * the presenter manifest, whose clip durations equal the narration's
17
+ * for the same steps (the clip is derived from that audio). Feeding
18
+ * the presenter manifest to the muted timeline keeps the progress
19
+ * bar, scrubbing, and step advancement in agreement on presenter
20
+ * steps, and converges muted timing on the export timeline there.
21
+ */
22
+ interface ManifestTiming {
23
+ readonly steps: readonly ({ readonly durationMs: number } | null | undefined)[];
24
+ }
25
+
26
+ /**
27
+ * Dwell time on the final step so viewers can absorb the result.
28
+ * Also the delay `applyTitleCards` gives a synthesized outro card, so
29
+ * the last authored step keeps exactly this dwell before the card.
30
+ */
31
+ export const FINAL_DWELL_MS = 3_000;
13
32
 
14
33
  export interface StepTimeline {
15
34
  /** Start time of each step in milliseconds (index 0 is always 0). */
@@ -30,7 +49,7 @@ export interface StepTimeline {
30
49
  */
31
50
  export function computeStepTimeline(
32
51
  steps: readonly StepTiming[],
33
- manifest: NarrationManifest | null | undefined,
52
+ manifest: ManifestTiming | null | undefined,
34
53
  ): StepTimeline {
35
54
  const stepStartTimesMs: number[] = [0];
36
55
 
@@ -43,7 +62,11 @@ export function computeStepTimeline(
43
62
 
44
63
  const lastStepStart = stepStartTimesMs[stepStartTimesMs.length - 1] ?? 0;
45
64
  const lastNarrationMs = manifest?.steps[steps.length - 1]?.durationMs ?? 0;
46
- const totalDurationMs = lastStepStart + Math.max(FINAL_DWELL_MS, lastNarrationMs);
65
+ // A final card step (a synthesized outro) dwells for its configured
66
+ // duration instead of the fixed default — cards are silent, so the
67
+ // narration max is a no-op for them but kept for uniformity.
68
+ const closingDwellMs = steps[steps.length - 1]?.card?.durationMs ?? FINAL_DWELL_MS;
69
+ const totalDurationMs = lastStepStart + Math.max(closingDwellMs, lastNarrationMs);
47
70
 
48
71
  return { stepStartTimesMs, totalDurationMs };
49
72
  }
@@ -0,0 +1,144 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { StepAction } from "../scenario/step-action.js";
3
+ import { deriveActionEvents, type ActionEvent } from "./derive-action-events.js";
4
+ import {
5
+ CLICK_DELAY_MS,
6
+ DRAG_SETTLE_MS,
7
+ HOVER_HOLD_MS,
8
+ TYPE_CHAR_DELAY_MS,
9
+ } from "../timing/constants.js";
10
+
11
+ const DURATION = 2000;
12
+
13
+ function offsets(events: ActionEvent[]): Record<string, number[]> {
14
+ const byKind: Record<string, number[]> = {};
15
+ for (const e of events) {
16
+ (byKind[e.kind] ??= []).push(e.offsetMs);
17
+ }
18
+ return byKind;
19
+ }
20
+
21
+ describe("deriveActionEvents", () => {
22
+ it("click: cursor move at fireAt, dispatch after the travel window", () => {
23
+ const action: StepAction = { atPercent: 0.5, type: "click", target: "btn" };
24
+ expect(offsets(deriveActionEvents(action, DURATION))).toEqual({
25
+ "cursor-move": [1000],
26
+ "click-dispatch": [1000 + CLICK_DELAY_MS],
27
+ });
28
+ });
29
+
30
+ it("type: one keystroke per character at the typing cadence", () => {
31
+ const action: StepAction = { atPercent: 0, type: "type", target: "input", text: "abc" };
32
+ const events = deriveActionEvents(action, DURATION);
33
+ const keystrokes = events.filter((e) => e.kind === "keystroke");
34
+
35
+ expect(events[0]).toEqual({ kind: "cursor-move", offsetMs: 0 });
36
+ expect(keystrokes).toEqual([
37
+ { kind: "keystroke", offsetMs: CLICK_DELAY_MS, charIndex: 0 },
38
+ { kind: "keystroke", offsetMs: CLICK_DELAY_MS + TYPE_CHAR_DELAY_MS, charIndex: 1 },
39
+ { kind: "keystroke", offsetMs: CLICK_DELAY_MS + 2 * TYPE_CHAR_DELAY_MS, charIndex: 2 },
40
+ ]);
41
+ });
42
+
43
+ it("type: honors a per-action typeDelay override", () => {
44
+ const action: StepAction = {
45
+ atPercent: 0,
46
+ type: "type",
47
+ target: "input",
48
+ text: "ab",
49
+ typeDelay: 120,
50
+ };
51
+ const keystrokes = deriveActionEvents(action, DURATION).filter(
52
+ (e) => e.kind === "keystroke",
53
+ );
54
+ expect(keystrokes.map((e) => e.offsetMs)).toEqual([
55
+ CLICK_DELAY_MS,
56
+ CLICK_DELAY_MS + 120,
57
+ ]);
58
+ });
59
+
60
+ it("type: empty text is a no-op, exactly like the schedulers", () => {
61
+ const action: StepAction = { atPercent: 0.5, type: "type", target: "input", text: "" };
62
+ expect(deriveActionEvents(action, DURATION)).toEqual([]);
63
+ });
64
+
65
+ it("type: unicode text counts UTF-16 code units, matching substring typing", () => {
66
+ // The schedulers type text.substring(0, i + 1) for i < text.length, so
67
+ // the derivation must count the same units — an emoji surrogate pair
68
+ // yields two keystrokes, one per code unit.
69
+ const action: StepAction = { atPercent: 0, type: "type", target: "input", text: "é🙂" };
70
+ const keystrokes = deriveActionEvents(action, DURATION).filter(
71
+ (e) => e.kind === "keystroke",
72
+ );
73
+ expect(keystrokes).toHaveLength("é🙂".length);
74
+ });
75
+
76
+ it("hover: enter after travel, leave after the hold", () => {
77
+ const action: StepAction = { atPercent: 0.25, type: "hover", target: "tip" };
78
+ expect(offsets(deriveActionEvents(action, DURATION))).toEqual({
79
+ "cursor-move": [500],
80
+ "hover-enter": [500 + CLICK_DELAY_MS],
81
+ "hover-leave": [500 + CLICK_DELAY_MS + HOVER_HOLD_MS],
82
+ });
83
+ });
84
+
85
+ it("hover: honors a per-action hoverDuration override", () => {
86
+ const action: StepAction = {
87
+ atPercent: 0,
88
+ type: "hover",
89
+ target: "tip",
90
+ hoverDuration: 200,
91
+ };
92
+ const leave = deriveActionEvents(action, DURATION).find((e) => e.kind === "hover-leave");
93
+ expect(leave?.offsetMs).toBe(CLICK_DELAY_MS + 200);
94
+ });
95
+
96
+ it("drag: press, move, release along the settle chain", () => {
97
+ const action: StepAction = {
98
+ atPercent: 0.1,
99
+ type: "drag",
100
+ target: "card",
101
+ dragTarget: "column",
102
+ };
103
+ expect(offsets(deriveActionEvents(action, DURATION))).toEqual({
104
+ "cursor-move": [200],
105
+ "drag-press": [200 + CLICK_DELAY_MS],
106
+ "drag-move": [200 + CLICK_DELAY_MS + DRAG_SETTLE_MS],
107
+ "drag-release": [200 + CLICK_DELAY_MS + DRAG_SETTLE_MS + CLICK_DELAY_MS],
108
+ });
109
+ });
110
+
111
+ it.each([
112
+ ["scroll_to", "list"],
113
+ ["set_cursor", "btn"],
114
+ ["clear_cursor", undefined],
115
+ ] as const)("%s: a single dispatch at fireAt", (type, target) => {
116
+ const action: StepAction = { atPercent: 0.5, type, target };
117
+ expect(deriveActionEvents(action, DURATION)).toEqual([
118
+ { kind: "simple-dispatch", offsetMs: 1000 },
119
+ ]);
120
+ });
121
+
122
+ it("viewport_transition: fires at fireAt with no travel delay", () => {
123
+ const action: StepAction = { atPercent: 0.5, type: "viewport_transition", target: "hero" };
124
+ expect(deriveActionEvents(action, DURATION)).toEqual([
125
+ { kind: "viewport-transition", offsetMs: 1000 },
126
+ ]);
127
+ });
128
+
129
+ it.each([
130
+ ["atPercent 0.0 anchors at step start", 0.0, 0],
131
+ ["atPercent 1.0 anchors at step end", 1.0, DURATION],
132
+ ])("%s", (_name, atPercent, expected) => {
133
+ const action: StepAction = { atPercent, type: "click", target: "btn" };
134
+ expect(deriveActionEvents(action, DURATION)[0]?.offsetMs).toBe(expected);
135
+ });
136
+
137
+ it("zero-duration step: every anchor collapses to the fixed offsets", () => {
138
+ const action: StepAction = { atPercent: 0.7, type: "click", target: "btn" };
139
+ expect(offsets(deriveActionEvents(action, 0))).toEqual({
140
+ "cursor-move": [0],
141
+ "click-dispatch": [CLICK_DELAY_MS],
142
+ });
143
+ });
144
+ });