feat: queue management

This commit is contained in:
joshuafhiggins committed 2026-06-04 20:08:28 -04:00 Verified
1 parent 364cae8a59
commit 5704b937fe
28 files changed
+1699 -203

No files matched your search

+15 -8
View File
@@ -1,8 +1,10 @@
import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider"
import { FavoritesProvider } from "@/components/favorites-provider"
import { PlaybackProvider } from "@/components/playback-provider"
import { PlayerBar } from "@/components/player-bar"
import { QueuePanel } from "@/components/queue-panel"
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
import { PlayerBar } from "@/components/player-bar"
export default function AppLayout({
children,
@@ -11,13 +13,18 @@ export default function AppLayout({
}>) {
return (
<SidebarProvider>
<AddToPlaylistProvider>
<FavoritesProvider>
<AppSidebar />
<SidebarInset>{children}</SidebarInset>
<PlayerBar />
</FavoritesProvider>
</AddToPlaylistProvider>
<PlaybackProvider>
<AddToPlaylistProvider>
<FavoritesProvider>
<AppSidebar />
<div className="flex min-h-svh min-w-0 flex-1">
<SidebarInset className="min-w-0 flex-1">{children}</SidebarInset>
<QueuePanel />
</div>
<PlayerBar />
</FavoritesProvider>
</AddToPlaylistProvider>
</PlaybackProvider>
</SidebarProvider>
)
}
+43 -56
View File
@@ -2,19 +2,18 @@
import Image from "next/image"
import Link from "next/link"
import {
ListEnd,
ListPlus,
ListStart,
MoreHorizontal,
Play,
Star,
User,
} from "lucide-react"
import { toast } from "sonner"
import { MoreHorizontal, Play } from "lucide-react"
import { useConvex } from "convex/react"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
import {
MediaContextMenuItems,
type MediaContextAction,
} from "@/components/media-context-menu"
import { usePlayback } from "@/components/playback-provider"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { api } from "@/convex/_generated/api"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
@@ -28,8 +27,31 @@ import type { Id } from "@/convex/_generated/dataModel"
import { albumCoverUrl } from "@/lib/cover-urls"
export function AlbumCard({ album }: { album: BrowseAlbum }) {
const convex = useConvex()
const { openAddAlbumToPlaylist } = useAddToPlaylist()
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
const { playAlbum } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
async function handleCardAction(action: MediaContextAction) {
switch (action) {
case "playlist":
void openAddAlbumToPlaylist(album.id as Id<"albums">)
break
case "favorite":
void toggleAlbumFavorite(album.id as Id<"albums">)
break
case "play-next":
case "play-last":
case "shuffle": {
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
albumId: album.id as Id<"albums">,
})
void runQueueAction(action, songIds)
break
}
}
}
return (
<div className="flex flex-col gap-2">
@@ -49,12 +71,15 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
<div className="pointer-events-none absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/40" />
<div className="absolute inset-x-0 bottom-0 z-10 flex items-center justify-between p-2 opacity-0 transition-opacity group-hover:opacity-100">
<div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 flex items-center justify-between p-2 opacity-0 transition-opacity group-hover:opacity-100 [&_button]:pointer-events-auto">
<Button
size="icon-sm"
className="rounded-full"
aria-label={`Play ${album.title}`}
onClick={(event) => event.preventDefault()}
onClick={(event) => {
event.preventDefault()
void playAlbum(album.id as Id<"albums">)
}}
>
<Play className="fill-current" />
</Button>
@@ -72,50 +97,12 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
className="justify-between"
onClick={(event) => {
event.preventDefault()
void openAddAlbumToPlaylist(album.id as Id<"albums">)
}}
>
Add to Playlist
<ListPlus />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="justify-between"
onClick={(event) => event.preventDefault()}
>
Play Next
<ListStart />
</DropdownMenuItem>
<DropdownMenuItem
className="justify-between"
onClick={(event) => event.preventDefault()}
>
Play Last
<ListEnd />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem asChild className="justify-between">
<Link href={`/artist/${album.artist.id}`}>
Go to Artist
<User />
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
variant={isAlbumFavorite(album.id) ? "destructive" : "default"}
className="justify-between"
onClick={(event) => {
event.preventDefault()
void toggleAlbumFavorite(album.id as Id<"albums">)
}}
>
{isAlbumFavorite(album.id) ? "Unfavorite" : "Favorite"}
<Star />
</DropdownMenuItem>
<MediaContextMenuItems
selectedCount={1}
onAction={(action) => void handleCardAction(action)}
favorited={isAlbumFavorite(album.id)}
navigation={{ artist: { id: album.artist.id } }}
/>
</DropdownMenuContent>
</DropdownMenu>
</div>
+39 -32
View File
@@ -5,9 +5,12 @@ import Image from "next/image"
import Link from "next/link"
import { Play, Share2, Shuffle, Star } from "lucide-react"
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { useFavorites } from "@/components/favorites-provider"
import { usePlayback } from "@/components/playback-provider"
import { toast } from "sonner"
import {
@@ -16,6 +19,7 @@ import {
} from "@/components/media-context-menu"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { cn } from "@/lib/utils"
import type { Id } from "@/convex/_generated/dataModel"
@@ -74,6 +78,8 @@ function TrackRow({
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
isNowPlaying,
onPlay,
}: {
track: BrowseAlbumTrack
index: number
@@ -88,6 +94,8 @@ function TrackRow({
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, trackId: string) => void
isNowPlaying: boolean
onPlay: () => void
}) {
const displayTrack = track.track > 0 ? track.track : index + 1
const inRange = isInSelectionRange(selectionPosition)
@@ -98,6 +106,10 @@ function TrackRow({
tabIndex={0}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
@@ -145,23 +157,14 @@ function TrackRow({
</Button>
</div>
<div
className={cn(
"flex w-8 shrink-0 items-center justify-center tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{isActive ? (
<Play
className={cn(
"size-4 fill-current",
inRange ? "text-primary-foreground" : "text-primary"
)}
/>
) : (
<span>{displayTrack}</span>
)}
</div>
<TrackNumberPlayButton
displayTrack={displayTrack}
title={track.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={onPlay}
/>
<span className={ALBUM_TRACK_TITLE}>{track.title}</span>
@@ -199,6 +202,13 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
toggleAlbumFavorite,
favoriteSongs,
} = useFavorites()
const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
usePlayback()
const { runQueueAction } = useQueueMediaActions()
const albumSongIds = React.useMemo(
() => album.tracks.map((track) => track.id as Id<"songs">),
[album.tracks]
)
const metadata = formatMetadata(album.genre, album.year)
const [activeTrackId, setActiveTrackId] = React.useState(
() => album.tracks[0]?.id ?? ""
@@ -231,8 +241,6 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
: activeTrackId
? [activeTrackId]
: []
const count = targetIds.length
switch (action) {
case "favorite":
void favoriteSongs(targetIds as Id<"songs">[])
@@ -241,34 +249,27 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
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"
)
case "shuffle":
void runQueueAction(action, targetIds as Id<"songs">[])
break
}
}
function handleAlbumMediaAction(action: MediaContextAction) {
const targetIds = album.tracks.map((track) => track.id)
const count = targetIds.length
const targetIds = album.tracks.map((track) => track.id as Id<"songs">)
switch (action) {
case "favorite":
void toggleAlbumFavorite(album.id as Id<"albums">)
break
case "playlist":
openAddToPlaylist(targetIds as Id<"songs">[])
openAddToPlaylist(targetIds)
break
case "play-next":
toast.success(`Queued ${count} songs to play next`)
break
case "play-last":
toast.success(`Queued ${count} songs to play last`)
case "shuffle":
void runQueueAction(action, targetIds)
break
}
}
@@ -335,12 +336,14 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
size="icon"
className="rounded-full"
aria-label="Shuffle album"
onClick={() => void playAlbumShuffled(album.id as Id<"albums">)}
>
<Shuffle />
</Button>
<Button
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
aria-label={`Play ${album.title}`}
onClick={() => void playAlbum(album.id as Id<"albums">)}
>
<Play className="fill-current" />
Play
@@ -383,6 +386,10 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
}
onPrepareContextMenu={() => prepareContextMenu(track.id)}
onMediaAction={handleMediaAction}
isNowPlaying={currentSong?.id === track.id}
onPlay={() =>
void playFromSong(track.id as Id<"songs">, albumSongIds)
}
/>
))
) : (
+19 -5
View File
@@ -3,10 +3,12 @@
import * as React from "react"
import Image from "next/image"
import { Play, Shuffle } from "lucide-react"
import { toast } from "sonner"
import { useConvex } from "convex/react"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
import { usePlayback } from "@/components/playback-provider"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { AlbumCard } from "@/components/album-card"
import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { ContentCarousel } from "@/components/content-carousel"
@@ -16,6 +18,7 @@ import {
} from "@/components/media-context-menu"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@/convex/library"
import {
@@ -38,8 +41,11 @@ export function ArtistView({
}) {
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { openAddArtistToPlaylist } = useAddToPlaylist()
const { playArtist, playArtistShuffled } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
const convex = useConvex()
function handleMediaAction(action: MediaContextAction) {
async function handleMediaAction(action: MediaContextAction) {
switch (action) {
case "favorite":
void toggleArtistFavorite(artist.id as Id<"artists">)
@@ -48,11 +54,15 @@ export function ArtistView({
void openAddArtistToPlaylist(artist.id as Id<"artists">)
break
case "play-next":
toast.success("Play next")
break
case "play-last":
toast.success("Play last")
case "shuffle": {
const songIds = await convex.query(
api.playlists.getOrderedArtistSongIds,
{ artistId: artist.id as Id<"artists"> }
)
void runQueueAction(action, songIds)
break
}
}
}
@@ -82,6 +92,7 @@ export function ArtistView({
size="icon"
className="size-11 rounded-full"
aria-label={`Play ${artist.name}`}
onClick={() => void playArtist(artist.id as Id<"artists">)}
>
<Play className="size-5 fill-current" />
</Button>
@@ -90,6 +101,9 @@ export function ArtistView({
size="icon"
className="size-11 rounded-full"
aria-label={`Shuffle ${artist.name}`}
onClick={() =>
void playArtistShuffled(artist.id as Id<"artists">)
}
>
<Shuffle className="size-4" />
</Button>
+13 -1
View File
@@ -8,6 +8,7 @@ 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 { usePlayback } from "@/components/playback-provider"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { cn } from "@/lib/utils"
@@ -68,6 +69,7 @@ export function ArtistsView({
() => sortedArtists[0]?.id ?? ""
)
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { playArtist, playArtistShuffled } = usePlayback()
const selectedArtist = sortedArtists.find(
(artist) => artist.id === selectedId
@@ -102,7 +104,14 @@ export function ArtistsView({
</Link>
<div className="flex shrink-0 items-center gap-2">
<Button size="icon" className="rounded-full" aria-label="Play">
<Button
size="icon"
className="rounded-full"
aria-label="Play"
onClick={() =>
void playArtist(selectedArtist.id as Id<"artists">)
}
>
<Play className="fill-current" />
</Button>
<Button
@@ -110,6 +119,9 @@ export function ArtistsView({
size="icon"
className="rounded-full"
aria-label="Shuffle"
onClick={() =>
void playArtistShuffled(selectedArtist.id as Id<"artists">)
}
>
<Shuffle />
</Button>
+14 -1
View File
@@ -8,6 +8,7 @@ import {
ListPlus,
ListStart,
MoreHorizontal,
Shuffle,
Star,
User,
} from "lucide-react"
@@ -22,7 +23,12 @@ import {
} from "@/components/ui/dropdown-menu"
import { cn } from "@/lib/utils"
export type MediaContextAction = "playlist" | "play-next" | "play-last" | "favorite"
export type MediaContextAction =
| "playlist"
| "play-next"
| "play-last"
| "shuffle"
| "favorite"
export type MediaContextNavigation = {
artist?: { id: string }
@@ -74,6 +80,13 @@ export function MediaContextMenuItems({
{actionLabel("Play Last", selectedCount)}
<ListEnd />
</DropdownMenuItem>
<DropdownMenuItem
className="justify-between"
onClick={() => onAction("shuffle")}
>
{actionLabel("Shuffle", selectedCount)}
<Shuffle />
</DropdownMenuItem>
{artist || album ? (
<>
<DropdownMenuSeparator />
+275
View File
@@ -0,0 +1,275 @@
"use client"
import * as React from "react"
import { useConvex, useMutation, useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import type { BrowseSong } from "@/convex/library"
type RepeatMode = "none" | "once" | "always"
type PlaybackContextValue = {
queue: BrowseSong[]
currentSong: BrowseSong | null
shuffleEnabled: boolean
repeatEnabled: RepeatMode
queueOpen: boolean
isPlaying: boolean
volume: number
setQueueOpen: (open: boolean) => void
toggleQueueOpen: () => void
setIsPlaying: (playing: boolean) => void
setVolume: (volume: number) => void
playInOrder: (songIds: Id<"songs">[]) => Promise<void>
playShuffled: (songIds: Id<"songs">[]) => Promise<void>
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
playAlbum: (albumId: Id<"albums">) => Promise<void>
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
playArtist: (artistId: Id<"artists">) => Promise<void>
playArtistShuffled: (artistId: Id<"artists">) => Promise<void>
playPlaylist: (playlistId: Id<"playlists">) => Promise<void>
playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise<void>
toggleShuffle: () => Promise<void>
cycleRepeat: () => Promise<void>
clearQueue: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void>
skipNext: () => Promise<void>
skipPrevious: () => Promise<void>
}
const PlaybackContext = React.createContext<PlaybackContextValue | null>(null)
export function usePlayback() {
const context = React.useContext(PlaybackContext)
if (!context) {
throw new Error("usePlayback must be used within PlaybackProvider")
}
return context
}
export function PlaybackProvider({ children }: { children: React.ReactNode }) {
const convex = useConvex()
const playback = useQuery(api.playback.getPlaybackState)
const playInOrderMutation = useMutation(api.playback.playInOrder)
const playShuffledMutation = useMutation(api.playback.playShuffled)
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
const playFromSongMutation = useMutation(api.playback.playFromSong)
const toggleShuffleMutation = useMutation(api.playback.toggleShuffle)
const cycleRepeatMutation = useMutation(api.playback.cycleRepeat)
const clearQueueMutation = useMutation(api.playback.clearQueue)
const reorderQueueMutation = useMutation(api.playback.reorderQueue)
const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex)
const skipNextMutation = useMutation(api.playback.skipNext)
const skipPreviousMutation = useMutation(api.playback.skipPrevious)
const [queueOpen, setQueueOpen] = React.useState(false)
const [isPlaying, setIsPlaying] = React.useState(false)
const [volume, setVolume] = React.useState(80)
React.useEffect(() => {
if (playback?.currentSong) {
setIsPlaying(true)
} else {
setIsPlaying(false)
}
}, [playback?.currentSong?.id])
const playInOrder = React.useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) {
return
}
await playInOrderMutation({ songIds })
setIsPlaying(true)
},
[playInOrderMutation]
)
const playShuffled = React.useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) {
return
}
await playShuffledMutation({ songIds })
setIsPlaying(true)
},
[playShuffledMutation]
)
const addToQueueNext = React.useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) {
return
}
await addToQueueNextMutation({ songIds })
setIsPlaying(true)
},
[addToQueueNextMutation]
)
const addToQueueLast = React.useCallback(
async (songIds: Id<"songs">[]) => {
if (songIds.length === 0) {
return
}
await addToQueueLastMutation({ songIds })
setIsPlaying(true)
},
[addToQueueLastMutation]
)
const playFromSong = React.useCallback(
async (songId: Id<"songs">, songIds: Id<"songs">[]) => {
await playFromSongMutation({ songId, songIds })
setIsPlaying(true)
},
[playFromSongMutation]
)
const playAlbum = React.useCallback(
async (albumId: Id<"albums">) => {
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
albumId,
})
await playInOrder(songIds)
},
[convex, playInOrder]
)
const playAlbumShuffled = React.useCallback(
async (albumId: Id<"albums">) => {
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
albumId,
})
await playShuffled(songIds)
},
[convex, playShuffled]
)
const playArtist = React.useCallback(
async (artistId: Id<"artists">) => {
const songIds = await convex.query(api.playlists.getOrderedArtistSongIds, {
artistId,
})
await playInOrder(songIds)
},
[convex, playInOrder]
)
const playArtistShuffled = React.useCallback(
async (artistId: Id<"artists">) => {
const songIds = await convex.query(api.playlists.getOrderedArtistSongIds, {
artistId,
})
await playShuffled(songIds)
},
[convex, playShuffled]
)
const playPlaylist = React.useCallback(
async (playlistId: Id<"playlists">) => {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
playlistId,
})
await playInOrder(songIds)
},
[convex, playInOrder]
)
const playPlaylistShuffled = React.useCallback(
async (playlistId: Id<"playlists">) => {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
playlistId,
})
await playShuffled(songIds)
},
[convex, playShuffled]
)
const toggleQueueOpen = React.useCallback(() => {
setQueueOpen((open) => !open)
}, [])
const value = React.useMemo<PlaybackContextValue>(
() => ({
queue: playback?.queue ?? [],
currentSong: playback?.currentSong ?? null,
shuffleEnabled: playback?.shuffleEnabled ?? false,
repeatEnabled: playback?.repeatEnabled ?? "none",
queueOpen,
isPlaying,
volume,
setQueueOpen,
toggleQueueOpen,
setIsPlaying,
setVolume,
playInOrder,
playShuffled,
addToQueueNext,
addToQueueLast,
playFromSong,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playPlaylist,
playPlaylistShuffled,
toggleShuffle: async () => {
await toggleShuffleMutation()
},
cycleRepeat: async () => {
await cycleRepeatMutation()
},
clearQueue: async () => {
await clearQueueMutation()
setIsPlaying(false)
},
reorderQueue: async (songIds) => {
await reorderQueueMutation({ songIds })
},
skipToQueueIndex: async (index) => {
await skipToQueueIndexMutation({ index })
},
skipNext: async () => {
await skipNextMutation()
},
skipPrevious: async () => {
await skipPreviousMutation()
},
}),
[
playback,
queueOpen,
isPlaying,
volume,
toggleQueueOpen,
playInOrder,
playShuffled,
addToQueueNext,
addToQueueLast,
playFromSong,
playAlbum,
playAlbumShuffled,
playArtist,
playArtistShuffled,
playPlaylist,
playPlaylistShuffled,
toggleShuffleMutation,
cycleRepeatMutation,
clearQueueMutation,
reorderQueueMutation,
skipToQueueIndexMutation,
skipNextMutation,
skipPreviousMutation,
]
)
return (
<PlaybackContext.Provider value={value}>{children}</PlaybackContext.Provider>
)
}
+67
View File
@@ -0,0 +1,67 @@
import Link from "next/link"
import type { BrowseSong } from "@/convex/library"
import { cn } from "@/lib/utils"
export function PlaybackSongMeta({
song,
isCurrent = false,
inRange = false,
align = "center",
showAlbum = true,
}: {
song: BrowseSong
isCurrent?: boolean
inRange?: boolean
align?: "center" | "start"
showAlbum?: boolean
}) {
return (
<div
className={cn(
"min-w-0",
align === "center" ? "max-w-48 text-center sm:max-w-64" : "flex-1"
)}
>
<Link
href={`/album/${song.album.id}`}
className={cn(
"block truncate text-sm font-medium hover:underline",
inRange && "text-primary-foreground hover:text-primary-foreground/80",
isCurrent && !inRange && "text-primary"
)}
>
{song.title}
</Link>
<p
className={cn(
"truncate text-xs",
inRange ? "text-primary-foreground/80" : "text-muted-foreground"
)}
>
<Link
href={`/artist/${song.artist.id}`}
className={cn(
"hover:underline",
inRange
? "text-primary-foreground/80 hover:text-primary-foreground"
: "hover:text-foreground"
)}
>
{song.artist.name}
</Link>
{showAlbum ? (
<>
<span aria-hidden="true"> — </span>
<Link
href={`/album/${song.album.id}`}
className="hover:text-foreground hover:underline"
>
{song.album.title}
</Link>
</>
) : null}
</p>
</div>
)
}
+132 -22
View File
@@ -1,58 +1,168 @@
"use client"
import Image from "next/image"
import {
ListMusic,
Music,
Pause,
Play,
Repeat,
Repeat1,
Shuffle,
SkipBack,
SkipForward,
Volume2,
} from "lucide-react"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider"
import { Button } from "@/components/ui/button"
import { Slider } from "@/components/ui/slider"
import { useSidebar } from "@/components/ui/sidebar"
import { albumCoverUrl } from "@/lib/cover-urls"
import { cn } from "@/lib/utils"
export function PlayerBar() {
const {
currentSong,
shuffleEnabled,
repeatEnabled,
queueOpen,
isPlaying,
volume,
queue,
setIsPlaying,
setVolume,
toggleQueueOpen,
toggleShuffle,
cycleRepeat,
skipNext,
skipPrevious,
} = usePlayback()
const { state, isMobile } = useSidebar()
const hasQueue = queue.length > 0
const sidebarExpanded = !isMobile && state === "expanded"
return (
<div className="pointer-events-none fixed bottom-0 left-0 right-0 z-10 flex justify-center px-4 pb-4 md:left-[var(--sidebar-width)] md:peer-data-[state=collapsed]:left-0">
<div className="pointer-events-auto flex w-full max-w-3xl items-center gap-3 rounded-xl border bg-card/80 px-3 py-2 shadow-lg backdrop-blur">
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" aria-label="Shuffle">
<div
className={cn(
"pointer-events-none fixed bottom-4 z-50 flex justify-center px-4 transition-[left,right] duration-200 ease-linear",
sidebarExpanded ? "left-[16rem] right-0" : "inset-x-0",
queueOpen && !isMobile && "right-72"
)}
>
<div className="pointer-events-auto grid w-full max-w-3xl grid-cols-[1fr_auto_1fr] items-center gap-2 rounded-xl border bg-card/80 px-3 py-2 shadow-lg backdrop-blur">
<div className="flex items-center justify-start gap-1">
<Button
variant="ghost"
size="icon"
aria-label="Shuffle"
aria-pressed={shuffleEnabled}
className={cn(shuffleEnabled && "text-primary")}
onClick={() => void toggleShuffle()}
>
<Shuffle />
</Button>
<Button variant="ghost" size="icon" aria-label="Previous">
<Button
variant="ghost"
size="icon"
aria-label="Previous"
disabled={!hasQueue}
onClick={() => void skipPrevious()}
>
<SkipBack />
</Button>
<Button variant="ghost" size="icon" aria-label="Play">
<Pause />
<Button
variant="ghost"
size="icon"
aria-label={isPlaying ? "Pause" : "Play"}
disabled={!hasQueue}
onClick={() => setIsPlaying(!isPlaying)}
>
{isPlaying ? <Pause /> : <Play className="fill-current" />}
</Button>
<Button variant="ghost" size="icon" aria-label="Next">
<Button
variant="ghost"
size="icon"
aria-label="Next"
disabled={!hasQueue}
onClick={() => void skipNext()}
>
<SkipForward />
</Button>
<Button variant="ghost" size="icon" aria-label="Repeat">
<Repeat />
<Button
variant="ghost"
size="icon"
aria-label="Repeat"
aria-pressed={repeatEnabled !== "none"}
className={cn(repeatEnabled !== "none" && "text-primary")}
onClick={() => void cycleRepeat()}
>
{repeatEnabled === "once" ? <Repeat1 /> : <Repeat />}
</Button>
</div>
<div className="flex min-w-0 flex-1 items-center justify-center gap-3 rounded-lg bg-muted/60 px-3 py-1.5">
<div className="size-8 shrink-0 rounded bg-gradient-to-br from-emerald-500 to-teal-800" />
<div className="min-w-0 text-center">
<p className="truncate text-sm font-medium">Ends of the Earth</p>
<p className="truncate text-xs text-muted-foreground">
The Longest Johns — Ends of the Earth
</p>
</div>
<div className="flex h-10 min-w-0 items-center justify-center gap-3 px-2">
{currentSong ? (
<>
<div className="relative size-8 shrink-0 overflow-hidden rounded">
<Image
src={albumCoverUrl(currentSong.album.id)}
alt={currentSong.album.title}
fill
sizes="32px"
className="object-cover"
/>
</div>
<div className="flex h-10 min-w-0 max-w-48 flex-col justify-center overflow-hidden sm:max-w-64">
<PlaybackSongMeta song={currentSong} />
</div>
</>
) : (
<div className="flex size-8 shrink-0 items-center justify-center">
<Image
src="/logo-monochrome.svg"
alt="oTunes"
width={14}
height={24}
className="h-6 w-auto opacity-85"
/>
</div>
)}
</div>
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" aria-label="Lyrics">
<div className="flex items-center justify-end gap-1">
<Button variant="ghost" size="icon" aria-label="Lyrics" disabled>
<Music />
</Button>
<Button variant="ghost" size="icon" aria-label="Queue">
<Button
variant="ghost"
size="icon"
aria-label="Queue"
aria-pressed={queueOpen}
className={cn(queueOpen && "text-primary")}
onClick={toggleQueueOpen}
>
<ListMusic />
</Button>
<Button variant="ghost" size="icon" aria-label="Volume">
<div className="hidden items-center gap-2 sm:flex">
<Volume2 className="size-4 shrink-0 text-muted-foreground" />
<Slider
className="w-20"
min={0}
max={100}
value={[volume]}
onValueChange={([value]) => setVolume(value)}
aria-label="Volume"
/>
</div>
<Button
variant="ghost"
size="icon"
aria-label="Volume"
className="sm:hidden"
>
<Volume2 />
</Button>
</div>
+47 -29
View File
@@ -6,13 +6,48 @@ import Link from "next/link"
import type { PlaylistSummary } from "@/convex/library"
import type { Id } from "@/convex/_generated/dataModel"
import { playlistCoverUrl } from "@/lib/cover-urls"
import { useConvex } from "convex/react"
import { MoreHorizontal, Play } from "lucide-react"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import {
MediaContextMenuItems,
type MediaContextAction,
} from "@/components/media-context-menu"
import { usePlayback } from "@/components/playback-provider"
import { Button } from "@/components/ui/button"
import { ListEnd, ListPlus, ListStart, MoreHorizontal, Play } from "lucide-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { api } from "@/convex/_generated/api"
export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
const convex = useConvex()
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
const { playPlaylist } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
async function handleCardAction(action: MediaContextAction) {
switch (action) {
case "playlist":
void openAddPlaylistToPlaylist(playlist.id as Id<"playlists">)
break
case "play-next":
case "play-last":
case "shuffle": {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
playlistId: playlist.id as Id<"playlists">,
})
void runQueueAction(action, songIds)
break
}
case "favorite":
break
}
}
return (
<div className="flex flex-col gap-2">
@@ -29,12 +64,15 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
<div className="pointer-events-none absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/40" />
<div className="absolute inset-x-0 bottom-0 z-10 flex items-center justify-between p-2 opacity-0 transition-opacity group-hover:opacity-100">
<div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 flex items-center justify-between p-2 opacity-0 transition-opacity group-hover:opacity-100 [&_button]:pointer-events-auto">
<Button
size="icon-sm"
className="rounded-full"
aria-label={`Play ${playlist.title}`}
onClick={(event) => event.preventDefault()}
onClick={(event) => {
event.preventDefault()
void playPlaylist(playlist.id as Id<"playlists">)
}}
>
<Play className="fill-current" />
</Button>
@@ -52,31 +90,11 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
className="justify-between"
onClick={(event) => {
event.preventDefault()
void openAddPlaylistToPlaylist(playlist.id as Id<"playlists">)
}}
>
Add to Playlist
<ListPlus />
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="justify-between"
onClick={(event) => event.preventDefault()}
>
Play Next
<ListStart />
</DropdownMenuItem>
<DropdownMenuItem
className="justify-between"
onClick={(event) => event.preventDefault()}
>
Play Last
<ListEnd />
</DropdownMenuItem>
<MediaContextMenuItems
selectedCount={1}
showFavorite={false}
onAction={(action) => void handleCardAction(action)}
/>
</DropdownMenuContent>
</DropdownMenu>
</div>
+45 -31
View File
@@ -16,6 +16,8 @@ import { toast } from "sonner"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
import { usePlayback } from "@/components/playback-provider"
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import {
MediaContextMenu,
MediaContextMenuItems,
@@ -30,6 +32,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
@@ -152,6 +155,8 @@ function PlaylistSongRow({
onDrop,
showFavoriteInMenu = true,
removeLabel = "Remove from Playlist",
isNowPlaying,
onPlay,
}: {
song: BrowseSong
index: number
@@ -174,6 +179,8 @@ function PlaylistSongRow({
onDrop: (event: React.DragEvent) => void
showFavoriteInMenu?: boolean
removeLabel?: string
isNowPlaying: boolean
onPlay: () => void
}) {
const displayTrack = index + 1
const inRange = isInSelectionRange(selectionPosition)
@@ -188,6 +195,10 @@ function PlaylistSongRow({
onDrop={onDrop}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
@@ -213,23 +224,14 @@ function PlaylistSongRow({
onToggleFavorite={onToggleFavorite}
/>
<div
className={cn(
"flex w-8 shrink-0 items-center justify-center tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{isActive ? (
<Play
className={cn(
"size-4 fill-current",
inRange ? "text-primary-foreground" : "text-primary"
)}
/>
) : (
<span>{displayTrack}</span>
)}
</div>
<TrackNumberPlayButton
displayTrack={displayTrack}
title={song.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={onPlay}
/>
<span className={ALBUM_TRACK_TITLE}>{song.title}</span>
@@ -285,6 +287,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
toggleSongsFavorite,
favoriteSongs: addFavoriteSongs,
} = useFavorites()
const {
currentSong,
playInOrder,
playShuffled,
playFromSong,
} = usePlayback()
const { runQueueAction } = useQueueMediaActions()
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
@@ -292,6 +301,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist)
const [songs, setSongs] = React.useState(playlist.songs)
const playlistSongIds = React.useMemo(
() => songs.map((song) => song.id as Id<"songs">),
[songs]
)
const [activeTrackId, setActiveTrackId] = React.useState(
() => playlist.songs[0]?.id ?? ""
)
@@ -338,7 +351,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
fallbackSongId?: string
) {
const targetIds = resolveTargetIds(fallbackSongId)
const count = targetIds.length
switch (action) {
case "favorite":
@@ -348,33 +360,27 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
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"
)
case "shuffle":
void runQueueAction(action, targetIds as Id<"songs">[])
break
}
}
function handlePlaylistMediaAction(action: MediaContextAction) {
const targetIds = songs.map((song) => song.id)
const targetIds = songs.map((song) => song.id as Id<"songs">)
switch (action) {
case "favorite":
void addFavoriteSongs(targetIds as Id<"songs">[])
void addFavoriteSongs(targetIds)
break
case "playlist":
openAddToPlaylist(targetIds as Id<"songs">[])
openAddToPlaylist(targetIds)
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`)
case "shuffle":
void runQueueAction(action, targetIds)
break
}
}
@@ -556,12 +562,16 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
size="icon"
className="rounded-full"
aria-label="Shuffle playlist"
onClick={() => void playShuffled(playlistSongIds)}
disabled={playlistSongIds.length === 0}
>
<Shuffle />
</Button>
<Button
className="h-10 gap-2 rounded-full bg-foreground px-6 text-background hover:bg-foreground/90"
aria-label={`Play ${playlist.title}`}
onClick={() => void playInOrder(playlistSongIds)}
disabled={playlistSongIds.length === 0}
>
<Play className="fill-current" />
Play
@@ -634,6 +644,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
event.preventDefault()
handleDrop(index)
}}
isNowPlaying={currentSong?.id === song.id}
onPlay={() =>
void playFromSong(song.id as Id<"songs">, playlistSongIds)
}
/>
))
) : (
+293
View File
@@ -0,0 +1,293 @@
"use client"
import * as React from "react"
import Image from "next/image"
import { useMutation } from "convex/react"
import { Music2 } from "lucide-react"
import { toast } from "sonner"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider"
import { Button } from "@/components/ui/button"
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 { BrowseSong } from "@/convex/library"
import { albumCoverUrl } from "@/lib/cover-urls"
import {
getContiguousSelectedIndices,
moveQueueBlock,
} from "@/lib/move-queue-block"
import {
getSelectionRangePositions,
isInSelectionRange,
QueueSelectionRangeHighlight,
QueueTrackRowActiveHighlight,
QueueTrackRowHoverHighlight,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { cn } from "@/lib/utils"
type QueueSelectable = BrowseSong & { selectionId: string }
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function toSelectableQueue(queue: BrowseSong[]): QueueSelectable[] {
return queue.map((song, index) => ({
...song,
selectionId: `${song.id}-${index}`,
}))
}
function QueueSongCover({
albumId,
title,
inRange,
}: {
albumId: string
title: string
inRange: boolean
}) {
return (
<div
className={cn(
"relative size-10 shrink-0 overflow-hidden ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(albumId)}
alt={title}
fill
sizes="40px"
className="object-cover"
/>
</div>
)
}
function QueueSongRow({
song,
isNowPlaying,
selectionPosition,
isDragging,
onSelect,
onPointerDown,
onSkipTo,
onDragStart,
onDragOver,
onDrop,
}: {
song: QueueSelectable
isNowPlaying: boolean
selectionPosition: SelectionRangePosition
isDragging: boolean
onSelect: (event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onSkipTo: () => void
onDragStart: (event: React.DragEvent) => void
onDragOver: (event: React.DragEvent) => void
onDrop: (event: React.DragEvent) => void
}) {
const inRange = isInSelectionRange(selectionPosition)
return (
<li
role="button"
tabIndex={0}
draggable
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onSkipTo()
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onSelect(event as unknown as React.MouseEvent)
}
}}
className={cn(
"group relative w-full cursor-pointer select-none py-2 text-left text-sm transition-colors",
inRange && "text-primary-foreground",
isDragging && "opacity-50"
)}
>
<QueueSelectionRangeHighlight position={selectionPosition} />
{!inRange && isNowPlaying ? <QueueTrackRowActiveHighlight /> : null}
{!inRange && !isNowPlaying ? <QueueTrackRowHoverHighlight /> : null}
<div className="relative z-10 flex items-center gap-3 px-2">
{song.album.id ? (
<QueueSongCover
albumId={song.album.id}
title={song.album.title}
inRange={inRange}
/>
) : (
<div
className={cn(
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Music2 className="size-4 text-muted-foreground" />
</div>
)}
<PlaybackSongMeta
song={song}
isCurrent={isNowPlaying}
inRange={inRange}
align="start"
showAlbum={false}
/>
<span
className={cn(
"shrink-0 text-xs tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
</div>
</li>
)
}
export function QueuePanel() {
const { queue, queueOpen, clearQueue, skipToQueueIndex } = usePlayback()
const reorderQueue = useMutation(api.playback.reorderQueue)
const selectableQueue = React.useMemo(() => toSelectableQueue(queue), [queue])
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
const {
selectedIds,
handleSelect,
handlePointerDown,
} = useTrackSelection(
selectableQueue.map((item) => ({ id: item.selectionId }))
)
const selectionPositions = React.useMemo(
() =>
getSelectionRangePositions(
selectableQueue.map((item) => item.selectionId),
selectedIds
),
[selectableQueue, selectedIds]
)
const draggingIndices = React.useMemo(() => {
if (dragIndex === null) {
return new Set<number>()
}
return new Set(
getContiguousSelectedIndices(selectableQueue, selectedIds, dragIndex)
)
}, [dragIndex, selectableQueue, selectedIds])
async function persistOrder(nextQueue: BrowseSong[]) {
try {
await reorderQueue({
songIds: nextQueue.map((song) => song.id as Id<"songs">),
})
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to reorder queue"
)
}
}
function handleDrop(targetIndex: number) {
if (dragIndex === null) {
return
}
const fromIndices = getContiguousSelectedIndices(
selectableQueue,
selectedIds,
dragIndex
)
const next = moveQueueBlock(queue, fromIndices, targetIndex)
setDragIndex(null)
if (next === queue) {
return
}
void persistOrder(next)
}
if (!queueOpen) {
return null
}
return (
<aside
className={cn(
"flex h-svh w-72 shrink-0 flex-col border-l bg-background",
"max-md:fixed max-md:inset-y-0 max-md:right-0 max-md:z-20 max-md:shadow-xl"
)}
>
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
<h1 className="text-lg font-semibold">Up Next</h1>
<Button
variant="ghost"
size="sm"
className="text-primary hover:text-primary"
onClick={() => void clearQueue()}
disabled={queue.length === 0}
>
Clear
</Button>
</header>
<ScrollArea className="min-h-0 flex-1">
{queue.length === 0 ? (
<p className="px-4 py-8 text-sm text-muted-foreground">
Nothing in the queue.
</p>
) : (
<ul className="flex flex-col py-1">
{selectableQueue.map((song, index) => (
<QueueSongRow
key={song.selectionId}
song={song}
isNowPlaying={index === 0}
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
onSelect={(event) => {
handleSelect(song.selectionId, index, event)
}}
onSkipTo={() => void skipToQueueIndex(index)}
onDragStart={(event) => {
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => {
event.preventDefault()
handleDrop(index)
}}
/>
))}
</ul>
)}
</ScrollArea>
</aside>
)
}
+6 -6
View File
@@ -2,10 +2,9 @@
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 { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import {
MediaContextMenu,
type MediaContextAction,
@@ -17,17 +16,18 @@ import { albumCoverUrl } from "@/lib/cover-urls"
export function SearchSongItem({ song }: { song: BrowseSong }) {
const { openAddToPlaylist } = useAddToPlaylist()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { runQueueAction } = useQueueMediaActions()
const songIds = [song.id as Id<"songs">]
function handleAction(action: MediaContextAction) {
switch (action) {
case "playlist":
openAddToPlaylist([song.id as Id<"songs">])
openAddToPlaylist(songIds)
break
case "play-next":
toast.success("Playing next")
break
case "play-last":
toast.success("Added to queue")
case "shuffle":
void runQueueAction(action, songIds)
break
case "favorite":
void toggleSongFavorite(song.id as Id<"songs">)
+31 -11
View File
@@ -8,6 +8,7 @@ import { toast } from "sonner"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
import { usePlayback } from "@/components/playback-provider"
import {
MediaContextMenu,
type MediaContextAction,
@@ -22,6 +23,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { ScrollArea } from "@/components/ui/scroll-area"
import {
@@ -61,7 +63,15 @@ function formatDuration(seconds: number): string {
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function SongCover({ song, inRange }: { song: BrowseSong; inRange: boolean }) {
function SongCover({
song,
inRange,
onPlay,
}: {
song: BrowseSong
inRange: boolean
onPlay: () => void
}) {
return (
<div
className={cn(
@@ -83,6 +93,7 @@ function SongCover({ song, inRange }: { song: BrowseSong; inRange: boolean }) {
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
onPlay()
}}
>
<Play className="size-3 fill-current" />
@@ -104,6 +115,7 @@ function SongRow({
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
onPlay,
}: {
song: BrowseSong
index: number
@@ -116,6 +128,7 @@ function SongRow({
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, songId: string) => void
onPlay: () => void
}) {
const inRange = isInSelectionRange(selectionPosition)
const linkClass = inRange
@@ -126,6 +139,10 @@ function SongRow({
<TableRow
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
className="group cursor-pointer select-none border-none hover:bg-transparent"
>
<TableCell colSpan={4} className="p-0">
@@ -170,7 +187,7 @@ function SongRow({
/>
</Button>
</div>
<SongCover song={song} inRange={inRange} />
<SongCover song={song} inRange={inRange} onPlay={onPlay} />
<span className={ALBUM_TRACK_TITLE}>
{song.title}
{song.explicit ? (
@@ -238,6 +255,8 @@ function SongRow({
export function SongsView({ songs }: { songs: BrowseSong[] }) {
const { openAddToPlaylist } = useAddToPlaylist()
const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
const { playFromSong } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
const [sortKey, setSortKey] = React.useState<SortKey>("title")
const [sortDirection, setSortDirection] =
React.useState<SortDirection>("asc")
@@ -283,6 +302,11 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
[sortedSongs, selectedIds]
)
const sortedSongIds = React.useMemo(
() => sortedSongs.map((song) => song.id as Id<"songs">),
[sortedSongs]
)
function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
const targetIds =
selectedIds.size > 0
@@ -290,8 +314,6 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
: fallbackSongId
? [fallbackSongId]
: []
const count = targetIds.length
switch (action) {
case "favorite":
void favoriteSongs(targetIds as Id<"songs">[])
@@ -300,14 +322,9 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
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"
)
case "shuffle":
void runQueueAction(action, targetIds as Id<"songs">[])
break
}
}
@@ -421,6 +438,9 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
}
onPrepareContextMenu={() => prepareContextMenu(song.id)}
onMediaAction={handleMediaAction}
onPlay={() =>
void playFromSong(song.id as Id<"songs">, sortedSongIds)
}
/>
))}
</TableBody>
+58
View File
@@ -0,0 +1,58 @@
import { Play } from "lucide-react"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
export function TrackNumberPlayButton({
displayTrack,
title,
isActive,
isNowPlaying,
inRange,
onPlay,
}: {
displayTrack: number | string
title: string
isActive: boolean
isNowPlaying: boolean
inRange: boolean
onPlay: () => void
}) {
const showPlay = isActive || isNowPlaying
return (
<div
className={cn(
"relative flex w-8 shrink-0 items-center justify-center",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
<span
className={cn(
"tabular-nums transition-opacity group-hover:opacity-0",
showPlay && "opacity-0"
)}
>
{displayTrack}
</span>
<Button
variant="ghost"
size="icon-sm"
className={cn(
"absolute size-8 opacity-0 transition-opacity group-hover:opacity-100",
showPlay && "opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary"
)}
aria-label={`Play ${title}`}
onClick={(event) => {
event.stopPropagation()
onPlay()
}}
>
<Play className="size-4 fill-current" />
</Button>
</div>
)
}
+2
View File
@@ -14,6 +14,7 @@ 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 playback from "../playback.js";
import type * as playlists from "../playlists.js";
import type * as users from "../users.js";
@@ -30,6 +31,7 @@ declare const fullApi: ApiFromModules<{
favorites: typeof favorites;
http: typeof http;
library: typeof library;
playback: typeof playback;
playlists: typeof playlists;
users: typeof users;
}>;
+20
View File
@@ -126,6 +126,26 @@ function toBrowseAlbum(
}
}
export async function browseSongsFromIds(
ctx: QueryCtx,
songIds: Id<"songs">[]
): Promise<BrowseSong[]> {
const songs: BrowseSong[] = []
for (const songId of songIds) {
const song = await ctx.db.get("songs", songId)
if (!song) {
continue
}
const album = await ctx.db.get("albums", song.album)
const albumArtist = await ctx.db.get("artists", song.albumArtist)
if (!album || !albumArtist) {
continue
}
songs.push(toBrowseSong(song, album, albumArtist))
}
return songs
}
function toBrowseSong(
song: Doc<"songs">,
album: Doc<"albums">,
+318
View File
@@ -0,0 +1,318 @@
import { getAuthUserId } from "@convex-dev/auth/server"
import { ConvexError, v } from "convex/values"
import type { Id } from "./_generated/dataModel"
import type { MutationCtx } from "./_generated/server"
import { mutation, query } from "./_generated/server"
import { browseSongsFromIds } from "./library"
function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
for (let i = next.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[next[i], next[j]] = [next[j], next[i]]
}
return next
}
async function requireAuth(ctx: MutationCtx) {
const userId = await getAuthUserId(ctx)
if (userId === null) {
throw new ConvexError("Not authenticated")
}
return userId
}
function uniqueSongIds(songIds: Id<"songs">[]) {
return [...new Set(songIds)]
}
async function setQueueState(
ctx: MutationCtx,
userId: Id<"users">,
patch: {
songQueue: Id<"songs">[]
shuffleEnabled?: boolean
currentSongProgress?: number
}
) {
await ctx.db.patch(userId, {
songQueue: patch.songQueue,
currentSongProgress: patch.currentSongProgress ?? 0,
...(patch.shuffleEnabled !== undefined
? { shuffleEnabled: patch.shuffleEnabled }
: {}),
})
}
export const getPlaybackState = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx)
if (userId === null) {
return null
}
const user = await ctx.db.get(userId)
if (!user) {
return null
}
const songIds = user.songQueue ?? []
const queue = await browseSongsFromIds(ctx, songIds)
return {
queue,
currentSong: queue[0] ?? null,
shuffleEnabled: user.shuffleEnabled ?? false,
repeatEnabled: user.repeatEnabled ?? ("none" as const),
currentSongProgress: user.currentSongProgress ?? 0,
}
},
})
export const playInOrder = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
const userId = await requireAuth(ctx)
const queue = uniqueSongIds(songIds)
await setQueueState(ctx, userId, {
songQueue: queue,
shuffleEnabled: false,
})
},
})
export const playShuffled = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
const userId = await requireAuth(ctx)
const queue = shuffleArray(uniqueSongIds(songIds))
await setQueueState(ctx, userId, { songQueue: queue })
},
})
function orderSongsForInsert(
songIds: Id<"songs">[],
shuffleEnabled: boolean
): Id<"songs">[] {
return shuffleEnabled ? shuffleArray(songIds) : songIds
}
export const addToQueueNext = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
if (songIds.length === 0) {
return
}
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
const queue = user.songQueue ?? []
if (queue.length === 0) {
await setQueueState(ctx, userId, { songQueue: toAdd })
return
}
const [current, ...rest] = queue
await setQueueState(ctx, userId, {
songQueue: [current, ...toAdd, ...rest],
})
},
})
export const addToQueueLast = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
if (songIds.length === 0) {
return
}
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false)
const queue = user.songQueue ?? []
await setQueueState(ctx, userId, {
songQueue: queue.length === 0 ? toAdd : [...queue, ...toAdd],
})
},
})
export const playFromSong = mutation({
args: {
songId: v.id("songs"),
songIds: v.array(v.id("songs")),
},
handler: async (ctx, { songId, songIds }) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const index = songIds.indexOf(songId)
const rest = index === -1 ? [] : songIds.slice(index + 1)
const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest
await setQueueState(ctx, userId, {
songQueue: [songId, ...queueRest],
})
},
})
export const toggleShuffle = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const shuffleEnabled = !(user.shuffleEnabled ?? false)
const queue = user.songQueue ?? []
if (shuffleEnabled && queue.length > 1) {
const [current, ...upNext] = queue
await ctx.db.patch(userId, {
shuffleEnabled: true,
songQueue: [current, ...shuffleArray(upNext)],
})
return
}
await ctx.db.patch(userId, { shuffleEnabled })
},
})
export const cycleRepeat = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const current = user.repeatEnabled ?? "none"
const next =
current === "none" ? "once" : current === "once" ? "always" : "none"
await ctx.db.patch(userId, { repeatEnabled: next })
},
})
export const clearQueue = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
await ctx.db.patch(userId, {
songQueue: [],
currentSongProgress: 0,
})
},
})
export const reorderQueue = mutation({
args: { songIds: v.array(v.id("songs")) },
handler: async (ctx, { songIds }) => {
const userId = await requireAuth(ctx)
await ctx.db.patch(userId, { songQueue: songIds })
},
})
export const skipToQueueIndex = mutation({
args: { index: v.number() },
handler: async (ctx, { index }) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
if (index < 0 || index >= queue.length) {
return
}
await ctx.db.patch(userId, {
songQueue: [...queue.slice(index), ...queue.slice(0, index)],
currentSongProgress: 0,
})
},
})
export const skipNext = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
if (queue.length === 0) {
return
}
const repeat = user.repeatEnabled ?? "none"
if (repeat === "once") {
await ctx.db.patch(userId, { currentSongProgress: 0 })
return
}
if (queue.length === 1 && repeat === "none") {
await ctx.db.patch(userId, {
songQueue: [],
currentSongProgress: 0,
})
return
}
const [current, ...rest] = queue
const nextQueue =
repeat === "always" ? [...rest, current] : rest
await ctx.db.patch(userId, {
songQueue: nextQueue,
currentSongProgress: 0,
})
},
})
export const skipPrevious = mutation({
args: {},
handler: async (ctx) => {
const userId = await requireAuth(ctx)
const user = await ctx.db.get(userId)
if (!user) {
throw new ConvexError("User not found")
}
const queue = user.songQueue ?? []
if (queue.length <= 1) {
await ctx.db.patch(userId, { currentSongProgress: 0 })
return
}
const last = queue[queue.length - 1]
const nextQueue = [last, ...queue.slice(0, -1)]
await ctx.db.patch(userId, {
songQueue: nextQueue,
currentSongProgress: 0,
})
},
})
+36
View File
@@ -299,6 +299,12 @@ export const getAlbumSongIds = query({
.query("songs")
.withIndex("by_album", (q) => q.eq("album", args.albumId))
.collect()
songs.sort((a, b) => {
if (a.track !== b.track) {
return a.track - b.track
}
return a.name.localeCompare(b.name)
})
return songs.map((song) => song._id)
},
})
@@ -314,6 +320,36 @@ export const getArtistSongIds = query({
},
})
export const getOrderedArtistSongIds = 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()
const albums = await ctx.db
.query("albums")
.withIndex("by_artist", (q) => q.eq("artist", args.artistId))
.collect()
const albumMap = new Map(albums.map((album) => [album._id, album]))
songs.sort((a, b) => {
const albumA = albumMap.get(a.album)?.name ?? ""
const albumB = albumMap.get(b.album)?.name ?? ""
if (albumA !== albumB) {
return albumA.localeCompare(albumB)
}
if (a.track !== b.track) {
return a.track - b.track
}
return a.name.localeCompare(b.name)
})
return songs.map((song) => song._id)
},
})
export const getPlaylistSongIds = query({
args: { playlistId: v.id("playlists") },
handler: async (ctx, args) => {
+4
View File
@@ -22,6 +22,10 @@ export default defineSchema({
favoriteArtists: v.optional(v.array(v.id("artists"))),
favoriteAlbums: v.optional(v.array(v.id("albums"))),
favoriteSongs: v.optional(v.array(v.id("songs"))),
songQueue: v.optional(v.array(v.id("songs"))),
currentSongProgress: v.optional(v.number()),
shuffleEnabled: v.optional(v.boolean()),
repeatEnabled: v.optional(v.union(v.literal("always"), v.literal("once"), v.literal("none"))),
}).index("email", ["email"]),
appSettings: defineTable({
disableAccountCreation: v.boolean(),
+64
View File
@@ -0,0 +1,64 @@
"use client"
import * as React from "react"
import { toast } from "sonner"
import { usePlayback } from "@/components/playback-provider"
import type { MediaContextAction } from "@/components/media-context-menu"
import type { Id } from "@/convex/_generated/dataModel"
export type QueueMediaAction = Extract<
MediaContextAction,
"play-next" | "play-last" | "shuffle"
>
function queueActionMessage(action: QueueMediaAction, count: number) {
switch (action) {
case "play-next":
return count > 1
? `Queued ${count} songs to play next`
: "Queued to play next"
case "play-last":
return count > 1
? `Queued ${count} songs to play last`
: "Queued to play last"
case "shuffle":
return count > 1
? `Playing ${count} songs shuffled`
: "Playing shuffled"
}
}
export function useQueueMediaActions() {
const { addToQueueNext, addToQueueLast, playShuffled } = usePlayback()
const runQueueAction = React.useCallback(
async (action: QueueMediaAction, songIds: Id<"songs">[]) => {
if (songIds.length === 0) {
return
}
try {
switch (action) {
case "play-next":
await addToQueueNext(songIds)
break
case "play-last":
await addToQueueLast(songIds)
break
case "shuffle":
await playShuffled(songIds)
break
}
toast.success(queueActionMessage(action, songIds.length))
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to update queue"
)
}
},
[addToQueueNext, addToQueueLast, playShuffled]
)
return { runQueueAction }
}
+45
View File
@@ -0,0 +1,45 @@
export function getContiguousSelectedIndices(
items: { selectionId: string }[],
selectedIds: Set<string>,
dragIndex: number
): number[] {
const selectedIndices = items
.map((item, index) => (selectedIds.has(item.selectionId) ? index : -1))
.filter((index) => index >= 0)
if (
selectedIndices.length > 1 &&
selectedIndices.includes(dragIndex)
) {
return selectedIndices
}
return [dragIndex]
}
export function moveQueueBlock<T>(
queue: T[],
fromIndices: number[],
targetIndex: number
): T[] {
const sorted = [...fromIndices].sort((a, b) => a - b)
if (sorted.length === 0) {
return queue
}
const block = sorted.map((index) => queue[index])
const remaining = queue.filter((_, index) => !sorted.includes(index))
const minSelected = sorted[0]
const maxSelected = sorted[sorted.length - 1]
if (targetIndex >= minSelected && targetIndex <= maxSelected) {
return queue
}
const removedBefore = sorted.filter((index) => index < targetIndex).length
const insertAt = Math.max(0, Math.min(targetIndex - removedBefore, remaining.length))
const next = [...remaining]
next.splice(insertAt, 0, ...block)
return next
}
+47
View File
@@ -160,3 +160,50 @@ export const ALBUM_TRACK_TITLE = "min-w-0 flex-1 truncate font-normal"
export function isInSelectionRange(position: SelectionRangePosition) {
return position !== "none"
}
/** Full-width, square-corner highlights for the queue sidebar. */
export const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export function QueueSelectionRangeHighlight({
position,
}: {
position: SelectionRangePosition
}) {
if (position === "none") {
return null
}
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-primary",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
export function QueueTrackRowHoverHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
export function QueueTrackRowActiveHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
+8
View File
@@ -0,0 +1,8 @@
export function shuffleArray<T>(items: T[]): T[] {
const next = [...items]
for (let i = next.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[next[i], next[j]] = [next[j], next[i]]
}
return next
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

+47
View File
@@ -0,0 +1,47 @@
{
"fill" : {
"automatic-gradient" : "display-p3:0.90526,0.26335,0.25253,1.00000"
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"value" : "automatic"
},
{
"appearance" : "dark",
"value" : {
"automatic-gradient" : "display-p3:0.90526,0.26335,0.25253,1.00000"
}
}
],
"image-name" : "music.note.png",
"name" : "music.note",
"position" : {
"scale" : 1,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.5
},
"translucency" : {
"enabled" : true,
"value" : 0.5
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--Generator: Apple Native CoreSVG 341-->
<!DOCTYPE svg
PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 305 513.75">
<g>
<rect height="513.75" opacity="0" width="305" x="0" y="0"/>
<path d="M305 125.25L305 31.25C305 18 294.25 9.5 281.5 12L153 40C137 43.5 128.25 52.25 128.25 66.25L128.75 344.25C130 356.5 124.25 364.5 113.25 366.75L73.5 375C23.5 385.5 0 411 0 448.75C0 487 29.5 513.75 71 513.75C107.75 513.75 162.75 486.75 162.75 414L162.75 185.25C162.75 172 165.25 169.25 177 166.75L291.25 141.75C299.75 140 305 133.5 305 125.25Z" fill="white" fill-opacity="0.85"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 779 B

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="209" height="256" viewBox="0 0 814 1000"><path d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>

Before

Width:  |  Height:  |  Size: 678 B