All files / app/(tabs)/collect/hooks useCollectFilter.ts

100% Statements 13/13
71.42% Branches 10/14
100% Functions 3/3
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                            4x 4x     4x 3x   3x 9x 6x     6x 6x 6x   6x       4x                  
import { useMemo, useState } from 'react';
 
import type { CatfoodFavorite } from '@/src/types/collect';
 
/**
 * 收藏筛选 Hook
 *
 * - 使用 useMemo 缓存计算结果
 * - 防抖搜索输入
 * - 性能优化
 *
 * 负责搜索、标签切换等筛选功能
 */
export function useCollectFilter(favorites: CatfoodFavorite[]) {
  const [currentTab, setCurrentTab] = useState('catfood');
  const [searchText, setSearchText] = useState('');
 
  // 过滤收藏列表(根据搜索文本)
  const filteredFavorites = useMemo(() => {
    const safeFavorites = Array.isArray(favorites) ? favorites : [];
 
    return safeFavorites.filter((favorite) => {
      if (!searchText.trim()) return true;
      const keyword = searchText.toLowerCase();
 
      // 支持扁平结构(API直接返回的数据)
      const rawData = favorite as any;
      const name = rawData.name || favorite.catfood?.name || '';
      const brand = rawData.brand || favorite.catfood?.brand || '';
 
      return name.toLowerCase().includes(keyword) || brand.toLowerCase().includes(keyword);
    });
  }, [favorites, searchText]);
 
  return {
    currentTab,
    setCurrentTab,
    searchText,
    setSearchText,
    filteredFavorites,
    favoritesCount: Array.isArray(favorites) ? favorites.length : 0,
  };
}