Sync shared snapshot from 9e58b6d
This commit is contained in:
1 parent
36ab01aab1
commit
5a4bf45bc7
10 files changed
+393
-51
No files matched your search
@@ -9,7 +9,7 @@
|
||||
|
||||
let {
|
||||
kind = 'video',
|
||||
src = '',
|
||||
src,
|
||||
poster = '',
|
||||
title = '',
|
||||
autoplay = false,
|
||||
@@ -35,6 +35,12 @@
|
||||
onSkip,
|
||||
onQualityChange,
|
||||
onToggleGraph,
|
||||
storageKey = '',
|
||||
showSpeed = true,
|
||||
controls = true,
|
||||
element = $bindable(null),
|
||||
preload = 'auto',
|
||||
crossorigin,
|
||||
endControls,
|
||||
}: {
|
||||
kind?: MediaPlayerKind
|
||||
@@ -66,6 +72,24 @@
|
||||
onSkip?: (seconds: number) => void
|
||||
onQualityChange?: (value: string) => void
|
||||
onToggleGraph?: () => void
|
||||
/**
|
||||
* Turns on resume: the position of each source is saved in localStorage under this prefix and
|
||||
* restored when the source loads. Give each app its own prefix. Empty (the default) keeps
|
||||
* playback position out of browser storage.
|
||||
*/
|
||||
storageKey?: string
|
||||
/** Offers the playback speed in the settings menu. */
|
||||
showSpeed?: boolean
|
||||
/**
|
||||
* False renders the element with no player controls, surface clicks, keyboard handling or
|
||||
* fullscreen tracking. The caller then drives playback itself, through `element`, and may set
|
||||
* the element's `src` directly: this component leaves `src` alone when none is passed.
|
||||
*/
|
||||
controls?: boolean
|
||||
/** The media element, once mounted. Cleared when it goes. */
|
||||
element?: HTMLMediaElement | null
|
||||
preload?: 'none' | 'metadata' | 'auto'
|
||||
crossorigin?: 'anonymous' | 'use-credentials'
|
||||
endControls?: Snippet
|
||||
} = $props()
|
||||
|
||||
@@ -81,12 +105,19 @@
|
||||
let orientationLocked = $state(false)
|
||||
let controlsHideTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
let orientationLockRequest = 0
|
||||
let playbackRate = $state(1)
|
||||
let lastProgressSaveAt = 0
|
||||
const PROGRESS_SAVE_INTERVAL_MS = 1500
|
||||
|
||||
const currentTime = $derived(externalCurrentTime ?? internalTime)
|
||||
const duration = $derived(externalDuration ?? internalDuration)
|
||||
const audio = $derived(kind === 'audio')
|
||||
const controlsHideDelay = 2500
|
||||
|
||||
$effect(() => {
|
||||
element = mediaElement
|
||||
})
|
||||
|
||||
function clearControlsHideTimer() {
|
||||
if (controlsHideTimeout === null) return
|
||||
clearTimeout(controlsHideTimeout)
|
||||
@@ -195,6 +226,65 @@
|
||||
skip(event.clientX - bounds.left < bounds.width / 2 ? -10 : 10)
|
||||
}
|
||||
|
||||
function progressKey() {
|
||||
return `${storageKey}:${src}`
|
||||
}
|
||||
|
||||
function restorePlaybackProgress() {
|
||||
if (!storageKey || !mediaElement) return
|
||||
try {
|
||||
const savedProgress = Number(window.localStorage.getItem(progressKey()))
|
||||
const length = mediaElement.duration
|
||||
if (
|
||||
Number.isFinite(savedProgress) &&
|
||||
savedProgress > 0 &&
|
||||
Number.isFinite(length) &&
|
||||
length > 0 &&
|
||||
savedProgress < length - 1
|
||||
) {
|
||||
mediaElement.currentTime = savedProgress
|
||||
}
|
||||
} catch {
|
||||
// Playback remains available when browser storage is disabled or full.
|
||||
}
|
||||
}
|
||||
|
||||
function savePlaybackProgress(force = false) {
|
||||
if (!storageKey || !mediaElement || mediaElement.ended) return
|
||||
const position = mediaElement.currentTime
|
||||
if (!Number.isFinite(position)) return
|
||||
try {
|
||||
if (position <= 0) {
|
||||
if (force) window.localStorage.removeItem(progressKey())
|
||||
return
|
||||
}
|
||||
if (!force && Date.now() - lastProgressSaveAt < PROGRESS_SAVE_INTERVAL_MS) return
|
||||
lastProgressSaveAt = Date.now()
|
||||
window.localStorage.setItem(progressKey(), String(position))
|
||||
} catch {
|
||||
// Keep playing when browser storage is disabled or full.
|
||||
}
|
||||
}
|
||||
|
||||
function clearPlaybackProgress() {
|
||||
if (!storageKey) return
|
||||
try {
|
||||
window.localStorage.removeItem(progressKey())
|
||||
} catch {
|
||||
// Keep playback completion independent from browser storage.
|
||||
}
|
||||
}
|
||||
|
||||
function changeSpeed(value: number) {
|
||||
if (!Number.isFinite(value) || value <= 0) return
|
||||
playbackRate = value
|
||||
if (mediaElement) mediaElement.playbackRate = value
|
||||
}
|
||||
|
||||
function handleSeeked() {
|
||||
savePlaybackProgress(true)
|
||||
}
|
||||
|
||||
function handlePlay(event: Event) {
|
||||
playing = true
|
||||
onPlay?.(event)
|
||||
@@ -203,11 +293,13 @@
|
||||
function handlePause(event: Event) {
|
||||
playing = false
|
||||
controlsVisible = true
|
||||
savePlaybackProgress(true)
|
||||
onPause?.(event)
|
||||
}
|
||||
|
||||
function handleTimeUpdate(event: Event) {
|
||||
if (mediaElement) internalTime = mediaElement.currentTime || 0
|
||||
savePlaybackProgress()
|
||||
onTimeUpdate?.(event)
|
||||
}
|
||||
|
||||
@@ -216,13 +308,17 @@
|
||||
internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0
|
||||
volume = mediaElement.volume
|
||||
muted = mediaElement.muted || mediaElement.volume === 0
|
||||
void syncScreenOrientation(fullscreen)
|
||||
// Loading a source resets the rate, so the chosen speed is applied again.
|
||||
mediaElement.playbackRate = playbackRate
|
||||
restorePlaybackProgress()
|
||||
if (controls) void syncScreenOrientation(fullscreen)
|
||||
onLoadedMetadata?.(event)
|
||||
}
|
||||
|
||||
function handleEnded(event: Event) {
|
||||
playing = false
|
||||
controlsVisible = true
|
||||
clearPlaybackProgress()
|
||||
onEnded?.(event)
|
||||
}
|
||||
|
||||
@@ -287,6 +383,7 @@
|
||||
}
|
||||
|
||||
function handleFullscreenChange() {
|
||||
if (!controls) return
|
||||
fullscreen = Boolean(document.fullscreenElement)
|
||||
void syncScreenOrientation(fullscreen)
|
||||
}
|
||||
@@ -311,7 +408,7 @@
|
||||
})
|
||||
|
||||
onMount(() => {
|
||||
if (!playerFrame) return
|
||||
if (!controls || !playerFrame) return
|
||||
|
||||
const activityEvents = ['mousemove', 'click', 'keydown', 'focusin', 'touchstart'] as const
|
||||
for (const eventName of activityEvents) playerFrame.addEventListener(eventName, handlePlayerActivity)
|
||||
@@ -329,15 +426,15 @@
|
||||
|
||||
<svelte:window onfullscreenchange={handleFullscreenChange} />
|
||||
|
||||
<div bind:this={playerFrame} class={`media-player ${className}`}>
|
||||
<div bind:this={playerFrame} class={controls ? `media-player ${className}` : className}>
|
||||
{#if audio}
|
||||
<div
|
||||
class="media-player-audio-surface"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
aria-label={title ? `Audio player for ${title}` : 'Audio player'}
|
||||
onclick={handleSurfaceClick}
|
||||
onkeydown={handleKeydown}
|
||||
onclick={controls ? handleSurfaceClick : undefined}
|
||||
onkeydown={controls ? handleKeydown : undefined}
|
||||
>
|
||||
<Music2 class="media-player-audio-icon" />
|
||||
{#if title}<span>{title}</span>{/if}
|
||||
@@ -346,7 +443,7 @@
|
||||
bind:this={mediaElement}
|
||||
{src}
|
||||
{autoplay}
|
||||
preload="auto"
|
||||
{preload}
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
onplay={handlePlay}
|
||||
@@ -355,6 +452,7 @@
|
||||
onloadedmetadata={handleLoadedMetadata}
|
||||
onended={handleEnded}
|
||||
onvolumechange={handleVolumeChange}
|
||||
onseeked={handleSeeked}
|
||||
onerror={handleError}
|
||||
></audio>
|
||||
{:else}
|
||||
@@ -366,25 +464,28 @@
|
||||
{poster}
|
||||
{autoplay}
|
||||
muted={autoplay && autoplayMuted}
|
||||
preload="auto"
|
||||
{preload}
|
||||
{crossorigin}
|
||||
playsinline
|
||||
tabindex="0"
|
||||
class={`media-player-video ${mediaClass}`}
|
||||
tabindex={controls ? 0 : undefined}
|
||||
class={[controls && 'media-player-video', mediaClass].filter(Boolean).join(' ')}
|
||||
aria-label={title ? `Video player for ${title}` : 'Video player'}
|
||||
onclick={handleSurfaceClick}
|
||||
ondblclick={handleVideoDoubleTap}
|
||||
onkeydown={handleKeydown}
|
||||
onclick={controls ? handleSurfaceClick : undefined}
|
||||
ondblclick={controls ? handleVideoDoubleTap : undefined}
|
||||
onkeydown={controls ? handleKeydown : undefined}
|
||||
onplay={handlePlay}
|
||||
onpause={handlePause}
|
||||
ontimeupdate={handleTimeUpdate}
|
||||
onloadedmetadata={handleLoadedMetadata}
|
||||
onended={handleEnded}
|
||||
onvolumechange={handleVolumeChange}
|
||||
onseeked={handleSeeked}
|
||||
onerror={handleError}
|
||||
>
|
||||
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT%0A" />
|
||||
</video>
|
||||
{/if}
|
||||
{#if controls}
|
||||
<MediaPlayerControls
|
||||
{kind}
|
||||
{currentTime}
|
||||
@@ -408,8 +509,12 @@
|
||||
{onQualityChange}
|
||||
{onToggleGraph}
|
||||
{endControls}
|
||||
{showSpeed}
|
||||
{playbackRate}
|
||||
onSpeedChange={changeSpeed}
|
||||
overlay
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -31,6 +31,8 @@
|
||||
graphVisible = false,
|
||||
qualityOptions = [],
|
||||
selectedQuality = '',
|
||||
showSpeed = true,
|
||||
playbackRate = 1,
|
||||
onTogglePlayback,
|
||||
onSeek,
|
||||
onSkip: _onSkip,
|
||||
@@ -39,6 +41,7 @@
|
||||
onToggleFullscreen,
|
||||
onToggleGraph,
|
||||
onQualityChange,
|
||||
onSpeedChange,
|
||||
endControls,
|
||||
}: {
|
||||
kind?: MediaPlayerKind
|
||||
@@ -68,9 +71,14 @@
|
||||
onToggleFullscreen?: () => void | Promise<void>
|
||||
onToggleGraph?: () => void
|
||||
onQualityChange?: (value: string) => void
|
||||
showSpeed?: boolean
|
||||
playbackRate?: number
|
||||
onSpeedChange?: (value: number) => void
|
||||
endControls?: Snippet
|
||||
} = $props()
|
||||
|
||||
const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2]
|
||||
|
||||
let settingsMenu = $state<HTMLDivElement | null>(null)
|
||||
let settingsOpen = $state(false)
|
||||
|
||||
@@ -100,6 +108,11 @@
|
||||
settingsOpen = false
|
||||
}
|
||||
|
||||
function handleSpeed(event: Event) {
|
||||
onSpeedChange?.(Number((event.currentTarget as HTMLSelectElement).value))
|
||||
settingsOpen = false
|
||||
}
|
||||
|
||||
function handleDocumentPointerDown(event: PointerEvent) {
|
||||
if (settingsOpen && !settingsMenu?.contains(event.target as Node)) settingsOpen = false
|
||||
}
|
||||
@@ -176,7 +189,7 @@
|
||||
<span class="media-player-time">{formatTime(currentTime)} / {formatTime(duration)}</span>
|
||||
<div class="media-player-control-trailing">
|
||||
{@render endControls?.()}
|
||||
{#if showGraph || qualityOptions.length > 0}
|
||||
{#if showGraph || qualityOptions.length > 0 || showSpeed}
|
||||
<div bind:this={settingsMenu} class="media-player-settings">
|
||||
<button
|
||||
type="button"
|
||||
@@ -215,6 +228,16 @@
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
{#if showSpeed}
|
||||
<label class="media-player-settings-quality">
|
||||
<span>Speed</span>
|
||||
<select value={String(playbackRate)} aria-label="Playback speed" {disabled} onchange={handleSpeed}>
|
||||
{#each SPEEDS as speed (speed)}
|
||||
<option value={String(speed)}>{speed}x</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import MediaPlayer from '../src/lib/components/MediaPlayer.svelte';
|
||||
import MediaPlayerHost from './fixtures/MediaPlayerHost.svelte';
|
||||
|
||||
afterEach(cleanup);
|
||||
beforeEach(() => window.localStorage.clear());
|
||||
|
||||
const SOURCE = 'https://media.example/clip.mp4';
|
||||
|
||||
const videoElement = (): HTMLVideoElement => {
|
||||
const element = document.querySelector<HTMLVideoElement>('video');
|
||||
if (!element) throw new Error('no video element');
|
||||
return element;
|
||||
};
|
||||
|
||||
// jsdom does not load or play media, so position, length and rate are set by hand.
|
||||
function setMedia(element: HTMLVideoElement, media: { currentTime: number; duration: number }) {
|
||||
Object.defineProperty(element, 'currentTime', { configurable: true, writable: true, value: media.currentTime });
|
||||
Object.defineProperty(element, 'duration', { configurable: true, value: media.duration });
|
||||
Object.defineProperty(element, 'playbackRate', { configurable: true, writable: true, value: 1 });
|
||||
}
|
||||
|
||||
describe('MediaPlayer resume', () => {
|
||||
it('saves the position under the storage key when playback pauses', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', storageKey: 'app-progress' } });
|
||||
setMedia(videoElement(), { currentTime: 42, duration: 100 });
|
||||
|
||||
await fireEvent.pause(videoElement());
|
||||
|
||||
expect(window.localStorage.getItem(`app-progress:${SOURCE}`)).toBe('42');
|
||||
});
|
||||
|
||||
it('resumes from the saved position once the metadata has loaded', async () => {
|
||||
window.localStorage.setItem(`app-progress:${SOURCE}`, '30');
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', storageKey: 'app-progress' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
|
||||
await fireEvent.loadedMetadata(element);
|
||||
|
||||
expect(element.currentTime).toBe(30);
|
||||
});
|
||||
|
||||
it('ignores a saved position at the very end of the video', async () => {
|
||||
window.localStorage.setItem(`app-progress:${SOURCE}`, '99.5');
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', storageKey: 'app-progress' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
|
||||
await fireEvent.loadedMetadata(element);
|
||||
|
||||
expect(element.currentTime).toBe(0);
|
||||
});
|
||||
|
||||
it('does not read or write browser storage without a storage key', async () => {
|
||||
window.localStorage.setItem(`${SOURCE}`, '30');
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 42, duration: 100 });
|
||||
|
||||
await fireEvent.loadedMetadata(element);
|
||||
await fireEvent.pause(element);
|
||||
|
||||
expect(element.currentTime).toBe(42);
|
||||
expect(window.localStorage.getItem(SOURCE)).toBe('30');
|
||||
expect(window.localStorage.length).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps separate storage keys apart so apps do not share positions', async () => {
|
||||
window.localStorage.setItem(`other-app:${SOURCE}`, '50');
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', storageKey: 'app-progress' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
|
||||
await fireEvent.loadedMetadata(element);
|
||||
|
||||
expect(element.currentTime).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MediaPlayer speed', () => {
|
||||
it('applies a speed chosen in the settings menu to the video straight away', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Player settings' }));
|
||||
await fireEvent.change(screen.getByRole('combobox', { name: 'Playback speed' }), { target: { value: '1.25' } });
|
||||
|
||||
expect(element.playbackRate).toBe(1.25);
|
||||
});
|
||||
|
||||
it('reapplies the chosen speed when a source loads', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip' } });
|
||||
const element = videoElement();
|
||||
setMedia(element, { currentTime: 0, duration: 100 });
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Player settings' }));
|
||||
await fireEvent.change(screen.getByRole('combobox', { name: 'Playback speed' }), { target: { value: '2' } });
|
||||
element.playbackRate = 1;
|
||||
|
||||
await fireEvent.loadedMetadata(element);
|
||||
|
||||
expect(element.playbackRate).toBe(2);
|
||||
});
|
||||
|
||||
it('hides the speed choice when showSpeed is off', async () => {
|
||||
render(MediaPlayer, { props: { kind: 'video', src: SOURCE, title: 'Clip', showSpeed: false } });
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Player settings' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MediaPlayer without controls', () => {
|
||||
it('renders the element with no player controls and leaves its src to the caller', () => {
|
||||
render(MediaPlayer, { props: { controls: false, kind: 'video' } });
|
||||
|
||||
expect(screen.queryByRole('slider')).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Player settings' })).toBeNull();
|
||||
expect(videoElement().hasAttribute('src')).toBe(false);
|
||||
});
|
||||
|
||||
it('hands the mounted element back through the element binding', async () => {
|
||||
const onElement = vi.fn();
|
||||
render(MediaPlayerHost, { props: { onElement } });
|
||||
|
||||
await waitFor(() => expect(onElement).toHaveBeenCalledWith(expect.any(HTMLVideoElement)));
|
||||
expect(onElement.mock.calls.at(-1)?.[0]).toBe(videoElement());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
<script lang="ts">
|
||||
import MediaPlayer from '../../src/lib/components/MediaPlayer.svelte';
|
||||
|
||||
// Mirrors how an app drives the element itself: no controls, and the element is handed back.
|
||||
let { onElement }: { onElement: (element: HTMLMediaElement | null) => void } = $props();
|
||||
let element = $state<HTMLMediaElement | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
onElement(element);
|
||||
});
|
||||
</script>
|
||||
|
||||
<MediaPlayer controls={false} bind:element />
|
||||
Reference in new issue
Block a user