All files / apps/huella-legal/layers/interest/app/composables useInterestHistory.ts

100% Statements 17/17
100% Branches 4/4
100% Functions 9/9
100% Lines 16/16

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          2x     2x   13x   13x 22x 14x       13x 6x     13x 1x 2x       13x 2x     13x 1x     13x    
import { useLocalStorage } from "@vueuse/core";
import * as v from "valibot";
import { interestEntrySchema } from "../schemas/interestEntry";
import type { InterestEntry } from "../types/InterestEntry";
 
const STORAGE_KEY = "huella-legal:interest-history";
 
/** The history table's rows, kept in this browser's local storage. */
export const useInterestHistory = () => {
    // Read after mount, since the page is prerendered with an empty table and must hydrate as one
    const stored = useLocalStorage<unknown>(STORAGE_KEY, [], { initOnMounted: true });
 
    const entries = computed<InterestEntry[]>(() =>
        Array.isArray(stored.value)
            ? stored.value.filter((entry) => v.is(interestEntrySchema, entry))
            : [],
    );
 
    const add = (entry: Omit<InterestEntry, "id">): void => {
        stored.value = [...entries.value, { ...entry, id: crypto.randomUUID() }];
    };
 
    const rename = (id: string, concept: string): void => {
        stored.value = entries.value.map((entry) =>
            entry.id === id ? { ...entry, concept: concept.trim() } : entry,
        );
    };
 
    const remove = (id: string): void => {
        stored.value = entries.value.filter((entry) => entry.id !== id);
    };
 
    const clear = (): void => {
        stored.value = [];
    };
 
    return { entries, add, rename, remove, clear };
};