feat: playlists and favorites
This commit is contained in:
32 files changed
+2701
-320
No files matched your search
@@ -7,7 +7,7 @@ import { AlbumView } from "@/components/album-view"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { AlbumDetail } from "@/lib/data"
|
||||
import type { BrowseAlbumDetail } from "@/convex/library"
|
||||
|
||||
export default function Page() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
@@ -33,5 +33,5 @@ export default function Page() {
|
||||
)
|
||||
}
|
||||
|
||||
return <AlbumView album={album as AlbumDetail} />
|
||||
return <AlbumView album={album} />
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider"
|
||||
import { FavoritesProvider } from "@/components/favorites-provider"
|
||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
|
||||
import { AppSidebar } from "@/components/app-sidebar"
|
||||
import { PlayerBar } from "@/components/player-bar"
|
||||
@@ -9,9 +11,13 @@ export default function AppLayout({
|
||||
}>) {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppSidebar />
|
||||
<SidebarInset>{children}</SidebarInset>
|
||||
<PlayerBar />
|
||||
<AddToPlaylistProvider>
|
||||
<FavoritesProvider>
|
||||
<AppSidebar />
|
||||
<SidebarInset>{children}</SidebarInset>
|
||||
<PlayerBar />
|
||||
</FavoritesProvider>
|
||||
</AddToPlaylistProvider>
|
||||
</SidebarProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowsePlaylistDetail } from "@/convex/library"
|
||||
|
||||
export default function Page() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const playlist = useQuery(api.playlists.browsePlaylistDetail, {
|
||||
id: id as Id<"playlists">,
|
||||
})
|
||||
|
||||
if (playlist === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (playlist === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">Playlist not found.</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={playlist} />
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { PlaylistView } from "@/components/playlist-view"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const favorites = useQuery(api.favorites.browseFavoritesPlaylistDetail)
|
||||
|
||||
if (favorites === undefined) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (favorites === null) {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<div className="flex flex-1 items-center justify-center pb-28">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sign in to view your favorites.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <PlaylistView playlist={favorites} />
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { PlaylistSummary } from "@/convex/library"
|
||||
import {
|
||||
albumGridCarouselContentClassName,
|
||||
albumGridCarouselSlideClassName,
|
||||
albumGridClassName,
|
||||
} from "@/lib/album-grid-classes"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { PlaylistCard } from "@/components/playlist-card"
|
||||
|
||||
export default function Page() {
|
||||
const playlists = useQuery(api.playlists.listAllPlaylists)
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Playlists</h1>
|
||||
</header>
|
||||
|
||||
{playlists === undefined ? (
|
||||
<LibraryLoading />
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto p-6 pb-28">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{playlists.map((playlist) => (
|
||||
<PlaylistCard key={playlist.id} playlist={playlist} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -7,10 +7,14 @@ import { SearchIcon } from "lucide-react"
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { SearchSongItem } from "@/components/search-song-item"
|
||||
import { placeholderPlaylists } from "@/lib/playlists"
|
||||
import { SearchTopResultCard, type TopResult } from "@/components/search-top-result-card"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Album, Artist, Song } from "@/lib/data"
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseArtist,
|
||||
BrowseSong,
|
||||
PlaylistSummary,
|
||||
} from "@/convex/library"
|
||||
|
||||
export default function Page() {
|
||||
const [query, setQuery] = useState("")
|
||||
@@ -21,8 +25,13 @@ export default function Page() {
|
||||
api.library.searchLibrary,
|
||||
hasQuery ? { query: deferredQuery } : "skip"
|
||||
)
|
||||
const playlistResults = useQuery(
|
||||
api.playlists.searchPlaylists,
|
||||
hasQuery ? { query: deferredQuery } : "skip"
|
||||
)
|
||||
|
||||
const showPlaylists = hasQuery && results !== undefined
|
||||
const showPlaylists =
|
||||
hasQuery && playlistResults !== undefined && playlistResults.length > 0
|
||||
const isSearching = hasQuery && results === undefined
|
||||
const hasLibraryResults =
|
||||
results &&
|
||||
@@ -82,14 +91,14 @@ export default function Page() {
|
||||
{results.artists.length > 0 && (
|
||||
<ContentCarousel
|
||||
title="Artists"
|
||||
content={results.artists as Artist[]}
|
||||
content={results.artists}
|
||||
/>
|
||||
)}
|
||||
|
||||
{results.albums.length > 0 && (
|
||||
<ContentCarousel
|
||||
title="Albums"
|
||||
content={results.albums as Album[]}
|
||||
content={results.albums}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -98,7 +107,7 @@ export default function Page() {
|
||||
<h2 className="text-xl font-bold tracking-tight">Songs</h2>
|
||||
<div className="grid gap-x-6 gap-y-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{results.songs.map((song) => (
|
||||
<SearchSongItem key={song.id} song={song as Song} />
|
||||
<SearchSongItem key={song.id} song={song} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
@@ -107,7 +116,7 @@ export default function Page() {
|
||||
{showPlaylists && (
|
||||
<ContentCarousel
|
||||
title="Playlists"
|
||||
content={placeholderPlaylists}
|
||||
content={playlistResults ?? []}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,28 +1,19 @@
|
||||
// import { api } from "@/convex/_generated/api"
|
||||
// import type { Id } from "@/convex/_generated/dataModel"
|
||||
// import { getConvexClient } from "@/lib/convex-server"
|
||||
import { PLACEHOLDER_PATH, serveCoverFile } from "@/lib/serve-cover"
|
||||
import fs from "node:fs/promises"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { getConvexClient } from "@/lib/convex-server"
|
||||
import { serveCoverFile } from "@/lib/serve-cover"
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
// const { id } = await params
|
||||
// try {
|
||||
// const album = await getConvexClient().query(api.library.getAlbum, {
|
||||
// id: id as Id<"albums">,
|
||||
// })
|
||||
// return serveCoverFile(album?.cover)
|
||||
// } catch {
|
||||
// return new Response("Not found", { status: 404 })
|
||||
// }
|
||||
|
||||
const placeholder = await fs.readFile(PLACEHOLDER_PATH)
|
||||
return new Response(placeholder, {
|
||||
headers: {
|
||||
"Content-Type": "image/svg+xml",
|
||||
"Cache-Control": "public, max-age=86400",
|
||||
},
|
||||
})
|
||||
const { id } = await params
|
||||
try {
|
||||
const playlist = await getConvexClient().query(api.library.getPlaylist, {
|
||||
id: id as Id<"playlists">,
|
||||
})
|
||||
return serveCoverFile(playlist?.cover)
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 })
|
||||
}
|
||||
}
|
||||
+7
-9
@@ -80,7 +80,6 @@
|
||||
--sidebar-accent-foreground: oklch(0.216 0.006 56.043);
|
||||
--sidebar-border: oklch(0.923 0.003 48.717);
|
||||
--sidebar-ring: oklch(0.709 0.01 56.259);
|
||||
--media-menu-highlight: color-mix(in oklch, var(--primary) 32%, var(--popover));
|
||||
}
|
||||
|
||||
.dark {
|
||||
@@ -115,16 +114,15 @@
|
||||
--sidebar-accent-foreground: oklch(0.985 0.001 106.423);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.553 0.013 58.071);
|
||||
--media-menu-highlight: color-mix(in oklch, var(--primary) 58%, var(--popover));
|
||||
}
|
||||
|
||||
.media-context-menu-trigger[data-state="open"] {
|
||||
background-color: var(--media-menu-highlight) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
.media-context-menu-trigger[data-state="open"]:hover {
|
||||
background-color: var(--media-menu-highlight) !important;
|
||||
.media-context-menu-trigger--in-range[data-state="open"],
|
||||
.media-context-menu-trigger--in-range[data-state="open"]:hover {
|
||||
background-color: color-mix(
|
||||
in oklch,
|
||||
var(--primary) 58%,
|
||||
var(--background)
|
||||
) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useConvex, useMutation, useQuery } from "convex/react"
|
||||
import { ListMusic, Plus } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
|
||||
type AddToPlaylistContextValue = {
|
||||
openAddToPlaylist: (songIds: Id<"songs">[]) => void
|
||||
openAddAlbumToPlaylist: (albumId: Id<"albums">) => Promise<void>
|
||||
openAddPlaylistToPlaylist: (playlistId: Id<"playlists">) => Promise<void>
|
||||
openAddArtistToPlaylist: (artistId: Id<"artists">) => Promise<void>
|
||||
}
|
||||
|
||||
const AddToPlaylistContext = React.createContext<AddToPlaylistContextValue | null>(
|
||||
null
|
||||
)
|
||||
|
||||
export function useAddToPlaylist() {
|
||||
const context = React.useContext(AddToPlaylistContext)
|
||||
if (!context) {
|
||||
throw new Error("useAddToPlaylist must be used within AddToPlaylistProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function AddToPlaylistProvider({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const convex = useConvex()
|
||||
const ownedPlaylists = useQuery(api.playlists.listOwnedPlaylists)
|
||||
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
|
||||
const createPlaylist = useMutation(api.playlists.createPlaylist)
|
||||
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [createOpen, setCreateOpen] = React.useState(false)
|
||||
const [newPlaylistName, setNewPlaylistName] = React.useState("")
|
||||
const [pendingSongIds, setPendingSongIds] = React.useState<Id<"songs">[]>([])
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false)
|
||||
|
||||
const openAddToPlaylist = React.useCallback((songIds: Id<"songs">[]) => {
|
||||
const unique = [...new Set(songIds)]
|
||||
if (unique.length === 0) {
|
||||
toast.error("No songs selected")
|
||||
return
|
||||
}
|
||||
setPendingSongIds(unique)
|
||||
setOpen(true)
|
||||
}, [])
|
||||
|
||||
const openAddAlbumToPlaylist = React.useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
albumId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddPlaylistToPlaylist = React.useCallback(
|
||||
async (playlistId: Id<"playlists">) => {
|
||||
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
|
||||
playlistId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
)
|
||||
|
||||
const openAddArtistToPlaylist = React.useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
const songIds = await convex.query(api.playlists.getArtistSongIds, {
|
||||
artistId,
|
||||
})
|
||||
openAddToPlaylist(songIds)
|
||||
},
|
||||
[convex, openAddToPlaylist]
|
||||
)
|
||||
|
||||
async function handleAddToPlaylist(playlistId: Id<"playlists">, title: string) {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await addSongs({ playlistId, songIds: pendingSongIds })
|
||||
const count = pendingSongIds.length
|
||||
toast.success(
|
||||
count > 1
|
||||
? `Added ${count} songs to ${title}`
|
||||
: `Added to ${title}`
|
||||
)
|
||||
setOpen(false)
|
||||
setPendingSongIds([])
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to add to playlist"
|
||||
)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreatePlaylist(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
const trimmed = newPlaylistName.trim()
|
||||
if (!trimmed) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await createPlaylist({
|
||||
name: trimmed,
|
||||
songIds: pendingSongIds,
|
||||
})
|
||||
const count = pendingSongIds.length
|
||||
toast.success(
|
||||
count > 1
|
||||
? `Created ${trimmed} with ${count} songs`
|
||||
: `Created ${trimmed}`
|
||||
)
|
||||
setCreateOpen(false)
|
||||
setOpen(false)
|
||||
setNewPlaylistName("")
|
||||
setPendingSongIds([])
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to create playlist"
|
||||
)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AddToPlaylistContext.Provider
|
||||
value={{
|
||||
openAddToPlaylist,
|
||||
openAddAlbumToPlaylist,
|
||||
openAddPlaylistToPlaylist,
|
||||
openAddArtistToPlaylist,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next)
|
||||
if (!next) {
|
||||
setPendingSongIds([])
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add to Playlist</DialogTitle>
|
||||
<DialogDescription>
|
||||
{pendingSongIds.length > 1
|
||||
? `Choose a playlist for ${pendingSongIds.length} songs.`
|
||||
: "Choose a playlist for this song."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-64">
|
||||
<div className="flex flex-col gap-1 pr-3">
|
||||
{ownedPlaylists === undefined ? (
|
||||
<p className="py-4 text-sm text-muted-foreground">Loading…</p>
|
||||
) : ownedPlaylists.length === 0 ? (
|
||||
<p className="py-4 text-sm text-muted-foreground">
|
||||
You do not have any playlists yet.
|
||||
</p>
|
||||
) : (
|
||||
ownedPlaylists.map((playlist) => (
|
||||
<Button
|
||||
key={playlist.id}
|
||||
variant="ghost"
|
||||
className="justify-start gap-2"
|
||||
disabled={isSubmitting}
|
||||
onClick={() =>
|
||||
handleAddToPlaylist(playlist.id, playlist.title)
|
||||
}
|
||||
>
|
||||
<ListMusic className="size-4 shrink-0" />
|
||||
<span className="truncate">{playlist.title}</span>
|
||||
</Button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter className="flex-col gap-2 sm:flex-col">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full gap-2"
|
||||
disabled={isSubmitting}
|
||||
onClick={() => {
|
||||
setCreateOpen(true)
|
||||
setNewPlaylistName("")
|
||||
}}
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
Create New Playlist
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<form onSubmit={handleCreatePlaylist}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New Playlist</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter a name for your new playlist.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
className="mt-4"
|
||||
placeholder="Playlist name"
|
||||
value={newPlaylistName}
|
||||
onChange={(event) => setNewPlaylistName(event.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
<DialogFooter className="mt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setCreateOpen(false)}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !newPlaylistName.trim()}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AddToPlaylistContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -9,8 +9,12 @@ import {
|
||||
MoreHorizontal,
|
||||
Play,
|
||||
Star,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -19,10 +23,14 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import type { Album } from "@/lib/data"
|
||||
import type { BrowseAlbum } from "@/convex/library"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
|
||||
export function AlbumCard({ album }: { album: Album }) {
|
||||
export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="group relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
|
||||
@@ -64,22 +72,48 @@ export function AlbumCard({ album }: { album: Album }) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem className="justify-between">
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
void openAddAlbumToPlaylist(album.id as Id<"albums">)
|
||||
}}
|
||||
>
|
||||
Add to Playlist
|
||||
<ListPlus />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="justify-between">
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={(event) => event.preventDefault()}
|
||||
>
|
||||
Play Next
|
||||
<ListStart />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="justify-between">
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={(event) => event.preventDefault()}
|
||||
>
|
||||
Play Last
|
||||
<ListEnd />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="justify-between">
|
||||
Favorite
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<Link href={`/artist/${album.artist.id}`}>
|
||||
Go to Artist
|
||||
<User />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant={isAlbumFavorite(album.id) ? "destructive" : "default"}
|
||||
className="justify-between"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
void toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
}}
|
||||
>
|
||||
{isAlbumFavorite(album.id) ? "Unfavorite" : "Favorite"}
|
||||
<Star />
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
|
||||
+36
-48
@@ -5,7 +5,9 @@ import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Play, Share2, Shuffle, Star } from "lucide-react"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import {
|
||||
@@ -16,7 +18,8 @@ import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { AlbumDetail, AlbumTrack } from "@/lib/data"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@/convex/library"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
isInSelectionRange,
|
||||
@@ -60,6 +63,7 @@ function formatMetadata(genre: string | null, year: number | null): string | nul
|
||||
function TrackRow({
|
||||
track,
|
||||
index,
|
||||
artist,
|
||||
isActive,
|
||||
isSelected,
|
||||
selectionPosition,
|
||||
@@ -71,8 +75,9 @@ function TrackRow({
|
||||
onPrepareContextMenu,
|
||||
onMediaAction,
|
||||
}: {
|
||||
track: AlbumTrack
|
||||
track: BrowseAlbumTrack
|
||||
index: number
|
||||
artist: BrowseAlbumDetail["artist"]
|
||||
isActive: boolean
|
||||
isSelected: boolean
|
||||
selectionPosition: SelectionRangePosition
|
||||
@@ -172,29 +177,32 @@ function TrackRow({
|
||||
<MediaContextMenu
|
||||
label={`More options for ${track.title}`}
|
||||
selectedCount={selectedCount}
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={onPrepareContextMenu}
|
||||
onAction={(action) => onMediaAction(action, track.id)}
|
||||
triggerClassName={cn(
|
||||
"size-8 shrink-0 transition-opacity",
|
||||
inRange
|
||||
? "text-primary-foreground opacity-100 hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
|
||||
)}
|
||||
favorited={isFavorite}
|
||||
navigation={{
|
||||
artist: { id: artist.id },
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const {
|
||||
isSongFavorite,
|
||||
isAlbumFavorite,
|
||||
toggleSongFavorite,
|
||||
toggleAlbumFavorite,
|
||||
favoriteSongs,
|
||||
} = useFavorites()
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState(
|
||||
() => album.tracks[0]?.id ?? ""
|
||||
)
|
||||
const [isAlbumFavorite, setIsAlbumFavorite] = React.useState(false)
|
||||
const [favoriteIds, setFavoriteIds] = React.useState<Set<string>>(
|
||||
() => new Set()
|
||||
)
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
@@ -211,18 +219,6 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
[album.tracks, selectedIds]
|
||||
)
|
||||
|
||||
function toggleFavorite(trackId: string) {
|
||||
setFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
if (next.has(trackId)) {
|
||||
next.delete(trackId)
|
||||
} else {
|
||||
next.add(trackId)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function handleMediaAction(
|
||||
action: MediaContextAction,
|
||||
fallbackTrackId?: string
|
||||
@@ -239,23 +235,10 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
setFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
for (const id of targetIds) {
|
||||
next.add(id)
|
||||
}
|
||||
return next
|
||||
})
|
||||
toast.success(
|
||||
count > 1 ? `Favorited ${count} songs` : "Added to favorites"
|
||||
)
|
||||
void favoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
toast.success(
|
||||
count > 1
|
||||
? `Added ${count} songs to playlist`
|
||||
: "Added to playlist"
|
||||
)
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
toast.success(
|
||||
@@ -276,12 +259,10 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
setIsAlbumFavorite(true)
|
||||
setFavoriteIds(new Set(targetIds))
|
||||
toast.success(`Favorited ${count} songs`)
|
||||
void toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
break
|
||||
case "playlist":
|
||||
toast.success(`Added ${count} songs to playlist`)
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
toast.success(`Queued ${count} songs to play next`)
|
||||
@@ -310,6 +291,8 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
selectedCount={album.tracks.length}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={handleAlbumMediaAction}
|
||||
favorited={isAlbumFavorite(album.id)}
|
||||
trackRowTrigger={false}
|
||||
triggerClassName="size-8"
|
||||
/>
|
||||
</div>
|
||||
@@ -363,8 +346,10 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
Play
|
||||
</Button>
|
||||
<FavoriteMediaButton
|
||||
isFavorite={isAlbumFavorite}
|
||||
onToggle={() => setIsAlbumFavorite((current) => !current)}
|
||||
isFavorite={isAlbumFavorite(album.id)}
|
||||
onToggle={() =>
|
||||
void toggleAlbumFavorite(album.id as Id<"albums">)
|
||||
}
|
||||
favoritedLabel={`Remove ${album.title} from favorites`}
|
||||
unfavoritedLabel={`Favorite ${album.title}`}
|
||||
/>
|
||||
@@ -378,10 +363,11 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
key={track.id}
|
||||
track={track}
|
||||
index={index}
|
||||
artist={album.artist}
|
||||
isActive={track.id === activeTrackId}
|
||||
isSelected={isSelected(track.id)}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={favoriteIds.has(track.id)}
|
||||
isFavorite={isSongFavorite(track.id)}
|
||||
selectedCount={
|
||||
isSelected(track.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
@@ -392,7 +378,9 @@ export function AlbumView({ album }: { album: AlbumDetail }) {
|
||||
handleSelect(track.id, index, event)
|
||||
setActiveTrackId(track.id)
|
||||
}}
|
||||
onToggleFavorite={() => toggleFavorite(track.id)}
|
||||
onToggleFavorite={() =>
|
||||
void toggleSongFavorite(track.id as Id<"songs">)
|
||||
}
|
||||
onPrepareContextMenu={() => prepareContextMenu(track.id)}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
|
||||
+18
-13
@@ -41,7 +41,6 @@ import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { useTheme } from "next-themes"
|
||||
import * as React from "react"
|
||||
import { placeholderPlaylists } from "@/lib/playlists"
|
||||
import { useQuery } from "convex/react"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
@@ -56,21 +55,12 @@ const library = [
|
||||
{ title: "Songs", path: "/library/songs", icon: Music2 },
|
||||
]
|
||||
|
||||
const playlists = [
|
||||
{ title: "All Playlists", path: "/playlists", icon: LayoutGrid },
|
||||
{ title: "Favorites", path: "/playlist/favorites", icon: Star },
|
||||
...placeholderPlaylists.map((playlist) => ({
|
||||
title: playlist.title,
|
||||
path: `/playlist/${playlist.id}`,
|
||||
icon: ListMusic,
|
||||
})),
|
||||
]
|
||||
|
||||
export function AppSidebar() {
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const { signOut } = useAuthActions()
|
||||
const user = useQuery(api.auth.currentUser)
|
||||
const sidebarPlaylists = useQuery(api.playlists.listSidebarPlaylists)
|
||||
const fallbackLetters = user?.name?.match(/\b(\w)/g)!.join('') || "NA"
|
||||
|
||||
const { resolvedTheme } = useTheme()
|
||||
@@ -88,6 +78,21 @@ export function AppSidebar() {
|
||||
|
||||
const isDark = mounted && resolvedTheme === "dark"
|
||||
|
||||
const playlistNav = [
|
||||
{ title: "All Playlists", path: "/playlists", icon: LayoutGrid },
|
||||
{ title: "Favorites", path: "/playlist/favorites", icon: Star },
|
||||
...(sidebarPlaylists?.owned ?? []).map((playlist) => ({
|
||||
title: playlist.title,
|
||||
path: `/playlist/${playlist.id}`,
|
||||
icon: ListMusic,
|
||||
})),
|
||||
...(sidebarPlaylists?.subscribed ?? []).map((playlist) => ({
|
||||
title: playlist.title,
|
||||
path: `/playlist/${playlist.id}`,
|
||||
icon: ListMusic,
|
||||
})),
|
||||
]
|
||||
|
||||
return (
|
||||
<Sidebar>
|
||||
<SidebarHeader>
|
||||
@@ -143,8 +148,8 @@ export function AppSidebar() {
|
||||
<SidebarGroupLabel>Playlists</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{playlists.map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
{playlistNav.map((item) => (
|
||||
<SidebarMenuItem key={item.path}>
|
||||
<SidebarMenuButton isActive={pathname === item.path} asChild>
|
||||
<Link href={item.path}>
|
||||
<item.icon />
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
|
||||
import type { Artist } from "@/lib/data"
|
||||
import type { BrowseArtist } from "@/convex/library"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
|
||||
export function ArtistCard({ artist }: { artist: Artist }) {
|
||||
export function ArtistCard({ artist }: { artist: BrowseArtist }) {
|
||||
return (
|
||||
<div className="group flex flex-col items-center gap-2">
|
||||
<Link
|
||||
|
||||
+18
-11
@@ -5,6 +5,8 @@ import Image from "next/image"
|
||||
import { Play, Shuffle } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { ContentCarousel } from "@/components/content-carousel"
|
||||
@@ -14,7 +16,8 @@ import {
|
||||
} from "@/components/media-context-menu"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import type { Album, Artist } from "@/lib/data"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowseAlbum, BrowseArtist } from "@/convex/library"
|
||||
import {
|
||||
albumGridCarouselContentClassName,
|
||||
albumGridCarouselSlideClassName,
|
||||
@@ -28,21 +31,21 @@ export function ArtistView({
|
||||
recentlyAdded,
|
||||
recentlyPlayed,
|
||||
}: {
|
||||
artist: Artist
|
||||
albums: Album[]
|
||||
recentlyAdded: Album[]
|
||||
recentlyPlayed: Album[]
|
||||
artist: BrowseArtist
|
||||
albums: BrowseAlbum[]
|
||||
recentlyAdded: BrowseAlbum[]
|
||||
recentlyPlayed: BrowseAlbum[]
|
||||
}) {
|
||||
const [isFavorite, setIsFavorite] = React.useState(false)
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
|
||||
function handleMediaAction(action: MediaContextAction) {
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
setIsFavorite(true)
|
||||
toast.success("Added artist to favorites")
|
||||
void toggleArtistFavorite(artist.id as Id<"artists">)
|
||||
break
|
||||
case "playlist":
|
||||
toast.success("Added to playlist")
|
||||
void openAddArtistToPlaylist(artist.id as Id<"artists">)
|
||||
break
|
||||
case "play-next":
|
||||
toast.success("Play next")
|
||||
@@ -91,8 +94,10 @@ export function ArtistView({
|
||||
<Shuffle className="size-4" />
|
||||
</Button>
|
||||
<FavoriteMediaButton
|
||||
isFavorite={isFavorite}
|
||||
onToggle={() => setIsFavorite((current) => !current)}
|
||||
isFavorite={isArtistFavorite(artist.id)}
|
||||
onToggle={() =>
|
||||
void toggleArtistFavorite(artist.id as Id<"artists">)
|
||||
}
|
||||
favoritedLabel={`Remove ${artist.name} from favorites`}
|
||||
unfavoritedLabel={`Favorite ${artist.name}`}
|
||||
className="size-11"
|
||||
@@ -102,6 +107,8 @@ export function ArtistView({
|
||||
selectedCount={albums.length}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={handleMediaAction}
|
||||
favorited={isArtistFavorite(artist.id)}
|
||||
trackRowTrigger={false}
|
||||
triggerVariant="secondary"
|
||||
triggerClassName="size-11 rounded-full"
|
||||
triggerIconClassName="size-4"
|
||||
|
||||
+10
-18
@@ -7,13 +7,15 @@ import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { Album, Artist } from "@/lib/data"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowseAlbum, BrowseArtist } from "@/convex/library"
|
||||
import { artistCoverUrl } from "@/lib/cover-urls"
|
||||
|
||||
function ArtistAvatar({ artist }: { artist: Artist }) {
|
||||
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
|
||||
return (
|
||||
<div className="relative size-8 shrink-0 overflow-hidden rounded-full ring-1 ring-foreground/10">
|
||||
<Image
|
||||
@@ -31,7 +33,7 @@ function ArtistListItem({
|
||||
isSelected,
|
||||
onSelect,
|
||||
}: {
|
||||
artist: Artist
|
||||
artist: BrowseArtist
|
||||
isSelected: boolean
|
||||
onSelect: () => void
|
||||
}) {
|
||||
@@ -54,8 +56,8 @@ export function ArtistsView({
|
||||
artists,
|
||||
albums,
|
||||
}: {
|
||||
artists: Artist[]
|
||||
albums: Album[]
|
||||
artists: BrowseArtist[]
|
||||
albums: BrowseAlbum[]
|
||||
}) {
|
||||
const sortedArtists = React.useMemo(
|
||||
() => [...artists].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
@@ -65,9 +67,7 @@ export function ArtistsView({
|
||||
const [selectedId, setSelectedId] = React.useState(
|
||||
() => sortedArtists[0]?.id ?? ""
|
||||
)
|
||||
const [favoriteIds, setFavoriteIds] = React.useState<Set<string>>(
|
||||
() => new Set()
|
||||
)
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
|
||||
const selectedArtist = sortedArtists.find(
|
||||
(artist) => artist.id === selectedId
|
||||
@@ -114,17 +114,9 @@ export function ArtistsView({
|
||||
<Shuffle />
|
||||
</Button>
|
||||
<FavoriteMediaButton
|
||||
isFavorite={favoriteIds.has(selectedArtist.id)}
|
||||
isFavorite={isArtistFavorite(selectedArtist.id)}
|
||||
onToggle={() =>
|
||||
setFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
if (next.has(selectedArtist.id)) {
|
||||
next.delete(selectedArtist.id)
|
||||
} else {
|
||||
next.add(selectedArtist.id)
|
||||
}
|
||||
return next
|
||||
})
|
||||
void toggleArtistFavorite(selectedArtist.id as Id<"artists">)
|
||||
}
|
||||
favoritedLabel={`Remove ${selectedArtist.name} from favorites`}
|
||||
unfavoritedLabel={`Favorite ${selectedArtist.name}`}
|
||||
|
||||
@@ -4,7 +4,11 @@ import Link from "next/link"
|
||||
import { ChevronRightIcon } from "lucide-react"
|
||||
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import type { Album, Artist, Playlist } from "@/lib/data"
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseArtist,
|
||||
PlaylistSummary,
|
||||
} from "@/convex/library"
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
@@ -16,7 +20,11 @@ import { cn } from "@/lib/utils"
|
||||
import { ArtistCard } from "./artist-card"
|
||||
import { PlaylistCard } from "./playlist-card"
|
||||
|
||||
function CarouselCard({ item }: { item: Album | Artist | Playlist }) {
|
||||
function CarouselCard({
|
||||
item,
|
||||
}: {
|
||||
item: BrowseAlbum | BrowseArtist | PlaylistSummary
|
||||
}) {
|
||||
if ("owner" in item) {
|
||||
return <PlaylistCard playlist={item} />
|
||||
}
|
||||
@@ -36,7 +44,7 @@ export function ContentCarousel({
|
||||
}: {
|
||||
title: string
|
||||
href?: string
|
||||
content: (Album | Artist | Playlist)[]
|
||||
content: (BrowseAlbum | BrowseArtist | PlaylistSummary)[]
|
||||
className?: string
|
||||
slideClassName?: string
|
||||
carouselContentClassName?: string
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useMutation, useQuery } from "convex/react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
|
||||
type FavoritesContextValue = {
|
||||
isSongFavorite: (songId: string) => boolean
|
||||
isAlbumFavorite: (albumId: string) => boolean
|
||||
isArtistFavorite: (artistId: string) => boolean
|
||||
toggleSongFavorite: (songId: Id<"songs">) => Promise<void>
|
||||
toggleSongsFavorite: (songIds: Id<"songs">[], favorited: boolean) => Promise<void>
|
||||
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
|
||||
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
|
||||
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
||||
}
|
||||
|
||||
const FavoritesContext = React.createContext<FavoritesContextValue | null>(null)
|
||||
|
||||
export function useFavorites() {
|
||||
const context = React.useContext(FavoritesContext)
|
||||
if (!context) {
|
||||
throw new Error("useFavorites must be used within FavoritesProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function FavoritesProvider({ children }: { children: React.ReactNode }) {
|
||||
const favorites = useQuery(api.favorites.getUserFavorites)
|
||||
const favoriteSong = useMutation(api.favorites.favoriteSong)
|
||||
const favoriteSongsMutation = useMutation(api.favorites.favoriteSongs)
|
||||
const unfavoriteSong = useMutation(api.favorites.unfavoriteSong)
|
||||
const unfavoriteSongs = useMutation(api.favorites.unfavoriteSongs)
|
||||
const favoriteAlbum = useMutation(api.favorites.favoriteAlbum)
|
||||
const unfavoriteAlbum = useMutation(api.favorites.unfavoriteAlbum)
|
||||
const favoriteArtist = useMutation(api.favorites.favoriteArtist)
|
||||
const unfavoriteArtist = useMutation(api.favorites.unfavoriteArtist)
|
||||
|
||||
const songIds = React.useMemo(
|
||||
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
|
||||
[favorites?.favoriteSongs]
|
||||
)
|
||||
const albumIds = React.useMemo(
|
||||
() => new Set(favorites?.favoriteAlbums.map(String) ?? []),
|
||||
[favorites?.favoriteAlbums]
|
||||
)
|
||||
const artistIds = React.useMemo(
|
||||
() => new Set(favorites?.favoriteArtists.map(String) ?? []),
|
||||
[favorites?.favoriteArtists]
|
||||
)
|
||||
|
||||
const isSongFavorite = React.useCallback(
|
||||
(songId: string) => songIds.has(songId),
|
||||
[songIds]
|
||||
)
|
||||
const isAlbumFavorite = React.useCallback(
|
||||
(albumId: string) => albumIds.has(albumId),
|
||||
[albumIds]
|
||||
)
|
||||
const isArtistFavorite = React.useCallback(
|
||||
(artistId: string) => artistIds.has(artistId),
|
||||
[artistIds]
|
||||
)
|
||||
|
||||
const toggleSongFavorite = React.useCallback(
|
||||
async (songId: Id<"songs">) => {
|
||||
try {
|
||||
if (songIds.has(songId)) {
|
||||
await unfavoriteSong({ songId })
|
||||
toast.success("Removed from favorites")
|
||||
} else {
|
||||
await favoriteSong({ songId })
|
||||
toast.success("Added to favorites")
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[songIds, favoriteSong, unfavoriteSong]
|
||||
)
|
||||
|
||||
const favoriteSongs = React.useCallback(
|
||||
async (ids: Id<"songs">[]) => {
|
||||
const unique = [...new Set(ids)]
|
||||
if (unique.length === 0) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await favoriteSongsMutation({ songIds: unique })
|
||||
toast.success(
|
||||
unique.length > 1
|
||||
? `Favorited ${unique.length} songs`
|
||||
: "Added to favorites"
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteSongsMutation]
|
||||
)
|
||||
|
||||
const toggleSongsFavorite = React.useCallback(
|
||||
async (ids: Id<"songs">[], favorited: boolean) => {
|
||||
const unique = [...new Set(ids)]
|
||||
if (unique.length === 0) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (favorited) {
|
||||
await unfavoriteSongs({ songIds: unique })
|
||||
toast.success(
|
||||
unique.length > 1
|
||||
? `Removed ${unique.length} songs from favorites`
|
||||
: "Removed from favorites"
|
||||
)
|
||||
} else {
|
||||
await favoriteSongsMutation({ songIds: unique })
|
||||
toast.success(
|
||||
unique.length > 1
|
||||
? `Favorited ${unique.length} songs`
|
||||
: "Added to favorites"
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[favoriteSongsMutation, unfavoriteSongs]
|
||||
)
|
||||
|
||||
const toggleAlbumFavorite = React.useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
try {
|
||||
if (albumIds.has(albumId)) {
|
||||
await unfavoriteAlbum({ albumId })
|
||||
toast.success("Removed album from favorites")
|
||||
} else {
|
||||
await favoriteAlbum({ albumId })
|
||||
toast.success("Added album to favorites")
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[albumIds, favoriteAlbum, unfavoriteAlbum]
|
||||
)
|
||||
|
||||
const toggleArtistFavorite = React.useCallback(
|
||||
async (artistId: Id<"artists">) => {
|
||||
try {
|
||||
if (artistIds.has(artistId)) {
|
||||
await unfavoriteArtist({ artistId })
|
||||
toast.success("Removed artist from favorites")
|
||||
} else {
|
||||
await favoriteArtist({ artistId })
|
||||
toast.success("Added artist to favorites")
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to update favorites"
|
||||
)
|
||||
}
|
||||
},
|
||||
[artistIds, favoriteArtist, unfavoriteArtist]
|
||||
)
|
||||
|
||||
const value = React.useMemo(
|
||||
() => ({
|
||||
isSongFavorite,
|
||||
isAlbumFavorite,
|
||||
isArtistFavorite,
|
||||
toggleSongFavorite,
|
||||
toggleSongsFavorite,
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
favoriteSongs,
|
||||
}),
|
||||
[
|
||||
isSongFavorite,
|
||||
isAlbumFavorite,
|
||||
isArtistFavorite,
|
||||
toggleSongFavorite,
|
||||
toggleSongsFavorite,
|
||||
toggleAlbumFavorite,
|
||||
toggleArtistFavorite,
|
||||
favoriteSongs,
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
<FavoritesContext.Provider value={value}>{children}</FavoritesContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import Link from "next/link"
|
||||
import {
|
||||
Disc3,
|
||||
ListEnd,
|
||||
ListPlus,
|
||||
ListStart,
|
||||
MoreHorizontal,
|
||||
Star,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -20,6 +24,11 @@ import { cn } from "@/lib/utils"
|
||||
|
||||
export type MediaContextAction = "playlist" | "play-next" | "play-last" | "favorite"
|
||||
|
||||
export type MediaContextNavigation = {
|
||||
artist?: { id: string }
|
||||
album?: { id: string }
|
||||
}
|
||||
|
||||
function actionLabel(base: string, selectedCount: number) {
|
||||
return selectedCount > 1 ? `${base} (${selectedCount})` : base
|
||||
}
|
||||
@@ -27,17 +36,27 @@ function actionLabel(base: string, selectedCount: number) {
|
||||
export function MediaContextMenuItems({
|
||||
selectedCount,
|
||||
onAction,
|
||||
playlistLabel = "Add to Playlist",
|
||||
showFavorite = true,
|
||||
favorited = false,
|
||||
navigation,
|
||||
}: {
|
||||
selectedCount: number
|
||||
onAction: (action: MediaContextAction) => void
|
||||
playlistLabel?: string
|
||||
showFavorite?: boolean
|
||||
favorited?: boolean
|
||||
navigation?: MediaContextNavigation
|
||||
}) {
|
||||
const { artist, album } = navigation ?? {}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("playlist")}
|
||||
>
|
||||
{actionLabel("Add to Playlist", selectedCount)}
|
||||
{actionLabel(playlistLabel, selectedCount)}
|
||||
<ListPlus />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
@@ -55,36 +74,102 @@ export function MediaContextMenuItems({
|
||||
{actionLabel("Play Last", selectedCount)}
|
||||
<ListEnd />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("favorite")}
|
||||
>
|
||||
{actionLabel("Favorite", selectedCount)}
|
||||
<Star />
|
||||
</DropdownMenuItem>
|
||||
{artist || album ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{artist ? (
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<Link href={`/artist/${artist.id}`}>
|
||||
Go to Artist
|
||||
<User />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{album ? (
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<Link href={`/album/${album.id}`}>
|
||||
Go to Album
|
||||
<Disc3 />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{showFavorite ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant={favorited ? "destructive" : "default"}
|
||||
className="justify-between"
|
||||
onClick={() => onAction("favorite")}
|
||||
>
|
||||
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
|
||||
<Star />
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function mediaContextMenuTriggerClassName({
|
||||
inSelectionRange = false,
|
||||
trackRow = true,
|
||||
className,
|
||||
}: {
|
||||
inSelectionRange?: boolean
|
||||
/** When false, uses default button styling (e.g. page header menus). */
|
||||
trackRow?: boolean
|
||||
className?: string
|
||||
}) {
|
||||
if (!trackRow) {
|
||||
return cn(className)
|
||||
}
|
||||
|
||||
return cn(
|
||||
"media-context-menu-trigger",
|
||||
"size-8 shrink-0 transition-opacity",
|
||||
inSelectionRange
|
||||
? "text-primary-foreground opacity-100 hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100",
|
||||
inSelectionRange && "media-context-menu-trigger--in-range",
|
||||
className
|
||||
)
|
||||
}
|
||||
|
||||
export function MediaContextMenu({
|
||||
label,
|
||||
selectedCount,
|
||||
onOpenMenu,
|
||||
onAction,
|
||||
playlistLabel,
|
||||
showFavorite = true,
|
||||
favorited = false,
|
||||
navigation,
|
||||
inSelectionRange = false,
|
||||
trackRowTrigger = true,
|
||||
triggerClassName,
|
||||
triggerVariant = "ghost",
|
||||
triggerIconClassName = "size-4",
|
||||
align = "end",
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
selectedCount: number
|
||||
onOpenMenu: () => void
|
||||
onAction: (action: MediaContextAction) => void
|
||||
playlistLabel?: string
|
||||
showFavorite?: boolean
|
||||
favorited?: boolean
|
||||
navigation?: MediaContextNavigation
|
||||
inSelectionRange?: boolean
|
||||
/** When false, the trigger uses default button/dropdown styling (page headers). */
|
||||
trackRowTrigger?: boolean
|
||||
triggerClassName?: string
|
||||
triggerVariant?: "ghost" | "secondary"
|
||||
triggerIconClassName?: string
|
||||
align?: "start" | "end"
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenu
|
||||
@@ -98,7 +183,11 @@ export function MediaContextMenu({
|
||||
<Button
|
||||
variant={triggerVariant}
|
||||
size="icon"
|
||||
className={cn("media-context-menu-trigger", triggerClassName)}
|
||||
className={mediaContextMenuTriggerClassName({
|
||||
inSelectionRange,
|
||||
trackRow: trackRowTrigger,
|
||||
className: triggerClassName,
|
||||
})}
|
||||
aria-label={label}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
@@ -109,7 +198,12 @@ export function MediaContextMenu({
|
||||
<MediaContextMenuItems
|
||||
selectedCount={selectedCount}
|
||||
onAction={onAction}
|
||||
playlistLabel={playlistLabel}
|
||||
showFavorite={showFavorite}
|
||||
favorited={favorited}
|
||||
navigation={navigation}
|
||||
/>
|
||||
{children}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
|
||||
@@ -3,13 +3,17 @@
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
|
||||
import type { Playlist } from "@/lib/data"
|
||||
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import type { PlaylistSummary } from "@/convex/library"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import { playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ListEnd, ListPlus, ListStart, MoreHorizontal, Play, Star } from "lucide-react"
|
||||
import { ListEnd, ListPlus, ListStart, MoreHorizontal, Play } from "lucide-react"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
|
||||
export function PlaylistCard({ playlist }: { playlist: Playlist }) {
|
||||
export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="group relative aspect-square overflow-hidden rounded-lg ring-1 ring-foreground/10">
|
||||
@@ -48,16 +52,28 @@ export function PlaylistCard({ playlist }: { playlist: Playlist }) {
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem className="justify-between">
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
void openAddPlaylistToPlaylist(playlist.id as Id<"playlists">)
|
||||
}}
|
||||
>
|
||||
Add to Playlist
|
||||
<ListPlus />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="justify-between">
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={(event) => event.preventDefault()}
|
||||
>
|
||||
Play Next
|
||||
<ListStart />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="justify-between">
|
||||
<DropdownMenuItem
|
||||
className="justify-between"
|
||||
onClick={(event) => event.preventDefault()}
|
||||
>
|
||||
Play Last
|
||||
<ListEnd />
|
||||
</DropdownMenuItem>
|
||||
|
||||
@@ -0,0 +1,649 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useMutation } from "convex/react"
|
||||
import {
|
||||
MoreHorizontal,
|
||||
Play,
|
||||
Share2,
|
||||
Shuffle,
|
||||
Star,
|
||||
Trash2,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowsePlaylistDetail, BrowseSong } from "@/convex/library"
|
||||
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
|
||||
import { cn } from "@/lib/utils"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
isInSelectionRange,
|
||||
ALBUM_TRACK_ROW,
|
||||
ALBUM_TRACK_TITLE,
|
||||
SelectionRangeHighlight,
|
||||
TrackRowActiveHighlight,
|
||||
TrackRowHoverHighlight,
|
||||
TRACK_ROW_PADDING,
|
||||
type SelectionRangePosition,
|
||||
} from "@/lib/selection-range-styles"
|
||||
|
||||
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function playlistUrl(playlist: BrowsePlaylistDetail) {
|
||||
if (playlist.isFavorites) {
|
||||
return `${window.location.origin}/playlist/favorites`
|
||||
}
|
||||
return `${window.location.origin}/playlist/${playlist.id}`
|
||||
}
|
||||
|
||||
async function copyPlaylistLink(playlist: BrowsePlaylistDetail) {
|
||||
await navigator.clipboard.writeText(playlistUrl(playlist))
|
||||
toast.success("Link Copied")
|
||||
}
|
||||
|
||||
function PlaylistSongCover({
|
||||
song,
|
||||
inRange,
|
||||
isFavorite,
|
||||
onToggleFavorite,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
inRange: boolean
|
||||
isFavorite: boolean
|
||||
onToggleFavorite: () => void
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group/cover relative size-10 shrink-0 overflow-hidden rounded ring-1",
|
||||
inRange ? "ring-white/25" : "ring-foreground/10"
|
||||
)}
|
||||
>
|
||||
<Image
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="40px"
|
||||
className="object-cover"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-opacity group-hover/cover:opacity-100",
|
||||
"group-hover/cover:bg-black/40"
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={cn(
|
||||
"size-8",
|
||||
inRange
|
||||
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "text-primary hover:text-primary"
|
||||
)}
|
||||
aria-label={
|
||||
isFavorite
|
||||
? `Remove ${song.title} from favorites`
|
||||
: `Favorite ${song.title}`
|
||||
}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onToggleFavorite()
|
||||
}}
|
||||
>
|
||||
<Star
|
||||
className={cn(
|
||||
"size-4",
|
||||
isFavorite && (inRange ? "fill-current" : "fill-primary")
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PlaylistSongRow({
|
||||
song,
|
||||
index,
|
||||
isOwner,
|
||||
canRemove,
|
||||
isActive,
|
||||
isSelected,
|
||||
selectionPosition,
|
||||
isFavorite,
|
||||
selectedCount,
|
||||
isDragging,
|
||||
onSelect,
|
||||
onPointerDown,
|
||||
onToggleFavorite,
|
||||
onPrepareContextMenu,
|
||||
onMediaAction,
|
||||
onRemove,
|
||||
onDragStart,
|
||||
onDragOver,
|
||||
onDrop,
|
||||
showFavoriteInMenu = true,
|
||||
removeLabel = "Remove from Playlist",
|
||||
}: {
|
||||
song: BrowseSong
|
||||
index: number
|
||||
isOwner: boolean
|
||||
canRemove: boolean
|
||||
isActive: boolean
|
||||
isSelected: boolean
|
||||
selectionPosition: SelectionRangePosition
|
||||
isFavorite: boolean
|
||||
selectedCount: number
|
||||
isDragging: boolean
|
||||
onSelect: (event: React.MouseEvent) => void
|
||||
onPointerDown: (event: React.MouseEvent) => void
|
||||
onToggleFavorite: () => void
|
||||
onPrepareContextMenu: () => void
|
||||
onMediaAction: (action: MediaContextAction, songId: string) => void
|
||||
onRemove: () => void
|
||||
onDragStart: (event: React.DragEvent) => void
|
||||
onDragOver: (event: React.DragEvent) => void
|
||||
onDrop: (event: React.DragEvent) => void
|
||||
showFavoriteInMenu?: boolean
|
||||
removeLabel?: string
|
||||
}) {
|
||||
const displayTrack = index + 1
|
||||
const inRange = isInSelectionRange(selectionPosition)
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
draggable={isOwner}
|
||||
onDragStart={onDragStart}
|
||||
onDragOver={onDragOver}
|
||||
onDrop={onDrop}
|
||||
onMouseDown={onPointerDown}
|
||||
onClick={onSelect}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault()
|
||||
onSelect(event as unknown as React.MouseEvent)
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors",
|
||||
inRange && "text-primary-foreground",
|
||||
isDragging && "opacity-50"
|
||||
)}
|
||||
>
|
||||
<SelectionRangeHighlight position={selectionPosition} />
|
||||
{!inRange && isActive ? <TrackRowActiveHighlight /> : null}
|
||||
{!inRange && !isActive ? <TrackRowHoverHighlight /> : null}
|
||||
<div
|
||||
className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}
|
||||
>
|
||||
<PlaylistSongCover
|
||||
song={song}
|
||||
inRange={inRange}
|
||||
isFavorite={isFavorite}
|
||||
onToggleFavorite={onToggleFavorite}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-8 shrink-0 items-center justify-center tabular-nums",
|
||||
inRange ? "text-primary-foreground" : "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{isActive ? (
|
||||
<Play
|
||||
className={cn(
|
||||
"size-4 fill-current",
|
||||
inRange ? "text-primary-foreground" : "text-primary"
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<span>{displayTrack}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<span className={ALBUM_TRACK_TITLE}>{song.title}</span>
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 text-right tabular-nums",
|
||||
inRange ? "text-primary-foreground" : "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
{formatDuration(song.durationSeconds)}
|
||||
</span>
|
||||
|
||||
<MediaContextMenu
|
||||
label={`More options for ${song.title}`}
|
||||
selectedCount={selectedCount}
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={onPrepareContextMenu}
|
||||
onAction={(action) => onMediaAction(action, song.id)}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavorite={showFavoriteInMenu}
|
||||
favorited={isFavorite}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
>
|
||||
{canRemove ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={onRemove}
|
||||
>
|
||||
{removeLabel}
|
||||
<Trash2 />
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</MediaContextMenu>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const router = useRouter()
|
||||
const isFavorites = playlist.isFavorites === true
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const {
|
||||
isSongFavorite,
|
||||
toggleSongFavorite,
|
||||
toggleSongsFavorite,
|
||||
favoriteSongs: addFavoriteSongs,
|
||||
} = useFavorites()
|
||||
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 [songs, setSongs] = React.useState(playlist.songs)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState(
|
||||
() => playlist.songs[0]?.id ?? ""
|
||||
)
|
||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
||||
|
||||
React.useEffect(() => {
|
||||
setSongs(playlist.songs)
|
||||
setIsSubscribed(playlist.isSubscribed)
|
||||
setActiveTrackId((current) => {
|
||||
if (playlist.songs.some((song) => song.id === current)) {
|
||||
return current
|
||||
}
|
||||
return playlist.songs[0]?.id ?? ""
|
||||
})
|
||||
}, [playlist])
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
selectedCount,
|
||||
isSelected,
|
||||
handleSelect,
|
||||
handlePointerDown,
|
||||
prepareContextMenu,
|
||||
} = useTrackSelection(songs)
|
||||
|
||||
const selectionPositions = React.useMemo(
|
||||
() => getSelectionRangePositions(songs.map((song) => song.id), selectedIds),
|
||||
[songs, selectedIds]
|
||||
)
|
||||
|
||||
function resolveTargetIds(fallbackSongId?: string) {
|
||||
return selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
: fallbackSongId
|
||||
? [fallbackSongId]
|
||||
: activeTrackId
|
||||
? [activeTrackId]
|
||||
: []
|
||||
}
|
||||
|
||||
function handleMediaAction(
|
||||
action: MediaContextAction,
|
||||
fallbackSongId?: string
|
||||
) {
|
||||
const targetIds = resolveTargetIds(fallbackSongId)
|
||||
const count = targetIds.length
|
||||
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
void addFavoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
toast.success(
|
||||
count > 1 ? `Queued ${count} songs to play next` : "Play next"
|
||||
)
|
||||
break
|
||||
case "play-last":
|
||||
toast.success(
|
||||
count > 1 ? `Queued ${count} songs to play last` : "Play last"
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
function handlePlaylistMediaAction(action: MediaContextAction) {
|
||||
const targetIds = songs.map((song) => song.id)
|
||||
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
void addFavoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
toast.success(`Queued ${targetIds.length} songs to play next`)
|
||||
break
|
||||
case "play-last":
|
||||
toast.success(`Queued ${targetIds.length} songs to play last`)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveSong(songId: string) {
|
||||
const ids =
|
||||
selectedIds.size > 0 && selectedIds.has(songId)
|
||||
? Array.from(selectedIds)
|
||||
: [songId]
|
||||
|
||||
if (isFavorites) {
|
||||
await toggleSongsFavorite(ids as Id<"songs">[], true)
|
||||
setSongs((current) => current.filter((song) => !ids.includes(song.id)))
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await removeSongs({
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
songIds: ids as Id<"songs">[],
|
||||
})
|
||||
setSongs((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(nextSongs: BrowseSong[]) {
|
||||
try {
|
||||
await reorderSongs({
|
||||
playlistId: playlist.id as Id<"playlists">,
|
||||
songIds: nextSongs.map((song) => song.id as Id<"songs">),
|
||||
})
|
||||
setSongs(nextSongs)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to reorder songs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function handleDrop(targetIndex: number) {
|
||||
if (isFavorites || !playlist.isOwner || dragIndex === null || dragIndex === targetIndex) {
|
||||
setDragIndex(null)
|
||||
return
|
||||
}
|
||||
|
||||
const next = [...songs]
|
||||
const [moved] = next.splice(dragIndex, 1)
|
||||
next.splice(targetIndex, 0, moved)
|
||||
setDragIndex(null)
|
||||
void persistOrder(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() {
|
||||
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"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="pb-28">
|
||||
<div className="flex items-center justify-end gap-1 px-6 pt-4">
|
||||
{!isFavorites ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Share playlist"
|
||||
onClick={() => copyPlaylistLink(playlist)}
|
||||
>
|
||||
<Share2 />
|
||||
</Button>
|
||||
) : null}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-8"
|
||||
aria-label="More playlist options"
|
||||
>
|
||||
<MoreHorizontal />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<MediaContextMenuItems
|
||||
selectedCount={songs.length}
|
||||
onAction={handlePlaylistMediaAction}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavorite={!isFavorites}
|
||||
/>
|
||||
{playlist.isOwner && !isFavorites ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={handleDeletePlaylist}
|
||||
>
|
||||
Delete Playlist
|
||||
<Trash2 />
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto w-full min-w-0 max-w-9/10">
|
||||
<div className="flex flex-col gap-8 px-6 pt-2 pb-8 sm:flex-row sm:items-end">
|
||||
<div className="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!)}
|
||||
alt={playlist.title}
|
||||
fill
|
||||
sizes="240px"
|
||||
className="object-cover"
|
||||
priority
|
||||
/>
|
||||
)}
|
||||
</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>
|
||||
</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"
|
||||
>
|
||||
<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}`}
|
||||
>
|
||||
<Play className="fill-current" />
|
||||
Play
|
||||
</Button>
|
||||
{!playlist.isOwner ? (
|
||||
<Button
|
||||
variant={isSubscribed ? "secondary" : "default"}
|
||||
className="h-10 rounded-full px-6"
|
||||
onClick={handleSubscribeToggle}
|
||||
>
|
||||
{isSubscribed ? "Subscribed" : "Subscribe"}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{songs.length > 0 ? (
|
||||
songs.map((song, index) => (
|
||||
<PlaylistSongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
index={index}
|
||||
isOwner={playlist.isOwner && !isFavorites}
|
||||
canRemove={isFavorites || playlist.isOwner}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites ? "Unfavorite" : "Remove from Playlist"
|
||||
}
|
||||
isActive={song.id === activeTrackId}
|
||||
isSelected={isSelected(song.id)}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={
|
||||
isSelected(song.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
: 1
|
||||
}
|
||||
isDragging={dragIndex === index}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(song.id, index, event)
|
||||
setActiveTrackId(song.id)
|
||||
}}
|
||||
onToggleFavorite={() => {
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
if (isFavorites && isSongFavorite(song.id)) {
|
||||
setSongs((current) =>
|
||||
current.filter((item) => item.id !== song.id)
|
||||
)
|
||||
}
|
||||
}}
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={() => handleRemoveSong(song.id)}
|
||||
onDragStart={(event) => {
|
||||
if (isFavorites || !playlist.isOwner) {
|
||||
return
|
||||
}
|
||||
setDragIndex(index)
|
||||
event.dataTransfer.effectAllowed = "move"
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (isFavorites || !playlist.isOwner) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
handleDrop(index)
|
||||
}}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<p className="px-6 py-8 text-sm text-muted-foreground">
|
||||
This playlist has no songs yet.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,18 +4,24 @@ import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import type { Song } from "@/lib/data"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@/convex/library"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
|
||||
export function SearchSongItem({ song }: { song: Song }) {
|
||||
export function SearchSongItem({ song }: { song: BrowseSong }) {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
|
||||
function handleAction(action: MediaContextAction) {
|
||||
switch (action) {
|
||||
case "playlist":
|
||||
toast.success("Added to playlist")
|
||||
openAddToPlaylist([song.id as Id<"songs">])
|
||||
break
|
||||
case "play-next":
|
||||
toast.success("Playing next")
|
||||
@@ -24,7 +30,7 @@ export function SearchSongItem({ song }: { song: Song }) {
|
||||
toast.success("Added to queue")
|
||||
break
|
||||
case "favorite":
|
||||
toast.success("Added to favorites")
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -60,6 +66,11 @@ export function SearchSongItem({ song }: { song: Song }) {
|
||||
selectedCount={1}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={handleAction}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
triggerClassName="size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100"
|
||||
triggerVariant="ghost"
|
||||
/>
|
||||
|
||||
@@ -3,14 +3,11 @@
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
|
||||
import type { Album, Artist, Song } from "@/lib/data"
|
||||
import type { SearchTopResultItem } from "@/convex/library"
|
||||
import { albumCoverUrl, artistCoverUrl } from "@/lib/cover-urls"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export type TopResult =
|
||||
| { kind: "song"; item: Song }
|
||||
| { kind: "album"; item: Album }
|
||||
| { kind: "artist"; item: Artist }
|
||||
export type TopResult = SearchTopResultItem
|
||||
|
||||
function resultHref(result: TopResult) {
|
||||
switch (result.kind) {
|
||||
|
||||
+21
-42
@@ -6,6 +6,8 @@ import Link from "next/link"
|
||||
import { ArrowUpDown, Play, Star } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
@@ -31,7 +33,8 @@ import {
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { Song } from "@/lib/data"
|
||||
import type { Id } from "@/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@/convex/library"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
getSelectionRangePositions,
|
||||
@@ -58,7 +61,7 @@ function formatDuration(seconds: number): string {
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function SongCover({ song, inRange }: { song: Song; inRange: boolean }) {
|
||||
function SongCover({ song, inRange }: { song: BrowseSong; inRange: boolean }) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -102,7 +105,7 @@ function SongRow({
|
||||
onPrepareContextMenu,
|
||||
onMediaAction,
|
||||
}: {
|
||||
song: Song
|
||||
song: BrowseSong
|
||||
index: number
|
||||
isSelected: boolean
|
||||
selectionPosition: SelectionRangePosition
|
||||
@@ -216,14 +219,14 @@ function SongRow({
|
||||
label={`More options for ${song.title}`}
|
||||
selectedCount={selectedCount}
|
||||
align="end"
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={onPrepareContextMenu}
|
||||
onAction={(action) => onMediaAction(action, song.id)}
|
||||
triggerClassName={cn(
|
||||
"size-8 shrink-0 transition-opacity",
|
||||
inRange
|
||||
? "text-primary-foreground opacity-100 hover:bg-white/15 hover:text-primary-foreground"
|
||||
: "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
|
||||
)}
|
||||
favorited={isFavorite}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -232,13 +235,12 @@ function SongRow({
|
||||
)
|
||||
}
|
||||
|
||||
export function SongsView({ songs }: { songs: Song[] }) {
|
||||
export function SongsView({ songs }: { songs: BrowseSong[] }) {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
|
||||
const [sortKey, setSortKey] = React.useState<SortKey>("title")
|
||||
const [sortDirection, setSortDirection] =
|
||||
React.useState<SortDirection>("asc")
|
||||
const [favoriteIds, setFavoriteIds] = React.useState<Set<string>>(
|
||||
() => new Set()
|
||||
)
|
||||
|
||||
const sortedSongs = React.useMemo(() => {
|
||||
const sorted = [...songs].sort((a, b) => {
|
||||
@@ -281,18 +283,6 @@ export function SongsView({ songs }: { songs: Song[] }) {
|
||||
[sortedSongs, selectedIds]
|
||||
)
|
||||
|
||||
function toggleFavorite(songId: string) {
|
||||
setFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
if (next.has(songId)) {
|
||||
next.delete(songId)
|
||||
} else {
|
||||
next.add(songId)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
|
||||
const targetIds =
|
||||
selectedIds.size > 0
|
||||
@@ -304,23 +294,10 @@ export function SongsView({ songs }: { songs: Song[] }) {
|
||||
|
||||
switch (action) {
|
||||
case "favorite":
|
||||
setFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
for (const id of targetIds) {
|
||||
next.add(id)
|
||||
}
|
||||
return next
|
||||
})
|
||||
toast.success(
|
||||
count > 1 ? `Favorited ${count} songs` : "Added to favorites"
|
||||
)
|
||||
void favoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
toast.success(
|
||||
count > 1
|
||||
? `Added ${count} songs to playlist`
|
||||
: "Added to playlist"
|
||||
)
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
toast.success(
|
||||
@@ -429,7 +406,7 @@ export function SongsView({ songs }: { songs: Song[] }) {
|
||||
index={index}
|
||||
isSelected={isSelected(song.id)}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={favoriteIds.has(song.id)}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={
|
||||
isSelected(song.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
@@ -439,7 +416,9 @@ export function SongsView({ songs }: { songs: Song[] }) {
|
||||
onSelect={(event) => {
|
||||
handleSelect(song.id, index, event)
|
||||
}}
|
||||
onToggleFavorite={() => toggleFavorite(song.id)}
|
||||
onToggleFavorite={() =>
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
}
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
|
||||
Vendored
+4
@@ -11,8 +11,10 @@
|
||||
import type * as actions from "../actions.js";
|
||||
import type * as auth from "../auth.js";
|
||||
import type * as crons from "../crons.js";
|
||||
import type * as favorites from "../favorites.js";
|
||||
import type * as http from "../http.js";
|
||||
import type * as library from "../library.js";
|
||||
import type * as playlists from "../playlists.js";
|
||||
import type * as users from "../users.js";
|
||||
|
||||
import type {
|
||||
@@ -25,8 +27,10 @@ declare const fullApi: ApiFromModules<{
|
||||
actions: typeof actions;
|
||||
auth: typeof auth;
|
||||
crons: typeof crons;
|
||||
favorites: typeof favorites;
|
||||
http: typeof http;
|
||||
library: typeof library;
|
||||
playlists: typeof playlists;
|
||||
users: typeof users;
|
||||
}>;
|
||||
|
||||
|
||||
+58
-9
@@ -5,12 +5,49 @@ import { api } from "@/convex/_generated/api"
|
||||
import * as fs from "node:fs/promises"
|
||||
import * as music from "music-metadata"
|
||||
|
||||
import { action } from "./_generated/server"
|
||||
import type { Id } from "./_generated/dataModel"
|
||||
import { action, type ActionCtx } from "./_generated/server"
|
||||
|
||||
const DATA_DIR = process.env.CONVEX_SITE_URL?.includes("127.0.0.1")
|
||||
? "/Users/joshuafhiggins/Downloads/test"
|
||||
: process.env.DATA || "/data"
|
||||
|
||||
async function coverPathIfExists(path: string): Promise<string | null> {
|
||||
return fs.access(path).then(() => path).catch(() => null)
|
||||
}
|
||||
|
||||
async function syncArtistCover(
|
||||
ctx: ActionCtx,
|
||||
dbCover: string | null,
|
||||
diskPath: string,
|
||||
id: Id<"artists">
|
||||
) {
|
||||
const onDisk = await coverPathIfExists(diskPath)
|
||||
if (onDisk !== null) {
|
||||
if (dbCover !== onDisk) {
|
||||
await ctx.runMutation(api.library.updateArtistCover, { id, cover: onDisk })
|
||||
}
|
||||
} else if (dbCover !== null) {
|
||||
await ctx.runMutation(api.library.updateArtistCover, { id, cover: null })
|
||||
}
|
||||
}
|
||||
|
||||
async function syncAlbumCover(
|
||||
ctx: ActionCtx,
|
||||
dbCover: string | null,
|
||||
diskPath: string,
|
||||
id: Id<"albums">
|
||||
) {
|
||||
const onDisk = await coverPathIfExists(diskPath)
|
||||
if (onDisk !== null) {
|
||||
if (dbCover !== onDisk) {
|
||||
await ctx.runMutation(api.library.updateAlbumCover, { id, cover: onDisk })
|
||||
}
|
||||
} else if (dbCover !== null) {
|
||||
await ctx.runMutation(api.library.updateAlbumCover, { id, cover: null })
|
||||
}
|
||||
}
|
||||
|
||||
export const updateLibrary = action({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
@@ -29,11 +66,10 @@ export const updateLibrary = action({
|
||||
const dbArtists = await ctx.runQuery(api.library.getArtists)
|
||||
const dbArtistsNames = dbArtists.map((artist) => artist.name)
|
||||
for (const artist of artists) {
|
||||
const artistCoverPath = `${DATA_DIR}/${codec}/${artist}/folder.jpg`
|
||||
|
||||
if (!dbArtistsNames.includes(artist)) {
|
||||
const cover = await fs
|
||||
.access(`${DATA_DIR}/${codec}/${artist}/folder.jpg`)
|
||||
.then(() => `${DATA_DIR}/${codec}/${artist}/folder.jpg`)
|
||||
.catch(() => null)
|
||||
const cover = await coverPathIfExists(artistCoverPath)
|
||||
await ctx.runMutation(api.library.createArtist, {
|
||||
name: artist,
|
||||
cover,
|
||||
@@ -43,6 +79,13 @@ export const updateLibrary = action({
|
||||
const dbArtist = (await ctx.runQuery(api.library.getArtistByName, {
|
||||
name: artist,
|
||||
}))!
|
||||
|
||||
await syncArtistCover(
|
||||
ctx,
|
||||
dbArtist.cover,
|
||||
artistCoverPath,
|
||||
dbArtist._id
|
||||
)
|
||||
const albums = (
|
||||
await fs.readdir(`${DATA_DIR}/${codec}/${artist}`, {
|
||||
withFileTypes: true,
|
||||
@@ -57,11 +100,10 @@ export const updateLibrary = action({
|
||||
const dbAlbumsNames = dbAlbums.map((album) => album.name)
|
||||
|
||||
for (const album of albums) {
|
||||
const albumCoverPath = `${DATA_DIR}/${codec}/${artist}/${album}/cover.jpg`
|
||||
|
||||
if (!dbAlbumsNames.includes(album)) {
|
||||
const cover = await fs
|
||||
.access(`${DATA_DIR}/${codec}/${artist}/${album}/cover.jpg`)
|
||||
.then(() => `${DATA_DIR}/${codec}/${artist}/${album}/cover.jpg`)
|
||||
.catch(() => null)
|
||||
const cover = await coverPathIfExists(albumCoverPath)
|
||||
await ctx.runMutation(api.library.createAlbum, {
|
||||
name: album,
|
||||
cover,
|
||||
@@ -73,6 +115,13 @@ export const updateLibrary = action({
|
||||
name: album,
|
||||
}))!
|
||||
|
||||
await syncAlbumCover(
|
||||
ctx,
|
||||
dbAlbum.cover,
|
||||
albumCoverPath,
|
||||
dbAlbum._id
|
||||
)
|
||||
|
||||
const songs = (
|
||||
await fs.readdir(`${DATA_DIR}/${codec}/${artist}/${album}`, {
|
||||
withFileTypes: true,
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import type { BrowsePlaylistDetail, BrowseSong } from "./library"
|
||||
|
||||
function uniqueIds<T extends string>(ids: T[]): T[] {
|
||||
return [...new Set(ids)]
|
||||
}
|
||||
|
||||
async function requireAuth(ctx: MutationCtx) {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
throw new ConvexError("Not authenticated")
|
||||
}
|
||||
return userId
|
||||
}
|
||||
|
||||
async function getAlbumIdsForArtist(ctx: QueryCtx, artistId: Id<"artists">) {
|
||||
const albums = await ctx.db
|
||||
.query("albums")
|
||||
.withIndex("by_artist", (q) => q.eq("artist", artistId))
|
||||
.collect()
|
||||
return albums.map((album) => album._id)
|
||||
}
|
||||
|
||||
async function getSongIdsForAlbum(ctx: QueryCtx, albumId: Id<"albums">) {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_album", (q) => q.eq("album", albumId))
|
||||
.collect()
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
async function getSongIdsForArtist(ctx: QueryCtx, artistId: Id<"artists">) {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_artist", (q) => q.eq("albumArtist", artistId))
|
||||
.collect()
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
function allAlbumSongsFavorited(
|
||||
albumSongIds: Id<"songs">[],
|
||||
favoriteSongs: Id<"songs">[]
|
||||
) {
|
||||
if (albumSongIds.length === 0) {
|
||||
return false
|
||||
}
|
||||
const favorited = new Set(favoriteSongs)
|
||||
return albumSongIds.every((id) => favorited.has(id))
|
||||
}
|
||||
|
||||
function allArtistAlbumsFavorited(
|
||||
artistAlbumIds: Id<"albums">[],
|
||||
favoriteAlbums: Id<"albums">[]
|
||||
) {
|
||||
if (artistAlbumIds.length === 0) {
|
||||
return false
|
||||
}
|
||||
const favorited = new Set(favoriteAlbums)
|
||||
return artistAlbumIds.every((id) => favorited.has(id))
|
||||
}
|
||||
|
||||
async function promoteAlbumIfAllSongsFavorited(
|
||||
ctx: MutationCtx,
|
||||
favoriteSongs: Id<"songs">[],
|
||||
favoriteAlbums: Id<"albums">[],
|
||||
albumId: Id<"albums">
|
||||
) {
|
||||
const albumSongIds = await getSongIdsForAlbum(ctx, albumId)
|
||||
if (!allAlbumSongsFavorited(albumSongIds, favoriteSongs)) {
|
||||
return favoriteAlbums
|
||||
}
|
||||
return uniqueIds([...favoriteAlbums, albumId])
|
||||
}
|
||||
|
||||
async function promoteArtistIfAllAlbumsFavorited(
|
||||
ctx: MutationCtx,
|
||||
favoriteAlbums: Id<"albums">[],
|
||||
favoriteArtists: Id<"artists">[],
|
||||
artistId: Id<"artists">
|
||||
) {
|
||||
const artistAlbumIds = await getAlbumIdsForArtist(ctx, artistId)
|
||||
if (!allArtistAlbumsFavorited(artistAlbumIds, favoriteAlbums)) {
|
||||
return favoriteArtists
|
||||
}
|
||||
return uniqueIds([...favoriteArtists, artistId])
|
||||
}
|
||||
|
||||
async function cascadeUpFromSongs(
|
||||
ctx: MutationCtx,
|
||||
favoriteSongs: Id<"songs">[],
|
||||
favoriteAlbums: Id<"albums">[],
|
||||
favoriteArtists: Id<"artists">[],
|
||||
songs: Doc<"songs">[]
|
||||
) {
|
||||
let albums = favoriteAlbums
|
||||
let artists = favoriteArtists
|
||||
|
||||
const albumIds = new Set(songs.map((song) => song.album))
|
||||
for (const albumId of albumIds) {
|
||||
albums = await promoteAlbumIfAllSongsFavorited(ctx, favoriteSongs, albums, albumId)
|
||||
}
|
||||
|
||||
const artistIds = new Set(songs.map((song) => song.albumArtist))
|
||||
for (const artistId of artistIds) {
|
||||
artists = await promoteArtistIfAllAlbumsFavorited(ctx, albums, artists, artistId)
|
||||
}
|
||||
|
||||
return { favoriteAlbums: albums, favoriteArtists: artists }
|
||||
}
|
||||
|
||||
function toBrowseArtist(artist: Doc<"artists">) {
|
||||
return {
|
||||
id: artist._id,
|
||||
name: artist.name,
|
||||
photo: artist.cover,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadArtistMap(ctx: QueryCtx) {
|
||||
const artists = await ctx.db.query("artists").collect()
|
||||
return new Map(artists.map((artist) => [artist._id, artist]))
|
||||
}
|
||||
|
||||
async function loadAlbumMap(ctx: QueryCtx) {
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
return new Map(albums.map((album) => [album._id, album]))
|
||||
}
|
||||
|
||||
async function toBrowseSong(
|
||||
ctx: QueryCtx,
|
||||
songId: Id<"songs">,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>
|
||||
): Promise<BrowseSong | null> {
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
return null
|
||||
}
|
||||
|
||||
const album = albumMap.get(song.album)
|
||||
const albumArtist = artistMap.get(song.albumArtist)
|
||||
if (!album || !albumArtist) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: song._id,
|
||||
title: song.name,
|
||||
artist: toBrowseArtist(albumArtist),
|
||||
album: {
|
||||
id: album._id,
|
||||
title: album.name,
|
||||
cover: album.cover,
|
||||
},
|
||||
durationSeconds: Math.round(song.length),
|
||||
}
|
||||
}
|
||||
|
||||
export const getUserFavorites = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return {
|
||||
favoriteSongs: [] as Id<"songs">[],
|
||||
favoriteAlbums: [] as Id<"albums">[],
|
||||
favoriteArtists: [] as Id<"artists">[],
|
||||
}
|
||||
}
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
return {
|
||||
favoriteSongs: [] as Id<"songs">[],
|
||||
favoriteAlbums: [] as Id<"albums">[],
|
||||
favoriteArtists: [] as Id<"artists">[],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
favoriteSongs: user.favoriteSongs ?? [],
|
||||
favoriteAlbums: user.favoriteAlbums ?? [],
|
||||
favoriteArtists: user.favoriteArtists ?? [],
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const browseFavoritesPlaylistDetail = query({
|
||||
args: {},
|
||||
handler: async (ctx): Promise<BrowsePlaylistDetail | null> => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return null
|
||||
}
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albumMap = await loadAlbumMap(ctx)
|
||||
|
||||
const songs: BrowseSong[] = []
|
||||
for (const songId of user.favoriteSongs ?? []) {
|
||||
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
||||
if (song) {
|
||||
songs.push(song)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: null,
|
||||
isFavorites: true,
|
||||
title: "Favorites",
|
||||
owner: {
|
||||
id: user._id,
|
||||
name: user.name,
|
||||
},
|
||||
cover: null,
|
||||
songs,
|
||||
isOwner: true,
|
||||
isSubscribed: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const favoriteSong = mutation({
|
||||
args: { songId: v.id("songs") },
|
||||
handler: async (ctx, { songId }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
throw new ConvexError("Song not found")
|
||||
}
|
||||
|
||||
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), songId])
|
||||
const cascaded = await cascadeUpFromSongs(
|
||||
ctx,
|
||||
favoriteSongs,
|
||||
user.favoriteAlbums ?? [],
|
||||
user.favoriteArtists ?? [],
|
||||
[song]
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs,
|
||||
favoriteAlbums: cascaded.favoriteAlbums,
|
||||
favoriteArtists: cascaded.favoriteArtists,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const favoriteSongs = mutation({
|
||||
args: { songIds: v.array(v.id("songs")) },
|
||||
handler: async (ctx, { songIds }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const songs: Doc<"songs">[] = []
|
||||
for (const id of songIds) {
|
||||
const song = await ctx.db.get("songs", id)
|
||||
if (song) {
|
||||
songs.push(song)
|
||||
}
|
||||
}
|
||||
|
||||
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), ...songIds])
|
||||
const cascaded = await cascadeUpFromSongs(
|
||||
ctx,
|
||||
favoriteSongs,
|
||||
user.favoriteAlbums ?? [],
|
||||
user.favoriteArtists ?? [],
|
||||
songs
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs,
|
||||
favoriteAlbums: cascaded.favoriteAlbums,
|
||||
favoriteArtists: cascaded.favoriteArtists,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const unfavoriteSong = mutation({
|
||||
args: { songId: v.id("songs") },
|
||||
handler: async (ctx, { songId }) => {
|
||||
await unfavoriteSongHandler(ctx, songId)
|
||||
},
|
||||
})
|
||||
|
||||
export const unfavoriteSongs = mutation({
|
||||
args: { songIds: v.array(v.id("songs")) },
|
||||
handler: async (ctx, { songIds }) => {
|
||||
for (const songId of songIds) {
|
||||
await unfavoriteSongHandler(ctx, songId)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
async function unfavoriteSongHandler(ctx: MutationCtx, songId: Id<"songs">) {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
return
|
||||
}
|
||||
|
||||
let favoriteSongs = (user.favoriteSongs ?? []).filter((id) => id !== songId)
|
||||
let favoriteAlbums = user.favoriteAlbums ?? []
|
||||
let favoriteArtists = user.favoriteArtists ?? []
|
||||
|
||||
if (favoriteAlbums.includes(song.album)) {
|
||||
favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album)
|
||||
}
|
||||
|
||||
if (favoriteArtists.includes(song.albumArtist)) {
|
||||
favoriteArtists = favoriteArtists.filter((id) => id !== song.albumArtist)
|
||||
favoriteAlbums = favoriteAlbums.filter((id) => id !== song.album)
|
||||
}
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs,
|
||||
favoriteAlbums,
|
||||
favoriteArtists,
|
||||
})
|
||||
}
|
||||
|
||||
export const favoriteAlbum = mutation({
|
||||
args: { albumId: v.id("albums") },
|
||||
handler: async (ctx, { albumId }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const album = await ctx.db.get("albums", albumId)
|
||||
if (!album) {
|
||||
throw new ConvexError("Album not found")
|
||||
}
|
||||
|
||||
const songIds = await getSongIdsForAlbum(ctx, albumId)
|
||||
|
||||
const favoriteAlbums = uniqueIds([...(user.favoriteAlbums ?? []), albumId])
|
||||
const favoriteSongs = uniqueIds([...(user.favoriteSongs ?? []), ...songIds])
|
||||
const favoriteArtists = await promoteArtistIfAllAlbumsFavorited(
|
||||
ctx,
|
||||
favoriteAlbums,
|
||||
user.favoriteArtists ?? [],
|
||||
album.artist
|
||||
)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteAlbums,
|
||||
favoriteSongs,
|
||||
favoriteArtists,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const unfavoriteAlbum = mutation({
|
||||
args: { albumId: v.id("albums") },
|
||||
handler: async (ctx, { albumId }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const album = await ctx.db.get("albums", albumId)
|
||||
if (!album) {
|
||||
return
|
||||
}
|
||||
|
||||
const albumSongIds = await getSongIdsForAlbum(ctx, albumId)
|
||||
const removeSongs = new Set(albumSongIds)
|
||||
|
||||
let favoriteAlbums = (user.favoriteAlbums ?? []).filter((id) => id !== albumId)
|
||||
let favoriteSongs = (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id))
|
||||
let favoriteArtists = user.favoriteArtists ?? []
|
||||
|
||||
if (favoriteArtists.includes(album.artist)) {
|
||||
favoriteArtists = favoriteArtists.filter((id) => id !== album.artist)
|
||||
}
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteSongs,
|
||||
favoriteAlbums,
|
||||
favoriteArtists,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const favoriteArtist = mutation({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, { artistId }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const artist = await ctx.db.get("artists", artistId)
|
||||
if (!artist) {
|
||||
throw new ConvexError("Artist not found")
|
||||
}
|
||||
|
||||
const albumIds = await getAlbumIdsForArtist(ctx, artistId)
|
||||
const songIds = await getSongIdsForArtist(ctx, artistId)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteArtists: uniqueIds([...(user.favoriteArtists ?? []), artistId]),
|
||||
favoriteAlbums: uniqueIds([...(user.favoriteAlbums ?? []), ...albumIds]),
|
||||
favoriteSongs: uniqueIds([...(user.favoriteSongs ?? []), ...songIds]),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const unfavoriteArtist = mutation({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, { artistId }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const albumIds = await getAlbumIdsForArtist(ctx, artistId)
|
||||
const songIds = await getSongIdsForArtist(ctx, artistId)
|
||||
const removeAlbums = new Set(albumIds)
|
||||
const removeSongs = new Set(songIds)
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
favoriteArtists: (user.favoriteArtists ?? []).filter((id) => id !== artistId),
|
||||
favoriteAlbums: (user.favoriteAlbums ?? []).filter((id) => !removeAlbums.has(id)),
|
||||
favoriteSongs: (user.favoriteSongs ?? []).filter((id) => !removeSongs.has(id)),
|
||||
})
|
||||
},
|
||||
})
|
||||
+118
-35
@@ -3,25 +3,102 @@ import { v } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { QueryCtx } from "./_generated/server"
|
||||
|
||||
type BrowseArtist = {
|
||||
export type BrowseArtist = {
|
||||
id: Id<"artists">
|
||||
name: string
|
||||
photo: string | null
|
||||
}
|
||||
|
||||
type BrowseAlbum = {
|
||||
export type BrowseAlbum = {
|
||||
id: Id<"albums">
|
||||
title: string
|
||||
artist: BrowseArtist
|
||||
cover: string | null
|
||||
}
|
||||
|
||||
type BrowseSong = {
|
||||
export type BrowseSong = {
|
||||
id: Id<"songs">
|
||||
title: string
|
||||
artist: BrowseArtist
|
||||
album: Pick<BrowseAlbum, "id" | "title" | "cover">
|
||||
durationSeconds: number
|
||||
explicit?: boolean
|
||||
}
|
||||
|
||||
export type BrowseAlbumTrack = {
|
||||
id: Id<"songs">
|
||||
title: string
|
||||
track: number
|
||||
durationSeconds: number
|
||||
}
|
||||
|
||||
export type BrowseAlbumDetail = BrowseAlbum & {
|
||||
year: number | null
|
||||
genre: string | null
|
||||
tracks: BrowseAlbumTrack[]
|
||||
}
|
||||
|
||||
export type BrowseArtistDetail = {
|
||||
artist: BrowseArtist
|
||||
albums: BrowseAlbum[]
|
||||
recentlyAdded: BrowseAlbum[]
|
||||
recentlyPlayed: BrowseAlbum[]
|
||||
}
|
||||
|
||||
export type PlaylistSummary = {
|
||||
id: Id<"playlists">
|
||||
title: string
|
||||
owner: string
|
||||
cover: string | null
|
||||
}
|
||||
|
||||
export type BrowsePlaylistOwner = {
|
||||
id: Id<"users">
|
||||
name: string
|
||||
}
|
||||
|
||||
export type BrowsePlaylistDetail = {
|
||||
id: Id<"playlists"> | null
|
||||
isFavorites?: boolean
|
||||
title: string
|
||||
owner: BrowsePlaylistOwner
|
||||
cover: string | null
|
||||
songs: BrowseSong[]
|
||||
isOwner: boolean
|
||||
isSubscribed: boolean
|
||||
}
|
||||
|
||||
export type SidebarPlaylists = {
|
||||
owned: PlaylistSummary[]
|
||||
subscribed: PlaylistSummary[]
|
||||
}
|
||||
|
||||
export type SearchTopResultItem =
|
||||
| { kind: "song"; item: BrowseSong }
|
||||
| { kind: "album"; item: BrowseAlbum }
|
||||
| { kind: "artist"; item: BrowseArtist }
|
||||
|
||||
export type LibrarySearchResults = {
|
||||
topResults: SearchTopResultItem[]
|
||||
artists: BrowseArtist[]
|
||||
albums: BrowseAlbum[]
|
||||
songs: BrowseSong[]
|
||||
}
|
||||
|
||||
type SearchTopResult =
|
||||
| { kind: "song"; item: BrowseSong; score: number }
|
||||
| { kind: "album"; item: BrowseAlbum; score: number }
|
||||
| { kind: "artist"; item: BrowseArtist; score: number }
|
||||
|
||||
function toSearchTopResultItem(result: SearchTopResult): SearchTopResultItem {
|
||||
switch (result.kind) {
|
||||
case "song":
|
||||
return { kind: "song", item: result.item }
|
||||
case "album":
|
||||
return { kind: "album", item: result.item }
|
||||
case "artist":
|
||||
return { kind: "artist", item: result.item }
|
||||
}
|
||||
}
|
||||
|
||||
async function loadArtistMap(ctx: QueryCtx) {
|
||||
@@ -117,19 +194,6 @@ export const browseSongs = query({
|
||||
},
|
||||
})
|
||||
|
||||
type BrowseAlbumTrack = {
|
||||
id: Id<"songs">
|
||||
title: string
|
||||
track: number
|
||||
durationSeconds: number
|
||||
}
|
||||
|
||||
type BrowseAlbumDetail = BrowseAlbum & {
|
||||
year: number | null
|
||||
genre: string | null
|
||||
tracks: BrowseAlbumTrack[]
|
||||
}
|
||||
|
||||
export const browseAlbumDetail = query({
|
||||
args: { id: v.id("albums") },
|
||||
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
|
||||
@@ -218,25 +282,16 @@ function matchScore(text: string, query: string): number {
|
||||
return 0
|
||||
}
|
||||
|
||||
type SearchTopResult =
|
||||
| { kind: "song"; item: BrowseSong; score: number }
|
||||
| { kind: "album"; item: BrowseAlbum; score: number }
|
||||
| { kind: "artist"; item: BrowseArtist; score: number }
|
||||
|
||||
export const searchLibrary = query({
|
||||
args: { query: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
const queryText = args.query.trim().toLowerCase()
|
||||
if (!queryText) {
|
||||
return {
|
||||
topResults: [] as Array<
|
||||
| { kind: "song"; item: BrowseSong }
|
||||
| { kind: "album"; item: BrowseAlbum }
|
||||
| { kind: "artist"; item: BrowseArtist }
|
||||
>,
|
||||
artists: [] as BrowseArtist[],
|
||||
albums: [] as BrowseAlbum[],
|
||||
songs: [] as BrowseSong[],
|
||||
topResults: [],
|
||||
artists: [],
|
||||
albums: [],
|
||||
songs: [],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +300,9 @@ export const searchLibrary = query({
|
||||
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
||||
const songs = await ctx.db.query("songs").collect()
|
||||
|
||||
const artistResults: SearchTopResult[] = [...artistMap.values()]
|
||||
const artistResults: Extract<SearchTopResult, { kind: "artist" }>[] = [
|
||||
...artistMap.values(),
|
||||
]
|
||||
.map((artist) => ({
|
||||
kind: "artist" as const,
|
||||
item: toBrowseArtist(artist),
|
||||
@@ -254,7 +311,7 @@ export const searchLibrary = query({
|
||||
.filter((result) => result.score > 0)
|
||||
.sort((a, b) => b.score - a.score || a.item.name.localeCompare(b.item.name))
|
||||
|
||||
const albumResults: SearchTopResult[] = albums
|
||||
const albumResults: Extract<SearchTopResult, { kind: "album" }>[] = albums
|
||||
.flatMap((album) => {
|
||||
const artist = artistMap.get(album.artist)
|
||||
if (!artist) {
|
||||
@@ -280,7 +337,7 @@ export const searchLibrary = query({
|
||||
b.score - a.score || a.item.title.localeCompare(b.item.title)
|
||||
)
|
||||
|
||||
const songResults: SearchTopResult[] = songs
|
||||
const songResults: Extract<SearchTopResult, { kind: "song" }>[] = songs
|
||||
.flatMap((song) => {
|
||||
const album = albumMap.get(song.album)
|
||||
const albumArtist = artistMap.get(song.albumArtist)
|
||||
@@ -309,17 +366,22 @@ export const searchLibrary = query({
|
||||
b.score - a.score || a.item.title.localeCompare(b.item.title)
|
||||
)
|
||||
|
||||
const topResults = [...songResults, ...albumResults, ...artistResults]
|
||||
const topResults: SearchTopResultItem[] = [
|
||||
...songResults,
|
||||
...albumResults,
|
||||
...artistResults,
|
||||
]
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, 6)
|
||||
.map(({ kind, item }) => ({ kind, item }))
|
||||
.map(toSearchTopResultItem)
|
||||
|
||||
return {
|
||||
const result: LibrarySearchResults = {
|
||||
topResults,
|
||||
artists: artistResults.map((result) => result.item),
|
||||
albums: albumResults.map((result) => result.item),
|
||||
songs: songResults.map((result) => result.item),
|
||||
}
|
||||
return result
|
||||
},
|
||||
})
|
||||
|
||||
@@ -424,6 +486,13 @@ export const getAlbumByName = query({
|
||||
},
|
||||
})
|
||||
|
||||
export const getPlaylist = query({
|
||||
args: { id: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.get("playlists", args.id)
|
||||
},
|
||||
})
|
||||
|
||||
export const getSong = query({
|
||||
args: { id: v.id("songs") },
|
||||
handler: async (ctx, args) => {
|
||||
@@ -532,6 +601,20 @@ export const changeFilesForSong = mutation({
|
||||
},
|
||||
})
|
||||
|
||||
export const updateArtistCover = mutation({
|
||||
args: { id: v.id("artists"), cover: v.nullable(v.string()) },
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.patch("artists", args.id, { cover: args.cover })
|
||||
},
|
||||
})
|
||||
|
||||
export const updateAlbumCover = mutation({
|
||||
args: { id: v.id("albums"), cover: v.nullable(v.string()) },
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.patch("albums", args.id, { cover: args.cover })
|
||||
},
|
||||
})
|
||||
|
||||
export const removeSongs = mutation({
|
||||
args: { ids: v.array(v.id("songs")) },
|
||||
handler: async (ctx, args) => {
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||
import { ConvexError, v } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { MutationCtx, QueryCtx } from "./_generated/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import type {
|
||||
BrowseArtist,
|
||||
BrowsePlaylistDetail,
|
||||
BrowseSong,
|
||||
PlaylistSummary,
|
||||
SidebarPlaylists,
|
||||
} from "./library"
|
||||
|
||||
function toBrowseArtist(artist: Doc<"artists">): BrowseArtist {
|
||||
return {
|
||||
id: artist._id,
|
||||
name: artist.name,
|
||||
photo: artist.cover,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadArtistMap(ctx: QueryCtx) {
|
||||
const artists = await ctx.db.query("artists").collect()
|
||||
return new Map(artists.map((artist) => [artist._id, artist]))
|
||||
}
|
||||
|
||||
async function toBrowseSong(
|
||||
ctx: QueryCtx,
|
||||
songId: Id<"songs">,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>
|
||||
): Promise<BrowseSong | null> {
|
||||
const song = await ctx.db.get("songs", songId)
|
||||
if (!song) {
|
||||
return null
|
||||
}
|
||||
|
||||
const album = albumMap.get(song.album)
|
||||
const albumArtist = artistMap.get(song.albumArtist)
|
||||
if (!album || !albumArtist) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
id: song._id,
|
||||
title: song.name,
|
||||
artist: toBrowseArtist(albumArtist),
|
||||
album: {
|
||||
id: album._id,
|
||||
title: album.name,
|
||||
cover: album.cover,
|
||||
},
|
||||
durationSeconds: Math.round(song.length),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAlbumMap(ctx: QueryCtx) {
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
return new Map(albums.map((album) => [album._id, album]))
|
||||
}
|
||||
|
||||
function toPlaylistSummary(
|
||||
playlist: Doc<"playlists">,
|
||||
ownerName: string
|
||||
): PlaylistSummary {
|
||||
return {
|
||||
id: playlist._id,
|
||||
title: playlist.name,
|
||||
owner: ownerName,
|
||||
cover: playlist.cover,
|
||||
}
|
||||
}
|
||||
|
||||
async function requireAuth(ctx: MutationCtx) {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
throw new ConvexError("Not authenticated")
|
||||
}
|
||||
return userId
|
||||
}
|
||||
|
||||
async function requirePlaylistOwner(
|
||||
ctx: MutationCtx,
|
||||
playlistId: Id<"playlists">
|
||||
) {
|
||||
const userId = await requireAuth(ctx)
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist) {
|
||||
throw new ConvexError("Playlist not found")
|
||||
}
|
||||
if (playlist.owner !== userId) {
|
||||
throw new ConvexError("Not authorized")
|
||||
}
|
||||
return { userId, playlist }
|
||||
}
|
||||
|
||||
export const browsePlaylistDetail = query({
|
||||
args: { id: v.id("playlists") },
|
||||
handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => {
|
||||
const playlist = await ctx.db.get("playlists", args.id)
|
||||
if (!playlist) {
|
||||
return null
|
||||
}
|
||||
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
if (!owner) {
|
||||
return null
|
||||
}
|
||||
|
||||
const userId = await getAuthUserId(ctx)
|
||||
const currentUser = userId ? await ctx.db.get("users", userId) : null
|
||||
const isOwner = userId === playlist.owner
|
||||
const isSubscribed =
|
||||
currentUser?.subscribedPlaylists?.includes(args.id) ?? false
|
||||
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albumMap = await loadAlbumMap(ctx)
|
||||
|
||||
const songs: BrowseSong[] = []
|
||||
for (const songId of playlist.songs) {
|
||||
const song = await toBrowseSong(ctx, songId, artistMap, albumMap)
|
||||
if (song) {
|
||||
songs.push(song)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: playlist._id,
|
||||
title: playlist.name,
|
||||
owner: {
|
||||
id: owner._id,
|
||||
name: owner.name,
|
||||
},
|
||||
cover: playlist.cover,
|
||||
songs,
|
||||
isOwner,
|
||||
isSubscribed,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const listOwnedPlaylists = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return []
|
||||
}
|
||||
|
||||
const playlists = await ctx.db
|
||||
.query("playlists")
|
||||
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
||||
.collect()
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
const ownerName = user?.name ?? "You"
|
||||
|
||||
return playlists
|
||||
.map((playlist) => toPlaylistSummary(playlist, ownerName))
|
||||
.sort((a, b) => a.title.localeCompare(b.title))
|
||||
},
|
||||
})
|
||||
|
||||
export const listSidebarPlaylists = query({
|
||||
args: {},
|
||||
handler: async (ctx): Promise<SidebarPlaylists> => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return { owned: [], subscribed: [] }
|
||||
}
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
return { owned: [], subscribed: [] }
|
||||
}
|
||||
|
||||
const ownedDocs = await ctx.db
|
||||
.query("playlists")
|
||||
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
||||
.collect()
|
||||
|
||||
const owned = ownedDocs
|
||||
.map((playlist) => toPlaylistSummary(playlist, user.name))
|
||||
.sort((a, b) => a.title.localeCompare(b.title))
|
||||
|
||||
const subscribed: PlaylistSummary[] = []
|
||||
for (const playlistId of user.subscribedPlaylists ?? []) {
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist || playlist.owner === userId) {
|
||||
continue
|
||||
}
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
subscribed.push(
|
||||
toPlaylistSummary(playlist, owner?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
|
||||
subscribed.sort((a, b) => a.title.localeCompare(b.title))
|
||||
|
||||
return { owned, subscribed }
|
||||
},
|
||||
})
|
||||
|
||||
export const searchPlaylists = query({
|
||||
args: { query: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
const queryText = args.query.trim().toLowerCase()
|
||||
if (!queryText) {
|
||||
return []
|
||||
}
|
||||
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return []
|
||||
}
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
return []
|
||||
}
|
||||
|
||||
const ownedDocs = await ctx.db
|
||||
.query("playlists")
|
||||
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
||||
.collect()
|
||||
|
||||
const ownedIds = new Set(ownedDocs.map((playlist) => playlist._id))
|
||||
const matches: PlaylistSummary[] = []
|
||||
|
||||
for (const playlist of ownedDocs) {
|
||||
if (playlist.name.toLowerCase().includes(queryText)) {
|
||||
matches.push(toPlaylistSummary(playlist, user.name))
|
||||
}
|
||||
}
|
||||
|
||||
for (const playlistId of user.subscribedPlaylists ?? []) {
|
||||
if (ownedIds.has(playlistId)) {
|
||||
continue
|
||||
}
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist || !playlist.name.toLowerCase().includes(queryText)) {
|
||||
continue
|
||||
}
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
matches.push(
|
||||
toPlaylistSummary(playlist, owner?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
|
||||
return matches.sort((a, b) => a.title.localeCompare(b.title))
|
||||
},
|
||||
})
|
||||
|
||||
export const listAllPlaylists = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return []
|
||||
}
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
return []
|
||||
}
|
||||
|
||||
const ownedDocs = await ctx.db
|
||||
.query("playlists")
|
||||
.withIndex("by_owner", (q) => q.eq("owner", userId))
|
||||
.collect()
|
||||
|
||||
const ownedIds = new Set(ownedDocs.map((playlist) => playlist._id))
|
||||
const summaries: PlaylistSummary[] = ownedDocs.map((playlist) =>
|
||||
toPlaylistSummary(playlist, user.name)
|
||||
)
|
||||
|
||||
for (const playlistId of user.subscribedPlaylists ?? []) {
|
||||
if (ownedIds.has(playlistId)) {
|
||||
continue
|
||||
}
|
||||
const playlist = await ctx.db.get("playlists", playlistId)
|
||||
if (!playlist) {
|
||||
continue
|
||||
}
|
||||
const owner = await ctx.db.get("users", playlist.owner)
|
||||
summaries.push(
|
||||
toPlaylistSummary(playlist, owner?.name ?? "Unknown")
|
||||
)
|
||||
}
|
||||
|
||||
return summaries.sort((a, b) => a.title.localeCompare(b.title))
|
||||
},
|
||||
})
|
||||
|
||||
export const getAlbumSongIds = query({
|
||||
args: { albumId: v.id("albums") },
|
||||
handler: async (ctx, args) => {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_album", (q) => q.eq("album", args.albumId))
|
||||
.collect()
|
||||
return songs.map((song) => song._id)
|
||||
},
|
||||
})
|
||||
|
||||
export const getArtistSongIds = query({
|
||||
args: { artistId: v.id("artists") },
|
||||
handler: async (ctx, args) => {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId))
|
||||
.collect()
|
||||
return songs.map((song) => song._id)
|
||||
},
|
||||
})
|
||||
|
||||
export const getPlaylistSongIds = query({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
const playlist = await ctx.db.get("playlists", args.playlistId)
|
||||
return playlist?.songs ?? []
|
||||
},
|
||||
})
|
||||
|
||||
export const createPlaylist = mutation({
|
||||
args: {
|
||||
name: v.string(),
|
||||
songIds: v.optional(v.array(v.id("songs"))),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const trimmed = args.name.trim()
|
||||
if (!trimmed) {
|
||||
throw new ConvexError("Playlist name cannot be empty")
|
||||
}
|
||||
|
||||
const uniqueSongIds = [...new Set(args.songIds ?? [])]
|
||||
|
||||
return await ctx.db.insert("playlists", {
|
||||
name: trimmed,
|
||||
owner: userId,
|
||||
cover: null,
|
||||
songs: uniqueSongIds,
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const addSongsToPlaylist = mutation({
|
||||
args: {
|
||||
playlistId: v.id("playlists"),
|
||||
songIds: v.array(v.id("songs")),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
||||
const existing = new Set(playlist.songs)
|
||||
for (const songId of args.songIds) {
|
||||
existing.add(songId)
|
||||
}
|
||||
await ctx.db.patch(playlist._id, { songs: [...existing] })
|
||||
},
|
||||
})
|
||||
|
||||
export const removeSongsFromPlaylist = mutation({
|
||||
args: {
|
||||
playlistId: v.id("playlists"),
|
||||
songIds: v.array(v.id("songs")),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
||||
const remove = new Set(args.songIds)
|
||||
await ctx.db.patch(playlist._id, {
|
||||
songs: playlist.songs.filter((songId) => !remove.has(songId)),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const reorderPlaylistSongs = mutation({
|
||||
args: {
|
||||
playlistId: v.id("playlists"),
|
||||
songIds: v.array(v.id("songs")),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { playlist } = await requirePlaylistOwner(ctx, args.playlistId)
|
||||
const existing = new Set(playlist.songs)
|
||||
if (
|
||||
args.songIds.length !== playlist.songs.length ||
|
||||
!args.songIds.every((songId) => existing.has(songId))
|
||||
) {
|
||||
throw new ConvexError("Invalid song order")
|
||||
}
|
||||
await ctx.db.patch(playlist._id, { songs: args.songIds })
|
||||
},
|
||||
})
|
||||
|
||||
export const deletePlaylist = mutation({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
await requirePlaylistOwner(ctx, args.playlistId)
|
||||
|
||||
const users = await ctx.db.query("users").collect()
|
||||
for (const user of users) {
|
||||
const subscribed = user.subscribedPlaylists
|
||||
if (!subscribed?.includes(args.playlistId)) {
|
||||
continue
|
||||
}
|
||||
await ctx.db.patch(user._id, {
|
||||
subscribedPlaylists: subscribed.filter((id) => id !== args.playlistId),
|
||||
})
|
||||
}
|
||||
|
||||
await ctx.db.delete("playlists", args.playlistId)
|
||||
},
|
||||
})
|
||||
|
||||
export const subscribeToPlaylist = mutation({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const playlist = await ctx.db.get("playlists", args.playlistId)
|
||||
if (!playlist) {
|
||||
throw new ConvexError("Playlist not found")
|
||||
}
|
||||
if (playlist.owner === userId) {
|
||||
throw new ConvexError("You already own this playlist")
|
||||
}
|
||||
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const subscribed = user.subscribedPlaylists ?? []
|
||||
if (subscribed.includes(args.playlistId)) {
|
||||
return
|
||||
}
|
||||
|
||||
await ctx.db.patch(userId, {
|
||||
subscribedPlaylists: [...subscribed, args.playlistId],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
export const unsubscribeFromPlaylist = mutation({
|
||||
args: { playlistId: v.id("playlists") },
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get("users", userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const subscribed = user.subscribedPlaylists ?? []
|
||||
await ctx.db.patch(userId, {
|
||||
subscribedPlaylists: subscribed.filter((id) => id !== args.playlistId),
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -18,6 +18,10 @@ export default defineSchema({
|
||||
)
|
||||
),
|
||||
preferAtmos: v.optional(v.boolean()),
|
||||
subscribedPlaylists: v.optional(v.array(v.id("playlists"))),
|
||||
favoriteArtists: v.optional(v.array(v.id("artists"))),
|
||||
favoriteAlbums: v.optional(v.array(v.id("albums"))),
|
||||
favoriteSongs: v.optional(v.array(v.id("songs"))),
|
||||
}).index("email", ["email"]),
|
||||
appSettings: defineTable({
|
||||
disableAccountCreation: v.boolean(),
|
||||
@@ -48,4 +52,10 @@ export default defineSchema({
|
||||
.index("by_artist", ["albumArtist"])
|
||||
.index("by_album", ["album"])
|
||||
.index("by_all", ["name", "albumArtist", "album"]),
|
||||
playlists: defineTable({
|
||||
name: v.string(),
|
||||
owner: v.id("users"),
|
||||
cover: v.nullable(v.string()),
|
||||
songs: v.array(v.id("songs")),
|
||||
}).index("by_owner", ["owner"]),
|
||||
})
|
||||
+18
-40
@@ -1,41 +1,19 @@
|
||||
export type Artist = {
|
||||
id: string
|
||||
name: string
|
||||
photo: string | null
|
||||
}
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseAlbumDetail,
|
||||
BrowseAlbumTrack,
|
||||
BrowseArtist,
|
||||
BrowsePlaylistDetail,
|
||||
BrowsePlaylistOwner,
|
||||
BrowseSong,
|
||||
PlaylistSummary,
|
||||
} from "@/convex/library"
|
||||
|
||||
export type Album = {
|
||||
id: string
|
||||
title: string
|
||||
artist: Artist
|
||||
cover: string | null
|
||||
}
|
||||
|
||||
export type Song = {
|
||||
id: string
|
||||
title: string
|
||||
artist: Artist
|
||||
album: Pick<Album, "id" | "title" | "cover">
|
||||
durationSeconds: number
|
||||
explicit?: boolean
|
||||
}
|
||||
|
||||
export type Playlist = {
|
||||
id: string
|
||||
title: string
|
||||
owner: string
|
||||
cover: string | null
|
||||
}
|
||||
|
||||
export type AlbumTrack = {
|
||||
id: string
|
||||
title: string
|
||||
track: number
|
||||
durationSeconds: number
|
||||
}
|
||||
|
||||
export type AlbumDetail = Album & {
|
||||
year: number | null
|
||||
genre: string | null
|
||||
tracks: AlbumTrack[]
|
||||
}
|
||||
export type Artist = BrowseArtist
|
||||
export type Album = BrowseAlbum
|
||||
export type Song = BrowseSong
|
||||
export type Playlist = PlaylistSummary
|
||||
export type PlaylistOwner = BrowsePlaylistOwner
|
||||
export type PlaylistDetail = BrowsePlaylistDetail
|
||||
export type AlbumTrack = BrowseAlbumTrack
|
||||
export type AlbumDetail = BrowseAlbumDetail
|
||||
@@ -1,23 +0,0 @@
|
||||
import type { Playlist } from "@/lib/data"
|
||||
|
||||
export const placeholderPlaylists: Playlist[] = [
|
||||
{
|
||||
id: "choir-bands",
|
||||
title: "Choir & Bands",
|
||||
owner: "Joshua Higgins",
|
||||
cover: null,
|
||||
},
|
||||
{ id: "plays", title: "Plays", owner: "Joshua Higgins", cover: null },
|
||||
{
|
||||
id: "sea-shanties",
|
||||
title: "Sea Shanties",
|
||||
owner: "Joshua Higgins",
|
||||
cover: null,
|
||||
},
|
||||
{
|
||||
id: "stay-civilized",
|
||||
title: "Stay Civilized",
|
||||
owner: "Joshua Higgins",
|
||||
cover: null,
|
||||
},
|
||||
]
|
||||
@@ -5,8 +5,17 @@ import {
|
||||
} from "@convex-dev/auth/nextjs/server"
|
||||
|
||||
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
|
||||
const isPublicCoverApiRoute = createRouteMatcher([
|
||||
"/api/album/:id/cover",
|
||||
"/api/artist/:id/cover",
|
||||
"/api/playlist/:id/cover",
|
||||
])
|
||||
|
||||
export default convexAuthNextjsMiddleware(async (request, { convexAuth }) => {
|
||||
if (isPublicCoverApiRoute(request)) {
|
||||
return
|
||||
}
|
||||
|
||||
const authenticated = await convexAuth.isAuthenticated()
|
||||
|
||||
if (isAuthPage(request) && authenticated) {
|
||||
|
||||
Reference in new issue
Block a user