All files / src/lib/stores history.svelte.ts

100% Statements 13/13
50% Branches 1/2
100% Functions 6/6
100% Lines 13/13

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    7x     7x 7x 7x             35x       7x     23x     13x         13x 13x       22x 22x         7x  
import type { HistoryEntry } from '../types'
 
const STORAGE_KEY = 'pomandoro-history'
 
function loadFromStorage(): HistoryEntry[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? (JSON.parse(raw) as HistoryEntry[]) : []
  } catch {
    return []
  }
}
 
function save(entries: HistoryEntry[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(entries))
}
 
function createHistoryStore() {
  let entries = $state<HistoryEntry[]>(loadFromStorage())
 
  return {
    get entries() { return entries },
 
    addEntry(entry: Omit<HistoryEntry, 'id' | 'completedAt'>) {
      const newEntry: HistoryEntry = {
        ...entry,
        id: crypto.randomUUID(),
        completedAt: Date.now()
      }
      entries = [newEntry, ...entries]
      save(entries)
    },
 
    clearHistory() {
      entries = []
      save(entries)
    }
  }
}
 
export const history = createHistoryStore()