/** * LocalStorage Composable * Type-safe localStorage operations with Vue reactivity */ import { ref, watch } from 'vue'; /** * Use localStorage with reactivity * @param {string} key - Storage key * @param {any} defaultValue - Default value * @returns {Ref} Reactive ref synced with localStorage */ export function useLocalStorage(key, defaultValue) { // Try to load from localStorage const loadValue = () => { try { const item = localStorage.getItem(key); if (item !== null) { return JSON.parse(item); } } catch (error) { console.error(`Error loading ${key} from localStorage:`, error); } return defaultValue; }; const storedValue = ref(loadValue()); // Watch for changes and save to localStorage watch( storedValue, newValue => { try { localStorage.setItem(key, JSON.stringify(newValue)); } catch (error) { console.error(`Error saving ${key} to localStorage:`, error); } }, { deep: true } ); return storedValue; } /** * Manage search history in localStorage * @param {string} key - Storage key * @param {number} maxItems - Maximum number of items to store * @returns {Object} History management functions */ export function useSearchHistory(key = 'searchHistory', maxItems = 5) { const history = useLocalStorage(key, []); const addToHistory = query => { if (!query || query.trim() === '') return; // Remove duplicates and add to front const newHistory = [ query, ...history.value.filter(item => item !== query) ].slice(0, maxItems); history.value = newHistory; }; const removeFromHistory = query => { history.value = history.value.filter(item => item !== query); }; const clearHistory = () => { history.value = []; }; return { history, addToHistory, removeFromHistory, clearHistory }; }