perf(web): virtualize song lists and add row right-click menus (#97)
This commit was merged in pull request #97.
This commit is contained in:
1 parent
d395273691
commit
36a01531d0
19 files changed
+696
-327
No files matched your search
@@ -13,7 +13,7 @@ import {
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -48,7 +48,7 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddAlbumToPlaylist } = useAddToPlaylist()
|
||||
const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites()
|
||||
const { playAlbum } = usePlayback()
|
||||
const { playAlbum } = usePlaybackActions()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const [menuOpen, setMenuOpen] = React.useState(false)
|
||||
const [hovered, setHovered] = React.useState(false)
|
||||
|
||||
@@ -11,7 +11,10 @@ import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
||||
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { copyAlbumLink } from "@/lib/media-links"
|
||||
|
||||
import {
|
||||
@@ -105,8 +108,8 @@ export function AlbumView({
|
||||
toggleSongFavorite,
|
||||
toggleAlbumFavorite,
|
||||
} = useFavorites()
|
||||
const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
|
||||
usePlayback()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions()
|
||||
const { runSongsAction } = useMediaActions()
|
||||
const albumSongIds = React.useMemo(
|
||||
() => album.tracks.map((track) => track.id as Id<"songs">),
|
||||
@@ -366,7 +369,7 @@ export function AlbumView({
|
||||
isFavorite={isSongFavorite(track.id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={album.artist.id}
|
||||
isNowPlaying={currentSong?.id === track.id}
|
||||
isNowPlaying={currentSongId === track.id}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
|
||||
@@ -6,7 +6,7 @@ import Image from "next/image"
|
||||
import { Play, Shuffle } from "lucide-react"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useMediaActions } from "@/hooks/use-media-actions"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
@@ -26,7 +26,7 @@ export function ArtistView({
|
||||
albums: BrowseAlbum[]
|
||||
}) {
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { runArtistAction } = useMediaActions()
|
||||
|
||||
return (
|
||||
|
||||
@@ -11,8 +11,10 @@ import { useFavorites } from "@/components/favorites-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
MediaContextMenuArea,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useMediaActions } from "@/hooks/use-media-actions"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
@@ -50,36 +52,42 @@ function ArtistListItem({
|
||||
onSelect: () => void
|
||||
onMediaAction: (action: MediaContextAction) => void
|
||||
}) {
|
||||
const menu: MediaContextMenuProps = {
|
||||
label: `More options for ${artist.name}`,
|
||||
selectedCount: albumCount,
|
||||
inSelectionRange: isSelected,
|
||||
onOpenMenu: () => {},
|
||||
onAction: onMediaAction,
|
||||
favorited: isFavorite,
|
||||
share: { type: "artist", artistId: artist.id },
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group flex w-full min-w-0 items-center gap-1 overflow-hidden pr-1",
|
||||
isSelected ? "bg-primary text-primary-foreground" : "hover:bg-muted/50"
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
<MediaContextMenuArea menu={menu}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
|
||||
isSelected ? "text-primary-foreground" : ""
|
||||
"group flex w-full min-w-0 items-center gap-1 overflow-hidden pr-1",
|
||||
isSelected
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "hover:bg-muted/50"
|
||||
)}
|
||||
>
|
||||
<ArtistAvatar artist={artist} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{artist.name}
|
||||
</span>
|
||||
</button>
|
||||
<MediaContextMenu
|
||||
label={`More options for ${artist.name}`}
|
||||
selectedCount={albumCount}
|
||||
inSelectionRange={isSelected}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={onMediaAction}
|
||||
favorited={isFavorite}
|
||||
share={{ type: "artist", artistId: artist.id }}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 items-center gap-3 overflow-hidden px-4 py-2.5 text-left text-sm transition-colors",
|
||||
isSelected ? "text-primary-foreground" : ""
|
||||
)}
|
||||
>
|
||||
<ArtistAvatar artist={artist} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">
|
||||
{artist.name}
|
||||
</span>
|
||||
</button>
|
||||
<MediaContextMenu {...menu} />
|
||||
</div>
|
||||
</MediaContextMenuArea>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -106,7 +114,7 @@ export function ArtistsView({
|
||||
return sortedArtists[0]?.id ?? ""
|
||||
}, [artistId, sortedArtists])
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { runArtistAction } = useMediaActions()
|
||||
|
||||
const selectedArtist = sortedArtists.find(
|
||||
|
||||
@@ -15,6 +15,13 @@ import {
|
||||
} from "lucide-react"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -53,6 +60,28 @@ function shouldShowShare(
|
||||
return true
|
||||
}
|
||||
|
||||
// Lets the same items render inside a dropdown or a right-click menu.
|
||||
const MenuKindContext = React.createContext<"dropdown" | "context">("dropdown")
|
||||
|
||||
/** Menu item that works in both `MediaContextMenu` and `MediaContextMenuArea`. */
|
||||
export function MediaMenuItem(
|
||||
props: React.ComponentProps<typeof DropdownMenuItem>
|
||||
) {
|
||||
return React.use(MenuKindContext) === "context" ? (
|
||||
<ContextMenuItem {...props} />
|
||||
) : (
|
||||
<DropdownMenuItem {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
export function MediaMenuSeparator() {
|
||||
return React.use(MenuKindContext) === "context" ? (
|
||||
<ContextMenuSeparator />
|
||||
) : (
|
||||
<DropdownMenuSeparator />
|
||||
)
|
||||
}
|
||||
|
||||
function actionLabel(base: string, selectedCount: number) {
|
||||
return selectedCount > 1 ? `${base} (${selectedCount})` : base
|
||||
}
|
||||
@@ -83,86 +112,86 @@ export function MediaContextMenuItems({
|
||||
<>
|
||||
{showShare ? (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => void copyMediaShareLink(share!)}
|
||||
>
|
||||
Share
|
||||
<Share2 />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</MediaMenuItem>
|
||||
<MediaMenuSeparator />
|
||||
</>
|
||||
) : null}
|
||||
<DropdownMenuItem
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("playlist")}
|
||||
>
|
||||
{actionLabel(playlistLabel, selectedCount)}
|
||||
<ListPlus />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
</MediaMenuItem>
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("play-next")}
|
||||
>
|
||||
{actionLabel("Play Next", selectedCount)}
|
||||
<ListStart />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
</MediaMenuItem>
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("play-last")}
|
||||
>
|
||||
{actionLabel("Play Last", selectedCount)}
|
||||
<ListEnd />
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
</MediaMenuItem>
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("shuffle")}
|
||||
>
|
||||
{actionLabel("Shuffle", selectedCount)}
|
||||
<Shuffle />
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
{stationArtistId ? (
|
||||
<DropdownMenuItem
|
||||
<MediaMenuItem
|
||||
className="justify-between"
|
||||
onClick={() => onAction("create-station")}
|
||||
>
|
||||
Create Station
|
||||
<Shuffle />
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
) : null}
|
||||
{artist || album ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<MediaMenuSeparator />
|
||||
{artist ? (
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<MediaMenuItem asChild className="justify-between">
|
||||
<Link href={`/artist/${artist.id}`}>
|
||||
Go to Artist
|
||||
<MicVocal />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
) : null}
|
||||
{album ? (
|
||||
<DropdownMenuItem asChild className="justify-between">
|
||||
<MediaMenuItem asChild className="justify-between">
|
||||
<Link href={`/album/${album.id}`}>
|
||||
Go to Album
|
||||
<GalleryVerticalEnd />
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{showFavorite ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
variant={favorited ? "destructive" : "default"}
|
||||
className="justify-between"
|
||||
onClick={() => onAction("favorite")}
|
||||
>
|
||||
{actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)}
|
||||
<Star />
|
||||
</DropdownMenuItem>
|
||||
</MediaMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
@@ -194,6 +223,67 @@ export function mediaContextMenuTriggerClassName({
|
||||
)
|
||||
}
|
||||
|
||||
export type MediaContextMenuProps = {
|
||||
label: string
|
||||
selectedCount: number
|
||||
onOpenMenu: () => void
|
||||
onAction: (action: MediaContextAction) => void
|
||||
playlistLabel?: string
|
||||
showFavorite?: boolean
|
||||
favorited?: boolean
|
||||
stationArtistId?: string
|
||||
navigation?: MediaContextNavigation
|
||||
share?: MediaShareContext
|
||||
inSelectionRange?: boolean
|
||||
/** When false, the trigger uses default button/dropdown styling (page headers). */
|
||||
trackRowTrigger?: boolean
|
||||
triggerClassName?: string
|
||||
triggerVariant?: "ghost" | "secondary"
|
||||
triggerIconClassName?: string
|
||||
align?: "start" | "end"
|
||||
/** Extra items; use `MediaMenuItem` so they also work in the right-click menu. */
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `menu` (the props given to the row's `MediaContextMenu`) when
|
||||
* `children`, a single element such as a track row, is right-clicked.
|
||||
*/
|
||||
export function MediaContextMenuArea({
|
||||
menu,
|
||||
children,
|
||||
}: {
|
||||
menu: MediaContextMenuProps
|
||||
children: React.ReactElement
|
||||
}) {
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
menu.onOpenMenu()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
|
||||
<ContextMenuContent className="w-48">
|
||||
<MenuKindContext value="context">
|
||||
<MediaContextMenuItems
|
||||
selectedCount={menu.selectedCount}
|
||||
onAction={menu.onAction}
|
||||
playlistLabel={menu.playlistLabel}
|
||||
showFavorite={menu.showFavorite}
|
||||
favorited={menu.favorited}
|
||||
stationArtistId={menu.stationArtistId}
|
||||
navigation={menu.navigation}
|
||||
share={menu.share}
|
||||
/>
|
||||
{menu.children}
|
||||
</MenuKindContext>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function MediaContextMenu({
|
||||
label,
|
||||
selectedCount,
|
||||
@@ -212,26 +302,7 @@ export function MediaContextMenu({
|
||||
triggerIconClassName = "size-4",
|
||||
align = "end",
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
selectedCount: number
|
||||
onOpenMenu: () => void
|
||||
onAction: (action: MediaContextAction) => void
|
||||
playlistLabel?: string
|
||||
showFavorite?: boolean
|
||||
favorited?: boolean
|
||||
stationArtistId?: string
|
||||
navigation?: MediaContextNavigation
|
||||
share?: MediaShareContext
|
||||
inSelectionRange?: boolean
|
||||
/** When false, the trigger uses default button/dropdown styling (page headers). */
|
||||
trackRowTrigger?: boolean
|
||||
triggerClassName?: string
|
||||
triggerVariant?: "ghost" | "secondary"
|
||||
triggerIconClassName?: string
|
||||
align?: "start" | "end"
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
}: MediaContextMenuProps) {
|
||||
return (
|
||||
<DropdownMenu
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -102,7 +102,26 @@ type PlaybackContextValue = {
|
||||
dolbyAtmosSupported: boolean | null
|
||||
}
|
||||
|
||||
type PlaybackActions = Omit<
|
||||
PlaybackContextValue,
|
||||
| "queueSongIds"
|
||||
| "queueHistorySongIds"
|
||||
| "currentFormat"
|
||||
| "currentSong"
|
||||
| "shuffleEnabled"
|
||||
| "repeatEnabled"
|
||||
| "queueOpen"
|
||||
| "isPlaying"
|
||||
| "volume"
|
||||
| "dolbyAtmosSupported"
|
||||
>
|
||||
|
||||
const PlaybackContext = createContext<PlaybackContextValue | null>(null)
|
||||
// Long lists read these narrow contexts so playback state changes do not
|
||||
// re-render every row.
|
||||
const PlaybackActionsContext = createContext<PlaybackActions | null>(null)
|
||||
const CurrentSongIdContext = createContext<Id<"songs"> | null>(null)
|
||||
const IsPlayingContext = createContext(false)
|
||||
const PlaybackProgressContext = createContext<{
|
||||
currentTime: number
|
||||
duration: number
|
||||
@@ -301,6 +320,22 @@ export function usePlayback() {
|
||||
return context
|
||||
}
|
||||
|
||||
export function usePlaybackActions() {
|
||||
const context = useContext(PlaybackActionsContext)
|
||||
if (!context) {
|
||||
throw new Error("usePlaybackActions must be used within PlaybackProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
export function useCurrentSongId() {
|
||||
return useContext(CurrentSongIdContext)
|
||||
}
|
||||
|
||||
export function useIsPlaying() {
|
||||
return useContext(IsPlayingContext)
|
||||
}
|
||||
|
||||
export function usePlaybackProgress() {
|
||||
const context = useContext(PlaybackProgressContext)
|
||||
if (!context) {
|
||||
@@ -1361,17 +1396,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
: null
|
||||
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
const actions = useMemo<PlaybackActions>(
|
||||
() => ({
|
||||
queueSongIds: playback.queue,
|
||||
queueHistorySongIds: playback.history,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
setQueueOpen,
|
||||
toggleQueueOpen,
|
||||
setIsPlaying,
|
||||
@@ -1395,15 +1421,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
playback,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
toggleQueueOpen,
|
||||
setVolume,
|
||||
playInOrder,
|
||||
@@ -1425,6 +1444,31 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
]
|
||||
)
|
||||
|
||||
const value = useMemo<PlaybackContextValue>(
|
||||
() => ({
|
||||
...actions,
|
||||
queueSongIds: playback.queue,
|
||||
queueHistorySongIds: playback.history,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
shuffleEnabled: playback.shuffleEnabled,
|
||||
repeatEnabled: playback.repeatEnabled,
|
||||
queueOpen,
|
||||
isPlaying: isPlaybackActive,
|
||||
volume,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
actions,
|
||||
playback,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
dolbyAtmosSupported,
|
||||
]
|
||||
)
|
||||
@@ -1435,10 +1479,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
|
||||
return (
|
||||
<PlaybackContext.Provider value={value}>
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
<PlaybackActionsContext.Provider value={actions}>
|
||||
<CurrentSongIdContext.Provider value={currentSongId}>
|
||||
<IsPlayingContext.Provider value={isPlaybackActive}>
|
||||
<PlaybackContext.Provider value={value}>
|
||||
<PlaybackProgressContext.Provider value={progressValue}>
|
||||
{children}
|
||||
</PlaybackProgressContext.Provider>
|
||||
</PlaybackContext.Provider>
|
||||
</IsPlayingContext.Provider>
|
||||
</CurrentSongIdContext.Provider>
|
||||
</PlaybackActionsContext.Provider>
|
||||
)
|
||||
}
|
||||
@@ -33,6 +33,39 @@ import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatDuration } from "@/lib/format-duration"
|
||||
|
||||
function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) {
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
|
||||
const maxDuration = Math.max(duration, 1)
|
||||
|
||||
return (
|
||||
<Slider
|
||||
className={cn(
|
||||
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
|
||||
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
|
||||
)}
|
||||
min={0}
|
||||
max={maxDuration}
|
||||
step={0.1}
|
||||
value={[displayTime]}
|
||||
disabled={!hasActiveSong}
|
||||
onValueChange={([value]) => {
|
||||
setIsSeeking(true)
|
||||
setSeekValue(value)
|
||||
}}
|
||||
onValueCommit={([value]) => {
|
||||
seekTo(value)
|
||||
setIsSeeking(false)
|
||||
}}
|
||||
aria-label="Seek"
|
||||
aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlayerBar() {
|
||||
const {
|
||||
currentSong,
|
||||
@@ -51,16 +84,10 @@ export function PlayerBar() {
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const { currentTime, duration, seekTo } = usePlaybackProgress()
|
||||
const { state, isMobile } = useSidebar()
|
||||
const [isSeeking, setIsSeeking] = React.useState(false)
|
||||
const [seekValue, setSeekValue] = React.useState(0)
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
const hasActiveSong = Boolean(currentSong)
|
||||
const sidebarExpanded = !isMobile && state === "expanded"
|
||||
const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0
|
||||
const maxDuration = Math.max(duration, 1)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -192,27 +219,7 @@ export function PlayerBar() {
|
||||
/>
|
||||
)}
|
||||
<div className="absolute inset-x-0 -bottom-1">
|
||||
<Slider
|
||||
className={cn(
|
||||
"h-3 flex-1 [&_[data-slot=slider-range]]:bg-current/80 [&_[data-slot=slider-thumb]]:size-2 [&_[data-slot=slider-thumb]]:border-current [&_[data-slot=slider-thumb]]:bg-current [&_[data-slot=slider-thumb]]:opacity-0 focus-within:[&_[data-slot=slider-thumb]]:opacity-100 hover:[&_[data-slot=slider-thumb]]:opacity-100 [&_[data-slot=slider-track]]:h-[3px] [&_[data-slot=slider-track]]:bg-current/30 md:[&_[data-slot=slider-track]]:h-0.5",
|
||||
!hasActiveSong && "[&_[data-slot=slider-thumb]]:hidden"
|
||||
)}
|
||||
min={0}
|
||||
max={maxDuration}
|
||||
step={0.1}
|
||||
value={[displayTime]}
|
||||
disabled={!hasActiveSong}
|
||||
onValueChange={([value]) => {
|
||||
setIsSeeking(true)
|
||||
setSeekValue(value)
|
||||
}}
|
||||
onValueCommit={([value]) => {
|
||||
seekTo(value)
|
||||
setIsSeeking(false)
|
||||
}}
|
||||
aria-label="Seek"
|
||||
aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`}
|
||||
/>
|
||||
<PlayerSeekBar hasActiveSong={Boolean(currentSong)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
MediaContextMenuItems,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -30,7 +30,7 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddPlaylistToPlaylist } = useAddToPlaylist()
|
||||
const { playPlaylist } = usePlayback()
|
||||
const { playPlaylist } = usePlaybackActions()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
|
||||
async function handleCardAction(action: MediaContextAction) {
|
||||
|
||||
@@ -10,13 +10,17 @@ import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
} from "@/components/media-context-menu"
|
||||
import { TrackRow } from "@/components/track-row"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenuItem,
|
||||
@@ -39,6 +43,7 @@ import { rememberSongs } from "@/lib/song-cache"
|
||||
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
|
||||
|
||||
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
||||
const estimatePlaylistRowSize = () => 60
|
||||
|
||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const router = useRouter()
|
||||
@@ -50,14 +55,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: currentUser?._id === playlist.owner.id
|
||||
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
|
||||
useFavorites()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const {
|
||||
currentSong,
|
||||
playInOrder,
|
||||
playShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
playFromSong,
|
||||
} = usePlayback()
|
||||
} = usePlaybackActions()
|
||||
const { runSongsAction } = useMediaActions()
|
||||
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
||||
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
|
||||
@@ -186,10 +191,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: [songId]
|
||||
|
||||
if (isFavorites) {
|
||||
const succeeded = await toggleSongsFavorite(
|
||||
ids as Id<"songs">[],
|
||||
true
|
||||
)
|
||||
const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true)
|
||||
if (!succeeded) return
|
||||
return
|
||||
}
|
||||
@@ -202,7 +204,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
setPlaylistSongs((current) =>
|
||||
current.filter((song) => !ids.includes(song.id))
|
||||
)
|
||||
toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song")
|
||||
toast.success(
|
||||
ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song"
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to remove song"
|
||||
@@ -291,7 +295,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
<PageHeader openApp />
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="pb-28">
|
||||
<div className="mx-auto w-full min-w-0 max-w-9/10">
|
||||
<div className="mx-auto w-full max-w-9/10 min-w-0">
|
||||
<div className="flex flex-col gap-8 px-6 pt-6 pb-8 sm:flex-row sm:items-end">
|
||||
<div className="relative mx-auto aspect-square w-full max-w-60 shrink-0 overflow-hidden rounded-lg ring-1 ring-foreground/10 sm:mx-0">
|
||||
{isFavorites ? (
|
||||
@@ -421,40 +425,49 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
</div>
|
||||
</div>
|
||||
{filteredSongs.length > 0 ? (
|
||||
filteredSongs.map((song, index) => (
|
||||
<TrackRow
|
||||
key={song.id}
|
||||
variant="playlist"
|
||||
song={song}
|
||||
index={index}
|
||||
trackNumber={playlistPositionById.get(song.id)}
|
||||
isActive={song.id === activeTrackId}
|
||||
isNowPlaying={currentSong?.id === song.id}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
isDragging={dragIndex === index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites
|
||||
? "Unfavorite"
|
||||
: isOwner
|
||||
? "Remove from Playlist"
|
||||
: undefined
|
||||
}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={handleRemoveSong}
|
||||
onDragStart={canReorder ? setDragIndex : undefined}
|
||||
onDrop={canReorder ? handleDrop : undefined}
|
||||
/>
|
||||
))
|
||||
<VirtualList
|
||||
count={filteredSongs.length}
|
||||
estimateSize={estimatePlaylistRowSize}
|
||||
getItemKey={(index) => filteredSongs[index].id}
|
||||
// Keep the drag source mounted so its drop still lands.
|
||||
keepMounted={dragIndex}
|
||||
renderItem={(index) => {
|
||||
const song = filteredSongs[index]
|
||||
return (
|
||||
<TrackRow
|
||||
variant="playlist"
|
||||
song={song}
|
||||
index={index}
|
||||
trackNumber={playlistPositionById.get(song.id)}
|
||||
isActive={song.id === activeTrackId}
|
||||
isNowPlaying={currentSongId === song.id}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
isDragging={dragIndex === index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites
|
||||
? "Unfavorite"
|
||||
: isOwner
|
||||
? "Remove from Playlist"
|
||||
: undefined
|
||||
}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={handleRemoveSong}
|
||||
onDragStart={canReorder ? setDragIndex : undefined}
|
||||
onDrop={canReorder ? handleDrop : undefined}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className="px-6 py-8 text-sm text-muted-foreground">
|
||||
{normalizedQuery
|
||||
|
||||
@@ -8,6 +8,8 @@ import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
MediaContextMenuArea,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
@@ -38,52 +40,57 @@ export function SearchSongItem({ song }: { song: BrowseSong }) {
|
||||
}
|
||||
}
|
||||
|
||||
const menu: MediaContextMenuProps = {
|
||||
label: `More options for ${song.title}`,
|
||||
stationArtistId: song.artist.id,
|
||||
selectedCount: 1,
|
||||
onOpenMenu: () => {},
|
||||
onAction: handleAction,
|
||||
favorited: isSongFavorite(song.id),
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
},
|
||||
share: {
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
},
|
||||
triggerClassName:
|
||||
"size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100",
|
||||
triggerVariant: "ghost",
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
|
||||
<Link
|
||||
href={`/album/${song.album.id}`}
|
||||
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
|
||||
>
|
||||
<Image
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="44px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</Link>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link href={`/album/${song.album.id}`} className="hover:underline">
|
||||
<p className="truncate text-sm font-medium">{song.title}</p>
|
||||
</Link>
|
||||
<MediaContextMenuArea menu={menu}>
|
||||
<div className="group flex items-center gap-3 rounded-lg px-1 py-1.5 transition-colors hover:bg-muted/50">
|
||||
<Link
|
||||
href={`/artist/${song.artist.id}`}
|
||||
className="text-muted-foreground hover:text-foreground hover:underline"
|
||||
href={`/album/${song.album.id}`}
|
||||
className="relative size-11 shrink-0 overflow-hidden rounded ring-1 ring-foreground/10"
|
||||
>
|
||||
<p className="truncate text-sm">{song.artist.name}</p>
|
||||
<Image
|
||||
src={albumCoverUrl(song.album.id)}
|
||||
alt={song.album.title}
|
||||
fill
|
||||
sizes="44px"
|
||||
className="object-cover"
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<MediaContextMenu
|
||||
label={`More options for ${song.title}`}
|
||||
stationArtistId={song.artist.id}
|
||||
selectedCount={1}
|
||||
onOpenMenu={() => {}}
|
||||
onAction={handleAction}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
share={{
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
}}
|
||||
triggerClassName="size-8 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 data-[state=open]:opacity-100"
|
||||
triggerVariant="ghost"
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link href={`/album/${song.album.id}`} className="hover:underline">
|
||||
<p className="truncate text-sm font-medium">{song.title}</p>
|
||||
</Link>
|
||||
<Link
|
||||
href={`/artist/${song.artist.id}`}
|
||||
className="text-muted-foreground hover:text-foreground hover:underline"
|
||||
>
|
||||
<p className="truncate text-sm">{song.artist.name}</p>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<MediaContextMenu {...menu} />
|
||||
</div>
|
||||
</MediaContextMenuArea>
|
||||
)
|
||||
}
|
||||
@@ -13,8 +13,9 @@ import {
|
||||
import { ArrowUpDown } from "lucide-react"
|
||||
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { LibraryTrackListHeader, TrackRow } from "@/components/track-row"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -43,10 +44,11 @@ type SortKey = "title" | "artist" | "album"
|
||||
type SortDirection = "asc" | "desc"
|
||||
|
||||
const SONGS_PAGE_SIZE = 50
|
||||
const estimateSongRowSize = () => 56
|
||||
|
||||
export function SongsView() {
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
const { playFromLibrarySong } = usePlayback()
|
||||
const { playFromLibrarySong } = usePlaybackActions()
|
||||
const [sortKey, setSortKey] = useState<SortKey>("title")
|
||||
const [sortDirection, setSortDirection] =
|
||||
useState<SortDirection>("asc")
|
||||
@@ -127,6 +129,7 @@ export function SongsView() {
|
||||
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
|
||||
[toggleSongFavorite]
|
||||
)
|
||||
const getSongKey = useCallback((index: number) => songs[index].id, [songs])
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return (
|
||||
@@ -197,7 +200,7 @@ export function SongsView() {
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-viewport]>div]:block!">
|
||||
<div
|
||||
className="w-full pb-28"
|
||||
onClick={(event) => {
|
||||
@@ -207,24 +210,28 @@ export function SongsView() {
|
||||
}}
|
||||
>
|
||||
<LibraryTrackListHeader />
|
||||
{songs.map((song, index) => (
|
||||
<TrackRow
|
||||
key={song.id}
|
||||
variant="library"
|
||||
song={song}
|
||||
index={index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
))}
|
||||
<VirtualList
|
||||
count={songs.length}
|
||||
estimateSize={estimateSongRowSize}
|
||||
getItemKey={getSongKey}
|
||||
renderItem={(index) => (
|
||||
<TrackRow
|
||||
variant="library"
|
||||
song={songs[index]}
|
||||
index={index}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(songs[index].id)}
|
||||
selectedCount={selectedCount}
|
||||
selectionStationArtistId={selectedStationArtistId}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onPlay={handleRowPlay}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
ref={loadMoreRef}
|
||||
className="flex items-center justify-center py-4"
|
||||
|
||||
@@ -3,10 +3,62 @@
|
||||
import type { MouseEvent } from "react"
|
||||
import { AudioLines, Pause, Play } from "lucide-react"
|
||||
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useIsPlaying,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function trackButtonClassName(showPlay: boolean, inRange: boolean) {
|
||||
return 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"
|
||||
)
|
||||
}
|
||||
|
||||
function NowPlayingButton({
|
||||
title,
|
||||
inRange,
|
||||
}: {
|
||||
title: string
|
||||
inRange: boolean
|
||||
}) {
|
||||
const isPlaying = useIsPlaying()
|
||||
const { setIsPlaying } = usePlaybackActions()
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={trackButtonClassName(true, inRange)}
|
||||
aria-label={isPlaying ? `Pause ${title}` : `Play ${title}`}
|
||||
onClick={(event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
setIsPlaying(!isPlaying)
|
||||
}}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity group-hover:opacity-0">
|
||||
{isPlaying ? (
|
||||
<AudioLines className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{isPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export function TrackNumberPlayButton({
|
||||
displayTrack,
|
||||
title,
|
||||
@@ -22,26 +74,7 @@ export function TrackNumberPlayButton({
|
||||
inRange: boolean
|
||||
onPlay: () => void
|
||||
}) {
|
||||
const { isPlaying, setIsPlaying } = usePlayback()
|
||||
const showPlay = isActive || isNowPlaying
|
||||
const isCurrentlyPlaying = isNowPlaying && isPlaying
|
||||
|
||||
const buttonClassName = 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"
|
||||
)
|
||||
|
||||
const handleClick = (event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
if (isNowPlaying) {
|
||||
setIsPlaying(!isPlaying)
|
||||
return
|
||||
}
|
||||
onPlay()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -59,35 +92,17 @@ export function TrackNumberPlayButton({
|
||||
{displayTrack}
|
||||
</span>
|
||||
{isNowPlaying ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={buttonClassName}
|
||||
aria-label={isCurrentlyPlaying ? `Pause ${title}` : `Play ${title}`}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<span className="absolute inset-0 flex items-center justify-center transition-opacity group-hover:opacity-0">
|
||||
{isCurrentlyPlaying ? (
|
||||
<AudioLines className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
|
||||
{isCurrentlyPlaying ? (
|
||||
<Pause className="size-4" />
|
||||
) : (
|
||||
<Play className="size-4 fill-current" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
<NowPlayingButton title={title} inRange={inRange} />
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={buttonClassName}
|
||||
className={trackButtonClassName(showPlay, inRange)}
|
||||
aria-label={`Play ${title}`}
|
||||
onClick={handleClick}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onPlay()
|
||||
}}
|
||||
>
|
||||
<Play className="size-4 fill-current" />
|
||||
</Button>
|
||||
|
||||
@@ -7,15 +7,15 @@ import { Music2, Play, Star, Trash2 } from "lucide-react"
|
||||
|
||||
import {
|
||||
MediaContextMenu,
|
||||
MediaContextMenuArea,
|
||||
MediaMenuItem,
|
||||
MediaMenuSeparator,
|
||||
type MediaContextAction,
|
||||
type MediaContextMenuProps,
|
||||
} from "@/components/media-context-menu"
|
||||
import { PlaybackSongMeta } from "@/components/playback-song-meta"
|
||||
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { albumCoverUrl } from "@/lib/cover-urls"
|
||||
import {
|
||||
ALBUM_TRACK_ROW,
|
||||
@@ -68,7 +68,7 @@ export type TrackRowProps = {
|
||||
onPlay: (index: number) => void
|
||||
onToggleFavorite?: (songId: string) => void
|
||||
onPrepareContextMenu?: (songId: string) => void
|
||||
/** Renders the "more options" menu when provided. */
|
||||
/** Renders the "more options" and right-click menus when provided. */
|
||||
onMediaAction?: (action: MediaContextAction, songId: string) => void
|
||||
onRemove?: (songId: string) => void
|
||||
/** Makes the row draggable when provided. */
|
||||
@@ -304,38 +304,40 @@ function TrackRowComponent({
|
||||
</span>
|
||||
)
|
||||
|
||||
const menu = onMediaAction ? (
|
||||
<MediaContextMenu
|
||||
label={`More options for ${song.title}`}
|
||||
stationArtistId={inRange ? selectionStationArtistId : song.artist.id}
|
||||
selectedCount={inRange && selectedCount > 0 ? selectedCount : 1}
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={() => onPrepareContextMenu?.(song.id)}
|
||||
onAction={(action) => onMediaAction(action, song.id)}
|
||||
playlistLabel={playlistLabel}
|
||||
showFavorite={showFavoriteInMenu}
|
||||
favorited={isFavorite}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
share={{ type: "song", albumId: song.album.id, songId: song.id }}
|
||||
>
|
||||
{removeLabel && onRemove ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={() => onRemove(song.id)}
|
||||
>
|
||||
{removeLabel}
|
||||
<Trash2 />
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</MediaContextMenu>
|
||||
) : null
|
||||
// Shared by the "more options" button and the right-click menu.
|
||||
const menuProps: MediaContextMenuProps | null = onMediaAction
|
||||
? {
|
||||
label: `More options for ${song.title}`,
|
||||
stationArtistId: inRange ? selectionStationArtistId : song.artist.id,
|
||||
selectedCount: inRange && selectedCount > 0 ? selectedCount : 1,
|
||||
inSelectionRange: inRange,
|
||||
onOpenMenu: () => onPrepareContextMenu?.(song.id),
|
||||
onAction: (action) => onMediaAction(action, song.id),
|
||||
playlistLabel,
|
||||
showFavorite: showFavoriteInMenu,
|
||||
favorited: isFavorite,
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
},
|
||||
share: { type: "song", albumId: song.album.id, songId: song.id },
|
||||
children:
|
||||
removeLabel && onRemove ? (
|
||||
<>
|
||||
<MediaMenuSeparator />
|
||||
<MediaMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={() => onRemove(song.id)}
|
||||
>
|
||||
{removeLabel}
|
||||
<Trash2 />
|
||||
</MediaMenuItem>
|
||||
</>
|
||||
) : null,
|
||||
}
|
||||
: null
|
||||
const menu = menuProps ? <MediaContextMenu {...menuProps} /> : null
|
||||
|
||||
let content: React.ReactNode
|
||||
switch (variant) {
|
||||
@@ -491,14 +493,21 @@ function TrackRowComponent({
|
||||
</>
|
||||
)
|
||||
|
||||
return variant === "queue" ? (
|
||||
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
|
||||
{children}
|
||||
</li>
|
||||
const shell =
|
||||
variant === "queue" ? (
|
||||
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
|
||||
{children}
|
||||
</li>
|
||||
) : (
|
||||
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
|
||||
return menuProps ? (
|
||||
<MediaContextMenuArea menu={menuProps}>{shell}</MediaContextMenuArea>
|
||||
) : (
|
||||
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
|
||||
{children}
|
||||
</div>
|
||||
shell
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
defaultRangeExtractor,
|
||||
useVirtualizer,
|
||||
type Range,
|
||||
} from "@tanstack/react-virtual"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const scrollViewportSelector = '[data-slot="scroll-area-viewport"]'
|
||||
|
||||
/**
|
||||
* Renders only the visible items of a list placed inside a `ScrollArea`.
|
||||
* The list may sit below other content in the same viewport.
|
||||
*/
|
||||
export function VirtualList({
|
||||
count,
|
||||
estimateSize,
|
||||
getItemKey,
|
||||
renderItem,
|
||||
overscan = 10,
|
||||
keepMounted = null,
|
||||
className,
|
||||
}: {
|
||||
count: number
|
||||
estimateSize: (index: number) => number
|
||||
getItemKey: (index: number) => string
|
||||
renderItem: (index: number) => React.ReactNode
|
||||
overscan?: number
|
||||
/** Index rendered even when off screen, e.g. the source of a drag. */
|
||||
keepMounted?: number | null
|
||||
className?: string
|
||||
}) {
|
||||
const listRef = React.useRef<HTMLDivElement>(null)
|
||||
const [scrollMargin, setScrollMargin] = React.useState(0)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
const list = listRef.current
|
||||
const viewport = list?.closest<HTMLElement>(scrollViewportSelector)
|
||||
if (!list || !viewport) return
|
||||
|
||||
const measure = () => {
|
||||
setScrollMargin(
|
||||
Math.round(
|
||||
list.getBoundingClientRect().top -
|
||||
viewport.getBoundingClientRect().top +
|
||||
viewport.scrollTop
|
||||
)
|
||||
)
|
||||
}
|
||||
const observer = new ResizeObserver(measure)
|
||||
observer.observe(viewport)
|
||||
if (viewport.firstElementChild) {
|
||||
observer.observe(viewport.firstElementChild)
|
||||
}
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const getScrollElement = () =>
|
||||
listRef.current?.closest<HTMLElement>(scrollViewportSelector) ?? null
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count,
|
||||
getScrollElement,
|
||||
// The virtualizer scrolls to this offset on attach. Keep the viewport's
|
||||
// current position so `ScrollRestoration` is not reset to the top.
|
||||
initialOffset: () => getScrollElement()?.scrollTop ?? 0,
|
||||
estimateSize,
|
||||
getItemKey,
|
||||
overscan,
|
||||
scrollMargin,
|
||||
rangeExtractor: React.useCallback(
|
||||
(range: Range) => {
|
||||
const indexes = defaultRangeExtractor(range)
|
||||
if (
|
||||
keepMounted !== null &&
|
||||
keepMounted < range.count &&
|
||||
!indexes.includes(keepMounted)
|
||||
) {
|
||||
indexes.push(keepMounted)
|
||||
indexes.sort((a, b) => a - b)
|
||||
}
|
||||
return indexes
|
||||
},
|
||||
[keepMounted]
|
||||
),
|
||||
})
|
||||
|
||||
// The virtualizer caches its offset across a detach. Clear it so a
|
||||
// re-attach (e.g. StrictMode's effect replay) re-reads `initialOffset`
|
||||
// instead of scrolling back to a stale position.
|
||||
React.useLayoutEffect(
|
||||
() => () => {
|
||||
virtualizer.scrollOffset = null
|
||||
},
|
||||
[virtualizer]
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={listRef}
|
||||
className={cn("relative w-full", className)}
|
||||
style={{ height: virtualizer.getTotalSize() }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((item) => (
|
||||
<div
|
||||
key={item.key}
|
||||
data-index={item.index}
|
||||
ref={virtualizer.measureElement}
|
||||
className="absolute top-0 left-0 w-full"
|
||||
style={{ transform: `translateY(${item.start - scrollMargin}px)` }}
|
||||
>
|
||||
{renderItem(item.index)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,13 +9,18 @@ import {
|
||||
type PaginatedQueryReference,
|
||||
} from "convex/react"
|
||||
import type { FunctionReference } from "convex/server"
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react"
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react"
|
||||
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { queryCacheKey } from "@otunes/convex/client/cached-query"
|
||||
import { readCache, subscribeCache, writeCache } from "@/lib/persistent-cache"
|
||||
|
||||
const MAX_CACHED_PAGINATED_ITEMS = 200
|
||||
const MAX_RESTORED_PAGINATED_ITEMS = 1000
|
||||
|
||||
// Items loaded per paginated query this session, so a remount (e.g. back
|
||||
// navigation) loads as much as before and scroll restoration can reach it.
|
||||
const loadedItemCounts = new Map<string, number>()
|
||||
|
||||
const noopUnsubscribe = () => {}
|
||||
|
||||
@@ -65,6 +70,7 @@ export function useCachedQuery<Query extends FunctionReference<"query">>(
|
||||
/**
|
||||
* `usePaginatedQuery` that shows the first persisted pages while the first live
|
||||
* page loads. `isCached` is true while those persisted results are shown.
|
||||
* Remounts start with as many items as were last loaded this session.
|
||||
*/
|
||||
export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||
query: Query,
|
||||
@@ -72,15 +78,28 @@ export function useCachedPaginatedQuery<Query extends PaginatedQueryReference>(
|
||||
options: { initialNumItems: number }
|
||||
) {
|
||||
const scope = useCacheScope()
|
||||
const result = usePaginatedQuery(query, args, options)
|
||||
const key =
|
||||
args === "skip"
|
||||
? null
|
||||
: `${queryCacheKey(scope, query, args as Record<string, unknown>)}:pages`
|
||||
// Fixed per key: `usePaginatedQuery` restarts when this changes.
|
||||
const initialNumItems = useMemo(
|
||||
() =>
|
||||
Math.max(
|
||||
options.initialNumItems,
|
||||
Math.min(
|
||||
(key && loadedItemCounts.get(key)) || 0,
|
||||
MAX_RESTORED_PAGINATED_ITEMS
|
||||
)
|
||||
),
|
||||
[key, options.initialNumItems]
|
||||
)
|
||||
const result = usePaginatedQuery(query, args, { initialNumItems })
|
||||
const cached = useCachedValue<PaginatedQueryItem<Query>[]>(key)
|
||||
|
||||
useEffect(() => {
|
||||
if (key && result.status !== "LoadingFirstPage") {
|
||||
loadedItemCounts.set(key, result.results.length)
|
||||
writeCache(key, result.results.slice(0, MAX_CACHED_PAGINATED_ITEMS))
|
||||
}
|
||||
}, [key, result.status, result.results])
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import * as React from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import type { MediaContextAction } from "@/components/media-context-menu"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
|
||||
@@ -29,7 +29,7 @@ function queueActionMessage(action: QueueMediaAction, count: number) {
|
||||
|
||||
export function useQueueMediaActions() {
|
||||
const { addToQueueNext, addToQueueLast, playShuffled, playArtistShuffled } =
|
||||
usePlayback()
|
||||
usePlaybackActions()
|
||||
|
||||
const runQueueAction = React.useCallback(
|
||||
async (action: QueueMediaAction, songIds: Id<"songs">[]) => {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
/**
|
||||
* Returns a function with a stable identity that always calls the latest
|
||||
* `callback`. Only call it from event handlers, never during render.
|
||||
*/
|
||||
export function useStableCallback<Args extends unknown[], Result>(
|
||||
callback: (...args: Args) => Result
|
||||
): (...args: Args) => Result {
|
||||
const callbackRef = React.useRef(callback)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
callbackRef.current = callback
|
||||
})
|
||||
|
||||
return React.useCallback((...args: Args) => callbackRef.current(...args), [])
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
"@base-ui/react": "^1.5.0",
|
||||
"@convex-dev/auth": "^0.0.93",
|
||||
"@otunes/convex": "workspace:*",
|
||||
"@tanstack/react-virtual": "^3.14.26",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
|
||||
Generated
+20
@@ -179,6 +179,9 @@ importers:
|
||||
'@otunes/convex':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/convex
|
||||
'@tanstack/react-virtual':
|
||||
specifier: ^3.14.26
|
||||
version: 3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
class-variance-authority:
|
||||
specifier: ^0.7.1
|
||||
version: 0.7.1
|
||||
@@ -2657,6 +2660,15 @@ packages:
|
||||
'@tailwindcss/postcss@4.3.2':
|
||||
resolution: {integrity: sha512-rjVWYCa7Ngbi5AarT6k8TkxUG3Wl1QKzHdIZVsjZSzf36Jmo2IKZt/NHRAwly8oDkbBOH0YTu+CHuf9jPxMc+g==}
|
||||
|
||||
'@tanstack/react-virtual@3.14.26':
|
||||
resolution: {integrity: sha512-HUDlfsrYH6ko5xH56L62Mcl/uzT+AGVNMHFuDNqDJMdZWc1AQa2oeVKNUvZ/RWBZQ4TYtyQerFrNvLnp39h65A==}
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
|
||||
'@tanstack/virtual-core@3.19.11':
|
||||
resolution: {integrity: sha512-/5iHb0RHBvj8Di59FDs4ESNm45jls33aZAi4zccVXZjc/6ZvwQP6nzEYeT6weXjTf9E6/vrp2JhYWRyO+ZP13A==}
|
||||
|
||||
'@tokenizer/inflate@0.4.1':
|
||||
resolution: {integrity: sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -9464,6 +9476,14 @@ snapshots:
|
||||
postcss: 8.5.16
|
||||
tailwindcss: 4.3.2
|
||||
|
||||
'@tanstack/react-virtual@3.14.26(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
|
||||
dependencies:
|
||||
'@tanstack/virtual-core': 3.19.11
|
||||
react: 19.3.1
|
||||
react-dom: 19.3.1(react@19.3.1)
|
||||
|
||||
'@tanstack/virtual-core@3.19.11': {}
|
||||
|
||||
'@tokenizer/inflate@0.4.1':
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
|
||||
Reference in new issue
Block a user