From 735129984151a4b00ea4075769e6c63234649280 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 13:59:46 -0500 Subject: [PATCH 1/2] perf(web): virtualize song lists and narrow playback subscriptions Co-Authored-By: Claude Opus 5.5 --- apps/web/components/album-card.tsx | 4 +- apps/web/components/album-view.tsx | 11 +- apps/web/components/artist-view.tsx | 4 +- apps/web/components/artists-view.tsx | 4 +- apps/web/components/playback-provider.tsx | 94 ++++-- apps/web/components/player-bar.tsx | 61 ++-- apps/web/components/playlist-card.tsx | 4 +- apps/web/components/playlist-view.tsx | 270 ++++++++++-------- apps/web/components/songs-view.tsx | 207 +++++++------- .../components/track-number-play-button.tsx | 103 ++++--- apps/web/components/virtual-list.tsx | 120 ++++++++ apps/web/hooks/use-queue-media-actions.ts | 4 +- apps/web/hooks/use-stable-callback.ts | 19 ++ apps/web/package.json | 1 + pnpm-lock.yaml | 20 ++ 15 files changed, 598 insertions(+), 328 deletions(-) create mode 100644 apps/web/components/virtual-list.tsx create mode 100644 apps/web/hooks/use-stable-callback.ts diff --git a/apps/web/components/album-card.tsx b/apps/web/components/album-card.tsx index b17a7a6..076ac12 100644 --- a/apps/web/components/album-card.tsx +++ b/apps/web/components/album-card.tsx @@ -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) diff --git a/apps/web/components/album-view.tsx b/apps/web/components/album-view.tsx index ec3ce45..4d55e83 100644 --- a/apps/web/components/album-view.tsx +++ b/apps/web/components/album-view.tsx @@ -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">, diff --git a/apps/web/components/artist-view.tsx b/apps/web/components/artist-view.tsx index 4b2fbf9..c5b568b 100644 --- a/apps/web/components/artist-view.tsx +++ b/apps/web/components/artist-view.tsx @@ -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() diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx index 554e35d..2322989 100644 --- a/apps/web/components/artists-view.tsx +++ b/apps/web/components/artists-view.tsx @@ -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( diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 524a611..3754d09 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -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(null) +// Long lists read these narrow contexts so playback state changes do not +// re-render every row. +const PlaybackActionsContext = createContext(null) +const CurrentSongIdContext = createContext | 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( + const actions = useMemo( () => ({ - 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( + () => ({ + ...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 ( - - - {children} - - + + + + + + {children} + + + + + ) } diff --git a/apps/web/components/player-bar.tsx b/apps/web/components/player-bar.tsx index ad8e8e0..6e28e99 100644 --- a/apps/web/components/player-bar.tsx +++ b/apps/web/components/player-bar.tsx @@ -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 ( + { + 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 (
)}
- { - setIsSeeking(true) - setSeekValue(value) - }} - onValueCommit={([value]) => { - seekTo(value) - setIsSeeking(false) - }} - aria-label="Seek" - aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`} - /> +
diff --git a/apps/web/components/playlist-card.tsx b/apps/web/components/playlist-card.tsx index 8f94976..2e796df 100644 --- a/apps/web/components/playlist-card.tsx +++ b/apps/web/components/playlist-card.tsx @@ -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) { diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index 57ceaa8..01b50d4 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -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)} /> {song.title} @@ -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({ onRemove(song.id)} > {removeLabel} @@ -265,7 +273,7 @@ function PlaylistSongRow({ ) -} +}) 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() ) - 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 }) { {filteredSongs.length > 0 ? ( - filteredSongs.map((song, index) => ( - 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}` - ) - } - /> - )) + { + const song = filteredSongs[index] + const selected = isSelected(song.id) + return ( + 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} + /> + ) + }} + /> ) : (

{normalizedQuery diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx index 066fb5b..b2bb036 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -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 ( - 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" > -

{ event.stopPropagation() - onToggleFavorite() + onToggleFavorite(song.id) }} >
- + {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({ /> - - + ) -} +}) 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("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() {

) : null} - +
{ if (event.target === event.currentTarget) { clearSelection() } }} > - - - - -
-
- - - Name -
- - Artist - - - Album - -
- - Time - - -
- - - - - {songs.map((song, index) => ( +
+
+ + + Name +
+ + Artist + + + Album + +
+ + Time + + +
+ { + const song = songs[index] + const selected = isSelected(song.id) + return ( 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} /> - ))} - -
+ ) + }} + />
{ + event.stopPropagation() + setIsPlaying(!isPlaying) + }} + > + + {isPlaying ? ( + + ) : ( + + )} + + + {isPlaying ? ( + + ) : ( + + )} + + + ) +} + 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 (
{isNowPlaying ? ( - + ) : ( diff --git a/apps/web/components/virtual-list.tsx b/apps/web/components/virtual-list.tsx new file mode 100644 index 0000000..66f0e63 --- /dev/null +++ b/apps/web/components/virtual-list.tsx @@ -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(null) + const [scrollMargin, setScrollMargin] = React.useState(0) + + React.useLayoutEffect(() => { + const list = listRef.current + const viewport = list?.closest(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(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 ( +
+ {virtualizer.getVirtualItems().map((item) => ( +
+ {renderItem(item.index)} +
+ ))} +
+ ) +} diff --git a/apps/web/hooks/use-queue-media-actions.ts b/apps/web/hooks/use-queue-media-actions.ts index 2837a81..b69d9f8 100644 --- a/apps/web/hooks/use-queue-media-actions.ts +++ b/apps/web/hooks/use-queue-media-actions.ts @@ -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">[]) => { diff --git a/apps/web/hooks/use-stable-callback.ts b/apps/web/hooks/use-stable-callback.ts new file mode 100644 index 0000000..e216f3d --- /dev/null +++ b/apps/web/hooks/use-stable-callback.ts @@ -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( + 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), []) +} diff --git a/apps/web/package.json b/apps/web/package.json index 1c7cd4a..f943371 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -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", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4631b7d..5866a70 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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 -- 2.54.1 From 9c1536578b93c4b29a0c6808ce4ddf66eab08574 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 14:37:38 -0500 Subject: [PATCH 2/2] feat(web): right-click menus on track rows and deep Songs scroll restore Co-Authored-By: Claude Opus 5.5 --- apps/web/components/album-view.tsx | 216 +++++++++---------- apps/web/components/artists-view.tsx | 60 +++--- apps/web/components/media-context-menu.tsx | 155 ++++++++++---- apps/web/components/playlist-view.tsx | 185 ++++++++-------- apps/web/components/search-song-item.tsx | 91 ++++---- apps/web/components/songs-view.tsx | 232 +++++++++++---------- apps/web/hooks/use-cached-query.ts | 23 +- 7 files changed, 543 insertions(+), 419 deletions(-) diff --git a/apps/web/components/album-view.tsx b/apps/web/components/album-view.tsx index 4d55e83..d82bcda 100644 --- a/apps/web/components/album-view.tsx +++ b/apps/web/components/album-view.tsx @@ -22,6 +22,8 @@ import { copyAlbumLink } from "@/lib/media-links" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + type MediaContextMenuProps, } from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" @@ -142,117 +144,121 @@ function TrackRow({ track.track > 0 ? track.track : sectionIndex + 1 const inRange = isInSelectionRange(selectionPosition) + const menu: MediaContextMenuProps = { + label: `More options for ${track.title}`, + stationArtistId: artist.id, + selectedCount, + inSelectionRange: inRange, + onOpenMenu: onPrepareContextMenu, + onAction: (action) => onMediaAction(action, track.id), + favorited: isFavorite, + navigation: { + artist: { id: artist.id }, + album: { id: albumId }, + }, + share: { + type: "song", + albumId, + songId: track.id, + }, + } + return ( -
{ - event.preventDefault() - onPlay() - }} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault() - onSelect(event as unknown as React.MouseEvent) - } - }} - className={cn( - "group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors", - inRange && "text-primary-foreground" - )} - > - - {!inRange && isActive ? : null} - {!inRange && !isActive ? : null} +
{ + event.preventDefault() + onPlay() + }} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault() + onSelect(event as unknown as React.MouseEvent) + } + }} + className={cn( + "group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors", + inRange && "text-primary-foreground" + )} > -
- -
- - - -
-
{track.title}
- {track.artists ? ( -

- {track.artists.join(", ")} -

- ) : null} -
- - + {!inRange && isActive ? : null} + {!inRange && !isActive ? : null} +
- {formatDuration(track.durationSeconds)} - +
+ +
- onMediaAction(action, track.id)} - favorited={isFavorite} - navigation={{ - artist: { id: artist.id }, - album: { id: albumId }, - }} - share={{ - type: "song", - albumId, - songId: track.id, - }} - /> + + +
+
{track.title}
+ {track.artists ? ( +

+ {track.artists.join(", ")} +

+ ) : null} +
+ + + {formatDuration(track.durationSeconds)} + + + +
-
+ ) } diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx index 2322989..a1a0938 100644 --- a/apps/web/components/artists-view.tsx +++ b/apps/web/components/artists-view.tsx @@ -14,6 +14,8 @@ import { useFavorites } from "@/components/favorites-provider" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + type MediaContextMenuProps, } from "@/components/media-context-menu" import { usePlaybackActions } from "@/components/playback-provider" import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" @@ -55,36 +57,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 ( -
- - {}} - onAction={onMediaAction} - favorited={isFavorite} - share={{ type: "artist", artistId: artist.id }} - /> -
+ + +
+ ) } diff --git a/apps/web/components/media-context-menu.tsx b/apps/web/components/media-context-menu.tsx index d216401..032dac0 100644 --- a/apps/web/components/media-context-menu.tsx +++ b/apps/web/components/media-context-menu.tsx @@ -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 +) { + return React.use(MenuKindContext) === "context" ? ( + + ) : ( + + ) +} + +export function MediaMenuSeparator() { + return React.use(MenuKindContext) === "context" ? ( + + ) : ( + + ) +} + function actionLabel(base: string, selectedCount: number) { return selectedCount > 1 ? `${base} (${selectedCount})` : base } @@ -83,86 +112,86 @@ export function MediaContextMenuItems({ <> {showShare ? ( <> - void copyMediaShareLink(share!)} > Share - - + + ) : null} - onAction("playlist")} > {actionLabel(playlistLabel, selectedCount)} - - - + + onAction("play-next")} > {actionLabel("Play Next", selectedCount)} - - + onAction("play-last")} > {actionLabel("Play Last", selectedCount)} - - + onAction("shuffle")} > {actionLabel("Shuffle", selectedCount)} - + {stationArtistId ? ( - onAction("create-station")} > Create Station - + ) : null} {artist || album ? ( <> - + {artist ? ( - + Go to Artist - + ) : null} {album ? ( - + Go to Album - + ) : null} ) : null} {showFavorite ? ( <> - - + onAction("favorite")} > {actionLabel(favorited ? "Unfavorite" : "Favorite", selectedCount)} - + ) : 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 ( + { + if (open) { + menu.onOpenMenu() + } + }} + > + {children} + + + + {menu.children} + + + + ) +} + 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 ( { diff --git a/apps/web/components/playlist-view.tsx b/apps/web/components/playlist-view.tsx index 01b50d4..a5da623 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -20,6 +20,10 @@ import { TrackNumberPlayButton } from "@/components/track-number-play-button" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + MediaMenuItem, + MediaMenuSeparator, + type MediaContextMenuProps, } from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { @@ -177,101 +181,104 @@ const PlaylistSongRow = React.memo(function PlaylistSongRow({ const select = (event: React.MouseEvent) => onSelect(song.id, index, event) const inRange = isInSelectionRange(selectionPosition) + const menu: MediaContextMenuProps = { + label: `More options for ${song.title}`, + stationArtistId: stationArtist, + selectedCount, + inSelectionRange: inRange, + onOpenMenu: () => onPrepareContextMenu(song.id), + onAction: (action) => onMediaAction(action, song.id), + playlistLabel: ADD_TO_ANOTHER_PLAYLIST, + 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: canRemove ? ( + <> + + onRemove(song.id)} + > + {removeLabel} + + + + ) : null, + } + return ( -
onDragStart(index, event)} - onDragOver={onDragOver} - onDrop={(event) => onDrop(index, event)} - onMouseDown={onPointerDown} - onClick={select} - onDoubleClick={(event) => { - event.preventDefault() - play() - }} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault() - select(event as unknown as React.MouseEvent) - } - }} - className={cn( - "group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors", - inRange && "text-primary-foreground", - isDragging && "opacity-50" - )} - > - - {!inRange && isActive ? : null} - {!inRange && !isActive ? : null} +
onDragStart(index, event)} + onDragOver={onDragOver} + onDrop={(event) => onDrop(index, event)} + onMouseDown={onPointerDown} + onClick={select} + onDoubleClick={(event) => { + event.preventDefault() + play() + }} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault() + select(event as unknown as React.MouseEvent) + } + }} + className={cn( + "group relative w-full cursor-pointer select-none py-2.5 text-left text-sm transition-colors", + inRange && "text-primary-foreground", + isDragging && "opacity-50" + )} > - onToggleFavorite(song.id)} - /> - - - - {song.title} - - + {!inRange && isActive ? : null} + {!inRange && !isActive ? : null} +
- {formatDuration(song.durationSeconds)} - + onToggleFavorite(song.id)} + /> - onPrepareContextMenu(song.id)} - onAction={(action) => onMediaAction(action, song.id)} - playlistLabel={ADD_TO_ANOTHER_PLAYLIST} - 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, - }} - > - {canRemove ? ( - <> - - onRemove(song.id)} - > - {removeLabel} - - - - ) : null} - + + + {song.title} + + + {formatDuration(song.durationSeconds)} + + + +
-
+ ) }) diff --git a/apps/web/components/search-song-item.tsx b/apps/web/components/search-song-item.tsx index 136d8ee..b4bfe05 100644 --- a/apps/web/components/search-song-item.tsx +++ b/apps/web/components/search-song-item.tsx @@ -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 ( -
- - {song.album.title} - - -
- -

{song.title}

- + +
-

{song.artist.name}

+ {song.album.title} -
- {}} - 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" - /> -
+
+ +

{song.title}

+ + +

{song.artist.name}

+ +
+ + +
+ ) } diff --git a/apps/web/components/songs-view.tsx b/apps/web/components/songs-view.tsx index b2bb036..0646849 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -13,6 +13,8 @@ import { usePlaybackActions } from "@/components/playback-provider" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + type MediaContextMenuProps, } from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { @@ -141,124 +143,128 @@ const SongRow = memo(function SongRow({ ? "text-primary-foreground hover:text-primary-foreground/80 hover:underline" : "text-muted-foreground hover:text-foreground hover:underline" + const menu: MediaContextMenuProps = { + label: `More options for ${song.title}`, + stationArtistId: stationArtist, + selectedCount, + align: "end", + inSelectionRange: inRange, + onOpenMenu: () => onPrepareContextMenu(song.id), + onAction: (action) => onMediaAction(action, song.id), + favorited: isFavorite, + navigation: { + artist: { id: song.artist.id }, + album: { id: song.album.id }, + }, + share: { + type: "song", + albumId: song.album.id, + songId: song.id, + }, + } + return ( -
onSelect(song.id, index, event)} - onDoubleClick={(event) => { - event.preventDefault() - play() - }} - className="group cursor-pointer select-none whitespace-nowrap text-sm transition-colors has-aria-expanded:bg-muted/50" - > -
- - {!inRange ? : null} + +
onSelect(song.id, index, event)} + onDoubleClick={(event) => { + event.preventDefault() + play() + }} + className="group cursor-pointer select-none whitespace-nowrap text-sm transition-colors has-aria-expanded:bg-muted/50" + >
-
-
- -
- - - {song.title} - {song.explicit ? ( - - E - - ) : null} - -
-
- event.stopPropagation()} - > - {song.artist.name} - -
-
- event.stopPropagation()} - > - {song.album.title} - -
-
- + {!inRange ? : null} +
- {formatDuration(song.durationSeconds)} - - onPrepareContextMenu(song.id)} - onAction={(action) => onMediaAction(action, song.id)} - favorited={isFavorite} - navigation={{ - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }} - share={{ - type: "song", - albumId: song.album.id, - songId: song.id, - }} - /> +
+
+ +
+ + + {song.title} + {song.explicit ? ( + + E + + ) : null} + +
+
+ event.stopPropagation()} + > + {song.artist.name} + +
+
+ event.stopPropagation()} + > + {song.album.title} + +
+
+ + {formatDuration(song.durationSeconds)} + + +
-
-
+
+
) }) diff --git a/apps/web/hooks/use-cached-query.ts b/apps/web/hooks/use-cached-query.ts index 87da8ff..98950ca 100644 --- a/apps/web/hooks/use-cached-query.ts +++ b/apps/web/hooks/use-cached-query.ts @@ -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() const noopUnsubscribe = () => {} @@ -65,6 +70,7 @@ export function useCachedQuery>( /** * `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: Query, @@ -72,15 +78,28 @@ export function useCachedPaginatedQuery( options: { initialNumItems: number } ) { const scope = useCacheScope() - const result = usePaginatedQuery(query, args, options) const key = args === "skip" ? null : `${queryCacheKey(scope, query, args as Record)}: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[]>(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]) -- 2.54.1