All files / hooks useSearchHistory.ts

94.73% Statements 36/38
88.88% Branches 8/9
90.9% Functions 10/11
97.22% Lines 35/36

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98                        1x 1x         1x 49x     49x 9x 9x 9x 3x 3x     1x 1x         49x 37x   37x 37x 37x             49x   35x 35x 302x     35x   1x 1x     1x 1x     34x         34x         49x 1x       49x 1x       49x 2x     49x                
import { useState, useEffect, useCallback } from 'react';
 
export type SearchItemType = 'procedure' | 'drug' | 'tool' | 'manual' | 'general';
 
export interface SearchHistoryItem {
  id: string;
  type: SearchItemType;
  title: string;
  path: string;
  searchedAt: number;
}
 
const STORAGE_KEY = 'emerges-tes-search-history';
const MAX_HISTORY_ITEMS = 20;
 
/**
 * Hook para gestionar historial de búsquedas
 */
export const useSearchHistory = () => {
  const [history, setHistory] = useState<SearchHistoryItem[]>([]);
 
  // Cargar historial al montar
  useEffect(() => {
    try {
      const stored = sessionStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored) as SearchHistoryItem[];
        setHistory(parsed);
      }
    } catch (error) {
      console.error('Error loading search history:', error);
      setHistory([]);
    }
  }, []);
 
  // Guardar historial en sessionStorage
  const saveHistory = useCallback((newHistory: SearchHistoryItem[]) => {
    try {
      // Limitar a MAX_HISTORY_ITEMS
      const limited = newHistory.slice(0, MAX_HISTORY_ITEMS);
      sessionStorage.setItem(STORAGE_KEY, JSON.stringify(limited));
      setHistory(limited);
    } catch (error) {
      console.error('Error saving search history:', error);
    }
  }, []);
 
  // Añadir al historial
  const addToHistory = useCallback((item: Omit<SearchHistoryItem, 'searchedAt'>) => {
    // Evitar duplicados recientes (mismo id en últimos 5 minutos)
    const now = Date.now();
    const recent = history.filter(
      (h) => h.id === item.id && now - h.searchedAt < 5 * 60 * 1000
    );
 
    if (recent.length > 0) {
      // Actualizar timestamp del existente
      const updated = history.map((h) =>
        h.id === item.id ? { ...h, searchedAt: now } : h
      );
      // Ordenar por fecha (más reciente primero)
      updated.sort((a, b) => b.searchedAt - a.searchedAt);
      saveHistory(updated);
    } else {
      // Añadir nuevo
      const newItem: SearchHistoryItem = {
        ...item,
        searchedAt: now,
      };
      // Añadir al inicio y limitar
      saveHistory([newItem, ...history]);
    }
  }, [history, saveHistory]);
 
  // Obtener historial reciente (últimos N)
  const getRecentHistory = useCallback((limit: number = 10) => {
    return history.slice(0, limit);
  }, [history]);
 
  // Limpiar historial
  const clearHistory = useCallback(() => {
    saveHistory([]);
  }, [saveHistory]);
 
  // Eliminar un item del historial
  const removeFromHistory = useCallback((id: string) => {
    saveHistory(history.filter((h) => h.id !== id));
  }, [history, saveHistory]);
 
  return {
    history,
    addToHistory,
    getRecentHistory,
    clearHistory,
    removeFromHistory,
  };
};