diff --git a/packages/starpod/src/components/media/board.ts b/packages/starpod/src/components/media/board.ts index 6b8a1e6..0cfb49f 100644 --- a/packages/starpod/src/components/media/board.ts +++ b/packages/starpod/src/components/media/board.ts @@ -727,18 +727,27 @@ export function mountBoard(host: HTMLElement): Board { } const idle = window.requestIdleCallback ?? ((fn: () => void) => window.setTimeout(fn, 200)); const lean = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection?.saveData === true; - // A shelf that failed to load is asked for again when the card is open - // (at once if it is), then each time it opens: never in a loop. + // A shelf that failed to load is asked for again each time the card + // opens: never in a loop. let asked = false; + // Each opening of a failed card asks only through its own callback: one + // left waiting from an earlier opening goes quiet. + let opening = 0; const failed = signal(false); const stopAsking = effect(() => { - const due = failed.value || lean ? open() : currentTime.value > 0; + const isOpen = open(); + if (failed.value && !isOpen) { + asked = false; + opening++; + } + const due = failed.value || lean ? isOpen : currentTime.value > 0; if (asked || !due) { return; } asked = true; + const mine = opening; idle(() => { - if (stopped) { + if (stopped || mine !== opening) { return; } void loadShelf().then((ok) => { @@ -749,8 +758,6 @@ export function mountBoard(host: HTMLElement): Board { arrive(); stopAsking(); } else { - asked = false; - // Asked again once the card next opens (not while it is open now). failed.value = true; } }); diff --git a/packages/starpod/src/components/media/engine.ts b/packages/starpod/src/components/media/engine.ts index 38475ae..4124edb 100644 --- a/packages/starpod/src/components/media/engine.ts +++ b/packages/starpod/src/components/media/engine.ts @@ -23,6 +23,7 @@ import type Hls from 'hls.js'; import { flipFrom, registerFlipTargets } from '../../motion/propflip'; import { activeMedium, + anchorPositioning, currentEpisode, currentTime, isBuffering, @@ -83,6 +84,8 @@ let generation = 0; let stoppedAt = 0; /** The episode whose playhead the element holds, once its source is ready. */ let playhead: string | null = null; +/** Where the source being loaded starts; a seek or skip meanwhile moves it. */ +let startAt = 0; /** Fired on the element when a source is ready and its playhead placed. */ const READY = 'starpod:ready'; /** @@ -263,11 +266,16 @@ async function loadSource( const video = element!; const source = ++generation; const sameEpisode = loaded?.id === episode.id; - // Switching medium mid-episode keeps the visitor's place; a new episode - // resumes where they left it last time; a retry, where it stopped. - const startAt = + // Switching medium mid-episode keeps the visitor's place (still pending in + // startAt if the source isn't ready yet); a new episode resumes where they + // left it last time; a retry, where it stopped. + startAt = retry?.at ?? - (sameEpisode ? video.currentTime : resumePoint(episode.id)); + (sameEpisode + ? playhead === episode.id + ? video.currentTime + : startAt + : resumePoint(episode.id)); if (retry) { isPlaying.value = retry.resume; } @@ -278,8 +286,10 @@ async function loadSource( playhead = null; delete video.dataset.ready; if (video.currentSrc) { - // The old source's pause on the way out is not the visitor's. + // The old source's pause on the way out is not the visitor's. Paused + // now, it can't play on past startAt while hls.js loads. swapping = true; + video.pause(); } if (!sameEpisode && video.currentSrc) { // Let go of the last episode before anything waits (hls.js is imported @@ -337,7 +347,7 @@ async function loadSource( return; } swapping = false; - if (startAt > 0 && Math.abs(video.currentTime - startAt) > 1) { + if (Math.abs(video.currentTime - startAt) > 1) { video.currentTime = startAt; } playhead = episode.id; @@ -386,21 +396,28 @@ function setMediaSession(episode: PlayableEpisode) { } } +/** Is the current episode's source still loading (its playhead is startAt)? */ +const loading = () => playhead !== currentEpisode.peek()?.id; + export function skip(seconds: number) { if (!element) { return; } const max = Number.isFinite(element.duration) ? element.duration : Infinity; - element.currentTime = Math.max(0, Math.min(max, element.currentTime + seconds)); - currentTime.value = element.currentTime; + seek(Math.max(0, Math.min(max, (loading() ? startAt : element.currentTime) + seconds))); } /** Seek without changing play/pause (the scrubber). */ export function seek(seconds: number) { - if (element) { + if (!element) { + return; + } + if (loading()) { + startAt = seconds; + } else { element.currentTime = seconds; - currentTime.value = seconds; } + currentTime.value = seconds; } /** Is the media element (or its container) showing fullscreen right now? */ @@ -500,8 +517,6 @@ function decideStation(fresh = false): Station { : 'corner'; } -// Flights and anchors need anchor positioning to target a home that scrolls. -const canAnchor = () => globalThis.CSS?.supports?.('anchor-name: --a') ?? false; let flight = 0; // Where the picture was on the page being navigated away from. let departure: DOMRect | null = null; @@ -574,9 +589,10 @@ export function placeMedia(mode?: 'again') { park(outer, station); return; } - // With nowhere to fly from, the box would only grow on its new home from - // the size it was parked at. - if (home && (!canAnchor() || !from?.width)) { + // Flights need anchor positioning to target a home that scrolls. With + // nowhere to fly from, the box would only grow on its new home from the + // size it was parked at. + if (home && (!anchorPositioning.value || !from?.width)) { moveInto(home); park(outer, station); return; diff --git a/tests/unit/engine-sources.test.ts b/tests/unit/engine-sources.test.ts index c3a098c..df590f9 100644 --- a/tests/unit/engine-sources.test.ts +++ b/tests/unit/engine-sources.test.ts @@ -15,9 +15,16 @@ vi.mock('../../packages/starpod/node_modules/hls.js', () => { return { default: FakeHls }; }); -import { setRate, startEngine } from 'starpod/src/components/media/engine'; +import { seek, setRate, skip, startEngine } from 'starpod/src/components/media/engine'; import { POSITION_PREFIX } from 'starpod/src/components/media/position'; -import { currentEpisode, isPlaying, seekTo, setMedium } from 'starpod/src/components/state'; +import { + anchorPositioning, + currentEpisode, + isPlaying, + miniClosed, + seekTo, + setMedium +} from 'starpod/src/components/state'; const episode = (id: string, video: false | 'hls' | 'mp4' | true = false) => ({ id, @@ -39,11 +46,15 @@ let video: HTMLVideoElement; let time = 0; let ready = 0; let failure: { code: number } | null = null; +let paused = true; const load = vi.fn(() => { failure = null; ready = 0; }); -const play = vi.fn(() => Promise.resolve()); +const play = vi.fn(() => { + paused = false; + return Promise.resolve(); +}); beforeAll(() => { Object.defineProperty(navigator, 'mediaSession', { @@ -65,7 +76,9 @@ beforeAll(() => { ); vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(load); vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(play); - vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}); + vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => { + paused = true; + }); const make = document.createElement.bind(document); const spy = vi.spyOn(document, 'createElement').mockImplementation((tag: string, options?: ElementCreationOptions) => { const element = make(tag, options); @@ -233,4 +246,95 @@ describe('the engine', () => { video.dispatchEvent(new Event('pause')); expect(localStorage.getItem(POSITION_PREFIX + 'pause-save')).toBe('103'); }); + + it('starts the video where the audio got to when Watch is chosen', async () => { + currentEpisode.value = episode('to-watch', true); + isPlaying.value = true; + arrive(); + time = 100; + setMedium('watch'); + // The MP3 plays on while hls.js loads, unless it was stopped. + if (!paused) { + time = 130; + } + const heard = time; + await vi.waitFor(() => expect(video.getAttribute('src')).toBe('blob:stream')); + arrive(); + expect(time).toBe(heard); + }); + + it('keeps a scrub made while loading when Watch is chosen before it is ready', async () => { + currentEpisode.value = episode('scrub-watch', true); + time = 0; + seek(600); + setMedium('watch'); + await vi.waitFor(() => expect(video.getAttribute('src')).toBe('blob:stream')); + arrive(); + expect(time).toBe(600); + }); + + it('keeps a skip made while the next episode loads', () => { + localStorage.setItem(POSITION_PREFIX + 'skip-b', '200'); + currentEpisode.value = episode('skip-a'); + arrive(); + time = 50; + currentEpisode.value = episode('skip-b'); + time = 0; + skip(30); + arrive(); + expect(time).toBe(230); + expect(isPlaying.value).toBe(false); + }); + + it('keeps a scrub made while the next episode loads', () => { + localStorage.setItem(POSITION_PREFIX + 'scrub-b', '200'); + currentEpisode.value = episode('scrub-a'); + arrive(); + currentEpisode.value = episode('scrub-b'); + time = 0; + seek(600); + arrive(); + expect(time).toBe(600); + expect(isPlaying.value).toBe(false); + }); + + it('places the picture without a flight where the player has no anchor positioning', () => { + const css = Object.getOwnPropertyDescriptor(globalThis, 'CSS'); + // The browser's own check would say yes; the player's homes say no. + Object.defineProperty(globalThis, 'CSS', { + configurable: true, + value: { supports: () => true, escape: (value: string) => value } + }); + anchorPositioning.value = false; + // A flight never finishes here, so a picture that flew stays in the box. + const animations = Object.getOwnPropertyDescriptor(Element.prototype, 'getAnimations'); + Object.defineProperty(Element.prototype, 'getAnimations', { + configurable: true, + value: () => [{ finished: new Promise(() => {}) }] + }); + document.body.innerHTML = + '
'; + try { + setMedium('watch'); + currentEpisode.value = episode('no-anchor', 'mp4'); + expect(video.parentElement).toBe(document.querySelector('[data-media-dock]')); + video.getBoundingClientRect = () => new DOMRect(0, 0, 160, 90); + miniClosed.value = true; + expect(video.parentElement).toBe(document.querySelector('[data-media-cell]')); + } finally { + miniClosed.value = false; + anchorPositioning.value = true; + document.body.replaceChildren(); + if (animations) { + Object.defineProperty(Element.prototype, 'getAnimations', animations); + } else { + delete (Element.prototype as { getAnimations?: unknown }).getAnimations; + } + if (css) { + Object.defineProperty(globalThis, 'CSS', css); + } else { + delete (globalThis as { CSS?: unknown }).CSS; + } + } + }); }); diff --git a/tests/unit/queue.test.tsx b/tests/unit/queue.test.tsx index a4ecfd6..5a082e1 100644 --- a/tests/unit/queue.test.tsx +++ b/tests/unit/queue.test.tsx @@ -188,6 +188,63 @@ describe('the Up next board', () => { await waitFor(() => expect(fetched).toHaveBeenCalledTimes(1)); }); + it('asks for a shelf that failed again each time the card opens, not while it stays open', async () => { + stop(); + document.body.replaceChildren(); + const fetched = vi.fn(async () => ({ ok: false, status: 503 })); + vi.stubGlobal('fetch', fetched); + vi.resetModules(); + const fresh = await import('starpod/src/components/media/board'); + const state = await import('starpod/src/components/state'); + state.currentEpisode.value = episode(1); + state.currentTime.value = 1; + state.islandHome.value = 'card'; + const host = document.createElement('div'); + document.body.append(host); + stop = fresh.mountBoard(host).stop; + await waitFor(() => expect(fetched).toHaveBeenCalledTimes(1)); + await new Promise((done) => setTimeout(done, 500)); + expect(fetched).toHaveBeenCalledTimes(1); + + act(() => { + state.islandHome.value = 'dock'; + }); + act(() => { + state.islandHome.value = 'card'; + }); + await waitFor(() => expect(fetched).toHaveBeenCalledTimes(2)); + }); + + it('asks once for a failed shelf when the card closes and opens again before asking', async () => { + stop(); + document.body.replaceChildren(); + const fetched = vi.fn(async () => ({ ok: false, status: 503 })); + vi.stubGlobal('fetch', fetched); + vi.resetModules(); + const fresh = await import('starpod/src/components/media/board'); + const state = await import('starpod/src/components/state'); + state.currentEpisode.value = episode(1); + state.currentTime.value = 1; + state.islandHome.value = 'card'; + const host = document.createElement('div'); + document.body.append(host); + stop = fresh.mountBoard(host).stop; + await waitFor(() => expect(fetched).toHaveBeenCalledTimes(1)); + + // Two openings in quick succession: only the last one's ask goes out. + for (let i = 0; i < 2; i++) { + act(() => { + state.islandHome.value = 'dock'; + }); + act(() => { + state.islandHome.value = 'card'; + }); + } + await waitFor(() => expect(fetched).toHaveBeenCalledTimes(2)); + await new Promise((done) => setTimeout(done, 500)); + expect(fetched).toHaveBeenCalledTimes(2); + }); + it('gives every episode one cover that fills a slot by name, and never moves it in the DOM', async () => { await waitFor(() => expect(fill('ep-5')).toBe('--slot-s0')); expect(fill('ep-1')).toBe('--slot-now');