| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import type {Atom, Getter, WritableAtom} from 'jotai'; |
| b69ab31 | | | 9 | import type {Json} from 'shared/typeUtils'; |
| b69ab31 | | | 10 | import type {Platform} from './platform'; |
| b69ab31 | | | 11 | import type {ConfigName, LocalStorageName, SettableConfigName} from './types'; |
| b69ab31 | | | 12 | |
| b69ab31 | | | 13 | import {atom, getDefaultStore, useAtomValue} from 'jotai'; |
| b69ab31 | | | 14 | import {loadable} from 'jotai/utils'; |
| b69ab31 | | | 15 | import {useMemo} from 'react'; |
| b69ab31 | | | 16 | import {RateLimiter} from 'shared/RateLimiter'; |
| b69ab31 | | | 17 | import {isPromise} from 'shared/utils'; |
| b69ab31 | | | 18 | import serverAPI from './ClientToServerAPI'; |
| b69ab31 | | | 19 | import platform from './platform'; |
| b69ab31 | | | 20 | import {assert} from './utils'; |
| b69ab31 | | | 21 | |
| b69ab31 | | | 22 | /** A mutable atom that stores type `T`. */ |
| b69ab31 | | | 23 | export type MutAtom<T> = WritableAtom<T, [T | ((prev: T) => T)], void>; |
| b69ab31 | | | 24 | |
| b69ab31 | | | 25 | /** |
| b69ab31 | | | 26 | * The store being used. Do not use this directly. Alternatives are: |
| b69ab31 | | | 27 | * - use `readAtom` instead of `store.get`. |
| b69ab31 | | | 28 | * - use `writeAtom` instead of `store.set`. |
| b69ab31 | | | 29 | * - use `atomWithOnChange` instead of `store.sub`. |
| b69ab31 | | | 30 | */ |
| b69ab31 | | | 31 | let store = getDefaultStore(); |
| b69ab31 | | | 32 | |
| b69ab31 | | | 33 | /** |
| b69ab31 | | | 34 | * Replace the current Jotai store used by this module. |
| b69ab31 | | | 35 | * Practically, this is only useful for tests to reset states. |
| b69ab31 | | | 36 | */ |
| b69ab31 | | | 37 | export function setJotaiStore(newStore: typeof store) { |
| b69ab31 | | | 38 | store = newStore; |
| b69ab31 | | | 39 | } |
| b69ab31 | | | 40 | |
| b69ab31 | | | 41 | /** Define a read-write atom backed by a config. */ |
| b69ab31 | | | 42 | export function configBackedAtom<T extends Json>( |
| b69ab31 | | | 43 | name: SettableConfigName, |
| b69ab31 | | | 44 | defaultValue: T, |
| b69ab31 | | | 45 | readonly?: false, |
| b69ab31 | | | 46 | ): MutAtom<T>; |
| b69ab31 | | | 47 | |
| b69ab31 | | | 48 | /** |
| b69ab31 | | | 49 | * Define a read-only atom backed by a config. |
| b69ab31 | | | 50 | * |
| b69ab31 | | | 51 | * This can be useful for staged rollout features |
| b69ab31 | | | 52 | * where the config is not supposed to be set by the user. |
| b69ab31 | | | 53 | * (user config will override the staged rollout config) |
| b69ab31 | | | 54 | */ |
| b69ab31 | | | 55 | export function configBackedAtom<T extends Json>( |
| b69ab31 | | | 56 | name: ConfigName, |
| b69ab31 | | | 57 | defaultValue: T, |
| b69ab31 | | | 58 | readonly: true, |
| b69ab31 | | | 59 | useRawValue?: boolean, |
| b69ab31 | | | 60 | ): Atom<T>; |
| b69ab31 | | | 61 | |
| b69ab31 | | | 62 | export function configBackedAtom<T extends Json>( |
| b69ab31 | | | 63 | name: ConfigName | SettableConfigName, |
| b69ab31 | | | 64 | defaultValue: T, |
| b69ab31 | | | 65 | readonly = false, |
| b69ab31 | | | 66 | useRawValue?: boolean, |
| b69ab31 | | | 67 | ): MutAtom<T> | Atom<T> { |
| b69ab31 | | | 68 | // https://jotai.org/docs/guides/persistence |
| b69ab31 | | | 69 | const primitiveAtom = atom<T>(defaultValue); |
| b69ab31 | | | 70 | |
| b69ab31 | | | 71 | let lastStrValue: undefined | string = undefined; |
| b69ab31 | | | 72 | serverAPI.onMessageOfType('gotConfig', event => { |
| b69ab31 | | | 73 | if (event.name !== name) { |
| b69ab31 | | | 74 | return; |
| b69ab31 | | | 75 | } |
| b69ab31 | | | 76 | lastStrValue = event.value; |
| b69ab31 | | | 77 | writeAtom( |
| b69ab31 | | | 78 | primitiveAtom, |
| b69ab31 | | | 79 | event.value === undefined |
| b69ab31 | | | 80 | ? defaultValue |
| b69ab31 | | | 81 | : useRawValue === true |
| b69ab31 | | | 82 | ? event.value |
| b69ab31 | | | 83 | : JSON.parse(event.value), |
| b69ab31 | | | 84 | ); |
| b69ab31 | | | 85 | }); |
| b69ab31 | | | 86 | serverAPI.onConnectOrReconnect(() => { |
| b69ab31 | | | 87 | serverAPI.postMessage({ |
| b69ab31 | | | 88 | type: 'getConfig', |
| b69ab31 | | | 89 | name: name as ConfigName, |
| b69ab31 | | | 90 | }); |
| b69ab31 | | | 91 | }); |
| b69ab31 | | | 92 | |
| b69ab31 | | | 93 | return readonly |
| b69ab31 | | | 94 | ? atom<T>(get => get(primitiveAtom)) |
| b69ab31 | | | 95 | : atom<T, [T | ((prev: T) => T)], void>( |
| b69ab31 | | | 96 | get => get(primitiveAtom), |
| b69ab31 | | | 97 | (get, set, update) => { |
| b69ab31 | | | 98 | const newValue = typeof update === 'function' ? update(get(primitiveAtom)) : update; |
| b69ab31 | | | 99 | set(primitiveAtom, newValue); |
| b69ab31 | | | 100 | const strValue = useRawValue ? String(newValue) : JSON.stringify(newValue); |
| b69ab31 | | | 101 | if (strValue !== lastStrValue) { |
| b69ab31 | | | 102 | lastStrValue = strValue; |
| b69ab31 | | | 103 | serverAPI.postMessage({ |
| b69ab31 | | | 104 | type: 'setConfig', |
| b69ab31 | | | 105 | name: name as SettableConfigName, |
| b69ab31 | | | 106 | value: strValue, |
| b69ab31 | | | 107 | }); |
| b69ab31 | | | 108 | } |
| b69ab31 | | | 109 | }, |
| b69ab31 | | | 110 | ); |
| b69ab31 | | | 111 | } |
| b69ab31 | | | 112 | |
| b69ab31 | | | 113 | /** |
| b69ab31 | | | 114 | * Loads this atom from a local persistent cache (usually browser local storage), |
| b69ab31 | | | 115 | * and persists any changes back to it. |
| b69ab31 | | | 116 | * Useful for some customizations that don't warrant a user-visible sl config, |
| b69ab31 | | | 117 | * for example UI expansion state. |
| b69ab31 | | | 118 | */ |
| b69ab31 | | | 119 | export function localStorageBackedAtom<T extends Json>( |
| b69ab31 | | | 120 | name: LocalStorageName, |
| b69ab31 | | | 121 | defaultValue: T, |
| b69ab31 | | | 122 | ): MutAtom<T> { |
| b69ab31 | | | 123 | const primitiveAtom = atom<T>(platform.getPersistedState<T>(name) ?? defaultValue); |
| b69ab31 | | | 124 | |
| b69ab31 | | | 125 | return atom( |
| b69ab31 | | | 126 | get => get(primitiveAtom), |
| b69ab31 | | | 127 | (get, set, update) => { |
| b69ab31 | | | 128 | const newValue = typeof update === 'function' ? update(get(primitiveAtom)) : update; |
| b69ab31 | | | 129 | set(primitiveAtom, newValue); |
| b69ab31 | | | 130 | platform.setPersistedState(name, newValue); |
| b69ab31 | | | 131 | }, |
| b69ab31 | | | 132 | ); |
| b69ab31 | | | 133 | } |
| b69ab31 | | | 134 | |
| b69ab31 | | | 135 | /** |
| b69ab31 | | | 136 | * Wraps an atom with an "onChange" callback. |
| b69ab31 | | | 137 | * Changing the returned atom will trigger the callback. |
| b69ab31 | | | 138 | * Calling this function will trigger `onChange` with the current value except when `skipInitialCall` is `true`. |
| b69ab31 | | | 139 | */ |
| b69ab31 | | | 140 | export function atomWithOnChange<T>( |
| b69ab31 | | | 141 | originalAtom: MutAtom<T>, |
| b69ab31 | | | 142 | onChange: (value: T) => void, |
| b69ab31 | | | 143 | skipInitialCall?: boolean, |
| b69ab31 | | | 144 | ): MutAtom<T> { |
| b69ab31 | | | 145 | if (skipInitialCall !== true) { |
| b69ab31 | | | 146 | onChange(readAtom(originalAtom)); |
| b69ab31 | | | 147 | } |
| b69ab31 | | | 148 | return atom( |
| b69ab31 | | | 149 | get => get(originalAtom), |
| b69ab31 | | | 150 | (get, set, args) => { |
| b69ab31 | | | 151 | const oldValue = get(originalAtom); |
| b69ab31 | | | 152 | set(originalAtom, args); |
| b69ab31 | | | 153 | const newValue = get(originalAtom); |
| b69ab31 | | | 154 | if (oldValue !== newValue) { |
| b69ab31 | | | 155 | onChange(newValue); |
| b69ab31 | | | 156 | } |
| b69ab31 | | | 157 | }, |
| b69ab31 | | | 158 | ); |
| b69ab31 | | | 159 | } |
| b69ab31 | | | 160 | |
| b69ab31 | | | 161 | /** |
| b69ab31 | | | 162 | * Creates a lazily initialized atom. |
| b69ab31 | | | 163 | * On first read, trigger `load` to get the actual value. |
| b69ab31 | | | 164 | * `fallback` provides the value when the async `load` is running. |
| b69ab31 | | | 165 | * `original` is an optional nullable atom to provide the value. |
| b69ab31 | | | 166 | */ |
| b69ab31 | | | 167 | export function lazyAtom<T>( |
| b69ab31 | | | 168 | load: (get: Getter) => Promise<T> | T, |
| b69ab31 | | | 169 | fallback: T, |
| b69ab31 | | | 170 | original?: MutAtom<T | undefined>, |
| b69ab31 | | | 171 | ): MutAtom<T> { |
| b69ab31 | | | 172 | const originalAtom = original ?? atom<T | undefined>(undefined); |
| b69ab31 | | | 173 | const limiter = new RateLimiter(1); |
| b69ab31 | | | 174 | return atom( |
| b69ab31 | | | 175 | get => { |
| b69ab31 | | | 176 | const value = get(originalAtom); |
| b69ab31 | | | 177 | if (value !== undefined) { |
| b69ab31 | | | 178 | return value; |
| b69ab31 | | | 179 | } |
| b69ab31 | | | 180 | const loaded = load(get); |
| b69ab31 | | | 181 | if (!isPromise(loaded)) { |
| b69ab31 | | | 182 | writeAtom(originalAtom, loaded); |
| b69ab31 | | | 183 | return loaded; |
| b69ab31 | | | 184 | } |
| b69ab31 | | | 185 | // Kick off the "load" but rate limit it. |
| b69ab31 | | | 186 | limiter.enqueueRun(async () => { |
| b69ab31 | | | 187 | if (get(originalAtom) !== undefined) { |
| b69ab31 | | | 188 | // A previous "load" was completed. |
| b69ab31 | | | 189 | return; |
| b69ab31 | | | 190 | } |
| b69ab31 | | | 191 | const newValue = await loaded; |
| b69ab31 | | | 192 | writeAtom(originalAtom, newValue); |
| b69ab31 | | | 193 | }); |
| b69ab31 | | | 194 | // Use the fallback value while waiting for the promise. |
| b69ab31 | | | 195 | return fallback; |
| b69ab31 | | | 196 | }, |
| b69ab31 | | | 197 | (get, set, args) => { |
| b69ab31 | | | 198 | const newValue = |
| b69ab31 | | | 199 | typeof args === 'function' ? (args as (prev: T) => T)(get(originalAtom) ?? fallback) : args; |
| b69ab31 | | | 200 | set(originalAtom, newValue); |
| b69ab31 | | | 201 | }, |
| b69ab31 | | | 202 | ); |
| b69ab31 | | | 203 | } |
| b69ab31 | | | 204 | |
| b69ab31 | | | 205 | export function readAtom<T>(atom: Atom<T>): T { |
| b69ab31 | | | 206 | return store.get(atom); |
| b69ab31 | | | 207 | } |
| b69ab31 | | | 208 | |
| b69ab31 | | | 209 | export function writeAtom<T>(atom: MutAtom<T>, value: T | ((prev: T) => T)) { |
| b69ab31 | | | 210 | store.set(atom, value); |
| b69ab31 | | | 211 | } |
| b69ab31 | | | 212 | |
| b69ab31 | | | 213 | export function refreshAtom<T>(atom: WritableAtom<T, [], void>) { |
| b69ab31 | | | 214 | store.set(atom); |
| b69ab31 | | | 215 | } |
| b69ab31 | | | 216 | |
| b69ab31 | | | 217 | /** Create an atom that is automatically reset when the depAtom is changed. */ |
| b69ab31 | | | 218 | export function atomResetOnDepChange<T>(defaultValue: T, depAtom: Atom<unknown>): MutAtom<T> { |
| b69ab31 | | | 219 | assert( |
| b69ab31 | | | 220 | typeof depAtom !== 'undefined', |
| b69ab31 | | | 221 | 'depAtom should not be undefined (is there a circular dependency?)', |
| b69ab31 | | | 222 | ); |
| b69ab31 | | | 223 | const primitiveAtom = atom<T>(defaultValue); |
| b69ab31 | | | 224 | let lastDep = readAtom(depAtom); |
| b69ab31 | | | 225 | return atom( |
| b69ab31 | | | 226 | get => { |
| b69ab31 | | | 227 | const dep = get(depAtom); |
| b69ab31 | | | 228 | if (dep !== lastDep) { |
| b69ab31 | | | 229 | lastDep = dep; |
| b69ab31 | | | 230 | writeAtom(primitiveAtom, defaultValue); |
| b69ab31 | | | 231 | } |
| b69ab31 | | | 232 | return get(primitiveAtom); |
| b69ab31 | | | 233 | }, |
| b69ab31 | | | 234 | (_get, set, update) => { |
| b69ab31 | | | 235 | set(primitiveAtom, update); |
| b69ab31 | | | 236 | }, |
| b69ab31 | | | 237 | ); |
| b69ab31 | | | 238 | } |
| b69ab31 | | | 239 | |
| b69ab31 | | | 240 | /** |
| b69ab31 | | | 241 | * Creates a derived atom that can be force-refreshed, by using the update function. |
| b69ab31 | | | 242 | * Uses Suspense for async update functions. |
| b69ab31 | | | 243 | * ``` |
| b69ab31 | | | 244 | * const postsAtom = atomWithRefresh(get => fetchPostsAsync()); |
| b69ab31 | | | 245 | * ... |
| b69ab31 | | | 246 | * const [posts, refreshPosts] = useAtom(postsAtom); |
| b69ab31 | | | 247 | * ``` |
| b69ab31 | | | 248 | */ |
| b69ab31 | | | 249 | export function atomWithRefresh<T>(fn: (get: Getter) => T) { |
| b69ab31 | | | 250 | const refreshCounter = atom(0); |
| b69ab31 | | | 251 | |
| b69ab31 | | | 252 | return atom( |
| b69ab31 | | | 253 | get => { |
| b69ab31 | | | 254 | get(refreshCounter); |
| b69ab31 | | | 255 | return fn(get); |
| b69ab31 | | | 256 | }, |
| b69ab31 | | | 257 | (_, set) => set(refreshCounter, i => i + 1), |
| b69ab31 | | | 258 | ); |
| b69ab31 | | | 259 | } |
| b69ab31 | | | 260 | |
| b69ab31 | | | 261 | /** |
| b69ab31 | | | 262 | * Creates a derived atom that can be force-refreshed, by using the update function. |
| b69ab31 | | | 263 | * The underlying async state is given as a Loadable atom instead of one that suspends. |
| b69ab31 | | | 264 | * ``` |
| b69ab31 | | | 265 | * const postsAtom = atomWithRefresh(get => fetchPostsAsync()); |
| b69ab31 | | | 266 | * ... |
| b69ab31 | | | 267 | * const [postsLoadable, refreshPosts] = useAtom(postsAtom); |
| b69ab31 | | | 268 | * if (postsLoadable.state === 'hasData') { |
| b69ab31 | | | 269 | * const posts = postsLoadable.data; |
| b69ab31 | | | 270 | * } |
| b69ab31 | | | 271 | * ``` |
| b69ab31 | | | 272 | */ |
| b69ab31 | | | 273 | export function atomLoadableWithRefresh<T>(fn: (get: Getter) => Promise<T>) { |
| b69ab31 | | | 274 | const refreshCounter = atom(0); |
| b69ab31 | | | 275 | const loadableAtom = loadable( |
| b69ab31 | | | 276 | atom(get => { |
| b69ab31 | | | 277 | get(refreshCounter); |
| b69ab31 | | | 278 | return fn(get); |
| b69ab31 | | | 279 | }), |
| b69ab31 | | | 280 | ); |
| b69ab31 | | | 281 | |
| b69ab31 | | | 282 | return atom( |
| b69ab31 | | | 283 | get => get(loadableAtom), |
| b69ab31 | | | 284 | (_, set) => set(refreshCounter, i => i + 1), |
| b69ab31 | | | 285 | ); |
| b69ab31 | | | 286 | } |
| b69ab31 | | | 287 | |
| b69ab31 | | | 288 | /** |
| b69ab31 | | | 289 | * Drop-in replacement of `atomFamily` that tries to book-keep internal cache |
| b69ab31 | | | 290 | * periodically to avoid memory leak. |
| b69ab31 | | | 291 | * |
| b69ab31 | | | 292 | * There are 2 caches: |
| b69ab31 | | | 293 | * - "strong" cache: keep atoms alive even if all references are gone. |
| b69ab31 | | | 294 | * - "weak" cache: keep atoms alive as long as there is a reference to it. |
| b69ab31 | | | 295 | * |
| b69ab31 | | | 296 | * Periodically, when the weak cache size reaches a threshold, a "cleanup" |
| b69ab31 | | | 297 | * process runs to: |
| b69ab31 | | | 298 | * - Clear the "strong" cache to mitigate memory leak. |
| b69ab31 | | | 299 | * - Drop dead entries in the "weak" cache. |
| b69ab31 | | | 300 | * - Update the threshold to 2x the "weak" cache size. |
| b69ab31 | | | 301 | * |
| b69ab31 | | | 302 | * Therefore the memory waste is hopefully within 2x of the needed memory. |
| b69ab31 | | | 303 | * |
| b69ab31 | | | 304 | * Setting `options.useStrongCache` to `false` disables the "strong" cache |
| b69ab31 | | | 305 | * to further limit memory usage. |
| b69ab31 | | | 306 | */ |
| b69ab31 | | | 307 | export function atomFamilyWeak<K, A extends Atom<unknown>>( |
| b69ab31 | | | 308 | fn: (key: K) => A, |
| b69ab31 | | | 309 | options?: AtomFamilyWeakOptions, |
| b69ab31 | | | 310 | ): AtomFamilyWeak<K, A> { |
| b69ab31 | | | 311 | const {useStrongCache = true, initialCleanupThreshold = 4} = options ?? {}; |
| b69ab31 | | | 312 | |
| b69ab31 | | | 313 | // This cache persists through component unmount / remount, therefore |
| b69ab31 | | | 314 | // it can be memory leaky. |
| b69ab31 | | | 315 | const strongCache = new Map<K, A>(); |
| b69ab31 | | | 316 | |
| b69ab31 | | | 317 | // This cache ensures atoms in use are returned as-is during re-render, |
| b69ab31 | | | 318 | // to avoid infinite re-render with React StrictMode. |
| b69ab31 | | | 319 | const weakCache = new Map<K, WeakRef<A>>(); |
| b69ab31 | | | 320 | |
| b69ab31 | | | 321 | const cleanup = () => { |
| b69ab31 | | | 322 | // Clear the strong cache. This allows GC to drop weakRefs. |
| b69ab31 | | | 323 | strongCache.clear(); |
| b69ab31 | | | 324 | // Clean up weak cache - remove dead entries. |
| b69ab31 | | | 325 | weakCache.forEach((weakRef, key) => { |
| b69ab31 | | | 326 | if (weakRef.deref() == null) { |
| b69ab31 | | | 327 | weakCache.delete(key); |
| b69ab31 | | | 328 | } |
| b69ab31 | | | 329 | }); |
| b69ab31 | | | 330 | // Adjust threshold to trigger the next cleanup. |
| b69ab31 | | | 331 | resultFunc.threshold = weakCache.size * 2; |
| b69ab31 | | | 332 | }; |
| b69ab31 | | | 333 | |
| b69ab31 | | | 334 | const resultFunc: AtomFamilyWeak<K, A> = (key: K) => { |
| b69ab31 | | | 335 | const cached = strongCache.get(key); |
| b69ab31 | | | 336 | if (cached != null) { |
| b69ab31 | | | 337 | // This state was accessed recently. |
| b69ab31 | | | 338 | return cached; |
| b69ab31 | | | 339 | } |
| b69ab31 | | | 340 | const weakCached = weakCache.get(key)?.deref(); |
| b69ab31 | | | 341 | if (weakCached != null) { |
| b69ab31 | | | 342 | // State is not dead yet. |
| b69ab31 | | | 343 | return weakCached; |
| b69ab31 | | | 344 | } |
| b69ab31 | | | 345 | // Not in cache. Need re-calculate. |
| b69ab31 | | | 346 | const atom = fn(key); |
| b69ab31 | | | 347 | if (useStrongCache) { |
| b69ab31 | | | 348 | strongCache.set(key, atom); |
| b69ab31 | | | 349 | } |
| b69ab31 | | | 350 | weakCache.set(key, new WeakRef(atom)); |
| b69ab31 | | | 351 | if (weakCache.size > resultFunc.threshold) { |
| b69ab31 | | | 352 | cleanup(); |
| b69ab31 | | | 353 | } |
| b69ab31 | | | 354 | if (resultFunc.debugLabel != null && atom.debugLabel == null) { |
| b69ab31 | | | 355 | atom.debugLabel = `${resultFunc.debugLabel}:${key}`; |
| b69ab31 | | | 356 | } |
| b69ab31 | | | 357 | return atom; |
| b69ab31 | | | 358 | }; |
| b69ab31 | | | 359 | |
| b69ab31 | | | 360 | resultFunc.cleanup = cleanup; |
| b69ab31 | | | 361 | resultFunc.threshold = initialCleanupThreshold; |
| b69ab31 | | | 362 | resultFunc.strongCache = strongCache; |
| b69ab31 | | | 363 | resultFunc.weakCache = weakCache; |
| b69ab31 | | | 364 | resultFunc.clear = () => { |
| b69ab31 | | | 365 | weakCache.clear(); |
| b69ab31 | | | 366 | strongCache.clear(); |
| b69ab31 | | | 367 | resultFunc.threshold = initialCleanupThreshold; |
| b69ab31 | | | 368 | }; |
| b69ab31 | | | 369 | |
| b69ab31 | | | 370 | return resultFunc; |
| b69ab31 | | | 371 | } |
| b69ab31 | | | 372 | |
| b69ab31 | | | 373 | type AtomFamilyWeakOptions = { |
| b69ab31 | | | 374 | /** |
| b69ab31 | | | 375 | * Enable the "strong" cache so unmount / remount can try to reuse the cache. |
| b69ab31 | | | 376 | * |
| b69ab31 | | | 377 | * If this is disabled, then only the weakRef cache is used, states that |
| b69ab31 | | | 378 | * are no longer referred by components might be lost to GC. |
| b69ab31 | | | 379 | * |
| b69ab31 | | | 380 | * Default: true. |
| b69ab31 | | | 381 | */ |
| b69ab31 | | | 382 | useStrongCache?: boolean; |
| b69ab31 | | | 383 | |
| b69ab31 | | | 384 | /** |
| b69ab31 | | | 385 | * Number of items before triggering an initial cleanup. |
| b69ab31 | | | 386 | * Default: 4. |
| b69ab31 | | | 387 | */ |
| b69ab31 | | | 388 | initialCleanupThreshold?: number; |
| b69ab31 | | | 389 | }; |
| b69ab31 | | | 390 | |
| b69ab31 | | | 391 | export interface AtomFamilyWeak<K, A extends Atom<unknown>> { |
| b69ab31 | | | 392 | (key: K): A; |
| b69ab31 | | | 393 | /** The "strong" cache (can be empty). */ |
| b69ab31 | | | 394 | strongCache: Map<K, A>; |
| b69ab31 | | | 395 | /** The weakRef cache (must contain entries that are still referred elsewhere). */ |
| b69ab31 | | | 396 | weakCache: Map<K, WeakRef<A>>; |
| b69ab31 | | | 397 | /** Trigger a cleanup ("GC"). */ |
| b69ab31 | | | 398 | cleanup(): void; |
| b69ab31 | | | 399 | /** Clear the cache */ |
| b69ab31 | | | 400 | clear(): void; |
| b69ab31 | | | 401 | /** Auto cleanup threshold on weakCache size. */ |
| b69ab31 | | | 402 | threshold: number; |
| b69ab31 | | | 403 | /** Prefix of debugLabel. */ |
| b69ab31 | | | 404 | debugLabel?: string; |
| b69ab31 | | | 405 | } |
| b69ab31 | | | 406 | |
| b69ab31 | | | 407 | function getAllPersistedStateWithPrefix<T>( |
| b69ab31 | | | 408 | prefix: LocalStorageName, |
| b69ab31 | | | 409 | islPlatform: Platform, |
| b69ab31 | | | 410 | ): Record<string, T> { |
| b69ab31 | | | 411 | const all = islPlatform.getAllPersistedState(); |
| b69ab31 | | | 412 | if (all == null) { |
| b69ab31 | | | 413 | return {}; |
| b69ab31 | | | 414 | } |
| b69ab31 | | | 415 | return Object.fromEntries( |
| b69ab31 | | | 416 | Object.entries(all) |
| b69ab31 | | | 417 | .filter(([key]) => key.startsWith(prefix)) |
| b69ab31 | | | 418 | .map(([key, value]) => [key.slice(prefix.length), value]), |
| b69ab31 | | | 419 | ); |
| b69ab31 | | | 420 | } |
| b69ab31 | | | 421 | |
| b69ab31 | | | 422 | /** |
| b69ab31 | | | 423 | * An atom family that loads and persists data from local storage. |
| b69ab31 | | | 424 | * Each key is stored in a separate local storage entry, using the `storageKeyPrefix`. |
| b69ab31 | | | 425 | * Each stored value includes a timestamp so that stale data can be evicted, |
| b69ab31 | | | 426 | * on next startup. |
| b69ab31 | | | 427 | * Data is loaded once on startup, but written to local storage on every change. |
| b69ab31 | | | 428 | * Write `undefined` to any atom to explicitly remove it from local storage. |
| b69ab31 | | | 429 | */ |
| b69ab31 | | | 430 | export function localStorageBackedAtomFamily<K extends string, T extends Json | Partial<Json>>( |
| b69ab31 | | | 431 | storageKeyPrefix: LocalStorageName, |
| b69ab31 | | | 432 | getDefault: (key: K) => T, |
| b69ab31 | | | 433 | maxAgeDays = 14, |
| b69ab31 | | | 434 | islPlatform = platform, |
| b69ab31 | | | 435 | ): AtomFamilyWeak<K, WritableAtom<T, [T | undefined | ((prev: T) => T | undefined)], void>> { |
| b69ab31 | | | 436 | type StoredData = { |
| b69ab31 | | | 437 | data: T; |
| b69ab31 | | | 438 | date: number; |
| b69ab31 | | | 439 | }; |
| b69ab31 | | | 440 | const initialData = getAllPersistedStateWithPrefix<StoredData>(storageKeyPrefix, islPlatform); |
| b69ab31 | | | 441 | |
| b69ab31 | | | 442 | const ONE_DAY_MS = 1000 * 60 * 60 * 24; |
| b69ab31 | | | 443 | // evict previously stored old data |
| b69ab31 | | | 444 | for (const key in initialData) { |
| b69ab31 | | | 445 | const data = initialData[key]; |
| b69ab31 | | | 446 | if (data?.date != null && Date.now() - data?.date > ONE_DAY_MS * maxAgeDays) { |
| b69ab31 | | | 447 | islPlatform.setPersistedState(storageKeyPrefix + key, undefined); |
| b69ab31 | | | 448 | delete initialData[key]; |
| b69ab31 | | | 449 | } |
| b69ab31 | | | 450 | } |
| b69ab31 | | | 451 | |
| b69ab31 | | | 452 | return atomFamilyWeak((key: K) => { |
| b69ab31 | | | 453 | // We use the full getPersistedState instead of initialData, as this atom may have been evicted from the weak cache, |
| b69ab31 | | | 454 | // and is now being recreated and requires checking the actual cache to get any changes after initialization. |
| b69ab31 | | | 455 | const data = islPlatform.getPersistedState(storageKeyPrefix + key) as StoredData | null; |
| b69ab31 | | | 456 | const initial = data?.data ?? getDefault(key); |
| b69ab31 | | | 457 | const storageKey = storageKeyPrefix + key; |
| b69ab31 | | | 458 | |
| b69ab31 | | | 459 | const inner = atom<T>(initial); |
| b69ab31 | | | 460 | return atom( |
| b69ab31 | | | 461 | get => get(inner), |
| b69ab31 | | | 462 | (get, set, value) => { |
| b69ab31 | | | 463 | const oldValue = get(inner); |
| b69ab31 | | | 464 | const result = typeof value === 'function' ? value(oldValue) : value; |
| b69ab31 | | | 465 | set(inner, result === undefined ? getDefault(key) : result); |
| b69ab31 | | | 466 | const newValue = get(inner); |
| b69ab31 | | | 467 | if (oldValue !== newValue) { |
| b69ab31 | | | 468 | // TODO: debounce? |
| b69ab31 | | | 469 | islPlatform.setPersistedState( |
| b69ab31 | | | 470 | storageKey, |
| b69ab31 | | | 471 | result == null |
| b69ab31 | | | 472 | ? undefined |
| b69ab31 | | | 473 | : ({ |
| b69ab31 | | | 474 | data: newValue as Json, |
| b69ab31 | | | 475 | date: Date.now(), |
| b69ab31 | | | 476 | } as StoredData as Json), |
| b69ab31 | | | 477 | ); |
| b69ab31 | | | 478 | } |
| b69ab31 | | | 479 | }, |
| b69ab31 | | | 480 | ); |
| b69ab31 | | | 481 | }); |
| b69ab31 | | | 482 | } |
| b69ab31 | | | 483 | |
| b69ab31 | | | 484 | function setDebugLabelForDerivedAtom<A extends Atom<unknown>>( |
| b69ab31 | | | 485 | original: Atom<unknown>, |
| b69ab31 | | | 486 | derived: A, |
| b69ab31 | | | 487 | key: unknown, |
| b69ab31 | | | 488 | ): A { |
| b69ab31 | | | 489 | derived.debugLabel = `${original.debugLabel ?? original.toString()}:${key}`; |
| b69ab31 | | | 490 | return derived; |
| b69ab31 | | | 491 | } |
| b69ab31 | | | 492 | |
| b69ab31 | | | 493 | /** |
| b69ab31 | | | 494 | * Similar to `useAtomValue(mapAtom).get(key)` but avoids re-render if the map |
| b69ab31 | | | 495 | * is changed but the `get(key)` does not change. |
| b69ab31 | | | 496 | * |
| b69ab31 | | | 497 | * This might be an appealing alternative to `atomFamilyWeak` in some cases. |
| b69ab31 | | | 498 | * The `atomFamilyWeak` keeps caching state within itself and it has |
| b69ab31 | | | 499 | * undesirable memory overhead regardless of settings. This function makes |
| b69ab31 | | | 500 | * the hook own the caching state so states can be released cleanly on unmount. |
| b69ab31 | | | 501 | */ |
| b69ab31 | | | 502 | export function useAtomGet<K, V>( |
| b69ab31 | | | 503 | mapAtom: Atom<{get(k: K): V | undefined}>, |
| b69ab31 | | | 504 | key: K, |
| b69ab31 | | | 505 | ): Awaited<V | undefined> { |
| b69ab31 | | | 506 | const derivedAtom = useMemo(() => { |
| b69ab31 | | | 507 | const derived = atom(get => get(mapAtom).get(key)); |
| b69ab31 | | | 508 | return setDebugLabelForDerivedAtom(mapAtom, derived, key); |
| b69ab31 | | | 509 | }, [key, mapAtom]); |
| b69ab31 | | | 510 | return useAtomValue(derivedAtom); |
| b69ab31 | | | 511 | } |
| b69ab31 | | | 512 | |
| b69ab31 | | | 513 | /** |
| b69ab31 | | | 514 | * Similar to `useAtomValue(setAtom).has(key)` but avoids re-render if the set |
| b69ab31 | | | 515 | * is changed but the `has(key)` does not change. |
| b69ab31 | | | 516 | * |
| b69ab31 | | | 517 | * This might be an appealing alternative to `atomFamilyWeak`. See `useAtomGet` |
| b69ab31 | | | 518 | * for explanation. |
| b69ab31 | | | 519 | */ |
| b69ab31 | | | 520 | export function useAtomHas<K>(setAtom: Atom<{has(k: K): boolean}>, key: K): Awaited<boolean> { |
| b69ab31 | | | 521 | const derivedAtom = useMemo(() => atom(get => get(setAtom).has(key)), [key, setAtom]); |
| b69ab31 | | | 522 | return useAtomValue(derivedAtom); |
| b69ab31 | | | 523 | } |