import { useEffect, useRef, useState } from 'react' import { useMutation, useQueryClient } from '@tanstack/react-query' import { Link } from 'react-router-dom' import type { CategoryDto, ChannelDto } from '../api/client' import { setChannelCategories } from '../api/client' interface Props { channel: ChannelDto categories: CategoryDto[] } function ChannelCard({ channel, categories }: Props) { const [open, setOpen] = useState(false) const popoverRef = useRef(null) const queryClient = useQueryClient() useEffect(() => { if (!open) return function handleClickOutside(e: MouseEvent) { if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) { setOpen(false) } } document.addEventListener('mousedown', handleClickOutside) return () => document.removeEventListener('mousedown', handleClickOutside) }, [open]) const mutation = useMutation({ mutationFn: (categoryIds: number[]) => setChannelCategories(channel.id, categoryIds), onMutate: async (categoryIds: number[]) => { await queryClient.cancelQueries({ queryKey: ['channels'] }) const previous = queryClient.getQueriesData({ queryKey: ['channels'] }) queryClient.setQueriesData({ queryKey: ['channels'] }, (old) => old?.map((c) => (c.id === channel.id ? { ...c, category_ids: categoryIds } : c)), ) return { previous } }, onError: (_err, _vars, context) => { context?.previous.forEach(([key, data]) => queryClient.setQueryData(key, data)) }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ['channels'] }) queryClient.invalidateQueries({ queryKey: ['categories'] }) }, }) function toggleCategory(categoryId: number) { const current = new Set(channel.category_ids) if (current.has(categoryId)) { current.delete(categoryId) } else { current.add(categoryId) } mutation.mutate(Array.from(current)) } const assignedNames = categories.filter((c) => channel.category_ids.includes(c.id)).map((c) => c.name) return (
  • {channel.thumbnail_url && {channel.title}}
    {channel.title} {!channel.subscribed && отписан}
    {assignedNames.map((name) => ( {name} ))}
    {open && (
    {categories.length === 0 &&
    Сначала создай категорию
    } {categories.map((category) => ( ))}
    )}
  • ) } export default ChannelCard