import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type PlaylistNode } from '../api' interface Props { count: number trackIds: string[] onClear: () => void onDone: (msg: string) => void onError: (msg: string) => void } function flattenPlaylists(nodes: PlaylistNode[]): PlaylistNode[] { return nodes.flatMap((n) => [ ...(n.type === 'PLAYLIST' ? [n] : []), ...flattenPlaylists(n.children), ]) } // Floating action bar shown when tracks are selected in the explorer. export function SelectionBar({ count, trackIds, onClear, onDone, onError }: Props) { const qc = useQueryClient() const [menuOpen, setMenuOpen] = useState(false) const { data: playlists } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists }) const flat = playlists ? flattenPlaylists(playlists) : [] const add = useMutation({ mutationFn: ({ uuid, ids }: { uuid: string; ids: string[] }) => api.addEntries(uuid, ids), onSuccess: (res, vars) => { qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['playlists'] }) qc.invalidateQueries({ queryKey: ['playlist', vars.uuid] }) const pl = flat.find((p) => p.id === vars.uuid) onDone(`Added ${res.added} track${res.added === 1 ? '' : 's'} to ${pl?.name ?? 'playlist'}`) setMenuOpen(false) onClear() }, onError: (e: Error) => onError(e.message), }) if (count === 0) return null return (
{count} selected
{menuOpen && (
{flat.length === 0 && (
No playlists yet
)} {flat.map((p) => ( ))}
)}
) }