feat(search): add search history functionality with dropdown and persistence
- Implement SearchHistoryDropdown component for displaying recent searches - Add useSearchHistory hook for managing search history in localStorage - Integrate search history into SearchOverlay for user convenience - Update GridToolbar to support filter presets - Enhance SearchOverlay with close button and history display
This commit is contained in:
42
src/Griddy/features/searchHistory/useSearchHistory.ts
Normal file
42
src/Griddy/features/searchHistory/useSearchHistory.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
|
||||
const MAX_HISTORY = 10
|
||||
|
||||
function getStorageKey(persistenceKey: string) {
|
||||
return `griddy-search-history-${persistenceKey}`
|
||||
}
|
||||
|
||||
function loadHistory(persistenceKey: string): string[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(getStorageKey(persistenceKey))
|
||||
return raw ? JSON.parse(raw) : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function saveHistory(persistenceKey: string, history: string[]) {
|
||||
localStorage.setItem(getStorageKey(persistenceKey), JSON.stringify(history))
|
||||
}
|
||||
|
||||
export function useSearchHistory(persistenceKey?: string) {
|
||||
const key = persistenceKey ?? 'default'
|
||||
const [history, setHistory] = useState<string[]>(() => loadHistory(key))
|
||||
|
||||
const addEntry = useCallback((query: string) => {
|
||||
if (!query.trim()) return
|
||||
setHistory((prev) => {
|
||||
const filtered = prev.filter((h) => h !== query)
|
||||
const next = [query, ...filtered].slice(0, MAX_HISTORY)
|
||||
saveHistory(key, next)
|
||||
return next
|
||||
})
|
||||
}, [key])
|
||||
|
||||
const clearHistory = useCallback(() => {
|
||||
setHistory([])
|
||||
localStorage.removeItem(getStorageKey(key))
|
||||
}, [key])
|
||||
|
||||
return { addEntry, clearHistory, history }
|
||||
}
|
||||
Reference in New Issue
Block a user