Compare commits

...
3 changed files with 219 additions and 132 deletions

No files matched your search

+18
View File
@@ -103,8 +103,11 @@ type PlaybackContextValue = {
toggleShuffle: () => Promise<void> toggleShuffle: () => Promise<void>
cycleRepeat: () => Promise<void> cycleRepeat: () => Promise<void>
clearQueue: () => Promise<void> clearQueue: () => Promise<void>
clearHistory: () => Promise<void>
reorderQueue: (songIds: Id<"songs">[]) => Promise<void> reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
skipToQueueIndex: (index: number) => Promise<void> skipToQueueIndex: (index: number) => Promise<void>
/** Plays `history[index]`, moving it and every later song back into the queue. */
skipToHistoryIndex: (index: number) => Promise<void>
skipNext: () => Promise<void> skipNext: () => Promise<void>
skipPrevious: () => Promise<void> skipPrevious: () => Promise<void>
dolbyAtmosSupported: boolean | null dolbyAtmosSupported: boolean | null
@@ -1455,6 +1458,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
setIsPlaying(false) setIsPlaying(false)
}, [store]) }, [store])
const clearHistory = useCallback(async () => {
store.update(playbackQueue.clearHistory)
}, [store])
const reorderQueue = useCallback( const reorderQueue = useCallback(
async (songIds: Id<"songs">[]) => { async (songIds: Id<"songs">[]) => {
store.update((state) => playbackQueue.reorderQueue(state, songIds)) store.update((state) => playbackQueue.reorderQueue(state, songIds))
@@ -1469,6 +1476,13 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
[store] [store]
) )
const skipToHistoryIndex = useCallback(
async (index: number) => {
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
},
[store]
)
const skipNext = useCallback(async () => { const skipNext = useCallback(async () => {
const before = store.getState() const before = store.getState()
if (before.repeatEnabled === "none" && before.queue.length <= 1) { if (before.repeatEnabled === "none" && before.queue.length <= 1) {
@@ -1550,8 +1564,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
toggleShuffle, toggleShuffle,
cycleRepeat, cycleRepeat,
clearQueue, clearQueue,
clearHistory,
reorderQueue, reorderQueue,
skipToQueueIndex, skipToQueueIndex,
skipToHistoryIndex,
skipNext, skipNext,
skipPrevious, skipPrevious,
}), }),
@@ -1573,8 +1589,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
toggleShuffle, toggleShuffle,
cycleRepeat, cycleRepeat,
clearQueue, clearQueue,
clearHistory,
reorderQueue, reorderQueue,
skipToQueueIndex, skipToQueueIndex,
skipToHistoryIndex,
skipNext, skipNext,
skipPrevious, skipPrevious,
] ]
+180 -120
View File
@@ -5,13 +5,11 @@ import * as React from "react"
import { PlaybackSongMeta } from "@/components/playback-song-meta" import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider" import { usePlayback } from "@/components/playback-provider"
import { TrackCover, TrackRow } from "@/components/track-row" import { TrackCover, TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton" import { Skeleton } from "@/components/ui/skeleton"
import { Spinner } from "@/components/ui/spinner" import { Spinner } from "@/components/ui/spinner"
import { useTrackSelection } from "@/hooks/use-track-selection" import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel" import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types" import type { BrowseSong, QueueSong } from "@otunes/convex/types"
import { import {
getContiguousSelectedIndices, getContiguousSelectedIndices,
moveQueueBlock, moveQueueBlock,
@@ -19,7 +17,6 @@ import {
import { getSelectionRangePositions } from "@/lib/selection-range-styles" import { getSelectionRangePositions } from "@/lib/selection-range-styles"
import { useSongs } from "@/lib/song-cache" import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { formatDuration } from "@/lib/format-duration"
const QUEUE_INITIAL_VISIBLE_COUNT = 100 const QUEUE_INITIAL_VISIBLE_COUNT = 100
const QUEUE_PAGE_SIZE = 50 const QUEUE_PAGE_SIZE = 50
@@ -32,11 +29,13 @@ type QueueItem = {
song: QueueSelectable | null song: QueueSelectable | null
} }
/** Upcoming songs only: queue index 0 is the current song, shown on its own. */
function toSelectableQueue( function toSelectableQueue(
songIds: Id<"songs">[], songIds: Id<"songs">[],
songs: (BrowseSong | undefined)[] songs: (BrowseSong | undefined)[]
): QueueItem[] { ): QueueItem[] {
return songIds.map((songId, queueIndex) => { return songIds.slice(1).map((songId, offset) => {
const queueIndex = offset + 1
const selectionId = `${songId}-${queueIndex}` const selectionId = `${songId}-${queueIndex}`
const song = songs[queueIndex] const song = songs[queueIndex]
return { return {
@@ -47,57 +46,75 @@ function toSelectableQueue(
}) })
} }
function HistorySongRow({ song }: { song: HistorySong }) { /** A played song; clicking it plays it again from that point in history. */
function HistorySongRow({
song,
historyIndex,
onPlay,
}: {
song: BrowseSong | undefined
historyIndex: number
onPlay: (historyIndex: number) => void
}) {
if (!song) {
return <QueueSongRowSkeleton />
}
return ( return (
<li className="relative w-full py-2 text-left text-sm opacity-60"> <li
<div className="relative z-10 flex items-center gap-3 px-2"> role="button"
<TrackCover tabIndex={0}
albumId={song.album.id} className="flex cursor-pointer items-center gap-3 px-4 py-2 text-sm hover:bg-foreground/5"
alt={song.album.title} onClick={() => onPlay(historyIndex)}
inRange={false} onKeyDown={(event) => {
square if (event.key === "Enter" || event.key === " ") {
/> event.preventDefault()
onPlay(historyIndex)
<PlaybackSongMeta }
song={song} }}
isCurrent={false} >
inRange={false} <TrackCover
align="start" albumId={song.album.id}
showAlbum={false} alt={song.album.title}
/> inRange={false}
/>
<span className="shrink-0 text-xs text-muted-foreground tabular-nums"> <PlaybackSongMeta song={song} align="start" showAlbum={false} />
{formatDuration(song.durationSeconds)}
</span>
</div>
</li> </li>
) )
} }
function QueueSongRowSkeleton() { function QueueSongRowSkeleton() {
return ( return (
<li className="flex items-center gap-3 px-2 py-2" aria-hidden> <li className="flex items-center gap-3 px-4 py-2" aria-hidden>
<Skeleton className="size-10 shrink-0 rounded-none" /> <Skeleton className="size-10 shrink-0 rounded" />
<div className="flex min-w-0 flex-1 flex-col gap-1.5"> <div className="flex min-w-0 flex-1 flex-col gap-1.5">
<Skeleton className="h-3.5 w-3/4" /> <Skeleton className="h-3.5 w-3/4" />
<Skeleton className="h-3 w-1/2" /> <Skeleton className="h-3 w-1/2" />
</div> </div>
<Skeleton className="h-3 w-8 shrink-0" />
</li> </li>
) )
} }
/**
* The queue sidebar, laid out like the mobile now playing queue: history above
* (scrolled out of view at first), then the current song and the upcoming
* songs, which can be dragged to reorder. Shuffle and repeat live in the
* player bar.
*/
export function QueuePanel() { export function QueuePanel() {
const { const {
queueSongIds, queueSongIds,
queueHistorySongIds, queueHistorySongIds,
queueOpen, queueOpen,
clearHistory,
clearQueue, clearQueue,
reorderQueue, reorderQueue,
skipToQueueIndex, skipToQueueIndex,
skipToHistoryIndex,
} = usePlayback() } = usePlayback()
const loadMoreRef = React.useRef<HTMLDivElement>(null) const loadMoreRef = React.useRef<HTMLDivElement>(null)
const nowPlayingRef = React.useRef<HTMLElement>(null) const scrollRef = React.useRef<HTMLDivElement>(null)
const currentRef = React.useRef<HTMLDivElement>(null)
const [visibleCount, setVisibleCount] = React.useState( const [visibleCount, setVisibleCount] = React.useState(
QUEUE_INITIAL_VISIBLE_COUNT QUEUE_INITIAL_VISIBLE_COUNT
) )
@@ -107,15 +124,10 @@ export function QueuePanel() {
[queueSongIds, visibleCount] [queueSongIds, visibleCount]
) )
const visibleQueueSongs = useSongs(visibleQueueIds) const visibleQueueSongs = useSongs(visibleQueueIds)
const historySongMetadata = useSongs(queueHistorySongIds) const historySongs = useSongs(queueHistorySongIds)
const historySongs = React.useMemo( const currentSong = visibleQueueSongs[0]
() =>
historySongMetadata.flatMap((song, historyIndex) =>
song ? [{ ...song, historyIndex }] : []
),
[historySongMetadata]
)
const hasMore = queueSongIds.length > visibleCount const hasMore = queueSongIds.length > visibleCount
const hasUpcoming = queueSongIds.length > 1
const selectableQueue = React.useMemo( const selectableQueue = React.useMemo(
() => toSelectableQueue(visibleQueueIds, visibleQueueSongs), () => toSelectableQueue(visibleQueueIds, visibleQueueSongs),
@@ -125,17 +137,21 @@ export function QueuePanel() {
const [dragIndex, setDragIndex] = React.useState<number | null>(null) const [dragIndex, setDragIndex] = React.useState<number | null>(null)
const currentQueueSongId = queueSongIds[0] const currentQueueSongId = queueSongIds[0]
React.useEffect(() => { // Keep the current song at the top as playback moves through the queue:
if (!queueOpen || queueSongIds.length === 0) { // jump there on open, then scroll smoothly as songs change.
const hasScrolledRef = React.useRef(false)
React.useLayoutEffect(() => {
const scroller = scrollRef.current
const current = currentRef.current
if (!queueOpen || !scroller || !current) {
return return
} }
scroller.scrollTo({
const frame = requestAnimationFrame(() => { top: current.offsetTop,
nowPlayingRef.current?.scrollIntoView({ block: "center" }) behavior: hasScrolledRef.current ? "smooth" : "instant",
}) })
hasScrolledRef.current = true
return () => cancelAnimationFrame(frame) }, [queueOpen, currentQueueSongId, queueHistorySongIds.length])
}, [queueOpen, queueSongIds.length, currentQueueSongId])
React.useEffect(() => { React.useEffect(() => {
if (!hasMore) { if (!hasMore) {
@@ -143,12 +159,8 @@ export function QueuePanel() {
} }
const sentinel = loadMoreRef.current const sentinel = loadMoreRef.current
if (!sentinel) { const root = scrollRef.current
return if (!sentinel || !root) {
}
const viewport = sentinel.closest('[data-slot="scroll-area-viewport"]')
if (!viewport) {
return return
} }
@@ -158,7 +170,7 @@ export function QueuePanel() {
setVisibleCount((count) => count + QUEUE_PAGE_SIZE) setVisibleCount((count) => count + QUEUE_PAGE_SIZE)
} }
}, },
{ root: viewport, rootMargin: "240px" } { root, rootMargin: "240px" }
) )
observer.observe(sentinel) observer.observe(sentinel)
@@ -186,6 +198,11 @@ export function QueuePanel() {
[selectableQueue, skipToQueueIndex] [selectableQueue, skipToQueueIndex]
) )
const handleHistoryPlay = React.useCallback(
(historyIndex: number) => void skipToHistoryIndex(historyIndex),
[skipToHistoryIndex]
)
const selectionPositions = React.useMemo( const selectionPositions = React.useMemo(
() => () =>
getSelectionRangePositions( getSelectionRangePositions(
@@ -240,76 +257,119 @@ export function QueuePanel() {
return ( return (
<aside <aside
className={cn( className={cn(
"flex h-svh w-72 shrink-0 flex-col border-l bg-background", "relative 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" "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"> <div
<h1 className="text-lg font-semibold">Up Next</h1> ref={scrollRef}
<Button className="relative min-h-0 flex-1 [scrollbar-width:none] overflow-y-auto overscroll-contain"
variant="ghost" >
size="sm" {queueHistorySongIds.length > 0 ? (
className="text-primary hover:text-primary" <section>
onClick={() => void clearQueue()} <header className="flex items-center justify-between px-4 pt-3 pb-1">
disabled={queueSongIds.length === 0} <h2 className="text-base font-bold">History</h2>
> <button
Clear type="button"
</Button> className="text-sm text-muted-foreground hover:text-foreground"
</header> onClick={() => void clearHistory()}
<ScrollArea className="min-h-0 flex-1">
{queueSongIds.length === 0 ? (
<p className="px-4 py-8 text-sm text-muted-foreground">
Nothing in the queue.
</p>
) : (
<>
{historySongs.length > 0 ? (
<ul className="flex flex-col border-b py-1">
{historySongs.map((song) => (
<HistorySongRow
key={`history-${song.id}-${song.historyIndex}`}
song={song}
/>
))}
</ul>
) : null}
<ul className="flex flex-col py-1">
{selectableQueue.map((item, index) =>
item.song ? (
<TrackRow
key={item.selectionId}
ref={item.queueIndex === 0 ? nowPlayingRef : undefined}
variant="queue"
song={item.song}
index={index}
isActive={item.queueIndex === 0}
isNowPlaying={item.queueIndex === 0}
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onDragStart={setDragIndex}
onDrop={handleDrop}
/>
) : (
<QueueSongRowSkeleton key={item.selectionId} />
)
)}
</ul>
{hasMore ? (
<div
ref={loadMoreRef}
className="flex items-center justify-center py-4"
aria-hidden
> >
<Spinner className="size-5 text-muted-foreground" /> Clear
</div> </button>
) : null} </header>
</> <ul className="flex flex-col">
)} {queueHistorySongIds.map((songId, historyIndex) => (
</ScrollArea> <HistorySongRow
key={`history-${songId}-${historyIndex}`}
song={historySongs[historyIndex]}
historyIndex={historyIndex}
onPlay={handleHistoryPlay}
/>
))}
</ul>
</section>
) : null}
{/* Fills the viewport so the current song can always scroll to the top. */}
<div ref={currentRef} className="flex min-h-full flex-col">
{currentQueueSongId ? (
<div className="flex items-center gap-3 px-4 py-3">
{currentSong ? (
<>
<TrackCover
albumId={currentSong.album.id}
alt={currentSong.album.title}
inRange={false}
size="lg"
/>
<PlaybackSongMeta
song={currentSong}
align="start"
showAlbum={false}
/>
</>
) : (
<Skeleton className="size-14 shrink-0 rounded-md" />
)}
</div>
) : null}
<header className="sticky top-0 z-20 flex items-center justify-between bg-background px-4 py-2">
<h2 className="text-base font-bold">Continue Playing</h2>
<button
type="button"
className="text-sm text-muted-foreground hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
onClick={() => void clearQueue()}
disabled={queueSongIds.length === 0}
>
Clear
</button>
</header>
{hasUpcoming ? (
<>
<ul className="flex flex-col pb-8">
{selectableQueue.map((item, index) =>
item.song ? (
<TrackRow
key={item.selectionId}
variant="queue"
song={item.song}
index={index}
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onDragStart={setDragIndex}
onDrop={handleDrop}
/>
) : (
<QueueSongRowSkeleton key={item.selectionId} />
)
)}
</ul>
{hasMore ? (
<div
ref={loadMoreRef}
className="flex items-center justify-center py-4"
aria-hidden
>
<Spinner className="size-5 text-muted-foreground" />
</div>
) : null}
</>
) : (
<p className="flex flex-1 items-center justify-center px-4 pb-24 text-center text-lg font-semibold text-muted-foreground">
Nothing else is queued.
</p>
)}
</div>
</div>
<div
aria-hidden
className="pointer-events-none absolute inset-x-0 bottom-0 h-9 bg-linear-to-b from-transparent to-background"
/>
</aside> </aside>
) )
} }
+21 -12
View File
@@ -3,7 +3,7 @@
import * as React from "react" import * as React from "react"
import Image from "next/image" import Image from "next/image"
import Link from "next/link" import Link from "next/link"
import { ArrowDownToLine, Music2, Play, Star, Trash2 } from "lucide-react" import { ArrowDownToLine, Menu, Music2, Play, Star, Trash2 } from "lucide-react"
import { import {
MediaContextMenu, MediaContextMenu,
@@ -38,7 +38,7 @@ import type { DownloadSource } from "@otunes/convex/client/download-queue"
* columns (use with `LibraryTrackListHeader`). * columns (use with `LibraryTrackListHeader`).
* - `album`: favorite star, track number, title with optional credits. * - `album`: favorite star, track number, title with optional credits.
* - `playlist`: cover with favorite overlay, track number, title. * - `playlist`: cover with favorite overlay, track number, title.
* - `queue`: square cover, title and artist, no menu. * - `queue`: cover, title and artist, duration, and a reorder grip. No menu.
*/ */
export type TrackRowVariant = "library" | "album" | "playlist" | "queue" export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
@@ -89,13 +89,14 @@ export function TrackCover({
albumId, albumId,
alt, alt,
inRange, inRange,
square = false, size = "md",
children, children,
}: { }: {
albumId: string | undefined albumId: string | undefined
alt: string alt: string
inRange: boolean inRange: boolean
square?: boolean /** `lg` is the larger current-song cover in the queue. */
size?: "md" | "lg"
/** Overlay shown above the cover image. */ /** Overlay shown above the cover image. */
children?: React.ReactNode children?: React.ReactNode
}) { }) {
@@ -105,8 +106,8 @@ export function TrackCover({
return ( return (
<div <div
className={cn( className={cn(
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1", "flex shrink-0 items-center justify-center bg-muted ring-1",
!square && "rounded", size === "lg" ? "size-14 rounded-md" : "size-10 rounded",
ringClass ringClass
)} )}
> >
@@ -118,8 +119,8 @@ export function TrackCover({
return ( return (
<div <div
className={cn( className={cn(
"group/cover relative size-10 shrink-0 overflow-hidden ring-1", "group/cover relative shrink-0 overflow-hidden ring-1",
!square && "rounded", size === "lg" ? "size-14 rounded-md" : "size-10 rounded",
ringClass ringClass
)} )}
> >
@@ -127,7 +128,7 @@ export function TrackCover({
src={albumCoverUrl(albumId)} src={albumCoverUrl(albumId)}
alt={alt} alt={alt}
fill fill
sizes="40px" sizes={size === "lg" ? "56px" : "40px"}
className="object-cover" className="object-cover"
/> />
{children} {children}
@@ -277,7 +278,9 @@ function TrackRowComponent({
const inRange = isInSelectionRange(selectionPosition) const inRange = isInSelectionRange(selectionPosition)
const downloadState = useSongDownloadState(song.id, downloadCollection) const downloadState = useSongDownloadState(song.id, downloadCollection)
const isDownloaded = downloadState === "here" const isDownloaded = downloadState === "here"
const showDownloaded = isDownloaded || downloadState === "device" // The queue row only shows the duration, like the mobile queue.
const showDownloaded =
variant !== "queue" && (isDownloaded || downloadState === "device")
const flush = variant === "library" || variant === "queue" const flush = variant === "library" || variant === "queue"
const play = () => onPlay(index) const play = () => onPlay(index)
const toggleFavorite = () => onToggleFavorite?.(song.id) const toggleFavorite = () => onToggleFavorite?.(song.id)
@@ -459,12 +462,11 @@ function TrackRowComponent({
break break
case "queue": case "queue":
content = ( content = (
<div className="relative z-10 flex items-center gap-3 px-2"> <div className="relative z-10 flex items-center gap-3 pr-2 pl-4">
<TrackCover <TrackCover
albumId={song.album.id} albumId={song.album.id}
alt={song.album.title} alt={song.album.title}
inRange={inRange} inRange={inRange}
square
/> />
<PlaybackSongMeta <PlaybackSongMeta
song={song} song={song}
@@ -474,6 +476,13 @@ function TrackRowComponent({
showAlbum={false} showAlbum={false}
/> />
{duration} {duration}
<Menu
aria-hidden
className={cn(
"size-4 shrink-0 cursor-grab",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
/>
</div> </div>
) )
break break