From e5f67eece4d2b60cb9cac6008986bba1a30c1914 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Sat, 6 Jun 2026 15:37:02 -0400 Subject: [PATCH] fix: phantom selections, pagination in /libary/songs & queue sidebar --- app/(app)/library/songs/page.tsx | 12 +- components/album-view.tsx | 4 +- components/playback-provider.tsx | 25 +++- components/player-bar.tsx | 4 +- components/playlist-view.tsx | 13 +- components/queue-panel.tsx | 167 ++++++++++++++++++------- components/songs-view.tsx | 96 +++++++++----- convex/library.ts | 206 +++++++++++++++++++++++++++++++ convex/playback.ts | 86 ++++++++++++- 9 files changed, 508 insertions(+), 105 deletions(-) diff --git a/app/(app)/library/songs/page.tsx b/app/(app)/library/songs/page.tsx index e3a9dde..c3437df 100644 --- a/app/(app)/library/songs/page.tsx +++ b/app/(app)/library/songs/page.tsx @@ -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 - } - - return + return } diff --git a/components/album-view.tsx b/components/album-view.tsx index 1776978..493e771 100644 --- a/components/album-view.tsx +++ b/components/album-view.tsx @@ -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, diff --git a/components/playback-provider.tsx b/components/playback-provider.tsx index d35a2a9..136f3d7 100644 --- a/components/playback-provider.tsx +++ b/components/playback-provider.tsx @@ -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 addToQueueLast: (songIds: Id<"songs">[]) => Promise playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise + playFromLibrarySong: ( + songId: Id<"songs">, + sort: { sortKey: "title" | "artist" | "album"; sortDirection: "asc" | "desc" } + ) => Promise playAlbum: (albumId: Id<"albums">) => Promise playAlbumShuffled: (albumId: Id<"albums">) => Promise playArtist: (artistId: Id<"artists">) => Promise @@ -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( () => ({ - 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, diff --git a/components/player-bar.tsx b/components/player-bar.tsx index 8ade2d2..a2695f5 100644 --- a/components/player-bar.tsx +++ b/components/player-bar.tsx @@ -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 diff --git a/components/playlist-view.tsx b/components/playlist-view.tsx index 01bd9fa..0fc27c6 100644 --- a/components/playlist-view.tsx +++ b/components/playlist-view.tsx @@ -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(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 { diff --git a/components/queue-panel.tsx b/components/queue-panel.tsx index 10f9eb7..0305652 100644 --- a/components/queue-panel.tsx +++ b/components/queue-panel.tsx @@ -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(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(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 - {queue.length === 0 ? ( + {queueSongIds.length === 0 ? (

Nothing in the queue.

+ ) : status === "LoadingFirstPage" ? ( +
+ +
) : ( -
    - {selectableQueue.map((song, index) => ( - { - 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) - }} - /> - ))} -
+ <> +
    + {selectableQueue.map((song, index) => ( + { + 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) + }} + /> + ))} +
+ {shouldPaginate ? ( +
+ {status === "LoadingMore" ? ( + + ) : null} +
+ ) : null} + )}
diff --git a/components/songs-view.tsx b/components/songs-view.tsx index 82f175f..c3fd685 100644 --- a/components/songs-view.tsx +++ b/components/songs-view.tsx @@ -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("title") const [sortDirection, setSortDirection] = React.useState("asc") + const loadMoreRef = React.useRef(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 ( +
+
+

Songs

+
+ +
+ ) + } + return (
@@ -416,7 +438,7 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) { - {sortedSongs.map((song, index) => ( + {songs.map((song, index) => ( prepareContextMenu(song.id)} onMediaAction={handleMediaAction} onPlay={() => - void playFromSong(song.id as Id<"songs">, sortedSongIds) + void playFromLibrarySong(song.id as Id<"songs">, { + sortKey, + sortDirection, + }) } /> ))} +
+ {status === "LoadingMore" ? ( + + ) : null} +
diff --git a/convex/library.ts b/convex/library.ts index e86ea60..0ad3bef 100644 --- a/convex/library.ts +++ b/convex/library.ts @@ -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, Doc<"artists">>, + albumMap: Map, 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, Doc<"artists">>, + albumMap: Map, Doc<"albums">> +): Promise> { + 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, Doc<"artists">>, + albumMap: Map, Doc<"albums">>, + sortKey: "artist" | "album" +): Promise> { + 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[]> { + 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 => { diff --git a/convex/playback.ts b/convex/playback.ts index 7d35130..e3f2119 100644 --- a/convex/playback.ts +++ b/convex/playback.ts @@ -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(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) => {