File size: 1,097 Bytes
fa7b380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
import { useEffect, useState, useCallback } from "react";
import { BUILTIN_SITES, type SiteConfig } from "./sites";

const KEY = "grabber.sites.v1";

export function useSites() {
  const [custom, setCustom] = useState<SiteConfig[]>([]);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(KEY);
      if (raw) setCustom(JSON.parse(raw) as SiteConfig[]);
    } catch {
      // ignore
    }
    setHydrated(true);
  }, []);

  const persist = useCallback((list: SiteConfig[]) => {
    setCustom(list);
    try {
      localStorage.setItem(KEY, JSON.stringify(list));
    } catch {
      // ignore
    }
  }, []);

  const addSite = useCallback(
    (site: SiteConfig) => {
      persist([...custom.filter((s) => s.id !== site.id), site]);
    },
    [custom, persist],
  );

  const removeSite = useCallback(
    (id: string) => {
      persist(custom.filter((s) => s.id !== id));
    },
    [custom, persist],
  );

  const all = [...BUILTIN_SITES, ...custom];

  return { sites: all, custom, addSite, removeSite, hydrated };
}