-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathhyperframes-player.test.ts
More file actions
1948 lines (1614 loc) · 64.5 KB
/
Copy pathhyperframes-player.test.ts
File metadata and controls
1948 lines (1614 loc) · 64.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { formatTime, formatSpeed, SPEED_PRESETS } from "./controls.js";
// ── Controls unit tests ──
describe("SPEED_PRESETS", () => {
it("contains logarithmic speed steps", () => {
expect(SPEED_PRESETS).toEqual([0.25, 0.5, 1, 1.5, 2, 4]);
});
it("includes 1x as default speed", () => {
expect(SPEED_PRESETS).toContain(1);
});
});
describe("formatSpeed", () => {
it("formats integer speeds", () => {
expect(formatSpeed(1)).toBe("1x");
expect(formatSpeed(2)).toBe("2x");
expect(formatSpeed(4)).toBe("4x");
});
it("formats fractional speeds", () => {
expect(formatSpeed(0.25)).toBe("0.25x");
expect(formatSpeed(0.5)).toBe("0.5x");
expect(formatSpeed(1.5)).toBe("1.5x");
});
});
describe("formatTime", () => {
it("formats 0 seconds", () => {
expect(formatTime(0)).toBe("0:00");
});
it("formats seconds under a minute", () => {
expect(formatTime(45)).toBe("0:45");
});
it("formats exact minutes", () => {
expect(formatTime(120)).toBe("2:00");
});
it("formats minutes and seconds", () => {
expect(formatTime(95)).toBe("1:35");
});
it("pads seconds with leading zero", () => {
expect(formatTime(61)).toBe("1:01");
});
it("floors fractional seconds", () => {
expect(formatTime(3.7)).toBe("0:03");
});
it("handles negative input", () => {
expect(formatTime(-5)).toBe("0:00");
});
});
// ── Parent-frame audio proxies (ownership-based) ──
//
// Parent-frame audio/video copies are preloaded mirror proxies of the iframe's
// timed media. They exist as a fallback for environments that block iframe
// `.play()`. Under the default `runtime` audio ownership, the iframe drives
// audible playback and the proxies stay paused. Ownership flips to `parent`
// only when the runtime posts `media-autoplay-blocked` — then the proxies
// become the audible source and the iframe is silenced via bridge.
describe("HyperframesPlayer parent-frame media", () => {
type PlayerElement = HTMLElement & {
play: () => void;
pause: () => void;
seek: (t: number) => void;
_audioOwner?: "runtime" | "parent";
_promoteToParentProxy?: () => void;
};
let player: PlayerElement;
let mockAudio: {
src: string;
preload: string;
muted: boolean;
playbackRate: number;
currentTime: number;
paused: boolean;
play: ReturnType<typeof vi.fn>;
pause: ReturnType<typeof vi.fn>;
load: ReturnType<typeof vi.fn>;
};
beforeEach(async () => {
await import("./hyperframes-player.js");
mockAudio = {
src: "",
preload: "",
muted: false,
playbackRate: 1,
currentTime: 0,
paused: true,
play: vi.fn().mockResolvedValue(undefined),
pause: vi.fn(),
load: vi.fn(),
};
vi.spyOn(globalThis, "Audio").mockImplementation(
() => mockAudio as unknown as HTMLAudioElement,
);
player = document.createElement("hyperframes-player") as PlayerElement;
});
afterEach(() => {
player.remove();
vi.restoreAllMocks();
});
it("includes audio-src in observedAttributes", () => {
const Ctor = player.constructor as typeof HTMLElement & {
observedAttributes: string[];
};
expect(Ctor.observedAttributes).toContain("audio-src");
});
it("creates Audio and starts preloading when audio-src is set", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
expect(globalThis.Audio).toHaveBeenCalled();
expect(mockAudio.preload).toBe("auto");
expect(mockAudio.src).toBe("https://cdn.example.com/narration.mp3");
expect(mockAudio.load).toHaveBeenCalled();
});
it("syncs muted attribute to parent media", () => {
player.setAttribute("muted", "");
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
expect(mockAudio.muted).toBe(true);
});
it("syncs playback-rate to parent media", () => {
player.setAttribute("playback-rate", "1.5");
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
expect(mockAudio.playbackRate).toBe(1.5);
});
it("play() does NOT start parent-proxy under runtime ownership", () => {
// Default ownership is `runtime` — the iframe drives audible playback.
// If we also started parent proxies here, both would play and the user
// would hear doubled, slightly-offset audio (the original bug).
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.play();
expect(mockAudio.play).not.toHaveBeenCalled();
expect(player._audioOwner).toBe("runtime");
});
it("pause() does NOT touch parent-proxy under runtime ownership", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.pause();
expect(mockAudio.pause).not.toHaveBeenCalled();
});
it("seek() does NOT update parent currentTime under runtime ownership", () => {
// Under runtime ownership the iframe is authoritative for time; touching
// the proxy's currentTime would just trigger a re-buffer for no gain.
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.seek(12.5);
expect(mockAudio.currentTime).toBe(0);
});
it("after promotion to parent ownership: play/pause/seek drive parent proxy", () => {
// Simulates the runtime having posted `media-autoplay-blocked`. Post
// promotion: the web component owns audible output and fully drives
// the parent proxy.
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player._promoteToParentProxy?.();
expect(player._audioOwner).toBe("parent");
player.play();
expect(mockAudio.play).toHaveBeenCalled();
player.seek(12.5);
expect(mockAudio.currentTime).toBe(12.5);
player.pause();
expect(mockAudio.pause).toHaveBeenCalled();
});
it("seek() while playing pauses parent proxy (prevents mirrorTime stutter loop)", () => {
// Regression: previously `seek()` only called `seekAll()`, leaving the
// proxy playing. With the timeline frozen at the new seek target, the
// parent's `mirrorTime` drift-correction would yank `currentTime` back
// every ~80ms of accumulated drift, producing an audible audio stutter
// loop while the video frame stayed frozen. `seek()` must be symmetric
// with `pause()` for the parent-owned audio path.
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player._promoteToParentProxy?.();
player.play();
expect(mockAudio.play).toHaveBeenCalled();
mockAudio.pause.mockClear();
player.seek(12.5);
expect(mockAudio.pause).toHaveBeenCalled();
expect(mockAudio.currentTime).toBe(12.5);
});
it("promotion is idempotent", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player._promoteToParentProxy?.();
player._promoteToParentProxy?.();
player._promoteToParentProxy?.();
// Only one play() attempt is triggered by promotion itself (gated on
// `!this._paused`, which is true by default so it doesn't trigger at all).
// The test's meaning is: ownership stays `parent`, no thrash, no errors.
expect(player._audioOwner).toBe("parent");
});
it("dispatches audioownershipchange on promotion", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
const events: Array<{ owner: string; reason: string }> = [];
player.addEventListener("audioownershipchange", (e: Event) => {
const detail = (e as CustomEvent<{ owner: string; reason: string }>).detail;
events.push(detail);
});
player._promoteToParentProxy?.();
expect(events).toEqual([{ owner: "parent", reason: "autoplay-blocked" }]);
// Second promote is idempotent — no duplicate event.
player._promoteToParentProxy?.();
expect(events).toHaveLength(1);
});
it("promotion mid-playback plays parent proxy immediately", () => {
// Previously-missing coverage: if the user is already playing when
// the runtime reports autoplay-blocked, the proxy must start audible
// right away — not wait for the user to hit pause/play again.
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.play(); // `_paused = false`, owner still `runtime` → no parent play yet
expect(mockAudio.play).not.toHaveBeenCalled();
player._promoteToParentProxy?.();
expect(mockAudio.play).toHaveBeenCalled();
});
it("surfaces playbackerror when parent proxy play() rejects", async () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
const rejection = Object.assign(new Error("blocked"), { name: "NotAllowedError" });
mockAudio.play = vi.fn().mockRejectedValueOnce(rejection);
const errors: unknown[] = [];
player.addEventListener("playbackerror", (e: Event) => {
errors.push((e as CustomEvent).detail);
});
player._promoteToParentProxy?.();
player.play();
// Promise rejection delivered on a microtask — flush.
await Promise.resolve();
await Promise.resolve();
expect(errors.length).toBeGreaterThan(0);
expect((errors[0] as { source: string }).source).toBe("parent-proxy");
});
it("playbackerror dedup: fires at most once per parent-ownership session", async () => {
// Under parent ownership with parent-also-blocked, every iframe
// paused→playing transition in the state loop re-invokes `_playParentMedia`.
// Without a latch, each rejection would re-fire `playbackerror`, spamming
// subscribers. Mirrors the runtime's `mediaAutoplayBlockedPosted` latch.
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
const rejection = Object.assign(new Error("blocked"), { name: "NotAllowedError" });
mockAudio.play = vi.fn().mockRejectedValue(rejection);
const errors: unknown[] = [];
player.addEventListener("playbackerror", (e: Event) => {
errors.push((e as CustomEvent).detail);
});
player._promoteToParentProxy?.();
player.play();
player.pause();
player.play();
player.pause();
player.play();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(errors).toHaveLength(1);
});
it("cleans up parent media on disconnect", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.remove();
expect(mockAudio.pause).toHaveBeenCalled();
expect(mockAudio.src).toBe("");
});
it("updates parent media when playback-rate changes after setup", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.setAttribute("playback-rate", "2");
expect(mockAudio.playbackRate).toBe(2);
});
it("updates parent media when muted toggles after setup", () => {
player.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(player);
player.setAttribute("muted", "");
expect(mockAudio.muted).toBe(true);
player.removeAttribute("muted");
expect(mockAudio.muted).toBe(false);
});
});
// ── Shader transition preview controls ──
//
// Shader transition capture scale and loading UI ownership are player-level
// preview concerns. The player forwards those options into the iframe before
// the composition runs, then renders transition-prep progress from runtime
// messages when `shader-loading="player"` is enabled.
describe("HyperframesPlayer shader transition options", () => {
type PlayerWithIframe = HTMLElement & {
iframeElement: HTMLIFrameElement;
};
beforeEach(async () => {
await import("./hyperframes-player.js");
});
afterEach(() => {
vi.useRealTimers();
document.body.innerHTML = "";
});
it("observes shader capture scale and loading attributes", () => {
const player = document.createElement("hyperframes-player");
const Ctor = player.constructor as typeof HTMLElement & {
observedAttributes: string[];
};
expect(Ctor.observedAttributes).toContain("shader-capture-scale");
expect(Ctor.observedAttributes).toContain("shader-loading");
});
it("passes shader options through src query parameters", () => {
const player = document.createElement("hyperframes-player") as PlayerWithIframe;
player.setAttribute("shader-capture-scale", "0.5");
player.setAttribute("shader-loading", "player");
player.setAttribute("src", "/api/projects/demo/preview?x=1#stage");
const url = new URL(player.iframeElement.src);
expect(url.pathname).toBe("/api/projects/demo/preview");
expect(url.searchParams.get("x")).toBe("1");
expect(url.searchParams.get("__hf_shader_capture_scale")).toBe("0.5");
expect(url.searchParams.get("__hf_shader_loading")).toBe("player");
expect(url.hash).toBe("#stage");
});
it("injects shader options into srcdoc before composition scripts run", () => {
const player = document.createElement("hyperframes-player") as PlayerWithIframe;
player.setAttribute("shader-capture-scale", "0.5");
player.setAttribute("shader-loading", "player");
player.setAttribute(
"srcdoc",
'<!doctype html><html><head><script src="composition.js"></script></head><body></body></html>',
);
const srcdoc = player.iframeElement.srcdoc;
expect(srcdoc).toContain('window.__HF_SHADER_CAPTURE_SCALE="0.5";');
expect(srcdoc).toContain('window.__HF_SHADER_LOADING="player";');
expect(srcdoc.indexOf("data-hyperframes-player-shader-options")).toBeLessThan(
srcdoc.indexOf("composition.js"),
);
});
it("shows and hides the player-owned shader loader from transition state messages", () => {
vi.useFakeTimers();
const player = document.createElement("hyperframes-player") as PlayerWithIframe;
player.setAttribute("shader-loading", "player");
document.body.appendChild(player);
const iframeWindow = player.iframeElement.contentWindow;
expect(iframeWindow).toBeTruthy();
window.dispatchEvent(
new MessageEvent("message", {
source: iframeWindow,
data: {
source: "hf-preview",
type: "shader-transition-state",
compositionId: "main",
state: {
loading: true,
progress: 3,
total: 10,
currentTransition: 1,
transitionTotal: 2,
transitionFrame: 3,
transitionFrames: 5,
phase: "capturing",
},
},
}),
);
const loader = player.shadowRoot?.querySelector(".hfp-shader-loader");
expect(loader?.classList.contains("hfp-visible")).toBe(true);
expect(loader?.textContent).toContain("1/2");
expect(loader?.textContent).toContain("3/5");
const playEvents: Event[] = [];
player.addEventListener("play", (event) => playEvents.push(event));
loader?.dispatchEvent(new MouseEvent("click", { bubbles: true, composed: true }));
expect(playEvents).toHaveLength(0);
window.dispatchEvent(
new MessageEvent("message", {
source: iframeWindow,
data: {
source: "hf-preview",
type: "shader-transition-state",
compositionId: "main",
state: { loading: false, ready: true },
},
}),
);
window.dispatchEvent(
new MessageEvent("message", {
source: iframeWindow,
data: {
source: "hf-preview",
type: "shader-transition-state",
compositionId: "main",
state: { loading: false, ready: true },
},
}),
);
expect(loader?.classList.contains("hfp-visible")).toBe(false);
expect(loader?.classList.contains("hfp-hiding")).toBe(true);
vi.advanceTimersByTime(420);
expect(loader?.classList.contains("hfp-hiding")).toBe(false);
vi.useRealTimers();
});
});
// ── Shared stylesheet (adoptedStyleSheets) ──
//
// Every player constructed in the same document should adopt the *same*
// CSSStyleSheet instance instead of getting its own <style> element. This is
// the studio thumbnail-grid win — N players, one parsed sheet.
describe("HyperframesPlayer adoptedStyleSheets", () => {
type AdoptingShadowRoot = ShadowRoot & { adoptedStyleSheets: CSSStyleSheet[] };
type PlayerWithShadow = HTMLElement & { shadowRoot: AdoptingShadowRoot | null };
beforeEach(async () => {
await import("./hyperframes-player.js");
});
afterEach(() => {
document.body.innerHTML = "";
});
it("shares a single CSSStyleSheet across multiple player instances", () => {
const a = document.createElement("hyperframes-player") as PlayerWithShadow;
const b = document.createElement("hyperframes-player") as PlayerWithShadow;
document.body.appendChild(a);
document.body.appendChild(b);
const sheetsA = a.shadowRoot?.adoptedStyleSheets ?? [];
const sheetsB = b.shadowRoot?.adoptedStyleSheets ?? [];
expect(sheetsA.length).toBeGreaterThan(0);
expect(sheetsB.length).toBeGreaterThan(0);
expect(sheetsA.at(-1)).toBe(sheetsB.at(-1));
});
it("does not inject a per-instance <style> when adoption succeeds", () => {
const player = document.createElement("hyperframes-player") as PlayerWithShadow;
document.body.appendChild(player);
expect(player.shadowRoot?.querySelector("style")).toBeNull();
});
});
// ── Media MutationObserver scoping ──
//
// The observer that catches late-attached `<audio data-start>` from
// sub-composition activation used to watch `iframe.contentDocument.body`
// wholesale. That fired on every body-level mutation — analytics scripts,
// runtime telemetry markers, dev-only overlays — even though only
// composition-tree changes can introduce new timed media. The fix is to
// scope per top-level composition host (see `selectMediaObserverTargets`);
// these tests verify the player honors that scoping.
describe("HyperframesPlayer media MutationObserver scoping", () => {
type PlayerInternal = HTMLElement & {
_observeDynamicMedia?: (doc: Document) => void;
};
beforeEach(async () => {
await import("./hyperframes-player.js");
});
afterEach(() => {
document.body.innerHTML = "";
vi.restoreAllMocks();
});
it("attaches the observer to each top-level composition host (not the body)", () => {
const observeSpy = vi.spyOn(MutationObserver.prototype, "observe");
const player = document.createElement("hyperframes-player") as PlayerInternal;
document.body.appendChild(player);
// The constructor doesn't install an observer — only `_observeDynamicMedia`
// does — so the spy starts clean for the call we care about.
observeSpy.mockClear();
// Simulates the iframe document the runtime hands the player after mount.
// Bypassing the iframe lifecycle keeps the test deterministic; the
// selection logic itself is exercised in `mediaObserverScope.test.ts`.
const fakeDoc = document.implementation.createHTMLDocument("test");
fakeDoc.body.innerHTML = `
<div data-composition-id="root-a"></div>
<div data-composition-id="root-b"></div>
<script>// runtime telemetry — body-level, must NOT be observed</script>
`;
player._observeDynamicMedia?.(fakeDoc);
expect(observeSpy).toHaveBeenCalledTimes(2);
const observedTargets = observeSpy.mock.calls.map((call) => call[0]);
expect(observedTargets.map((t) => (t as Element).getAttribute("data-composition-id"))).toEqual([
"root-a",
"root-b",
]);
expect(observedTargets).not.toContain(fakeDoc.body);
// Subtree is still required — sub-composition media can be deeply nested
// inside the host (e.g. wrapper div around the `<audio>`).
// Attribute observation on "preload" is required so the player creates
// parent proxies just-in-time when the preloader promotes a clip.
for (const call of observeSpy.mock.calls) {
expect(call[1]).toEqual({
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["preload"],
});
}
});
it("falls back to observing the document body when no composition hosts exist", () => {
// Preserves the legacy behavior for documents that haven't bootstrapped
// a composition tree yet (e.g. a blank iframe between src changes).
const observeSpy = vi.spyOn(MutationObserver.prototype, "observe");
const player = document.createElement("hyperframes-player") as PlayerInternal;
document.body.appendChild(player);
observeSpy.mockClear();
const fakeDoc = document.implementation.createHTMLDocument("test");
fakeDoc.body.innerHTML = `<div class="not-a-composition"></div>`;
player._observeDynamicMedia?.(fakeDoc);
expect(observeSpy).toHaveBeenCalledTimes(1);
expect(observeSpy.mock.calls[0]?.[0]).toBe(fakeDoc.body);
});
});
// ── Parent-proxy time-mirror coalescing ──
//
// `_mirrorParentMediaTime` is the steady-state correction loop that nudges
// every parent-frame audio/video proxy back onto the iframe's timeline. The
// post-`P1-4` contract: a single over-threshold sample (one slow bridge tick,
// one tab-throttled rAF, one GC pause) is absorbed by a per-proxy counter and
// does NOT cost a `currentTime` write. Only a *trending* drift — two
// consecutive samples above the 50 ms threshold — triggers a seek. Forced
// callers (audio-ownership promotion, brand-new proxy initialization) bypass
// the gate so the listener never hears a misaligned sample on cut-over.
describe("HyperframesPlayer parent-proxy time-mirror coalescing", () => {
type DriftEntry = {
el: { currentTime: number; src: string; pause: () => void };
start: number;
duration: number;
driftSamples: number;
};
type PlayerInternal = HTMLElement & {
_parentMedia: DriftEntry[];
_mirrorParentMediaTime: (timelineSeconds: number, options?: { force?: boolean }) => void;
_promoteToParentProxy?: () => void;
};
let player: PlayerInternal;
beforeEach(async () => {
await import("./hyperframes-player.js");
player = document.createElement("hyperframes-player") as PlayerInternal;
document.body.appendChild(player);
// No audio-src was set, so `_parentMedia` is empty. Tests push synthetic
// POJO entries — `_mirrorParentMediaTime` only reads/writes
// `el.currentTime`, so a plain object stands in fine for HTMLMediaElement.
});
afterEach(() => {
player.remove();
vi.restoreAllMocks();
});
function makeEntry(
opts: {
currentTime?: number;
start?: number;
duration?: number;
driftSamples?: number;
} = {},
): DriftEntry {
// Include `pause`/`src` so `disconnectedCallback`'s teardown loop
// (`m.el.pause(); m.el.src = ""`) doesn't blow up when the player is
// removed at the end of the test — `_mirrorParentMediaTime` itself only
// touches `currentTime`.
const entry: DriftEntry = {
el: {
currentTime: opts.currentTime ?? 0,
src: "",
pause: vi.fn(),
},
start: opts.start ?? 0,
duration: opts.duration ?? 100,
driftSamples: opts.driftSamples ?? 0,
};
player._parentMedia.push(entry);
return entry;
}
it("initializes new parent-media entries with driftSamples=0", () => {
// Mock Audio just for this test so the audio-src bootstrap path produces
// a real entry rather than throwing on construction.
const mockAudio = {
src: "",
preload: "",
muted: false,
playbackRate: 1,
currentTime: 0,
paused: true,
play: vi.fn().mockResolvedValue(undefined),
pause: vi.fn(),
load: vi.fn(),
};
vi.spyOn(globalThis, "Audio").mockImplementation(
() => mockAudio as unknown as HTMLAudioElement,
);
const fresh = document.createElement("hyperframes-player") as PlayerInternal;
fresh.setAttribute("audio-src", "https://cdn.example.com/narration.mp3");
document.body.appendChild(fresh);
expect(fresh._parentMedia).toHaveLength(1);
expect(fresh._parentMedia[0]?.driftSamples).toBe(0);
fresh.remove();
});
it("does nothing when drift is within the 50 ms threshold", () => {
const m = makeEntry({ currentTime: 5 });
player._mirrorParentMediaTime(5.04);
expect(m.el.currentTime).toBe(5);
expect(m.driftSamples).toBe(0);
});
it("absorbs a single over-threshold spike without writing currentTime", () => {
const m = makeEntry({ currentTime: 5 });
player._mirrorParentMediaTime(5.5);
expect(m.el.currentTime).toBe(5);
expect(m.driftSamples).toBe(1);
});
it("issues a seek on the second consecutive over-threshold sample", () => {
const m = makeEntry({ currentTime: 5 });
player._mirrorParentMediaTime(5.5);
expect(m.el.currentTime).toBe(5);
expect(m.driftSamples).toBe(1);
// Second sample with the same drift: the gate trips, the write fires,
// and the counter resets so the proxy doesn't re-seek every later tick.
player._mirrorParentMediaTime(5.5);
expect(m.el.currentTime).toBe(5.5);
expect(m.driftSamples).toBe(0);
});
it("resets the counter when a sample comes back within threshold", () => {
const m = makeEntry({ currentTime: 5 });
player._mirrorParentMediaTime(5.5);
expect(m.driftSamples).toBe(1);
// Recovery — counter must clear so a later isolated spike doesn't
// accidentally satisfy the 2-sample gate by piggy-backing on stale state.
player._mirrorParentMediaTime(5.02);
expect(m.driftSamples).toBe(0);
expect(m.el.currentTime).toBe(5);
player._mirrorParentMediaTime(5.5);
expect(m.driftSamples).toBe(1);
expect(m.el.currentTime).toBe(5);
});
it("force: true writes immediately on the first over-threshold sample", () => {
const m = makeEntry({ currentTime: 5 });
player._mirrorParentMediaTime(5.5, { force: true });
expect(m.el.currentTime).toBe(5.5);
expect(m.driftSamples).toBe(0);
});
it("force: true clears any pre-existing drift counter", () => {
const m = makeEntry({ currentTime: 5, driftSamples: 1 });
player._mirrorParentMediaTime(5.5, { force: true });
expect(m.el.currentTime).toBe(5.5);
expect(m.driftSamples).toBe(0);
});
it("does not seek out-of-range entries and resets their counters", () => {
// Active window [10, 15). currentTime=99 is a sentinel — if the function
// ever writes inside an out-of-range branch the test catches it because
// relTime would be 5 (or 15), not 99.
const m = makeEntry({
currentTime: 99,
start: 10,
duration: 5,
driftSamples: 5,
});
player._mirrorParentMediaTime(5);
expect(m.el.currentTime).toBe(99);
expect(m.driftSamples).toBe(0);
// Boundary: relTime === duration → still out of range (the loop uses `>=`).
m.driftSamples = 7;
player._mirrorParentMediaTime(15);
expect(m.el.currentTime).toBe(99);
expect(m.driftSamples).toBe(0);
});
it("tracks drift independently across multiple proxies", () => {
// a is drifted; b is aligned. A single tick must increment a's counter
// and reset b's — proving the per-entry state is genuinely per-entry.
const a = makeEntry({ currentTime: 5 });
const b = makeEntry({ currentTime: 7.01, driftSamples: 1 });
player._mirrorParentMediaTime(7);
expect(a.el.currentTime).toBe(5);
expect(a.driftSamples).toBe(1);
expect(b.el.currentTime).toBe(7.01);
expect(b.driftSamples).toBe(0);
});
it("force: true bypasses the gate for every proxy in a single sweep", () => {
const a = makeEntry({ currentTime: 5 });
const b = makeEntry({ currentTime: 8 });
player._mirrorParentMediaTime(7, { force: true });
expect(a.el.currentTime).toBe(7);
expect(b.el.currentTime).toBe(7);
expect(a.driftSamples).toBe(0);
expect(b.driftSamples).toBe(0);
});
it("_promoteToParentProxy invokes _mirrorParentMediaTime with force: true", () => {
// Integration check of the promotion call site — we cannot tolerate even
// ~80 ms of audible drift across an ownership flip, so the call site
// must opt out of the jitter gate.
const spy = vi.spyOn(player, "_mirrorParentMediaTime");
player._promoteToParentProxy?.();
const forcedCall = spy.mock.calls.find(([, opts]) => opts?.force === true);
expect(forcedCall).toBeDefined();
});
});
// ── Synchronous seek() with same-origin detection ──
//
// Studio has long reached past the postMessage bridge and called the runtime's
// `__player.seek` directly (`useTimelinePlayer.ts:233`) — that's the only way
// to land a scrubbed frame in the same task as the input event so the user
// sees no perceived lag. P3-1 promotes that pattern to a public API: the
// player element's own `seek()` now tries the same shortcut first, and only
// falls back to the async postMessage bridge when the iframe is genuinely
// cross-origin (or the runtime hasn't installed `__player` yet). The tests
// here stub `iframe.contentWindow` so we can exercise the branch matrix
// without booting an actual runtime.
describe("HyperframesPlayer seek() sync path", () => {
type SyncPlayerStub = {
seek?: (t: number) => void;
play?: () => void;
pause?: () => void;
};
type TimelineStub = {
duration: () => number;
time: () => number;
seek: (t: number) => void;
play: () => void;
pause: () => void;
};
type FakeContentWindow = {
__player?: SyncPlayerStub;
__timelines?: Record<string, TimelineStub>;
postMessage?: ReturnType<typeof vi.fn>;
};
type PlayerInternal = HTMLElement & {
seek: (t: number) => void;
play: () => void;
pause: () => void;
iframe: HTMLIFrameElement;
_currentTime: number;
};
let player: PlayerInternal;
beforeEach(async () => {
await import("./hyperframes-player.js");
player = document.createElement("hyperframes-player") as PlayerInternal;
document.body.appendChild(player);
});
afterEach(() => {
player.remove();
vi.restoreAllMocks();
});
// Replace the iframe's `contentWindow` getter so the test controls what the
// sync path sees. Passing `"throw"` simulates the cross-origin SecurityError
// a real browser raises when reading `contentWindow.<anything>`.
function stubContentWindow(stub: FakeContentWindow | "throw") {
Object.defineProperty(player.iframe, "contentWindow", {
configurable: true,
get() {
if (stub === "throw") throw new Error("SecurityError");
return stub;
},
});
}
it("calls __player.seek directly on the same-origin path", () => {
// The whole point of P3-1: when the runtime is reachable, scrubs land in
// the same task as the input. `postMessage` must NOT also fire — that
// would cause a duplicate, async re-seek a tick later.
const sync = vi.fn();
const post = vi.fn();
stubContentWindow({ __player: { seek: sync }, postMessage: post });
player.seek(12.5);
expect(sync).toHaveBeenCalledTimes(1);
expect(sync).toHaveBeenCalledWith(12.5);
expect(post).not.toHaveBeenCalled();
});
it("passes the raw time-in-seconds through, not a rounded frame number", () => {
// The postMessage bridge has to round to a frame at the wire boundary,
// but the in-process call accepts seconds directly — preserving the
// caller's precision for fractional scrubs.
const sync = vi.fn();
stubContentWindow({ __player: { seek: sync } });
player.seek(7.3333);
expect(sync).toHaveBeenCalledWith(7.3333);
});
it("falls back to postMessage when __player has not been installed yet", () => {
// Before the runtime bootstraps, `contentWindow` exists but `__player` is
// undefined. The fallback queues the seek via postMessage, which the
// runtime drains once `installRuntimeControlBridge` runs.
const post = vi.fn();
stubContentWindow({ postMessage: post });
player.seek(12.5);
expect(post).toHaveBeenCalledTimes(1);
expect(post).toHaveBeenCalledWith(
expect.objectContaining({
source: "hf-parent",
type: "control",
action: "seek",
frame: Math.round(12.5 * 30),
}),
"*",
);
});
it("seeks same-origin __timelines when no runtime bridge exists", () => {
const timeline: TimelineStub = {
duration: vi.fn(() => 5),
time: vi.fn(() => 0),
seek: vi.fn(),
play: vi.fn(),
pause: vi.fn(),
};
const post = vi.fn();
stubContentWindow({ __timelines: { main: timeline }, postMessage: post });
player.seek(2);
expect(timeline.seek).toHaveBeenCalledTimes(1);
expect(timeline.seek).toHaveBeenCalledWith(2);
expect(post).not.toHaveBeenCalled();
});
it("plays and pauses same-origin __timelines when no runtime bridge exists", () => {
const timeline: TimelineStub = {
duration: vi.fn(() => 5),
time: vi.fn(() => 0),
seek: vi.fn(),
play: vi.fn(),
pause: vi.fn(),
};
const post = vi.fn();
stubContentWindow({ __timelines: { main: timeline }, postMessage: post });
player.play();
player.pause();
expect(timeline.play).toHaveBeenCalledTimes(1);
expect(timeline.pause).toHaveBeenCalledTimes(1);
expect(post).not.toHaveBeenCalled();
});
it("pauses same-origin __timelines after seek while playing", () => {
const pause = vi.fn();
const timeline: TimelineStub = {
duration: vi.fn(() => 5),
time: vi.fn(() => 0),
seek: vi.fn(),
play: vi.fn(),
pause,
};
const post = vi.fn();
stubContentWindow({ __timelines: { main: timeline }, postMessage: post });
player.play();
pause.mockClear();
player.seek(2);
expect(timeline.seek).toHaveBeenCalledWith(2);
expect(pause).toHaveBeenCalledTimes(1);
expect(post).not.toHaveBeenCalled();
});
it("does not bypass an installed runtime bridge for direct __timelines playback", () => {
const timeline: TimelineStub = {
duration: vi.fn(() => 5),
time: vi.fn(() => 0),
seek: vi.fn(),
play: vi.fn(),
pause: vi.fn(),
};
const post = vi.fn();
stubContentWindow({
__player: { play: vi.fn(), pause: vi.fn() },
__timelines: { main: timeline },
postMessage: post,
});
player.play();
player.pause();
expect(timeline.play).not.toHaveBeenCalled();
expect(timeline.pause).not.toHaveBeenCalled();
expect(post).toHaveBeenCalledWith(expect.objectContaining({ action: "play" }), "*");
expect(post).toHaveBeenCalledWith(expect.objectContaining({ action: "pause" }), "*");
});
it("falls back to postMessage when __player exists but lacks seek()", () => {
// Defensive: a partial `__player` (e.g. older runtime, mocked stub) must
// not be assumed callable. `typeof seek !== "function"` guards this.
const post = vi.fn();
stubContentWindow({