All files / src/lib recent-searches.ts

100% Statements 18/18
87.5% Branches 7/8
100% Functions 5/5
100% Lines 17/17

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          6x 6x     33x 33x 33x 33x   31x       1x           13x 13x 12x   20x   12x 12x       12x       2x 2x          
/**
 * The reader's last site searches (ADR-082), kept in this browser's local
 * storage and nowhere else. Every access is guarded: storage can be blocked,
 * full or missing, and the search works without it.
 */
export const RECENT_SEARCHES_KEY = "site-search-recent";
const RECENT_SEARCHES_MAX = 5;
 
export function readRecentSearches(): string[] {
  try {
    const raw = window.localStorage.getItem(RECENT_SEARCHES_KEY);
    const list: unknown = raw ? JSON.parse(raw) : [];
    return Array.isArray(list)
      ? list
          .filter((s): s is string => typeof s === "string" && s.trim() !== "")
          .slice(0, RECENT_SEARCHES_MAX)
      : [];
  } catch {
    return [];
  }
}
 
/** Put a search first, without a second copy of it; newest first, five kept. */
export function rememberSearch(query: string): string[] {
  const q = query.trim();
  if (!q) return readRecentSearches();
  const next = [
    q,
    ...readRecentSearches().filter((s) => s.toLowerCase() !== q.toLowerCase()),
  ].slice(0, RECENT_SEARCHES_MAX);
  try {
    window.localStorage.setItem(RECENT_SEARCHES_KEY, JSON.stringify(next));
  } catch {
    // Not kept this time; the search itself is unaffected.
  }
  return next;
}
 
export function clearRecentSearches(): void {
  try {
    window.localStorage.removeItem(RECENT_SEARCHES_KEY);
  } catch {
    // Nothing to clear when storage is unavailable.
  }
}