Files
otunes/apps/web/hooks/use-media-session.ts
joshuafhigginsandremhelper 3c721d9584 feat: optimize cover image delivery (#16)
- Add sized, resized WebP cover responses
- Request appropriately sized artwork in mobile

---------

Co-authored-by: Rem Helper <remhelper@abunchofknowitalls.com>
Reviewed-on: https://git.abunchofknowitalls.com/joshuafhiggins/otunes/pulls/16
2026-08-19 11:42:31 -04:00

192 lines
4.1 KiB
TypeScript

"use client"
import * as React from "react"
import type { BrowseSong } from "@otunes/convex/types"
import {
albumCoverUrl,
type CoverImageSize,
} from "@/lib/cover-urls"
const MEDIA_SESSION_ACTIONS = [
"play",
"pause",
"previoustrack",
"nexttrack",
"seekto",
] as const
const MEDIA_SESSION_ARTWORK_SIZES = [
64,
128,
192,
256,
384,
512,
] as const satisfies readonly CoverImageSize[]
function mediaSessionSupported() {
return typeof navigator !== "undefined" && "mediaSession" in navigator
}
function setActionHandler(
action: MediaSessionAction,
handler: MediaSessionActionHandler | null
) {
try {
navigator.mediaSession.setActionHandler(action, handler)
} catch {
// The browser may not support every Media Session action.
}
}
function artworkForSong(song: BrowseSong): MediaImage[] {
return MEDIA_SESSION_ARTWORK_SIZES.map((size) => ({
src: new URL(
albumCoverUrl(song.album.id, size),
window.location.origin
).href,
sizes: `${size}x${size}`,
}))
}
function updatePositionState(duration: number, position: number) {
if (!("setPositionState" in navigator.mediaSession)) {
return
}
if (!Number.isFinite(duration) || duration <= 0) {
try {
navigator.mediaSession.setPositionState()
} catch {
// Ignore browsers that reject clearing position state.
}
return
}
const clampedPosition = Math.max(0, Math.min(position, duration))
try {
navigator.mediaSession.setPositionState({
duration,
playbackRate: 1,
position: clampedPosition,
})
} catch {
// Ignore invalid position state races (e.g. position > duration).
}
}
export function useMediaSession({
song,
isPlaying,
duration,
currentTime,
seekTo,
setIsPlaying,
skipNext,
skipPrevious,
}: {
song: BrowseSong | null
isPlaying: boolean
duration: number
currentTime: number
seekTo: (seconds: number) => void
setIsPlaying: (playing: boolean) => void
skipNext: () => void | Promise<void>
skipPrevious: () => void | Promise<void>
}) {
const songRef = React.useRef(song)
const seekToRef = React.useRef(seekTo)
const setIsPlayingRef = React.useRef(setIsPlaying)
const skipNextRef = React.useRef(skipNext)
const skipPreviousRef = React.useRef(skipPrevious)
React.useEffect(() => {
songRef.current = song
seekToRef.current = seekTo
setIsPlayingRef.current = setIsPlaying
skipNextRef.current = skipNext
skipPreviousRef.current = skipPrevious
})
React.useEffect(() => {
if (!mediaSessionSupported()) {
return
}
setActionHandler("play", () => {
if (!songRef.current) {
return
}
setIsPlayingRef.current(true)
})
setActionHandler("pause", () => {
setIsPlayingRef.current(false)
})
setActionHandler("previoustrack", () => {
void skipPreviousRef.current()
})
setActionHandler("nexttrack", () => {
void skipNextRef.current()
})
setActionHandler("seekto", (details) => {
if (typeof details.seekTime === "number") {
seekToRef.current(details.seekTime)
}
})
return () => {
for (const action of MEDIA_SESSION_ACTIONS) {
setActionHandler(action, null)
}
navigator.mediaSession.metadata = null
navigator.mediaSession.playbackState = "none"
updatePositionState(0, 0)
}
}, [])
React.useEffect(() => {
if (!mediaSessionSupported()) {
return
}
if (!song) {
navigator.mediaSession.metadata = null
return
}
navigator.mediaSession.metadata = new MediaMetadata({
title: song.title,
artist: song.artist.name,
album: song.album.title,
artwork: artworkForSong(song),
})
}, [song])
React.useEffect(() => {
if (!mediaSessionSupported()) {
return
}
navigator.mediaSession.playbackState = song
? isPlaying
? "playing"
: "paused"
: "none"
}, [isPlaying, song])
React.useEffect(() => {
if (!mediaSessionSupported()) {
return
}
if (!song) {
updatePositionState(0, 0)
return
}
updatePositionState(duration, currentTime)
}, [song, duration, currentTime])
}