Files
otunes/apps/web/components/track-row.tsx
T

553 lines
16 KiB
TypeScript

"use client"
import * as React from "react"
import Image from "next/image"
import Link from "next/link"
import { ArrowDownToLine, 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 { 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 { formatDuration } from "@/lib/format-duration"
import { useSongDownloadState } from "@/hooks/use-downloads"
import { cn } from "@/lib/utils"
import type { BrowseSong } from "@otunes/convex/types"
import type { DownloadSource } from "@otunes/convex/client/download-queue"
/**
* - `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
/** The download this row belongs to; defaults to Other Downloaded Songs. */
downloadCollection?: DownloadSource
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" and right-click menus 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"
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] leading-none font-semibold",
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,
downloadCollection,
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 downloadState = useSongDownloadState(song.id, downloadCollection)
const isDownloaded = downloadState === "here"
const showDownloaded = isDownloaded || downloadState === "device"
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(
"flex shrink-0 items-center justify-end gap-2 tabular-nums",
variant === "queue" && "text-xs",
inRange ? "text-primary-foreground" : "text-muted-foreground"
)}
>
{showDownloaded ? (
<ArrowDownToLine className="size-3.5" aria-label="Downloaded" />
) : null}
{formatDuration(song.durationSeconds)}
</span>
)
// 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 },
downloaded: isDownloaded,
children:
removeLabel && onRemove ? (
<>
<MediaMenuSeparator />
<MediaMenuItem
variant="destructive"
className="justify-between"
onClick={() => onRemove(song.id)}
>
{removeLabel}
<Trash2 />
</MediaMenuItem>
</>
) : null,
}
: null
const menu = menuProps ? <MediaContextMenu {...menuProps} /> : null
let content: React.ReactNode
switch (variant) {
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 text-left text-sm transition-colors select-none",
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}
</>
)
const shell =
variant === "queue" ? (
<li ref={ref as React.Ref<HTMLLIElement>} {...shellProps}>
{children}
</li>
) : (
<div ref={ref as React.Ref<HTMLDivElement>} {...shellProps}>
{children}
</div>
)
return menuProps ? (
<MediaContextMenuArea menu={menuProps}>{shell}</MediaContextMenuArea>
) : (
shell
)
}
/**
* 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)