575 lines
20 KiB
TypeScript
575 lines
20 KiB
TypeScript
"use client"
|
|
|
|
import { PageHeader } from "@/components/library-skeletons"
|
|
import { stationArtistId } from "@/lib/station-artist"
|
|
import * as React from "react"
|
|
import Image from "next/image"
|
|
import { useRouter } from "next/navigation"
|
|
import { useMutation, useQuery } from "convex/react"
|
|
import {
|
|
ImageIcon,
|
|
Pencil,
|
|
Play,
|
|
SearchIcon,
|
|
Share2,
|
|
Shuffle,
|
|
Star,
|
|
Trash2,
|
|
} 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,
|
|
} from "@/components/playback-provider"
|
|
import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
|
import { PlaylistCoverDialog } from "@/components/playlist-cover-dialog"
|
|
import {
|
|
MediaContextMenu,
|
|
type MediaContextAction,
|
|
} from "@/components/media-context-menu"
|
|
import { TrackRow } from "@/components/track-row"
|
|
import { VirtualList } from "@/components/virtual-list"
|
|
import { Button } from "@/components/ui/button"
|
|
import {
|
|
DropdownMenuItem,
|
|
DropdownMenuSeparator,
|
|
} from "@/components/ui/dropdown-menu"
|
|
import { ScrollArea } from "@/components/ui/scroll-area"
|
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
|
import {
|
|
useMediaActions,
|
|
useTrackListMediaAction,
|
|
} from "@/hooks/use-media-actions"
|
|
import { useTrackSelection } from "@/hooks/use-track-selection"
|
|
import { api } from "@otunes/convex/_generated/api"
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
|
|
import { playlistCoverUrl } from "@/lib/cover-urls"
|
|
import { copyPlaylistLink } from "@/lib/media-links"
|
|
import { sumDurationSeconds } from "@/lib/media-summary"
|
|
import { rememberSongs } from "@/lib/song-cache"
|
|
import { filterSongs } from "@otunes/convex/client/song-search"
|
|
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
|
|
|
|
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
|
const estimatePlaylistRowSize = () => 60
|
|
|
|
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
|
const router = useRouter()
|
|
const isFavorites = playlist.isFavorites === true
|
|
const currentUser = useCachedQuery(api.auth.currentUser)
|
|
const isOwner =
|
|
currentUser === undefined
|
|
? playlist.isOwner
|
|
: currentUser?._id === playlist.owner.id
|
|
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
|
|
useFavorites()
|
|
const currentSongId = useCurrentSongId()
|
|
const {
|
|
playInOrder,
|
|
playShuffled,
|
|
playPlaylist,
|
|
playPlaylistShuffled,
|
|
playFromSong,
|
|
} = usePlaybackActions()
|
|
const { runSongsAction } = useMediaActions()
|
|
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
|
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
|
|
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
|
|
const subscribe = useMutation(api.playlists.subscribeToPlaylist)
|
|
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
|
|
|
|
const [playlistSongs, setPlaylistSongs] = React.useState(playlist.songs)
|
|
const [syncedPlaylist, setSyncedPlaylist] = React.useState(playlist)
|
|
const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState(
|
|
() => new Set<string>()
|
|
)
|
|
const songs = isFavorites
|
|
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
|
|
: playlistSongs
|
|
const [searchQuery, setSearchQuery] = React.useState("")
|
|
const isSearching = searchQuery.trim() !== ""
|
|
const lyricsMatches = useQuery(
|
|
api.lyrics.matchingSongIds,
|
|
isSearching ? { query: searchQuery } : "skip"
|
|
)
|
|
const filteredSongs = React.useMemo(
|
|
() => filterSongs(songs, searchQuery, lyricsMatches),
|
|
[songs, searchQuery, lyricsMatches]
|
|
)
|
|
const playlistSongIds = React.useMemo(
|
|
() => songs.map((song) => song.id as Id<"songs">),
|
|
[songs]
|
|
)
|
|
const playlistPositionById = React.useMemo(
|
|
() => new Map(songs.map((song, index) => [song.id, index + 1])),
|
|
[songs]
|
|
)
|
|
const [activeTrackId, setActiveTrackId] = React.useState("")
|
|
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
|
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
|
const [subscriptionPending, setSubscriptionPending] = React.useState(false)
|
|
const [coverDialogOpen, setCoverDialogOpen] = React.useState(false)
|
|
const canEditCover = isOwner && !isFavorites && playlist.id !== null
|
|
|
|
if (syncedPlaylist !== playlist) {
|
|
setSyncedPlaylist(playlist)
|
|
setPlaylistSongs(playlist.songs)
|
|
setIsSubscribed(playlist.isSubscribed)
|
|
}
|
|
|
|
const {
|
|
selectedIds,
|
|
selectedCount,
|
|
handleSelect,
|
|
handlePointerDown,
|
|
prepareContextMenu,
|
|
clearSelection,
|
|
} = useTrackSelection(filteredSongs)
|
|
|
|
const selectedStationArtistId = React.useMemo(
|
|
() => stationArtistId(songs, selectedIds),
|
|
[songs, selectedIds]
|
|
)
|
|
|
|
const selectionPositions = React.useMemo(
|
|
() =>
|
|
getSelectionRangePositions(
|
|
filteredSongs.map((song) => song.id),
|
|
selectedIds
|
|
),
|
|
[filteredSongs, selectedIds]
|
|
)
|
|
const totalDurationSeconds = React.useMemo(
|
|
() => sumDurationSeconds(songs),
|
|
[songs]
|
|
)
|
|
|
|
React.useEffect(() => {
|
|
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 (fromDownloads) {
|
|
void (shuffled ? playShuffled : playInOrder)(playlistSongIds, playOrigin)
|
|
} else if (playlist.id) {
|
|
const play = shuffled ? playPlaylistShuffled : playPlaylist
|
|
void play(playlist.id, playlistSongIds)
|
|
} else {
|
|
void (shuffled ? playShuffled : playInOrder)(playlistSongIds)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
const canReorder = isOwner && !isFavorites && !isSearching
|
|
|
|
function handleRowSelect(index: number, event: React.MouseEvent) {
|
|
const songId = filteredSongs[index].id
|
|
handleSelect(songId, index, event)
|
|
setActiveTrackId(songId)
|
|
}
|
|
|
|
function handleRowPlay(index: number) {
|
|
void playFromSong(filteredSongs[index].id, playlistSongIds, playOrigin)
|
|
}
|
|
|
|
function handleToggleFavorite(songId: string) {
|
|
const wasFavorite = isSongFavorite(songId)
|
|
void toggleSongFavorite(songId as Id<"songs">)
|
|
if (isFavorites && wasFavorite) {
|
|
setHiddenFavoriteIds((current) => {
|
|
const next = new Set(current)
|
|
next.add(songId)
|
|
return next
|
|
})
|
|
}
|
|
}
|
|
|
|
async function handleRemoveSong(songId: string) {
|
|
const ids =
|
|
selectedIds.size > 0 && selectedIds.has(songId)
|
|
? Array.from(selectedIds)
|
|
: [songId]
|
|
|
|
if (isFavorites) {
|
|
const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true)
|
|
if (!succeeded) return
|
|
return
|
|
}
|
|
|
|
try {
|
|
await removeSongs({
|
|
playlistId: playlist.id as Id<"playlists">,
|
|
songIds: ids as Id<"songs">[],
|
|
})
|
|
setPlaylistSongs((current) =>
|
|
current.filter((song) => !ids.includes(song.id))
|
|
)
|
|
toast.success(
|
|
ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song"
|
|
)
|
|
} catch (error) {
|
|
toast.error(
|
|
error instanceof Error ? error.message : "Failed to remove song"
|
|
)
|
|
}
|
|
}
|
|
|
|
async function persistOrder(
|
|
previousSongs: BrowseSong[],
|
|
nextSongs: BrowseSong[]
|
|
) {
|
|
try {
|
|
await reorderSongs({
|
|
playlistId: playlist.id as Id<"playlists">,
|
|
songIds: nextSongs.map((song) => song.id as Id<"songs">),
|
|
})
|
|
} catch (error) {
|
|
setPlaylistSongs((current) =>
|
|
current === nextSongs ? previousSongs : current
|
|
)
|
|
toast.error(
|
|
error instanceof Error ? error.message : "Failed to reorder songs"
|
|
)
|
|
}
|
|
}
|
|
|
|
function handleDrop(targetIndex: number) {
|
|
if (!canReorder || dragIndex === null || dragIndex === targetIndex) {
|
|
setDragIndex(null)
|
|
return
|
|
}
|
|
|
|
const previous = songs
|
|
const next = [...previous]
|
|
const [moved] = next.splice(dragIndex, 1)
|
|
next.splice(targetIndex, 0, moved)
|
|
setDragIndex(null)
|
|
setPlaylistSongs(next)
|
|
void persistOrder(previous, next)
|
|
}
|
|
|
|
async function handleDeletePlaylist() {
|
|
try {
|
|
await deletePlaylist({
|
|
playlistId: playlist.id as Id<"playlists">,
|
|
})
|
|
toast.success("Playlist deleted")
|
|
router.push("/playlists")
|
|
} catch (error) {
|
|
toast.error(
|
|
error instanceof Error ? error.message : "Failed to delete playlist"
|
|
)
|
|
}
|
|
}
|
|
|
|
async function handleSubscribeToggle() {
|
|
if (subscriptionPending) {
|
|
return
|
|
}
|
|
setSubscriptionPending(true)
|
|
try {
|
|
if (isSubscribed) {
|
|
await unsubscribe({
|
|
playlistId: playlist.id as Id<"playlists">,
|
|
})
|
|
setIsSubscribed(false)
|
|
toast.success("Unsubscribed from playlist")
|
|
} else {
|
|
await subscribe({
|
|
playlistId: playlist.id as Id<"playlists">,
|
|
})
|
|
setIsSubscribed(true)
|
|
toast.success("Subscribed to playlist")
|
|
}
|
|
} catch (error) {
|
|
toast.error(
|
|
error instanceof Error ? error.message : "Failed to update subscription"
|
|
)
|
|
} finally {
|
|
setSubscriptionPending(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="flex h-svh flex-col">
|
|
<PageHeader openApp />
|
|
<div className="flex shrink-0 justify-end px-4 pt-3 pb-1">
|
|
<div className="relative w-full md:w-64">
|
|
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
|
<input
|
|
type="search"
|
|
aria-label="Find in playlist"
|
|
placeholder="Find in Playlist"
|
|
value={searchQuery}
|
|
onChange={(event) => {
|
|
setSearchQuery(event.target.value)
|
|
clearSelection()
|
|
setActiveTrackId("")
|
|
setDragIndex(null)
|
|
}}
|
|
className="h-9 w-full min-w-0 rounded-full border border-input bg-input/30 pr-3 pl-9 text-sm text-foreground transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<ScrollArea className="min-h-0 flex-1">
|
|
<div className="pb-28">
|
|
<div className="mx-auto w-full max-w-9/10 min-w-0">
|
|
<div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end">
|
|
<div className="group relative mx-auto aspect-square w-full max-w-60 shrink-0 overflow-hidden rounded-lg ring-1 ring-foreground/10 sm:mx-0">
|
|
{isFavorites ? (
|
|
<div className="flex size-full items-center justify-center bg-muted">
|
|
<Star className="size-16 fill-primary text-primary" />
|
|
</div>
|
|
) : (
|
|
<Image
|
|
src={playlistCoverUrl(playlist.id!, playlist.cover, 512)}
|
|
alt={playlist.title}
|
|
fill
|
|
unoptimized
|
|
className="object-cover"
|
|
preload
|
|
/>
|
|
)}
|
|
{canEditCover ? (
|
|
<Button
|
|
variant="secondary"
|
|
size="icon"
|
|
className="absolute right-2 bottom-2 rounded-full opacity-0 shadow-md transition-opacity group-hover:opacity-100 focus-visible:opacity-100"
|
|
aria-label="Change cover"
|
|
onClick={() => setCoverDialogOpen(true)}
|
|
>
|
|
<Pencil />
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
|
|
<div className="flex min-w-0 flex-1 flex-col gap-4">
|
|
<div className="space-y-1 text-center sm:text-left">
|
|
<p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
|
Playlist
|
|
</p>
|
|
<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">
|
|
{playlist.title}
|
|
</h1>
|
|
<p className="text-lg font-semibold text-primary">
|
|
{playlist.owner.name}
|
|
</p>
|
|
<p className="text-sm text-muted-foreground empty:hidden">
|
|
<DownloadedQuality collection={downloadRef} />
|
|
</p>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
|
|
<Button
|
|
variant="secondary"
|
|
size="icon"
|
|
className="rounded-full"
|
|
aria-label="Shuffle playlist"
|
|
onClick={() => playAll(true)}
|
|
disabled={playlistSongIds.length === 0}
|
|
>
|
|
<Shuffle />
|
|
</Button>
|
|
<Button
|
|
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
|
|
aria-label={`Play ${playlist.title}`}
|
|
onClick={() => playAll(false)}
|
|
disabled={playlistSongIds.length === 0}
|
|
>
|
|
<Play className="fill-current" />
|
|
Play
|
|
</Button>
|
|
{!isOwner ? (
|
|
<Button
|
|
variant={isSubscribed ? "secondary" : "default"}
|
|
className="h-10 rounded-full px-6"
|
|
onClick={() => void handleSubscribeToggle()}
|
|
disabled={subscriptionPending}
|
|
>
|
|
{isSubscribed ? "Subscribed" : "Subscribe"}
|
|
</Button>
|
|
) : null}
|
|
<DownloadButton target={downloadTarget} />
|
|
{!isFavorites ? (
|
|
<Button
|
|
variant="secondary"
|
|
size="icon"
|
|
className="rounded-full"
|
|
aria-label="Share playlist"
|
|
onClick={() =>
|
|
void copyPlaylistLink(playlist.id!, {
|
|
isFavorites,
|
|
})
|
|
}
|
|
>
|
|
<Share2 />
|
|
</Button>
|
|
) : null}
|
|
<MediaContextMenu
|
|
label="More playlist options"
|
|
selectedCount={songs.length}
|
|
onOpenMenu={() => {}}
|
|
onAction={handlePlaylistMediaAction}
|
|
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
|
showFavorite={!isFavorites}
|
|
downloaded={playlistDownloaded}
|
|
trackRowTrigger={false}
|
|
triggerVariant="secondary"
|
|
triggerClassName="rounded-full"
|
|
share={{
|
|
type: "playlist",
|
|
playlistId: playlist.id ?? "favorites",
|
|
isFavorites,
|
|
}}
|
|
>
|
|
{isOwner && !isFavorites ? (
|
|
<>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuItem
|
|
className="justify-between"
|
|
onClick={() => setCoverDialogOpen(true)}
|
|
>
|
|
Change Cover
|
|
<ImageIcon />
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
variant="destructive"
|
|
className="justify-between"
|
|
onClick={handleDeletePlaylist}
|
|
>
|
|
Delete Playlist
|
|
<Trash2 />
|
|
</DropdownMenuItem>
|
|
</>
|
|
) : null}
|
|
</MediaContextMenu>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{filteredSongs.length > 0 ? (
|
|
<VirtualList
|
|
count={filteredSongs.length}
|
|
estimateSize={estimatePlaylistRowSize}
|
|
getItemKey={(index) => filteredSongs[index].id}
|
|
// Keep the drag source mounted so its drop still lands.
|
|
keepMounted={dragIndex}
|
|
renderItem={(index) => {
|
|
const song = filteredSongs[index]
|
|
return (
|
|
<TrackRow
|
|
variant="playlist"
|
|
song={song}
|
|
index={index}
|
|
trackNumber={playlistPositionById.get(song.id)}
|
|
isActive={song.id === activeTrackId}
|
|
isNowPlaying={currentSongId === song.id}
|
|
isFavorite={isSongFavorite(song.id)}
|
|
isDragging={dragIndex === index}
|
|
selectionPosition={selectionPositions[index]}
|
|
selectedCount={selectedCount}
|
|
selectionStationArtistId={selectedStationArtistId}
|
|
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
|
downloadCollection={downloadRef}
|
|
showFavoriteInMenu={!isFavorites}
|
|
removeLabel={
|
|
isFavorites
|
|
? "Unfavorite"
|
|
: isOwner
|
|
? "Remove from Playlist"
|
|
: undefined
|
|
}
|
|
onPointerDown={handlePointerDown}
|
|
onSelect={handleRowSelect}
|
|
onPlay={handleRowPlay}
|
|
onToggleFavorite={handleToggleFavorite}
|
|
onPrepareContextMenu={prepareContextMenu}
|
|
onMediaAction={handleMediaAction}
|
|
onRemove={handleRemoveSong}
|
|
onDragStart={canReorder ? setDragIndex : undefined}
|
|
onDrop={canReorder ? handleDrop : undefined}
|
|
/>
|
|
)
|
|
}}
|
|
/>
|
|
) : (
|
|
<p className="px-6 py-8 text-sm text-muted-foreground">
|
|
{isSearching
|
|
? "No songs found."
|
|
: "This playlist has no songs yet."}
|
|
</p>
|
|
)}
|
|
<MediaCollectionFooter
|
|
songCount={songs.length}
|
|
totalDurationSeconds={totalDurationSeconds}
|
|
/>
|
|
</div>
|
|
</div>
|
|
</ScrollArea>
|
|
{canEditCover ? (
|
|
<PlaylistCoverDialog
|
|
open={coverDialogOpen}
|
|
onOpenChange={setCoverDialogOpen}
|
|
playlistId={playlist.id!}
|
|
title={playlist.title}
|
|
coverVersion={playlist.cover}
|
|
songs={songs}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
)
|
|
}
|