perf(web): virtualize song lists and narrow playback subscriptions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dce66b7697
commit
7351299841
15 files changed
+598
-328
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)
|
||||
|
||||
@@ -13,7 +13,10 @@ import { TrackNumberPlayButton } from "@/components/track-number-play-button"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { copyAlbumLink } from "@/lib/media-links"
|
||||
|
||||
import {
|
||||
@@ -268,8 +271,8 @@ export function AlbumView({
|
||||
toggleAlbumFavorite,
|
||||
favoriteSongs,
|
||||
} = useFavorites()
|
||||
const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
|
||||
usePlayback()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const albumSongIds = React.useMemo(
|
||||
() => album.tracks.map((track) => track.id as Id<"songs">),
|
||||
@@ -543,7 +546,7 @@ export function AlbumView({
|
||||
prepareContextMenu(track.id)
|
||||
}
|
||||
onMediaAction={handleMediaAction}
|
||||
isNowPlaying={currentSong?.id === track.id}
|
||||
isNowPlaying={currentSongId === track.id}
|
||||
onPlay={() =>
|
||||
void playFromSong(
|
||||
track.id as Id<"songs">,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useConvex } from "convex/react"
|
||||
import { useCacheScope } from "@/components/persistent-cache-provider"
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { AlbumCard } from "@/components/album-card"
|
||||
import { FavoriteMediaButton } from "@/components/favorite-media-button"
|
||||
@@ -35,7 +35,7 @@ export function ArtistView({
|
||||
}) {
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
const convex = useConvex()
|
||||
const cacheScope = useCacheScope()
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
MediaContextMenu,
|
||||
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 { Button } from "@/components/ui/button"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
@@ -114,7 +114,7 @@ export function ArtistsView({
|
||||
const cacheScope = useCacheScope()
|
||||
const { openAddArtistToPlaylist } = useAddToPlaylist()
|
||||
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
|
||||
const { playArtist, playArtistShuffled } = usePlayback()
|
||||
const { playArtist, playArtistShuffled } = usePlaybackActions()
|
||||
const { runQueueAction } = useQueueMediaActions()
|
||||
|
||||
const selectedArtist = sortedArtists.find(
|
||||
|
||||
@@ -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) {
|
||||
@@ -1360,17 +1395,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,
|
||||
@@ -1394,15 +1420,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
skipToQueueIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
dolbyAtmosSupported,
|
||||
}),
|
||||
[
|
||||
playback,
|
||||
currentSong,
|
||||
currentFormat,
|
||||
queueOpen,
|
||||
isPlaybackActive,
|
||||
volume,
|
||||
toggleQueueOpen,
|
||||
setVolume,
|
||||
playInOrder,
|
||||
@@ -1424,6 +1443,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,
|
||||
]
|
||||
)
|
||||
@@ -1434,10 +1478,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>
|
||||
)
|
||||
}
|
||||
@@ -39,6 +39,39 @@ function formatDuration(seconds: number): string {
|
||||
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -57,16 +90,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
|
||||
@@ -198,27 +225,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) {
|
||||
|
||||
@@ -11,7 +11,10 @@ import { toast } from "sonner"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import {
|
||||
useCurrentSongId,
|
||||
usePlaybackActions,
|
||||
} from "@/components/playback-provider"
|
||||
import { MediaCollectionFooter } from "@/components/media-collection-footer"
|
||||
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
|
||||
import {
|
||||
@@ -24,8 +27,10 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
|
||||
import { useStableCallback } from "@/hooks/use-stable-callback"
|
||||
import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
@@ -48,6 +53,7 @@ import {
|
||||
} from "@/lib/selection-range-styles"
|
||||
|
||||
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
|
||||
const estimatePlaylistRowSize = () => 60
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
@@ -117,7 +123,7 @@ function PlaylistSongCover({
|
||||
)
|
||||
}
|
||||
|
||||
function PlaylistSongRow({
|
||||
const PlaylistSongRow = React.memo(function PlaylistSongRow({
|
||||
song,
|
||||
index,
|
||||
isOwner,
|
||||
@@ -152,21 +158,23 @@ function PlaylistSongRow({
|
||||
selectedCount: number
|
||||
stationArtist?: string
|
||||
isDragging: boolean
|
||||
onSelect: (event: React.MouseEvent) => void
|
||||
onSelect: (songId: string, index: number, event: React.MouseEvent) => void
|
||||
onPointerDown: (event: React.MouseEvent) => void
|
||||
onToggleFavorite: () => void
|
||||
onPrepareContextMenu: () => void
|
||||
onToggleFavorite: (songId: string) => void
|
||||
onPrepareContextMenu: (songId: string) => void
|
||||
onMediaAction: (action: MediaContextAction, songId: string) => void
|
||||
onRemove: () => void
|
||||
onDragStart: (event: React.DragEvent) => void
|
||||
onRemove: (songId: string) => void
|
||||
onDragStart: (index: number, event: React.DragEvent) => void
|
||||
onDragOver: (event: React.DragEvent) => void
|
||||
onDrop: (event: React.DragEvent) => void
|
||||
onDrop: (index: number, event: React.DragEvent) => void
|
||||
showFavoriteInMenu?: boolean
|
||||
removeLabel?: string
|
||||
isNowPlaying: boolean
|
||||
onPlay: () => void
|
||||
onPlay: (songId: string) => void
|
||||
}) {
|
||||
const displayTrack = index + 1
|
||||
const play = () => onPlay(song.id)
|
||||
const select = (event: React.MouseEvent) => onSelect(song.id, index, event)
|
||||
const inRange = isInSelectionRange(selectionPosition)
|
||||
|
||||
return (
|
||||
@@ -174,19 +182,19 @@ function PlaylistSongRow({
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
draggable={isOwner}
|
||||
onDragStart={onDragStart}
|
||||
onDragStart={(event) => onDragStart(index, event)}
|
||||
onDragOver={onDragOver}
|
||||
onDrop={onDrop}
|
||||
onDrop={(event) => onDrop(index, event)}
|
||||
onMouseDown={onPointerDown}
|
||||
onClick={onSelect}
|
||||
onClick={select}
|
||||
onDoubleClick={(event) => {
|
||||
event.preventDefault()
|
||||
onPlay()
|
||||
play()
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault()
|
||||
onSelect(event as unknown as React.MouseEvent)
|
||||
select(event as unknown as React.MouseEvent)
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
@@ -205,7 +213,7 @@ function PlaylistSongRow({
|
||||
song={song}
|
||||
inRange={inRange}
|
||||
isFavorite={isFavorite}
|
||||
onToggleFavorite={onToggleFavorite}
|
||||
onToggleFavorite={() => onToggleFavorite(song.id)}
|
||||
/>
|
||||
|
||||
<TrackNumberPlayButton
|
||||
@@ -214,7 +222,7 @@ function PlaylistSongRow({
|
||||
isActive={isActive}
|
||||
isNowPlaying={isNowPlaying}
|
||||
inRange={inRange}
|
||||
onPlay={onPlay}
|
||||
onPlay={play}
|
||||
/>
|
||||
|
||||
<span className={ALBUM_TRACK_TITLE}>{song.title}</span>
|
||||
@@ -233,7 +241,7 @@ function PlaylistSongRow({
|
||||
stationArtistId={stationArtist}
|
||||
selectedCount={selectedCount}
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={onPrepareContextMenu}
|
||||
onOpenMenu={() => onPrepareContextMenu(song.id)}
|
||||
onAction={(action) => onMediaAction(action, song.id)}
|
||||
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
|
||||
showFavorite={showFavoriteInMenu}
|
||||
@@ -254,7 +262,7 @@ function PlaylistSongRow({
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
className="justify-between"
|
||||
onClick={onRemove}
|
||||
onClick={() => onRemove(song.id)}
|
||||
>
|
||||
{removeLabel}
|
||||
<Trash2 />
|
||||
@@ -265,7 +273,7 @@ function PlaylistSongRow({
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const router = useRouter()
|
||||
@@ -282,14 +290,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
toggleSongsFavorite,
|
||||
favoriteSongs: addFavoriteSongs,
|
||||
} = useFavorites()
|
||||
const currentSongId = useCurrentSongId()
|
||||
const {
|
||||
currentSong,
|
||||
playInOrder,
|
||||
playShuffled,
|
||||
playPlaylist,
|
||||
playPlaylistShuffled,
|
||||
playFromSong,
|
||||
} = usePlayback()
|
||||
} = usePlaybackActions()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
|
||||
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
|
||||
@@ -302,9 +310,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
const [hiddenFavoriteIds, setHiddenFavoriteIds] = React.useState(
|
||||
() => new Set<string>()
|
||||
)
|
||||
const songs = isFavorites
|
||||
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
|
||||
: playlistSongs
|
||||
const songs = React.useMemo(
|
||||
() =>
|
||||
isFavorites
|
||||
? playlist.songs.filter((song) => !hiddenFavoriteIds.has(song.id))
|
||||
: playlistSongs,
|
||||
[isFavorites, playlist.songs, hiddenFavoriteIds, playlistSongs]
|
||||
)
|
||||
const [searchQuery, setSearchQuery] = React.useState("")
|
||||
const normalizedQuery = searchQuery.trim().toLowerCase()
|
||||
const filteredSongs = React.useMemo(
|
||||
@@ -384,31 +396,30 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
: []
|
||||
}
|
||||
|
||||
function handleMediaAction(
|
||||
action: MediaContextAction,
|
||||
fallbackSongId?: string
|
||||
) {
|
||||
const targetIds = resolveTargetIds(fallbackSongId)
|
||||
const handleMediaAction = useStableCallback(
|
||||
(action: MediaContextAction, fallbackSongId?: string) => {
|
||||
const targetIds = resolveTargetIds(fallbackSongId)
|
||||
|
||||
switch (action) {
|
||||
case "create-station": {
|
||||
const artistId = stationArtistId(songs, new Set(targetIds))
|
||||
if (artistId) void createStation(artistId)
|
||||
break
|
||||
switch (action) {
|
||||
case "create-station": {
|
||||
const artistId = stationArtistId(songs, new Set(targetIds))
|
||||
if (artistId) void createStation(artistId)
|
||||
break
|
||||
}
|
||||
case "favorite":
|
||||
void addFavoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
case "favorite":
|
||||
void addFavoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function handlePlaylistMediaAction(action: MediaContextAction) {
|
||||
const targetIds = songs.map((song) => song.id as Id<"songs">)
|
||||
@@ -499,6 +510,59 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
void persistOrder(previous, next)
|
||||
}
|
||||
|
||||
const canReorder = isOwner && !isFavorites && !normalizedQuery
|
||||
const getSongKey = React.useCallback(
|
||||
(index: number) => filteredSongs[index].id,
|
||||
[filteredSongs]
|
||||
)
|
||||
|
||||
// Stable row callbacks so memoized rows skip re-rendering.
|
||||
const handleRowSelect = useStableCallback(
|
||||
(songId: string, index: number, event: React.MouseEvent) => {
|
||||
handleSelect(songId, index, event)
|
||||
setActiveTrackId(songId)
|
||||
}
|
||||
)
|
||||
|
||||
const handleToggleFavorite = useStableCallback((songId: string) => {
|
||||
const wasFavorite = isSongFavorite(songId)
|
||||
void toggleSongFavorite(songId as Id<"songs">)
|
||||
if (isFavorites && wasFavorite) {
|
||||
setHiddenFavoriteIds((current) => new Set(current).add(songId))
|
||||
}
|
||||
})
|
||||
|
||||
const handleRemove = useStableCallback((songId: string) => {
|
||||
void handleRemoveSong(songId)
|
||||
})
|
||||
|
||||
const handleDragStart = useStableCallback(
|
||||
(index: number, event: React.DragEvent) => {
|
||||
if (!canReorder) return
|
||||
setDragIndex(index)
|
||||
event.dataTransfer.effectAllowed = "move"
|
||||
}
|
||||
)
|
||||
|
||||
const handleDragOver = useStableCallback((event: React.DragEvent) => {
|
||||
if (canReorder) event.preventDefault()
|
||||
})
|
||||
|
||||
const handleRowDrop = useStableCallback(
|
||||
(index: number, event: React.DragEvent) => {
|
||||
event.preventDefault()
|
||||
handleDrop(index)
|
||||
}
|
||||
)
|
||||
|
||||
const handlePlay = useStableCallback((songId: string) => {
|
||||
void playFromSong(
|
||||
songId as Id<"songs">,
|
||||
playlistSongIds,
|
||||
`playlist:${playlist.id}`
|
||||
)
|
||||
})
|
||||
|
||||
async function handleDeletePlaylist() {
|
||||
try {
|
||||
await deletePlaylist({
|
||||
@@ -676,77 +740,49 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
|
||||
</div>
|
||||
</div>
|
||||
{filteredSongs.length > 0 ? (
|
||||
filteredSongs.map((song, index) => (
|
||||
<PlaylistSongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
index={index}
|
||||
isOwner={isOwner && !isFavorites && !normalizedQuery}
|
||||
canRemove={isFavorites || isOwner}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites ? "Unfavorite" : "Remove from Playlist"
|
||||
}
|
||||
isActive={song.id === activeTrackId}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={
|
||||
isSelected(song.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
: 1
|
||||
}
|
||||
stationArtist={
|
||||
isSelected(song.id)
|
||||
? selectedStationArtistId
|
||||
: song.artist.id
|
||||
}
|
||||
isDragging={dragIndex === index}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(song.id, index, event)
|
||||
setActiveTrackId(song.id)
|
||||
}}
|
||||
onToggleFavorite={() => {
|
||||
const wasFavorite = isSongFavorite(song.id)
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
if (isFavorites && wasFavorite) {
|
||||
setHiddenFavoriteIds((current) => {
|
||||
const next = new Set(current)
|
||||
next.add(song.id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
}}
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={() => handleRemoveSong(song.id)}
|
||||
onDragStart={(event) => {
|
||||
if (normalizedQuery || isFavorites || !isOwner) {
|
||||
return
|
||||
}
|
||||
setDragIndex(index)
|
||||
event.dataTransfer.effectAllowed = "move"
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (normalizedQuery || isFavorites || !isOwner) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
handleDrop(index)
|
||||
}}
|
||||
isNowPlaying={currentSong?.id === song.id}
|
||||
onPlay={() =>
|
||||
void playFromSong(
|
||||
song.id as Id<"songs">,
|
||||
playlistSongIds,
|
||||
`playlist:${playlist.id}`
|
||||
)
|
||||
}
|
||||
/>
|
||||
))
|
||||
<VirtualList
|
||||
count={filteredSongs.length}
|
||||
estimateSize={estimatePlaylistRowSize}
|
||||
getItemKey={getSongKey}
|
||||
keepMounted={dragIndex}
|
||||
renderItem={(index) => {
|
||||
const song = filteredSongs[index]
|
||||
const selected = isSelected(song.id)
|
||||
return (
|
||||
<PlaylistSongRow
|
||||
song={song}
|
||||
index={index}
|
||||
isOwner={canReorder}
|
||||
canRemove={isFavorites || isOwner}
|
||||
showFavoriteInMenu={!isFavorites}
|
||||
removeLabel={
|
||||
isFavorites ? "Unfavorite" : "Remove from Playlist"
|
||||
}
|
||||
isActive={song.id === activeTrackId}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
selectedCount={
|
||||
selected && selectedCount > 0 ? selectedCount : 1
|
||||
}
|
||||
stationArtist={
|
||||
selected ? selectedStationArtistId : song.artist.id
|
||||
}
|
||||
isDragging={dragIndex === index}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={handleRowSelect}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onRemove={handleRemove}
|
||||
onDragStart={handleDragStart}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleRowDrop}
|
||||
isNowPlaying={currentSongId === song.id}
|
||||
onPlay={handlePlay}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className="px-6 py-8 text-sm text-muted-foreground">
|
||||
{normalizedQuery
|
||||
|
||||
+103
-104
@@ -2,14 +2,14 @@
|
||||
|
||||
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
|
||||
import { stationArtistId } from "@/lib/station-artist"
|
||||
import { useEffect, useMemo, useState, useRef, MouseEvent } from "react"
|
||||
import { memo, useCallback, useEffect, useMemo, useState, useRef, MouseEvent } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { ArrowUpDown, Play, Star } from "lucide-react"
|
||||
|
||||
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
|
||||
import { useFavorites } from "@/components/favorites-provider"
|
||||
import { usePlayback } from "@/components/playback-provider"
|
||||
import { usePlaybackActions } from "@/components/playback-provider"
|
||||
import {
|
||||
MediaContextMenu,
|
||||
type MediaContextAction,
|
||||
@@ -30,15 +30,9 @@ import { useTrackSelection } from "@/hooks/use-track-selection"
|
||||
import { SongListSkeleton } from "@/components/library-skeletons"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
import { VirtualList } from "@/components/virtual-list"
|
||||
import { useStableCallback } from "@/hooks/use-stable-callback"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import { cn } from "@/lib/utils"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
@@ -57,6 +51,7 @@ type SortKey = "title" | "artist" | "album"
|
||||
type SortDirection = "asc" | "desc"
|
||||
|
||||
const SONGS_PAGE_SIZE = 50
|
||||
const estimateSongRowSize = () => 56
|
||||
|
||||
const songRowLayout =
|
||||
"flex w-full items-center gap-x-4"
|
||||
@@ -111,8 +106,9 @@ function SongCover({
|
||||
)
|
||||
}
|
||||
|
||||
function SongRow({
|
||||
const SongRow = memo(function SongRow({
|
||||
song,
|
||||
index,
|
||||
isSelected,
|
||||
selectionPosition,
|
||||
isFavorite,
|
||||
@@ -126,34 +122,35 @@ function SongRow({
|
||||
onPlay,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
index: number
|
||||
isSelected: boolean
|
||||
selectionPosition: SelectionRangePosition
|
||||
isFavorite: boolean
|
||||
selectedCount: number
|
||||
stationArtist?: string
|
||||
onSelect: (event: MouseEvent) => void
|
||||
onSelect: (songId: string, index: number, event: MouseEvent) => void
|
||||
onPointerDown: (event: MouseEvent) => void
|
||||
onToggleFavorite: () => void
|
||||
onPrepareContextMenu: () => void
|
||||
onToggleFavorite: (songId: string) => void
|
||||
onPrepareContextMenu: (songId: string) => void
|
||||
onMediaAction: (action: MediaContextAction, songId: string) => void
|
||||
onPlay: () => void
|
||||
onPlay: (songId: string) => void
|
||||
}) {
|
||||
const play = () => onPlay(song.id)
|
||||
const inRange = isInSelectionRange(selectionPosition)
|
||||
const linkClass = inRange
|
||||
? "text-primary-foreground hover:text-primary-foreground/80 hover:underline"
|
||||
: "text-muted-foreground hover:text-foreground hover:underline"
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
<div
|
||||
onMouseDown={onPointerDown}
|
||||
onClick={onSelect}
|
||||
onClick={(event) => onSelect(song.id, index, event)}
|
||||
onDoubleClick={(event) => {
|
||||
event.preventDefault()
|
||||
onPlay()
|
||||
play()
|
||||
}}
|
||||
className="group cursor-pointer select-none border-none hover:bg-transparent"
|
||||
className="group cursor-pointer select-none whitespace-nowrap text-sm transition-colors has-aria-expanded:bg-muted/50"
|
||||
>
|
||||
<TableCell colSpan={4} className="p-0">
|
||||
<div
|
||||
className={cn(
|
||||
"relative py-2",
|
||||
@@ -184,7 +181,7 @@ function SongRow({
|
||||
}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onToggleFavorite()
|
||||
onToggleFavorite(song.id)
|
||||
}}
|
||||
>
|
||||
<Star
|
||||
@@ -195,7 +192,7 @@ function SongRow({
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
<SongCover song={song} inRange={inRange} onPlay={onPlay} />
|
||||
<SongCover song={song} inRange={inRange} onPlay={play} />
|
||||
<span className={ALBUM_TRACK_TITLE}>
|
||||
{song.title}
|
||||
{song.explicit ? (
|
||||
@@ -246,7 +243,7 @@ function SongRow({
|
||||
selectedCount={selectedCount}
|
||||
align="end"
|
||||
inSelectionRange={inRange}
|
||||
onOpenMenu={onPrepareContextMenu}
|
||||
onOpenMenu={() => onPrepareContextMenu(song.id)}
|
||||
onAction={(action) => onMediaAction(action, song.id)}
|
||||
favorited={isFavorite}
|
||||
navigation={{
|
||||
@@ -261,15 +258,14 @@ function SongRow({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
export function SongsView() {
|
||||
const { openAddToPlaylist } = useAddToPlaylist()
|
||||
const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
|
||||
const { playFromLibrarySong } = usePlayback()
|
||||
const { playFromLibrarySong } = usePlaybackActions()
|
||||
const { runQueueAction, createStation } = useQueueMediaActions()
|
||||
const [sortKey, setSortKey] = useState<SortKey>("title")
|
||||
const [sortDirection, setSortDirection] =
|
||||
@@ -332,32 +328,49 @@ export function SongsView() {
|
||||
[songs, selectedIds]
|
||||
)
|
||||
|
||||
function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) {
|
||||
const targetIds =
|
||||
selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
: fallbackSongId
|
||||
? [fallbackSongId]
|
||||
: []
|
||||
switch (action) {
|
||||
case "create-station": {
|
||||
const artistId = stationArtistId(songs, new Set(targetIds))
|
||||
if (artistId) void createStation(artistId)
|
||||
break
|
||||
const handleMediaAction = useStableCallback(
|
||||
(action: MediaContextAction, fallbackSongId?: string) => {
|
||||
const targetIds =
|
||||
selectedIds.size > 0
|
||||
? Array.from(selectedIds)
|
||||
: fallbackSongId
|
||||
? [fallbackSongId]
|
||||
: []
|
||||
switch (action) {
|
||||
case "create-station": {
|
||||
const artistId = stationArtistId(songs, new Set(targetIds))
|
||||
if (artistId) void createStation(artistId)
|
||||
break
|
||||
}
|
||||
case "favorite":
|
||||
void favoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
case "favorite":
|
||||
void favoriteSongs(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "playlist":
|
||||
openAddToPlaylist(targetIds as Id<"songs">[])
|
||||
break
|
||||
case "play-next":
|
||||
case "play-last":
|
||||
case "shuffle":
|
||||
void runQueueAction(action, targetIds as Id<"songs">[])
|
||||
break
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
const handleRowSelect = useStableCallback(handleSelect)
|
||||
const handleToggleFavorite = useCallback(
|
||||
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
|
||||
[toggleSongFavorite]
|
||||
)
|
||||
const handlePlay = useCallback(
|
||||
(songId: string) =>
|
||||
void playFromLibrarySong(songId as Id<"songs">, {
|
||||
sortKey,
|
||||
sortDirection,
|
||||
}),
|
||||
[playFromLibrarySong, sortKey, sortDirection]
|
||||
)
|
||||
const getSongKey = useCallback((index: number) => songs[index].id, [songs])
|
||||
|
||||
if (status === "LoadingFirstPage" && !isCached) {
|
||||
return (
|
||||
@@ -428,77 +441,63 @@ 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"
|
||||
className="w-full pb-28 text-sm"
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
clearSelection()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="border-none hover:bg-transparent">
|
||||
<TableHead colSpan={4} className="h-9 p-0 font-normal">
|
||||
<div className={cn(songRowLayout, TRACK_ROW_PADDING)}>
|
||||
<div className={nameColumnLayout}>
|
||||
<span aria-hidden />
|
||||
<span aria-hidden />
|
||||
<span className="text-xs text-muted-foreground">Name</span>
|
||||
</div>
|
||||
<span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
|
||||
Artist
|
||||
</span>
|
||||
<span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
|
||||
Album
|
||||
</span>
|
||||
<div className="min-w-4 flex-1" />
|
||||
<span className="shrink-0 text-right text-xs text-muted-foreground">
|
||||
Time
|
||||
</span>
|
||||
<span className="size-8 shrink-0" aria-hidden />
|
||||
</div>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{songs.map((song, index) => (
|
||||
<div className={cn(songRowLayout, TRACK_ROW_PADDING, "h-9")}>
|
||||
<div className={nameColumnLayout}>
|
||||
<span aria-hidden />
|
||||
<span aria-hidden />
|
||||
<span className="text-xs text-muted-foreground">Name</span>
|
||||
</div>
|
||||
<span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
|
||||
Artist
|
||||
</span>
|
||||
<span className={cn(songColumnClass, "text-xs text-muted-foreground")}>
|
||||
Album
|
||||
</span>
|
||||
<div className="min-w-4 flex-1" />
|
||||
<span className="shrink-0 text-right text-xs text-muted-foreground">
|
||||
Time
|
||||
</span>
|
||||
<span className="size-8 shrink-0" aria-hidden />
|
||||
</div>
|
||||
<VirtualList
|
||||
count={songs.length}
|
||||
estimateSize={estimateSongRowSize}
|
||||
getItemKey={getSongKey}
|
||||
renderItem={(index) => {
|
||||
const song = songs[index]
|
||||
const selected = isSelected(song.id)
|
||||
return (
|
||||
<SongRow
|
||||
key={song.id}
|
||||
song={song}
|
||||
isSelected={isSelected(song.id)}
|
||||
index={index}
|
||||
isSelected={selected}
|
||||
selectionPosition={selectionPositions[index]}
|
||||
isFavorite={isSongFavorite(song.id)}
|
||||
stationArtist={
|
||||
isSelected(song.id)
|
||||
? selectedStationArtistId
|
||||
: song.artist.id
|
||||
selected ? selectedStationArtistId : song.artist.id
|
||||
}
|
||||
selectedCount={
|
||||
isSelected(song.id) && selectedCount > 0
|
||||
? selectedCount
|
||||
: 1
|
||||
selected && selectedCount > 0 ? selectedCount : 1
|
||||
}
|
||||
onPointerDown={handlePointerDown}
|
||||
onSelect={(event) => {
|
||||
handleSelect(song.id, index, event)
|
||||
}}
|
||||
onToggleFavorite={() =>
|
||||
void toggleSongFavorite(song.id as Id<"songs">)
|
||||
}
|
||||
onPrepareContextMenu={() => prepareContextMenu(song.id)}
|
||||
onSelect={handleRowSelect}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onPrepareContextMenu={prepareContextMenu}
|
||||
onMediaAction={handleMediaAction}
|
||||
onPlay={() =>
|
||||
void playFromLibrarySong(song.id as Id<"songs">, {
|
||||
sortKey,
|
||||
sortDirection,
|
||||
})
|
||||
}
|
||||
onPlay={handlePlay}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<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>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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