Sync shared snapshot from 9e58b6d
Security / Secrets (gitleaks) (push) Successful in 2m3s
Security / Code (Semgrep) (push) Successful in 2m22s
Security / Dependencies (Trivy) (push) Successful in 1m16s
Docker / Docker Build & Push (push) Successful in 7m40s

This commit is contained in:
Claude Code committed 2026-11-18 14:00:13 +01:00
1 parent 36ab01aab1
commit 5a4bf45bc7
10 files changed
+388 -46

No files matched your search

+6 -1
View File
@@ -6,13 +6,16 @@ on:
pull_request:
branches: [main, master]
schedule:
# Weekly, so advisories published after the last push still get reported.
# Daily, for the Trivy job, so advisories published after the last push still get reported.
- cron: '23 5 * * *'
# Weekly, for the secrets and code jobs. Each job's if: condition picks the entry that runs it.
- cron: '23 5 * * 1'
workflow_dispatch: {}
jobs:
secrets:
name: Secrets (gitleaks)
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -35,6 +38,7 @@ jobs:
code:
name: Code (Semgrep)
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -55,6 +59,7 @@ jobs:
dependencies:
name: Dependencies (Trivy)
if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * *'
runs-on: ubuntu-latest
permissions:
contents: read
+1 -1
View File
@@ -75,7 +75,7 @@ These are the complete Svelte component exports from `packages/web-ui/src/lib/in
| Component | Includes |
|---|---|
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
| `MediaPlayer` | Audio/video player with playback, seeking, volume, speed, quality, fullscreen, keyboard controls, custom end controls, and optional resume from the saved position (`storageKey`, per app). With `controls={false}` it is just the element, returned through `element`, for apps that drive playback themselves and set `src` on it. |
#### Accounts and access
+26 -12
View File
@@ -135,7 +135,23 @@ func (c *Service) streamMediaIdentifier(w http.ResponseWriter, r *http.Request,
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+upstream)
c.carrierNode.Proxy(w, r, streamUpstreamPath(upstream, r.URL.Query()))
}
// streamUpstreamPath is the CarrierNode request path for a stream. CarrierNode answers with a live
// H.264 copy when the query carries quality (a height) and start (seconds), which is how browsers get
// containers they cannot decode. Those two parameters are the only ones forwarded.
func streamUpstreamPath(upstream string, query url.Values) string {
forward := url.Values{}
for _, key := range []string{"quality", "start"} {
if value := strings.TrimSpace(query.Get(key)); value != "" {
forward.Set(key, value)
}
}
if len(forward) == 0 {
return "/media/" + upstream
}
return "/media/" + upstream + "?" + forward.Encode()
}
func (c *Service) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) {
@@ -911,21 +927,19 @@ func urlPath(value string) string {
return value
}
// upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false
// when the stored path is not a safe relative path, or when it contains a query or fragment marker
// that CarrierNode would read as the end of the path.
// upstreamMediaPath returns the CarrierNode path for a stored file path. It reports false only when
// the stored path is not a safe relative path.
//
// url.PathEscape would write a comma as %2C, and the request then keeps that escape as a raw path.
// CarrierNode's router matches a raw path literally, so "Hello, World.mp4" would never be found. A
// URL built from Path alone leaves no raw path, so the name reaches CarrierNode decoded. Query and
// fragment markers are escaped the same way, so they no longer need refusing.
func upstreamMediaPath(filePath string) (string, bool) {
relative := urlPath(filePath)
if !files.SafeRelative(relative) || strings.ContainsAny(relative, "?#") {
if !files.SafeRelative(relative) {
return "", false
}
// Escape each segment so percent-escapes and other reserved characters in a stored name
// reach CarrierNode as literal text, not as an escape or a traversal it decodes later.
segments := strings.Split(relative, "/")
for i, segment := range segments {
segments[i] = url.PathEscape(segment)
}
return strings.Join(segments, "/"), true
return (&url.URL{Path: relative}).EscapedPath(), true
}
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
+18
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
@@ -124,3 +125,20 @@ func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
}
}
}
func TestStreamUpstreamPathForwardsOnlyLiveTranscodeOptions(t *testing.T) {
for _, tc := range []struct {
name string
query url.Values
want string
}{
{"plain stream", url.Values{"mediaKey": {"abc"}}, "/media/Videos/clip.mp4"},
{"blank options are dropped", url.Values{"quality": {" "}, "start": {""}}, "/media/Videos/clip.mp4"},
{"quality and start are forwarded", url.Values{"mediaKey": {"abc"}, "quality": {"1080"}, "start": {" 12.5 "}}, "/media/Videos/clip.mp4?quality=1080&start=12.5"},
{"quality alone", url.Values{"quality": {"720"}}, "/media/Videos/clip.mp4?quality=720"},
} {
if got := streamUpstreamPath("Videos/clip.mp4", tc.query); got != tc.want {
t.Errorf("%s: streamUpstreamPath() = %q, want %q", tc.name, got, tc.want)
}
}
}
+28 -2
View File
@@ -1,17 +1,39 @@
package media
import (
"net/http"
"testing"
)
func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) {
for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
func TestUpstreamMediaPathRefusesTraversal(t *testing.T) {
for _, stored := range []string{"../x.mp4", "media/../../x.mp4", `..\x.mp4`} {
if _, ok := upstreamMediaPath(stored); ok {
t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored)
}
}
}
// CarrierNode's router matches a raw request path literally, so a name must reach it with no raw path:
// a %2C for a comma would never match "Hello, World.mp4". Query and fragment markers are escaped, not refused.
func TestUpstreamMediaPathReachesCarrierNodeAsTheLiteralName(t *testing.T) {
for _, stored := range []string{"Hello, World.mp4", "a;b.mp4", "x?y.mp4", "a#b.mp4", "100%.mp4", "dir one/x y.mp4"} {
upstream, ok := upstreamMediaPath(stored)
if !ok {
t.Fatalf("upstreamMediaPath(%q) refused", stored)
}
request, err := http.NewRequest(http.MethodGet, "http://carrier.example/media/"+upstream, nil)
if err != nil {
t.Fatalf("NewRequest for %q: %v", stored, err)
}
if request.URL.RawPath != "" {
t.Errorf("%q produced raw path %q; CarrierNode would match that instead of the name", stored, request.URL.RawPath)
}
if want := "/media/" + urlPath(stored); request.URL.Path != want {
t.Errorf("%q decodes to %q, want %q", stored, request.URL.Path, want)
}
}
}
func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
cases := map[string]string{
"clips/clip.mp4": "clips/clip.mp4",
@@ -19,6 +41,10 @@ func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) {
"100%.mp4": "100%25.mp4",
"media/a b/c.mp4": "a%20b/c.mp4",
"/leading.mp4": "leading.mp4",
"Hello, World.mp4": "Hello,%20World.mp4",
"a;b.mp4": "a;b.mp4",
"x?y.mp4": "x%3Fy.mp4",
"a#b.mp4": "a%23b.mp4",
}
for stored, want := range cases {
got, ok := upstreamMediaPath(stored)
+24 -16
View File
@@ -1885,9 +1885,9 @@
"peer": true
},
"node_modules/@sveltejs/acorn-typescript": {
"version": "1.0.13",
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
"integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
"integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==",
"license": "MIT",
"peerDependencies": {
"acorn": "^8.9.0"
@@ -2080,6 +2080,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.72.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.0.tgz",
@@ -3108,9 +3114,9 @@
}
},
"node_modules/esrap": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz",
"integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz",
"integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==",
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15"
@@ -4755,22 +4761,23 @@
}
},
"node_modules/svelte": {
"version": "5.57.3",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz",
"integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==",
"version": "5.56.8",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz",
"integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==",
"license": "MIT",
"dependencies": {
"@jridgewell/remapping": "^2.3.5",
"@jridgewell/sourcemap-codec": "^1.6.0",
"@sveltejs/acorn-typescript": "^1.0.13",
"@types/estree": "^1.0.9",
"acorn": "^8.18.0",
"@jridgewell/remapping": "^2.3.4",
"@jridgewell/sourcemap-codec": "^1.5.0",
"@sveltejs/acorn-typescript": "^1.0.10",
"@types/estree": "^1.0.5",
"@types/trusted-types": "^2.0.7",
"acorn": "^8.12.1",
"aria-query": "5.3.1",
"axobject-query": "^4.1.0",
"clsx": "^2.1.1",
"devalue": "^5.9.2",
"devalue": "^5.8.1",
"esm-env": "^1.2.1",
"esrap": "^2.3.6",
"esrap": "^2.2.12",
"is-reference": "^3.0.3",
"locate-character": "^3.0.0",
"magic-string": "^0.30.11",
@@ -5496,6 +5503,7 @@
"version": "0.1.1",
"license": "MIT",
"dependencies": {
"@gabriel20xx/design-tokens": "0.1.1",
"@lucide/svelte": "1.28.0"
},
"devDependencies": {
@@ -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 />