diff --git a/app/album/[id]/page.tsx b/app/album/[id]/page.tsx new file mode 100644 index 0000000..de32860 --- /dev/null +++ b/app/album/[id]/page.tsx @@ -0,0 +1,37 @@ +"use client" + +import { useParams } from "next/navigation" +import { useQuery } from "convex/react" + +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" + +export default function Page() { + const { id } = useParams<{ id: string }>() + const album = useQuery(api.library.browseAlbumDetail, { + id: id as Id<"albums">, + }) + + if (album === undefined) { + return ( +
+ +
+ ) + } + + if (album === null) { + return ( +
+
+

Album not found.

+
+
+ ) + } + + return +} diff --git a/app/api/album/[id]/cover/route.ts b/app/api/album/[id]/cover/route.ts new file mode 100644 index 0000000..016d2d3 --- /dev/null +++ b/app/api/album/[id]/cover/route.ts @@ -0,0 +1,20 @@ +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 }) + } +} diff --git a/app/api/artist/[id]/cover/route.ts b/app/api/artist/[id]/cover/route.ts new file mode 100644 index 0000000..78acbc7 --- /dev/null +++ b/app/api/artist/[id]/cover/route.ts @@ -0,0 +1,20 @@ +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 artist = await getConvexClient().query(api.library.getArtist, { + id: id as Id<"artists">, + }) + return serveCoverFile(artist?.cover) + } catch { + return new Response("Not found", { status: 404 }) + } +} diff --git a/app/api/playlist/[id]/cover/route.ts b/app/api/playlist/[id]/cover/route.ts new file mode 100644 index 0000000..a21ebb9 --- /dev/null +++ b/app/api/playlist/[id]/cover/route.ts @@ -0,0 +1,28 @@ +// 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" + +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", + }, + }) +} diff --git a/app/artist/[id]/page.tsx b/app/artist/[id]/page.tsx new file mode 100644 index 0000000..6afbe2b --- /dev/null +++ b/app/artist/[id]/page.tsx @@ -0,0 +1,43 @@ +"use client" + +import { useParams } from "next/navigation" +import { useQuery } from "convex/react" + +import { ArtistView } from "@/components/artist-view" +import { LibraryLoading } from "@/components/library-loading" +import { api } from "@/convex/_generated/api" +import type { Id } from "@/convex/_generated/dataModel" + +export default function Page() { + const { id } = useParams<{ id: string }>() + const data = useQuery(api.library.browseArtistDetail, { + id: id as Id<"artists">, + }) + + if (data === undefined) { + return ( +
+ +
+ ) + } + + if (data === null) { + return ( +
+
+

Artist not found.

+
+
+ ) + } + + return ( + + ) +} diff --git a/app/globals.css b/app/globals.css index 7b5d576..a24ca80 100644 --- a/app/globals.css +++ b/app/globals.css @@ -80,6 +80,7 @@ --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 { @@ -114,6 +115,17 @@ --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; + color: var(--foreground) !important; } @layer base { diff --git a/app/layout.tsx b/app/layout.tsx index d31bbec..c867ec3 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,11 +1,13 @@ import { Geist, Geist_Mono, Inter } from "next/font/google" import "./globals.css" +import { ConvexClientProvider } from "@/components/convex-client-provider" import { ThemeProvider } from "@/components/theme-provider" import { cn } from "@/lib/utils" import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar" import { AppSidebar } from "@/components/app-sidebar" import { PlayerBar } from "@/components/player-bar" +import { Toaster } from "@/components/ui/sonner" import type { Metadata } from "next" const inter = Inter({ subsets: ["latin"], variable: "--font-sans" }) @@ -37,15 +39,18 @@ export default function RootLayout({ )} > - - - - - {children} - - - - + + + + + + {children} + + + + + + ) diff --git a/app/library/albums/page.tsx b/app/library/albums/page.tsx index beb1602..bd32d46 100644 --- a/app/library/albums/page.tsx +++ b/app/library/albums/page.tsx @@ -1,20 +1,31 @@ +"use client" + +import { useQuery } from "convex/react" + import { AlbumCard } from "@/components/album-card" -import { albums } from "@/lib/data" +import { LibraryLoading } from "@/components/library-loading" +import { api } from "@/convex/_generated/api" export default function Page() { + const albums = useQuery(api.library.browseAlbums) + return (

Albums

-
-
- {albums.map((album) => ( - - ))} + {albums === undefined ? ( + + ) : ( +
+
+ {albums.map((album) => ( + + ))} +
-
+ )}
) } diff --git a/app/library/artists/page.tsx b/app/library/artists/page.tsx index d556863..be6db88 100644 --- a/app/library/artists/page.tsx +++ b/app/library/artists/page.tsx @@ -1,14 +1,26 @@ +"use client" + +import { useQuery } from "convex/react" + import { ArtistsView } from "@/components/artists-view" -import { albums, artists } from "@/lib/data" +import { LibraryLoading } from "@/components/library-loading" +import { api } from "@/convex/_generated/api" export default function Page() { + const artists = useQuery(api.library.browseArtists) + const albums = useQuery(api.library.browseAlbums) + return (

Artists

- + {artists === undefined || albums === undefined ? ( + + ) : ( + + )}
) } diff --git a/app/library/songs/page.tsx b/app/library/songs/page.tsx index 9ddbf06..e3a9dde 100644 --- a/app/library/songs/page.tsx +++ b/app/library/songs/page.tsx @@ -1,6 +1,17 @@ +"use client" + +import { useQuery } from "convex/react" + +import { LibraryLoading } from "@/components/library-loading" import { SongsView } from "@/components/songs-view" -import { songs } from "@/lib/data" +import { api } from "@/convex/_generated/api" export default function Page() { + const songs = useQuery(api.library.browseSongs) + + if (songs === undefined) { + return + } + return } diff --git a/app/page.tsx b/app/page.tsx index a5b8df1..d77dbd7 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,9 +1,26 @@ "use client" +import { useQuery } from "convex/react" + import { ContentCarousel } from "@/components/content-carousel" -import { recentlyAdded, recentlyPlayed } from "@/lib/data" +import { LibraryLoading } from "@/components/library-loading" +import { api } from "@/convex/_generated/api" export default function Page() { + const recentlyAdded = useQuery(api.library.browseRecentlyAdded) + const recentlyPlayed = useQuery(api.library.browseAlbums) + + if (recentlyAdded === undefined || recentlyPlayed === undefined) { + return ( +
+
+

Home

+
+ +
+ ) + } + return (
@@ -15,12 +32,12 @@ export default function Page() {
diff --git a/app/recently-added/page.tsx b/app/recently-added/page.tsx index 29d0ccc..0da5a49 100644 --- a/app/recently-added/page.tsx +++ b/app/recently-added/page.tsx @@ -1,20 +1,31 @@ +"use client" + +import { useQuery } from "convex/react" + import { AlbumCard } from "@/components/album-card" -import { albums } from "@/lib/data" +import { LibraryLoading } from "@/components/library-loading" +import { api } from "@/convex/_generated/api" export default function Page() { + const albums = useQuery(api.library.browseRecentlyAdded) + return (

Recently Added

-
-
- {albums.map((album) => ( - - ))} + {albums === undefined ? ( + + ) : ( +
+
+ {albums.map((album) => ( + + ))} +
-
+ )}
) } diff --git a/app/recently-played/page.tsx b/app/recently-played/page.tsx index aee5994..f71316b 100644 --- a/app/recently-played/page.tsx +++ b/app/recently-played/page.tsx @@ -1,20 +1,31 @@ +"use client" + +import { useQuery } from "convex/react" + import { AlbumCard } from "@/components/album-card" -import { albums } from "@/lib/data" +import { LibraryLoading } from "@/components/library-loading" +import { api } from "@/convex/_generated/api" export default function Page() { + const albums = useQuery(api.library.browseAlbums) + return (

Recently Played

-
-
- {albums.map((album) => ( - - ))} + {albums === undefined ? ( + + ) : ( +
+
+ {albums.map((album) => ( + + ))} +
-
+ )}
) } diff --git a/app/search/page.tsx b/app/search/page.tsx index 3e72e92..3cdcbb4 100644 --- a/app/search/page.tsx +++ b/app/search/page.tsx @@ -1,31 +1,118 @@ "use client" -import { AlbumCard } from "@/components/album-card" -import { albums } from "@/lib/data" +import { useDeferredValue, useState } from "react" +import { useQuery } from "convex/react" 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" + export default function Page() { + const [query, setQuery] = useState("") + const deferredQuery = useDeferredValue(query.trim()) + const hasQuery = deferredQuery.length > 0 + + const results = useQuery( + api.library.searchLibrary, + hasQuery ? { query: deferredQuery } : "skip" + ) + + const showPlaylists = hasQuery && results !== undefined + const isSearching = hasQuery && results === undefined + const hasLibraryResults = + results && + (results.topResults.length > 0 || + results.artists.length > 0 || + results.albums.length > 0 || + results.songs.length > 0) + const showResults = hasQuery && results !== undefined + return (
-
-
+
+
setQuery(event.target.value)} placeholder="Search" - className="h-9 w-full min-w-0 rounded-full border border-input bg-input/30 pr-3 pl-9 text-sm text-foreground transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" + className="h-10 w-full min-w-0 rounded-full border border-input bg-input/30 pr-3 pl-9 text-sm text-foreground transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" />
-
-
- {albums.map((album) => ( - - ))} + {isSearching ? ( + + ) : !hasQuery ? ( +
+

+ Search for songs, albums, artists, and playlists in your library. +

-
+ ) : !showResults ? null : ( +
+
+ {!hasLibraryResults && ( +

+ No library results for “{deferredQuery}” +

+ )} + + {results.topResults.length > 0 && ( +
+

Top Results

+
+ {results.topResults.map((result) => ( + + ))} +
+
+ )} + + {results.artists.length > 0 && ( + + )} + + {results.albums.length > 0 && ( + + )} + + {results.songs.length > 0 && ( +
+

Songs

+
+ {results.songs.map((song) => ( + + ))} +
+
+ )} + + {showPlaylists && ( + + )} +
+
+ )}
) } diff --git a/components/album-card.tsx b/components/album-card.tsx index 795b1fa..76a8c4e 100644 --- a/components/album-card.tsx +++ b/components/album-card.tsx @@ -20,31 +20,23 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import type { Album } from "@/lib/data" +import { albumCoverUrl } from "@/lib/cover-urls" export function AlbumCard({ album }: { album: Album }) { return ( -
-
+
+
- {album.cover ? ( - {album.title} - ) : ( - {album.title} - )} + {album.title}
@@ -96,11 +88,14 @@ export function AlbumCard({ album }: { album: Album }) {
- +

{album.title}

- -

+ +

{album.artist.name}

diff --git a/components/album-view.tsx b/components/album-view.tsx new file mode 100644 index 0000000..ae8a36b --- /dev/null +++ b/components/album-view.tsx @@ -0,0 +1,416 @@ +"use client" + +import * as React from "react" +import Image from "next/image" +import Link from "next/link" +import { Play, Share2, Shuffle, Star } from "lucide-react" + +import { FavoriteMediaButton } from "@/components/favorite-media-button" +import { toast } from "sonner" + +import { + MediaContextMenu, + type MediaContextAction, +} from "@/components/media-context-menu" +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 { + getSelectionRangePositions, + isInSelectionRange, + ALBUM_TRACK_ROW, + ALBUM_TRACK_TITLE, + SelectionRangeHighlight, + TRACK_LIST_CONTAINER, + TrackRowActiveHighlight, + TrackRowHoverHighlight, + TRACK_ROW_PADDING, + type SelectionRangePosition, +} from "@/lib/selection-range-styles" +import { albumCoverUrl } from "@/lib/cover-urls" + +function formatDuration(seconds: number): string { + const minutes = Math.floor(seconds / 60) + const remainingSeconds = seconds % 60 + return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}` +} + +function albumUrl(albumId: string) { + return `${window.location.origin}/album/${albumId}` +} + +async function copyAlbumLink(albumId: string) { + await navigator.clipboard.writeText(albumUrl(albumId)) + toast.success("Link Copied") +} + +function formatMetadata(genre: string | null, year: number | null): string | null { + const parts: string[] = [] + if (genre) { + parts.push(genre) + } + if (year) { + parts.push(String(year)) + } + return parts.length > 0 ? parts.join(" · ") : null +} + +function TrackRow({ + track, + index, + isActive, + isSelected, + selectionPosition, + isFavorite, + selectedCount, + onSelect, + onPointerDown, + onToggleFavorite, + onPrepareContextMenu, + onMediaAction, +}: { + track: AlbumTrack + index: number + isActive: boolean + isSelected: boolean + selectionPosition: SelectionRangePosition + isFavorite: boolean + selectedCount: number + onSelect: (event: React.MouseEvent) => void + onPointerDown: (event: React.MouseEvent) => void + onToggleFavorite: () => void + onPrepareContextMenu: () => void + onMediaAction: (action: MediaContextAction, trackId: string) => void +}) { + const displayTrack = track.track > 0 ? track.track : 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" + )} + > + + {!inRange && isActive ? : null} + {!inRange && !isActive ? : null} +
+
+
+ +
+ +
+ {isActive ? ( + + ) : ( + {displayTrack} + )} +
+ + {track.title} +
+ +
+ +
+ + {formatDuration(track.durationSeconds)} + + + 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" + )} + /> +
+
+
+ ) +} + +export function AlbumView({ album }: { album: AlbumDetail }) { + 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, + selectedCount, + isSelected, + handleSelect, + handlePointerDown, + prepareContextMenu, + clearSelection, + } = useTrackSelection(album.tracks) + + const selectionPositions = React.useMemo( + () => getSelectionRangePositions(album.tracks.map((track) => track.id), selectedIds), + [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 + ) { + const targetIds = + selectedIds.size > 0 + ? Array.from(selectedIds) + : fallbackTrackId + ? [fallbackTrackId] + : activeTrackId + ? [activeTrackId] + : [] + const count = targetIds.length + + 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" + ) + break + case "playlist": + toast.success( + count > 1 + ? `Added ${count} songs to playlist` + : "Added to playlist" + ) + 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 handleAlbumMediaAction(action: MediaContextAction) { + const targetIds = album.tracks.map((track) => track.id) + const count = targetIds.length + + switch (action) { + case "favorite": + setIsAlbumFavorite(true) + setFavoriteIds(new Set(targetIds)) + toast.success(`Favorited ${count} songs`) + break + case "playlist": + toast.success(`Added ${count} songs to playlist`) + break + case "play-next": + toast.success(`Queued ${count} songs to play next`) + break + case "play-last": + toast.success(`Queued ${count} songs to play last`) + break + } + } + + return ( +
+ +
+
+ + {}} + onAction={handleAlbumMediaAction} + triggerClassName="size-8" + /> +
+ +
+
+ {album.title} +
+ +
+
+

+ Album +

+

+ {album.title} +

+ + {album.artist.name} + + {metadata ? ( +

{metadata}

+ ) : null} +
+ +
+ + + setIsAlbumFavorite((current) => !current)} + favoritedLabel={`Remove ${album.title} from favorites`} + unfavoritedLabel={`Favorite ${album.title}`} + /> +
+
+
+ +
+ {album.tracks.length > 0 ? ( + album.tracks.map((track, index) => ( + 0 + ? selectedCount + : 1 + } + onPointerDown={handlePointerDown} + onSelect={(event) => { + handleSelect(track.id, index, event) + setActiveTrackId(track.id) + }} + onToggleFavorite={() => toggleFavorite(track.id)} + onPrepareContextMenu={() => prepareContextMenu(track.id)} + onMediaAction={handleMediaAction} + /> + )) + ) : ( +

+ No tracks in this album. +

+ )} +
+
+
+
+ ) +} diff --git a/components/app-sidebar.tsx b/components/app-sidebar.tsx index 4202d24..7347f77 100644 --- a/components/app-sidebar.tsx +++ b/components/app-sidebar.tsx @@ -29,6 +29,7 @@ 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" const browse = [ { title: "Home", path: "/", icon: House }, @@ -43,11 +44,11 @@ const library = [ const playlists = [ { title: "All Playlists", path: "/playlists", icon: ListMusic }, - { title: "Favorite Songs", path: "/playlist/Favorite Songs", icon: ListMusic }, - { title: "Choir & Bands", path: "/playlist/Choir & Bands", icon: ListMusic }, - { title: "Plays", path: "/playlist/Plays", icon: ListMusic }, - { title: "Sea Shanties", path: "/playlist/Sea Shanties", icon: ListMusic }, - { title: "Stay Civilized", path: "/playlist/Stay Civilized", icon: ListMusic }, + ...placeholderPlaylists.map((playlist) => ({ + title: playlist.title, + path: playlist.path, + icon: ListMusic, + })), ] export function AppSidebar() { diff --git a/components/artist-card.tsx b/components/artist-card.tsx index ffcca75..e2304ba 100644 --- a/components/artist-card.tsx +++ b/components/artist-card.tsx @@ -4,33 +4,25 @@ import Image from "next/image" import Link from "next/link" import type { Artist } from "@/lib/data" +import { artistCoverUrl } from "@/lib/cover-urls" export function ArtistCard({ artist }: { artist: Artist }) { return (
- {artist.photo ? ( - {artist.name} - ) : ( - {artist.name} - )} + {artist.name}
- +

{artist.name}

diff --git a/components/artist-view.tsx b/components/artist-view.tsx new file mode 100644 index 0000000..428e6c5 --- /dev/null +++ b/components/artist-view.tsx @@ -0,0 +1,158 @@ +"use client" + +import * as React from "react" +import Image from "next/image" +import { Play, Shuffle } from "lucide-react" +import { toast } from "sonner" + +import { AlbumCard } from "@/components/album-card" +import { FavoriteMediaButton } from "@/components/favorite-media-button" +import { ContentCarousel } from "@/components/content-carousel" +import { + MediaContextMenu, + type MediaContextAction, +} 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 { + albumGridCarouselContentClassName, + albumGridCarouselSlideClassName, + albumGridClassName, +} from "@/lib/album-grid-classes" +import { artistCoverUrl } from "@/lib/cover-urls" + +export function ArtistView({ + artist, + albums, + recentlyAdded, + recentlyPlayed, +}: { + artist: Artist + albums: Album[] + recentlyAdded: Album[] + recentlyPlayed: Album[] +}) { + const [isFavorite, setIsFavorite] = React.useState(false) + + function handleMediaAction(action: MediaContextAction) { + switch (action) { + case "favorite": + setIsFavorite(true) + toast.success("Added artist to favorites") + break + case "playlist": + toast.success("Added to playlist") + break + case "play-next": + toast.success("Play next") + break + case "play-last": + toast.success("Play last") + break + } + } + + return ( +
+ +
+
+
+ {artist.name} +
+ +
+

+ {artist.name} +

+ +
+ + + setIsFavorite((current) => !current)} + favoritedLabel={`Remove ${artist.name} from favorites`} + unfavoritedLabel={`Favorite ${artist.name}`} + className="size-11" + /> + {}} + onAction={handleMediaAction} + triggerVariant="secondary" + triggerClassName="size-11 rounded-full" + triggerIconClassName="size-4" + /> +
+
+
+ +
+ {recentlyPlayed.length > 0 || recentlyAdded.length > 0 ? ( +
+ {recentlyPlayed.length > 0 ? ( + + ) : ( +
+ )} + {recentlyAdded.length > 0 ? ( + + ) : ( +
+ )} +
+ ) : null} + +
+

Albums

+ {albums.length > 0 ? ( +
+ {albums.map((album) => ( + + ))} +
+ ) : ( +

+ No albums for this artist. +

+ )} +
+
+
+ +
+ ) +} diff --git a/components/artists-view.tsx b/components/artists-view.tsx index dad3c62..cc3e5ac 100644 --- a/components/artists-view.tsx +++ b/components/artists-view.tsx @@ -3,24 +3,21 @@ import * as React from "react" import Image from "next/image" import Link from "next/link" -import { - ChevronRightIcon, - Play, - Shuffle, - Star, -} from "lucide-react" +import { ChevronRightIcon, Play, Shuffle } from "lucide-react" import { AlbumCard } from "@/components/album-card" +import { FavoriteMediaButton } from "@/components/favorite-media-button" 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 { artistCoverUrl } from "@/lib/cover-urls" function ArtistAvatar({ artist }: { artist: Artist }) { return (
{artist.name} sortedArtists[0]?.id ?? "" ) + const [favoriteIds, setFavoriteIds] = React.useState>( + () => new Set() + ) const selectedArtist = sortedArtists.find( (artist) => artist.id === selectedId @@ -94,8 +94,8 @@ export function ArtistsView({
{selectedArtist.name} @@ -113,14 +113,22 @@ 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 + }) + } + favoritedLabel={`Remove ${selectedArtist.name} from favorites`} + unfavoritedLabel={`Favorite ${selectedArtist.name}`} + />
diff --git a/components/content-carousel.tsx b/components/content-carousel.tsx index ad7835b..1c4fed2 100644 --- a/components/content-carousel.tsx +++ b/components/content-carousel.tsx @@ -4,7 +4,7 @@ import Link from "next/link" import { ChevronRightIcon } from "lucide-react" import { AlbumCard } from "@/components/album-card" -import type { Album, Artist } from "@/lib/data" +import type { Album, Artist, Playlist } from "@/lib/data" import { Carousel, CarouselContent, @@ -12,26 +12,48 @@ import { CarouselNext, CarouselPrevious, } from "@/components/ui/carousel" +import { cn } from "@/lib/utils" import { ArtistCard } from "./artist-card" +import { PlaylistCard } from "./playlist-card" + +function CarouselCard({ item }: { item: Album | Artist | Playlist }) { + if ("owner" in item) { + return + } + if ("artist" in item) { + return + } + return +} export function ContentCarousel({ title, href, content, + className, + slideClassName = "basis-1/2 pl-4 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6", + carouselContentClassName, }: { title: string - href: string - content: (Album | Artist)[] + href?: string + content: (Album | Artist | Playlist)[] + className?: string + slideClassName?: string + carouselContentClassName?: string }) { return ( -
- - {title} - - +
+ {href ? ( + + {title} + + + ) : ( +

{title}

+ )} - - {content.map((card) => ( - - {"artist" in card ? ( - - ) : ( - - )} + + {content.map((item) => ( + + ))} -
- - +
+ +
diff --git a/components/convex-client-provider.tsx b/components/convex-client-provider.tsx new file mode 100644 index 0000000..31c2fa5 --- /dev/null +++ b/components/convex-client-provider.tsx @@ -0,0 +1,13 @@ +"use client" + +import { ConvexProvider, ConvexReactClient } from "convex/react" + +const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!) + +export function ConvexClientProvider({ + children, +}: { + children: React.ReactNode +}) { + return {children} +} diff --git a/components/favorite-media-button.tsx b/components/favorite-media-button.tsx new file mode 100644 index 0000000..e475640 --- /dev/null +++ b/components/favorite-media-button.tsx @@ -0,0 +1,42 @@ +"use client" + +import { Star } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { cn } from "@/lib/utils" + +type FavoriteMediaButtonProps = { + isFavorite: boolean + onToggle: () => void + favoritedLabel: string + unfavoritedLabel: string + className?: string + iconClassName?: string +} + +export function FavoriteMediaButton({ + isFavorite, + onToggle, + favoritedLabel, + unfavoritedLabel, + className, + iconClassName = "size-4", +}: FavoriteMediaButtonProps) { + return ( + + ) +} diff --git a/components/library-loading.tsx b/components/library-loading.tsx new file mode 100644 index 0000000..a89bcd1 --- /dev/null +++ b/components/library-loading.tsx @@ -0,0 +1,9 @@ +import { Spinner } from "@/components/ui/spinner" + +export function LibraryLoading() { + return ( +
+ +
+ ) +} diff --git a/components/media-context-menu.tsx b/components/media-context-menu.tsx new file mode 100644 index 0000000..f4b5c32 --- /dev/null +++ b/components/media-context-menu.tsx @@ -0,0 +1,116 @@ +"use client" + +import { + ListEnd, + ListPlus, + ListStart, + MoreHorizontal, + Star, +} from "lucide-react" + +import { Button } from "@/components/ui/button" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { cn } from "@/lib/utils" + +export type MediaContextAction = "playlist" | "play-next" | "play-last" | "favorite" + +function actionLabel(base: string, selectedCount: number) { + return selectedCount > 1 ? `${base} (${selectedCount})` : base +} + +export function MediaContextMenuItems({ + selectedCount, + onAction, +}: { + selectedCount: number + onAction: (action: MediaContextAction) => void +}) { + return ( + <> + onAction("playlist")} + > + {actionLabel("Add to Playlist", selectedCount)} + + + + onAction("play-next")} + > + {actionLabel("Play Next", selectedCount)} + + + onAction("play-last")} + > + {actionLabel("Play Last", selectedCount)} + + + + onAction("favorite")} + > + {actionLabel("Favorite", selectedCount)} + + + + ) +} + +export function MediaContextMenu({ + label, + selectedCount, + onOpenMenu, + onAction, + triggerClassName, + triggerVariant = "ghost", + triggerIconClassName = "size-4", + align = "end", +}: { + label: string + selectedCount: number + onOpenMenu: () => void + onAction: (action: MediaContextAction) => void + triggerClassName?: string + triggerVariant?: "ghost" | "secondary" + triggerIconClassName?: string + align?: "start" | "end" +}) { + return ( + { + if (open) { + onOpenMenu() + } + }} + > + + + + + + + + ) +} diff --git a/components/playlist-card.tsx b/components/playlist-card.tsx new file mode 100644 index 0000000..091a9e4 --- /dev/null +++ b/components/playlist-card.tsx @@ -0,0 +1,79 @@ +"use client" + +import Image from "next/image" +import Link from "next/link" + +import type { Playlist } from "@/lib/data" +import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls" +import { Button } from "@/components/ui/button" +import { ListEnd, ListPlus, ListStart, MoreHorizontal, Play, Star } from "lucide-react" +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" + +export function PlaylistCard({ playlist }: { playlist: Playlist }) { + return ( +
+
+ + {playlist.title} + + +
+ +
+ + + + + + + + + Add to Playlist + + + + + Play Next + + + + Play Last + + + + +
+
+ +
+ +

{playlist.title}

+ +

+ {playlist.owner} +

+
+
+ ) +} diff --git a/components/search-song-item.tsx b/components/search-song-item.tsx new file mode 100644 index 0000000..6080b42 --- /dev/null +++ b/components/search-song-item.tsx @@ -0,0 +1,68 @@ +"use client" + +import Image from "next/image" +import Link from "next/link" +import { toast } from "sonner" + +import { + MediaContextMenu, + type MediaContextAction, +} from "@/components/media-context-menu" +import type { Song } from "@/lib/data" +import { albumCoverUrl } from "@/lib/cover-urls" + +export function SearchSongItem({ song }: { song: Song }) { + function handleAction(action: MediaContextAction) { + switch (action) { + case "playlist": + toast.success("Added to playlist") + break + case "play-next": + toast.success("Playing next") + break + case "play-last": + toast.success("Added to queue") + break + case "favorite": + toast.success("Added to favorites") + break + } + } + + return ( +
+ + {song.album.title} + + +
+ +

{song.title}

+ + +

{song.artist.name}

+ +
+ + {}} + onAction={handleAction} + 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 new file mode 100644 index 0000000..53d3d33 --- /dev/null +++ b/components/search-top-result-card.tsx @@ -0,0 +1,98 @@ +"use client" + +import Image from "next/image" +import Link from "next/link" + +import type { Album, Artist, Song } from "@/lib/data" +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 } + +function resultHref(result: TopResult) { + switch (result.kind) { + case "song": + return `/album/${result.item.album.id}` + case "album": + return `/album/${result.item.id}` + case "artist": + return `/artist/${result.item.id}` + } +} + +function resultImage(result: TopResult) { + switch (result.kind) { + case "song": + return { + src: albumCoverUrl(result.item.album.id), + alt: result.item.album.title, + rounded: false, + } + case "album": + return { + src: albumCoverUrl(result.item.id), + alt: result.item.title, + rounded: false, + } + case "artist": + return { + src: artistCoverUrl(result.item.id), + alt: result.item.name, + rounded: true, + } + } +} + +function resultTitle(result: TopResult) { + switch (result.kind) { + case "song": + return result.item.title + case "album": + return result.item.title + case "artist": + return result.item.name + } +} + +function resultSubtitle(result: TopResult) { + switch (result.kind) { + case "song": + return `Song • ${result.item.artist.name}` + case "album": + return `Album • ${result.item.artist.name}` + case "artist": + return "Artist" + } +} + +export function SearchTopResultCard({ result }: { result: TopResult }) { + const image = resultImage(result) + + return ( + +
+ {image.alt} +
+
+

{resultTitle(result)}

+

+ {resultSubtitle(result)} +

+

+ From Your Library +

+
+ + ) +} diff --git a/components/songs-view.tsx b/components/songs-view.tsx index d5582cd..4593aa4 100644 --- a/components/songs-view.tsx +++ b/components/songs-view.tsx @@ -2,27 +2,25 @@ import * as React from "react" import Image from "next/image" -import { - ArrowUpDown, - ListEnd, - ListPlus, - ListStart, - MoreHorizontal, - Play, - Star, -} from "lucide-react" +import Link from "next/link" +import { ArrowUpDown, Play, Star } from "lucide-react" +import { toast } from "sonner" +import { + MediaContextMenu, + type MediaContextAction, +} from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, - DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" +import { useTrackSelection } from "@/hooks/use-track-selection" import { ScrollArea } from "@/components/ui/scroll-area" import { Table, @@ -34,12 +32,25 @@ import { } from "@/components/ui/table" import { cn } from "@/lib/utils" import type { Song } from "@/lib/data" +import { albumCoverUrl } from "@/lib/cover-urls" +import { + getSelectionRangePositions, + isInSelectionRange, + ALBUM_TRACK_TITLE, + SongsSelectionRangeHighlight, + SongsTrackRowHoverHighlight, + TRACK_ROW_PADDING, + type SelectionRangePosition, +} from "@/lib/selection-range-styles" type SortKey = "title" | "artist" | "album" type SortDirection = "asc" | "desc" +const songRowLayout = + "flex w-full items-center gap-x-4" const nameColumnLayout = - "grid grid-cols-[2rem_2.5rem_minmax(0,1fr)_2rem] items-center gap-x-2" + "grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2" +const songColumnClass = "w-36 shrink-0 truncate" function formatDuration(seconds: number): string { const minutes = Math.floor(seconds / 60) @@ -47,49 +58,16 @@ function formatDuration(seconds: number): string { return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}` } -function SongContextMenu({ song }: { song: Song }) { +function SongCover({ song, inRange }: { song: Song; inRange: boolean }) { return ( - - - - - - - Add to Playlist - - - - - Play Next - - - - Play Last - - - - - Favorite - - - - - ) -} - -function SongCover({ song }: { song: Song }) { - return ( -
+
{song.album.title} event.stopPropagation()} + onClick={(event) => { + event.preventDefault() + event.stopPropagation() + }} > @@ -111,68 +92,142 @@ function SongCover({ song }: { song: Song }) { function SongRow({ song, index, + isSelected, + selectionPosition, isFavorite, + selectedCount, + onSelect, + onPointerDown, onToggleFavorite, + onPrepareContextMenu, + onMediaAction, }: { song: Song index: number + isSelected: boolean + selectionPosition: SelectionRangePosition isFavorite: boolean + selectedCount: number + onSelect: (event: React.MouseEvent) => void + onPointerDown: (event: React.MouseEvent) => void onToggleFavorite: () => void + onPrepareContextMenu: () => void + onMediaAction: (action: MediaContextAction, songId: string) => void }) { + const inRange = isInSelectionRange(selectionPosition) + const linkClass = inRange + ? "text-primary-foreground hover:text-primary-foreground/80 hover:underline" + : "text-muted-foreground hover:text-foreground hover:underline" + return ( - -
-
- -
- - - {song.title} - {song.explicit ? ( - - E + +
+ + {!inRange ? : null} +
+
+
+ +
+ + + {song.title} + {song.explicit ? ( + + E + + ) : null} - ) : null} - - +
+
+ event.stopPropagation()} + > + {song.artist.name} + +
+
+ event.stopPropagation()} + > + {song.album.title} + +
+
+ + {formatDuration(song.durationSeconds)} + + 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" + )} + /> +
- - {song.artist.name} - - - {song.album.title} - - - {formatDuration(song.durationSeconds)} - ) } @@ -207,6 +262,25 @@ export function SongsView({ songs }: { songs: Song[] }) { return sorted }, [songs, sortKey, sortDirection]) + const { + selectedIds, + selectedCount, + isSelected, + handleSelect, + handlePointerDown, + prepareContextMenu, + clearSelection, + } = useTrackSelection(sortedSongs) + + const selectionPositions = React.useMemo( + () => + getSelectionRangePositions( + sortedSongs.map((song) => song.id), + selectedIds + ), + [sortedSongs, selectedIds] + ) + function toggleFavorite(songId: string) { setFavoriteIds((current) => { const next = new Set(current) @@ -219,6 +293,48 @@ export function SongsView({ songs }: { songs: Song[] }) { }) } + function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) { + const targetIds = + selectedIds.size > 0 + ? Array.from(selectedIds) + : fallbackSongId + ? [fallbackSongId] + : [] + const count = targetIds.length + + 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" + ) + break + case "playlist": + toast.success( + count > 1 + ? `Added ${count} songs to playlist` + : "Added to playlist" + ) + 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 + } + } + return (
@@ -260,30 +376,49 @@ export function SongsView({ songs }: { songs: Song[] }) {
+ {selectedCount > 1 ? ( +

+ {selectedCount} songs selected +

+ ) : null} + -
+
{ + if (event.target === event.currentTarget) { + clearSelection() + } + }} + > - -
- - - Name + +
+
+ + + Name +
+ + Artist - - + + Album + +
+ + Time + +
- - Artist - - - Album - - - Time - @@ -292,8 +427,21 @@ export function SongsView({ songs }: { songs: Song[] }) { key={song.id} song={song} index={index} + isSelected={isSelected(song.id)} + selectionPosition={selectionPositions[index]} isFavorite={favoriteIds.has(song.id)} + selectedCount={ + isSelected(song.id) && selectedCount > 0 + ? selectedCount + : 1 + } + onPointerDown={handlePointerDown} + onSelect={(event) => { + handleSelect(song.id, index, event) + }} onToggleFavorite={() => toggleFavorite(song.id)} + onPrepareContextMenu={() => prepareContextMenu(song.id)} + onMediaAction={handleMediaAction} /> ))} diff --git a/components/ui/sonner.tsx b/components/ui/sonner.tsx index 9280ee5..b4c6ebc 100644 --- a/components/ui/sonner.tsx +++ b/components/ui/sonner.tsx @@ -9,6 +9,7 @@ const Toaster = ({ ...props }: ToasterProps) => { return ( + name: string + photo: string | null +} + +type BrowseAlbum = { + id: Id<"albums"> + title: string + artist: BrowseArtist + cover: string | null +} + +type BrowseSong = { + id: Id<"songs"> + title: string + artist: BrowseArtist + album: Pick + durationSeconds: number +} + +async function loadArtistMap(ctx: QueryCtx) { + const artists = await ctx.db.query("artists").collect() + return new Map(artists.map((artist) => [artist._id, artist])) +} + +function toBrowseArtist(artist: Doc<"artists">): BrowseArtist { + return { + id: artist._id, + name: artist.name, + photo: artist.cover, + } +} + +function toBrowseAlbum( + album: Doc<"albums">, + artist: Doc<"artists"> +): BrowseAlbum { + return { + id: album._id, + title: album.name, + artist: toBrowseArtist(artist), + cover: album.cover, + } +} + +function toBrowseSong( + song: Doc<"songs">, + album: Doc<"albums">, + albumArtist: Doc<"artists"> +): BrowseSong { + return { + id: song._id, + title: song.name, + artist: { + id: albumArtist._id, + name: albumArtist.name, + photo: albumArtist.cover, + }, + album: { + id: album._id, + title: album.name, + cover: album.cover, + }, + durationSeconds: Math.round(song.length), + } +} + +export const browseAlbums = query({ + args: {}, + handler: async (ctx) => { + const artistMap = await loadArtistMap(ctx) + const albums = await ctx.db.query("albums").collect() + + return albums + .flatMap((album) => { + const artist = artistMap.get(album.artist) + return artist ? [toBrowseAlbum(album, artist)] : [] + }) + .sort((a, b) => a.title.localeCompare(b.title)) + }, +}) + +export const browseArtists = query({ + args: {}, + handler: async (ctx) => { + const artists = await ctx.db.query("artists").collect() + return artists + .map(toBrowseArtist) + .sort((a, b) => a.name.localeCompare(b.name)) + }, +}) + +export const browseSongs = query({ + args: {}, + handler: async (ctx) => { + const artistMap = await loadArtistMap(ctx) + const albums = await ctx.db.query("albums").collect() + const albumMap = new Map(albums.map((album) => [album._id, album])) + const songs = await ctx.db.query("songs").collect() + + return songs + .flatMap((song) => { + const album = albumMap.get(song.album) + const albumArtist = artistMap.get(song.albumArtist) + if (!album || !albumArtist) { + return [] + } + return [toBrowseSong(song, album, albumArtist)] + }) + .sort((a, b) => a.title.localeCompare(b.title)) + }, +}) + +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 => { + const album = await ctx.db.get("albums", args.id) + if (!album) { + return null + } + + const artist = await ctx.db.get("artists", album.artist) + if (!artist) { + return null + } + + const songs = await ctx.db + .query("songs") + .withIndex("by_album", (q) => q.eq("album", args.id)) + .collect() + + songs.sort((a, b) => { + if (a.track !== b.track) { + return a.track - b.track + } + return a.name.localeCompare(b.name) + }) + + const primarySong = songs[0] + + return { + ...toBrowseAlbum(album, artist), + year: primarySong?.year ?? null, + genre: primarySong?.genres[0] ?? null, + tracks: songs.map((song) => ({ + id: song._id, + title: song.name, + track: song.track, + durationSeconds: Math.round(song.length), + })), + } + }, +}) + +export const browseArtistDetail = query({ + args: { id: v.id("artists") }, + handler: async (ctx, args) => { + const artist = await ctx.db.get("artists", args.id) + if (!artist) { + return null + } + + const albums = await ctx.db + .query("albums") + .withIndex("by_artist", (q) => q.eq("artist", args.id)) + .collect() + + const recentlyAdded = [...albums] + .sort((a, b) => b._creationTime - a._creationTime) + .map((album) => toBrowseAlbum(album, artist)) + + const recentlyPlayed = [...albums] + .sort((a, b) => a.name.localeCompare(b.name)) + .map((album) => toBrowseAlbum(album, artist)) + + return { + artist: toBrowseArtist(artist), + albums: recentlyPlayed, + recentlyAdded, + recentlyPlayed, + } + }, +}) + +function matchScore(text: string, query: string): number { + const lower = text.toLowerCase() + if (lower === query) { + return 100 + } + if (lower.startsWith(query)) { + return 80 + } + if (lower.split(/\s+/).some((word) => word.startsWith(query))) { + return 60 + } + if (lower.includes(query)) { + return 40 + } + 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[], + } + } + + const artistMap = await loadArtistMap(ctx) + const albums = await ctx.db.query("albums").collect() + const albumMap = new Map(albums.map((album) => [album._id, album])) + const songs = await ctx.db.query("songs").collect() + + const artistResults: SearchTopResult[] = [...artistMap.values()] + .map((artist) => ({ + kind: "artist" as const, + item: toBrowseArtist(artist), + score: matchScore(artist.name, queryText), + })) + .filter((result) => result.score > 0) + .sort((a, b) => b.score - a.score || a.item.name.localeCompare(b.item.name)) + + const albumResults: SearchTopResult[] = albums + .flatMap((album) => { + const artist = artistMap.get(album.artist) + if (!artist) { + return [] + } + const score = Math.max( + matchScore(album.name, queryText), + matchScore(artist.name, queryText) + ) + if (score === 0) { + return [] + } + return [ + { + kind: "album" as const, + item: toBrowseAlbum(album, artist), + score, + }, + ] + }) + .sort( + (a, b) => + b.score - a.score || a.item.title.localeCompare(b.item.title) + ) + + const songResults: SearchTopResult[] = songs + .flatMap((song) => { + const album = albumMap.get(song.album) + const albumArtist = artistMap.get(song.albumArtist) + if (!album || !albumArtist) { + return [] + } + const score = Math.max( + matchScore(song.name, queryText), + matchScore(song.artist, queryText), + matchScore(album.name, queryText), + matchScore(albumArtist.name, queryText) + ) + if (score === 0) { + return [] + } + return [ + { + kind: "song" as const, + item: toBrowseSong(song, album, albumArtist), + score, + }, + ] + }) + .sort( + (a, b) => + b.score - a.score || a.item.title.localeCompare(b.item.title) + ) + + const topResults = [...songResults, ...albumResults, ...artistResults] + .sort((a, b) => b.score - a.score) + .slice(0, 6) + .map(({ kind, item }) => ({ kind, item })) + + return { + topResults, + artists: artistResults.map((result) => result.item), + albums: albumResults.map((result) => result.item), + songs: songResults.map((result) => result.item), + } + }, +}) + +export const browseRecentlyAdded = query({ + args: {}, + handler: async (ctx) => { + const artistMap = await loadArtistMap(ctx) + const albums = await ctx.db.query("albums").collect() + + return albums + .flatMap((album) => { + const artist = artistMap.get(album.artist) + return artist ? [{ album, artist, addedAt: album._creationTime }] : [] + }) + .sort((a, b) => b.addedAt - a.addedAt) + .map(({ album, artist }) => toBrowseAlbum(album, artist)) + }, +}) export const getArtists = query({ args: {}, diff --git a/hooks/use-track-selection.ts b/hooks/use-track-selection.ts new file mode 100644 index 0000000..32dcafc --- /dev/null +++ b/hooks/use-track-selection.ts @@ -0,0 +1,83 @@ +"use client" + +import * as React from "react" + +type Selectable = { id: string } + +export function useTrackSelection(items: T[]) { + const [selectedIds, setSelectedIds] = React.useState>( + () => new Set() + ) + const anchorIndexRef = React.useRef(null) + + const isSelected = React.useCallback( + (id: string) => selectedIds.has(id), + [selectedIds] + ) + + const handlePointerDown = React.useCallback((event: React.MouseEvent) => { + if (event.shiftKey) { + event.preventDefault() + } + }, []) + + const handleSelect = React.useCallback( + (id: string, index: number, event: React.MouseEvent) => { + if (event.shiftKey || event.metaKey || event.ctrlKey) { + event.preventDefault() + window.getSelection()?.removeAllRanges() + } + + if (event.metaKey || event.ctrlKey) { + setSelectedIds((current) => { + const next = new Set(current) + if (next.has(id)) { + next.delete(id) + } else { + next.add(id) + } + return next + }) + anchorIndexRef.current = index + return + } + + if (event.shiftKey && anchorIndexRef.current !== null) { + const start = Math.min(anchorIndexRef.current, index) + const end = Math.max(anchorIndexRef.current, index) + setSelectedIds( + new Set(items.slice(start, end + 1).map((item) => item.id)) + ) + return + } + + setSelectedIds(new Set([id])) + anchorIndexRef.current = index + }, + [items] + ) + + const prepareContextMenu = React.useCallback((id: string) => { + setSelectedIds((current) => { + if (current.has(id)) { + return current + } + return new Set([id]) + }) + }, []) + + const clearSelection = React.useCallback(() => { + setSelectedIds(new Set()) + anchorIndexRef.current = null + }, []) + + return { + selectedIds, + selectedCount: selectedIds.size, + isSelected, + handleSelect, + handlePointerDown, + prepareContextMenu, + clearSelection, + } +} diff --git a/lib/album-grid-classes.ts b/lib/album-grid-classes.ts new file mode 100644 index 0000000..a306661 --- /dev/null +++ b/lib/album-grid-classes.ts @@ -0,0 +1,9 @@ +/** Shared layout for album grids and carousel slides (gap-x-6 = 1.5rem). */ +export const albumGridClassName = + "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" + +/** Slide width matches one cell of `albumGridClassName` inside an `@container` ancestor. */ +export const albumGridCarouselSlideClassName = + "w-[calc((100cqw-1.5rem)/2)] shrink-0 grow-0 basis-auto pl-6 sm:w-[calc((100cqw-3rem)/3)] md:w-[calc((100cqw-4.5rem)/4)] lg:w-[calc((100cqw-6rem)/5)] xl:w-[calc((100cqw-7.5rem)/6)]" + +export const albumGridCarouselContentClassName = "-ml-6" diff --git a/lib/convex-server.ts b/lib/convex-server.ts new file mode 100644 index 0000000..dd78f09 --- /dev/null +++ b/lib/convex-server.ts @@ -0,0 +1,10 @@ +import { ConvexHttpClient } from "convex/browser" + +let client: ConvexHttpClient | null = null + +export function getConvexClient() { + if (!client) { + client = new ConvexHttpClient(process.env.NEXT_PUBLIC_CONVEX_URL!) + } + return client +} diff --git a/lib/cover-urls.ts b/lib/cover-urls.ts new file mode 100644 index 0000000..6961c70 --- /dev/null +++ b/lib/cover-urls.ts @@ -0,0 +1,11 @@ +export function artistCoverUrl(artistId: string) { + return `/api/artist/${artistId}/cover` +} + +export function albumCoverUrl(albumId: string) { + return `/api/album/${albumId}/cover` +} + +export function playlistCoverUrl(playlistId: string) { + return `/api/playlist/${playlistId}/cover` +} diff --git a/lib/data.ts b/lib/data.ts index d9a6c93..e12f7d1 100644 --- a/lib/data.ts +++ b/lib/data.ts @@ -20,149 +20,22 @@ export type Song = { explicit?: boolean } -export const albums: Album[] = [ - { id: "live-from-the-hollywood-bowl", title: "Live from the Hollywood Bowl", artist: { id: "ajr", name: "AJR", photo: null }, cover: null }, - { id: "ends-of-the-earth", title: "Ends of the Earth", artist: { id: "the-longest-johns", name: "The Longest Johns", photo: null }, cover: null }, - { id: "the-parting-glass-single", title: "The Parting Glass - Single", artist: { id: "the-ramparts", name: "The Ramparts", photo: null }, cover: null }, - { id: "fairytale-of-new-york-single", title: "Fairytale of New York - Single", artist: { id: "the-ramparts", name: "The Ramparts", photo: null }, cover: null }, - { id: "the-rocky-road-to-dublin-single", title: "The Rocky Road to Dublin - Single", artist: { id: "the-ramparts", name: "The Ramparts", photo: null }, cover: null }, - { id: "1778-ep", title: "1778 - EP", artist: { id: "the-wellermen", name: "The Wellermen", photo: null }, cover: null }, - { id: "the-high-kings", title: "The High Kings", artist: { id: "the-high-kings", name: "The High Kings", photo: null }, cover: null }, - { id: "the-fall-off", title: "The Fall-Off", artist: { id: "j-cole", name: "J. Cole", photo: null }, cover: null }, - { id: "enchanted-isle", title: "Enchanted Isle", artist: { id: "voces8", name: "VOCES8", photo: null }, cover: null }, - { id: "unknown-album", title: "Unknown Album", artist: { id: "unknown-artist", name: "Unknown Artist", photo: null }, cover: null }, - { id: "song-of-durin-complete-edition", title: "Song of Durin (Complete Edition)", artist: { id: "clamavi-de-profundis", name: "Clamavi De Profundis", photo: null }, cover: null }, - { id: "sid-meiers-civilization-v-soundtrack", title: "Sid Meier's Civilization V (Soundtrack)", artist: { id: "geoff-knorr-michael-curran", name: "Geoff Knorr & Michael Curran", photo: null }, cover: null }, - { id: "the-last-goodbye-single", title: "The Last Goodbye - Single", artist: { id: "seth-staton-watkins", name: "Seth Staton Watkins", photo: null }, cover: null }, - { id: "do-you-hear-the-people-sing-single", title: "Do You Hear the People Sing? - Single", artist: { id: "seth-staton-watkins-aaron-dolan", name: "Seth Staton Watkins & Aaron Dolan", photo: null }, cover: null }, - { id: "fiddlers-green-single", title: "Fiddler's Green - Single", artist: { id: "seth-staton-watkins", name: "Seth Staton Watkins", photo: null }, cover: null }, - { id: "the-orange-and-the-green-single", title: "The Orange and the Green - Single", artist: { id: "seth-staton-watkins", name: "Seth Staton Watkins", photo: null }, cover: null }, - { id: "horse-soldier-horse-soldier-single", title: "Horse Soldier, Horse Soldier - Single", artist: { id: "seth-staton-watkins", name: "Seth Staton Watkins", photo: null }, cover: null }, - { id: "my-mother-told-me-feat-3lake-single", title: "My Mother Told Me (feat. 3lake) - Single", artist: { id: "seth-staton-watkins", name: "Seth Staton Watkins", photo: null }, cover: null }, -] +export type Playlist = { + id: string + title: string + owner: string + cover: string | null +} -export const recentlyPlayed: Album[] = albums.slice(0, 9) +export type AlbumTrack = { + id: string + title: string + track: number + durationSeconds: number +} -export const recentlyAdded: Album[] = albums.slice(10) - -export const artists: Artist[] = Array.from( - new Map(albums.map((album) => [album.artist.id, album.artist])).values() -) - -export const songs: Song[] = [ - { - id: "aaron-burr-sir", - title: "Aaron Burr, Sir", - artist: { id: "lin-manuel-miranda", name: "Lin-Manuel Miranda, Original Broadway Cast of Hamilton, Leslie Odom, Jr. & Original Broadway Cast of Hamilton", photo: null }, - album: { id: "hamilton-obcr", title: "Hamilton (Original Broadway Cast Recording)", cover: null }, - durationSeconds: 156, - }, - { - id: "actually-romantic", - title: "Actually Romantic", - artist: { id: "taylor-swift", name: "Taylor Swift", photo: null }, - album: { id: "the-life-of-a-showgirl", title: "The Life of a Showgirl", cover: null }, - durationSeconds: 163, - explicit: true, - }, - { - id: "adagio-in-g-major", - title: "Adagio in G Major", - artist: { id: "voces8-paul-van-nevel", name: "VOCES8, Paul Van Nevel & L'Arpeggiata", photo: null }, - album: { id: "enchanted-isle", title: "Enchanted Isle", cover: null }, - durationSeconds: 219, - }, - { - id: "after-all", - title: "After All", - artist: { id: "ed-sheeran", name: "Ed Sheeran", photo: null }, - album: { id: "play", title: "Play", cover: null }, - durationSeconds: 210, - }, - { - id: "afire-love", - title: "Afire Love", - artist: { id: "ed-sheeran", name: "Ed Sheeran", photo: null }, - album: { id: "x", title: "x", cover: null }, - durationSeconds: 314, - }, - { - id: "again-lil-tecca", - title: "Again", - artist: { id: "lil-tecca", name: "Lil Tecca", photo: null }, - album: { id: "we-love-you-tecca-2-deluxe", title: "We Love You Tecca 2 (Deluxe)", cover: null }, - durationSeconds: 170, - }, - { - id: "again-fetty-wap", - title: "Again (feat. XXXTENTACION)", - artist: { id: "fetty-wap", name: "Fetty Wap", photo: null }, - album: { id: "again-feat-xxxtentacion", title: "Again (feat. XXXTENTACION) - Single", cover: null }, - durationSeconds: 302, - }, - { - id: "a-hard-days-night", - title: "A Hard Day's Night", - artist: { id: "the-beatles", name: "The Beatles", photo: null }, - album: { id: "a-hard-days-night", title: "A Hard Day's Night", cover: null }, - durationSeconds: 149, - }, - { - id: "aint-no-sunshine", - title: "Ain't No Sunshine", - artist: { id: "bill-withers", name: "Bill Withers", photo: null }, - album: { id: "just-as-i-am", title: "Just As I Am", cover: null }, - durationSeconds: 124, - }, - { - id: "airplanes-pt-ii", - title: "Airplanes, Pt. II (feat. Hayley Williams of Paramore)", - artist: { id: "b-o-b", name: "Hayley Williams, B.o.B & Eminem", photo: null }, - album: { id: "bob-presents-adventures", title: "B.o.B Presents: The Adventures of Bobby Ray", cover: null }, - durationSeconds: 319, - explicit: true, - }, - { - id: "aja", - title: "Aja", - artist: { id: "ajr", name: "AJR", photo: null }, - album: { id: "live-from-the-hollywood-bowl", title: "Live from the Hollywood Bowl", cover: null }, - durationSeconds: 172, - }, - { - id: "all-you-need-is-love", - title: "All You Need Is Love", - artist: { id: "the-beatles", name: "The Beatles", photo: null }, - album: { id: "beatles-1", title: "1", cover: null }, - durationSeconds: 228, - }, - { - id: "ends-of-the-earth", - title: "Ends of the Earth", - artist: { id: "the-longest-johns", name: "The Longest Johns", photo: null }, - album: { id: "ends-of-the-earth", title: "Ends of the Earth", cover: null }, - durationSeconds: 245, - }, - { - id: "the-parting-glass", - title: "The Parting Glass", - artist: { id: "the-ramparts", name: "The Ramparts", photo: null }, - album: { id: "the-parting-glass-single", title: "The Parting Glass - Single", cover: null }, - durationSeconds: 198, - }, - { - id: "song-of-durin", - title: "Song of Durin", - artist: { id: "clamavi-de-profundis", name: "Clamavi De Profundis", photo: null }, - album: { id: "song-of-durin-complete-edition", title: "Song of Durin (Complete Edition)", cover: null }, - durationSeconds: 412, - }, - { - id: "babysitter", - title: "Babysitter (feat. Ari Lennox)", - artist: { id: "j-cole", name: "J. Cole", photo: null }, - album: { id: "the-fall-off", title: "The Fall-Off", cover: null }, - durationSeconds: 267, - explicit: true, - }, -] +export type AlbumDetail = Album & { + year: number | null + genre: string | null + tracks: AlbumTrack[] +} diff --git a/lib/playlists.ts b/lib/playlists.ts new file mode 100644 index 0000000..9cd10de --- /dev/null +++ b/lib/playlists.ts @@ -0,0 +1,29 @@ +import type { Playlist } from "@/lib/data" + +export const placeholderPlaylists: Playlist[] = [ + { + id: "favorite-songs", + title: "Favorite Songs", + owner: "Joshua Higgins", + cover: null, + }, + { + 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/lib/selection-range-styles.tsx b/lib/selection-range-styles.tsx new file mode 100644 index 0000000..4ea8189 --- /dev/null +++ b/lib/selection-range-styles.tsx @@ -0,0 +1,158 @@ +import { cn } from "@/lib/utils" + +export type SelectionRangePosition = "none" | "only" | "start" | "middle" | "end" + +export function getSelectionRangePositions( + itemIds: string[], + selectedIds: Set +): SelectionRangePosition[] { + const positions: SelectionRangePosition[] = itemIds.map((id) => + selectedIds.has(id) ? "only" : "none" + ) + + let index = 0 + while (index < itemIds.length) { + if (!selectedIds.has(itemIds[index])) { + index++ + continue + } + + const start = index + while (index < itemIds.length && selectedIds.has(itemIds[index])) { + index++ + } + + const end = index - 1 + const count = end - start + 1 + + for (let position = start; position <= end; position++) { + if (count === 1) { + positions[position] = "only" + } else if (position === start) { + positions[position] = "start" + } else if (position === end) { + positions[position] = "end" + } else { + positions[position] = "middle" + } + } + } + + return positions +} + +export function selectionHighlightRadiusClass( + position: SelectionRangePosition +) { + switch (position) { + case "only": + return "rounded-lg" + case "start": + return "rounded-t-lg" + case "end": + return "rounded-b-lg" + default: + return "" + } +} + +export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2" + +export function SelectionRangeHighlight({ + position, +}: { + position: SelectionRangePosition +}) { + if (position === "none") { + return null + } + + return ( +
+ ) +} + +/** Inset rounded hover background matching the selection pill shape. */ +export function TrackRowHoverHighlight() { + return ( +
+ ) +} + +/** Inset rounded background for the active (now playing) row. */ +export function TrackRowActiveHighlight() { + return ( +
+ ) +} + +/** Shared horizontal padding for track rows — same when selected or not. */ +export const TRACK_ROW_PADDING = "pl-8 pr-10" + +/** Centers the track list in the main content area. */ +export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-3xl" + +/** Full-width highlight for library song rows (no horizontal inset). */ +export const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0" + +export function SongsSelectionRangeHighlight({ + position, +}: { + position: SelectionRangePosition +}) { + if (position === "none") { + return null + } + + return ( +
+ ) +} + +/** Full-width hover background for library song rows (not rounded). */ +export function SongsTrackRowHoverHighlight() { + return ( +
+ ) +} + +/** Album track row: leading columns + spacer + duration & menu on the right. */ +export const ALBUM_TRACK_ROW = + "flex w-full items-center gap-x-3" + +export const ALBUM_TRACK_TITLE = "max-w-40 min-w-0 truncate font-normal" + +export function isInSelectionRange(position: SelectionRangePosition) { + return position !== "none" +} diff --git a/lib/serve-cover.ts b/lib/serve-cover.ts new file mode 100644 index 0000000..ae03994 --- /dev/null +++ b/lib/serve-cover.ts @@ -0,0 +1,41 @@ +import fs from "node:fs/promises" +import path from "node:path" + +export const PLACEHOLDER_PATH = path.join(process.cwd(), "public/placeholder-album.svg") + +const MIME_TYPES: Record = { + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".webp": "image/webp", + ".gif": "image/gif", + ".svg": "image/svg+xml", +} + +function contentTypeFor(filePath: string) { + return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream" +} + +export async function serveCoverFile(coverPath: string | null | undefined) { + if (coverPath) { + try { + const data = await fs.readFile(coverPath) + return new Response(data, { + headers: { + "Content-Type": contentTypeFor(coverPath), + "Cache-Control": "public, max-age=86400, immutable", + }, + }) + } catch { + // Fall through to placeholder when the file is missing on disk. + } + } + + const placeholder = await fs.readFile(PLACEHOLDER_PATH) + return new Response(placeholder, { + headers: { + "Content-Type": "image/svg+xml", + "Cache-Control": "public, max-age=86400", + }, + }) +} diff --git a/next.config.ts b/next.config.ts index f62ca42..f737c95 100644 --- a/next.config.ts +++ b/next.config.ts @@ -2,4 +2,12 @@ import type { NextConfig } from "next" const nextConfig: NextConfig = {} +module.exports = { + images: { + dangerouslyAllowSVG: true, + contentDispositionType: "attachment", + contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", + }, +} + export default nextConfig