fix: phantom selections, pagination in /libary/songs & queue sidebar
This commit is contained in:
9 files changed
+508
-105
No files matched your search
@@ -1,17 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useQuery } from "convex/react"
|
||||
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { SongsView } from "@/components/songs-view"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
|
||||
export default function Page() {
|
||||
const songs = useQuery(api.library.browseSongs)
|
||||
|
||||
if (songs === undefined) {
|
||||
return <LibraryLoading />
|
||||
}
|
||||
|
||||
return <SongsView songs={songs} />
|
||||
return <SongsView />
|
||||
}
|
||||
@@ -263,9 +263,7 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) {
|
||||
[album.tracks]
|
||||
)
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState(
|
||||
() => album.tracks[0]?.id ?? ""
|
||||
)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState("")
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
|
||||
@@ -13,7 +13,7 @@ import { songPlayUrl } from "@/lib/song-play-url"
|
||||
type RepeatMode = "none" | "once" | "always"
|
||||
|
||||
type PlaybackContextValue = {
|
||||
queue: BrowseSong[]
|
||||
queueSongIds: Id<"songs">[]
|
||||
currentSong: BrowseSong | null
|
||||
shuffleEnabled: boolean
|
||||
repeatEnabled: RepeatMode
|
||||
@@ -32,6 +32,10 @@ type PlaybackContextValue = {
|
||||
addToQueueNext: (songIds: Id<"songs">[]) => Promise<void>
|
||||
addToQueueLast: (songIds: Id<"songs">[]) => Promise<void>
|
||||
playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
|
||||
playFromLibrarySong: (
|
||||
songId: Id<"songs">,
|
||||
sort: { sortKey: "title" | "artist" | "album"; sortDirection: "asc" | "desc" }
|
||||
) => Promise<void>
|
||||
playAlbum: (albumId: Id<"albums">) => Promise<void>
|
||||
playAlbumShuffled: (albumId: Id<"albums">) => Promise<void>
|
||||
playArtist: (artistId: Id<"artists">) => Promise<void>
|
||||
@@ -115,6 +119,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) {
|
||||
const addToQueueNextMutation = useMutation(api.playback.addToQueueNext)
|
||||
const addToQueueLastMutation = useMutation(api.playback.addToQueueLast)
|
||||
const playFromSongMutation = useMutation(api.playback.playFromSong)
|
||||
const playFromLibrarySongMutation = useMutation(api.playback.playFromLibrarySong)
|
||||
const toggleShuffleMutation = useMutation(api.playback.toggleShuffle)
|
||||
const cycleRepeatMutation = useMutation(api.playback.cycleRepeat)
|
||||
const clearQueueMutation = useMutation(api.playback.clearQueue)
|
||||
@@ -446,6 +451,20 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) {
|
||||
[playFromSongMutation]
|
||||
)
|
||||
|
||||
const playFromLibrarySong = React.useCallback(
|
||||
async (
|
||||
songId: Id<"songs">,
|
||||
sort: {
|
||||
sortKey: "title" | "artist" | "album"
|
||||
sortDirection: "asc" | "desc"
|
||||
}
|
||||
) => {
|
||||
await playFromLibrarySongMutation({ songId, ...sort })
|
||||
setIsPlaying(true)
|
||||
},
|
||||
[playFromLibrarySongMutation]
|
||||
)
|
||||
|
||||
const playAlbum = React.useCallback(
|
||||
async (albumId: Id<"albums">) => {
|
||||
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
|
||||
@@ -512,7 +531,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const value = React.useMemo<PlaybackContextValue>(
|
||||
() => ({
|
||||
queue: playback?.queue ?? [],
|
||||
queueSongIds: playback?.queueSongIds ?? [],
|
||||
currentSong: playback?.currentSong ?? null,
|
||||
shuffleEnabled: playback?.shuffleEnabled ?? false,
|
||||
repeatEnabled: playback?.repeatEnabled ?? "none",
|
||||
@@ -531,6 +550,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) {
|
||||
addToQueueNext,
|
||||
addToQueueLast,
|
||||
playFromSong,
|
||||
playFromLibrarySong,
|
||||
playAlbum,
|
||||
playAlbumShuffled,
|
||||
playArtist,
|
||||
@@ -576,6 +596,7 @@ export function PlaybackProvider({ children }: { children: React.ReactNode }) {
|
||||
addToQueueNext,
|
||||
addToQueueLast,
|
||||
playFromSong,
|
||||
playFromLibrarySong,
|
||||
playAlbum,
|
||||
playAlbumShuffled,
|
||||
playArtist,
|
||||
|
||||
@@ -42,7 +42,7 @@ export function PlayerBar() {
|
||||
volume,
|
||||
currentTime,
|
||||
duration,
|
||||
queue,
|
||||
queueSongIds,
|
||||
setIsPlaying,
|
||||
setVolume,
|
||||
seekTo,
|
||||
@@ -56,7 +56,7 @@ export function PlayerBar() {
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
const hasQueue = queue.length > 0
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
const hasActiveSong = Boolean(currentSong)
|
||||
const sidebarExpanded = !isMobile && state === "expanded"
|
||||
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
|
||||
|
||||
@@ -305,21 +305,16 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
() => songs.map((song) => song.id as Id<"songs">),
|
||||
[songs]
|
||||
)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState(
|
||||
() => playlist.songs[0]?.id ?? ""
|
||||
)
|
||||
const [activeTrackId, setActiveTrackId] = React.useState("")
|
||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
|
||||
|
||||
React.useEffect(() => {
|
||||
setSongs(playlist.songs)
|
||||
setIsSubscribed(playlist.isSubscribed)
|
||||
setActiveTrackId((current) => {
|
||||
if (playlist.songs.some((song) => song.id === current)) {
|
||||
return current
|
||||
}
|
||||
return playlist.songs[0]?.id ?? ""
|
||||
})
|
||||
setActiveTrackId((current) =>
|
||||
playlist.songs.some((song) => song.id === current) ? current : ""
|
||||
)
|
||||
}, [playlist])
|
||||
|
||||
const {
|
||||
|
||||
+124
-43
@@ -2,7 +2,7 @@
|
||||
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import { useMutation } from "convex/react"
|
||||
import { useMutation, usePaginatedQuery } from "convex/react"
|
||||
import { Music2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
@@ -10,10 +10,11 @@ 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 { Spinner } from "@/components/ui/spinner"
|
||||
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 type { QueueSong } from "@/convex/playback"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
getContiguousSelectedIndices,
|
||||
@@ -29,7 +30,17 @@ import {
|
||||
} from "@/lib/selection-range-styles"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type QueueSelectable = BrowseSong & { selectionId: string }
|
||||
const QUEUE_PAGINATION_THRESHOLD = 100
|
||||
const QUEUE_PAGE_SIZE = 50
|
||||
|
||||
type QueueSelectable = QueueSong & { selectionId: string }
|
||||
|
||||
function getQueueVersion(queueSongIds: Id<"songs">[]) {
|
||||
if (queueSongIds.length === 0) {
|
||||
return "empty"
|
||||
}
|
||||
return `${queueSongIds.length}:${queueSongIds[0]}:${queueSongIds[queueSongIds.length - 1]}`
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
@@ -37,10 +48,10 @@ function formatDuration(seconds: number): string {
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
function toSelectableQueue(queue: BrowseSong[]): QueueSelectable[] {
|
||||
return queue.map((song, index) => ({
|
||||
function toSelectableQueue(songs: QueueSong[]): QueueSelectable[] {
|
||||
return songs.map((song) => ({
|
||||
...song,
|
||||
selectionId: `${song.id}-${index}`,
|
||||
selectionId: `${song.id}-${song.queueIndex}`,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -165,13 +176,64 @@ function QueueSongRow({
|
||||
}
|
||||
|
||||
export function QueuePanel() {
|
||||
const { queue, queueOpen, clearQueue, skipToQueueIndex } = usePlayback()
|
||||
const { queueSongIds, queueOpen, clearQueue, skipToQueueIndex } =
|
||||
usePlayback()
|
||||
const reorderQueue = useMutation(api.playback.reorderQueue)
|
||||
const loadMoreRef = React.useRef<HTMLDivElement>(null)
|
||||
|
||||
const selectableQueue = React.useMemo(() => toSelectableQueue(queue), [queue])
|
||||
const queueVersion = React.useMemo(
|
||||
() => getQueueVersion(queueSongIds),
|
||||
[queueSongIds]
|
||||
)
|
||||
const shouldPaginate = queueSongIds.length > QUEUE_PAGINATION_THRESHOLD
|
||||
const initialPageSize = shouldPaginate
|
||||
? QUEUE_PAGE_SIZE
|
||||
: queueSongIds.length
|
||||
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.playback.getQueuePaginated,
|
||||
queueOpen && queueSongIds.length > 0
|
||||
? { queueVersion }
|
||||
: "skip",
|
||||
{ initialNumItems: initialPageSize }
|
||||
)
|
||||
|
||||
const queueSongs = results ?? []
|
||||
const selectableQueue = React.useMemo(
|
||||
() => toSelectableQueue(queueSongs),
|
||||
[queueSongs]
|
||||
)
|
||||
|
||||
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!shouldPaginate) {
|
||||
return
|
||||
}
|
||||
|
||||
const sentinel = loadMoreRef.current
|
||||
if (!sentinel) {
|
||||
return
|
||||
}
|
||||
|
||||
const viewport = sentinel.closest('[data-slot="scroll-area-viewport"]')
|
||||
if (!viewport) {
|
||||
return
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0]?.isIntersecting && status === "CanLoadMore") {
|
||||
loadMore(QUEUE_PAGE_SIZE)
|
||||
}
|
||||
},
|
||||
{ root: viewport, rootMargin: "240px" }
|
||||
)
|
||||
|
||||
observer.observe(sentinel)
|
||||
return () => observer.disconnect()
|
||||
}, [shouldPaginate, status, loadMore])
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
handleSelect,
|
||||
@@ -198,11 +260,9 @@ export function QueuePanel() {
|
||||
)
|
||||
}, [dragIndex, selectableQueue, selectedIds])
|
||||
|
||||
async function persistOrder(nextQueue: BrowseSong[]) {
|
||||
async function persistOrder(nextQueue: Id<"songs">[]) {
|
||||
try {
|
||||
await reorderQueue({
|
||||
songIds: nextQueue.map((song) => song.id as Id<"songs">),
|
||||
})
|
||||
await reorderQueue({ songIds: nextQueue })
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to reorder queue"
|
||||
@@ -210,21 +270,25 @@ export function QueuePanel() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleDrop(targetIndex: number) {
|
||||
function handleDrop(targetLocalIndex: number) {
|
||||
if (dragIndex === null) {
|
||||
return
|
||||
}
|
||||
|
||||
const fromIndices = getContiguousSelectedIndices(
|
||||
const fromLocalIndices = getContiguousSelectedIndices(
|
||||
selectableQueue,
|
||||
selectedIds,
|
||||
dragIndex
|
||||
)
|
||||
const next = moveQueueBlock(queue, fromIndices, targetIndex)
|
||||
const fromQueueIndices = fromLocalIndices.map(
|
||||
(index) => selectableQueue[index].queueIndex
|
||||
)
|
||||
const targetQueueIndex = selectableQueue[targetLocalIndex].queueIndex
|
||||
const next = moveQueueBlock(queueSongIds, fromQueueIndices, targetQueueIndex)
|
||||
|
||||
setDragIndex(null)
|
||||
|
||||
if (next === queue) {
|
||||
if (next === queueSongIds) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -249,43 +313,60 @@ export function QueuePanel() {
|
||||
size="sm"
|
||||
className="text-primary hover:text-primary"
|
||||
onClick={() => void clearQueue()}
|
||||
disabled={queue.length === 0}
|
||||
disabled={queueSongIds.length === 0}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
{queue.length === 0 ? (
|
||||
{queueSongIds.length === 0 ? (
|
||||
<p className="px-4 py-8 text-sm text-muted-foreground">
|
||||
Nothing in the queue.
|
||||
</p>
|
||||
) : status === "LoadingFirstPage" ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Spinner className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<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>
|
||||
<>
|
||||
<ul className="flex flex-col py-1">
|
||||
{selectableQueue.map((song, index) => (
|
||||
<QueueSongRow
|
||||
key={song.selectionId}
|
||||
song={song}
|
||||
isNowPlaying={song.queueIndex === 0}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isDragging={draggingIndices.has(index)}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(song.selectionId, index, event)
|
||||
}}
|
||||
onSkipTo={() => void skipToQueueIndex(song.queueIndex)}
|
||||
onDragStart={(event) => {
|
||||
setDragIndex(index)
|
||||
event.dataTransfer.effectAllowed = "move"
|
||||
}}
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
handleDrop(index)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{shouldPaginate ? (
|
||||
<div
|
||||
ref={loadMoreRef}
|
||||
className="flex items-center justify-center py-4"
|
||||
aria-hidden={status !== "LoadingMore"}
|
||||
>
|
||||
{status === "LoadingMore" ? (
|
||||
<Spinner className="size-5 text-muted-foreground" />
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
|
||||
+65
-31
@@ -3,8 +3,8 @@
|
||||
import * as React from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { usePaginatedQuery } from "convex/react"
|
||||
import { ArrowUpDown, Play, Star } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
@@ -25,7 +25,10 @@ import {
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { LibraryLoading } from "@/components/library-loading"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { api } from "@/convex/_generated/api"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -51,6 +54,8 @@ import {
|
||||
type SortKey = "title" | "artist" | "album"
|
||||
type SortDirection = "asc" | "desc"
|
||||
|
||||
const SONGS_PAGE_SIZE = 50
|
||||
|
||||
const songRowLayout =
|
||||
"flex w-full items-center gap-x-4"
|
||||
const nameColumnLayout =
|
||||
@@ -252,36 +257,47 @@ function SongRow({
|
||||
)
|
||||
}
|
||||
|
||||
export function SongsView({ songs }: { songs: BrowseSong[] }) {
|
||||
export function SongsView() {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
|
||||
const { playFromSong } = usePlayback()
|
||||
const { playFromLibrarySong } = usePlayback()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
const [sortKey, setSortKey] = React.useState<SortKey>("title")
|
||||
const [sortDirection, setSortDirection] =
|
||||
React.useState<SortDirection>("asc")
|
||||
const loadMoreRef = React.useRef<HTMLDivElement>(null)
|
||||
|
||||
const sortedSongs = React.useMemo(() => {
|
||||
const sorted = [...songs].sort((a, b) => {
|
||||
let comparison = 0
|
||||
const { results, status, loadMore } = usePaginatedQuery(
|
||||
api.library.browseSongsPaginated,
|
||||
{ sortKey, sortDirection },
|
||||
{ initialNumItems: SONGS_PAGE_SIZE }
|
||||
)
|
||||
|
||||
switch (sortKey) {
|
||||
case "title":
|
||||
comparison = a.title.localeCompare(b.title)
|
||||
break
|
||||
case "artist":
|
||||
comparison = a.artist.name.localeCompare(b.artist.name)
|
||||
break
|
||||
case "album":
|
||||
comparison = a.album.title.localeCompare(b.album.title)
|
||||
break
|
||||
}
|
||||
const songs = results ?? []
|
||||
|
||||
return sortDirection === "asc" ? comparison : -comparison
|
||||
})
|
||||
React.useEffect(() => {
|
||||
const sentinel = loadMoreRef.current
|
||||
if (!sentinel) {
|
||||
return
|
||||
}
|
||||
|
||||
return sorted
|
||||
}, [songs, sortKey, sortDirection])
|
||||
const viewport = sentinel.closest('[data-slot="scroll-area-viewport"]')
|
||||
if (!viewport) {
|
||||
return
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0]?.isIntersecting && status === "CanLoadMore") {
|
||||
loadMore(SONGS_PAGE_SIZE)
|
||||
}
|
||||
},
|
||||
{ root: viewport, rootMargin: "240px" }
|
||||
)
|
||||
|
||||
observer.observe(sentinel)
|
||||
return () => observer.disconnect()
|
||||
}, [status, loadMore])
|
||||
|
||||
const {
|
||||
selectedIds,
|
||||
@@ -291,20 +307,15 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
|
||||
handlePointerDown,
|
||||
prepareContextMenu,
|
||||
clearSelection,
|
||||
} = useTrackSelection(sortedSongs)
|
||||
} = useTrackSelection(songs)
|
||||
|
||||
const selectionPositions = React.useMemo(
|
||||
() =>
|
||||
getSelectionRangePositions(
|
||||
sortedSongs.map((song) => song.id),
|
||||
songs.map((song) => song.id),
|
||||
selectedIds
|
||||
),
|
||||
[sortedSongs, selectedIds]
|
||||
)
|
||||
|
||||
const sortedSongIds = React.useMemo(
|
||||
() => sortedSongs.map((song) => song.id as Id<"songs">),
|
||||
[sortedSongs]
|
||||
[songs, selectedIds]
|
||||
)
|
||||
|
||||
function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
|
||||
@@ -329,6 +340,17 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
|
||||
}
|
||||
}
|
||||
|
||||
if (status === "LoadingFirstPage") {
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
|
||||
<h1 className="text-lg font-semibold">Songs</h1>
|
||||
</header>
|
||||
<LibraryLoading />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-svh flex-col">
|
||||
<header className="flex items-center justify-between gap-2 border-b px-4 py-3">
|
||||
@@ -416,7 +438,7 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortedSongs.map((song, index) => (
|
||||
{songs.map((song, index) => (
|
||||
<SongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
@@ -439,12 +461,24 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) {
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
onMediaAction={handleMediaAction}
|
||||
onPlay={() =>
|
||||
void playFromSong(song.id as Id<"songs">, sortedSongIds)
|
||||
void playFromLibrarySong(song.id as Id<"songs">, {
|
||||
sortKey,
|
||||
sortDirection,
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div
|
||||
ref={loadMoreRef}
|
||||
className="flex items-center justify-center py-4"
|
||||
aria-hidden={status !== "LoadingMore"}
|
||||
>
|
||||
{status === "LoadingMore" ? (
|
||||
<Spinner className="size-5 text-muted-foreground" />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { paginationOptsValidator } from "convex/server"
|
||||
import { mutation, query } from "./_generated/server"
|
||||
import { v } from "convex/values"
|
||||
import type { Doc, Id } from "./_generated/dataModel"
|
||||
import type { QueryCtx } from "./_generated/server"
|
||||
import type { PaginationOptions, PaginationResult } from "convex/server"
|
||||
|
||||
export type BrowseArtist = {
|
||||
id: Id<"artists">
|
||||
@@ -268,6 +270,210 @@ export const browseSongs = query({
|
||||
},
|
||||
})
|
||||
|
||||
export const songsSortKeyValidator = v.union(
|
||||
v.literal("title"),
|
||||
v.literal("artist"),
|
||||
v.literal("album")
|
||||
)
|
||||
export const songsSortDirectionValidator = v.union(
|
||||
v.literal("asc"),
|
||||
v.literal("desc")
|
||||
)
|
||||
|
||||
export type SongsSortKey = "title" | "artist" | "album"
|
||||
export type SongsSortDirection = "asc" | "desc"
|
||||
|
||||
type GroupedSongsCursor = {
|
||||
groupIndex: number
|
||||
songIndex: number
|
||||
}
|
||||
|
||||
function compareSongNames(
|
||||
a: string,
|
||||
b: string,
|
||||
direction: SongsSortDirection
|
||||
): number {
|
||||
const comparison = a.localeCompare(b)
|
||||
return direction === "asc" ? comparison : -comparison
|
||||
}
|
||||
|
||||
function mapSongToBrowse(
|
||||
song: Doc<"songs">,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>
|
||||
): BrowseSong | null {
|
||||
const album = albumMap.get(song.album)
|
||||
const albumArtist = artistMap.get(song.albumArtist)
|
||||
if (!album || !albumArtist) {
|
||||
return null
|
||||
}
|
||||
return toBrowseSong(song, album, albumArtist)
|
||||
}
|
||||
|
||||
async function paginateSongsByTitle(
|
||||
ctx: QueryCtx,
|
||||
paginationOpts: PaginationOptions,
|
||||
sortDirection: SongsSortDirection,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>
|
||||
): Promise<PaginationResult<BrowseSong>> {
|
||||
const result = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_name")
|
||||
.order(sortDirection)
|
||||
.paginate(paginationOpts)
|
||||
|
||||
return {
|
||||
...result,
|
||||
page: result.page.flatMap((song) => {
|
||||
const mapped = mapSongToBrowse(song, artistMap, albumMap)
|
||||
return mapped ? [mapped] : []
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async function paginateSongsByGroup(
|
||||
ctx: QueryCtx,
|
||||
paginationOpts: PaginationOptions,
|
||||
sortDirection: SongsSortDirection,
|
||||
artistMap: Map<Id<"artists">, Doc<"artists">>,
|
||||
albumMap: Map<Id<"albums">, Doc<"albums">>,
|
||||
sortKey: "artist" | "album"
|
||||
): Promise<PaginationResult<BrowseSong>> {
|
||||
const cursor: GroupedSongsCursor = paginationOpts.cursor
|
||||
? (JSON.parse(paginationOpts.cursor) as GroupedSongsCursor)
|
||||
: { groupIndex: 0, songIndex: 0 }
|
||||
|
||||
const groups =
|
||||
sortKey === "artist"
|
||||
? [...artistMap.values()].sort((a, b) =>
|
||||
compareSongNames(a.name, b.name, sortDirection)
|
||||
)
|
||||
: [...albumMap.values()].sort((a, b) =>
|
||||
compareSongNames(a.name, b.name, sortDirection)
|
||||
)
|
||||
|
||||
const page: BrowseSong[] = []
|
||||
let { groupIndex, songIndex } = cursor
|
||||
|
||||
while (page.length < paginationOpts.numItems && groupIndex < groups.length) {
|
||||
const group = groups[groupIndex]
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) =>
|
||||
sortKey === "artist"
|
||||
? q.eq("albumArtist", group._id as Id<"artists">)
|
||||
: q.eq("album", group._id as Id<"albums">)
|
||||
)
|
||||
.collect()
|
||||
|
||||
songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection))
|
||||
|
||||
while (songIndex < songs.length && page.length < paginationOpts.numItems) {
|
||||
const mapped = mapSongToBrowse(songs[songIndex], artistMap, albumMap)
|
||||
if (mapped) {
|
||||
page.push(mapped)
|
||||
}
|
||||
songIndex++
|
||||
}
|
||||
|
||||
if (songIndex >= songs.length) {
|
||||
groupIndex++
|
||||
songIndex = 0
|
||||
}
|
||||
}
|
||||
|
||||
const isDone = groupIndex >= groups.length
|
||||
|
||||
return {
|
||||
page,
|
||||
isDone,
|
||||
continueCursor: isDone
|
||||
? ""
|
||||
: JSON.stringify({ groupIndex, songIndex } satisfies GroupedSongsCursor),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSortedLibrarySongIds(
|
||||
ctx: QueryCtx,
|
||||
sortKey: SongsSortKey,
|
||||
sortDirection: SongsSortDirection
|
||||
): Promise<Id<"songs">[]> {
|
||||
if (sortKey === "title") {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex("by_name")
|
||||
.order(sortDirection)
|
||||
.collect()
|
||||
return songs.map((song) => song._id)
|
||||
}
|
||||
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
||||
|
||||
const groups =
|
||||
sortKey === "artist"
|
||||
? [...artistMap.values()].sort((a, b) =>
|
||||
compareSongNames(a.name, b.name, sortDirection)
|
||||
)
|
||||
: [...albumMap.values()].sort((a, b) =>
|
||||
compareSongNames(a.name, b.name, sortDirection)
|
||||
)
|
||||
|
||||
const songIds: Id<"songs">[] = []
|
||||
|
||||
for (const group of groups) {
|
||||
const songs = await ctx.db
|
||||
.query("songs")
|
||||
.withIndex(sortKey === "artist" ? "by_artist" : "by_album", (q) =>
|
||||
sortKey === "artist"
|
||||
? q.eq("albumArtist", group._id as Id<"artists">)
|
||||
: q.eq("album", group._id as Id<"albums">)
|
||||
)
|
||||
.collect()
|
||||
|
||||
songs.sort((a, b) => compareSongNames(a.name, b.name, sortDirection))
|
||||
for (const song of songs) {
|
||||
songIds.push(song._id)
|
||||
}
|
||||
}
|
||||
|
||||
return songIds
|
||||
}
|
||||
|
||||
export const browseSongsPaginated = query({
|
||||
args: {
|
||||
paginationOpts: paginationOptsValidator,
|
||||
sortKey: songsSortKeyValidator,
|
||||
sortDirection: songsSortDirectionValidator,
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const artistMap = await loadArtistMap(ctx)
|
||||
const albums = await ctx.db.query("albums").collect()
|
||||
const albumMap = new Map(albums.map((album) => [album._id, album]))
|
||||
|
||||
if (args.sortKey === "title") {
|
||||
return paginateSongsByTitle(
|
||||
ctx,
|
||||
args.paginationOpts,
|
||||
args.sortDirection,
|
||||
artistMap,
|
||||
albumMap
|
||||
)
|
||||
}
|
||||
|
||||
return paginateSongsByGroup(
|
||||
ctx,
|
||||
args.paginationOpts,
|
||||
args.sortDirection,
|
||||
artistMap,
|
||||
albumMap,
|
||||
args.sortKey
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
export const browseAlbumDetail = query({
|
||||
args: { id: v.id("albums") },
|
||||
handler: async (ctx, args): Promise<BrowseAlbumDetail | null> => {
|
||||
|
||||
+82
-4
@@ -1,9 +1,18 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server"
|
||||
import { paginationOptsValidator } from "convex/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"
|
||||
import {
|
||||
browseSongsFromIds,
|
||||
type BrowseSong,
|
||||
getSortedLibrarySongIds,
|
||||
songsSortDirectionValidator,
|
||||
songsSortKeyValidator,
|
||||
} from "./library"
|
||||
|
||||
export type QueueSong = BrowseSong & { queueIndex: number }
|
||||
|
||||
function shuffleArray<T>(items: T[]): T[] {
|
||||
const next = [...items]
|
||||
@@ -58,11 +67,14 @@ export const getPlaybackState = query({
|
||||
}
|
||||
|
||||
const songIds = user.songQueue ?? []
|
||||
const queue = await browseSongsFromIds(ctx, songIds)
|
||||
const currentSong =
|
||||
songIds.length > 0
|
||||
? ((await browseSongsFromIds(ctx, [songIds[0]]))[0] ?? null)
|
||||
: null
|
||||
|
||||
return {
|
||||
queue,
|
||||
currentSong: queue[0] ?? null,
|
||||
queueSongIds: songIds,
|
||||
currentSong,
|
||||
shuffleEnabled: user.shuffleEnabled ?? false,
|
||||
repeatEnabled: user.repeatEnabled ?? ("none" as const),
|
||||
currentSongProgress: user.currentSongProgress ?? 0,
|
||||
@@ -70,6 +82,48 @@ export const getPlaybackState = query({
|
||||
},
|
||||
})
|
||||
|
||||
export const getQueuePaginated = query({
|
||||
args: {
|
||||
paginationOpts: paginationOptsValidator,
|
||||
queueVersion: v.string(),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await getAuthUserId(ctx)
|
||||
if (userId === null) {
|
||||
return { page: [], isDone: true, continueCursor: "" }
|
||||
}
|
||||
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
return { page: [], isDone: true, continueCursor: "" }
|
||||
}
|
||||
|
||||
const songIds = user.songQueue ?? []
|
||||
const startIndex = args.paginationOpts.cursor
|
||||
? Number.parseInt(args.paginationOpts.cursor, 10)
|
||||
: 0
|
||||
const endIndex = Math.min(
|
||||
startIndex + args.paginationOpts.numItems,
|
||||
songIds.length
|
||||
)
|
||||
const pageIds = songIds.slice(startIndex, endIndex)
|
||||
const songs = await browseSongsFromIds(ctx, pageIds)
|
||||
|
||||
const page: QueueSong[] = songs.map((song, index) => ({
|
||||
...song,
|
||||
queueIndex: startIndex + index,
|
||||
}))
|
||||
|
||||
const isDone = endIndex >= songIds.length
|
||||
|
||||
return {
|
||||
page,
|
||||
isDone,
|
||||
continueCursor: isDone ? "" : String(endIndex),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const playInOrder = mutation({
|
||||
args: { songIds: v.array(v.id("songs")) },
|
||||
handler: async (ctx, { songIds }) => {
|
||||
@@ -170,6 +224,30 @@ export const playFromSong = mutation({
|
||||
},
|
||||
})
|
||||
|
||||
export const playFromLibrarySong = mutation({
|
||||
args: {
|
||||
songId: v.id("songs"),
|
||||
sortKey: songsSortKeyValidator,
|
||||
sortDirection: songsSortDirectionValidator,
|
||||
},
|
||||
handler: async (ctx, { songId, sortKey, sortDirection }) => {
|
||||
const userId = await requireAuth(ctx)
|
||||
const user = await ctx.db.get(userId)
|
||||
if (!user) {
|
||||
throw new ConvexError("User not found")
|
||||
}
|
||||
|
||||
const songIds = await getSortedLibrarySongIds(ctx, sortKey, sortDirection)
|
||||
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) => {
|
||||
|
||||
Reference in new issue
Block a user