Files
CollabTable/shared/packages/web-ui/src/lib/components/MediaPlayer.svelte
T

702 lines
20 KiB
Svelte
Raw Normal View History

2026-09-23 06:00:59 +02:00
<script lang="ts">
import { Music2 } from '@lucide/svelte'
2026-09-24 20:14:21 +02:00
import { onMount } from 'svelte'
2026-09-23 06:00:59 +02:00
import type { Snippet } from 'svelte'
import MediaPlayerControls, {
type MediaPlayerKind,
type MediaPlayerQualityOption,
type MediaPlayerSettingsGroup,
2026-09-23 06:00:59 +02:00
} from './MediaPlayerControls.svelte'
let {
kind = 'video',
2026-11-18 14:00:13 +01:00
src,
2026-09-23 06:00:59 +02:00
poster = '',
title = '',
autoplay = false,
autoplayMuted = false,
2026-09-23 06:00:59 +02:00
class: className = '',
mediaClass = '',
mediaVisible = true,
2026-09-25 11:28:19 +02:00
showSeekButtons: _showSeekButtons = true,
seekOnCommit = false,
seekWithoutDuration = false,
2026-09-23 06:00:59 +02:00
showVolume = true,
showFullscreen = true,
2026-09-25 11:28:19 +02:00
showGraph = false,
graphVisible = false,
settingsGroups = [],
settings,
2026-09-23 06:00:59 +02:00
qualityOptions = [],
selectedQuality = '',
currentTime: externalCurrentTime = null,
duration: externalDuration = null,
playing: externalPlaying = null,
volume: externalVolume = null,
muted: externalMuted = null,
fullscreen: externalFullscreen = null,
playbackRate: externalPlaybackRate = null,
controlsDisabled = false,
speedDisabled = false,
2026-09-23 06:00:59 +02:00
onError,
onPlay,
onPause,
onTimeUpdate,
onLoadedMetadata,
onEnded,
onSeek,
onSkip,
onTogglePlayback,
onToggleMute,
onVolumeChange,
onToggleFullscreen,
2026-09-25 11:28:19 +02:00
onQualityChange,
onToggleGraph,
onSpeedChange,
2026-11-18 14:00:13 +01:00
storageKey = '',
showSpeed = true,
controls = true,
controlsPlacement = 'overlay',
autoHideControls = true,
surfaceControls = true,
globalKeyboardControls = false,
2026-11-18 14:00:13 +01:00
element = $bindable(null),
preload = 'auto',
crossorigin,
2026-09-23 06:00:59 +02:00
endControls,
}: {
kind?: MediaPlayerKind
src?: string
poster?: string
title?: string
autoplay?: boolean
/** Start autoplaying video muted, so browser autoplay policies allow playback. */
autoplayMuted?: boolean
2026-09-23 06:00:59 +02:00
class?: string
mediaClass?: string
/** Hides the media element while keeping the player controls mounted. */
mediaVisible?: boolean
2026-09-25 11:28:19 +02:00
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
2026-09-23 06:00:59 +02:00
showSeekButtons?: boolean
seekOnCommit?: boolean
seekWithoutDuration?: boolean
2026-09-23 06:00:59 +02:00
showVolume?: boolean
showFullscreen?: boolean
2026-09-25 11:28:19 +02:00
showGraph?: boolean
graphVisible?: boolean
settingsGroups?: MediaPlayerSettingsGroup[]
settings?: Snippet<[string]>
2026-09-23 06:00:59 +02:00
qualityOptions?: MediaPlayerQualityOption[]
selectedQuality?: string
currentTime?: number | null
duration?: number | null
playing?: boolean | null
volume?: number | null
muted?: boolean | null
fullscreen?: boolean | null
playbackRate?: number | null
controlsDisabled?: boolean
speedDisabled?: boolean
2026-09-23 06:00:59 +02:00
onError?: () => void
onPlay?: (event: Event) => void
onPause?: (event: Event) => void
onTimeUpdate?: (event: Event) => void
onLoadedMetadata?: (event: Event) => void
onEnded?: (event: Event) => void
onSeek?: (value: number) => void
onSkip?: (seconds: number) => void
onTogglePlayback?: () => void
onToggleMute?: () => void
onVolumeChange?: (value: number) => void
onToggleFullscreen?: () => void | Promise<void>
2026-09-25 11:28:19 +02:00
onQualityChange?: (value: string) => void
onToggleGraph?: () => void
onSpeedChange?: (value: number) => void
2026-11-18 14:00:13 +01:00
/**
* 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
/** Renders the controls over the media surface or as a toolbar below it. */
controlsPlacement?: 'overlay' | 'toolbar'
/** Keep controls visible during playback. */
autoHideControls?: boolean
/** Whether clicks and key presses on the media surface control playback. */
surfaceControls?: boolean
/** Listen for player shortcuts on the window, outside media-focused use. */
globalKeyboardControls?: boolean
2026-11-18 14:00:13 +01:00
/** The media element, once mounted. Cleared when it goes. */
element?: HTMLMediaElement | null
preload?: 'none' | 'metadata' | 'auto'
crossorigin?: 'anonymous' | 'use-credentials'
2026-09-23 06:00:59 +02:00
endControls?: Snippet
} = $props()
let playerFrame = $state<HTMLDivElement | null>(null)
let mediaElement = $state<HTMLMediaElement | null>(null)
let internalTime = $state(0)
let internalDuration = $state(0)
let internalPlaying = $state(false)
let internalVolume = $state(1)
let internalMuted = $state(false)
let internalFullscreen = $state(false)
2026-09-24 20:14:21 +02:00
let controlsVisible = $state(true)
2026-09-25 11:28:19 +02:00
let orientationLocked = $state(false)
2026-09-24 20:14:21 +02:00
let controlsHideTimeout: ReturnType<typeof setTimeout> | null = null
2026-09-25 11:28:19 +02:00
let orientationLockRequest = 0
let internalPlaybackRate = $state(1)
2026-11-18 14:00:13 +01:00
let lastProgressSaveAt = 0
const PROGRESS_SAVE_INTERVAL_MS = 1500
2026-09-23 06:00:59 +02:00
const currentTime = $derived(externalCurrentTime ?? internalTime)
const duration = $derived(externalDuration ?? internalDuration)
const playing = $derived(externalPlaying ?? internalPlaying)
const volume = $derived(externalVolume ?? internalVolume)
const muted = $derived(externalMuted ?? internalMuted)
const fullscreen = $derived(externalFullscreen ?? internalFullscreen)
const playbackRate = $derived(externalPlaybackRate ?? internalPlaybackRate)
2026-09-23 06:00:59 +02:00
const audio = $derived(kind === 'audio')
2026-09-24 20:14:21 +02:00
const controlsHideDelay = 2500
2026-11-18 14:00:13 +01:00
$effect(() => {
element = mediaElement
})
2026-09-24 20:14:21 +02:00
function clearControlsHideTimer() {
if (controlsHideTimeout === null) return
clearTimeout(controlsHideTimeout)
controlsHideTimeout = null
}
function scheduleControlsHide() {
clearControlsHideTimer()
if (!autoHideControls || audio || !playing) return
2026-09-24 20:14:21 +02:00
controlsHideTimeout = setTimeout(() => {
controlsVisible = false
controlsHideTimeout = null
}, controlsHideDelay)
}
function handlePlayerActivity() {
if (audio) return
controlsVisible = true
scheduleControlsHide()
}
2026-09-23 06:00:59 +02:00
function togglePlayback() {
if (controlsDisabled) return
if (onTogglePlayback) {
onTogglePlayback()
return
}
2026-09-23 06:00:59 +02:00
if (!mediaElement) return
if (mediaElement.paused) void mediaElement.play().catch(() => undefined)
else mediaElement.pause()
}
function handleSurfaceClick() {
togglePlayback()
}
function handleKeydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return
2026-09-23 06:00:59 +02:00
const target = event.target as HTMLElement | null
if (target?.closest('button, input, select, textarea, a, [contenteditable]:not([contenteditable="false"])')) return
2026-09-23 06:00:59 +02:00
const key = event.key.toLowerCase()
if (key === ' ' || key === 'k') {
if (event.repeat) return
2026-09-23 06:00:59 +02:00
event.preventDefault()
togglePlayback()
} else if (key === 'arrowleft') {
event.preventDefault()
skip(-10)
} else if (key === 'arrowright') {
event.preventDefault()
skip(10)
} else if (key === 'm') {
event.preventDefault()
toggleMute()
} else if (key === 'f') {
event.preventDefault()
void toggleFullscreen()
}
}
2026-09-25 11:28:19 +02:00
function isMobileDevice() {
return (
typeof window !== 'undefined' &&
(window.matchMedia?.('(pointer: coarse)').matches === true || navigator.maxTouchPoints > 0)
)
}
function isWideVideo() {
return Boolean(
mediaElement &&
!audio &&
mediaElement instanceof HTMLVideoElement &&
mediaElement.videoWidth > mediaElement.videoHeight,
)
}
async function syncScreenOrientation(nextFullscreen: boolean) {
const request = ++orientationLockRequest
const orientation =
typeof window !== 'undefined'
? (window.screen?.orientation as
| (ScreenOrientation & {
lock: (orientation: 'landscape') => Promise<void>
})
| undefined)
: undefined
const shouldLock = nextFullscreen && isMobileDevice() && isWideVideo()
if (!shouldLock) {
if (orientationLocked) orientation?.unlock()
orientationLocked = false
return
}
if (!orientation?.lock) return
try {
await orientation.lock('landscape')
if (request !== orientationLockRequest) {
orientation.unlock()
return
}
orientationLocked = true
} catch {
// Orientation locking is not available in every mobile browser.
}
}
function handleVideoDoubleTap(event: MouseEvent) {
if (audio || !isMobileDevice()) return
const target = event.currentTarget as HTMLVideoElement
const bounds = target.getBoundingClientRect()
skip(event.clientX - bounds.left < bounds.width / 2 ? -10 : 10)
}
2026-11-18 14:00:13 +01:00
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
if (onSpeedChange) {
onSpeedChange(value)
return
}
internalPlaybackRate = value
2026-11-18 14:00:13 +01:00
if (mediaElement) mediaElement.playbackRate = value
}
function handleSeeked() {
savePlaybackProgress(true)
}
2026-09-23 06:00:59 +02:00
function handlePlay(event: Event) {
internalPlaying = true
2026-09-23 06:00:59 +02:00
onPlay?.(event)
}
function handlePause(event: Event) {
internalPlaying = false
2026-09-24 20:14:21 +02:00
controlsVisible = true
2026-11-18 14:00:13 +01:00
savePlaybackProgress(true)
2026-09-23 06:00:59 +02:00
onPause?.(event)
}
function handleTimeUpdate(event: Event) {
if (mediaElement) internalTime = mediaElement.currentTime || 0
2026-11-18 14:00:13 +01:00
savePlaybackProgress()
2026-09-23 06:00:59 +02:00
onTimeUpdate?.(event)
}
function handleLoadedMetadata(event: Event) {
if (!mediaElement) return
internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0
internalVolume = mediaElement.volume
internalMuted = mediaElement.muted || mediaElement.volume === 0
2026-11-18 14:00:13 +01:00
// Loading a source resets the rate, so the chosen speed is applied again.
mediaElement.playbackRate = playbackRate
restorePlaybackProgress()
if (controls) void syncScreenOrientation(fullscreen)
2026-09-23 06:00:59 +02:00
onLoadedMetadata?.(event)
}
function handleEnded(event: Event) {
internalPlaying = false
2026-09-24 20:14:21 +02:00
controlsVisible = true
2026-11-18 14:00:13 +01:00
clearPlaybackProgress()
2026-09-23 06:00:59 +02:00
onEnded?.(event)
}
function handleError() {
onError?.()
}
function seek(value: number) {
if (controlsDisabled || !Number.isFinite(value)) return
2026-09-23 06:00:59 +02:00
if (onSeek) {
onSeek(value)
return
}
if (!mediaElement) return
const nextTime = Math.min(Math.max(0, value), duration > 0 ? duration : value)
mediaElement.currentTime = nextTime
internalTime = nextTime
}
function skip(seconds: number) {
if (controlsDisabled) return
2026-09-23 06:00:59 +02:00
if (onSkip) {
onSkip(seconds)
return
}
seek((mediaElement?.currentTime || currentTime) + seconds)
}
function toggleMute() {
if (onToggleMute) {
onToggleMute()
return
}
2026-09-23 06:00:59 +02:00
if (!mediaElement) return
if (muted || mediaElement.muted) {
mediaElement.muted = false
internalMuted = false
2026-09-23 06:00:59 +02:00
if (mediaElement.volume === 0) mediaElement.volume = volume || 1
internalVolume = mediaElement.volume
2026-09-23 06:00:59 +02:00
return
}
internalVolume = mediaElement.volume || volume || 1
2026-09-23 06:00:59 +02:00
mediaElement.muted = true
internalMuted = true
2026-09-23 06:00:59 +02:00
}
function changeVolume(value: number) {
if (!Number.isFinite(value)) return
const nextVolume = Math.min(1, Math.max(0, value))
if (onVolumeChange) {
onVolumeChange(nextVolume)
return
}
if (!mediaElement) return
internalVolume = nextVolume
mediaElement.volume = internalVolume
mediaElement.muted = internalVolume === 0
internalMuted = internalVolume === 0
2026-09-23 06:00:59 +02:00
}
function handleVolumeChange() {
if (!mediaElement) return
internalVolume = mediaElement.volume
internalMuted = mediaElement.muted || mediaElement.volume === 0
2026-09-23 06:00:59 +02:00
}
async function toggleFullscreen() {
if (onToggleFullscreen) {
await onToggleFullscreen()
return
}
2026-09-23 06:00:59 +02:00
if (document.fullscreenElement) {
await document.exitFullscreen().catch(() => undefined)
return
}
if (playerFrame) await playerFrame.requestFullscreen().catch(() => undefined)
}
function handleFullscreenChange() {
2026-11-18 14:00:13 +01:00
if (!controls) return
internalFullscreen = Boolean(document.fullscreenElement)
2026-09-25 11:28:19 +02:00
void syncScreenOrientation(fullscreen)
2026-09-23 06:00:59 +02:00
}
$effect(() => {
const nextSource = src
if (!mediaElement || !nextSource) return
if (!audio && autoplay && autoplayMuted) mediaElement.muted = true
2026-09-23 06:00:59 +02:00
mediaElement.load()
if (autoplay) void mediaElement.play().catch(() => undefined)
})
2026-09-24 20:14:21 +02:00
$effect(() => {
if (!controls || !autoHideControls || audio || !playing) {
2026-09-24 20:14:21 +02:00
clearControlsHideTimer()
controlsVisible = true
return
}
scheduleControlsHide()
return clearControlsHideTimer
})
onMount(() => {
2026-11-18 14:00:13 +01:00
if (!controls || !playerFrame) return
2026-09-24 20:14:21 +02:00
const activityEvents = ['mousemove', 'click', 'keydown', 'focusin', 'touchstart'] as const
for (const eventName of activityEvents) playerFrame.addEventListener(eventName, handlePlayerActivity)
return () => {
for (const eventName of activityEvents) playerFrame?.removeEventListener(eventName, handlePlayerActivity)
2026-09-25 11:28:19 +02:00
orientationLockRequest += 1
if (orientationLocked) {
window.screen?.orientation?.unlock()
orientationLocked = false
}
2026-09-24 20:14:21 +02:00
}
})
2026-09-23 06:00:59 +02:00
</script>
<svelte:window
onfullscreenchange={handleFullscreenChange}
onkeydown={globalKeyboardControls ? handleKeydown : undefined}
/>
2026-09-23 06:00:59 +02:00
<div
bind:this={playerFrame}
class={controls
? `media-player ${controlsPlacement === 'toolbar' ? 'media-player-toolbar ' : ''}${className}`
: className}
>
2026-09-23 06:00:59 +02:00
{#if audio}
<div
class="media-player-audio-surface"
role="button"
tabindex="0"
aria-label={title ? `Audio player for ${title}` : 'Audio player'}
onclick={controls && surfaceControls ? handleSurfaceClick : undefined}
onkeydown={controls && surfaceControls && !globalKeyboardControls ? handleKeydown : undefined}
2026-09-23 06:00:59 +02:00
>
<Music2 class="media-player-audio-icon" />
{#if title}<span>{title}</span>{/if}
</div>
<audio
bind:this={mediaElement}
{src}
{autoplay}
2026-11-18 14:00:13 +01:00
{preload}
2026-09-23 06:00:59 +02:00
tabindex="-1"
aria-hidden="true"
onplay={handlePlay}
onpause={handlePause}
ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata}
onended={handleEnded}
onvolumechange={handleVolumeChange}
2026-11-18 14:00:13 +01:00
onseeked={handleSeeked}
2026-09-23 06:00:59 +02:00
onerror={handleError}
></audio>
{:else}
<!-- The empty caption track keeps the custom player accessible without requiring callers to
invent a caption URL for streams that do not provide captions. -->
<video
bind:this={mediaElement}
{src}
2026-11-18 20:40:49 +01:00
poster={poster || undefined}
2026-09-23 06:00:59 +02:00
{autoplay}
muted={autoplay && autoplayMuted}
2026-11-18 14:00:13 +01:00
{preload}
{crossorigin}
2026-09-23 06:00:59 +02:00
playsinline
2026-11-18 14:00:13 +01:00
tabindex={controls ? 0 : undefined}
class={[
controls && 'media-player-video',
controls && !mediaVisible && 'media-player-video-hidden',
mediaClass,
].filter(Boolean).join(' ')}
2026-09-23 06:00:59 +02:00
aria-label={title ? `Video player for ${title}` : 'Video player'}
onclick={controls && surfaceControls ? handleSurfaceClick : undefined}
ondblclick={controls && surfaceControls ? handleVideoDoubleTap : undefined}
onkeydown={controls && surfaceControls && !globalKeyboardControls ? handleKeydown : undefined}
2026-09-23 06:00:59 +02:00
onplay={handlePlay}
onpause={handlePause}
ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata}
onended={handleEnded}
onvolumechange={handleVolumeChange}
2026-11-18 14:00:13 +01:00
onseeked={handleSeeked}
2026-09-23 06:00:59 +02:00
onerror={handleError}
>
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT%0A" />
</video>
{/if}
2026-11-18 14:00:13 +01:00
{#if controls}
2026-09-23 06:00:59 +02:00
<MediaPlayerControls
{kind}
{currentTime}
{duration}
{playing}
{volume}
{muted}
{fullscreen}
2026-09-24 20:14:21 +02:00
{controlsVisible}
2026-09-23 06:00:59 +02:00
onTogglePlayback={togglePlayback}
onSeek={seek}
{seekOnCommit}
{seekWithoutDuration}
2026-09-23 06:00:59 +02:00
onToggleMute={toggleMute}
onVolumeChange={changeVolume}
onToggleFullscreen={toggleFullscreen}
{showVolume}
{showFullscreen}
2026-09-25 11:28:19 +02:00
{showGraph}
{graphVisible}
2026-09-23 06:00:59 +02:00
{qualityOptions}
{selectedQuality}
{settingsGroups}
{settings}
2026-09-25 11:28:19 +02:00
{onQualityChange}
{onToggleGraph}
2026-09-23 06:00:59 +02:00
{endControls}
2026-11-18 14:00:13 +01:00
{showSpeed}
{playbackRate}
onSpeedChange={changeSpeed}
playbackDisabled={controlsDisabled}
{speedDisabled}
placement={controlsPlacement}
overlay={controlsPlacement === 'overlay'}
2026-09-23 06:00:59 +02:00
/>
2026-11-18 14:00:13 +01:00
{/if}
2026-09-23 06:00:59 +02:00
</div>
<style>
.media-player {
position: relative;
display: flex;
width: 100%;
min-width: 0;
aspect-ratio: 16 / 9;
overflow: hidden;
background: black;
color: white;
}
.media-player:fullscreen {
width: 100vw;
height: 100vh;
aspect-ratio: auto;
border-radius: 0;
}
.media-player-toolbar {
aspect-ratio: auto;
display: flex;
flex-direction: column;
justify-content: flex-end;
overflow: visible;
background: transparent;
color: var(--sc-fg, white);
}
.media-player-toolbar .media-player-video:not(.media-player-video-hidden) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: auto;
}
.media-player-toolbar .media-player-video-hidden {
position: absolute;
top: 0;
left: 0;
width: 1px;
height: 1px;
overflow: hidden;
opacity: 0;
pointer-events: none;
}
2026-09-23 06:00:59 +02:00
.media-player-video {
width: 100%;
height: 100%;
object-fit: contain;
2026-09-25 11:28:19 +02:00
touch-action: manipulation;
2026-09-23 06:00:59 +02:00
}
.media-player-audio-surface {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1.5rem;
padding: 1.5rem;
cursor: pointer;
}
.media-player-audio-icon {
width: 4rem;
height: 4rem;
padding: 1rem;
border-radius: 9999px;
color: var(--sc-primary, #80b6f5);
background: color-mix(in srgb, var(--sc-primary, #80b6f5) 15%, transparent);
}
.media-player-audio-surface span {
max-width: 100%;
overflow: hidden;
color: rgb(255 255 255 / 0.75);
font-size: 0.875rem;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>