import { unwrap } from '@pipu/core'; import { useInfiniteQuery } from '@tanstack/react-query'; import { Link } from '@tanstack/react-router'; import { useTranslation } from 'react-i18next'; import { useSession } from '../app/session'; import { AlbumGrid, ArtistChip, TrackList } from '../entities/catalog'; import { useErrorText } from '../shared/lib/errors'; import { Button, FormError } from '../shared/ui/ui'; import s from './page.module.css'; import c from './catalog.module.css'; export type SearchType = 'all' | 'artists' | 'albums' | 'tracks'; const TYPES: SearchType[] = ['all', 'artists', 'albums', 'tracks']; export function SearchPage({ q, type }: { q: string; type: SearchType }) { const { t } = useTranslation(); const session = useSession(); const errorText = useErrorText(); const query = q.trim(); const results = useInfiniteQuery({ queryKey: ['search', query, type], enabled: query !== '', initialPageParam: undefined as string | undefined, queryFn: async ({ pageParam, signal }) => unwrap( await session.client.GET('/api/v1/search', { params: { query: { q: query, type, cursor: pageParam, limit: type === 'all' ? undefined : 40 } }, signal, }), ), getNextPageParam: (p) => p.next_cursor ?? undefined, }); const pages = results.data?.pages ?? []; const first = pages[0]; const artists = pages.flatMap((p) => p.artists); const albums = pages.flatMap((p) => p.albums); const tracks = pages.flatMap((p) => p.tracks); const empty = results.isSuccess && artists.length + albums.length + tracks.length === 0; const count = (k: Exclude) => first?.totals[k]; return (

{t('search.title', { query })}

{first?.corrected_query && (

{t('search.corrected', { query: first.corrected_query })}

)}
{TYPES.map((k) => ( {t(`search.${k}`)} {k !== 'all' && count(k) !== undefined && type === 'all' && {count(k)}} ))}
{results.error ? errorText(results.error) : null} {empty &&
{t('search.nothing')}
} {artists.length > 0 && (
{type === 'all' &&

{t('search.artists')}

}
{artists.map((a) => ( ))}
)} {albums.length > 0 && (
{type === 'all' &&

{t('search.albums')}

}
)} {tracks.length > 0 && (
{type === 'all' &&

{t('search.tracks')}

}
)} {results.hasNextPage && ( )}
); }