Files
otunes/apps/web/components/add-to-playlist-provider.tsx
T

337 lines
10 KiB
TypeScript

"use client"
import * as React from "react"
import { useConvex, useMutation, useQuery } from "convex/react"
import { useRouter } from "next/navigation"
import { ListMusic, Plus } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
function countSongsToAdd(
playlistSongIds: Id<"songs">[],
pendingSongIds: Id<"songs">[]
) {
const existing = new Set(playlistSongIds)
return pendingSongIds.filter((songId) => !existing.has(songId)).length
}
function formatAddToPlaylistToast(
title: string,
addedCount: number,
skippedCount: number
) {
if (addedCount === 0) {
return skippedCount === 1
? `Song is already in ${title}`
: `All selected songs are already in ${title}`
}
const addedLabel =
addedCount > 1 ? `Added ${addedCount} songs to ${title}` : `Added to ${title}`
if (skippedCount === 0) {
return addedLabel
}
const skippedLabel =
skippedCount > 1
? `${skippedCount} were already in the playlist`
: "1 was already in the playlist"
return `${addedLabel} (${skippedLabel})`
}
type AddToPlaylistContextValue = {
openAddToPlaylist: (songIds: Id<"songs">[]) => void
openAddAlbumToPlaylist: (albumId: Id<"albums">) => Promise<void>
openAddPlaylistToPlaylist: (playlistId: Id<"playlists">) => Promise<void>
openAddArtistToPlaylist: (artistId: Id<"artists">) => Promise<void>
openCreatePlaylist: () => void
}
const AddToPlaylistContext = React.createContext<AddToPlaylistContextValue | null>(
null
)
export function useAddToPlaylist() {
const context = React.useContext(AddToPlaylistContext)
if (!context) {
throw new Error("useAddToPlaylist must be used within AddToPlaylistProvider")
}
return context
}
export function AddToPlaylistProvider({
children,
}: {
children: React.ReactNode
}) {
const convex = useConvex()
const router = useRouter()
const ownedPlaylists = useQuery(api.playlists.listOwnedPlaylists)
const addSongs = useMutation(api.playlists.addSongsToPlaylist)
const createPlaylist = useMutation(api.playlists.createPlaylist)
const [open, setOpen] = React.useState(false)
const [createOpen, setCreateOpen] = React.useState(false)
const [newPlaylistName, setNewPlaylistName] = React.useState("")
const [pendingSongIds, setPendingSongIds] = React.useState<Id<"songs">[]>([])
const [isSubmitting, setIsSubmitting] = React.useState(false)
const openAddToPlaylist = React.useCallback((songIds: Id<"songs">[]) => {
const unique = [...new Set(songIds)]
if (unique.length === 0) {
toast.error("No songs selected")
return
}
setPendingSongIds(unique)
setOpen(true)
}, [])
const openAddAlbumToPlaylist = React.useCallback(
async (albumId: Id<"albums">) => {
const songIds = await convex.query(api.playlists.getAlbumSongIds, {
albumId,
})
openAddToPlaylist(songIds)
},
[convex, openAddToPlaylist]
)
const openAddPlaylistToPlaylist = React.useCallback(
async (playlistId: Id<"playlists">) => {
const songIds = await convex.query(api.playlists.getPlaylistSongIds, {
playlistId,
})
openAddToPlaylist(songIds)
},
[convex, openAddToPlaylist]
)
const openAddArtistToPlaylist = React.useCallback(
async (artistId: Id<"artists">) => {
const songIds = await convex.query(api.playlists.getArtistSongIds, {
artistId,
})
openAddToPlaylist(songIds)
},
[convex, openAddToPlaylist]
)
const openCreatePlaylist = React.useCallback(() => {
setPendingSongIds([])
setNewPlaylistName("")
setCreateOpen(true)
}, [])
async function handleAddToPlaylist(playlistId: Id<"playlists">, title: string) {
setIsSubmitting(true)
try {
const { addedCount, skippedCount } = await addSongs({
playlistId,
songIds: pendingSongIds,
})
const message = formatAddToPlaylistToast(title, addedCount, skippedCount)
if (addedCount === 0) {
toast.message(message)
} else {
toast.success(message)
}
setOpen(false)
setPendingSongIds([])
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to add to playlist"
)
} finally {
setIsSubmitting(false)
}
}
async function handleCreatePlaylist(event: React.FormEvent) {
event.preventDefault()
const trimmed = newPlaylistName.trim()
if (!trimmed) {
return
}
const songIds = pendingSongIds
setIsSubmitting(true)
try {
const playlistId = await createPlaylist({
name: trimmed,
songIds,
})
const count = songIds.length
toast.success(
count > 1
? `Created ${trimmed} with ${count} songs`
: `Created ${trimmed}`
)
setCreateOpen(false)
setOpen(false)
setNewPlaylistName("")
setPendingSongIds([])
if (count === 0) {
router.push(`/playlist/${playlistId}`)
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : "Failed to create playlist"
)
} finally {
setIsSubmitting(false)
}
}
return (
<AddToPlaylistContext.Provider
value={{
openAddToPlaylist,
openAddAlbumToPlaylist,
openAddPlaylistToPlaylist,
openAddArtistToPlaylist,
openCreatePlaylist,
}}
>
{children}
<Dialog
open={open}
onOpenChange={(next) => {
setOpen(next)
if (!next) {
setPendingSongIds([])
}
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Add to Playlist</DialogTitle>
<DialogDescription>
{pendingSongIds.length > 1
? `Choose a playlist for ${pendingSongIds.length} songs.`
: "Choose a playlist for this song."}
</DialogDescription>
</DialogHeader>
<ScrollArea className="max-h-64">
<div className="flex flex-col gap-1 pr-3">
{ownedPlaylists === undefined ? (
<p className="py-4 text-sm text-muted-foreground">Loading…</p>
) : ownedPlaylists.length === 0 ? (
<p className="py-4 text-sm text-muted-foreground">
You do not have any playlists yet.
</p>
) : ownedPlaylists.every(
(playlist) =>
countSongsToAdd(playlist.songIds, pendingSongIds) === 0
) ? (
<p className="py-4 text-sm text-muted-foreground">
{pendingSongIds.length > 1
? "All selected songs are already in your playlists."
: "This song is already in all of your playlists."}
</p>
) : (
ownedPlaylists.map((playlist) => {
const songsToAdd = countSongsToAdd(
playlist.songIds,
pendingSongIds
)
const allDuplicates = songsToAdd === 0
return (
<Button
key={playlist.id}
variant="ghost"
className="h-auto justify-start gap-2 py-2"
disabled={isSubmitting || allDuplicates}
onClick={() =>
handleAddToPlaylist(playlist.id, playlist.title)
}
>
<ListMusic className="size-4 shrink-0" />
<span className="flex min-w-0 flex-col items-start gap-0.5">
<span className="truncate">{playlist.title}</span>
{allDuplicates ? (
<span className="text-xs text-muted-foreground">
Already added
</span>
) : null}
</span>
</Button>
)
})
)}
</div>
</ScrollArea>
<DialogFooter className="flex-col gap-2 sm:flex-col">
<Button
variant="secondary"
className="w-full gap-2"
disabled={isSubmitting}
onClick={() => {
setCreateOpen(true)
setNewPlaylistName("")
}}
>
<Plus className="size-4" />
Create New Playlist
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent className="sm:max-w-md">
<form onSubmit={handleCreatePlaylist}>
<DialogHeader>
<DialogTitle>New Playlist</DialogTitle>
<DialogDescription>
Enter a name for your new playlist.
</DialogDescription>
</DialogHeader>
<Input
className="mt-4"
placeholder="Playlist name"
value={newPlaylistName}
onChange={(event) => setNewPlaylistName(event.target.value)}
autoFocus
/>
<DialogFooter className="mt-4">
<Button
type="button"
variant="outline"
onClick={() => setCreateOpen(false)}
disabled={isSubmitting}
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || !newPlaylistName.trim()}
>
Create
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</AddToPlaylistContext.Provider>
)
}