| 1 |
import * as React from "react"; |
| 2 |
import { createContext, useContext, useEffect } from "react"; |
| 3 |
import { useLiveQuery } from "dexie-react-hooks"; |
| 4 |
import prefs, { PREF_DEFAULTS } from "../app/Prefs"; |
| 5 |
|
| 6 |
// A CACHE of the user's prefs -- not the source of truth (that's the `prefs` IndexedDB table, via |
| 7 |
// Prefs.js). Preloaded once in Layout so Settings renders instantly, and written through to |
| 8 |
// localStorage on every change so (a) Settings is instant even on a cold load and (b) the inline |
| 9 |
// splash script in index.html can read the theme synchronously before the bundle loads. The |
| 10 |
// "prefcache" key is duplicated in that script -- keep them in sync. |
| 11 |
const PREFCACHE_LOCALSTORAGE_KEY = "prefcache"; |
| 12 |
|
| 13 |
const PrefCacheContext = createContext(undefined); |
| 14 |
|
| 15 |
// Synchronous fallback before the live query resolves. Merged over PREF_DEFAULTS so a newly-added |
| 16 |
// pref still has a value. |
| 17 |
const readPersistedCache = () => { |
| 18 |
try { |
| 19 |
const raw = localStorage.getItem(PREFCACHE_LOCALSTORAGE_KEY); |
| 20 |
if (raw) { |
| 21 |
return { ...PREF_DEFAULTS, ...JSON.parse(raw) }; |
| 22 |
} |
| 23 |
} catch (e) { |
| 24 |
// malformed or unavailable storage -- fall back to defaults |
| 25 |
} |
| 26 |
return PREF_DEFAULTS; |
| 27 |
}; |
| 28 |
|
| 29 |
export const PrefCacheProvider = ({ children }) => { |
| 30 |
const cache = useLiveQuery(async () => ({ |
| 31 |
sound: await prefs.sound(), |
| 32 |
minPriority: await prefs.minPriority(), |
| 33 |
deleteAfter: await prefs.deleteAfter(), |
| 34 |
theme: await prefs.theme(), |
| 35 |
dateFormat: await prefs.dateFormat(), |
| 36 |
timeFormat: await prefs.timeFormat(), |
| 37 |
webPushEnabled: await prefs.webPushEnabled(), |
| 38 |
})); |
| 39 |
|
| 40 |
// Write through to localStorage on change (prefs change rarely). |
| 41 |
useEffect(() => { |
| 42 |
if (cache !== undefined) { |
| 43 |
try { |
| 44 |
localStorage.setItem(PREFCACHE_LOCALSTORAGE_KEY, JSON.stringify(cache)); |
| 45 |
} catch (e) { |
| 46 |
// localStorage may be unavailable (private mode) -- the cache just isn't persisted |
| 47 |
} |
| 48 |
} |
| 49 |
}, [cache]); |
| 50 |
|
| 51 |
return <PrefCacheContext.Provider value={cache}>{children}</PrefCacheContext.Provider>; |
| 52 |
}; |
| 53 |
|
| 54 |
// Live context once resolved; else the synchronous localStorage snapshot (instant on cold load); |
| 55 |
// else defaults. |
| 56 |
export const usePrefCache = () => useContext(PrefCacheContext) ?? readPersistedCache(); |