import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type PlaylistNode } from '../api' import { SaveBar } from './SaveBar' export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string } interface Props { source: Source onSelect: (s: Source) => void onError: (msg: string) => void onOpenHistory: () => void } const icons: Record = { FOLDER: '▸', PLAYLIST: '♫', SMARTLIST: '✦', } function NodeRow({ node, depth, source, onSelect, onError, }: { node: PlaylistNode depth: number source: Source onSelect: (s: Source) => void onError: (msg: string) => void }) { const qc = useQueryClient() const [open, setOpen] = useState(true) const [renaming, setRenaming] = useState(false) const [draft, setDraft] = useState(node.name) const isFolder = node.type === 'FOLDER' const selected = source.kind === 'playlist' && source.id === node.id const selectable = node.type === 'PLAYLIST' const invalidate = () => { qc.invalidateQueries({ queryKey: ['playlists'] }) qc.invalidateQueries({ queryKey: ['state'] }) } const rename = useMutation({ mutationFn: (name: string) => api.renamePlaylist(node.id, name), onSuccess: (_d, name) => { invalidate() if (source.kind === 'playlist' && source.id === node.id) onSelect({ kind: 'playlist', id: node.id, name }) }, onError: (e: Error) => onError(e.message), }) const del = useMutation({ mutationFn: () => api.deletePlaylist(node.id), onSuccess: () => { invalidate() if (source.kind === 'playlist' && source.id === node.id) onSelect({ kind: 'all' }) }, onError: (e: Error) => onError(e.message), }) return (
{node.type === 'PLAYLIST' && !renaming && ( <> {node.count} )}
{isFolder && open && node.children.length > 0 && (
{node.children.map((c) => ( ))}
)}
) } export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { const qc = useQueryClient() const [creating, setCreating] = useState(false) const [newName, setNewName] = useState('') const { data: playlists, isLoading } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists, }) const create = useMutation({ mutationFn: (name: string) => api.createPlaylist(name), onSuccess: (pl) => { qc.invalidateQueries({ queryKey: ['playlists'] }) qc.invalidateQueries({ queryKey: ['state'] }) onSelect({ kind: 'playlist', id: pl.id, name: pl.name }) }, onError: (e: Error) => onError(e.message), }) const submitNew = () => { setCreating(false) if (newName.trim()) create.mutate(newName.trim()) setNewName('') } return ( ) }