Files
otunes/apps/mobile/contexts/playback.tsx
T
joshuafhiggins 9da758b196 perf: optimize app rendering and data loading (#18)
- Virtualize mobile lists and defer queue loading
- Split playback state from actions to reduce rerenders
- Skip invalid or unnecessary Convex queries

Reviewed-on: #18
2026-09-05 16:35:37 -04:00

1144 lines
32 KiB
TypeScript

import {
createAudioPlaylist,
setAudioModeAsync,
type AudioMetadata,
type AudioPlaylist,
type AudioPlaylistStatus,
type AudioSource,
} from "expo-audio"
import { useConvex, useMutation, useQuery } from "convex/react"
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { useServerConfig } from "@/contexts/server-config"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong } from "@otunes/convex/types"
import { playbackStreamPlan } from "@otunes/convex/playback-stream"
import { getAuthCookieHeader } from "@/lib/auth-cookies"
import { showError } from "@/lib/toast"
import { albumCoverUrl, songAudioSource } from "@/lib/urls"
import {
activatePlaylistLockScreen,
releaseAudioPlaylist,
updatePlaylistLockScreenMetadata,
} from "@/lib/audio-playlist-lock-screen"
import {
nativePlaylistNeedsRebuild,
nativePlaylistSongIds,
repeatToPlaylistLoop,
} from "@/lib/native-playlist-window"
type RepeatMode = "none" | "once" | "always"
const PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS = 5
const VOLUME_STORAGE_KEY = "otunes:volume"
const DEFAULT_VOLUME = 0.8
function lockScreenMetadata(
song: BrowseSong,
serverUrl: string
): AudioMetadata {
return {
title: song.title,
artist: song.artist.name,
albumTitle: song.album.title,
artworkUrl: albumCoverUrl(serverUrl, song.album.id, 512),
}
}
type PlaybackContextValue = {
queueSongIds: Id<"songs">[]
queueHistorySongIds: Id<"songs">[]
currentSong: BrowseSong | null
shuffleEnabled: boolean
repeatEnabled: RepeatMode
isPlaying: boolean
volume: number
currentTime: number
duration: number
seekTo: (seconds: number) => void
setIsPlaying: (playing: boolean) => void
setVolume: (volume: number) => void
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
playFromLibrarySong: (
songId: Id<"songs">,
sort: {
sortKey: "title" | "artist" | "album"
sortDirection: "asc" | "desc"
}
) => Promise<void>
playAlbum: (albumId: Id<"albums">) => Promise<void>
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
playArtist: (artistId: Id<"artists">) => Promise<void>
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
toggleShuffle: () => Promise<void>
cycleRepeat: () => Promise<void>
clearQueue: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void>
skipNext: () => Promise<void>
skipPrevious: () => Promise<void>
}
type PlaybackActionsValue = Pick<
PlaybackContextValue,
| "setIsPlaying"
| "playInOrder"
| "playShuffled"
| "addToQueueNext"
| "addToQueueLast"
| "playFromSong"
| "playFromLibrarySong"
| "playAlbum"
| "playAlbumShuffled"
| "playArtist"
| "playArtistShuffled"
| "playPlaylist"
| "playPlaylistShuffled"
| "toggleShuffle"
| "cycleRepeat"
| "clearQueue"
| "reorderQueue"
| "skipToQueueIndex"
| "skipNext"
| "skipPrevious"
>
type PlaybackQueueValue = Pick<
PlaybackContextValue,
"queueSongIds" | "queueHistorySongIds" | "currentSong" | "isPlaying"
>
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
const PlaybackActionsContext = createContext<PlaybackActionsValue | null>(null)
const PlaybackQueueContext = createContext<PlaybackQueueValue | null>(null)
export function usePlayback() {
const context = useContext(PlaybackContext)
if (!context) {
throw new Error("usePlayback must be used within PlaybackProvider")
}
return context
}
export function usePlaybackActions() {
const context = useContext(PlaybackActionsContext)
if (!context) {
throw new Error("usePlaybackActions must be used within PlaybackProvider")
}
return context
}
export function usePlaybackQueue() {
const context = useContext(PlaybackQueueContext)
if (!context) {
throw new Error("usePlaybackQueue must be used within PlaybackProvider")
}
return context
}
export function PlaybackProvider({ children }: { children: ReactNode }) {
const convex = useConvex()
const { config } = useServerConfig()
const user = useQuery(api.auth.currentUser)
const playback = useQuery(api.playback.getPlaybackState)
const playlistRef = useRef<AudioPlaylist | null>(null)
const statusSubscriptionRef = useRef<{ remove: () => void } | null>(null)
const trackChangedSubscriptionRef = useRef<{ remove: () => void } | null>(
null
)
const loadedSongIdsRef = useRef<Id<"songs">[]>([])
const loadedLoadKeyRef = useRef<string | null>(null)
const ignoreTrackChangeRef = useRef(false)
const applyingFromNativeRef = useRef(false)
const autoPlayNextRef = useRef(false)
const isPlayingRef = useRef(false)
const progressRestoredForSongRef = useRef<Id<"songs"> | null>(null)
const lastSavedProgressRef = useRef(-1)
const prevIsPlayingRef = useRef(false)
const currentTimeRef = useRef(0)
const pendingSeekRef = useRef<number | null>(null)
const currentSongIdRef = useRef<Id<"songs"> | null>(null)
const loadRequestIdRef = useRef(0)
const handlingEndRef = useRef(false)
const volumeRef = useRef(DEFAULT_VOLUME)
const volumeChangedRef = useRef(false)
const volumeSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const ignoreTrackChangeTimerRef = useRef<ReturnType<
typeof setTimeout
> | null>(null)
const [isPlaying, setIsPlayingState] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [duration, setDuration] = useState(0)
const [volume, setVolumeState] = useState(DEFAULT_VOLUME)
const [progressToRestore, setProgressToRestore] = useState<number | null>(
null
)
const playInOrderMutation = useMutation(api.playback.playInOrder)
const playShuffledMutation = useMutation(api.playback.playShuffled)
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
const playFromSongMutation = useMutation(api.playback.playFromSong)
const playFromLibrarySongMutation = useMutation(
api.playback.playFromLibrarySong
)
const playAlbumMutation = useMutation(api.playback.playAlbum)
const playAlbumShuffledMutation = useMutation(api.playback.playAlbumShuffled)
const playArtistMutation = useMutation(api.playback.playArtist)
const playArtistShuffledMutation = useMutation(
api.playback.playArtistShuffled
)
const playPlaylistMutation = useMutation(api.playback.playPlaylist)
const playPlaylistShuffledMutation = useMutation(
api.playback.playPlaylistShuffled
)
const toggleShuffleMutation = useMutation(
api.playback.toggleShuffle
).withOptimisticUpdate((store) => {
const current = store.getQuery(api.playback.getPlaybackState, {})
if (!current) return
store.setQuery(api.playback.getPlaybackState, {}, {
...current,
shuffleEnabled: !current.shuffleEnabled,
})
})
const cycleRepeatMutation = useMutation(
api.playback.cycleRepeat
).withOptimisticUpdate((store) => {
const current = store.getQuery(api.playback.getPlaybackState, {})
if (!current) return
const next =
current.repeatEnabled === "none"
? "once"
: current.repeatEnabled === "once"
? "always"
: "none"
store.setQuery(api.playback.getPlaybackState, {}, {
...current,
repeatEnabled: next,
})
})
const clearQueueMutation = useMutation(api.playback.clearQueue)
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
const skipNextMutation = useMutation(api.playback.skipNext)
const skipPreviousMutation = useMutation(api.playback.skipPrevious)
const updateSongProgressMutation = useMutation(
api.playback.updateSongProgress
)
const currentSong = playback?.currentSong ?? null
const repeatEnabled = playback?.repeatEnabled ?? "none"
const queueLength = playback?.queueSongIds.length ?? 0
const queueSongIds = playback?.queueSongIds ?? []
const queueHistorySongIds = playback?.queueHistorySongIds ?? []
const queueSyncKey = useMemo(
() => JSON.stringify(queueSongIds),
[queueSongIds]
)
const historySyncKey = useMemo(
() => JSON.stringify(queueHistorySongIds),
[queueHistorySongIds]
)
const currentSongSyncKey = currentSong
? JSON.stringify([
currentSong.id,
currentSong.title,
currentSong.artist.name,
currentSong.album.id,
currentSong.album.title,
currentSong.album.cover ?? "",
currentSong.durationSeconds,
])
: ""
const userPlaybackKey = user
? JSON.stringify([
user._id,
user.playbackQuality,
user.preferAtmos ?? false,
])
: ""
useEffect(() => {
currentSongIdRef.current = currentSong?.id ?? null
}, [currentSong?.id])
const repeatEnabledRef = useRef(repeatEnabled)
const queueLengthRef = useRef(queueLength)
const historyLengthRef = useRef(queueHistorySongIds.length)
useEffect(() => {
repeatEnabledRef.current = repeatEnabled
}, [repeatEnabled])
useEffect(() => {
queueLengthRef.current = queueLength
}, [queueLength])
useEffect(() => {
historyLengthRef.current = queueHistorySongIds.length
}, [queueHistorySongIds.length])
const skipNextMutationRef = useRef(skipNextMutation)
useEffect(() => {
skipNextMutationRef.current = skipNextMutation
}, [skipNextMutation])
const skipPreviousMutationRef = useRef(skipPreviousMutation)
useEffect(() => {
skipPreviousMutationRef.current = skipPreviousMutation
}, [skipPreviousMutation])
const skipToQueueIndexMutationRef = useRef(skipToQueueIndexMutation)
useEffect(() => {
skipToQueueIndexMutationRef.current = skipToQueueIndexMutation
}, [skipToQueueIndexMutation])
const scheduleTrackChangeHandling = useCallback(() => {
if (ignoreTrackChangeTimerRef.current) {
clearTimeout(ignoreTrackChangeTimerRef.current)
}
ignoreTrackChangeTimerRef.current = setTimeout(() => {
ignoreTrackChangeTimerRef.current = null
ignoreTrackChangeRef.current = false
}, 150)
}, [])
const destroyPlaylist = useCallback(() => {
if (ignoreTrackChangeTimerRef.current) {
clearTimeout(ignoreTrackChangeTimerRef.current)
ignoreTrackChangeTimerRef.current = null
}
statusSubscriptionRef.current?.remove()
statusSubscriptionRef.current = null
trackChangedSubscriptionRef.current?.remove()
trackChangedSubscriptionRef.current = null
const playlist = playlistRef.current
if (playlist) {
playlist.pause()
releaseAudioPlaylist(playlist)
}
playlistRef.current = null
loadedSongIdsRef.current = []
loadedLoadKeyRef.current = null
}, [])
const handlePlaylistStatusUpdate = useCallback(
(status: AudioPlaylistStatus) => {
if (!status.isLoaded) return
if (
loadedSongIdsRef.current[status.currentIndex] !==
currentSongIdRef.current
) {
return
}
currentTimeRef.current = status.currentTime
setCurrentTime(status.currentTime)
if (status.duration > 0) {
setDuration(status.duration)
}
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
const seekSeconds = pendingSeekRef.current
pendingSeekRef.current = null
void playlistRef.current?.seekTo(seekSeconds)
currentTimeRef.current = seekSeconds
setCurrentTime(seekSeconds)
}
if (status.playing) {
autoPlayNextRef.current = false
if (!isPlayingRef.current) {
isPlayingRef.current = true
setIsPlayingState(true)
}
} else if (isPlayingRef.current && !status.didJustFinish) {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlayingState(false)
}
if (!status.didJustFinish) return
if (handlingEndRef.current) return
if (repeatEnabledRef.current === "once") return
if (status.currentIndex < status.trackCount - 1) return
handlingEndRef.current = true
const shouldContinue =
repeatEnabledRef.current !== "none" || queueLengthRef.current > 1
if (shouldContinue) {
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
}
void skipNextMutationRef
.current()
.then(() => {
if (shouldContinue) {
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
return
}
autoPlayNextRef.current = false
isPlayingRef.current = false
void playlistRef.current?.seekTo(0)
currentTimeRef.current = 0
setCurrentTime(0)
setIsPlayingState(false)
})
.catch(() => {
autoPlayNextRef.current = false
isPlayingRef.current = false
setIsPlayingState(false)
})
.finally(() => {
handlingEndRef.current = false
})
},
[]
)
const handleTrackChanged = useCallback(
(data: { currentIndex: number; previousIndex: number }) => {
if (ignoreTrackChangeRef.current) return
if (data.currentIndex === data.previousIndex) return
applyingFromNativeRef.current = true
autoPlayNextRef.current = true
isPlayingRef.current = true
setIsPlayingState(true)
const steps = data.currentIndex - data.previousIndex
if (steps > 0) {
void (
steps === 1
? skipNextMutationRef.current()
: skipToQueueIndexMutationRef.current({ index: steps })
).catch(() => {
applyingFromNativeRef.current = false
})
return
}
void (async () => {
for (let i = 0; i < -steps; i++) {
await skipPreviousMutationRef.current()
}
})().catch(() => {
applyingFromNativeRef.current = false
})
},
[]
)
const ensurePlaylist = useCallback(
(sources: AudioSource[]) => {
if (playlistRef.current) {
return playlistRef.current
}
ignoreTrackChangeRef.current = true
const playlist = createAudioPlaylist({
sources,
updateInterval: 500,
loop: repeatToPlaylistLoop(repeatEnabledRef.current),
})
playlist.volume = volumeRef.current
statusSubscriptionRef.current = playlist.addListener(
"playlistStatusUpdate",
handlePlaylistStatusUpdate
)
trackChangedSubscriptionRef.current = playlist.addListener(
"trackChanged",
handleTrackChanged
)
playlistRef.current = playlist
scheduleTrackChangeHandling()
return playlist
},
[
handlePlaylistStatusUpdate,
handleTrackChanged,
scheduleTrackChangeHandling,
]
)
useEffect(() => {
let cancelled = false
void setAudioModeAsync({
playsInSilentMode: true,
shouldPlayInBackground: true,
interruptionMode: "doNotMix",
}).catch(() => {
if (!cancelled) {
showError("Audio playback could not be initialized.")
}
})
void AsyncStorage.getItem(VOLUME_STORAGE_KEY)
.then((stored) => {
if (!cancelled && !volumeChangedRef.current && stored) {
const parsed = Number(stored)
if (Number.isFinite(parsed)) {
const restoredVolume = Math.min(1, Math.max(0, parsed))
volumeRef.current = restoredVolume
setVolumeState(restoredVolume)
}
}
})
.catch(() => {})
return () => {
cancelled = true
if (volumeSaveTimerRef.current) {
clearTimeout(volumeSaveTimerRef.current)
volumeSaveTimerRef.current = null
}
if (volumeChangedRef.current) {
void AsyncStorage.setItem(
VOLUME_STORAGE_KEY,
String(volumeRef.current)
).catch(() => {})
}
destroyPlaylist()
}
}, [destroyPlaylist])
useEffect(() => {
volumeRef.current = volume
if (playlistRef.current) {
playlistRef.current.volume = volume
}
}, [volume])
useEffect(() => {
const playlist = playlistRef.current
if (playlist) {
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
}
}, [repeatEnabled])
const setIsPlaying = useCallback((playing: boolean) => {
isPlayingRef.current = playing
setIsPlayingState(playing)
const playlist = playlistRef.current
if (!playlist) return
if (playing) {
playlist.play()
} else {
playlist.pause()
}
}, [])
const setVolume = useCallback((nextVolume: number) => {
const clamped = Math.min(1, Math.max(0, nextVolume))
volumeChangedRef.current = true
volumeRef.current = clamped
setVolumeState(clamped)
if (volumeSaveTimerRef.current) {
clearTimeout(volumeSaveTimerRef.current)
}
volumeSaveTimerRef.current = setTimeout(() => {
volumeSaveTimerRef.current = null
void AsyncStorage.setItem(VOLUME_STORAGE_KEY, String(clamped)).catch(
() => {}
)
}, 250)
if (playlistRef.current) {
playlistRef.current.volume = clamped
}
}, [])
const seekTo = useCallback(
async (seconds: number) => {
const playlist = playlistRef.current
if (!playlist) return
const maxDuration = playlist.duration || duration || 0
const clamped = Math.max(0, Math.min(seconds, maxDuration))
await playlist.seekTo(clamped)
currentTimeRef.current = clamped
setCurrentTime(clamped)
},
[duration]
)
const saveProgress = useCallback(
(seconds: number) => {
const songId = currentSongIdRef.current
if (!songId) return
const progressSeconds = Math.max(0, Math.floor(seconds))
if (progressSeconds === lastSavedProgressRef.current) return
lastSavedProgressRef.current = progressSeconds
void updateSongProgressMutation({
songId,
progressSeconds,
}).catch(() => {})
},
[updateSongProgressMutation]
)
const handlePlaybackLoadFailure = useCallback(() => {
autoPlayNextRef.current = false
isPlayingRef.current = false
destroyPlaylist()
setIsPlayingState(false)
showError("Could not play this track. The queue has been cleared.")
void clearQueueMutation().catch(() => {})
}, [clearQueueMutation, destroyPlaylist])
useEffect(() => {
if (!currentSong) {
progressRestoredForSongRef.current = null
applyingFromNativeRef.current = false
destroyPlaylist()
return
}
if (progressRestoredForSongRef.current === currentSong.id) return
progressRestoredForSongRef.current = currentSong.id
lastSavedProgressRef.current = -1
currentTimeRef.current = 0
setCurrentTime(0)
setDuration(currentSong.durationSeconds)
if (applyingFromNativeRef.current) {
applyingFromNativeRef.current = false
setProgressToRestore(0)
return
}
setProgressToRestore(playback?.currentSongProgress ?? 0)
}, [currentSong?.id, currentSong?.durationSeconds, destroyPlaylist])
useEffect(() => {
if (progressToRestore === null || progressToRestore <= 0) return
if (!currentSong || !playlistRef.current) return
const maxDuration = duration > 0 ? duration : progressToRestore
const clamped = Math.min(progressToRestore, maxDuration)
pendingSeekRef.current = clamped
setProgressToRestore(null)
}, [progressToRestore, currentSong?.id, duration])
useEffect(() => {
if (!currentSong) return
if (prevIsPlayingRef.current === isPlaying) return
prevIsPlayingRef.current = isPlaying
saveProgress(currentTimeRef.current)
}, [isPlaying, currentSong?.id, saveProgress])
useEffect(() => {
const loadRequestId = ++loadRequestIdRef.current
const isCurrentLoad = () => loadRequestIdRef.current === loadRequestId
async function syncPlaylist() {
if (!config || !currentSong || user === undefined || !user) {
if (!currentSong) {
destroyPlaylist()
}
return
}
const windowSongIds = nativePlaylistSongIds(
queueHistorySongIds,
queueSongIds
)
const currentIndex = queueHistorySongIds.length
const cookieHeader = await getAuthCookieHeader(
config.serverUrl,
config.convexUrl
)
if (!cookieHeader) {
showError("Your session has expired. Please sign in again.")
return
}
if (!isCurrentLoad()) return
const loadKey = `${user.playbackQuality}:${user.preferAtmos ?? false}:${cookieHeader}`
const needsRebuild =
loadedLoadKeyRef.current !== loadKey ||
nativePlaylistNeedsRebuild(
loadedSongIdsRef.current,
queueHistorySongIds,
queueSongIds
)
const metadata = lockScreenMetadata(currentSong, config.serverUrl)
const shouldPlay = isPlayingRef.current || autoPlayNextRef.current
if (!needsRebuild) {
const playlist = playlistRef.current
if (!playlist) return
ignoreTrackChangeRef.current = true
if (playlist.currentIndex !== currentIndex) {
playlist.skipTo(currentIndex)
}
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
playlist.volume = volumeRef.current
updatePlaylistLockScreenMetadata(playlist, metadata)
scheduleTrackChangeHandling()
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
playlist.play()
}
return
}
const songs = await convex.query(api.library.getSongsForPlayback, {
ids: windowSongIds,
})
if (!isCurrentLoad()) return
const sources: AudioSource[] = []
for (let i = 0; i < windowSongIds.length; i++) {
const song = songs[i]
if (!song) {
handlePlaybackLoadFailure()
return
}
const plan = playbackStreamPlan(
song.files,
user.playbackQuality,
user.preferAtmos ?? false
)
sources.push(
songAudioSource(
config.serverUrl,
song.id,
plan.playbackQuality,
plan.preferAtmos,
plan.useHls,
{ cookieHeader, songTitle: song.title }
)
)
}
ignoreTrackChangeRef.current = true
destroyPlaylist()
if (!isCurrentLoad()) {
ignoreTrackChangeRef.current = false
return
}
const playlist = ensurePlaylist(sources)
loadedSongIdsRef.current = windowSongIds
loadedLoadKeyRef.current = loadKey
playlist.volume = volumeRef.current
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
if (currentIndex > 0) {
playlist.skipTo(currentIndex)
}
activatePlaylistLockScreen(playlist, metadata)
scheduleTrackChangeHandling()
if (shouldPlay) {
isPlayingRef.current = true
setIsPlayingState(true)
playlist.play()
} else {
playlist.pause()
}
setDuration(currentSong.durationSeconds)
}
void syncPlaylist().catch(() => {
if (!isCurrentLoad()) return
handlePlaybackLoadFailure()
})
return () => {
if (loadRequestIdRef.current === loadRequestId) {
loadRequestIdRef.current += 1
}
}
}, [
config,
convex,
currentSongSyncKey,
destroyPlaylist,
ensurePlaylist,
handlePlaybackLoadFailure,
historySyncKey,
queueSyncKey,
repeatEnabled,
scheduleTrackChangeHandling,
userPlaybackKey,
])
useEffect(() => {
if (!isPlaying || !currentSong) return
const interval = setInterval(() => {
saveProgress(currentTimeRef.current)
}, 5000)
return () => clearInterval(interval)
}, [isPlaying, currentSong?.id, saveProgress])
const playInOrder = useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
const restartsCurrentSong =
currentSongIdRef.current === songIds[0]
await playInOrderMutation({ songIds })
if (restartsCurrentSong) {
await seekTo(0)
}
setIsPlaying(true)
},
[playInOrderMutation, seekTo, setIsPlaying]
)
const playShuffled = useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
const restartsCurrentSong =
songIds.length === 1 && currentSongIdRef.current === songIds[0]
await playShuffledMutation({ songIds })
if (restartsCurrentSong) {
await seekTo(0)
}
setIsPlaying(true)
},
[playShuffledMutation, seekTo, setIsPlaying]
)
const addToQueueNext = useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
const shouldStartPlayback = currentSongIdRef.current === null
await addToQueueNextMutation({ songIds })
if (shouldStartPlayback) {
setIsPlaying(true)
}
},
[addToQueueNextMutation, setIsPlaying]
)
const addToQueueLast = useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) return
const shouldStartPlayback = currentSongIdRef.current === null
await addToQueueLastMutation({ songIds })
if (shouldStartPlayback) {
setIsPlaying(true)
}
},
[addToQueueLastMutation, setIsPlaying]
)
const playFromSong = useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
const restartsCurrentSong = currentSongIdRef.current === songId
await playFromSongMutation({ songId, songIds })
if (restartsCurrentSong) {
await seekTo(0)
}
setIsPlaying(true)
},
[playFromSongMutation, seekTo, setIsPlaying]
)
const playFromLibrarySong = useCallback(
async (
songId: Id<"songs">,
sort: {
sortKey: "title" | "artist" | "album"
sortDirection: "asc" | "desc"
}
) => {
const restartsCurrentSong = currentSongIdRef.current === songId
await playFromLibrarySongMutation({ songId, ...sort })
if (restartsCurrentSong) {
await seekTo(0)
}
setIsPlaying(true)
},
[playFromLibrarySongMutation, seekTo, setIsPlaying]
)
const playAlbum = useCallback(
async (albumId: Id<"albums">) => {
await playAlbumMutation({ albumId })
setIsPlaying(true)
},
[playAlbumMutation, setIsPlaying]
)
const playAlbumShuffled = useCallback(
async (albumId: Id<"albums">) => {
await playAlbumShuffledMutation({ albumId })
setIsPlaying(true)
},
[playAlbumShuffledMutation, setIsPlaying]
)
const playArtist = useCallback(
async (artistId: Id<"artists">) => {
await playArtistMutation({ artistId })
setIsPlaying(true)
},
[playArtistMutation, setIsPlaying]
)
const playArtistShuffled = useCallback(
async (artistId: Id<"artists">) => {
await playArtistShuffledMutation({ artistId })
setIsPlaying(true)
},
[playArtistShuffledMutation, setIsPlaying]
)
const playPlaylist = useCallback(
async (playlistId: Id<"playlists">) => {
await playPlaylistMutation({ playlistId })
setIsPlaying(true)
},
[playPlaylistMutation, setIsPlaying]
)
const playPlaylistShuffled = useCallback(
async (playlistId: Id<"playlists">) => {
await playPlaylistShuffledMutation({ playlistId })
setIsPlaying(true)
},
[playPlaylistShuffledMutation, setIsPlaying]
)
const toggleShuffle = useCallback(async () => {
await toggleShuffleMutation()
}, [toggleShuffleMutation])
const cycleRepeat = useCallback(async () => {
await cycleRepeatMutation()
}, [cycleRepeatMutation])
const clearQueue = useCallback(async () => {
await clearQueueMutation()
setIsPlaying(false)
}, [clearQueueMutation, setIsPlaying])
const reorderQueue = useCallback(
async (songIds: Id<"songs">[]) => {
await reorderQueueMutation({ songIds })
},
[reorderQueueMutation]
)
const skipToQueueIndex = useCallback(
async (index: number) => {
if (index <= 0) return
autoPlayNextRef.current = true
try {
await skipToQueueIndexMutation({ index })
} catch (error) {
autoPlayNextRef.current = false
throw error
}
},
[skipToQueueIndexMutation]
)
const skipNext = useCallback(async () => {
const isFinishingQueue =
repeatEnabledRef.current === "none" && queueLengthRef.current <= 1
if (isFinishingQueue) {
setIsPlaying(false)
await seekTo(0)
await skipNextMutation()
await seekTo(0)
return
}
if (repeatEnabledRef.current === "once" || queueLengthRef.current <= 1) {
await seekTo(0)
await skipNextMutation()
setIsPlaying(true)
return
}
autoPlayNextRef.current = true
try {
await skipNextMutation()
} catch (error) {
autoPlayNextRef.current = false
throw error
}
}, [seekTo, setIsPlaying, skipNextMutation])
const skipPrevious = useCallback(async () => {
if (currentTimeRef.current > PREVIOUS_TRACK_RESTART_THRESHOLD_SECONDS) {
await seekTo(0)
return
}
if (historyLengthRef.current === 0) {
await seekTo(0)
await skipPreviousMutation()
return
}
autoPlayNextRef.current = true
try {
await skipPreviousMutation()
} catch (error) {
autoPlayNextRef.current = false
throw error
}
}, [seekTo, skipPreviousMutation])
const actionsValue = useMemo<PlaybackActionsValue>(
() => ({
setIsPlaying,
playInOrder,
playShuffled,
addToQueueNext,
addToQueueLast,
playFromSong,
playFromLibrarySong,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playPlaylist,
playPlaylistShuffled,
toggleShuffle,
cycleRepeat,
clearQueue,
reorderQueue,
skipToQueueIndex,
skipNext,
skipPrevious,
}),
[
addToQueueNext,
addToQueueLast,
clearQueue,
cycleRepeat,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playFromLibrarySong,
playFromSong,
playInOrder,
playPlaylist,
playPlaylistShuffled,
playShuffled,
reorderQueue,
setIsPlaying,
skipNext,
skipPrevious,
skipToQueueIndex,
toggleShuffle,
]
)
const queueValue = useMemo<PlaybackQueueValue>(
() => ({
queueSongIds,
queueHistorySongIds,
currentSong,
isPlaying: Boolean(currentSong && isPlaying),
}),
[currentSong, isPlaying, queueHistorySongIds, queueSongIds]
)
const value = useMemo<PlaybackContextValue>(
() => ({
queueSongIds,
queueHistorySongIds,
currentSong,
shuffleEnabled: playback?.shuffleEnabled ?? false,
repeatEnabled,
isPlaying: Boolean(currentSong && isPlaying),
volume,
currentTime,
duration,
seekTo,
setIsPlaying,
setVolume,
playInOrder,
playShuffled,
addToQueueNext,
addToQueueLast,
playFromSong,
playFromLibrarySong,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playPlaylist,
playPlaylistShuffled,
toggleShuffle,
cycleRepeat,
clearQueue,
reorderQueue,
skipToQueueIndex,
skipNext,
skipPrevious,
}),
[
addToQueueLast,
addToQueueNext,
currentSong,
currentTime,
cycleRepeat,
duration,
isPlaying,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playFromLibrarySong,
playFromSong,
playInOrder,
playPlaylist,
playPlaylistShuffled,
playShuffled,
playback?.shuffleEnabled,
queueHistorySongIds,
queueLength,
queueSongIds,
reorderQueue,
repeatEnabled,
seekTo,
setIsPlaying,
setVolume,
skipNext,
skipPrevious,
skipToQueueIndex,
toggleShuffle,
clearQueue,
volume,
]
)
return (
<PlaybackActionsContext.Provider value={actionsValue}>
<PlaybackQueueContext.Provider value={queueValue}>
<PlaybackContext.Provider value={value}>
{children}
</PlaybackContext.Provider>
</PlaybackQueueContext.Provider>
</PlaybackActionsContext.Provider>
)
}