A fast, local-first "redirection engine" for !bang users with a few extra features ^-^
at main 1.5 kB view raw
1import { CONSTANTS } from "./main"; 2 3const createAudio = (src: string) => { 4 const audio = new Audio(); 5 audio.src = src; 6 return audio; 7}; 8 9const storage = { 10 get: (key: string) => localStorage.getItem(key), 11 set: (key: string, value: string) => localStorage.setItem(key, value), 12 remove: (key: string) => localStorage.removeItem(key), 13}; 14 15const memoizedGetSearchHistory = (() => { 16 let cache: Array<{ 17 query: string; 18 bang: string; 19 name: string; 20 timestamp: number; 21 }> | null = null; 22 return () => { 23 if (!cache) { 24 cache = JSON.parse( 25 storage.get(CONSTANTS.LOCAL_STORAGE_KEYS.SEARCH_HISTORY) || "[]", 26 ); 27 } 28 return cache; 29 }; 30})(); 31 32function addToSearchHistory( 33 query: string, 34 bang: { bang: string; name: string; url: string }, 35) { 36 const history = memoizedGetSearchHistory(); 37 if (!history) return; 38 39 history.unshift({ 40 query, 41 bang: bang.bang, 42 name: bang.name, 43 timestamp: Date.now(), 44 }); 45 history.splice(CONSTANTS.MAX_HISTORY); 46 storage.set( 47 CONSTANTS.LOCAL_STORAGE_KEYS.SEARCH_HISTORY, 48 JSON.stringify(history), 49 ); 50} 51 52function getSearchHistory(): Array<{ 53 query: string; 54 bang: string; 55 name: string; 56 timestamp: number; 57}> { 58 try { 59 return JSON.parse( 60 storage.get(CONSTANTS.LOCAL_STORAGE_KEYS.SEARCH_HISTORY) || "[]", 61 ); 62 } catch { 63 return []; 64 } 65} 66 67function clearSearchHistory() { 68 storage.set(CONSTANTS.LOCAL_STORAGE_KEYS.SEARCH_HISTORY, "[]"); 69} 70 71export { 72 createAudio, 73 storage, 74 memoizedGetSearchHistory, 75 addToSearchHistory, 76 getSearchHistory, 77 clearSearchHistory, 78};