From 5704b937fe6c222f6457b919473a0d83f22b0ee2 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Thu, 4 Jun 2026 20:06:43 -0400 Subject: [PATCH] feat: queue management --- app/(app)/layout.tsx | 23 +- components/album-card.tsx | 99 ++++---- components/album-view.tsx | 71 +++--- components/artist-view.tsx | 24 +- components/artists-view.tsx | 14 +- components/media-context-menu.tsx | 15 +- components/playback-provider.tsx | 275 ++++++++++++++++++++ components/playback-song-meta.tsx | 67 +++++ components/player-bar.tsx | 154 ++++++++++-- components/playlist-card.tsx | 76 +++--- components/playlist-view.tsx | 76 +++--- components/queue-panel.tsx | 293 ++++++++++++++++++++++ components/search-song-item.tsx | 12 +- components/songs-view.tsx | 42 +++- components/track-number-play-button.tsx | 58 +++++ convex/_generated/api.d.ts | 2 + convex/library.ts | 20 ++ convex/playback.ts | 318 ++++++++++++++++++++++++ convex/playlists.ts | 36 +++ convex/schema.ts | 4 + hooks/use-queue-media-actions.ts | 64 +++++ lib/move-queue-block.ts | 45 ++++ lib/selection-range-styles.tsx | 47 ++++ lib/shuffle-array.ts | 8 + oTunes.icon/Assets/music.note.png | Bin 0 -> 9041 bytes oTunes.icon/icon.json | 47 ++++ public/logo-monochrome.svg | 11 + public/logo.svg | 1 - 28 files changed, 1699 insertions(+), 203 deletions(-) create mode 100644 components/playback-provider.tsx create mode 100644 components/playback-song-meta.tsx create mode 100644 components/queue-panel.tsx create mode 100644 components/track-number-play-button.tsx create mode 100644 convex/playback.ts create mode 100644 hooks/use-queue-media-actions.ts create mode 100644 lib/move-queue-block.ts create mode 100644 lib/shuffle-array.ts create mode 100644 oTunes.icon/Assets/music.note.png create mode 100644 oTunes.icon/icon.json create mode 100644 public/logo-monochrome.svg delete mode 100644 public/logo.svg diff --git a/app/(app)/layout.tsx b/app/(app)/layout.tsx index 36f78b3..7a972e1 100644 --- a/app/(app)/layout.tsx +++ b/app/(app)/layout.tsx @@ -1,8 +1,10 @@ import { AddToPlaylistProvider } from "@/components/add-to-playlist-provider" import { FavoritesProvider } from "@/components/favorites-provider" +import { PlaybackProvider } from "@/components/playback-provider" +import { PlayerBar } from "@/components/player-bar" +import { QueuePanel } from "@/components/queue-panel" import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar" import { AppSidebar } from "@/components/app-sidebar" -import { PlayerBar } from "@/components/player-bar" export default function AppLayout({ children, @@ -11,13 +13,18 @@ export default function AppLayout({ }>) { return ( - - - - {children} - - - + + + + +
+ {children} + +
+ +
+
+
) } diff --git a/components/album-card.tsx b/components/album-card.tsx index 32bec2c..a3b69a9 100644 --- a/components/album-card.tsx +++ b/components/album-card.tsx @@ -2,19 +2,18 @@ import Image from "next/image" import Link from "next/link" -import { - ListEnd, - ListPlus, - ListStart, - MoreHorizontal, - Play, - Star, - User, -} from "lucide-react" -import { toast } from "sonner" +import { MoreHorizontal, Play } from "lucide-react" +import { useConvex } from "convex/react" import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" +import { + MediaContextMenuItems, + type MediaContextAction, +} from "@/components/media-context-menu" +import { usePlayback } from "@/components/playback-provider" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { api } from "@/convex/_generated/api" import { Button } from "@/components/ui/button" import { DropdownMenu, @@ -28,8 +27,31 @@ import type { Id } from "@/convex/_generated/dataModel" import { albumCoverUrl } from "@/lib/cover-urls" export function AlbumCard({ album }: { album: BrowseAlbum }) { + const convex = useConvex() const { openAddAlbumToPlaylist } = useAddToPlaylist() const { isAlbumFavorite, toggleAlbumFavorite } = useFavorites() + const { playAlbum } = usePlayback() + const { runQueueAction } = useQueueMediaActions() + + async function handleCardAction(action: MediaContextAction) { + switch (action) { + case "playlist": + void openAddAlbumToPlaylist(album.id as Id<"albums">) + break + case "favorite": + void toggleAlbumFavorite(album.id as Id<"albums">) + break + case "play-next": + case "play-last": + case "shuffle": { + const songIds = await convex.query(api.playlists.getAlbumSongIds, { + albumId: album.id as Id<"albums">, + }) + void runQueueAction(action, songIds) + break + } + } + } return (
@@ -49,12 +71,15 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) {
-
+
@@ -72,50 +97,12 @@ export function AlbumCard({ album }: { album: BrowseAlbum }) { - { - event.preventDefault() - void openAddAlbumToPlaylist(album.id as Id<"albums">) - }} - > - Add to Playlist - - - - event.preventDefault()} - > - Play Next - - - event.preventDefault()} - > - Play Last - - - - - - Go to Artist - - - - - { - event.preventDefault() - void toggleAlbumFavorite(album.id as Id<"albums">) - }} - > - {isAlbumFavorite(album.id) ? "Unfavorite" : "Favorite"} - - + void handleCardAction(action)} + favorited={isAlbumFavorite(album.id)} + navigation={{ artist: { id: album.artist.id } }} + />
diff --git a/components/album-view.tsx b/components/album-view.tsx index 8837b33..b654e35 100644 --- a/components/album-view.tsx +++ b/components/album-view.tsx @@ -5,9 +5,12 @@ import Image from "next/image" import Link from "next/link" import { Play, Share2, Shuffle, Star } from "lucide-react" +import { TrackNumberPlayButton } from "@/components/track-number-play-button" + import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { FavoriteMediaButton } from "@/components/favorite-media-button" import { useFavorites } from "@/components/favorites-provider" +import { usePlayback } from "@/components/playback-provider" import { toast } from "sonner" import { @@ -16,6 +19,7 @@ import { } from "@/components/media-context-menu" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { useTrackSelection } from "@/hooks/use-track-selection" import { cn } from "@/lib/utils" import type { Id } from "@/convex/_generated/dataModel" @@ -74,6 +78,8 @@ function TrackRow({ onToggleFavorite, onPrepareContextMenu, onMediaAction, + isNowPlaying, + onPlay, }: { track: BrowseAlbumTrack index: number @@ -88,6 +94,8 @@ function TrackRow({ onToggleFavorite: () => void onPrepareContextMenu: () => void onMediaAction: (action: MediaContextAction, trackId: string) => void + isNowPlaying: boolean + onPlay: () => void }) { const displayTrack = track.track > 0 ? track.track : index + 1 const inRange = isInSelectionRange(selectionPosition) @@ -98,6 +106,10 @@ function TrackRow({ tabIndex={0} onMouseDown={onPointerDown} onClick={onSelect} + onDoubleClick={(event) => { + event.preventDefault() + onPlay() + }} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault() @@ -145,23 +157,14 @@ function TrackRow({
-
- {isActive ? ( - - ) : ( - {displayTrack} - )} -
+ {track.title} @@ -199,6 +202,13 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) { toggleAlbumFavorite, favoriteSongs, } = useFavorites() + const { currentSong, playFromSong, playAlbum, playAlbumShuffled } = + usePlayback() + const { runQueueAction } = useQueueMediaActions() + const albumSongIds = React.useMemo( + () => album.tracks.map((track) => track.id as Id<"songs">), + [album.tracks] + ) const metadata = formatMetadata(album.genre, album.year) const [activeTrackId, setActiveTrackId] = React.useState( () => album.tracks[0]?.id ?? "" @@ -231,8 +241,6 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) { : activeTrackId ? [activeTrackId] : [] - const count = targetIds.length - switch (action) { case "favorite": void favoriteSongs(targetIds as Id<"songs">[]) @@ -241,34 +249,27 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) { openAddToPlaylist(targetIds as Id<"songs">[]) break case "play-next": - toast.success( - count > 1 ? `Queued ${count} songs to play next` : "Play next" - ) - break case "play-last": - toast.success( - count > 1 ? `Queued ${count} songs to play last` : "Play last" - ) + case "shuffle": + void runQueueAction(action, targetIds as Id<"songs">[]) break } } function handleAlbumMediaAction(action: MediaContextAction) { - const targetIds = album.tracks.map((track) => track.id) - const count = targetIds.length + const targetIds = album.tracks.map((track) => track.id as Id<"songs">) switch (action) { case "favorite": void toggleAlbumFavorite(album.id as Id<"albums">) break case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) + openAddToPlaylist(targetIds) break case "play-next": - toast.success(`Queued ${count} songs to play next`) - break case "play-last": - toast.success(`Queued ${count} songs to play last`) + case "shuffle": + void runQueueAction(action, targetIds) break } } @@ -335,12 +336,14 @@ export function AlbumView({ album }: { album: BrowseAlbumDetail }) { size="icon" className="rounded-full" aria-label="Shuffle album" + onClick={() => void playAlbumShuffled(album.id as Id<"albums">)} > @@ -90,6 +101,9 @@ export function ArtistView({ size="icon" className="size-11 rounded-full" aria-label={`Shuffle ${artist.name}`} + onClick={() => + void playArtistShuffled(artist.id as Id<"artists">) + } > diff --git a/components/artists-view.tsx b/components/artists-view.tsx index b458d6d..9f45cce 100644 --- a/components/artists-view.tsx +++ b/components/artists-view.tsx @@ -8,6 +8,7 @@ import { ChevronRightIcon, Play, Shuffle } from "lucide-react" import { AlbumCard } from "@/components/album-card" import { FavoriteMediaButton } from "@/components/favorite-media-button" import { useFavorites } from "@/components/favorites-provider" +import { usePlayback } from "@/components/playback-provider" import { Button } from "@/components/ui/button" import { ScrollArea } from "@/components/ui/scroll-area" import { cn } from "@/lib/utils" @@ -68,6 +69,7 @@ export function ArtistsView({ () => sortedArtists[0]?.id ?? "" ) const { isArtistFavorite, toggleArtistFavorite } = useFavorites() + const { playArtist, playArtistShuffled } = usePlayback() const selectedArtist = sortedArtists.find( (artist) => artist.id === selectedId @@ -102,7 +104,14 @@ export function ArtistsView({
- diff --git a/components/media-context-menu.tsx b/components/media-context-menu.tsx index 30320eb..370da75 100644 --- a/components/media-context-menu.tsx +++ b/components/media-context-menu.tsx @@ -8,6 +8,7 @@ import { ListPlus, ListStart, MoreHorizontal, + Shuffle, Star, User, } from "lucide-react" @@ -22,7 +23,12 @@ import { } from "@/components/ui/dropdown-menu" import { cn } from "@/lib/utils" -export type MediaContextAction = "playlist" | "play-next" | "play-last" | "favorite" +export type MediaContextAction = + | "playlist" + | "play-next" + | "play-last" + | "shuffle" + | "favorite" export type MediaContextNavigation = { artist?: { id: string } @@ -74,6 +80,13 @@ export function MediaContextMenuItems({ {actionLabel("Play Last", selectedCount)} + onAction("shuffle")} + > + {actionLabel("Shuffle", selectedCount)} + + {artist || album ? ( <> diff --git a/components/playback-provider.tsx b/components/playback-provider.tsx new file mode 100644 index 0000000..0e57477 --- /dev/null +++ b/components/playback-provider.tsx @@ -0,0 +1,275 @@ +"use client" + +import * as React from "react" +import { useConvex, useMutation, useQuery } from "convex/react" + +import { api } from "@/convex/_generated/api" +import type { Id } from "@/convex/_generated/dataModel" +import type { BrowseSong } from "@/convex/library" + +type RepeatMode = "none" | "once" | "always" + +type PlaybackContextValue = { + queue: BrowseSong[] + currentSong: BrowseSong | null + shuffleEnabled: boolean + repeatEnabled: RepeatMode + queueOpen: boolean + isPlaying: boolean + volume: number + setQueueOpen: (open: boolean) => void + toggleQueueOpen: () => void + setIsPlaying: (playing: boolean) => void + setVolume: (volume: number) => void + playInOrder: (songIds: Id<"songs">[]) => Promise + playShuffled: (songIds: Id<"songs">[]) => Promise + addToQueueNext: (songIds: Id<"songs">[]) => Promise + addToQueueLast: (songIds: Id<"songs">[]) => Promise + playFromSong: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise + playAlbum: (albumId: Id<"albums">) => Promise + playAlbumShuffled: (albumId: Id<"albums">) => Promise + playArtist: (artistId: Id<"artists">) => Promise + playArtistShuffled: (artistId: Id<"artists">) => Promise + playPlaylist: (playlistId: Id<"playlists">) => Promise + playPlaylistShuffled: (playlistId: Id<"playlists">) => Promise + toggleShuffle: () => Promise + cycleRepeat: () => Promise + clearQueue: () => Promise + reorderQueue: (songIds: Id<"songs">[]) => Promise + skipToQueueIndex: (index: number) => Promise + skipNext: () => Promise + skipPrevious: () => Promise +} + +const PlaybackContext = React.createContext(null) + +export function usePlayback() { + const context = React.useContext(PlaybackContext) + if (!context) { + throw new Error("usePlayback must be used within PlaybackProvider") + } + return context +} + +export function PlaybackProvider({ children }: { children: React.ReactNode }) { + const convex = useConvex() + const playback = useQuery(api.playback.getPlaybackState) + const playInOrderMutation = useMutation(api.playback.playInOrder) + const playShuffledMutation = useMutation(api.playback.playShuffled) + const addToQueueNextMutation = useMutation(api.playback.addToQueueNext) + const addToQueueLastMutation = useMutation(api.playback.addToQueueLast) + const playFromSongMutation = useMutation(api.playback.playFromSong) + const toggleShuffleMutation = useMutation(api.playback.toggleShuffle) + const cycleRepeatMutation = useMutation(api.playback.cycleRepeat) + const clearQueueMutation = useMutation(api.playback.clearQueue) + const reorderQueueMutation = useMutation(api.playback.reorderQueue) + const skipToQueueIndexMutation = useMutation(api.playback.skipToQueueIndex) + const skipNextMutation = useMutation(api.playback.skipNext) + const skipPreviousMutation = useMutation(api.playback.skipPrevious) + + const [queueOpen, setQueueOpen] = React.useState(false) + const [isPlaying, setIsPlaying] = React.useState(false) + const [volume, setVolume] = React.useState(80) + + React.useEffect(() => { + if (playback?.currentSong) { + setIsPlaying(true) + } else { + setIsPlaying(false) + } + }, [playback?.currentSong?.id]) + + const playInOrder = React.useCallback( + async (songIds: Id<"songs">[]) => { + if (songIds.length === 0) { + return + } + await playInOrderMutation({ songIds }) + setIsPlaying(true) + }, + [playInOrderMutation] + ) + + const playShuffled = React.useCallback( + async (songIds: Id<"songs">[]) => { + if (songIds.length === 0) { + return + } + await playShuffledMutation({ songIds }) + setIsPlaying(true) + }, + [playShuffledMutation] + ) + + const addToQueueNext = React.useCallback( + async (songIds: Id<"songs">[]) => { + if (songIds.length === 0) { + return + } + await addToQueueNextMutation({ songIds }) + setIsPlaying(true) + }, + [addToQueueNextMutation] + ) + + const addToQueueLast = React.useCallback( + async (songIds: Id<"songs">[]) => { + if (songIds.length === 0) { + return + } + await addToQueueLastMutation({ songIds }) + setIsPlaying(true) + }, + [addToQueueLastMutation] + ) + + const playFromSong = React.useCallback( + async (songId: Id<"songs">, songIds: Id<"songs">[]) => { + await playFromSongMutation({ songId, songIds }) + setIsPlaying(true) + }, + [playFromSongMutation] + ) + + const playAlbum = React.useCallback( + async (albumId: Id<"albums">) => { + const songIds = await convex.query(api.playlists.getAlbumSongIds, { + albumId, + }) + await playInOrder(songIds) + }, + [convex, playInOrder] + ) + + const playAlbumShuffled = React.useCallback( + async (albumId: Id<"albums">) => { + const songIds = await convex.query(api.playlists.getAlbumSongIds, { + albumId, + }) + await playShuffled(songIds) + }, + [convex, playShuffled] + ) + + const playArtist = React.useCallback( + async (artistId: Id<"artists">) => { + const songIds = await convex.query(api.playlists.getOrderedArtistSongIds, { + artistId, + }) + await playInOrder(songIds) + }, + [convex, playInOrder] + ) + + const playArtistShuffled = React.useCallback( + async (artistId: Id<"artists">) => { + const songIds = await convex.query(api.playlists.getOrderedArtistSongIds, { + artistId, + }) + await playShuffled(songIds) + }, + [convex, playShuffled] + ) + + const playPlaylist = React.useCallback( + async (playlistId: Id<"playlists">) => { + const songIds = await convex.query(api.playlists.getPlaylistSongIds, { + playlistId, + }) + await playInOrder(songIds) + }, + [convex, playInOrder] + ) + + const playPlaylistShuffled = React.useCallback( + async (playlistId: Id<"playlists">) => { + const songIds = await convex.query(api.playlists.getPlaylistSongIds, { + playlistId, + }) + await playShuffled(songIds) + }, + [convex, playShuffled] + ) + + const toggleQueueOpen = React.useCallback(() => { + setQueueOpen((open) => !open) + }, []) + + const value = React.useMemo( + () => ({ + queue: playback?.queue ?? [], + currentSong: playback?.currentSong ?? null, + shuffleEnabled: playback?.shuffleEnabled ?? false, + repeatEnabled: playback?.repeatEnabled ?? "none", + queueOpen, + isPlaying, + volume, + setQueueOpen, + toggleQueueOpen, + setIsPlaying, + setVolume, + playInOrder, + playShuffled, + addToQueueNext, + addToQueueLast, + playFromSong, + playAlbum, + playAlbumShuffled, + playArtist, + playArtistShuffled, + playPlaylist, + playPlaylistShuffled, + toggleShuffle: async () => { + await toggleShuffleMutation() + }, + cycleRepeat: async () => { + await cycleRepeatMutation() + }, + clearQueue: async () => { + await clearQueueMutation() + setIsPlaying(false) + }, + reorderQueue: async (songIds) => { + await reorderQueueMutation({ songIds }) + }, + skipToQueueIndex: async (index) => { + await skipToQueueIndexMutation({ index }) + }, + skipNext: async () => { + await skipNextMutation() + }, + skipPrevious: async () => { + await skipPreviousMutation() + }, + }), + [ + playback, + queueOpen, + isPlaying, + volume, + toggleQueueOpen, + playInOrder, + playShuffled, + addToQueueNext, + addToQueueLast, + playFromSong, + playAlbum, + playAlbumShuffled, + playArtist, + playArtistShuffled, + playPlaylist, + playPlaylistShuffled, + toggleShuffleMutation, + cycleRepeatMutation, + clearQueueMutation, + reorderQueueMutation, + skipToQueueIndexMutation, + skipNextMutation, + skipPreviousMutation, + ] + ) + + return ( + {children} + ) +} diff --git a/components/playback-song-meta.tsx b/components/playback-song-meta.tsx new file mode 100644 index 0000000..5538813 --- /dev/null +++ b/components/playback-song-meta.tsx @@ -0,0 +1,67 @@ +import Link from "next/link" + +import type { BrowseSong } from "@/convex/library" +import { cn } from "@/lib/utils" + +export function PlaybackSongMeta({ + song, + isCurrent = false, + inRange = false, + align = "center", + showAlbum = true, +}: { + song: BrowseSong + isCurrent?: boolean + inRange?: boolean + align?: "center" | "start" + showAlbum?: boolean +}) { + return ( +
+ + {song.title} + +

+ + {song.artist.name} + + {showAlbum ? ( + <> + + + {song.album.title} + + + ) : null} +

+
+ ) +} diff --git a/components/player-bar.tsx b/components/player-bar.tsx index c72c3c7..fddacc7 100644 --- a/components/player-bar.tsx +++ b/components/player-bar.tsx @@ -1,58 +1,168 @@ "use client" +import Image from "next/image" import { ListMusic, Music, Pause, + Play, Repeat, + Repeat1, Shuffle, SkipBack, SkipForward, Volume2, } from "lucide-react" +import { PlaybackSongMeta } from "@/components/playback-song-meta" +import { usePlayback } from "@/components/playback-provider" import { Button } from "@/components/ui/button" +import { Slider } from "@/components/ui/slider" +import { useSidebar } from "@/components/ui/sidebar" +import { albumCoverUrl } from "@/lib/cover-urls" +import { cn } from "@/lib/utils" export function PlayerBar() { + const { + currentSong, + shuffleEnabled, + repeatEnabled, + queueOpen, + isPlaying, + volume, + queue, + setIsPlaying, + setVolume, + toggleQueueOpen, + toggleShuffle, + cycleRepeat, + skipNext, + skipPrevious, + } = usePlayback() + const { state, isMobile } = useSidebar() + + const hasQueue = queue.length > 0 + const sidebarExpanded = !isMobile && state === "expanded" + return ( -
-
-
- - - - -
-
-
-
-

Ends of the Earth

-

- The Longest Johns — Ends of the Earth -

-
+
+ {currentSong ? ( + <> +
+ {currentSong.album.title} +
+
+ +
+ + ) : ( +
+ oTunes +
+ )}
-
- - -
diff --git a/components/playlist-card.tsx b/components/playlist-card.tsx index acf00f8..1b743e3 100644 --- a/components/playlist-card.tsx +++ b/components/playlist-card.tsx @@ -6,13 +6,48 @@ import Link from "next/link" import type { PlaylistSummary } from "@/convex/library" import type { Id } from "@/convex/_generated/dataModel" import { playlistCoverUrl } from "@/lib/cover-urls" +import { useConvex } from "convex/react" +import { MoreHorizontal, Play } from "lucide-react" + import { useAddToPlaylist } from "@/components/add-to-playlist-provider" +import { + MediaContextMenuItems, + type MediaContextAction, +} from "@/components/media-context-menu" +import { usePlayback } from "@/components/playback-provider" import { Button } from "@/components/ui/button" -import { ListEnd, ListPlus, ListStart, MoreHorizontal, Play } from "lucide-react" -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" +import { api } from "@/convex/_generated/api" export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { + const convex = useConvex() const { openAddPlaylistToPlaylist } = useAddToPlaylist() + const { playPlaylist } = usePlayback() + const { runQueueAction } = useQueueMediaActions() + + async function handleCardAction(action: MediaContextAction) { + switch (action) { + case "playlist": + void openAddPlaylistToPlaylist(playlist.id as Id<"playlists">) + break + case "play-next": + case "play-last": + case "shuffle": { + const songIds = await convex.query(api.playlists.getPlaylistSongIds, { + playlistId: playlist.id as Id<"playlists">, + }) + void runQueueAction(action, songIds) + break + } + case "favorite": + break + } + } return (
@@ -29,12 +64,15 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) {
-
+
@@ -52,31 +90,11 @@ export function PlaylistCard({ playlist }: { playlist: PlaylistSummary }) { - { - event.preventDefault() - void openAddPlaylistToPlaylist(playlist.id as Id<"playlists">) - }} - > - Add to Playlist - - - - event.preventDefault()} - > - Play Next - - - event.preventDefault()} - > - Play Last - - + void handleCardAction(action)} + />
diff --git a/components/playlist-view.tsx b/components/playlist-view.tsx index fd1843b..01bd9fa 100644 --- a/components/playlist-view.tsx +++ b/components/playlist-view.tsx @@ -16,6 +16,8 @@ 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 { TrackNumberPlayButton } from "@/components/track-number-play-button" import { MediaContextMenu, MediaContextMenuItems, @@ -30,6 +32,7 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { ScrollArea } from "@/components/ui/scroll-area" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { useTrackSelection } from "@/hooks/use-track-selection" import { api } from "@/convex/_generated/api" import type { Id } from "@/convex/_generated/dataModel" @@ -152,6 +155,8 @@ function PlaylistSongRow({ onDrop, showFavoriteInMenu = true, removeLabel = "Remove from Playlist", + isNowPlaying, + onPlay, }: { song: BrowseSong index: number @@ -174,6 +179,8 @@ function PlaylistSongRow({ onDrop: (event: React.DragEvent) => void showFavoriteInMenu?: boolean removeLabel?: string + isNowPlaying: boolean + onPlay: () => void }) { const displayTrack = index + 1 const inRange = isInSelectionRange(selectionPosition) @@ -188,6 +195,10 @@ function PlaylistSongRow({ onDrop={onDrop} onMouseDown={onPointerDown} onClick={onSelect} + onDoubleClick={(event) => { + event.preventDefault() + onPlay() + }} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault() @@ -213,23 +224,14 @@ function PlaylistSongRow({ onToggleFavorite={onToggleFavorite} /> -
- {isActive ? ( - - ) : ( - {displayTrack} - )} -
+ {song.title} @@ -285,6 +287,13 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { toggleSongsFavorite, favoriteSongs: addFavoriteSongs, } = useFavorites() + const { + currentSong, + playInOrder, + playShuffled, + playFromSong, + } = usePlayback() + const { runQueueAction } = useQueueMediaActions() const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const reorderSongs = useMutation(api.playlists.reorderPlaylistSongs) const deletePlaylist = useMutation(api.playlists.deletePlaylist) @@ -292,6 +301,10 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist) const [songs, setSongs] = React.useState(playlist.songs) + const playlistSongIds = React.useMemo( + () => songs.map((song) => song.id as Id<"songs">), + [songs] + ) const [activeTrackId, setActiveTrackId] = React.useState( () => playlist.songs[0]?.id ?? "" ) @@ -338,7 +351,6 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { fallbackSongId?: string ) { const targetIds = resolveTargetIds(fallbackSongId) - const count = targetIds.length switch (action) { case "favorite": @@ -348,33 +360,27 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { openAddToPlaylist(targetIds as Id<"songs">[]) break case "play-next": - toast.success( - count > 1 ? `Queued ${count} songs to play next` : "Play next" - ) - break case "play-last": - toast.success( - count > 1 ? `Queued ${count} songs to play last` : "Play last" - ) + case "shuffle": + void runQueueAction(action, targetIds as Id<"songs">[]) break } } function handlePlaylistMediaAction(action: MediaContextAction) { - const targetIds = songs.map((song) => song.id) + const targetIds = songs.map((song) => song.id as Id<"songs">) switch (action) { case "favorite": - void addFavoriteSongs(targetIds as Id<"songs">[]) + void addFavoriteSongs(targetIds) break case "playlist": - openAddToPlaylist(targetIds as Id<"songs">[]) + openAddToPlaylist(targetIds) break case "play-next": - toast.success(`Queued ${targetIds.length} songs to play next`) - break case "play-last": - toast.success(`Queued ${targetIds.length} songs to play last`) + case "shuffle": + void runQueueAction(action, targetIds) break } } @@ -556,12 +562,16 @@ export function PlaylistView({ playlist }: { playlist: BrowsePlaylistDetail }) { size="icon" className="rounded-full" aria-label="Shuffle playlist" + onClick={() => void playShuffled(playlistSongIds)} + disabled={playlistSongIds.length === 0} > + + + + {queue.length === 0 ? ( +

+ Nothing in the queue. +

+ ) : ( +
    + {selectableQueue.map((song, index) => ( + { + handleSelect(song.selectionId, index, event) + }} + onSkipTo={() => void skipToQueueIndex(index)} + onDragStart={(event) => { + setDragIndex(index) + event.dataTransfer.effectAllowed = "move" + }} + onDragOver={(event) => event.preventDefault()} + onDrop={(event) => { + event.preventDefault() + handleDrop(index) + }} + /> + ))} +
+ )} +
+ + ) +} diff --git a/components/search-song-item.tsx b/components/search-song-item.tsx index 183a24d..3093727 100644 --- a/components/search-song-item.tsx +++ b/components/search-song-item.tsx @@ -2,10 +2,9 @@ import Image from "next/image" import Link from "next/link" -import { toast } from "sonner" - import { useAddToPlaylist } from "@/components/add-to-playlist-provider" import { useFavorites } from "@/components/favorites-provider" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { MediaContextMenu, type MediaContextAction, @@ -17,17 +16,18 @@ import { albumCoverUrl } from "@/lib/cover-urls" export function SearchSongItem({ song }: { song: BrowseSong }) { const { openAddToPlaylist } = useAddToPlaylist() const { isSongFavorite, toggleSongFavorite } = useFavorites() + const { runQueueAction } = useQueueMediaActions() + const songIds = [song.id as Id<"songs">] function handleAction(action: MediaContextAction) { switch (action) { case "playlist": - openAddToPlaylist([song.id as Id<"songs">]) + openAddToPlaylist(songIds) break case "play-next": - toast.success("Playing next") - break case "play-last": - toast.success("Added to queue") + case "shuffle": + void runQueueAction(action, songIds) break case "favorite": void toggleSongFavorite(song.id as Id<"songs">) diff --git a/components/songs-view.tsx b/components/songs-view.tsx index b29d26c..82f175f 100644 --- a/components/songs-view.tsx +++ b/components/songs-view.tsx @@ -8,6 +8,7 @@ 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 { MediaContextMenu, type MediaContextAction, @@ -22,6 +23,7 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" +import { useQueueMediaActions } from "@/hooks/use-queue-media-actions" import { useTrackSelection } from "@/hooks/use-track-selection" import { ScrollArea } from "@/components/ui/scroll-area" import { @@ -61,7 +63,15 @@ function formatDuration(seconds: number): string { return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}` } -function SongCover({ song, inRange }: { song: BrowseSong; inRange: boolean }) { +function SongCover({ + song, + inRange, + onPlay, +}: { + song: BrowseSong + inRange: boolean + onPlay: () => void +}) { return (
{ event.preventDefault() event.stopPropagation() + onPlay() }} > @@ -104,6 +115,7 @@ function SongRow({ onToggleFavorite, onPrepareContextMenu, onMediaAction, + onPlay, }: { song: BrowseSong index: number @@ -116,6 +128,7 @@ function SongRow({ onToggleFavorite: () => void onPrepareContextMenu: () => void onMediaAction: (action: MediaContextAction, songId: string) => void + onPlay: () => void }) { const inRange = isInSelectionRange(selectionPosition) const linkClass = inRange @@ -126,6 +139,10 @@ function SongRow({ { + event.preventDefault() + onPlay() + }} className="group cursor-pointer select-none border-none hover:bg-transparent" > @@ -170,7 +187,7 @@ function SongRow({ />
- + {song.title} {song.explicit ? ( @@ -238,6 +255,8 @@ function SongRow({ export function SongsView({ songs }: { songs: BrowseSong[] }) { const { openAddToPlaylist } = useAddToPlaylist() const { isSongFavorite, toggleSongFavorite, favoriteSongs } = useFavorites() + const { playFromSong } = usePlayback() + const { runQueueAction } = useQueueMediaActions() const [sortKey, setSortKey] = React.useState("title") const [sortDirection, setSortDirection] = React.useState("asc") @@ -283,6 +302,11 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) { [sortedSongs, selectedIds] ) + const sortedSongIds = React.useMemo( + () => sortedSongs.map((song) => song.id as Id<"songs">), + [sortedSongs] + ) + function handleMediaAction(action: MediaContextAction, fallbackSongId?: string) { const targetIds = selectedIds.size > 0 @@ -290,8 +314,6 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) { : fallbackSongId ? [fallbackSongId] : [] - const count = targetIds.length - switch (action) { case "favorite": void favoriteSongs(targetIds as Id<"songs">[]) @@ -300,14 +322,9 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) { openAddToPlaylist(targetIds as Id<"songs">[]) break case "play-next": - toast.success( - count > 1 ? `Queued ${count} songs to play next` : "Play next" - ) - break case "play-last": - toast.success( - count > 1 ? `Queued ${count} songs to play last` : "Play last" - ) + case "shuffle": + void runQueueAction(action, targetIds as Id<"songs">[]) break } } @@ -421,6 +438,9 @@ export function SongsView({ songs }: { songs: BrowseSong[] }) { } onPrepareContextMenu={() => prepareContextMenu(song.id)} onMediaAction={handleMediaAction} + onPlay={() => + void playFromSong(song.id as Id<"songs">, sortedSongIds) + } /> ))} diff --git a/components/track-number-play-button.tsx b/components/track-number-play-button.tsx new file mode 100644 index 0000000..b2f1bd8 --- /dev/null +++ b/components/track-number-play-button.tsx @@ -0,0 +1,58 @@ +import { Play } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { cn } from "@/lib/utils" + +export function TrackNumberPlayButton({ + displayTrack, + title, + isActive, + isNowPlaying, + inRange, + onPlay, +}: { + displayTrack: number | string + title: string + isActive: boolean + isNowPlaying: boolean + inRange: boolean + onPlay: () => void +}) { + const showPlay = isActive || isNowPlaying + + return ( +
+ + {displayTrack} + + +
+ ) +} diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index d65bf0f..a2c0df9 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -14,6 +14,7 @@ import type * as crons from "../crons.js"; import type * as favorites from "../favorites.js"; import type * as http from "../http.js"; import type * as library from "../library.js"; +import type * as playback from "../playback.js"; import type * as playlists from "../playlists.js"; import type * as users from "../users.js"; @@ -30,6 +31,7 @@ declare const fullApi: ApiFromModules<{ favorites: typeof favorites; http: typeof http; library: typeof library; + playback: typeof playback; playlists: typeof playlists; users: typeof users; }>; diff --git a/convex/library.ts b/convex/library.ts index 6fe387b..b2ef4c8 100644 --- a/convex/library.ts +++ b/convex/library.ts @@ -126,6 +126,26 @@ function toBrowseAlbum( } } +export async function browseSongsFromIds( + ctx: QueryCtx, + songIds: Id<"songs">[] +): Promise { + const songs: BrowseSong[] = [] + for (const songId of songIds) { + const song = await ctx.db.get("songs", songId) + if (!song) { + continue + } + const album = await ctx.db.get("albums", song.album) + const albumArtist = await ctx.db.get("artists", song.albumArtist) + if (!album || !albumArtist) { + continue + } + songs.push(toBrowseSong(song, album, albumArtist)) + } + return songs +} + function toBrowseSong( song: Doc<"songs">, album: Doc<"albums">, diff --git a/convex/playback.ts b/convex/playback.ts new file mode 100644 index 0000000..7d35130 --- /dev/null +++ b/convex/playback.ts @@ -0,0 +1,318 @@ +import { getAuthUserId } from "@convex-dev/auth/server" +import { ConvexError, v } from "convex/values" +import type { Id } from "./_generated/dataModel" +import type { MutationCtx } from "./_generated/server" +import { mutation, query } from "./_generated/server" +import { browseSongsFromIds } from "./library" + +function shuffleArray(items: T[]): T[] { + const next = [...items] + for (let i = next.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)) + ;[next[i], next[j]] = [next[j], next[i]] + } + return next +} + +async function requireAuth(ctx: MutationCtx) { + const userId = await getAuthUserId(ctx) + if (userId === null) { + throw new ConvexError("Not authenticated") + } + return userId +} + +function uniqueSongIds(songIds: Id<"songs">[]) { + return [...new Set(songIds)] +} + +async function setQueueState( + ctx: MutationCtx, + userId: Id<"users">, + patch: { + songQueue: Id<"songs">[] + shuffleEnabled?: boolean + currentSongProgress?: number + } +) { + await ctx.db.patch(userId, { + songQueue: patch.songQueue, + currentSongProgress: patch.currentSongProgress ?? 0, + ...(patch.shuffleEnabled !== undefined + ? { shuffleEnabled: patch.shuffleEnabled } + : {}), + }) +} + +export const getPlaybackState = query({ + args: {}, + handler: async (ctx) => { + const userId = await getAuthUserId(ctx) + if (userId === null) { + return null + } + + const user = await ctx.db.get(userId) + if (!user) { + return null + } + + const songIds = user.songQueue ?? [] + const queue = await browseSongsFromIds(ctx, songIds) + + return { + queue, + currentSong: queue[0] ?? null, + shuffleEnabled: user.shuffleEnabled ?? false, + repeatEnabled: user.repeatEnabled ?? ("none" as const), + currentSongProgress: user.currentSongProgress ?? 0, + } + }, +}) + +export const playInOrder = mutation({ + args: { songIds: v.array(v.id("songs")) }, + handler: async (ctx, { songIds }) => { + const userId = await requireAuth(ctx) + const queue = uniqueSongIds(songIds) + await setQueueState(ctx, userId, { + songQueue: queue, + shuffleEnabled: false, + }) + }, +}) + +export const playShuffled = mutation({ + args: { songIds: v.array(v.id("songs")) }, + handler: async (ctx, { songIds }) => { + const userId = await requireAuth(ctx) + const queue = shuffleArray(uniqueSongIds(songIds)) + await setQueueState(ctx, userId, { songQueue: queue }) + }, +}) + +function orderSongsForInsert( + songIds: Id<"songs">[], + shuffleEnabled: boolean +): Id<"songs">[] { + return shuffleEnabled ? shuffleArray(songIds) : songIds +} + +export const addToQueueNext = mutation({ + args: { songIds: v.array(v.id("songs")) }, + handler: async (ctx, { songIds }) => { + if (songIds.length === 0) { + return + } + + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false) + const queue = user.songQueue ?? [] + + if (queue.length === 0) { + await setQueueState(ctx, userId, { songQueue: toAdd }) + return + } + + const [current, ...rest] = queue + await setQueueState(ctx, userId, { + songQueue: [current, ...toAdd, ...rest], + }) + }, +}) + +export const addToQueueLast = mutation({ + args: { songIds: v.array(v.id("songs")) }, + handler: async (ctx, { songIds }) => { + if (songIds.length === 0) { + return + } + + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const toAdd = orderSongsForInsert(songIds, user.shuffleEnabled ?? false) + const queue = user.songQueue ?? [] + + await setQueueState(ctx, userId, { + songQueue: queue.length === 0 ? toAdd : [...queue, ...toAdd], + }) + }, +}) + +export const playFromSong = mutation({ + args: { + songId: v.id("songs"), + songIds: v.array(v.id("songs")), + }, + handler: async (ctx, { songId, songIds }) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const index = songIds.indexOf(songId) + const rest = index === -1 ? [] : songIds.slice(index + 1) + const queueRest = user.shuffleEnabled ? shuffleArray(rest) : rest + + await setQueueState(ctx, userId, { + songQueue: [songId, ...queueRest], + }) + }, +}) + +export const toggleShuffle = mutation({ + args: {}, + handler: async (ctx) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const shuffleEnabled = !(user.shuffleEnabled ?? false) + const queue = user.songQueue ?? [] + + if (shuffleEnabled && queue.length > 1) { + const [current, ...upNext] = queue + await ctx.db.patch(userId, { + shuffleEnabled: true, + songQueue: [current, ...shuffleArray(upNext)], + }) + return + } + + await ctx.db.patch(userId, { shuffleEnabled }) + }, +}) + +export const cycleRepeat = mutation({ + args: {}, + handler: async (ctx) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const current = user.repeatEnabled ?? "none" + const next = + current === "none" ? "once" : current === "once" ? "always" : "none" + + await ctx.db.patch(userId, { repeatEnabled: next }) + }, +}) + +export const clearQueue = mutation({ + args: {}, + handler: async (ctx) => { + const userId = await requireAuth(ctx) + await ctx.db.patch(userId, { + songQueue: [], + currentSongProgress: 0, + }) + }, +}) + +export const reorderQueue = mutation({ + args: { songIds: v.array(v.id("songs")) }, + handler: async (ctx, { songIds }) => { + const userId = await requireAuth(ctx) + await ctx.db.patch(userId, { songQueue: songIds }) + }, +}) + +export const skipToQueueIndex = mutation({ + args: { index: v.number() }, + handler: async (ctx, { index }) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const queue = user.songQueue ?? [] + if (index < 0 || index >= queue.length) { + return + } + + await ctx.db.patch(userId, { + songQueue: [...queue.slice(index), ...queue.slice(0, index)], + currentSongProgress: 0, + }) + }, +}) + +export const skipNext = mutation({ + args: {}, + handler: async (ctx) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const queue = user.songQueue ?? [] + if (queue.length === 0) { + return + } + + const repeat = user.repeatEnabled ?? "none" + + if (repeat === "once") { + await ctx.db.patch(userId, { currentSongProgress: 0 }) + return + } + + if (queue.length === 1 && repeat === "none") { + await ctx.db.patch(userId, { + songQueue: [], + currentSongProgress: 0, + }) + return + } + + const [current, ...rest] = queue + const nextQueue = + repeat === "always" ? [...rest, current] : rest + + await ctx.db.patch(userId, { + songQueue: nextQueue, + currentSongProgress: 0, + }) + }, +}) + +export const skipPrevious = mutation({ + args: {}, + handler: async (ctx) => { + const userId = await requireAuth(ctx) + const user = await ctx.db.get(userId) + if (!user) { + throw new ConvexError("User not found") + } + + const queue = user.songQueue ?? [] + if (queue.length <= 1) { + await ctx.db.patch(userId, { currentSongProgress: 0 }) + return + } + + const last = queue[queue.length - 1] + const nextQueue = [last, ...queue.slice(0, -1)] + + await ctx.db.patch(userId, { + songQueue: nextQueue, + currentSongProgress: 0, + }) + }, +}) diff --git a/convex/playlists.ts b/convex/playlists.ts index 62c2c96..340b725 100644 --- a/convex/playlists.ts +++ b/convex/playlists.ts @@ -299,6 +299,12 @@ export const getAlbumSongIds = query({ .query("songs") .withIndex("by_album", (q) => q.eq("album", args.albumId)) .collect() + songs.sort((a, b) => { + if (a.track !== b.track) { + return a.track - b.track + } + return a.name.localeCompare(b.name) + }) return songs.map((song) => song._id) }, }) @@ -314,6 +320,36 @@ export const getArtistSongIds = query({ }, }) +export const getOrderedArtistSongIds = query({ + args: { artistId: v.id("artists") }, + handler: async (ctx, args) => { + const songs = await ctx.db + .query("songs") + .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) + .collect() + + const albums = await ctx.db + .query("albums") + .withIndex("by_artist", (q) => q.eq("artist", args.artistId)) + .collect() + const albumMap = new Map(albums.map((album) => [album._id, album])) + + songs.sort((a, b) => { + const albumA = albumMap.get(a.album)?.name ?? "" + const albumB = albumMap.get(b.album)?.name ?? "" + if (albumA !== albumB) { + return albumA.localeCompare(albumB) + } + if (a.track !== b.track) { + return a.track - b.track + } + return a.name.localeCompare(b.name) + }) + + return songs.map((song) => song._id) + }, +}) + export const getPlaylistSongIds = query({ args: { playlistId: v.id("playlists") }, handler: async (ctx, args) => { diff --git a/convex/schema.ts b/convex/schema.ts index b329233..9e97a55 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -22,6 +22,10 @@ export default defineSchema({ favoriteArtists: v.optional(v.array(v.id("artists"))), favoriteAlbums: v.optional(v.array(v.id("albums"))), favoriteSongs: v.optional(v.array(v.id("songs"))), + songQueue: v.optional(v.array(v.id("songs"))), + currentSongProgress: v.optional(v.number()), + shuffleEnabled: v.optional(v.boolean()), + repeatEnabled: v.optional(v.union(v.literal("always"), v.literal("once"), v.literal("none"))), }).index("email", ["email"]), appSettings: defineTable({ disableAccountCreation: v.boolean(), diff --git a/hooks/use-queue-media-actions.ts b/hooks/use-queue-media-actions.ts new file mode 100644 index 0000000..c48b275 --- /dev/null +++ b/hooks/use-queue-media-actions.ts @@ -0,0 +1,64 @@ +"use client" + +import * as React from "react" +import { toast } from "sonner" + +import { usePlayback } from "@/components/playback-provider" +import type { MediaContextAction } from "@/components/media-context-menu" +import type { Id } from "@/convex/_generated/dataModel" + +export type QueueMediaAction = Extract< + MediaContextAction, + "play-next" | "play-last" | "shuffle" +> + +function queueActionMessage(action: QueueMediaAction, count: number) { + switch (action) { + case "play-next": + return count > 1 + ? `Queued ${count} songs to play next` + : "Queued to play next" + case "play-last": + return count > 1 + ? `Queued ${count} songs to play last` + : "Queued to play last" + case "shuffle": + return count > 1 + ? `Playing ${count} songs shuffled` + : "Playing shuffled" + } +} + +export function useQueueMediaActions() { + const { addToQueueNext, addToQueueLast, playShuffled } = usePlayback() + + const runQueueAction = React.useCallback( + async (action: QueueMediaAction, songIds: Id<"songs">[]) => { + if (songIds.length === 0) { + return + } + + try { + switch (action) { + case "play-next": + await addToQueueNext(songIds) + break + case "play-last": + await addToQueueLast(songIds) + break + case "shuffle": + await playShuffled(songIds) + break + } + toast.success(queueActionMessage(action, songIds.length)) + } catch (error) { + toast.error( + error instanceof Error ? error.message : "Failed to update queue" + ) + } + }, + [addToQueueNext, addToQueueLast, playShuffled] + ) + + return { runQueueAction } +} diff --git a/lib/move-queue-block.ts b/lib/move-queue-block.ts new file mode 100644 index 0000000..9d03bf7 --- /dev/null +++ b/lib/move-queue-block.ts @@ -0,0 +1,45 @@ +export function getContiguousSelectedIndices( + items: { selectionId: string }[], + selectedIds: Set, + dragIndex: number +): number[] { + const selectedIndices = items + .map((item, index) => (selectedIds.has(item.selectionId) ? index : -1)) + .filter((index) => index >= 0) + + if ( + selectedIndices.length > 1 && + selectedIndices.includes(dragIndex) + ) { + return selectedIndices + } + + return [dragIndex] +} + +export function moveQueueBlock( + queue: T[], + fromIndices: number[], + targetIndex: number +): T[] { + const sorted = [...fromIndices].sort((a, b) => a - b) + if (sorted.length === 0) { + return queue + } + + const block = sorted.map((index) => queue[index]) + const remaining = queue.filter((_, index) => !sorted.includes(index)) + + const minSelected = sorted[0] + const maxSelected = sorted[sorted.length - 1] + if (targetIndex >= minSelected && targetIndex <= maxSelected) { + return queue + } + + const removedBefore = sorted.filter((index) => index < targetIndex).length + const insertAt = Math.max(0, Math.min(targetIndex - removedBefore, remaining.length)) + + const next = [...remaining] + next.splice(insertAt, 0, ...block) + return next +} diff --git a/lib/selection-range-styles.tsx b/lib/selection-range-styles.tsx index 2493a87..38ead70 100644 --- a/lib/selection-range-styles.tsx +++ b/lib/selection-range-styles.tsx @@ -160,3 +160,50 @@ 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 ( +
+ ) +} + +export function QueueTrackRowHoverHighlight() { + return ( +
+ ) +} + +export function QueueTrackRowActiveHighlight() { + return ( +
+ ) +} diff --git a/lib/shuffle-array.ts b/lib/shuffle-array.ts new file mode 100644 index 0000000..f6e3c97 --- /dev/null +++ b/lib/shuffle-array.ts @@ -0,0 +1,8 @@ +export function shuffleArray(items: T[]): T[] { + const next = [...items] + for (let i = next.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)) + ;[next[i], next[j]] = [next[j], next[i]] + } + return next +} diff --git a/oTunes.icon/Assets/music.note.png b/oTunes.icon/Assets/music.note.png new file mode 100644 index 0000000000000000000000000000000000000000..83a50474a425345efa04c8b1c0dd4186735832d8 GIT binary patch literal 9041 zcmdsddpy(q|M#{=qc9s1VwjP$9CB`sZHN$&(=5kGHdAP=_)Hv|IV zAregOAP}e;1OkI0IKj&8<7>;{3mR&7&=^wHDK-uMF!gpK`W!k0kq5sK5NMJ=1irNe zd_=$p0@-#Q3fTs}p<8R$VgGsxRlC0JU%z3nt&K9DT}&VlsYary(UG&zxgs8VxP$Za zv2|V((z!O@N9RhVM76K1}A>$x$3vKP(Z*@e#x=6=kNY|+N(PaK*Efc$bN>iB>5hmr zB}-=eZG$4Luo%ynYIkkxXlbSBku&7Ug{+mk)4iF4Jd&r3{@OE(!T9gFA&a}`lNf%) zR3oi?ek|ivP@yI#s=zF%A9Gj@%GF-wsj04*MeC@Kkbu6}F2g*Kr=^T4Fi-r7ymKY) zRPB}Khdj2W3MTSuX|i4zax9+R~2_)J~fzbK)#H zAeH^(#v2rj2nfe+Lx*b=8>_tg>js)l#t+Ic=k$!W!H~kmaTjZoOX$VO2c_NzjJyi0 z$6cGk1l1YSac4PTZxDoI5qyr(&VDtD556M?RMJ{t)Q;^beaO6mxQpIr8iqMm%#SUP z{F&(MQplQdvR3BJ5XaCH<8FoDx4xg7u)Lla7=kFg#GZ&N?YBS>oR(8~I(D{;&mBE; z&7Qa>-aT@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tWB$oNf-VLZS&Qu literal 0 HcmV?d00001 diff --git a/oTunes.icon/icon.json b/oTunes.icon/icon.json new file mode 100644 index 0000000..6bf41b6 --- /dev/null +++ b/oTunes.icon/icon.json @@ -0,0 +1,47 @@ +{ + "fill" : { + "automatic-gradient" : "display-p3:0.90526,0.26335,0.25253,1.00000" + }, + "groups" : [ + { + "layers" : [ + { + "fill-specializations" : [ + { + "value" : "automatic" + }, + { + "appearance" : "dark", + "value" : { + "automatic-gradient" : "display-p3:0.90526,0.26335,0.25253,1.00000" + } + } + ], + "image-name" : "music.note.png", + "name" : "music.note", + "position" : { + "scale" : 1, + "translation-in-points" : [ + 0, + 0 + ] + } + } + ], + "shadow" : { + "kind" : "neutral", + "opacity" : 0.5 + }, + "translucency" : { + "enabled" : true, + "value" : 0.5 + } + } + ], + "supported-platforms" : { + "circles" : [ + "watchOS" + ], + "squares" : "shared" + } +} \ No newline at end of file diff --git a/public/logo-monochrome.svg b/public/logo-monochrome.svg new file mode 100644 index 0000000..ad56d9f --- /dev/null +++ b/public/logo-monochrome.svg @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/public/logo.svg b/public/logo.svg deleted file mode 100644 index bcb9380..0000000 --- a/public/logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file