@choksheak/react-utils 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunk-25NYDKKO.min.js +2 -0
- package/chunk-25NYDKKO.min.js.map +1 -0
- package/chunk-2WE3FDDW.min.cjs +2 -0
- package/{chunk-SQX7XDQJ.min.cjs.map → chunk-2WE3FDDW.min.cjs.map} +1 -1
- package/{chunk-UBAHJNMF.js → chunk-5O4HBYCM.js} +214 -284
- package/{chunk-ALTY6BU7.cjs → chunk-5WECMKSV.cjs} +219 -289
- package/chunk-AX6NADU2.min.cjs +2 -0
- package/chunk-AX6NADU2.min.cjs.map +1 -0
- package/chunk-JHM37XTC.min.js +2 -0
- package/chunk-JHM37XTC.min.js.map +1 -0
- package/{chunk-KXFV42DP.cjs → chunk-YMQDZV47.cjs} +30 -10
- package/{chunk-H4OYYPJV.js → chunk-ZEVXDXJD.js} +30 -10
- package/index.cjs +3 -3
- package/index.d.cts +1 -1
- package/index.d.ts +1 -1
- package/index.js +2 -2
- package/index.min.cjs +1 -1
- package/index.min.js +1 -1
- package/package.json +12 -12
- package/sharedQuery.cjs +3 -3
- package/sharedQuery.d.cts +16 -79
- package/sharedQuery.d.ts +16 -79
- package/sharedQuery.js +2 -2
- package/sharedQuery.min.cjs +1 -1
- package/sharedQuery.min.js +1 -1
- package/sharedState.cjs +2 -2
- package/sharedState.d.cts +2 -2
- package/sharedState.d.ts +2 -2
- package/sharedState.js +1 -1
- package/sharedState.min.cjs +1 -1
- package/sharedState.min.js +1 -1
- package/chunk-GV7KUTU2.min.js +0 -2
- package/chunk-GV7KUTU2.min.js.map +0 -1
- package/chunk-IKHSARNO.min.js +0 -2
- package/chunk-IKHSARNO.min.js.map +0 -1
- package/chunk-OCJG7MUG.min.cjs +0 -2
- package/chunk-OCJG7MUG.min.cjs.map +0 -1
- package/chunk-SQX7XDQJ.min.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as p}from"./chunk-QASRLGQX.min.js";import{MS_PER_DAY as v}from"@choksheak/ts-utils/timeConstants";import{useSyncExternalStore as w}from"react";var T=typeof window<"u",f={storeExpiryMs:30*v,lazyLoad:!1,log:(...e)=>{T&&console.log("[sharedState]",...e)}};function U(e){Object.assign(f,e)}function y(){let e=new Map,n=new Map;function u(r,i,o){let a=n.get(r);if(!a)return;let S=Array.from(a.values());for(let l of S)try{l(i,o)}catch(b){console.error("Error invoking subscriber:",b)}}return{get(r){return e.get(r)},set(r,i){let o=e.get(r);o!==i&&(e.set(r,i),u(r,i,o))},delete(r){e.delete(r)},setNoNotify(r,i){e.set(r,i)},subscribe(r,i){let o=n.get(r);return o||(o=new Set,n.set(r,o)),o.add(i),()=>{o.delete(i),o.size===0&&n.delete(r)}}}}function P(){if(T){let e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=y())}return y()}var d=P(),m="state",O=0;function E(){if(T){let e=window.globalThis;return e.reactUtilsStateKey=(e.reactUtilsStateKey??0)+1,e.reactUtilsStateKey}return++O}function V(e,n){let u=()=>{},r=new Promise(t=>{u=t}),i=u,o=n?.log||f.log,a=String(E());o&&n?.name&&o(`${n.name} -> ${a}`);let S=p(n,f.storeExpiryMs);d.setNoNotify(a,e);let l=n?.lazyLoad,b=l!==void 0?l:f.lazyLoad;function c(t){if(s.initDone)return!1;let g=t!==void 0?t:e;return d.set(a,g),s.initStarted=!0,s.initDone=!0,i(),!0}let s={name:n?.name,defaultValue:e,pubSubKey:a,readyPromise:r,storeExpiryMs:f.storeExpiryMs,lazy:b,storageAdapter:S,initStarted:!1,initDone:!1,subscribe(t){return d.subscribe(a,()=>t())},hasStore(){return!!S},setInStore(t){return S?.set(m,t)},getFromStore(){return S?.get(m)},getSnapshot(){return d.get(a)},setValue(t){if(typeof t=="function"){let h=d.get(a);t=t(h)}return c(t)||d.set(a,t),s.setInStore(t)},delete(){return s.setValue(e)},initDefaultValueOnce(){if(!(s.initDone||s.initStarted)){s.initStarted=!0;try{let t=s.getFromStore();t instanceof Promise?t.then(c).catch(g=>{o(`[ERROR] Failed to load from store${n?.name?` (${n.name})`:""}:`,g),c(void 0)}):c(t)}catch(t){o(`[ERROR] Error while loading from store${n?.name?` (${n.name})`:""}:`,t),c(void 0)}}}};return b||s.initDefaultValueOnce(),s}function R(e){return e.initDefaultValueOnce(),[w(u=>e.subscribe(u),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function $(e){return R(e)[0]}function C(e){return e.initDefaultValueOnce(),e.setValue}export{f as a,U as b,V as c,R as d,$ as e,C as f};
|
|
2
|
+
//# sourceMappingURL=chunk-25NYDKKO.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sharedState.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\nconst hasWindow = typeof window !== \"undefined\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => {\n if (!hasWindow) return; // don't log in the SSR server side\n console.log(\"[sharedState]\", ...args);\n },\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (hasWindow) {\n const t = window.globalThis as {\n reactUtilsPubSubStore?: ReturnType<typeof createPubSubStore>;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n /** Load from store only on first use of useSharedState(). */\n lazyLoad?: boolean;\n /** Used for debug logging. */\n name?: string;\n /** Customize the logger. */\n log?: (...args: unknown[]) => void;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n// Try to make this safe across hot reloads and bundling.\nfunction getNextStateKey() {\n if (hasWindow) {\n const t = window.globalThis as { reactUtilsStateKey?: number };\n t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;\n return t.reactUtilsStateKey;\n }\n return ++stateKey;\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n const log = options?.log || SharedStateConfig.log;\n\n // We'll make a new key with each hot reload, but that's ok.\n const pubSubKey = String(getNextStateKey());\n\n if (log && options?.name) {\n log(`${options.name} -> ${pubSubKey}`);\n }\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n // Returns true if we published the value to the listeners.\n function completeInit(stored: T | undefined): boolean {\n // Async storage reads can finish after setValue()/delete(). Don't overwrite\n // newer in-memory values with a stale snapshot from when init started.\n if (obj.initDone) {\n return false;\n }\n\n const value = stored !== undefined ? stored : defaultValue;\n pubSubStore.set(pubSubKey, value);\n\n // If we init from setValue()/delete(), then initStarted might not have\n // been initialized yet, so just set it manually here.\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n\n return true;\n }\n\n const obj = {\n name: options?.name,\n defaultValue,\n pubSubKey,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n storeExpiryMs: SharedStateConfig.storeExpiryMs,\n lazy,\n storageAdapter,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n setInStore(value: T): Promise<void> | void {\n return storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n getFromStore(): Promise<T | undefined> | T | undefined {\n return storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): Promise<void> | void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n // Win race to complete init before init with default value.\n const updated = completeInit(next);\n\n if (!updated) {\n pubSubStore.set(pubSubKey, next);\n }\n\n return obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete(): Promise<void> | void {\n return obj.setValue(defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n // Ensure that the readyPromise always resolves even if getFromStore()\n // throws an error.\n try {\n const storedOrPromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (storedOrPromise instanceof Promise) {\n storedOrPromise.then(completeInit).catch((e) => {\n log(\n `[ERROR] Failed to load from store${options?.name ? ` (${options.name})` : \"\"}:`,\n e,\n );\n completeInit(undefined);\n });\n } else {\n completeInit(storedOrPromise);\n }\n } catch (e) {\n log(\n `[ERROR] Error while loading from store${options?.name ? ` (${options.name})` : \"\"}:`,\n e,\n );\n completeInit(undefined);\n }\n },\n } as const;\n\n if (!lazy) {\n obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n"],"mappings":"4CAwDA,OAAS,cAAAA,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QAI/D,IAAMC,EAAY,OAAO,OAAW,IASvBC,EAAoB,CAK/B,cAAe,GAAKC,EAMpB,SAAU,GAGV,IAAK,IAAIC,IAAoB,CACtBH,GACL,QAAQ,IAAI,gBAAiB,GAAGG,CAAI,CACtC,CACF,EAKO,SAASC,EAAqBC,EAAoC,CACvE,OAAO,OAAOJ,EAAmBI,CAAM,CACzC,CAQA,SAASC,GAAoB,CAC3B,IAAMC,EAAY,IAAI,IAChBC,EAAmB,IAAI,IAE7B,SAASC,EAAUC,EAAaC,EAASC,EAAe,CACtD,IAAMC,EAAcL,EAAiB,IAAIE,CAAG,EAC5C,GAAI,CAACG,EAAa,OAGlB,IAAMC,EAAO,MAAM,KAAKD,EAAY,OAAO,CAAC,EAC5C,QAAWE,KAAcD,EACvB,GAAI,CACFC,E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BAA6C,CAC3C,GAAI,EAAAc,EAAI,UAAYA,EAAI,aAExB,CAAAA,EAAI,YAAc,GAIlB,GAAI,CACF,IAAMC,EAAkBD,EAAI,aAAa,EAIrCC,aAA2B,QAC7BA,EAAgB,KAAKH,CAAY,EAAE,MAAOrB,GAAM,CAC9Ce,EACE,oCAAoCL,GAAS,KAAO,KAAKA,EAAQ,IAAI,IAAM,EAAE,IAC7EV,CACF,EACAqB,EAAa,MAAS,CACxB,CAAC,EAEDA,EAAaG,CAAe,CAEhC,OAASxB,EAAG,CACVe,EACE,yCAAyCL,GAAS,KAAO,KAAKA,EAAQ,IAAI,IAAM,EAAE,IAClFV,CACF,EACAqB,EAAa,MAAS,CACxB,EACF,CACF,EAEA,OAAKD,GACHG,EAAI,qBAAqB,EAGpBA,CACT,CAYO,SAASE,EACdC,EACkC,CAClC,OAAKA,EAAM,qBAAqB,EASzB,CAPOC,EACXC,GAAkBF,EAAM,UAAUE,CAAa,EAChD,IAAMF,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,QAAQ,CAC/B,CAUO,SAASG,EAAuBH,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAUO,SAASI,EAAwBJ,EAAuB,CAC7D,OAAKA,EAAM,qBAAqB,EAEzBA,EAAM,QACf","names":["MS_PER_DAY","useSyncExternalStore","hasWindow","SharedStateConfig","MS_PER_DAY","args","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","getNextStateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","log","pubSubKey","storageAdapter","getStorageAdapter","lazyLoad","lazy","completeInit","stored","obj","storedOrPromise","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkUFJQLQFImincjs = require('./chunk-UFJQLQFI.min.cjs');var _timeConstants = require('@choksheak/ts-utils/timeConstants');var _react = require('react');var T=typeof window<"u",f= exports.a ={storeExpiryMs:30*_timeConstants.MS_PER_DAY,lazyLoad:!1,log:(...e)=>{T&&console.log("[sharedState]",...e)}};function U(e){Object.assign(f,e)}function y(){let e=new Map,n=new Map;function u(r,i,o){let a=n.get(r);if(!a)return;let S=Array.from(a.values());for(let l of S)try{l(i,o)}catch(b){console.error("Error invoking subscriber:",b)}}return{get(r){return e.get(r)},set(r,i){let o=e.get(r);o!==i&&(e.set(r,i),u(r,i,o))},delete(r){e.delete(r)},setNoNotify(r,i){e.set(r,i)},subscribe(r,i){let o=n.get(r);return o||(o=new Set,n.set(r,o)),o.add(i),()=>{o.delete(i),o.size===0&&n.delete(r)}}}}function P(){if(T){let e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=y())}return y()}var d=P(),m="state",O=0;function E(){if(T){let e=window.globalThis;return e.reactUtilsStateKey=(_nullishCoalesce(e.reactUtilsStateKey, () => (0)))+1,e.reactUtilsStateKey}return++O}function V(e,n){let u=()=>{},r=new Promise(t=>{u=t}),i=u,o=_optionalChain([n, 'optionalAccess', _ => _.log])||f.log,a=String(E());o&&_optionalChain([n, 'optionalAccess', _2 => _2.name])&&o(`${n.name} -> ${a}`);let S=_chunkUFJQLQFImincjs.a.call(void 0, n,f.storeExpiryMs);d.setNoNotify(a,e);let l=_optionalChain([n, 'optionalAccess', _3 => _3.lazyLoad]),b=l!==void 0?l:f.lazyLoad;function c(t){if(s.initDone)return!1;let g=t!==void 0?t:e;return d.set(a,g),s.initStarted=!0,s.initDone=!0,i(),!0}let s={name:_optionalChain([n, 'optionalAccess', _4 => _4.name]),defaultValue:e,pubSubKey:a,readyPromise:r,storeExpiryMs:f.storeExpiryMs,lazy:b,storageAdapter:S,initStarted:!1,initDone:!1,subscribe(t){return d.subscribe(a,()=>t())},hasStore(){return!!S},setInStore(t){return _optionalChain([S, 'optionalAccess', _5 => _5.set, 'call', _6 => _6(m,t)])},getFromStore(){return _optionalChain([S, 'optionalAccess', _7 => _7.get, 'call', _8 => _8(m)])},getSnapshot(){return d.get(a)},setValue(t){if(typeof t=="function"){let h=d.get(a);t=t(h)}return c(t)||d.set(a,t),s.setInStore(t)},delete(){return s.setValue(e)},initDefaultValueOnce(){if(!(s.initDone||s.initStarted)){s.initStarted=!0;try{let t=s.getFromStore();t instanceof Promise?t.then(c).catch(g=>{o(`[ERROR] Failed to load from store${_optionalChain([n, 'optionalAccess', _9 => _9.name])?` (${n.name})`:""}:`,g),c(void 0)}):c(t)}catch(t){o(`[ERROR] Error while loading from store${_optionalChain([n, 'optionalAccess', _10 => _10.name])?` (${n.name})`:""}:`,t),c(void 0)}}}};return b||s.initDefaultValueOnce(),s}function R(e){return e.initDefaultValueOnce(),[_react.useSyncExternalStore.call(void 0, u=>e.subscribe(u),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function $(e){return R(e)[0]}function C(e){return e.initDefaultValueOnce(),e.setValue}exports.a = f; exports.b = U; exports.c = V; exports.d = R; exports.e = $; exports.f = C;
|
|
2
|
+
//# sourceMappingURL=chunk-2WE3FDDW.min.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-SQX7XDQJ.min.cjs","../src/sharedState.ts"],"names":["hasWindow","SharedStateConfig","MS_PER_DAY","args","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","getNextStateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","log","pubSubKey"],"mappings":"AAAA,gvBAA4C,kECwDjB,8BACoC,IAIzDA,CAAAA,CAAY,OAAO,MAAA,CAAW,GAAA,CASvBC,CAAAA,aAAoB,CAK/B,aAAA,CAAe,EAAA,CAAKC,yBAAAA,CAMpB,QAAA,CAAU,CAAA,CAAA,CAGV,GAAA,CAAK,CAAA,GAAIC,CAAAA,CAAAA,EAAoB,CACtBH,CAAAA,EACL,OAAA,CAAQ,GAAA,CAAI,eAAA,CAAiB,GAAGG,CAAI,CACtC,CACF,CAAA,CAKO,SAASC,CAAAA,CAAqBC,CAAAA,CAAoC,CACvE,MAAA,CAAO,MAAA,CAAOJ,CAAAA,CAAmBI,CAAM,CACzC,CAQA,SAASC,CAAAA,CAAAA,CAAoB,CAC3B,IAAMC,CAAAA,CAAY,IAAI,GAAA,CAChBC,CAAAA,CAAmB,IAAI,GAAA,CAE7B,SAASC,CAAAA,CAAUC,CAAAA,CAAaC,CAAAA,CAASC,CAAAA,CAAe,CACtD,IAAMC,CAAAA,CAAcL,CAAAA,CAAiB,GAAA,CAAIE,CAAG,CAAA,CAC5C,EAAA,CAAI,CAACG,CAAAA,CAAa,MAAA,CAGlB,IAAMC,CAAAA,CAAO,KAAA,CAAM,IAAA,CAAKD,CAAAA,CAAY,MAAA,CAAO,CAAC,CAAA,CAC5C,GAAA,CAAA,IAAWE,EAAAA,GAAcD,CAAAA,CACvB,GAAI,CACFC,CAAAA,CAAWJ,CAAAA,CAAMC,CAAI,CACvB,CAAA,KAAA,CAASI,CAAAA,CAAG,CACV,OAAA,CAAQ,KAAA,CAAM,4BAAA,CAA8BA,CAAC,CAC/C,CAEJ,CAEA,MAAO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CAAAA,CAAkB,CAAA,CAE5E,CACA,OAAOA,CAAAA,CAAkB,CAC3B,CAEA,IAAMc,CAAAA,CAAcF,CAAAA,CAAuB,CAAA,CAMrCG,CAAAA,CAAc,OAAA,CAYhBC,CAAAA,CAAW,CAAA,CAGf,SAASC,CAAAA,CAAAA,CAAkB,CACzB,EAAA,CAAIvB,CAAAA,CAAW,CACb,IAAMmB,CAAAA,CAAI,MAAA,CAAO,UAAA,CACjB,OAAAA,CAAAA,CAAE,kBAAA,CAAA,kBAAsBA,CAAAA,CAAE,kBAAA,SAAsB,GAAA,CAAA,CAAK,CAAA,CAC9CA,CAAAA,CAAE,kBACX,CACA,MAAO,EAAEG,CACX,CAUO,SAASE,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACA,CACA,IAAIC,CAAAA,CAA2B,CAAA,CAAA,EAAM,CAAC,CAAA,CAEhCC,CAAAA,CAAe,IAAI,OAAA,CAAeC,CAAAA,EAAY,CAClDF,CAAAA,CAAeE,CACjB,CAAC,CAAA,CAEKC,CAAAA,CAAsBH,CAAAA,CAEtBI,CAAAA,iBAAML,CAAAA,2BAAS,KAAA,EAAOzB,CAAAA,CAAkB,GAAA,CAGxC+B,CAAAA,CAAY,MAAA,CAAOT,CAAAA,CAAgB,CAAC,CAAA,CAEtCQ,CAAAA,kBAAOL,CAAAA,6BAAS,MAAA,EAClBK,CAAAA,CAAI,CAAA,EAAA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-SQX7XDQJ.min.cjs","sourcesContent":[null,"/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\nconst hasWindow = typeof window !== \"undefined\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => {\n if (!hasWindow) return; // don't log in the SSR server side\n console.log(\"[sharedState]\", ...args);\n },\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (hasWindow) {\n const t = window.globalThis as {\n reactUtilsPubSubStore?: ReturnType<typeof createPubSubStore>;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n /** Load from store only on first use of useSharedState(). */\n lazyLoad?: boolean;\n /** Used for debug logging. */\n name?: string;\n /** Customize the logger. */\n log?: (...args: unknown[]) => void;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n// Try to make this safe across hot reloads and bundling.\nfunction getNextStateKey() {\n if (hasWindow) {\n const t = window.globalThis as { reactUtilsStateKey?: number };\n t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;\n return t.reactUtilsStateKey;\n }\n return ++stateKey;\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n const log = options?.log || SharedStateConfig.log;\n\n // We'll make a new key with each hot reload, but that's ok.\n const pubSubKey = String(getNextStateKey());\n\n if (log && options?.name) {\n log(`${options.name} -> ${pubSubKey}`);\n }\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n function completeInit(stored: T | undefined) {\n const value = stored !== undefined ? stored : defaultValue;\n\n pubSubStore.set(pubSubKey, value);\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n }\n\n const obj = {\n name: options?.name,\n defaultValue,\n pubSubKey,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n storeExpiryMs: SharedStateConfig.storeExpiryMs,\n lazy,\n storageAdapter,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n setInStore(value: T): Promise<void> | void {\n return storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n getFromStore(): Promise<T | undefined> | T | undefined {\n return storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(pubSubKey, next);\n void obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete(): Promise<void> | void {\n pubSubStore.set(pubSubKey, defaultValue);\n return storageAdapter?.set(STORAGE_KEY, defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n const maybePromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (maybePromise instanceof Promise) {\n return maybePromise.then(completeInit);\n } else {\n const stored = maybePromise;\n completeInit(stored);\n }\n },\n } as const;\n\n if (!lazy) {\n obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-2WE3FDDW.min.cjs","../src/sharedState.ts"],"names":["hasWindow","SharedStateConfig","MS_PER_DAY","args","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","getNextStateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","log","pubSubKey"],"mappings":"AAAA,gvBAA4C,kECwDjB,8BACoC,IAIzDA,CAAAA,CAAY,OAAO,MAAA,CAAW,GAAA,CASvBC,CAAAA,aAAoB,CAK/B,aAAA,CAAe,EAAA,CAAKC,yBAAAA,CAMpB,QAAA,CAAU,CAAA,CAAA,CAGV,GAAA,CAAK,CAAA,GAAIC,CAAAA,CAAAA,EAAoB,CACtBH,CAAAA,EACL,OAAA,CAAQ,GAAA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AAIC,CAAAA,CAA2B,CAAA,CAAA,EAAM,CAAC,CAAA,CAEhCC,CAAAA,CAAe,IAAI,OAAA,CAAeC,CAAAA,EAAY,CAClDF,CAAAA,CAAeE,CACjB,CAAC,CAAA,CAEKC,CAAAA,CAAsBH,CAAAA,CAEtBI,CAAAA,iBAAML,CAAAA,2BAAS,KAAA,EAAOzB,CAAAA,CAAkB,GAAA,CAGxC+B,CAAAA,CAAY,MAAA,CAAOT,CAAAA,CAAgB,CAAC,CAAA,CAEtCQ,CAAAA,kBAAOL,CAAAA,6BAAS,MAAA,EAClBK,CAAAA,CAAI,CAAA,EAAA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-2WE3FDDW.min.cjs","sourcesContent":[null,"/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\nconst hasWindow = typeof window !== \"undefined\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => {\n if (!hasWindow) return; // don't log in the SSR server side\n console.log(\"[sharedState]\", ...args);\n },\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (hasWindow) {\n const t = window.globalThis as {\n reactUtilsPubSubStore?: ReturnType<typeof createPubSubStore>;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n /** Load from store only on first use of useSharedState(). */\n lazyLoad?: boolean;\n /** Used for debug logging. */\n name?: string;\n /** Customize the logger. */\n log?: (...args: unknown[]) => void;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n// Try to make this safe across hot reloads and bundling.\nfunction getNextStateKey() {\n if (hasWindow) {\n const t = window.globalThis as { reactUtilsStateKey?: number };\n t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;\n return t.reactUtilsStateKey;\n }\n return ++stateKey;\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n const log = options?.log || SharedStateConfig.log;\n\n // We'll make a new key with each hot reload, but that's ok.\n const pubSubKey = String(getNextStateKey());\n\n if (log && options?.name) {\n log(`${options.name} -> ${pubSubKey}`);\n }\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n // Returns true if we published the value to the listeners.\n function completeInit(stored: T | undefined): boolean {\n // Async storage reads can finish after setValue()/delete(). Don't overwrite\n // newer in-memory values with a stale snapshot from when init started.\n if (obj.initDone) {\n return false;\n }\n\n const value = stored !== undefined ? stored : defaultValue;\n pubSubStore.set(pubSubKey, value);\n\n // If we init from setValue()/delete(), then initStarted might not have\n // been initialized yet, so just set it manually here.\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n\n return true;\n }\n\n const obj = {\n name: options?.name,\n defaultValue,\n pubSubKey,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n storeExpiryMs: SharedStateConfig.storeExpiryMs,\n lazy,\n storageAdapter,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n setInStore(value: T): Promise<void> | void {\n return storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n getFromStore(): Promise<T | undefined> | T | undefined {\n return storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): Promise<void> | void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n // Win race to complete init before init with default value.\n const updated = completeInit(next);\n\n if (!updated) {\n pubSubStore.set(pubSubKey, next);\n }\n\n return obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete(): Promise<void> | void {\n return obj.setValue(defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n // Ensure that the readyPromise always resolves even if getFromStore()\n // throws an error.\n try {\n const storedOrPromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (storedOrPromise instanceof Promise) {\n storedOrPromise.then(completeInit).catch((e) => {\n log(\n `[ERROR] Failed to load from store${options?.name ? ` (${options.name})` : \"\"}:`,\n e,\n );\n completeInit(undefined);\n });\n } else {\n completeInit(storedOrPromise);\n }\n } catch (e) {\n log(\n `[ERROR] Error while loading from store${options?.name ? ` (${options.name})` : \"\"}:`,\n e,\n );\n completeInit(undefined);\n }\n },\n } as const;\n\n if (!lazy) {\n obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n"]}
|