refactor(web): share one track row and media action hook

Replace SongRow, PlaylistSongRow, album TrackRow and QueueSongRow with a
memoized TrackRow that takes a variant, and replace the five
handleMediaAction switches with useMediaActions/useTrackListMediaAction.

Playlist rows now show each song's real playlist position while filtering
instead of renumbering from 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
joshuafhigginsandClaude Opus 5.5 committed 2026-11-16 13:56:44 -05:00 Verified
1 parent dce66b7697
commit 679ea36e63
9 files changed
+871 -1273

No files matched your search

+73 -251
View File
@@ -4,13 +4,11 @@ import { PageHeader } from "@/components/library-skeletons"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { Play, Share2, Shuffle, Star } from "lucide-react"
import { Play, Share2, Shuffle } from "lucide-react"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { MediaCollectionFooter } from "@/components/media-collection-footer"
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"
@@ -20,37 +18,31 @@ import {
MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
import { TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { api } from "@otunes/convex/_generated/api"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import {
useMediaActions,
useTrackListMediaAction,
} from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types"
import type {
BrowseAlbumDetail,
BrowseAlbumTrack,
BrowseSong,
} from "@otunes/convex/types"
import {
getSelectionRangePositions,
isInSelectionRange,
ALBUM_TRACK_ROW,
ALBUM_TRACK_TITLE,
SelectionRangeHighlight,
TRACK_LIST_CONTAINER,
TrackRowActiveHighlight,
TrackRowHoverHighlight,
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { albumCoverUrl } from "@/lib/cover-urls"
import { sumDurationSeconds } from "@/lib/media-summary"
import { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function formatMetadata(genre: string | null, year: number | null): string | null {
const parts: string[] = []
if (genre) {
@@ -100,159 +92,6 @@ function groupAlbumTracksByDisk(tracks: BrowseAlbumTrack[]): AlbumTrackSection[]
return sections
}
function TrackRow({
track,
sectionIndex,
artist,
isActive,
isSelected,
selectionPosition,
isFavorite,
selectedCount,
onSelect,
onPointerDown,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
isNowPlaying,
onPlay,
albumId,
}: {
track: BrowseAlbumTrack
sectionIndex: number
artist: BrowseAlbumDetail["artist"]
albumId: string
isActive: boolean
isSelected: boolean
selectionPosition: SelectionRangePosition
isFavorite: boolean
selectedCount: number
onSelect: (event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, trackId: string) => void
isNowPlaying: boolean
onPlay: () => void
}) {
const displayTrack =
track.track > 0 ? track.track : sectionIndex + 1
const inRange = isInSelectionRange(selectionPosition)
return (
<div
role="button"
tabIndex={0}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
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"
)}
>
<SelectionRangeHighlight position={selectionPosition} />
{!inRange && isActive ? <TrackRowActiveHighlight /> : null}
{!inRange && !isActive ? <TrackRowHoverHighlight /> : null}
<div
className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}
>
<div className="flex shrink-0 items-center justify-center">
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8 opacity-0 transition-opacity group-hover:opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary",
(isFavorite || isActive || isSelected) && "opacity-100"
)}
aria-label={
isFavorite
? `Remove ${track.title} from favorites`
: `Favorite ${track.title}`
}
onClick={(event) => {
event.stopPropagation()
onToggleFavorite()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
</div>
<TrackNumberPlayButton
displayTrack={displayTrack}
title={track.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={onPlay}
/>
<div className="min-w-0 flex-1">
<div className={ALBUM_TRACK_TITLE}>{track.title}</div>
{track.artists ? (
<p
className={cn(
"truncate text-xs",
inRange
? "text-primary-foreground/80"
: "text-muted-foreground"
)}
>
{track.artists.join(", ")}
</p>
) : null}
</div>
<span
className={cn(
"shrink-0 text-right tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(track.durationSeconds)}
</span>
<MediaContextMenu
label={`More options for ${track.title}`}
stationArtistId={artist.id}
selectedCount={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,
}}
/>
</div>
</div>
)
}
export function AlbumView({
album,
highlightedSongId,
@@ -260,17 +99,15 @@ export function AlbumView({
album: BrowseAlbumDetail
highlightedSongId?: string
}) {
const { openAddToPlaylist } = useAddToPlaylist()
const {
isSongFavorite,
isAlbumFavorite,
toggleSongFavorite,
toggleAlbumFavorite,
favoriteSongs,
} = useFavorites()
const { currentSong, playFromSong, playAlbum, playAlbumShuffled } =
usePlayback()
const { runQueueAction, createStation } = useQueueMediaActions()
const { runSongsAction } = useMediaActions()
const albumSongIds = React.useMemo(
() => album.tracks.map((track) => track.id as Id<"songs">),
[album.tracks]
@@ -308,7 +145,6 @@ export function AlbumView({
const {
selectedIds,
selectedCount,
isSelected,
handleSelect,
handlePointerDown,
prepareContextMenu,
@@ -336,55 +172,55 @@ export function AlbumView({
return indexById
}, [album.tracks])
function handleMediaAction(
action: MediaContextAction,
fallbackTrackId?: string
) {
const targetIds =
selectedIds.size > 0
? Array.from(selectedIds)
: fallbackTrackId
? [fallbackTrackId]
: activeTrackId
? [activeTrackId]
: []
switch (action) {
case "create-station":
void createStation(album.artist.id)
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 trackSongs = React.useMemo(
() =>
new Map<string, BrowseSong>(
album.tracks.map((track) => [
track.id,
{
id: track.id,
title: track.title,
durationSeconds: track.durationSeconds,
artist: album.artist,
album: { id: album.id, title: album.title, cover: album.cover },
},
])
),
[album.tracks, album.artist, album.id, album.title, album.cover]
)
const handleMediaAction = useTrackListMediaAction({
selectedIds,
artistId: album.artist.id,
})
const handleRowSelect = React.useCallback(
(index: number, event: React.MouseEvent) => {
const trackId = album.tracks[index].id
handleSelect(trackId, index, event)
setActiveTrackId(trackId)
},
[album.tracks, handleSelect]
)
const handleRowPlay = React.useCallback(
(index: number) => {
void playFromSong(album.tracks[index].id, albumSongIds, `album:${album.id}`)
},
[album.tracks, album.id, albumSongIds, playFromSong]
)
const handleToggleFavorite = React.useCallback(
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
[toggleSongFavorite]
)
function handleAlbumMediaAction(action: MediaContextAction) {
const targetIds = album.tracks.map((track) => track.id as Id<"songs">)
switch (action) {
case "create-station":
void createStation(album.artist.id)
break
case "favorite":
void toggleAlbumFavorite(album.id as Id<"albums">)
break
case "playlist":
openAddToPlaylist(targetIds)
break
case "play-next":
case "play-last":
case "shuffle":
void runQueueAction(action, targetIds)
break
if (action === "favorite") {
void toggleAlbumFavorite(album.id as Id<"albums">)
return
}
runSongsAction(action, albumSongIds, album.artist.id)
}
return (
@@ -518,39 +354,25 @@ export function AlbumView({
return (
<TrackRow
key={track.id}
track={track}
sectionIndex={sectionTrackIndex}
artist={album.artist}
albumId={album.id}
variant="album"
song={trackSongs.get(track.id)!}
index={listIndex}
trackNumber={
track.track > 0 ? track.track : sectionTrackIndex + 1
}
subtitle={track.artists?.join(", ")}
isActive={track.id === activeTrackId}
isSelected={isSelected(track.id)}
selectionPosition={selectionPositions[listIndex]}
isFavorite={isSongFavorite(track.id)}
selectedCount={
isSelected(track.id) && selectedCount > 0
? selectedCount
: 1
}
onPointerDown={handlePointerDown}
onSelect={(event) => {
handleSelect(track.id, listIndex, event)
setActiveTrackId(track.id)
}}
onToggleFavorite={() =>
void toggleSongFavorite(track.id as Id<"songs">)
}
onPrepareContextMenu={() =>
prepareContextMenu(track.id)
}
onMediaAction={handleMediaAction}
selectedCount={selectedCount}
selectionStationArtistId={album.artist.id}
isNowPlaying={currentSong?.id === track.id}
onPlay={() =>
void playFromSong(
track.id as Id<"songs">,
albumSongIds,
`album:${album.id}`
)
}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onToggleFavorite={handleToggleFavorite}
onPrepareContextMenu={prepareContextMenu}
onMediaAction={handleMediaAction}
/>
)
})}
+4 -38
View File
@@ -4,27 +4,19 @@ import { PageHeader } from "@/components/library-skeletons"
import * as React from "react"
import Image from "next/image"
import { Play, Shuffle } from "lucide-react"
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 { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useMediaActions } from "@/hooks/use-media-actions"
import { AlbumCard } from "@/components/album-card"
import { FavoriteMediaButton } from "@/components/favorite-media-button"
import {
MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
import { MediaContextMenu } from "@/components/media-context-menu"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { albumGridClassName } from "@/lib/album-grid-classes"
import { artistCoverUrl } from "@/lib/cover-urls"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
export function ArtistView({
artist,
@@ -34,34 +26,8 @@ export function ArtistView({
albums: BrowseAlbum[]
}) {
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { openAddArtistToPlaylist } = useAddToPlaylist()
const { playArtist, playArtistShuffled } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
const convex = useConvex()
const cacheScope = useCacheScope()
async function handleMediaAction(action: MediaContextAction) {
switch (action) {
case "favorite":
void toggleArtistFavorite(artist.id as Id<"artists">)
break
case "playlist":
void openAddArtistToPlaylist(artist.id as Id<"artists">)
break
case "play-next":
case "play-last":
case "shuffle": {
const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: artist.id as Id<"artists"> }
)
void runQueueAction(action, songIds)
break
}
}
}
const { runArtistAction } = useMediaActions()
return (
<div className="flex h-svh flex-col">
@@ -118,7 +84,7 @@ export function ArtistView({
label={`More options for ${artist.name}`}
selectedCount={albums.length}
onOpenMenu={() => {}}
onAction={handleMediaAction}
onAction={(action) => void runArtistAction(action, artist.id)}
favorited={isArtistFavorite(artist.id)}
trackRowTrigger={false}
triggerVariant="secondary"
+4 -38
View File
@@ -4,11 +4,8 @@ import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronRightIcon, Play, Shuffle } from "lucide-react"
import { useConvex } from "convex/react"
import { useCacheScope } from "@/components/persistent-cache-provider"
import { AlbumCard } from "@/components/album-card"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { FavoriteMediaButton } from "@/components/favorite-media-button"
import { useFavorites } from "@/components/favorites-provider"
import {
@@ -16,15 +13,13 @@ import {
type MediaContextAction,
} from "@/components/media-context-menu"
import { usePlayback } from "@/components/playback-provider"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useMediaActions } from "@/hooks/use-media-actions"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@otunes/convex/_generated/api"
import { cn } from "@/lib/utils"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseAlbum, BrowseArtist } from "@otunes/convex/types"
import { artistCoverUrl } from "@/lib/cover-urls"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
function ArtistAvatar({ artist }: { artist: BrowseArtist }) {
return (
@@ -110,12 +105,9 @@ export function ArtistsView({
}
return sortedArtists[0]?.id ?? ""
}, [artistId, sortedArtists])
const convex = useConvex()
const cacheScope = useCacheScope()
const { openAddArtistToPlaylist } = useAddToPlaylist()
const { isArtistFavorite, toggleArtistFavorite } = useFavorites()
const { playArtist, playArtistShuffled } = usePlayback()
const { runQueueAction } = useQueueMediaActions()
const { runArtistAction } = useMediaActions()
const selectedArtist = sortedArtists.find(
(artist) => artist.id === selectedId
@@ -130,32 +122,6 @@ export function ArtistsView({
return counts
}, [albums])
async function handleMediaAction(
artistId: string,
action: MediaContextAction
) {
switch (action) {
case "favorite":
void toggleArtistFavorite(artistId as Id<"artists">)
break
case "playlist":
void openAddArtistToPlaylist(artistId as Id<"artists">)
break
case "play-next":
case "play-last":
case "shuffle": {
const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: artistId as Id<"artists"> }
)
void runQueueAction(action, songIds)
break
}
}
}
return (
<div className="flex min-h-0 flex-1">
<ScrollArea className="w-72 shrink-0 border-r">
@@ -169,7 +135,7 @@ export function ArtistsView({
isFavorite={isArtistFavorite(artist.id)}
onSelect={() => onSelectArtist(artist.id)}
onMediaAction={(action) =>
void handleMediaAction(artist.id, action)
void runArtistAction(action, artist.id)
}
/>
))}
@@ -225,7 +191,7 @@ export function ArtistsView({
selectedCount={artistAlbums.length}
onOpenMenu={() => {}}
onAction={(action) =>
void handleMediaAction(selectedArtist.id, action)
void runArtistAction(action, selectedArtist.id)
}
favorited={isArtistFavorite(selectedArtist.id)}
trackRowTrigger={false}
+66 -358
View File
@@ -9,15 +9,14 @@ import { useMutation } from "convex/react"
import { Play, SearchIcon, Share2, Shuffle, Star, Trash2 } from "lucide-react"
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 { MediaCollectionFooter } from "@/components/media-collection-footer"
import { TrackNumberPlayButton } from "@/components/track-number-play-button"
import {
MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
import { TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import {
DropdownMenuItem,
@@ -25,248 +24,22 @@ import {
} from "@/components/ui/dropdown-menu"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import {
useMediaActions,
useTrackListMediaAction,
} from "@/hooks/use-media-actions"
import { useTrackSelection } from "@/hooks/use-track-selection"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types"
import { albumCoverUrl, playlistCoverUrl } from "@/lib/cover-urls"
import { playlistCoverUrl } from "@/lib/cover-urls"
import { copyPlaylistLink } from "@/lib/media-links"
import { sumDurationSeconds } from "@/lib/media-summary"
import { rememberSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
import {
getSelectionRangePositions,
isInSelectionRange,
ALBUM_TRACK_ROW,
ALBUM_TRACK_TITLE,
SelectionRangeHighlight,
TrackRowActiveHighlight,
TrackRowHoverHighlight,
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
const ADD_TO_ANOTHER_PLAYLIST = "Add to Another Playlist"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function PlaylistSongCover({
song,
inRange,
isFavorite,
onToggleFavorite,
}: {
song: BrowseSong
inRange: boolean
isFavorite: boolean
onToggleFavorite: () => void
}) {
return (
<div
className={cn(
"group/cover relative size-10 shrink-0 overflow-hidden rounded ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(song.album.id)}
alt={song.album.title}
fill
sizes="40px"
className="object-cover"
/>
<div
className={cn(
"absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-opacity group-hover/cover:opacity-100",
"group-hover/cover:bg-black/40"
)}
>
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary"
)}
aria-label={
isFavorite
? `Remove ${song.title} from favorites`
: `Favorite ${song.title}`
}
onClick={(event) => {
event.stopPropagation()
onToggleFavorite()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
</div>
</div>
)
}
function PlaylistSongRow({
song,
index,
isOwner,
canRemove,
isActive,
selectionPosition,
isFavorite,
selectedCount,
stationArtist,
isDragging,
onSelect,
onPointerDown,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
onRemove,
onDragStart,
onDragOver,
onDrop,
showFavoriteInMenu = true,
removeLabel = "Remove from Playlist",
isNowPlaying,
onPlay,
}: {
song: BrowseSong
index: number
isOwner: boolean
canRemove: boolean
isActive: boolean
selectionPosition: SelectionRangePosition
isFavorite: boolean
selectedCount: number
stationArtist?: string
isDragging: boolean
onSelect: (event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, songId: string) => void
onRemove: () => void
onDragStart: (event: React.DragEvent) => void
onDragOver: (event: React.DragEvent) => void
onDrop: (event: React.DragEvent) => void
showFavoriteInMenu?: boolean
removeLabel?: string
isNowPlaying: boolean
onPlay: () => void
}) {
const displayTrack = index + 1
const inRange = isInSelectionRange(selectionPosition)
return (
<div
role="button"
tabIndex={0}
draggable={isOwner}
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
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",
isDragging && "opacity-50"
)}
>
<SelectionRangeHighlight position={selectionPosition} />
{!inRange && isActive ? <TrackRowActiveHighlight /> : null}
{!inRange && !isActive ? <TrackRowHoverHighlight /> : null}
<div
className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}
>
<PlaylistSongCover
song={song}
inRange={inRange}
isFavorite={isFavorite}
onToggleFavorite={onToggleFavorite}
/>
<TrackNumberPlayButton
displayTrack={displayTrack}
title={song.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={onPlay}
/>
<span className={ALBUM_TRACK_TITLE}>{song.title}</span>
<span
className={cn(
"shrink-0 text-right tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
<MediaContextMenu
label={`More options for ${song.title}`}
stationArtistId={stationArtist}
selectedCount={selectedCount}
inSelectionRange={inRange}
onOpenMenu={onPrepareContextMenu}
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 ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
className="justify-between"
onClick={onRemove}
>
{removeLabel}
<Trash2 />
</DropdownMenuItem>
</>
) : null}
</MediaContextMenu>
</div>
</div>
)
}
export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const router = useRouter()
const isFavorites = playlist.isFavorites === true
@@ -275,13 +48,8 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
currentUser === undefined
? playlist.isOwner
: currentUser?._id === playlist.owner.id
const { openAddToPlaylist } = useAddToPlaylist()
const {
isSongFavorite,
toggleSongFavorite,
toggleSongsFavorite,
favoriteSongs: addFavoriteSongs,
} = useFavorites()
const { isSongFavorite, toggleSongFavorite, toggleSongsFavorite } =
useFavorites()
const {
currentSong,
playInOrder,
@@ -290,7 +58,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
playPlaylistShuffled,
playFromSong,
} = usePlayback()
const { runQueueAction, createStation } = useQueueMediaActions()
const { runSongsAction } = useMediaActions()
const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist)
const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs)
const deletePlaylist = useMutation(api.playlists.deletePlaylist)
@@ -322,6 +90,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
() => songs.map((song) => song.id as Id<"songs">),
[songs]
)
const playlistPositionById = React.useMemo(
() => new Map(songs.map((song, index) => [song.id, index + 1])),
[songs]
)
const [activeTrackId, setActiveTrackId] = React.useState("")
const [dragIndex, setDragIndex] = React.useState<number | null>(null)
const [isSubscribed, setIsSubscribed] = React.useState(playlist.isSubscribed)
@@ -336,7 +108,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
const {
selectedIds,
selectedCount,
isSelected,
handleSelect,
handlePointerDown,
prepareContextMenu,
@@ -374,57 +145,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
}
function resolveTargetIds(fallbackSongId?: string) {
return selectedIds.size > 0
? Array.from(selectedIds)
: fallbackSongId
? [fallbackSongId]
: activeTrackId
? [activeTrackId]
: []
}
function handleMediaAction(
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
}
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
}
}
const handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
function handlePlaylistMediaAction(action: MediaContextAction) {
const targetIds = songs.map((song) => song.id as Id<"songs">)
runSongsAction(action, playlistSongIds)
}
switch (action) {
case "favorite":
void addFavoriteSongs(targetIds)
break
case "playlist":
openAddToPlaylist(targetIds)
break
case "play-next":
case "play-last":
case "shuffle":
void runQueueAction(action, targetIds)
break
const canReorder = isOwner && !isFavorites && !normalizedQuery
function handleRowSelect(index: number, event: React.MouseEvent) {
const songId = filteredSongs[index].id
handleSelect(songId, index, event)
setActiveTrackId(songId)
}
function handleRowPlay(index: number) {
void playFromSong(
filteredSongs[index].id,
playlistSongIds,
`playlist:${playlist.id}`
)
}
function handleToggleFavorite(songId: string) {
const wasFavorite = isSongFavorite(songId)
void toggleSongFavorite(songId as Id<"songs">)
if (isFavorites && wasFavorite) {
setHiddenFavoriteIds((current) => {
const next = new Set(current)
next.add(songId)
return next
})
}
}
@@ -479,13 +230,7 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
}
function handleDrop(targetIndex: number) {
if (
normalizedQuery ||
isFavorites ||
!isOwner ||
dragIndex === null ||
dragIndex === targetIndex
) {
if (!canReorder || dragIndex === null || dragIndex === targetIndex) {
setDragIndex(null)
return
}
@@ -677,74 +422,37 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) {
</div>
{filteredSongs.length > 0 ? (
filteredSongs.map((song, index) => (
<PlaylistSongRow
<TrackRow
key={song.id}
variant="playlist"
song={song}
index={index}
isOwner={isOwner && !isFavorites && !normalizedQuery}
canRemove={isFavorites || isOwner}
trackNumber={playlistPositionById.get(song.id)}
isActive={song.id === activeTrackId}
isNowPlaying={currentSong?.id === song.id}
isFavorite={isSongFavorite(song.id)}
isDragging={dragIndex === index}
selectionPosition={selectionPositions[index]}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
playlistLabel={ADD_TO_ANOTHER_PLAYLIST}
showFavoriteInMenu={!isFavorites}
removeLabel={
isFavorites ? "Unfavorite" : "Remove from Playlist"
isFavorites
? "Unfavorite"
: isOwner
? "Remove from Playlist"
: undefined
}
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)}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onToggleFavorite={handleToggleFavorite}
onPrepareContextMenu={prepareContextMenu}
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}`
)
}
onRemove={handleRemoveSong}
onDragStart={canReorder ? setDragIndex : undefined}
onDrop={canReorder ? handleDrop : undefined}
/>
))
) : (
+36 -170
View File
@@ -1,11 +1,10 @@
"use client"
import * as React from "react"
import Image from "next/image"
import { Music2 } from "lucide-react"
import { PlaybackSongMeta } from "@/components/playback-song-meta"
import { usePlayback } from "@/components/playback-provider"
import { TrackCover, TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"
@@ -13,19 +12,11 @@ import { Spinner } from "@/components/ui/spinner"
import { useTrackSelection } from "@/hooks/use-track-selection"
import type { Id } from "@otunes/convex/_generated/dataModel"
import type { BrowseSong, HistorySong, QueueSong } from "@otunes/convex/types"
import { albumCoverUrl } from "@/lib/cover-urls"
import {
getContiguousSelectedIndices,
moveQueueBlock,
} from "@/lib/move-queue-block"
import {
getSelectionRangePositions,
isInSelectionRange,
QueueSelectionRangeHighlight,
QueueTrackRowActiveHighlight,
QueueTrackRowHoverHighlight,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { getSelectionRangePositions } from "@/lib/selection-range-styles"
import { useSongs } from "@/lib/song-cache"
import { cn } from "@/lib/utils"
@@ -61,48 +52,16 @@ function toSelectableQueue(
})
}
function QueueSongCover({
albumId,
title,
inRange,
}: {
albumId: string
title: string
inRange: boolean
}) {
return (
<div
className={cn(
"relative size-10 shrink-0 overflow-hidden ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(albumId)}
alt={title}
fill
sizes="40px"
className="object-cover"
/>
</div>
)
}
function HistorySongRow({ song }: { song: HistorySong }) {
return (
<li className="relative w-full py-2 text-left text-sm opacity-60">
<div className="relative z-10 flex items-center gap-3 px-2">
{song.album.id ? (
<QueueSongCover
albumId={song.album.id}
title={song.album.title}
inRange={false}
/>
) : (
<div className="flex size-10 shrink-0 items-center justify-center bg-muted ring-1 ring-foreground/10">
<Music2 className="size-4 text-muted-foreground" />
</div>
)}
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={false}
square
/>
<PlaybackSongMeta
song={song}
@@ -120,106 +79,6 @@ function HistorySongRow({ song }: { song: HistorySong }) {
)
}
const QueueSongRow = React.forwardRef<
HTMLLIElement,
{
song: QueueSelectable
isNowPlaying: boolean
selectionPosition: SelectionRangePosition
isDragging: boolean
onSelect: (event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onSkipTo: () => void
onDragStart: (event: React.DragEvent) => void
onDragOver: (event: React.DragEvent) => void
onDrop: (event: React.DragEvent) => void
}
>(function QueueSongRow(
{
song,
isNowPlaying,
selectionPosition,
isDragging,
onSelect,
onPointerDown,
onSkipTo,
onDragStart,
onDragOver,
onDrop,
},
ref
) {
const inRange = isInSelectionRange(selectionPosition)
return (
<li
ref={ref}
role="button"
tabIndex={0}
draggable
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onSkipTo()
}}
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 text-left text-sm transition-colors",
inRange && "text-primary-foreground",
isDragging && "opacity-50"
)}
>
<QueueSelectionRangeHighlight position={selectionPosition} />
{!inRange && isNowPlaying ? <QueueTrackRowActiveHighlight /> : null}
{!inRange && !isNowPlaying ? <QueueTrackRowHoverHighlight /> : null}
<div className="relative z-10 flex items-center gap-3 px-2">
{song.album.id ? (
<QueueSongCover
albumId={song.album.id}
title={song.album.title}
inRange={inRange}
/>
) : (
<div
className={cn(
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Music2 className="size-4 text-muted-foreground" />
</div>
)}
<PlaybackSongMeta
song={song}
isCurrent={isNowPlaying}
inRange={inRange}
align="start"
showAlbum={false}
/>
<span
className={cn(
"shrink-0 text-xs tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
</div>
</li>
)
})
function QueueSongRowSkeleton() {
return (
<li className="flex items-center gap-3 px-2 py-2" aria-hidden>
@@ -243,7 +102,7 @@ export function QueuePanel() {
skipToQueueIndex,
} = usePlayback()
const loadMoreRef = React.useRef<HTMLDivElement>(null)
const nowPlayingRef = React.useRef<HTMLLIElement>(null)
const nowPlayingRef = React.useRef<HTMLElement>(null)
const [visibleCount, setVisibleCount] = React.useState(
QUEUE_INITIAL_VISIBLE_COUNT
)
@@ -311,12 +170,25 @@ export function QueuePanel() {
return () => observer.disconnect()
}, [hasMore])
const {
selectedIds,
handleSelect,
handlePointerDown,
} = useTrackSelection(
selectableQueue.map((item) => ({ id: item.selectionId }))
const selectionItems = React.useMemo(
() => selectableQueue.map((item) => ({ id: item.selectionId })),
[selectableQueue]
)
const { selectedIds, handleSelect, handlePointerDown } =
useTrackSelection(selectionItems)
const handleRowSelect = React.useCallback(
(index: number, event: React.MouseEvent) => {
handleSelect(selectableQueue[index].selectionId, index, event)
},
[selectableQueue, handleSelect]
)
const handleRowPlay = React.useCallback(
(index: number) => {
void skipToQueueIndex(selectableQueue[index].queueIndex)
},
[selectableQueue, skipToQueueIndex]
)
const selectionPositions = React.useMemo(
@@ -403,27 +275,21 @@ export function QueuePanel() {
<ul className="flex flex-col py-1">
{selectableQueue.map((item, index) =>
item.song ? (
<QueueSongRow
<TrackRow
key={item.selectionId}
ref={item.queueIndex === 0 ? nowPlayingRef : undefined}
variant="queue"
song={item.song}
index={index}
isActive={item.queueIndex === 0}
isNowPlaying={item.queueIndex === 0}
selectionPosition={selectionPositions[index]}
isDragging={draggingIndices.has(index)}
onPointerDown={handlePointerDown}
onSelect={(event) => {
handleSelect(item.selectionId, index, event)
}}
onSkipTo={() => void skipToQueueIndex(item.queueIndex)}
onDragStart={(event) => {
setDragIndex(index)
event.dataTransfer.effectAllowed = "move"
}}
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => {
event.preventDefault()
handleDrop(index)
}}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onDragStart={setDragIndex}
onDrop={handleDrop}
/>
) : (
<QueueSongRowSkeleton key={item.selectionId} />
+51 -325
View File
@@ -2,18 +2,19 @@
import { MobileSidebarTrigger } from "@/components/mobile-sidebar-trigger"
import { stationArtistId } from "@/lib/station-artist"
import { 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 {
useCallback,
useEffect,
useMemo,
useState,
useRef,
type MouseEvent,
} from "react"
import { ArrowUpDown } from "lucide-react"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
import { usePlayback } from "@/components/playback-provider"
import {
MediaContextMenu,
type MediaContextAction,
} from "@/components/media-context-menu"
import { LibraryTrackListHeader, TrackRow } from "@/components/track-row"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
@@ -25,32 +26,17 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useCachedPaginatedQuery } from "@/hooks/use-cached-query"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { useTrackListMediaAction } from "@/hooks/use-media-actions"
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 { 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"
import { albumCoverUrl } from "@/lib/cover-urls"
import {
getSelectionRangePositions,
isInSelectionRange,
ALBUM_TRACK_TITLE,
SongsSelectionRangeHighlight,
SongsTrackRowHoverHighlight,
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
type SortKey = "title" | "artist" | "album"
@@ -58,219 +44,9 @@ type SortDirection = "asc" | "desc"
const SONGS_PAGE_SIZE = 50
const songRowLayout =
"flex w-full items-center gap-x-4"
const nameColumnLayout =
"grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2"
const songColumnClass = "w-36 shrink-0 truncate"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
function SongCover({
song,
inRange,
onPlay,
}: {
song: BrowseSong
inRange: boolean
onPlay: () => void
}) {
return (
<div
className={cn(
"relative size-10 shrink-0 overflow-hidden rounded ring-1",
inRange ? "ring-white/25" : "ring-foreground/10"
)}
>
<Image
src={albumCoverUrl(song.album.id)}
alt={song.album.title}
fill
sizes="40px"
className="object-cover"
/>
<div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/40">
<Button
size="icon-sm"
className="size-7 rounded-full opacity-0 transition-opacity group-hover:opacity-100"
aria-label={`Play ${song.title}`}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
onPlay()
}}
>
<Play className="size-3 fill-current" />
</Button>
</div>
</div>
)
}
function SongRow({
song,
isSelected,
selectionPosition,
isFavorite,
selectedCount,
stationArtist,
onSelect,
onPointerDown,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
onPlay,
}: {
song: BrowseSong
isSelected: boolean
selectionPosition: SelectionRangePosition
isFavorite: boolean
selectedCount: number
stationArtist?: string
onSelect: (event: MouseEvent) => void
onPointerDown: (event: MouseEvent) => void
onToggleFavorite: () => void
onPrepareContextMenu: () => void
onMediaAction: (action: MediaContextAction, songId: string) => void
onPlay: () => void
}) {
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
onMouseDown={onPointerDown}
onClick={onSelect}
onDoubleClick={(event) => {
event.preventDefault()
onPlay()
}}
className="group cursor-pointer select-none border-none hover:bg-transparent"
>
<TableCell colSpan={4} className="p-0">
<div
className={cn(
"relative py-2",
inRange && "text-primary-foreground"
)}
>
<SongsSelectionRangeHighlight position={selectionPosition} />
{!inRange ? <SongsTrackRowHoverHighlight /> : null}
<div
className={cn("relative z-10", songRowLayout, TRACK_ROW_PADDING)}
>
<div className={nameColumnLayout}>
<div className="flex items-center justify-center">
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8 opacity-0 transition-opacity group-hover:opacity-100",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary",
(isFavorite || isSelected) && "opacity-100"
)}
aria-label={
isFavorite
? `Remove ${song.title} from favorites`
: `Favorite ${song.title}`
}
onClick={(event) => {
event.stopPropagation()
onToggleFavorite()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
</div>
<SongCover song={song} inRange={inRange} onPlay={onPlay} />
<span className={ALBUM_TRACK_TITLE}>
{song.title}
{song.explicit ? (
<span
className={cn(
"ml-1.5 inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-[9px] font-semibold leading-none",
inRange
? "bg-white/20 text-primary-foreground"
: "bg-muted-foreground/20 text-muted-foreground"
)}
aria-label="Explicit"
>
E
</span>
) : null}
</span>
</div>
<div className={songColumnClass}>
<Link
href={"/artist/" + song.artist.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.artist.name}
</Link>
</div>
<div className={songColumnClass}>
<Link
href={"/album/" + song.album.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.album.title}
</Link>
</div>
<div className="min-w-4 flex-1" />
<span
className={cn(
"shrink-0 text-right tabular-nums",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
<MediaContextMenu
label={`More options for ${song.title}`}
stationArtistId={stationArtist}
selectedCount={selectedCount}
align="end"
inSelectionRange={inRange}
onOpenMenu={onPrepareContextMenu}
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,
}}
/>
</div>
</div>
</TableCell>
</TableRow>
)
}
export function SongsView() {
const { openAddToPlaylist } = useAddToPlaylist()
const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites()
const { isSongFavorite, toggleSongFavorite } = useFavorites()
const { playFromLibrarySong } = usePlayback()
const { runQueueAction, createStation } = useQueueMediaActions()
const [sortKey, setSortKey] = useState<SortKey>("title")
const [sortDirection, setSortDirection] =
useState<SortDirection>("asc")
@@ -311,7 +87,6 @@ export function SongsView() {
const {
selectedIds,
selectedCount,
isSelected,
handleSelect,
handlePointerDown,
prepareContextMenu,
@@ -332,32 +107,26 @@ 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
}
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 handleMediaAction = useTrackListMediaAction({ selectedIds, songs })
const handleRowSelect = useCallback(
(index: number, event: MouseEvent) => {
handleSelect(songs[index].id, index, event)
},
[songs, handleSelect]
)
const handleRowPlay = useCallback(
(index: number) => {
void playFromLibrarySong(songs[index].id, { sortKey, sortDirection })
},
[songs, sortKey, sortDirection, playFromLibrarySong]
)
const handleToggleFavorite = useCallback(
(songId: string) => void toggleSongFavorite(songId as Id<"songs">),
[toggleSongFavorite]
)
if (status === "LoadingFirstPage" && !isCached) {
return (
@@ -437,68 +206,25 @@ export function SongsView() {
}
}}
>
<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) => (
<SongRow
key={song.id}
song={song}
isSelected={isSelected(song.id)}
selectionPosition={selectionPositions[index]}
isFavorite={isSongFavorite(song.id)}
stationArtist={
isSelected(song.id)
? selectedStationArtistId
: song.artist.id
}
selectedCount={
isSelected(song.id) && 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)}
onMediaAction={handleMediaAction}
onPlay={() =>
void playFromLibrarySong(song.id as Id<"songs">, {
sortKey,
sortDirection,
})
}
/>
))}
</TableBody>
</Table>
<LibraryTrackListHeader />
{songs.map((song, index) => (
<TrackRow
key={song.id}
variant="library"
song={song}
index={index}
selectionPosition={selectionPositions[index]}
isFavorite={isSongFavorite(song.id)}
selectedCount={selectedCount}
selectionStationArtistId={selectedStationArtistId}
onPointerDown={handlePointerDown}
onSelect={handleRowSelect}
onPlay={handleRowPlay}
onToggleFavorite={handleToggleFavorite}
onPrepareContextMenu={prepareContextMenu}
onMediaAction={handleMediaAction}
/>
))}
<div
ref={loadMoreRef}
className="flex items-center justify-center py-4"
+514
View File
@@ -0,0 +1,514 @@
"use client"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { Music2, Play, Star, Trash2 } from "lucide-react"
import {
MediaContextMenu,
type MediaContextAction,
} 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,
ALBUM_TRACK_TITLE,
isInSelectionRange,
SelectionRangeHighlight,
TrackRowActiveHighlight,
TrackRowHoverHighlight,
TRACK_ROW_PADDING,
type SelectionRangePosition,
} from "@/lib/selection-range-styles"
import { cn } from "@/lib/utils"
import type { BrowseSong } from "@otunes/convex/types"
/**
* - `library`: favorite star, cover with play overlay, title, artist and album
* columns (use with `LibraryTrackListHeader`).
* - `album`: favorite star, track number, title with optional credits.
* - `playlist`: cover with favorite overlay, track number, title.
* - `queue`: square cover, title and artist, no menu.
*/
export type TrackRowVariant = "library" | "album" | "playlist" | "queue"
export type TrackRowProps = {
variant: TrackRowVariant
song: BrowseSong
/** Position in the list the selection hook was given. */
index: number
/** Number shown in the track number column (`album` and `playlist`). */
trackNumber?: number
/** Secondary line under the title, e.g. album track credits. */
subtitle?: string
selectionPosition: SelectionRangePosition
isActive?: boolean
isNowPlaying?: boolean
isFavorite?: boolean
isDragging?: boolean
/** Total selected songs; the menu acts on these when this row is selected. */
selectedCount?: number
/** Station artist for the selection when this row is selected. */
selectionStationArtistId?: string
playlistLabel?: string
showFavoriteInMenu?: boolean
/** Adds a destructive menu item calling `onRemove`. */
removeLabel?: string
ref?: React.Ref<HTMLElement>
onSelect: (index: number, event: React.MouseEvent) => void
onPointerDown: (event: React.MouseEvent) => void
onPlay: (index: number) => void
onToggleFavorite?: (songId: string) => void
onPrepareContextMenu?: (songId: string) => void
/** Renders the "more options" menu when provided. */
onMediaAction?: (action: MediaContextAction, songId: string) => void
onRemove?: (songId: string) => void
/** Makes the row draggable when provided. */
onDragStart?: (index: number) => void
onDrop?: (index: number) => void
}
const LIBRARY_ROW_LAYOUT = "flex w-full items-center gap-x-4"
const LIBRARY_NAME_COLUMNS =
"grid grid-cols-[2rem_2.5rem_minmax(0,10rem)] items-center gap-x-2"
const LIBRARY_COLUMN = "w-36 shrink-0 truncate"
function formatDuration(seconds: number): string {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
}
export function TrackCover({
albumId,
alt,
inRange,
square = false,
children,
}: {
albumId: string | undefined
alt: string
inRange: boolean
square?: boolean
/** Overlay shown above the cover image. */
children?: React.ReactNode
}) {
const ringClass = inRange ? "ring-white/25" : "ring-foreground/10"
if (!albumId) {
return (
<div
className={cn(
"flex size-10 shrink-0 items-center justify-center bg-muted ring-1",
!square && "rounded",
ringClass
)}
>
<Music2 className="size-4 text-muted-foreground" />
</div>
)
}
return (
<div
className={cn(
"group/cover relative size-10 shrink-0 overflow-hidden ring-1",
!square && "rounded",
ringClass
)}
>
<Image
src={albumCoverUrl(albumId)}
alt={alt}
fill
sizes="40px"
className="object-cover"
/>
{children}
</div>
)
}
function FavoriteStarButton({
title,
isFavorite,
inRange,
className,
onToggle,
}: {
title: string
isFavorite: boolean
inRange: boolean
className?: string
onToggle: () => void
}) {
return (
<Button
variant="ghost"
size="icon-sm"
className={cn(
"size-8",
inRange
? "text-primary-foreground hover:bg-white/15 hover:text-primary-foreground"
: "text-primary hover:text-primary",
className
)}
aria-label={isFavorite ? `Remove ${title} from favorites` : `Favorite ${title}`}
onClick={(event) => {
event.stopPropagation()
onToggle()
}}
>
<Star
className={cn(
"size-4",
isFavorite && (inRange ? "fill-current" : "fill-primary")
)}
/>
</Button>
)
}
function ExplicitBadge({ inRange }: { inRange: boolean }) {
return (
<span
className={cn(
"ml-1.5 inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-[9px] font-semibold leading-none",
inRange
? "bg-white/20 text-primary-foreground"
: "bg-muted-foreground/20 text-muted-foreground"
)}
aria-label="Explicit"
>
E
</span>
)
}
function TrackTitle({
song,
subtitle,
inRange,
}: {
song: BrowseSong
subtitle?: string
inRange: boolean
}) {
return (
<div className="min-w-0 flex-1">
<div className={ALBUM_TRACK_TITLE}>
{song.title}
{song.explicit ? <ExplicitBadge inRange={inRange} /> : null}
</div>
{subtitle ? (
<p
className={cn(
"truncate text-xs",
inRange ? "text-primary-foreground/80" : "text-muted-foreground"
)}
>
{subtitle}
</p>
) : null}
</div>
)
}
export function LibraryTrackListHeader() {
const labelClass = "text-xs text-muted-foreground"
return (
<div className={cn("flex h-9 items-center", LIBRARY_ROW_LAYOUT, TRACK_ROW_PADDING)}>
<div className={LIBRARY_NAME_COLUMNS}>
<span aria-hidden />
<span aria-hidden />
<span className={labelClass}>Name</span>
</div>
<span className={cn(LIBRARY_COLUMN, labelClass)}>Artist</span>
<span className={cn(LIBRARY_COLUMN, labelClass)}>Album</span>
<div className="min-w-4 flex-1" />
<span className={cn("shrink-0 text-right", labelClass)}>Time</span>
<span className="size-8 shrink-0" aria-hidden />
</div>
)
}
function TrackRowComponent({
variant,
song,
index,
trackNumber,
subtitle,
selectionPosition,
isActive = false,
isNowPlaying = false,
isFavorite = false,
isDragging = false,
selectedCount = 0,
selectionStationArtistId,
playlistLabel,
showFavoriteInMenu = true,
removeLabel,
ref,
onSelect,
onPointerDown,
onPlay,
onToggleFavorite,
onPrepareContextMenu,
onMediaAction,
onRemove,
onDragStart,
onDrop,
}: TrackRowProps) {
const inRange = isInSelectionRange(selectionPosition)
const flush = variant === "library" || variant === "queue"
const play = () => onPlay(index)
const toggleFavorite = () => onToggleFavorite?.(song.id)
const favoriteStar = (
<div className="flex shrink-0 items-center justify-center">
<FavoriteStarButton
title={song.title}
isFavorite={isFavorite}
inRange={inRange}
className={cn(
"opacity-0 transition-opacity group-hover:opacity-100",
(isFavorite || isActive || inRange) && "opacity-100"
)}
onToggle={toggleFavorite}
/>
</div>
)
const trackNumberButton = (
<TrackNumberPlayButton
displayTrack={trackNumber ?? index + 1}
title={song.title}
isActive={isActive}
isNowPlaying={isNowPlaying}
inRange={inRange}
onPlay={play}
/>
)
const duration = (
<span
className={cn(
"shrink-0 text-right tabular-nums",
variant === "queue" && "text-xs",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{formatDuration(song.durationSeconds)}
</span>
)
const menu = onMediaAction ? (
<MediaContextMenu
label={`More options for ${song.title}`}
stationArtistId={inRange ? selectionStationArtistId : song.artist.id}
selectedCount={inRange && selectedCount > 0 ? selectedCount : 1}
inSelectionRange={inRange}
onOpenMenu={() => onPrepareContextMenu?.(song.id)}
onAction={(action) => onMediaAction(action, song.id)}
playlistLabel={playlistLabel}
showFavorite={showFavoriteInMenu}
favorited={isFavorite}
navigation={{
artist: { id: song.artist.id },
album: { id: song.album.id },
}}
share={{ type: "song", albumId: song.album.id, songId: song.id }}
>
{removeLabel && onRemove ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
className="justify-between"
onClick={() => onRemove(song.id)}
>
{removeLabel}
<Trash2 />
</DropdownMenuItem>
</>
) : null}
</MediaContextMenu>
) : null
let content: React.ReactNode
switch (variant) {
case "library": {
const linkClass = inRange
? "text-primary-foreground hover:text-primary-foreground/80 hover:underline"
: "text-muted-foreground hover:text-foreground hover:underline"
content = (
<div className={cn("relative z-10", LIBRARY_ROW_LAYOUT, TRACK_ROW_PADDING)}>
<div className={LIBRARY_NAME_COLUMNS}>
{favoriteStar}
<TrackCover albumId={song.album.id} alt={song.album.title} inRange={inRange}>
<div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/40">
<Button
size="icon-sm"
className="size-7 rounded-full opacity-0 transition-opacity group-hover:opacity-100"
aria-label={`Play ${song.title}`}
onClick={(event) => {
event.preventDefault()
event.stopPropagation()
play()
}}
>
<Play className="size-3 fill-current" />
</Button>
</div>
</TrackCover>
<TrackTitle song={song} inRange={inRange} />
</div>
<div className={LIBRARY_COLUMN}>
<Link
href={"/artist/" + song.artist.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.artist.name}
</Link>
</div>
<div className={LIBRARY_COLUMN}>
<Link
href={"/album/" + song.album.id}
className={linkClass}
onClick={(event) => event.stopPropagation()}
>
{song.album.title}
</Link>
</div>
<div className="min-w-4 flex-1" />
{duration}
{menu}
</div>
)
break
}
case "album":
content = (
<div className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}>
{favoriteStar}
{trackNumberButton}
<TrackTitle song={song} subtitle={subtitle} inRange={inRange} />
{duration}
{menu}
</div>
)
break
case "playlist":
content = (
<div className={cn("relative z-10", ALBUM_TRACK_ROW, TRACK_ROW_PADDING)}>
<TrackCover albumId={song.album.id} alt={song.album.title} inRange={inRange}>
<div className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-opacity group-hover/cover:bg-black/40 group-hover/cover:opacity-100">
<FavoriteStarButton
title={song.title}
isFavorite={isFavorite}
inRange={inRange}
onToggle={toggleFavorite}
/>
</div>
</TrackCover>
{trackNumberButton}
<TrackTitle song={song} subtitle={subtitle} inRange={inRange} />
{duration}
{menu}
</div>
)
break
case "queue":
content = (
<div className="relative z-10 flex items-center gap-3 px-2">
<TrackCover
albumId={song.album.id}
alt={song.album.title}
inRange={inRange}
square
/>
<PlaybackSongMeta
song={song}
isCurrent={isNowPlaying}
inRange={inRange}
align="start"
showAlbum={false}
/>
{duration}
</div>
)
break
}
const shellProps = {
role: "button",
tabIndex: 0,
draggable: onDragStart ? true : undefined,
onDragStart: onDragStart
? (event: React.DragEvent) => {
event.dataTransfer.effectAllowed = "move"
onDragStart(index)
}
: undefined,
onDragOver: onDragStart
? (event: React.DragEvent) => event.preventDefault()
: undefined,
onDrop: onDrop
? (event: React.DragEvent) => {
event.preventDefault()
onDrop(index)
}
: undefined,
onMouseDown: onPointerDown,
onClick: (event: React.MouseEvent) => onSelect(index, event),
onDoubleClick: (event: React.MouseEvent) => {
event.preventDefault()
play()
},
onKeyDown: (event: React.KeyboardEvent) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onSelect(index, event as unknown as React.MouseEvent)
}
},
className: cn(
"group relative w-full cursor-pointer select-none text-left text-sm transition-colors",
flush ? "py-2" : "py-2.5",
inRange && "text-primary-foreground",
isDragging && "opacity-50"
),
}
const children = (
<>
<SelectionRangeHighlight position={selectionPosition} flush={flush} />
{!inRange && isActive ? <TrackRowActiveHighlight flush={flush} /> : null}
{!inRange && !isActive ? <TrackRowHoverHighlight flush={flush} /> : null}
{content}
</>
)
return variant === "queue" ? (
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
{children}
</li>
) : (
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
{children}
</div>
)
}
/**
* Pass stable callbacks: they receive the row's `index` or song id, so one
* handler can serve every row.
*/
export const TrackRow = React.memo(TrackRowComponent)
+104
View File
@@ -0,0 +1,104 @@
"use client"
import * as React from "react"
import { useConvex } from "convex/react"
import { useAddToPlaylist } from "@/components/add-to-playlist-provider"
import { useFavorites } from "@/components/favorites-provider"
import type { MediaContextAction } from "@/components/media-context-menu"
import { useCacheScope } from "@/components/persistent-cache-provider"
import { useQueueMediaActions } from "@/hooks/use-queue-media-actions"
import { stationArtistId } from "@/lib/station-artist"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { fetchCachedQuery } from "@otunes/convex/client/cached-query"
export function useMediaActions() {
const { openAddToPlaylist, openAddArtistToPlaylist } = useAddToPlaylist()
const { favoriteSongs, toggleArtistFavorite } = useFavorites()
const { runQueueAction, createStation } = useQueueMediaActions()
const convex = useConvex()
const cacheScope = useCacheScope()
const runSongsAction = React.useCallback(
(
action: MediaContextAction,
songIds: Id<"songs">[],
stationArtist?: string
) => {
switch (action) {
case "create-station":
if (stationArtist) void createStation(stationArtist)
break
case "favorite":
void favoriteSongs(songIds)
break
case "playlist":
openAddToPlaylist(songIds)
break
case "play-next":
case "play-last":
case "shuffle":
void runQueueAction(action, songIds)
break
}
},
[createStation, favoriteSongs, openAddToPlaylist, runQueueAction]
)
const runArtistAction = React.useCallback(
async (action: MediaContextAction, artistId: string) => {
switch (action) {
case "favorite":
void toggleArtistFavorite(artistId as Id<"artists">)
break
case "playlist":
void openAddArtistToPlaylist(artistId as Id<"artists">)
break
case "play-next":
case "play-last":
case "shuffle": {
const songIds = await fetchCachedQuery(
convex,
cacheScope,
api.playlists.getOrderedArtistSongIds,
{ artistId: artistId as Id<"artists"> }
)
void runQueueAction(action, songIds)
break
}
}
},
[convex, cacheScope, toggleArtistFavorite, openAddArtistToPlaylist, runQueueAction]
)
return { runSongsAction, runArtistAction }
}
/**
* Handles a track row menu action, targeting the current selection or else the
* row's song. The station artist is `artistId` when given, otherwise the artist
* every targeted song in `songs` shares.
*/
export function useTrackListMediaAction({
selectedIds,
songs,
artistId,
}: {
selectedIds: ReadonlySet<string>
songs?: { id: string; artist: { id: string } }[]
artistId?: string
}) {
const { runSongsAction } = useMediaActions()
return React.useCallback(
(action: MediaContextAction, songId: string) => {
const targetIds = selectedIds.size > 0 ? Array.from(selectedIds) : [songId]
const stationArtist =
artistId ??
(songs ? stationArtistId(songs, new Set(targetIds)) : undefined)
runSongsAction(action, targetIds as Id<"songs">[], stationArtist)
},
[selectedIds, songs, artistId, runSongsAction]
)
}
+19 -93
View File
@@ -63,10 +63,19 @@ export function selectionHighlightRadiusClass(
export const TRACK_ROW_HIGHLIGHT_INSET = "absolute inset-y-0 left-2 right-2"
/** Full-width, square-corner highlight used by the library and queue lists. */
export const FLUSH_ROW_HIGHLIGHT_INSET = "absolute inset-0"
/**
* Track row highlights are inset rounded pills by default; `flush` makes them
* full-width with square corners.
*/
export function SelectionRangeHighlight({
position,
flush = false,
}: {
position: SelectionRangePosition
flush?: boolean
}) {
if (position === "none") {
return null
@@ -77,34 +86,34 @@ export function SelectionRangeHighlight({
aria-hidden
className={cn(
"pointer-events-none bg-primary",
TRACK_ROW_HIGHLIGHT_INSET,
selectionHighlightRadiusClass(position)
flush
? FLUSH_ROW_HIGHLIGHT_INSET
: [TRACK_ROW_HIGHLIGHT_INSET, selectionHighlightRadiusClass(position)]
)}
/>
)
}
/** Inset rounded hover background matching the selection pill shape. */
export function TrackRowHoverHighlight() {
export function TrackRowHoverHighlight({ flush = false }: { flush?: boolean }) {
return (
<div
aria-hidden
className={cn(
"pointer-events-none rounded-lg bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
TRACK_ROW_HIGHLIGHT_INSET
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
flush ? FLUSH_ROW_HIGHLIGHT_INSET : [TRACK_ROW_HIGHLIGHT_INSET, "rounded-lg"]
)}
/>
)
}
/** Inset rounded background for the active (now playing) row. */
export function TrackRowActiveHighlight() {
/** Background for the active (focused or now playing) row. */
export function TrackRowActiveHighlight({ flush = false }: { flush?: boolean }) {
return (
<div
aria-hidden
className={cn(
"pointer-events-none rounded-lg bg-muted/60",
TRACK_ROW_HIGHLIGHT_INSET
"pointer-events-none bg-muted/60",
flush ? FLUSH_ROW_HIGHLIGHT_INSET : [TRACK_ROW_HIGHLIGHT_INSET, "rounded-lg"]
)}
/>
)
@@ -116,42 +125,6 @@ export const TRACK_ROW_PADDING = "pl-8 pr-10"
/** Centers the track list in the main content area. */
export const TRACK_LIST_CONTAINER = "mx-auto w-full max-w-9/10"
/** Full-width highlight for library song rows (no horizontal inset). */
export const SONGS_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export function SongsSelectionRangeHighlight({
position,
}: {
position: SelectionRangePosition
}) {
if (position === "none") {
return null
}
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-primary",
SONGS_ROW_HIGHLIGHT_INSET
)}
/>
)
}
/** Full-width hover background for library song rows (not rounded). */
export function SongsTrackRowHoverHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
SONGS_ROW_HIGHLIGHT_INSET
)}
/>
)
}
/** Album track row: star, track #, title (flex), duration, menu. */
export const ALBUM_TRACK_ROW = "flex w-full min-w-0 items-center gap-x-3"
@@ -160,50 +133,3 @@ export const ALBUM_TRACK_TITLE = "min-w-0 flex-1 truncate font-normal"
export function isInSelectionRange(position: SelectionRangePosition) {
return position !== "none"
}
/** Full-width, square-corner highlights for the queue sidebar. */
export const QUEUE_ROW_HIGHLIGHT_INSET = "absolute inset-0"
export function QueueSelectionRangeHighlight({
position,
}: {
position: SelectionRangePosition
}) {
if (position === "none") {
return null
}
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-primary",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
export function QueueTrackRowHoverHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60 opacity-0 transition-opacity group-hover:opacity-100",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}
export function QueueTrackRowActiveHighlight() {
return (
<div
aria-hidden
className={cn(
"pointer-events-none bg-muted/60",
QUEUE_ROW_HIGHLIGHT_INSET
)}
/>
)
}