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

465 lines
12 KiB
Svelte
Raw Normal View History

2026-09-23 05:35:28 +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 05:35:28 +02:00
import type { Snippet } from 'svelte'
import MediaPlayerControls, {
type MediaPlayerKind,
type MediaPlayerQualityOption,
} from './MediaPlayerControls.svelte'
let {
kind = 'video',
src = '',
poster = '',
title = '',
autoplay = false,
class: className = '',
mediaClass = '',
2026-09-25 11:28:19 +02:00
showSeekButtons: _showSeekButtons = true,
2026-09-23 05:35:28 +02:00
showVolume = true,
showFullscreen = true,
2026-09-25 11:28:19 +02:00
showGraph = false,
graphVisible = false,
2026-09-23 05:35:28 +02:00
qualityOptions = [],
selectedQuality = '',
currentTime: externalCurrentTime = null,
duration: externalDuration = null,
onError,
onPlay,
onPause,
onTimeUpdate,
onLoadedMetadata,
onEnded,
onSeek,
onSkip,
2026-09-25 11:28:19 +02:00
onQualityChange,
onToggleGraph,
2026-09-23 05:35:28 +02:00
endControls,
}: {
kind?: MediaPlayerKind
src?: string
poster?: string
title?: string
autoplay?: boolean
class?: string
mediaClass?: string
2026-09-25 11:28:19 +02:00
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
2026-09-23 05:35:28 +02:00
showSeekButtons?: boolean
showVolume?: boolean
showFullscreen?: boolean
2026-09-25 11:28:19 +02:00
showGraph?: boolean
graphVisible?: boolean
2026-09-23 05:35:28 +02:00
qualityOptions?: MediaPlayerQualityOption[]
selectedQuality?: string
currentTime?: number | null
duration?: number | null
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
2026-09-25 11:28:19 +02:00
onQualityChange?: (value: string) => void
onToggleGraph?: () => void
2026-09-23 05:35:28 +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 playing = $state(false)
let volume = $state(1)
let muted = $state(false)
let fullscreen = $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
2026-09-23 05:35:28 +02:00
const currentTime = $derived(externalCurrentTime ?? internalTime)
const duration = $derived(externalDuration ?? internalDuration)
const audio = $derived(kind === 'audio')
2026-09-24 20:14:21 +02:00
const controlsHideDelay = 2500
function clearControlsHideTimer() {
if (controlsHideTimeout === null) return
clearTimeout(controlsHideTimeout)
controlsHideTimeout = null
}
function scheduleControlsHide() {
clearControlsHideTimer()
if (audio || !playing) return
controlsHideTimeout = setTimeout(() => {
controlsVisible = false
controlsHideTimeout = null
}, controlsHideDelay)
}
function handlePlayerActivity() {
if (audio) return
controlsVisible = true
scheduleControlsHide()
}
2026-09-23 05:35:28 +02:00
function togglePlayback() {
if (!mediaElement) return
if (mediaElement.paused) void mediaElement.play().catch(() => undefined)
else mediaElement.pause()
}
function handleSurfaceClick() {
togglePlayback()
}
function handleKeydown(event: KeyboardEvent) {
const target = event.target as HTMLElement | null
if (target?.closest('button, input, select, textarea, a')) return
const key = event.key.toLowerCase()
if (key === ' ' || key === 'k') {
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-09-23 05:35:28 +02:00
function handlePlay(event: Event) {
playing = true
onPlay?.(event)
}
function handlePause(event: Event) {
playing = false
2026-09-24 20:14:21 +02:00
controlsVisible = true
2026-09-23 05:35:28 +02:00
onPause?.(event)
}
function handleTimeUpdate(event: Event) {
if (mediaElement) internalTime = mediaElement.currentTime || 0
onTimeUpdate?.(event)
}
function handleLoadedMetadata(event: Event) {
if (!mediaElement) return
internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0
volume = mediaElement.volume
muted = mediaElement.muted || mediaElement.volume === 0
2026-09-25 11:28:19 +02:00
void syncScreenOrientation(fullscreen)
2026-09-23 05:35:28 +02:00
onLoadedMetadata?.(event)
}
function handleEnded(event: Event) {
playing = false
2026-09-24 20:14:21 +02:00
controlsVisible = true
2026-09-23 05:35:28 +02:00
onEnded?.(event)
}
function handleError() {
onError?.()
}
function seek(value: number) {
if (!Number.isFinite(value)) return
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 (onSkip) {
onSkip(seconds)
return
}
seek((mediaElement?.currentTime || currentTime) + seconds)
}
function toggleMute() {
if (!mediaElement) return
if (muted || mediaElement.muted) {
mediaElement.muted = false
muted = false
if (mediaElement.volume === 0) mediaElement.volume = volume || 1
volume = mediaElement.volume
return
}
volume = mediaElement.volume || volume || 1
mediaElement.muted = true
muted = true
}
function changeVolume(value: number) {
if (!mediaElement || !Number.isFinite(value)) return
volume = Math.min(1, Math.max(0, value))
mediaElement.volume = volume
mediaElement.muted = volume === 0
muted = volume === 0
}
function handleVolumeChange() {
if (!mediaElement) return
volume = mediaElement.volume
muted = mediaElement.muted || mediaElement.volume === 0
}
async function toggleFullscreen() {
if (document.fullscreenElement) {
await document.exitFullscreen().catch(() => undefined)
return
}
if (playerFrame) await playerFrame.requestFullscreen().catch(() => undefined)
}
function handleFullscreenChange() {
fullscreen = Boolean(document.fullscreenElement)
2026-09-25 11:28:19 +02:00
void syncScreenOrientation(fullscreen)
2026-09-23 05:35:28 +02:00
}
$effect(() => {
const nextSource = src
if (!mediaElement || !nextSource) return
mediaElement.load()
if (autoplay) void mediaElement.play().catch(() => undefined)
})
2026-09-24 20:14:21 +02:00
$effect(() => {
if (audio || !playing) {
clearControlsHideTimer()
controlsVisible = true
return
}
scheduleControlsHide()
return clearControlsHideTimer
})
onMount(() => {
if (!playerFrame) return
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 05:35:28 +02:00
</script>
<svelte:window onfullscreenchange={handleFullscreenChange} />
2026-09-25 11:28:19 +02:00
<div bind:this={playerFrame} class={`media-player ${className}`}>
2026-09-23 05:35:28 +02:00
{#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}
>
<Music2 class="media-player-audio-icon" />
{#if title}<span>{title}</span>{/if}
</div>
<audio
bind:this={mediaElement}
{src}
{autoplay}
preload="auto"
tabindex="-1"
aria-hidden="true"
onplay={handlePlay}
onpause={handlePause}
ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata}
onended={handleEnded}
onvolumechange={handleVolumeChange}
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}
{poster}
{autoplay}
preload="auto"
playsinline
2026-09-25 11:28:19 +02:00
tabindex="0"
2026-09-23 05:35:28 +02:00
class={`media-player-video ${mediaClass}`}
aria-label={title ? `Video player for ${title}` : 'Video player'}
onclick={handleSurfaceClick}
2026-09-25 11:28:19 +02:00
ondblclick={handleVideoDoubleTap}
2026-09-23 05:35:28 +02:00
onkeydown={handleKeydown}
onplay={handlePlay}
onpause={handlePause}
ontimeupdate={handleTimeUpdate}
onloadedmetadata={handleLoadedMetadata}
onended={handleEnded}
onvolumechange={handleVolumeChange}
onerror={handleError}
>
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT%0A" />
</video>
{/if}
<MediaPlayerControls
2026-09-23 06:00:15 +02:00
{kind}
2026-09-23 05:35:28 +02:00
{currentTime}
{duration}
{playing}
{volume}
{muted}
{fullscreen}
2026-09-24 20:14:21 +02:00
{controlsVisible}
2026-09-23 05:35:28 +02:00
onTogglePlayback={togglePlayback}
onSeek={seek}
onToggleMute={toggleMute}
onVolumeChange={changeVolume}
onToggleFullscreen={toggleFullscreen}
{showVolume}
{showFullscreen}
2026-09-25 11:28:19 +02:00
{showGraph}
{graphVisible}
2026-09-23 05:35:28 +02:00
{qualityOptions}
{selectedQuality}
2026-09-25 11:28:19 +02:00
{onQualityChange}
{onToggleGraph}
2026-09-23 05:35:28 +02:00
{endControls}
overlay
/>
</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-video {
width: 100%;
height: 100%;
object-fit: contain;
2026-09-25 11:28:19 +02:00
touch-action: manipulation;
2026-09-23 05:35:28 +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>