/** * TDD Phase 2: GREEN - Minimal code to pass tests * * This Hook implements works search functionality: * - Uses @tanstack/react-query for data fetching * - Supports keyword search * - Supports category filter * - Supports pagination * - Only executes query when keyword is provided */ import { useQuery } from '@tanstack/react-query' import { root } from '@repo/core' import { TemplateGenerationController } from '@repo/sdk' import { useCallback } from 'react' // Type definitions export interface UseWorksSearchParams { keyword: string category?: '全部' | '萌宠' | '写真' | '合拍' page?: number limit?: number } export interface WorksSearchResult { id: string createdAt: Date template: { id: string name: string } status: string duration: number } export interface WorksSearchResponse { data: WorksSearchResult[] total: number page: number limit: number totalPages: number } /** * Hook for searching works with keyword and category filtering * * @param params - Search parameters including keyword, category, page, and limit * @returns Query result with data, loading state, error, and refetch function * * @example * ```tsx * const { data, works, isLoading, error } = useWorksSearch({ * keyword: '测试', * category: '萌宠', * page: 1, * limit: 20 * }) * ``` */ export function useWorksSearch(params: UseWorksSearchParams) { const { keyword, category, page = 1, limit = 20 } = params // Build query key - "全部" category should not be included const queryKey = [ 'worksSearch', keyword, category === '全部' ? undefined : category, page, limit, ] as const // Build API params - only include category if it's not "全部" const apiParams = { keyword, ...(category && category !== '全部' && { category }), page, limit, } // Query function const queryFn = useCallback(async (): Promise => { const controller = root.get(TemplateGenerationController) const result = await controller.list(apiParams) return result as WorksSearchResponse }, [keyword, category, page, limit]) // Execute query only when keyword has content const trimmedKeyword = keyword?.trim() || '' const isEnabled = !!trimmedKeyword const query = useQuery({ queryKey, queryFn, enabled: isEnabled, }) return { data: query.data, works: query.data?.data || [], isLoading: query.isLoading, error: query.error, refetch: query.refetch, } }