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 5fc401c..e18b273 100644 --- a/apps/web/components/album-view.tsx +++ b/apps/web/components/album-view.tsx @@ -11,7 +11,10 @@ import { MediaCollectionFooter } from "@/components/media-collection-footer" import { FavoriteMediaButton } from "@/components/favorite-media-button" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { + useCurrentSongId, + usePlaybackActions, +} from "@/components/playback-provider" import { copyAlbumLink } from "@/lib/media-links" import { @@ -105,8 +108,8 @@ export function AlbumView({ toggleSongFavorite, toggleAlbumFavorite, } = useFavorites() - const { currentSong, playFromSong, playAlbum, playAlbumShuffled } = - usePlayback() + const currentSongId = useCurrentSongId() + const { playFromSong, playAlbum, playAlbumShuffled } = usePlaybackActions() const { runSongsAction } = useMediaActions() const albumSongIds = React.useMemo( () => album.tracks.map((track) => track.id as Id<"songs">), @@ -366,7 +369,7 @@ export function AlbumView({ isFavorite={isSongFavorite(track.id)} selectedCount={selectedCount} selectionStationArtistId={album.artist.id} - isNowPlaying={currentSong?.id === track.id} + isNowPlaying={currentSongId === track.id} onPointerDown={handlePointerDown} onSelect={handleRowSelect} onPlay={handleRowPlay} diff --git a/apps/web/components/artist-view.tsx b/apps/web/components/artist-view.tsx index 5bab21e..5ab9e1e 100644 --- a/apps/web/components/artist-view.tsx +++ b/apps/web/components/artist-view.tsx @@ -6,7 +6,7 @@ import Image from "next/image" import { Play, Shuffle } from "lucide-react" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { useMediaActions } from "@/hooks/use-media-actions" import { AlbumCard } from "@/components/album-card" import { FavoriteMediaButton } from "@/components/favorite-media-button" @@ -26,7 +26,7 @@ export function ArtistView({ albums: BrowseAlbum[] }) { const { isArtistFavorite, toggleArtistFavorite } = useFavorites() - const { playArtist, playArtistShuffled } = usePlayback() + const { playArtist, playArtistShuffled } = usePlaybackActions() const { runArtistAction } = useMediaActions() return ( diff --git a/apps/web/components/artists-view.tsx b/apps/web/components/artists-view.tsx index 48b3d8a..f10b361 100644 --- a/apps/web/components/artists-view.tsx +++ b/apps/web/components/artists-view.tsx @@ -11,8 +11,10 @@ import { useFavorites } from "@/components/favorites-provider" import { MediaContextMenu, type MediaContextAction, + MediaContextMenuArea, + type MediaContextMenuProps, } from "@/components/media-context-menu" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { useMediaActions } from "@/hooks/use-media-actions" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" @@ -50,36 +52,42 @@ function ArtistListItem({ onSelect: () => void onMediaAction: (action: MediaContextAction) => void }) { + const menu: MediaContextMenuProps = { + label: `More options for ${artist.name}`, + selectedCount: albumCount, + inSelectionRange: isSelected, + onOpenMenu: () => {}, + onAction: onMediaAction, + favorited: isFavorite, + share: { type: "artist", artistId: artist.id }, + } + return ( -
- - {}} - onAction={onMediaAction} - favorited={isFavorite} - share={{ type: "artist", artistId: artist.id }} - /> -
+ + + + ) } @@ -106,7 +114,7 @@ export function ArtistsView({ return sortedArtists[0]?.id ?? "" }, [artistId, sortedArtists]) const { isArtistFavorite, toggleArtistFavorite } = useFavorites() - const { playArtist, playArtistShuffled } = usePlayback() + const { playArtist, playArtistShuffled } = usePlaybackActions() const { runArtistAction } = useMediaActions() const selectedArtist = sortedArtists.find( 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/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 99471b7..79f9446 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) { @@ -1361,17 +1396,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, @@ -1395,15 +1421,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipToQueueIndex, skipNext, skipPrevious, - dolbyAtmosSupported, }), [ - playback, - currentSong, - currentFormat, - queueOpen, - isPlaybackActive, - volume, toggleQueueOpen, setVolume, playInOrder, @@ -1425,6 +1444,31 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { skipToQueueIndex, skipNext, skipPrevious, + ] + ) + + const value = useMemo( + () => ({ + ...actions, + queueSongIds: playback.queue, + queueHistorySongIds: playback.history, + currentSong, + currentFormat, + shuffleEnabled: playback.shuffleEnabled, + repeatEnabled: playback.repeatEnabled, + queueOpen, + isPlaying: isPlaybackActive, + volume, + dolbyAtmosSupported, + }), + [ + actions, + playback, + currentSong, + currentFormat, + queueOpen, + isPlaybackActive, + volume, dolbyAtmosSupported, ] ) @@ -1435,10 +1479,16 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { ) return ( - - - {children} - - + + + + + + {children} + + + + + ) } diff --git a/apps/web/components/player-bar.tsx b/apps/web/components/player-bar.tsx index 82b7def..720f459 100644 --- a/apps/web/components/player-bar.tsx +++ b/apps/web/components/player-bar.tsx @@ -33,6 +33,39 @@ import { albumCoverUrl } from "@/lib/cover-urls" import { cn } from "@/lib/utils" import { formatDuration } from "@/lib/format-duration" +function PlayerSeekBar({ hasActiveSong }: { hasActiveSong: boolean }) { + const { currentTime, duration, seekTo } = usePlaybackProgress() + const [isSeeking, setIsSeeking] = React.useState(false) + const [seekValue, setSeekValue] = React.useState(0) + + const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0 + const maxDuration = Math.max(duration, 1) + + return ( + { + setIsSeeking(true) + setSeekValue(value) + }} + onValueCommit={([value]) => { + seekTo(value) + setIsSeeking(false) + }} + aria-label="Seek" + aria-valuetext={`${formatDuration(displayTime)} of ${formatDuration(duration)}`} + /> + ) +} + export function PlayerBar() { const { currentSong, @@ -51,16 +84,10 @@ export function PlayerBar() { skipNext, skipPrevious, } = usePlayback() - const { currentTime, duration, seekTo } = usePlaybackProgress() const { state, isMobile } = useSidebar() - const [isSeeking, setIsSeeking] = React.useState(false) - const [seekValue, setSeekValue] = React.useState(0) const hasQueue = queueSongIds.length > 0 - const hasActiveSong = Boolean(currentSong) const sidebarExpanded = !isMobile && state === "expanded" - const displayTime = hasActiveSong ? (isSeeking ? seekValue : currentTime) : 0 - const maxDuration = Math.max(duration, 1) return (
)}
- { - 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 6dd6eaa..6889fd3 100644 --- a/apps/web/components/playlist-view.tsx +++ b/apps/web/components/playlist-view.tsx @@ -10,13 +10,17 @@ import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react" import { toast } from "sonner" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { + useCurrentSongId, + usePlaybackActions, +} from "@/components/playback-provider" import { MediaCollectionFooter } from "@/components/media-collection-footer" import { MediaContextMenu, type MediaContextAction, } from "@/components/media-context-menu" import { TrackRow } from "@/components/track-row" +import { VirtualList } from "@/components/virtual-list" import { Button } from "@/components/ui/button" import { DropdownMenuItem, @@ -39,6 +43,7 @@ import { rememberSongs } from "@/lib/song-cache" import { getSelectionRangePositions } from "@/lib/selection-range-styles" const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist" +const estimatePlaylistRowSize = () => 60 export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const router = useRouter() @@ -50,14 +55,14 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { : currentUser?._id === playlist.owner.id const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } = useFavorites() + const currentSongId = useCurrentSongId() const { - currentSong, playInOrder, playShuffled, playPlaylist, playPlaylistShuffled, playFromSong, - } = usePlayback() + } = usePlaybackActions() const { runSongsAction } = useMediaActions() const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs) @@ -186,10 +191,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { : [songId] if (isFavorites) { - const succeeded = await toggleSongsFavorite( - ids as Id<"songs">[], - true - ) + const succeeded = await toggleSongsFavorite(ids as Id<"songs">[], true) if (!succeeded) return return } @@ -202,7 +204,9 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { setPlaylistSongs((current) => current.filter((song) => !ids.includes(song.id)) ) - toast.success(ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song") + toast.success( + ids.length > 1 ? `Removed ${ids.length} songs` : "Removed song" + ) } catch (error) { toast.error( error instanceof Error ? error.message : "Failed to remove song" @@ -291,7 +295,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
-
+
{isFavorites ? ( @@ -421,40 +425,49 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
{filteredSongs.length > 0 ? ( - filteredSongs.map((song, index) => ( - - )) + filteredSongs[index].id} + // Keep the drag source mounted so its drop still lands. + keepMounted={dragIndex} + renderItem={(index) => { + const song = filteredSongs[index] + return ( + + ) + }} + /> ) : (

{normalizedQuery 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 2bdf0ae..b0404b7 100644 --- a/apps/web/components/songs-view.tsx +++ b/apps/web/components/songs-view.tsx @@ -13,8 +13,9 @@ import { import { ArrowUpDown } from "lucide-react" import { useFavorites } from "@/components/favorites-provider" -import { usePlayback } from "@/components/playback-provider" +import { usePlaybackActions } from "@/components/playback-provider" import { LibraryTrackListHeader, TrackRow } from "@/components/track-row" +import { VirtualList } from "@/components/virtual-list" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -43,10 +44,11 @@ type SortKey = "title" | "artist" | "album" type SortDirection = "asc" | "desc" const SONGS_PAGE_SIZE = 50 +const estimateSongRowSize = () => 56 export function SongsView() { const { isSongFavorite, toggleSongFavorite } = useFavorites() - const { playFromLibrarySong } = usePlayback() + const { playFromLibrarySong } = usePlaybackActions() const [sortKey, setSortKey] = useState("title") const [sortDirection, setSortDirection] = useState("asc") @@ -127,6 +129,7 @@ export function SongsView() { (songId: string) => void toggleSongFavorite(songId as Id<"songs">), [toggleSongFavorite] ) + const getSongKey = useCallback((index: number) => songs[index].id, [songs]) if (status === "LoadingFirstPage" && !isCached) { return ( @@ -197,7 +200,7 @@ export function SongsView() {

) : null} - +
{ @@ -207,24 +210,28 @@ export function SongsView() { }} > - {songs.map((song, index) => ( - - ))} + ( + + )} + />
{ + 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/track-row.tsx b/apps/web/components/track-row.tsx index 6fb653c..9cbb54a 100644 --- a/apps/web/components/track-row.tsx +++ b/apps/web/components/track-row.tsx @@ -7,15 +7,15 @@ import { Music2, Play, Star, Trash2 } from "lucide-react" import { MediaContextMenu, + MediaContextMenuArea, + MediaMenuItem, + MediaMenuSeparator, type MediaContextAction, + type MediaContextMenuProps, } from "@/components/media-context-menu" import { PlaybackSongMeta } from "@/components/playback-song-meta" import { TrackNumberPlayButton } from "@/components/track-number-play-button" import { Button } from "@/components/ui/button" -import { - DropdownMenuItem, - DropdownMenuSeparator, -} from "@/components/ui/dropdown-menu" import { albumCoverUrl } from "@/lib/cover-urls" import { ALBUM_TRACK_ROW, @@ -68,7 +68,7 @@ export type TrackRowProps = { onPlay: (index: number) => void onToggleFavorite?: (songId: string) => void onPrepareContextMenu?: (songId: string) => void - /** Renders the "more options" menu when provided. */ + /** Renders the "more options" and right-click menus when provided. */ onMediaAction?: (action: MediaContextAction, songId: string) => void onRemove?: (songId: string) => void /** Makes the row draggable when provided. */ @@ -304,38 +304,40 @@ function TrackRowComponent({ ) - const menu = onMediaAction ? ( - 0 ? selectedCount : 1} - inSelectionRange={inRange} - onOpenMenu={() => onPrepareContextMenu?.(song.id)} - onAction={(action) => onMediaAction(action, song.id)} - playlistLabel={playlistLabel} - showFavorite={showFavoriteInMenu} - favorited={isFavorite} - navigation={{ - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }} - share={{ type: "song", albumId: song.album.id, songId: song.id }} - > - {removeLabel && onRemove ? ( - <> - - onRemove(song.id)} - > - {removeLabel} - - - - ) : null} - - ) : null + // Shared by the "more options" button and the right-click menu. + const menuProps: MediaContextMenuProps | null = onMediaAction + ? { + label: `More options for ${song.title}`, + stationArtistId: inRange ? selectionStationArtistId : song.artist.id, + selectedCount: inRange && selectedCount > 0 ? selectedCount : 1, + inSelectionRange: inRange, + onOpenMenu: () => onPrepareContextMenu?.(song.id), + onAction: (action) => onMediaAction(action, song.id), + playlistLabel, + showFavorite: showFavoriteInMenu, + favorited: isFavorite, + navigation: { + artist: { id: song.artist.id }, + album: { id: song.album.id }, + }, + share: { type: "song", albumId: song.album.id, songId: song.id }, + children: + removeLabel && onRemove ? ( + <> + + onRemove(song.id)} + > + {removeLabel} + + + + ) : null, + } + : null + const menu = menuProps ? : null let content: React.ReactNode switch (variant) { @@ -491,14 +493,21 @@ function TrackRowComponent({ ) - return variant === "queue" ? ( -
  • } {...shellProps}> - {children} -
  • + const shell = + variant === "queue" ? ( +
  • } {...shellProps}> + {children} +
  • + ) : ( +
    } {...shellProps}> + {children} +
    + ) + + return menuProps ? ( + {shell} ) : ( -
    } {...shellProps}> - {children} -
    + shell ) } 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-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]) 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