diff --git a/app/(app)/album/[id]/page.tsx b/app/(app)/album/[id]/page.tsx index de32860..23ff8a7 100644 --- a/app/(app)/album/[id]/page.tsx +++ b/app/(app)/album/[id]/page.tsx @@ -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 + return } diff --git a/app/(app)/layout.tsx b/app/(app)/layout.tsx index 045663d..36f78b3 100644 --- a/app/(app)/layout.tsx +++ b/app/(app)/layout.tsx @@ -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 ( - - {children} - + + + + {children} + + + ) } diff --git a/app/(app)/playlist/[id]/page.tsx b/app/(app)/playlist/[id]/page.tsx new file mode 100644 index 0000000..520010b --- /dev/null +++ b/app/(app)/playlist/[id]/page.tsx @@ -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 ( +
+ +
+ ) + } + + if (playlist === null) { + return ( +
+
+

Playlist not found.

+
+
+ ) + } + + return +} diff --git a/app/(app)/playlist/favorites/page.tsx b/app/(app)/playlist/favorites/page.tsx new file mode 100644 index 0000000..17dbe7f --- /dev/null +++ b/app/(app)/playlist/favorites/page.tsx @@ -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 ( +
+ +
+ ) + } + + if (favorites === null) { + return ( +
+
+

+ Sign in to view your favorites. +

+
+
+ ) + } + + return +} diff --git a/app/(app)/playlists/page.tsx b/app/(app)/playlists/page.tsx new file mode 100644 index 0000000..087db27 --- /dev/null +++ b/app/(app)/playlists/page.tsx @@ -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 ( +
+
+

Playlists

+
+ + {playlists === undefined ? ( + + ) : ( +
+
+ {playlists.map((playlist) => ( + + ))} +
+
+ )} +
+ ) +} diff --git a/app/(app)/search/page.tsx b/app/(app)/search/page.tsx index 3cdcbb4..767eca7 100644 --- a/app/(app)/search/page.tsx +++ b/app/(app)/search/page.tsx @@ -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 && ( )} {results.albums.length > 0 && ( )} @@ -98,7 +107,7 @@ export default function Page() {

Songs

{results.songs.map((song) => ( - + ))}
@@ -107,7 +116,7 @@ export default function Page() { {showPlaylists && ( )} diff --git a/app/api/playlist/[id]/cover/route.ts b/app/api/playlist/[id]/cover/route.ts index a21ebb9..faf0488 100644 --- a/app/api/playlist/[id]/cover/route.ts +++ b/app/api/playlist/[id]/cover/route.ts @@ -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 }) + } } diff --git a/app/globals.css b/app/globals.css index a24ca80..2ce10f5 100644 --- a/app/globals.css +++ b/app/globals.css @@ -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; } diff --git a/components/add-to-playlist-provider.tsx b/components/add-to-playlist-provider.tsx new file mode 100644 index 0000000..283771f --- /dev/null +++ b/components/add-to-playlist-provider.tsx @@ -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 + openAddPlaylistToPlaylist: (playlistId: Id<"playlists">) => Promise + openAddArtistToPlaylist: (artistId: Id<"artists">) => Promise +} + +const AddToPlaylistContext = React.createContext( + 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[]>([]) + 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 ( + + {children} + + { + setOpen(next) + if (!next) { + setPendingSongIds([]) + } + }} + > + + + Add to Playlist + + {pendingSongIds.length > 1 + ? `Choose a playlist for ${pendingSongIds.length} songs.` + : "Choose a playlist for this song."} + + + + +
+ {ownedPlaylists === undefined ? ( +

Loading…

+ ) : ownedPlaylists.length === 0 ? ( +

+ You do not have any playlists yet. +

+ ) : ( + ownedPlaylists.map((playlist) => ( + + )) + )} +
+
+ + + + +
+
+ + + +
+ + New Playlist + + Enter a name for your new playlist. + + + setNewPlaylistName(event.target.value)} + autoFocus + /> + + + + +
+
+
+
+ ) +} diff --git a/components/album-card.tsx b/components/album-card.tsx index 76a8c4e..32bec2c 100644 --- a/components/album-card.tsx +++ b/components/album-card.tsx @@ -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 (
@@ -64,22 +72,48 @@ export function AlbumCard({ album }: { album: Album }) { - + { + event.preventDefault() + void openAddAlbumToPlaylist(album.id as Id<"albums">) + }} + > Add to Playlist - + event.preventDefault()} + > Play Next - + event.preventDefault()} + > Play Last - - Favorite + + + Go to Artist + + + + + { + event.preventDefault() + void toggleAlbumFavorite(album.id as Id<"albums">) + }} + > + {isAlbumFavorite(album.id) ? "Unfavorite" : "Favorite"} diff --git a/components/album-view.tsx b/components/album-view.tsx index 60dbd4b..8837b33 100644 --- a/components/album-view.tsx +++ b/components/album-view.tsx @@ -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({ 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 }, + }} />
) } -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>( - () => 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" /> @@ -363,8 +346,10 @@ export function AlbumView({ album }: { album: AlbumDetail }) { Play 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} /> diff --git a/components/app-sidebar.tsx b/components/app-sidebar.tsx index 73c246d..86a3437 100644 --- a/components/app-sidebar.tsx +++ b/components/app-sidebar.tsx @@ -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 ( @@ -143,8 +148,8 @@ export function AppSidebar() { Playlists - {playlists.map((item) => ( - + {playlistNav.map((item) => ( + diff --git a/components/artist-card.tsx b/components/artist-card.tsx index e2304ba..add6f93 100644 --- a/components/artist-card.tsx +++ b/components/artist-card.tsx @@ -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 (
) 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({ 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" diff --git a/components/artists-view.tsx b/components/artists-view.tsx index cc3e5ac..b458d6d 100644 --- a/components/artists-view.tsx +++ b/components/artists-view.tsx @@ -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 (
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>( - () => new Set() - ) + const { isArtistFavorite, toggleArtistFavorite } = useFavorites() const selectedArtist = sortedArtists.find( (artist) => artist.id === selectedId @@ -114,17 +114,9 @@ export function ArtistsView({ - 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}`} diff --git a/components/content-carousel.tsx b/components/content-carousel.tsx index 1c4fed2..d0c3d32 100644 --- a/components/content-carousel.tsx +++ b/components/content-carousel.tsx @@ -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 } @@ -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 diff --git a/components/favorites-provider.tsx b/components/favorites-provider.tsx new file mode 100644 index 0000000..61fe145 --- /dev/null +++ b/components/favorites-provider.tsx @@ -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 + toggleSongsFavorite: (songIds: Id<"songs">[], favorited: boolean) => Promise + toggleAlbumFavorite: (albumId: Id<"albums">) => Promise + toggleArtistFavorite: (artistId: Id<"artists">) => Promise + favoriteSongs: (songIds: Id<"songs">[]) => Promise +} + +const FavoritesContext = React.createContext(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 ( + {children} + ) +} diff --git a/components/media-context-menu.tsx b/components/media-context-menu.tsx index f4b5c32..30320eb 100644 --- a/components/media-context-menu.tsx +++ b/components/media-context-menu.tsx @@ -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 ( <> onAction("playlist")} > - {actionLabel("Add to Playlist", selectedCount)} + {actionLabel(playlistLabel, selectedCount)} @@ -55,36 +74,102 @@ export function MediaContextMenuItems({ {actionLabel("Play Last", selectedCount)} - - onAction("favorite")} - > - {actionLabel("Favorite", selectedCount)} - - + {artist || album ? ( + <> + + {artist ? ( + + + Go to Artist + + + + ) : null} + {album ? ( + + + Go to Album + + + + ) : null} + + ) : null} + {showFavorite ? ( + <> + + onAction("favorite")} + > + {actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)} + + + + ) : 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 ( event.stopPropagation()} > @@ -109,7 +198,12 @@ export function MediaContextMenu({ + {children} ) diff --git a/components/playlist-card.tsx b/components/playlist-card.tsx index 091a9e4..acf00f8 100644 --- a/components/playlist-card.tsx +++ b/components/playlist-card.tsx @@ -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 (
@@ -48,16 +52,28 @@ export function PlaylistCard({ playlist }: { playlist: Playlist }) { - + { + event.preventDefault() + void openAddPlaylistToPlaylist(playlist.id as Id<"playlists">) + }} + > Add to Playlist - + event.preventDefault()} + > Play Next - + event.preventDefault()} + > Play Last diff --git a/components/playlist-view.tsx b/components/playlist-view.tsx new file mode 100644 index 0000000..fd1843b --- /dev/null +++ b/components/playlist-view.tsx @@ -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 ( +
+ {song.album.title} +
+ +
+
+ ) +} + +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 ( +
{ + 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" + )} + > + + {!inRange && isActive ? : null} + {!inRange && !isActive ? : null} +
+ + +
+ {isActive ? ( + + ) : ( + {displayTrack} + )} +
+ + {song.title} + + + {formatDuration(song.durationSeconds)} + + + 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 ? ( + <> + + + {removeLabel} + + + + ) : null} + +
+
+ ) +} + +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(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 ( +
+ +
+
+ {!isFavorites ? ( + + ) : null} + + + + + + + {playlist.isOwner && !isFavorites ? ( + <> + + + Delete Playlist + + + + ) : null} + + +
+ +
+
+
+ {isFavorites ? ( +
+ +
+ ) : ( + {playlist.title} + )} +
+ +
+
+

+ Playlist +

+

+ {playlist.title} +

+

+ {playlist.owner.name} +

+
+ +
+ + + {!playlist.isOwner ? ( + + ) : null} +
+
+
+ + {songs.length > 0 ? ( + songs.map((song, index) => ( + 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) + }} + /> + )) + ) : ( +

+ This playlist has no songs yet. +

+ )} +
+
+
+
+ ) +} diff --git a/components/search-song-item.tsx b/components/search-song-item.tsx index 6080b42..183a24d 100644 --- a/components/search-song-item.tsx +++ b/components/search-song-item.tsx @@ -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" /> diff --git a/components/search-top-result-card.tsx b/components/search-top-result-card.tsx index 53d3d33..74c6854 100644 --- a/components/search-top-result-card.tsx +++ b/components/search-top-result-card.tsx @@ -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) { diff --git a/components/songs-view.tsx b/components/songs-view.tsx index 4593aa4..b29d26c 100644 --- a/components/songs-view.tsx +++ b/components/songs-view.tsx @@ -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 (
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 }, + }} />
@@ -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("title") const [sortDirection, setSortDirection] = React.useState("asc") - const [favoriteIds, setFavoriteIds] = React.useState>( - () => 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} /> diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index 1615508..d65bf0f 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -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; }>; diff --git a/convex/actions.ts b/convex/actions.ts index 8cc65f3..85190ff 100644 --- a/convex/actions.ts +++ b/convex/actions.ts @@ -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 { + 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, diff --git a/convex/favorites.ts b/convex/favorites.ts new file mode 100644 index 0000000..d7c074c --- /dev/null +++ b/convex/favorites.ts @@ -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(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, Doc<"artists">>, + albumMap: Map, Doc<"albums">> +): Promise { + 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 => { + 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)), + }) + }, +}) diff --git a/convex/library.ts b/convex/library.ts index a676d3b..6fe387b 100644 --- a/convex/library.ts +++ b/convex/library.ts @@ -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 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 => { @@ -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[] = [ + ...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[] = 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[] = 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) => { diff --git a/convex/playlists.ts b/convex/playlists.ts new file mode 100644 index 0000000..62c2c96 --- /dev/null +++ b/convex/playlists.ts @@ -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, Doc<"artists">>, + albumMap: Map, Doc<"albums">> +): Promise { + 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 => { + 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 => { + 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), + }) + }, +}) diff --git a/convex/schema.ts b/convex/schema.ts index aa1c6c1..b329233 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -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"]), }) diff --git a/lib/data.ts b/lib/data.ts index e12f7d1..662421d 100644 --- a/lib/data.ts +++ b/lib/data.ts @@ -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 - 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 diff --git a/lib/playlists.ts b/lib/playlists.ts deleted file mode 100644 index 79c1ceb..0000000 --- a/lib/playlists.ts +++ /dev/null @@ -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, - }, -] diff --git a/proxy.ts b/proxy.ts index 6384f30..5a91618 100644 --- a/proxy.ts +++ b/proxy.ts @@ -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) {