+
+
Downloads
+
+ {formatBytes(breakdown.bytes)} · {songCount(breakdown.songs)}
+ {breakdown.queued > 0 ? ` · ${breakdown.queued} downloading` : ""}
+
+
+
+
+
+ {breakdown.songs > 0 ? (
+
+
+ {qualities.map((entry) => (
+
+ ))}
+
+
+ {qualities.map((entry) => (
+
+
+
+
+
+
+ {songCount(entry.songs)}
+
+
+ {formatBytes(entry.bytes)}
+
+
+ ))}
+
+
+ ) : null}
+
+ {breakdown.collections.length > 0 ||
+ breakdown.otherSongs.songIds.length > 0 ? (
+
+ {breakdown.collections.map(
+ ({ collection, bytes, status, fallbackCount }) => (
+
+
+
{collection.title}
+
+
+ {collection.kind === "album" ? "Album" : "Playlist"}
+
+ ·
+
+ {fallbackCount > 0 ? (
+ ({fallbackCount} in High)
+ ) : null}
+ {status.downloaded < status.total ? (
+ <>
+ ·
+
+ {status.downloaded} of {status.total}
+
+ >
+ ) : null}
+
+
+
{formatBytes(bytes)}
+
+
+ )
+ )}
+ {breakdown.otherSongs.songIds.length > 0 ? (
+
+
+
Other Downloaded Songs
+
+ {songCount(breakdown.otherSongs.songIds.length)}
+
+
+
+ {formatBytes(breakdown.otherSongs.bytes)}
+
+
+
+ ) : null}
+
+ ) : (
+
+ Nothing downloaded in this browser.
+
+ )}
+
+ {breakdown.songs > 0 || breakdown.queued > 0 ? (
+
+
+
+
+
+
+ Remove all downloads?
+
+
+ Cancel
+ void downloadQueue.removeAll()}
+ >
+ Remove
+
+
+
+
+ ) : null}
+
+ )
+}
diff --git a/apps/web/components/downloads-view.tsx b/apps/web/components/downloads-view.tsx
new file mode 100644
index 0000000..14d3c99
--- /dev/null
+++ b/apps/web/components/downloads-view.tsx
@@ -0,0 +1,152 @@
+"use client"
+
+import * as React from "react"
+import Image from "next/image"
+import Link from "next/link"
+import { Star } from "lucide-react"
+
+import { FAVORITES_DOWNLOAD_ID } from "@/components/downloads-provider"
+import { PageHeader } from "@/components/library-skeletons"
+import {
+ FROM_DOWNLOADS_PARAM,
+ useDownloadsVersion,
+} from "@/hooks/use-downloads"
+import { albumGridClassName } from "@/lib/album-grid-classes"
+import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
+import { downloadQueue } from "@/lib/downloads"
+import type { DownloadedCollection } from "@otunes/convex/client/download-queue"
+import { formatBytes } from "@otunes/convex/download-quality"
+
+export const OTHER_DOWNLOADS_PATH = "/library/downloads/other"
+export const OTHER_DOWNLOADS_TITLE = "Other Downloaded Songs"
+
+function collectionHref({ kind, id }: DownloadedCollection) {
+ if (kind === "album") return `/album/${id}?${FROM_DOWNLOADS_PARAM}`
+ if (id === FAVORITES_DOWNLOAD_ID) {
+ return `/playlist/favorites?${FROM_DOWNLOADS_PARAM}`
+ }
+ return `/playlist/${id}?${FROM_DOWNLOADS_PARAM}`
+}
+
+function CollectionCover({ collection }: { collection: DownloadedCollection }) {
+ if (collection.id === FAVORITES_DOWNLOAD_ID) {
+ return (
+
{activeSection === "profile" &&
}
{activeSection === "quality" &&
}
+ {activeSection === "downloads" &&
}
{activeSection === "library" && isAdmin ? (
) : null}
diff --git a/apps/web/components/other-downloads-view.tsx b/apps/web/components/other-downloads-view.tsx
new file mode 100644
index 0000000..1902fa1
--- /dev/null
+++ b/apps/web/components/other-downloads-view.tsx
@@ -0,0 +1,158 @@
+"use client"
+
+import { useCallback, useMemo, type MouseEvent } from "react"
+import { Play, Shuffle } from "lucide-react"
+
+import { OTHER_DOWNLOADS_TITLE } from "@/components/downloads-view"
+import { useFavorites } from "@/components/favorites-provider"
+import { PageHeader } from "@/components/library-skeletons"
+import { usePlaybackActions } from "@/components/playback-provider"
+import { LibraryTrackListHeader, TrackRow } from "@/components/track-row"
+import { Button } from "@/components/ui/button"
+import { ScrollArea } from "@/components/ui/scroll-area"
+import { VirtualList } from "@/components/virtual-list"
+import { useDownloadsVersion } from "@/hooks/use-downloads"
+import { useTrackListMediaAction } from "@/hooks/use-media-actions"
+import { useTrackSelection } from "@/hooks/use-track-selection"
+import { downloadQueue } from "@/lib/downloads"
+import { getSelectionRangePositions } from "@/lib/selection-range-styles"
+import { stationArtistId } from "@/lib/station-artist"
+import { useSongs } from "@/lib/song-cache"
+import type { Id } from "@otunes/convex/_generated/dataModel"
+import type { BrowseSong } from "@otunes/convex/types"
+import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
+
+const PLAY_ORIGIN = downloadsQueueOrigin("other")
+const estimateSongRowSize = () => 56
+
+/** Songs downloaded on their own. Playback here always uses the downloads. */
+export function OtherDownloadsView() {
+ const version = useDownloadsVersion()
+ const songIds = useMemo(
+ () =>
+ downloadQueue
+ .otherSongIds()
+ .filter((songId) => downloadQueue.getDownloaded(songId))
+ .reverse() as Id<"songs">[],
+ // version invalidates the lookup when downloads change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [version]
+ )
+ const cachedSongs = useSongs(songIds)
+ const songs = useMemo(
+ () => cachedSongs.filter((song): song is BrowseSong => song !== undefined),
+ [cachedSongs]
+ )
+ const playableIds = useMemo(
+ () => songs.map((song) => song.id as Id<"songs">),
+ [songs]
+ )
+
+ const { isSongFavorite, toggleSongFavorite } = useFavorites()
+ const { playFromSong, playInOrder, playShuffled } = usePlaybackActions()
+ const {
+ selectedIds,
+ selectedCount,
+ handleSelect,
+ handlePointerDown,
+ prepareContextMenu,
+ clearSelection,
+ } = useTrackSelection(songs)
+ const selectedStationArtistId = useMemo(
+ () => stationArtistId(songs, selectedIds),
+ [songs, selectedIds]
+ )
+ const selectionPositions = useMemo(
+ () =>
+ getSelectionRangePositions(
+ songs.map((song) => song.id),
+ selectedIds
+ ),
+ [songs, selectedIds]
+ )
+ const handleMediaAction = useTrackListMediaAction({
+ selectedIds,
+ songs,
+ downloadFrom: "other",
+ })
+ const handleRowSelect = useCallback(
+ (index: number, event: MouseEvent) =>
+ handleSelect(songs[index].id, index, event),
+ [songs, handleSelect]
+ )
+ const handleRowPlay = useCallback(
+ (index: number) =>
+ void playFromSong(songs[index].id, playableIds, PLAY_ORIGIN),
+ [songs, playableIds, playFromSong]
+ )
+ const handleToggleFavorite = useCallback(
+ (songId: string) => void toggleSongFavorite(songId as Id<"songs">),
+ [toggleSongFavorite]
+ )
+
+ return (
+
+
+
+ {
+ if (event.target === event.currentTarget) clearSelection()
+ }}
+ >
+ {songIds.length === 0 ? (
+
+ Songs you download on their own appear here.
+
+ ) : (
+ <>
+
+
+
+
+
+
songs[index].id}
+ renderItem={(index) => (
+
+ )}
+ />
+ >
+ )}
+
+
+
+ )
+}
diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx
index e4e9cf2..95ccc42 100644
--- a/apps/web/components/playback-provider.tsx
+++ b/apps/web/components/playback-provider.tsx
@@ -35,6 +35,11 @@ import { useCachedQuery } from "@/hooks/use-cached-query"
import { useMediaSession } from "@/hooks/use-media-session"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
import { supportsDolbyAtmosPlayback } from "@/lib/dolby-atmos-support"
+import { downloadedAudioUrl, downloadQueue } from "@/lib/downloads"
+import {
+ isDownloadsQueueOrigin,
+ streamDownloadQuality,
+} from "@otunes/convex/download-quality"
import { flushPersistentCache } from "@/lib/persistent-cache"
import * as playbackQueue from "@otunes/convex/client/playback-queue"
import type { RepeatMode } from "@otunes/convex/client/playback-queue"
@@ -61,8 +66,9 @@ type PlaybackContextValue = {
toggleQueueOpen: () => void
setIsPlaying: (playing: boolean) => void
setVolume: (volume: number) => void
- playInOrder: (songIds: Id<"songs">[]) => Promise
- playShuffled: (songIds: Id<"songs">[]) => Promise
+ /** An origin from `downloadsQueueOrigin` plays downloads in any quality. */
+ playInOrder: (songIds: Id<"songs">[], origin?: string) => Promise
+ playShuffled: (songIds: Id<"songs">[], origin?: string) => Promise
addToQueueNext: (songIds: Id<"songs">[]) => Promise
addToQueueLast: (songIds: Id<"songs">[]) => Promise
playFromSong: (
@@ -189,28 +195,79 @@ type PlaybackLoadSettings = {
useHls: boolean
}
-function playbackLoadSettings(
+function userStreamPlan(
user: {
preferAtmos?: boolean
playbackQuality?: PlaybackQuality
},
dolbyAtmosSupported: boolean | null,
files: Record
-): PlaybackLoadSettings {
+) {
const preferAtmos =
dolbyAtmosSupported === true && (user.preferAtmos ?? false)
- const plan = playbackStreamPlan(files, user.playbackQuality, preferAtmos)
+ return playbackStreamPlan(files, user.playbackQuality, preferAtmos)
+}
+
+/** Where a song plays from: this device's download, or the server. */
+type AudioSourceChoice =
+ { kind: "download" } | { kind: "stream"; settings: PlaybackLoadSettings }
+
+/**
+ * Downloads stand in for streams in the same quality, and always play in
+ * queues started from Downloads. Without the user or file info (offline),
+ * any download plays.
+ */
+function audioSourceChoice(
+ songId: string,
+ user: { preferAtmos?: boolean; playbackQuality?: PlaybackQuality } | null,
+ dolbyAtmosSupported: boolean | null,
+ files: Record | undefined,
+ fromDownloads: boolean
+): AudioSourceChoice | null {
+ const download = downloadQueue.getDownloaded(songId)
+ if (!user || !files) {
+ return download ? { kind: "download" } : null
+ }
+ const plan = userStreamPlan(user, dolbyAtmosSupported, files)
+ if (
+ download &&
+ (fromDownloads || download.quality === streamDownloadQuality(plan))
+ ) {
+ return { kind: "download" }
+ }
return {
- preferAtmos: plan.preferAtmos,
- playbackQuality: plan.playbackQuality,
- useHls: plan.useHls,
+ kind: "stream",
+ settings: {
+ preferAtmos: plan.preferAtmos,
+ playbackQuality: plan.playbackQuality,
+ useHls: plan.useHls,
+ },
}
}
-function songLoadKey(songId: string, settings: PlaybackLoadSettings) {
+function songLoadKey(songId: string, source: AudioSourceChoice) {
+ if (source.kind === "download") {
+ return `${songId}:download`
+ }
+ const { settings } = source
return `${songId}:${settings.preferAtmos}:${settings.playbackQuality}:${settings.useHls ? "hls" : "file"}`
}
+/**
+ * True when `loadedKey` is this song from the other side of download vs
+ * stream. Finishing or removing a download keeps the loaded audio playing.
+ */
+function switchesDownloadSource(
+ loadedKey: string | null,
+ songId: string,
+ source: AudioSourceChoice
+) {
+ if (!loadedKey?.startsWith(`${songId}:`)) {
+ return false
+ }
+ return (source.kind === "download") !== loadedKey.endsWith(":download")
+}
+
function destroyHlsInstance(hlsRef: RefObject) {
hlsRef.current?.destroy()
hlsRef.current = null
@@ -242,21 +299,11 @@ function loadAudioSource(
audio: HTMLAudioElement,
hlsRef: RefObject,
songId: string,
- settings: PlaybackLoadSettings,
+ source: AudioSourceChoice,
onReady: () => void
): AudioSourceCleanup {
let disposed = false
let hlsInstance: Hls | null = null
- const directUrl = songPlayPath(
- songId,
- settings.playbackQuality,
- settings.preferAtmos
- )
- const hlsUrl = songHlsPlaylistPath(
- songId,
- settings.playbackQuality,
- settings.preferAtmos
- )
const onReadyToPlay = () => {
audio.removeEventListener("loadedmetadata", onReadyToPlay)
@@ -269,6 +316,48 @@ function loadAudioSource(
audio.addEventListener("loadeddata", onReadyToPlay)
audio.addEventListener("canplay", onReadyToPlay)
+ const cleanup = () => {
+ disposed = true
+ audio.removeEventListener("loadedmetadata", onReadyToPlay)
+ audio.removeEventListener("loadeddata", onReadyToPlay)
+ audio.removeEventListener("canplay", onReadyToPlay)
+ if (hlsInstance && hlsRef.current === hlsInstance) {
+ hlsInstance.destroy()
+ hlsRef.current = null
+ }
+ }
+
+ if (source.kind === "download") {
+ void downloadedAudioUrl(songId)
+ .catch(() => null)
+ .then((url) => {
+ if (disposed) {
+ return
+ }
+ if (!url) {
+ // Removed since it was chosen; the audio error handler reports it.
+ audio.removeAttribute("src")
+ audio.load()
+ return
+ }
+ audio.src = url
+ audio.load()
+ })
+ return cleanup
+ }
+
+ const { settings } = source
+ const directUrl = songPlayPath(
+ songId,
+ settings.playbackQuality,
+ settings.preferAtmos
+ )
+ const hlsUrl = songHlsPlaylistPath(
+ songId,
+ settings.playbackQuality,
+ settings.preferAtmos
+ )
+
const loadDirectSource = () => {
if (disposed) {
return
@@ -302,16 +391,7 @@ function loadAudioSource(
loadDirectSource()
}
- return () => {
- disposed = true
- audio.removeEventListener("loadedmetadata", onReadyToPlay)
- audio.removeEventListener("loadeddata", onReadyToPlay)
- audio.removeEventListener("canplay", onReadyToPlay)
- if (hlsInstance && hlsRef.current === hlsInstance) {
- hlsInstance.destroy()
- hlsRef.current = null
- }
- }
+ return cleanup
}
export function usePlayback() {
@@ -439,6 +519,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
getDolbyAtmosSnapshot,
() => null
)
+ // Re-picks audio sources when songs finish downloading or are removed.
+ const downloadsVersion = useSyncExternalStore(
+ downloadQueue.subscribe,
+ downloadQueue.getVersion,
+ () => 0
+ )
+ useEffect(() => {
+ void downloadQueue.load().catch(() => {})
+ }, [])
+ // Queues started from the Downloads page play downloads in any quality.
+ const [fromDownloads, setFromDownloads] = useState(false)
const volume = useSyncExternalStore(
subscribeVolume,
readStoredVolume,
@@ -759,18 +850,22 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return
}
- if (!user || !currentSongDoc) {
+ const source = audioSourceChoice(
+ currentSongId,
+ user ? { playbackQuality, preferAtmos } : null,
+ dolbyAtmosSupported,
+ currentSongDoc?.files,
+ fromDownloads
+ )
+ if (!source) {
return
}
+ const loadKey = songLoadKey(currentSongId, source)
- const settings = playbackLoadSettings(
- { playbackQuality, preferAtmos },
- dolbyAtmosSupported,
- currentSongDoc.files
- )
- const loadKey = songLoadKey(currentSongId, settings)
-
- if (loadedSongKeyRef.current === loadKey) {
+ if (
+ loadedSongKeyRef.current === loadKey ||
+ switchesDownloadSource(loadedSongKeyRef.current, currentSongId, source)
+ ) {
return
}
@@ -811,7 +906,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
audio,
hlsRef,
currentSongId,
- settings,
+ source,
requestPlay
)
@@ -826,6 +921,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playbackQuality,
preferAtmos,
dolbyAtmosSupported,
+ downloadsVersion,
+ fromDownloads,
runWithoutAudioSync,
destroyHls,
clearPreload,
@@ -839,16 +936,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
return
}
- if (!user || !nextQueueSongDoc) {
+ const source = audioSourceChoice(
+ nextQueueSongId,
+ user ? { playbackQuality, preferAtmos } : null,
+ dolbyAtmosSupported,
+ nextQueueSongDoc?.files,
+ fromDownloads
+ )
+ if (!source) {
return
}
-
- const settings = playbackLoadSettings(
- { playbackQuality, preferAtmos },
- dolbyAtmosSupported,
- nextQueueSongDoc.files
- )
- const loadKey = songLoadKey(nextQueueSongId, settings)
+ const loadKey = songLoadKey(nextQueueSongId, source)
if (preloadedSongKeyRef.current === loadKey) {
return
@@ -867,7 +965,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
preloadAudio,
preloadHlsRef,
nextQueueSongId,
- settings,
+ source,
onPreloadReady
)
@@ -888,6 +986,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
playbackQuality,
preferAtmos,
dolbyAtmosSupported,
+ downloadsVersion,
+ fromDownloads,
clearPreload,
destroyPreloadHls,
])
@@ -949,19 +1049,22 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
}
const preloadAudio = preloadAudioRef.current
+ const nextSource = nextQueueSongId
+ ? audioSourceChoice(
+ nextQueueSongId,
+ user ?? null,
+ dolbyAtmosSupported,
+ nextQueueSongDoc?.files,
+ fromDownloads
+ )
+ : null
if (
shouldContinuePlaying &&
preloadAudio &&
nextQueueSongId &&
- user &&
- nextQueueSongDoc
+ nextSource
) {
- const settings = playbackLoadSettings(
- user,
- dolbyAtmosSupported,
- nextQueueSongDoc.files
- )
- const nextLoadKey = songLoadKey(nextQueueSongId, settings)
+ const nextLoadKey = songLoadKey(nextQueueSongId, nextSource)
if (
preloadedSongKeyRef.current === nextLoadKey &&
@@ -1048,6 +1151,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
nextQueueSongDoc,
user,
dolbyAtmosSupported,
+ fromDownloads,
store,
destroyHls,
runWithoutAudioSync,
@@ -1109,6 +1213,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
queueOriginRef.current =
recorded.origin ??
(recorded.playlistId ? `playlist:${recorded.playlistId}` : undefined)
+ setFromDownloads(isDownloadsQueueOrigin(recorded.origin))
const previousSongId = store.getState().queue[0]
store.update(playbackQueue.clearQueue)
store.update(recipe)
@@ -1161,21 +1266,26 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
)
const playInOrder = useCallback(
- async (songIds: Id<"songs">[]) => {
+ async (songIds: Id<"songs">[], origin?: string) => {
if (songIds.length === 0) {
return
}
- startPlayback((state) => playbackQueue.startQueue(state, songIds, false))
+ startPlayback(
+ (state) => playbackQueue.startQueue(state, songIds, false),
+ { origin }
+ )
},
[startPlayback]
)
const playShuffled = useCallback(
- async (songIds: Id<"songs">[]) => {
+ async (songIds: Id<"songs">[], origin?: string) => {
if (songIds.length === 0) {
return
}
- startPlayback((state) => playbackQueue.startQueue(state, songIds, true))
+ startPlayback((state) => playbackQueue.startQueue(state, songIds, true), {
+ origin,
+ })
},
[startPlayback]
)
@@ -1393,8 +1503,25 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
skipPrevious,
})
- const currentFormat =
- currentSongDoc && user
+ const currentSource = currentSongId
+ ? audioSourceChoice(
+ currentSongId,
+ user ? { playbackQuality, preferAtmos } : null,
+ dolbyAtmosSupported,
+ currentSongDoc?.files,
+ fromDownloads
+ )
+ : null
+ const currentDownload =
+ currentSource?.kind === "download" && currentSongId
+ ? downloadQueue.getDownloaded(currentSongId)
+ : undefined
+ const currentFormat = currentDownload
+ ? currentDownload.quality === "atmos" ||
+ currentDownload.quality === "lossless"
+ ? currentDownload.quality
+ : null
+ : currentSongDoc && user
? playbackFormat(
currentSongDoc.files,
user.playbackQuality,
diff --git a/apps/web/components/playlist-card.tsx b/apps/web/components/playlist-card.tsx
index e65bcd9..2b1e71c 100644
--- a/apps/web/components/playlist-card.tsx
+++ b/apps/web/components/playlist-card.tsx
@@ -22,6 +22,8 @@ import {
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
+import { useDownloads } from "@/components/downloads-provider"
+import { useIsCollectionDownloaded } from "@/hooks/use-downloads"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { api } from "@otunes/convex/_generated/api"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
@@ -32,6 +34,9 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
const { playPlaylist } = usePlaybackActions()
const { runQueueAction } = useQueueMediaActions()
+ const { requestDownload, removeDownload } = useDownloads()
+ const downloadRef = { kind: "playlist" as const, id: playlist.id }
+ const downloaded = useIsCollectionDownloaded(downloadRef)
async function handleCardAction(action: MediaContextAction) {
switch (action) {
@@ -52,6 +57,20 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
void runQueueAction(action, songIds)
break
}
+ case "download":
+ case "remove-download": {
+ const songIds = await fetchCachedQuery(
+ convex,
+ cacheScope,
+ api.playlists.getPlaylistSongIds,
+ { playlistId: playlist.id as Id<"playlists"> }
+ )
+ const target = { ...downloadRef, title: playlist.title, songIds }
+ void (action === "download"
+ ? requestDownload(target)
+ : removeDownload(target))
+ break
+ }
case "favorite":
break
}
@@ -101,6 +120,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
void handleCardAction(action)}
share={{ type: "playlist", playlistId: playlist.id }}
/>
diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx
index 637ccac..a4a8a42 100644
--- a/apps/web/components/playlist-view.tsx
+++ b/apps/web/components/playlist-view.tsx
@@ -18,7 +18,17 @@ import {
} from "lucide-react"
import { toast } from "sonner"
+import { DownloadButton, DownloadedQuality } from "@/components/download-button"
+import {
+ FAVORITES_DOWNLOAD_ID,
+ useDownloads,
+} from "@/components/downloads-provider"
import { useFavorites } from "@/components/favorites-provider"
+import {
+ useIsCollectionDownloaded,
+ useOpenedFromDownloads,
+} from "@/hooks/use-downloads"
+import { downloadsQueueOrigin } from "@otunes/convex/download-quality"
import {
useCurrentSongId,
usePlaybackActions,
@@ -147,8 +157,22 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
rememberSongs(playlist.songs)
}, [playlist.songs])
+ const downloadRef = React.useMemo(
+ () => ({
+ kind: "playlist" as const,
+ id: playlist.id ?? FAVORITES_DOWNLOAD_ID,
+ }),
+ [playlist.id]
+ )
+ const fromDownloads = useOpenedFromDownloads()
+ const playOrigin = fromDownloads
+ ? downloadsQueueOrigin(`playlist:${downloadRef.id}`)
+ : `playlist:${playlist.id}`
+
function playAll(shuffled: boolean) {
- if (playlist.id) {
+ if (fromDownloads) {
+ void (shuffled ? playShuffled : playInOrder)(playlistSongIds, playOrigin)
+ } else if (playlist.id) {
const play = shuffled ? playPlaylistShuffled : playPlaylist
void play(playlist.id, playlistSongIds)
} else {
@@ -156,9 +180,32 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
}
- const handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
+ const handleMediaAction = useTrackListMediaAction({
+ selectedIds,
+ songs,
+ downloadFrom: downloadRef,
+ })
+
+ const { requestDownload, removeDownload } = useDownloads()
+ const downloadTarget = React.useMemo(
+ () => ({
+ ...downloadRef,
+ title: playlist.title,
+ songIds: playlistSongIds,
+ }),
+ [downloadRef, playlist.title, playlistSongIds]
+ )
+ const playlistDownloaded = useIsCollectionDownloaded(downloadTarget)
function handlePlaylistMediaAction(action: MediaContextAction) {
+ if (action === "download") {
+ void requestDownload(downloadTarget)
+ return
+ }
+ if (action === "remove-download") {
+ void removeDownload(downloadTarget)
+ return
+ }
runSongsAction(action, playlistSongIds)
}
@@ -171,11 +218,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
function handleRowPlay(index: number) {
- void playFromSong(
- filteredSongs[index].id,
- playlistSongIds,
- `playlist:${playlist.id}`
- )
+ void playFromSong(filteredSongs[index].id, playlistSongIds, playOrigin)
}
function handleToggleFavorite(songId: string) {
@@ -342,6 +385,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
{playlist.owner.name}
+
+
+