@oxog/state 1.3.1 → 1.4.0
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/dist/{chunk-R6MFYVYQ.js → chunk-2QNZBQ4V.js} +12 -5
- package/dist/chunk-2QNZBQ4V.js.map +1 -0
- package/dist/{chunk-IWT3T2PM.cjs → chunk-V6ASKKTH.cjs} +12 -5
- package/dist/chunk-V6ASKKTH.cjs.map +1 -0
- package/dist/iife/index.global.js +1 -1
- package/dist/index.cjs +70 -70
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/vanilla.cjs +66 -66
- package/dist/vanilla.d.cts +2 -2
- package/dist/vanilla.d.ts +2 -2
- package/dist/vanilla.js +1 -1
- package/package.json +18 -9
- package/dist/chunk-IWT3T2PM.cjs.map +0 -1
- package/dist/chunk-R6MFYVYQ.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.ts"],"names":["selector","identity","shallowEqual","useRef","useCallback","useSyncExternalStore","useDebugValue","createStore","useEffect"],"mappings":";;;;;AAqDO,SAAS,QAAA,CACd,KAAA,EACAA,SAAAA,GAAwCC,0BAAA,EACxC,aAAoCC,8BAAA,EACzB;AAEX,EAAA,MAAM,WAAA,GAAcC,aAAOH,SAAQ,CAAA;AACnC,EAAA,MAAM,aAAA,GAAgBG,aAAO,UAAU,CAAA;AACvC,EAAA,WAAA,CAAY,OAAA,GAAUH,SAAAA;AACtB,EAAA,aAAA,CAAc,OAAA,GAAU,UAAA;AAKxB,EAAA,MAAM,QAAA,GAAWG,aAKP,IAAI,CAAA;AAEd,EAAA,MAAM,WAAA,GAAcC,kBAAY,MAAiB;AAC/C,IAAA,MAAM,KAAA,GAAQ,MAAM,QAAA,EAAS;AAC7B,IAAA,MAAM,kBAAkB,WAAA,CAAY,OAAA;AACpC,IAAA,MAAM,QAAQ,QAAA,C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;AAAA,EACrB;AAEA,EAAA,MAAM,WAAA,GAAcA,YAAA,CAAO,CAAC,OAAA,KAAoE;AAC9F,IAAA,QAAA,CAAS,OAAA,CAAQ,SAAS,OAAO,CAAA;AAAA,EACnC,CAAC,CAAA;AAED,EAAA,OAAO,WAAA,CAAY,OAAA;AACrB","file":"index.cjs","sourcesContent":["import { useSyncExternalStore, useDebugValue, useEffect, useRef, useCallback } from 'react';\nimport type { EqualityFn, Selector, Store } from './types.js';\nimport { identity } from './utils/identity.js';\nimport { shallowEqual } from './utils/shallow-equal.js';\nimport { createStore as _createStore } from './store.js';\n\n/**\n * React hook for subscribing to store state changes.\n *\n * Uses useSyncExternalStore for optimal performance and SSR compatibility.\n *\n * @typeParam TState - The store state type\n * @typeParam TSelected - The selected state type\n * @param store - The store instance\n * @param selector - Optional selector to extract a slice of state\n * @param equalityFn - Optional custom equality function\n * @returns The selected state slice\n *\n * @example\n * ```typescript\n * import { createStore, useStore } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * name: 'John',\n * increment: (state) => ({ count: state.count + 1 }),\n * });\n *\n * function Counter() {\n * // Select entire state\n * const state = useStore(store);\n *\n * // Select with selector\n * const count = useStore(store, (state) => state.count);\n *\n * // Select with custom equality check\n * const user = useStore(\n * store,\n * (state) => state.user,\n * (a, b) => a?.id === b?.id\n * );\n *\n * // Select action\n * const increment = useStore(store, (state) => state.increment);\n *\n * return (\n * <button onClick={increment}>\n * Count: {count}\n * </button>\n * );\n * }\n * ```\n */\nexport function useStore<TState, TSelected = TState>(\n store: Store<TState>,\n selector: Selector<TState, TSelected> = identity as any,\n equalityFn: EqualityFn<TSelected> = shallowEqual as any\n): TSelected {\n // Latest selector / equality function (inline functions are fine).\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Last selection. getSnapshot must return the same reference while the\n // selection is unchanged, otherwise useSyncExternalStore re-renders forever\n // for selectors that build a new object/array.\n const cacheRef = useRef<{\n store: Store<TState>;\n state: TState;\n selector: Selector<TState, TSelected>;\n selected: TSelected;\n } | null>(null);\n\n const getSnapshot = useCallback((): TSelected => {\n const state = store.getState();\n const currentSelector = selectorRef.current;\n const cache = cacheRef.current;\n if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {\n return cache.selected;\n }\n const next = currentSelector(state);\n if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {\n cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };\n return cache.selected;\n }\n cacheRef.current = { store, state, selector: currentSelector, selected: next };\n return next;\n }, [store]);\n\n const subscribe = useCallback((callback: () => void) => store.subscribe(() => callback()), [store]);\n\n const selectedState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // Debug value for React DevTools\n useDebugValue(selectedState);\n\n return selectedState;\n}\n\n/**\n * React hook for creating and using a store.\n *\n * Creates a store on first render and destroys it after the component\n * unmounts. Safe under React StrictMode (the simulated unmount/remount in\n * development does not destroy the store).\n *\n * @typeParam TState - The store state type\n * @param initialState - The initial state\n * @returns The store instance\n *\n * @example\n * ```typescript\n * import { useCreateStore } from '@oxog/state';\n *\n * function Component() {\n * const store = useCreateStore({ count: 0 });\n * const count = useStore(store, (s) => s.count);\n *\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useCreateStore<TState>(initialState: TState): Store<TState> {\n const storeRef = useRef<Store<TState>>();\n const pendingDestroyRef = useRef<object | null>(null);\n\n if (storeRef.current === undefined) {\n storeRef.current = _createStore(initialState) as unknown as Store<TState>;\n }\n const store = storeRef.current;\n\n useEffect(() => {\n // (Re)mounted: cancel a destroy scheduled by a StrictMode cleanup.\n pendingDestroyRef.current = null;\n return () => {\n // Defer the destroy: StrictMode re-runs the effect synchronously after\n // this cleanup, which cancels it. A real unmount lets it run.\n const token = {};\n pendingDestroyRef.current = token;\n queueMicrotask(() => {\n if (pendingDestroyRef.current === token) {\n store.destroy();\n if (storeRef.current === store) {\n storeRef.current = undefined;\n }\n }\n });\n };\n }, [store]);\n\n return store;\n}\n\n/**\n * React hook for getting a store action.\n *\n * Convenience hook for selecting action functions from a store.\n *\n * @typeParam TState - The store state type\n * @typeParam TAction - The action type\n * @param store - The store instance\n * @param actionName - The name of the action\n * @returns The action function\n *\n * @example\n * ```typescript\n * import { createStore, useAction } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * increment: (state) => ({ count: state.count + 1 }),\n * decrement: (state) => ({ count: state.count - 1 }),\n * });\n *\n * function Counter() {\n * const increment = useAction(store, 'increment');\n * const decrement = useAction(store, 'decrement');\n * const count = useStore(store, (s) => s.count);\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <span>{count}</span>\n * <button onClick={increment}>+</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useAction<TState, TAction extends (...args: any[]) => any>(\n store: Store<TState>,\n actionName: string\n): TAction {\n // Actions are methods on the store instance, not properties of state\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n // Get the action from the store instance\n const action = (storeRef.current as any)[actionName];\n\n // Return a stable reference to the action\n const actionRef = useRef(action);\n if (actionRef.current !== action) {\n actionRef.current = action;\n }\n\n return actionRef.current as TAction;\n}\n\n/**\n * Create a shallow equality wrapper for selectors.\n *\n * Use this hook to wrap selectors that return objects or arrays\n * and you want to avoid re-renders when the content hasn't changed.\n *\n * @param selector - The selector function to wrap\n * @returns A wrapped selector with shallow equality\n *\n * @example\n * ```typescript\n * import { useStore, useShallow } from '@oxog/state';\n *\n * function UserInfo() {\n * // Without useShallow - re-renders on every state change\n * const { name, email } = useStore(store, s => ({ name: s.name, email: s.email }));\n *\n * // With useShallow - only re-renders when name or email actually changes\n * const { name, email } = useStore(\n * store,\n * useShallow(s => ({ name: s.name, email: s.email }))\n * );\n * }\n * ```\n */\nexport function useShallow<TState, TSelected extends object>(\n selector: Selector<TState, TSelected>\n): Selector<TState, TSelected> {\n const prev = useRef<TSelected>();\n\n return (state: TState): TSelected => {\n const next = selector(state);\n\n if (prev.current === undefined) {\n prev.current = next;\n return next;\n }\n\n // Shallow compare\n if (shallowCompareObjects(prev.current, next)) {\n return prev.current;\n }\n\n prev.current = next;\n return next;\n };\n}\n\n/**\n * Shallow compare two objects.\n */\nfunction shallowCompareObjects<T extends object>(a: T, b: T): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n if (a === null || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if ((a as any)[key] !== (b as any)[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Hook for selecting multiple actions from a store.\n *\n * Returns stable references to actions that don't change between renders.\n *\n * @param store - The store instance\n * @param actionNames - Names of actions to select\n * @returns An object with the selected actions\n *\n * @example\n * ```typescript\n * import { useStoreActions } from '@oxog/state';\n *\n * function Counter() {\n * const { increment, decrement, reset } = useStoreActions(\n * store,\n * 'increment',\n * 'decrement',\n * 'reset'\n * );\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <button onClick={increment}>+</button>\n * <button onClick={reset}>Reset</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useStoreActions<\n TState,\n TKeys extends string[]\n>(\n store: Store<TState>,\n ...actionNames: TKeys\n): { [K in TKeys[number]]: (...args: any[]) => any } {\n const storeRef = useRef(store);\n const actionsRef = useRef<Record<string, Function>>({});\n\n // Update store ref if it changes\n if (storeRef.current !== store) {\n storeRef.current = store;\n // Reset actions cache when store changes\n actionsRef.current = {};\n }\n\n // Get or cache actions\n const result: any = {};\n for (const name of actionNames) {\n if (!actionsRef.current[name]) {\n actionsRef.current[name] = (storeRef.current as any)[name];\n }\n result[name] = actionsRef.current[name];\n }\n\n return result;\n}\n\n/**\n * Hook for selecting multiple values with independent selectors.\n *\n * Each selector is tracked independently, so the component only\n * re-renders when a selector's output actually changes.\n *\n * @param store - The store instance\n * @param selectors - Object of named selectors\n * @returns An object with selected values\n *\n * @example\n * ```typescript\n * import { useStoreSelector } from '@oxog/state';\n *\n * function Dashboard() {\n * const { userCount, activeUsers, totalRevenue } = useStoreSelector(store, {\n * userCount: s => s.users.length,\n * activeUsers: s => s.users.filter(u => u.active).length,\n * totalRevenue: s => s.orders.reduce((sum, o) => sum + o.total, 0),\n * });\n *\n * return (\n * <div>\n * <p>Users: {userCount} ({activeUsers} active)</p>\n * <p>Revenue: ${totalRevenue}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useStoreSelector<\n TState,\n TSelectors extends Record<string, Selector<TState, any>>\n>(\n store: Store<TState>,\n selectors: TSelectors\n): { [K in keyof TSelectors]: ReturnType<TSelectors[K]> } {\n const prevResultRef = useRef<any>(null);\n\n // A new selectors object gives a new combined selector (so useStore\n // recomputes); the previous result is reused while every value is equal.\n const combinedSelector = useCallback((state: TState) => {\n const keys = Object.keys(selectors);\n const result: any = {};\n\n for (const key of keys) {\n const selector = selectors[key];\n if (selector) {\n result[key] = selector(state);\n }\n }\n\n // Check if result is equal to previous (shallow compare each key)\n const prev = prevResultRef.current;\n if (prev !== null && Object.keys(prev).length === keys.length) {\n let isEqual = true;\n for (const key of keys) {\n if (!(key in prev) || !shallowEqual(prev[key], result[key])) {\n isEqual = false;\n break;\n }\n }\n if (isEqual) {\n return prev;\n }\n }\n\n prevResultRef.current = result;\n return result;\n }, [selectors]);\n\n return useStore(store, combinedSelector);\n}\n\n/**\n * Hook for transient updates - subscribe without causing re-renders.\n *\n * Use this for side effects that don't need to update the UI.\n *\n * @param store - The store instance\n * @param selector - Selector function\n * @param callback - Callback to run on changes\n *\n * @example\n * ```typescript\n * import { useTransientSubscribe } from '@oxog/state';\n *\n * function Analytics() {\n * // Track page views without re-rendering\n * useTransientSubscribe(\n * store,\n * s => s.currentPage,\n * (page) => analytics.track('pageview', { page })\n * );\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useTransientSubscribe<TState, TSelected>(\n store: Store<TState>,\n selector: Selector<TState, TSelected>,\n callback: (value: TSelected, prevValue: TSelected) => void,\n equalityFn: EqualityFn<TSelected> = shallowEqual\n): void {\n const callbackRef = useRef(callback);\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n callbackRef.current = callback;\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Subscribe once per store; inline selectors/callbacks do not resubscribe.\n useEffect(() => {\n const unsubscribe = store.subscribe(\n (state: TState) => selectorRef.current(state),\n (value, prevValue) => callbackRef.current(value, prevValue),\n (a, b) => equalityFnRef.current(a, b)\n );\n\n return unsubscribe;\n }, [store]);\n}\n\n/**\n * Hook that returns the store's setState function with stable reference.\n *\n * @param store - The store instance\n * @returns The setState function\n *\n * @example\n * ```typescript\n * function Form() {\n * const setState = useSetState(store);\n *\n * const handleChange = (e) => {\n * setState({ [e.target.name]: e.target.value });\n * };\n *\n * return <input onChange={handleChange} />;\n * }\n * ```\n */\nexport function useSetState<TState>(\n store: Store<TState>\n): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void {\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n const setStateRef = useRef((partial: Partial<TState> | ((state: TState) => Partial<TState>)) => {\n storeRef.current.setState(partial);\n });\n\n return setStateRef.current;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/react.ts"],"names":["selector","identity","shallowEqual","useRef","useCallback","useSyncExternalStore","useDebugValue","createStore","useEffect"],"mappings":";;;;;AAqDO,SAAS,QAAA,CACd,KAAA,EACAA,SAAAA,GAAwCC,0BAAA,EACxC,aAAoCC,8BAAA,EACzB;AAEX,EAAA,MAAM,WAAA,GAAcC,aAAOH,SAAQ,CAAA;AACnC,EAAA,MAAM,aAAA,GAAgBG,aAAO,UAAU,CAAA;AACvC,EAAA,WAAA,CAAY,OAAA,GAAUH,SAAAA;AACtB,EAAA,aAAA,CAAc,OAAA,GAAU,UAAA;AAKxB,EAAA,MAAM,QAAA,GAAWG,aAKP,IAAI,CAA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Z;AAqBO,SAAS,YACd,KAAA,EAC2E;AAC3E,EAAA,MAAM,QAAA,GAAWL,aAAO,KAAK,CAAA;AAC7B,EAAA,IAAI,QAAA,CAAS,YAAY,KAAA,EAAO;AAC9B,IAAA,QAAA,CAAS,OAAA,GAAU,KAAA;AAAA,EACrB;AAEA,EAAA,MAAM,WAAA,GAAcA,YAAA,CAAO,CAAC,OAAA,KAAoE;AAC9F,IAAA,QAAA,CAAS,OAAA,CAAQ,SAAS,OAAO,CAAA;AAAA,EACnC,CAAC,CAAA;AAED,EAAA,OAAO,WAAA,CAAY,OAAA;AACrB","file":"index.cjs","sourcesContent":["import { useSyncExternalStore, useDebugValue, useEffect, useRef, useCallback } from 'react';\nimport type { EqualityFn, Selector, Store } from './types.js';\nimport { identity } from './utils/identity.js';\nimport { shallowEqual } from './utils/shallow-equal.js';\nimport { createStore as _createStore } from './store.js';\n\n/**\n * React hook for subscribing to store state changes.\n *\n * Uses useSyncExternalStore for optimal performance and SSR compatibility.\n *\n * @typeParam TState - The store state type\n * @typeParam TSelected - The selected state type\n * @param store - The store instance\n * @param selector - Optional selector to extract a slice of state\n * @param equalityFn - Optional custom equality function\n * @returns The selected state slice\n *\n * @example\n * ```typescript\n * import { createStore, useStore } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * name: 'John',\n * increment: (state) => ({ count: state.count + 1 }),\n * });\n *\n * function Counter() {\n * // Select entire state\n * const state = useStore(store);\n *\n * // Select with selector\n * const count = useStore(store, (state) => state.count);\n *\n * // Select with custom equality check\n * const user = useStore(\n * store,\n * (state) => state.user,\n * (a, b) => a?.id === b?.id\n * );\n *\n * // Select action\n * const increment = useStore(store, (state) => state.increment);\n *\n * return (\n * <button onClick={increment}>\n * Count: {count}\n * </button>\n * );\n * }\n * ```\n */\nexport function useStore<TState, TSelected = TState>(\n store: Store<TState>,\n selector: Selector<TState, TSelected> = identity as any,\n equalityFn: EqualityFn<TSelected> = shallowEqual\n): TSelected {\n // Latest selector / equality function (inline functions are fine).\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Last selection. getSnapshot must return the same reference while the\n // selection is unchanged, otherwise useSyncExternalStore re-renders forever\n // for selectors that build a new object/array.\n const cacheRef = useRef<{\n store: Store<TState>;\n state: TState;\n selector: Selector<TState, TSelected>;\n selected: TSelected;\n } | null>(null);\n\n const getSnapshot = useCallback((): TSelected => {\n const state = store.getState();\n const currentSelector = selectorRef.current;\n const cache = cacheRef.current;\n if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {\n return cache.selected;\n }\n const next = currentSelector(state);\n if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {\n cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };\n return cache.selected;\n }\n cacheRef.current = { store, state, selector: currentSelector, selected: next };\n return next;\n }, [store]);\n\n const subscribe = useCallback((callback: () => void) => store.subscribe(() => callback()), [store]);\n\n const selectedState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // Debug value for React DevTools\n useDebugValue(selectedState);\n\n return selectedState;\n}\n\n/**\n * React hook for creating and using a store.\n *\n * Creates a store on first render and destroys it after the component\n * unmounts. Safe under React StrictMode (the simulated unmount/remount in\n * development does not destroy the store).\n *\n * @typeParam TState - The store state type\n * @param initialState - The initial state\n * @returns The store instance\n *\n * @example\n * ```typescript\n * import { useCreateStore } from '@oxog/state';\n *\n * function Component() {\n * const store = useCreateStore({ count: 0 });\n * const count = useStore(store, (s) => s.count);\n *\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useCreateStore<TState>(initialState: TState): Store<TState> {\n const storeRef = useRef<Store<TState>>();\n const pendingDestroyRef = useRef<object | null>(null);\n\n if (storeRef.current === undefined) {\n storeRef.current = _createStore(initialState) as unknown as Store<TState>;\n }\n const store = storeRef.current;\n\n useEffect(() => {\n // (Re)mounted: cancel a destroy scheduled by a StrictMode cleanup.\n pendingDestroyRef.current = null;\n return () => {\n // Defer the destroy: StrictMode re-runs the effect synchronously after\n // this cleanup, which cancels it. A real unmount lets it run.\n const token = {};\n pendingDestroyRef.current = token;\n queueMicrotask(() => {\n if (pendingDestroyRef.current === token) {\n store.destroy();\n if (storeRef.current === store) {\n storeRef.current = undefined;\n }\n }\n });\n };\n }, [store]);\n\n return store;\n}\n\n/**\n * React hook for getting a store action.\n *\n * Convenience hook for selecting action functions from a store.\n *\n * @typeParam TState - The store state type\n * @typeParam TAction - The action type\n * @param store - The store instance\n * @param actionName - The name of the action\n * @returns The action function\n *\n * @example\n * ```typescript\n * import { createStore, useAction } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * increment: (state) => ({ count: state.count + 1 }),\n * decrement: (state) => ({ count: state.count - 1 }),\n * });\n *\n * function Counter() {\n * const increment = useAction(store, 'increment');\n * const decrement = useAction(store, 'decrement');\n * const count = useStore(store, (s) => s.count);\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <span>{count}</span>\n * <button onClick={increment}>+</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useAction<TState, TAction extends (...args: any[]) => any>(\n store: Store<TState>,\n actionName: string\n): TAction {\n // Actions are methods on the store instance, not properties of state\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n // Get the action from the store instance\n const action = (storeRef.current as any)[actionName];\n\n // Return a stable reference to the action\n const actionRef = useRef(action);\n if (actionRef.current !== action) {\n actionRef.current = action;\n }\n\n return actionRef.current as TAction;\n}\n\n/**\n * Create a shallow equality wrapper for selectors.\n *\n * Use this hook to wrap selectors that return objects or arrays\n * and you want to avoid re-renders when the content hasn't changed.\n *\n * @param selector - The selector function to wrap\n * @returns A wrapped selector with shallow equality\n *\n * @example\n * ```typescript\n * import { useStore, useShallow } from '@oxog/state';\n *\n * function UserInfo() {\n * // Without useShallow - re-renders on every state change\n * const { name, email } = useStore(store, s => ({ name: s.name, email: s.email }));\n *\n * // With useShallow - only re-renders when name or email actually changes\n * const { name, email } = useStore(\n * store,\n * useShallow(s => ({ name: s.name, email: s.email }))\n * );\n * }\n * ```\n */\nexport function useShallow<TState, TSelected extends object>(\n selector: Selector<TState, TSelected>\n): Selector<TState, TSelected> {\n const prev = useRef<TSelected>();\n\n return (state: TState): TSelected => {\n const next = selector(state);\n\n if (prev.current === undefined) {\n prev.current = next;\n return next;\n }\n\n // Shallow compare\n if (shallowCompareObjects(prev.current, next)) {\n return prev.current;\n }\n\n prev.current = next;\n return next;\n };\n}\n\n/**\n * Shallow compare two objects.\n */\nfunction shallowCompareObjects<T extends object>(a: T, b: T): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n if (a === null || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if ((a as any)[key] !== (b as any)[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Hook for selecting multiple actions from a store.\n *\n * Returns stable references to actions that don't change between renders.\n *\n * @param store - The store instance\n * @param actionNames - Names of actions to select\n * @returns An object with the selected actions\n *\n * @example\n * ```typescript\n * import { useStoreActions } from '@oxog/state';\n *\n * function Counter() {\n * const { increment, decrement, reset } = useStoreActions(\n * store,\n * 'increment',\n * 'decrement',\n * 'reset'\n * );\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <button onClick={increment}>+</button>\n * <button onClick={reset}>Reset</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useStoreActions<\n TState,\n TKeys extends string[]\n>(\n store: Store<TState>,\n ...actionNames: TKeys\n): { [K in TKeys[number]]: (...args: any[]) => any } {\n const storeRef = useRef(store);\n const actionsRef = useRef<Record<string, Function>>({});\n\n // Update store ref if it changes\n if (storeRef.current !== store) {\n storeRef.current = store;\n // Reset actions cache when store changes\n actionsRef.current = {};\n }\n\n // Get or cache actions\n const result: any = {};\n for (const name of actionNames) {\n if (!actionsRef.current[name]) {\n actionsRef.current[name] = (storeRef.current as any)[name];\n }\n result[name] = actionsRef.current[name];\n }\n\n return result;\n}\n\n/**\n * Hook for selecting multiple values with independent selectors.\n *\n * Each selector is tracked independently, so the component only\n * re-renders when a selector's output actually changes.\n *\n * @param store - The store instance\n * @param selectors - Object of named selectors\n * @returns An object with selected values\n *\n * @example\n * ```typescript\n * import { useStoreSelector } from '@oxog/state';\n *\n * function Dashboard() {\n * const { userCount, activeUsers, totalRevenue } = useStoreSelector(store, {\n * userCount: s => s.users.length,\n * activeUsers: s => s.users.filter(u => u.active).length,\n * totalRevenue: s => s.orders.reduce((sum, o) => sum + o.total, 0),\n * });\n *\n * return (\n * <div>\n * <p>Users: {userCount} ({activeUsers} active)</p>\n * <p>Revenue: ${totalRevenue}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useStoreSelector<\n TState,\n TSelectors extends Record<string, Selector<TState, any>>\n>(\n store: Store<TState>,\n selectors: TSelectors\n): { [K in keyof TSelectors]: ReturnType<TSelectors[K]> } {\n const prevResultRef = useRef<any>(null);\n\n // A new selectors object gives a new combined selector (so useStore\n // recomputes); the previous result is reused while every value is equal.\n const combinedSelector = useCallback((state: TState) => {\n const keys = Object.keys(selectors);\n const result: any = {};\n\n for (const key of keys) {\n const selector = selectors[key];\n if (selector) {\n result[key] = selector(state);\n }\n }\n\n // Check if result is equal to previous (shallow compare each key)\n const prev = prevResultRef.current;\n if (prev !== null && Object.keys(prev).length === keys.length) {\n let isEqual = true;\n for (const key of keys) {\n if (!(key in prev) || !shallowEqual(prev[key], result[key])) {\n isEqual = false;\n break;\n }\n }\n if (isEqual) {\n return prev;\n }\n }\n\n prevResultRef.current = result;\n return result;\n }, [selectors]);\n\n return useStore(store, combinedSelector);\n}\n\n/**\n * Hook for transient updates - subscribe without causing re-renders.\n *\n * Use this for side effects that don't need to update the UI.\n *\n * @param store - The store instance\n * @param selector - Selector function\n * @param callback - Callback to run on changes\n *\n * @example\n * ```typescript\n * import { useTransientSubscribe } from '@oxog/state';\n *\n * function Analytics() {\n * // Track page views without re-rendering\n * useTransientSubscribe(\n * store,\n * s => s.currentPage,\n * (page) => analytics.track('pageview', { page })\n * );\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useTransientSubscribe<TState, TSelected>(\n store: Store<TState>,\n selector: Selector<TState, TSelected>,\n callback: (value: TSelected, prevValue: TSelected) => void,\n equalityFn: EqualityFn<TSelected> = shallowEqual\n): void {\n const callbackRef = useRef(callback);\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n callbackRef.current = callback;\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Subscribe once per store; inline selectors/callbacks do not resubscribe.\n useEffect(() => {\n const unsubscribe = store.subscribe(\n (state: TState) => selectorRef.current(state),\n (value, prevValue) => callbackRef.current(value, prevValue),\n (a, b) => equalityFnRef.current(a, b)\n );\n\n return unsubscribe;\n }, [store]);\n}\n\n/**\n * Hook that returns the store's setState function with stable reference.\n *\n * @param store - The store instance\n * @returns The setState function\n *\n * @example\n * ```typescript\n * function Form() {\n * const setState = useSetState(store);\n *\n * const handleChange = (e) => {\n * setState({ [e.target.name]: e.target.value });\n * };\n *\n * return <input onChange={handleChange} />;\n * }\n * ```\n */\nexport function useSetState<TState>(\n store: Store<TState>\n): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void {\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n const setStateRef = useRef((partial: Partial<TState> | ((state: TState) => Partial<TState>)) => {\n storeRef.current.setState(partial);\n });\n\n return setStateRef.current;\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { identity, shallowEqual, createStore } from './chunk-
|
|
2
|
-
export { StoreError, StoreErrorCode, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, validate, waitForFederated } from './chunk-
|
|
1
|
+
import { identity, shallowEqual, createStore } from './chunk-2QNZBQ4V.js';
|
|
2
|
+
export { StoreError, StoreErrorCode, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, validate, waitForFederated } from './chunk-2QNZBQ4V.js';
|
|
3
3
|
import { useRef, useCallback, useSyncExternalStore, useDebugValue, useEffect } from 'react';
|
|
4
4
|
|
|
5
5
|
function useStore(store, selector2 = identity, equalityFn = shallowEqual) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react.ts"],"names":["selector"],"mappings":";;;;AAqDO,SAAS,QAAA,CACd,KAAA,EACAA,SAAAA,GAAwC,QAAA,EACxC,aAAoC,YAAA,EACzB;AAEX,EAAA,MAAM,WAAA,GAAc,OAAOA,SAAQ,CAAA;AACnC,EAAA,MAAM,aAAA,GAA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AA,CAAc,OAAA,CAAQ,GAAG,CAAC;AAAA,KACtC;AAEA,IAAA,OAAO,WAAA;AAAA,EACT,CAAA,EAAG,CAAC,KAAK,CAAC,CAAA;AACZ;AAqBO,SAAS,YACd,KAAA,EAC2E;AAC3E,EAAA,MAAM,QAAA,GAAW,OAAO,KAAK,CAAA;AAC7B,EAAA,IAAI,QAAA,CAAS,YAAY,KAAA,EAAO;AAC9B,IAAA,QAAA,CAAS,OAAA,GAAU,KAAA;AAAA,EACrB;AAEA,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,CAAC,OAAA,KAAoE;AAC9F,IAAA,QAAA,CAAS,OAAA,CAAQ,SAAS,OAAO,CAAA;AAAA,EACnC,CAAC,CAAA;AAED,EAAA,OAAO,WAAA,CAAY,OAAA;AACrB","file":"index.js","sourcesContent":["import { useSyncExternalStore, useDebugValue, useEffect, useRef, useCallback } from 'react';\nimport type { EqualityFn, Selector, Store } from './types.js';\nimport { identity } from './utils/identity.js';\nimport { shallowEqual } from './utils/shallow-equal.js';\nimport { createStore as _createStore } from './store.js';\n\n/**\n * React hook for subscribing to store state changes.\n *\n * Uses useSyncExternalStore for optimal performance and SSR compatibility.\n *\n * @typeParam TState - The store state type\n * @typeParam TSelected - The selected state type\n * @param store - The store instance\n * @param selector - Optional selector to extract a slice of state\n * @param equalityFn - Optional custom equality function\n * @returns The selected state slice\n *\n * @example\n * ```typescript\n * import { createStore, useStore } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * name: 'John',\n * increment: (state) => ({ count: state.count + 1 }),\n * });\n *\n * function Counter() {\n * // Select entire state\n * const state = useStore(store);\n *\n * // Select with selector\n * const count = useStore(store, (state) => state.count);\n *\n * // Select with custom equality check\n * const user = useStore(\n * store,\n * (state) => state.user,\n * (a, b) => a?.id === b?.id\n * );\n *\n * // Select action\n * const increment = useStore(store, (state) => state.increment);\n *\n * return (\n * <button onClick={increment}>\n * Count: {count}\n * </button>\n * );\n * }\n * ```\n */\nexport function useStore<TState, TSelected = TState>(\n store: Store<TState>,\n selector: Selector<TState, TSelected> = identity as any,\n equalityFn: EqualityFn<TSelected> = shallowEqual as any\n): TSelected {\n // Latest selector / equality function (inline functions are fine).\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Last selection. getSnapshot must return the same reference while the\n // selection is unchanged, otherwise useSyncExternalStore re-renders forever\n // for selectors that build a new object/array.\n const cacheRef = useRef<{\n store: Store<TState>;\n state: TState;\n selector: Selector<TState, TSelected>;\n selected: TSelected;\n } | null>(null);\n\n const getSnapshot = useCallback((): TSelected => {\n const state = store.getState();\n const currentSelector = selectorRef.current;\n const cache = cacheRef.current;\n if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {\n return cache.selected;\n }\n const next = currentSelector(state);\n if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {\n cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };\n return cache.selected;\n }\n cacheRef.current = { store, state, selector: currentSelector, selected: next };\n return next;\n }, [store]);\n\n const subscribe = useCallback((callback: () => void) => store.subscribe(() => callback()), [store]);\n\n const selectedState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // Debug value for React DevTools\n useDebugValue(selectedState);\n\n return selectedState;\n}\n\n/**\n * React hook for creating and using a store.\n *\n * Creates a store on first render and destroys it after the component\n * unmounts. Safe under React StrictMode (the simulated unmount/remount in\n * development does not destroy the store).\n *\n * @typeParam TState - The store state type\n * @param initialState - The initial state\n * @returns The store instance\n *\n * @example\n * ```typescript\n * import { useCreateStore } from '@oxog/state';\n *\n * function Component() {\n * const store = useCreateStore({ count: 0 });\n * const count = useStore(store, (s) => s.count);\n *\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useCreateStore<TState>(initialState: TState): Store<TState> {\n const storeRef = useRef<Store<TState>>();\n const pendingDestroyRef = useRef<object | null>(null);\n\n if (storeRef.current === undefined) {\n storeRef.current = _createStore(initialState) as unknown as Store<TState>;\n }\n const store = storeRef.current;\n\n useEffect(() => {\n // (Re)mounted: cancel a destroy scheduled by a StrictMode cleanup.\n pendingDestroyRef.current = null;\n return () => {\n // Defer the destroy: StrictMode re-runs the effect synchronously after\n // this cleanup, which cancels it. A real unmount lets it run.\n const token = {};\n pendingDestroyRef.current = token;\n queueMicrotask(() => {\n if (pendingDestroyRef.current === token) {\n store.destroy();\n if (storeRef.current === store) {\n storeRef.current = undefined;\n }\n }\n });\n };\n }, [store]);\n\n return store;\n}\n\n/**\n * React hook for getting a store action.\n *\n * Convenience hook for selecting action functions from a store.\n *\n * @typeParam TState - The store state type\n * @typeParam TAction - The action type\n * @param store - The store instance\n * @param actionName - The name of the action\n * @returns The action function\n *\n * @example\n * ```typescript\n * import { createStore, useAction } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * increment: (state) => ({ count: state.count + 1 }),\n * decrement: (state) => ({ count: state.count - 1 }),\n * });\n *\n * function Counter() {\n * const increment = useAction(store, 'increment');\n * const decrement = useAction(store, 'decrement');\n * const count = useStore(store, (s) => s.count);\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <span>{count}</span>\n * <button onClick={increment}>+</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useAction<TState, TAction extends (...args: any[]) => any>(\n store: Store<TState>,\n actionName: string\n): TAction {\n // Actions are methods on the store instance, not properties of state\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n // Get the action from the store instance\n const action = (storeRef.current as any)[actionName];\n\n // Return a stable reference to the action\n const actionRef = useRef(action);\n if (actionRef.current !== action) {\n actionRef.current = action;\n }\n\n return actionRef.current as TAction;\n}\n\n/**\n * Create a shallow equality wrapper for selectors.\n *\n * Use this hook to wrap selectors that return objects or arrays\n * and you want to avoid re-renders when the content hasn't changed.\n *\n * @param selector - The selector function to wrap\n * @returns A wrapped selector with shallow equality\n *\n * @example\n * ```typescript\n * import { useStore, useShallow } from '@oxog/state';\n *\n * function UserInfo() {\n * // Without useShallow - re-renders on every state change\n * const { name, email } = useStore(store, s => ({ name: s.name, email: s.email }));\n *\n * // With useShallow - only re-renders when name or email actually changes\n * const { name, email } = useStore(\n * store,\n * useShallow(s => ({ name: s.name, email: s.email }))\n * );\n * }\n * ```\n */\nexport function useShallow<TState, TSelected extends object>(\n selector: Selector<TState, TSelected>\n): Selector<TState, TSelected> {\n const prev = useRef<TSelected>();\n\n return (state: TState): TSelected => {\n const next = selector(state);\n\n if (prev.current === undefined) {\n prev.current = next;\n return next;\n }\n\n // Shallow compare\n if (shallowCompareObjects(prev.current, next)) {\n return prev.current;\n }\n\n prev.current = next;\n return next;\n };\n}\n\n/**\n * Shallow compare two objects.\n */\nfunction shallowCompareObjects<T extends object>(a: T, b: T): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n if (a === null || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if ((a as any)[key] !== (b as any)[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Hook for selecting multiple actions from a store.\n *\n * Returns stable references to actions that don't change between renders.\n *\n * @param store - The store instance\n * @param actionNames - Names of actions to select\n * @returns An object with the selected actions\n *\n * @example\n * ```typescript\n * import { useStoreActions } from '@oxog/state';\n *\n * function Counter() {\n * const { increment, decrement, reset } = useStoreActions(\n * store,\n * 'increment',\n * 'decrement',\n * 'reset'\n * );\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <button onClick={increment}>+</button>\n * <button onClick={reset}>Reset</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useStoreActions<\n TState,\n TKeys extends string[]\n>(\n store: Store<TState>,\n ...actionNames: TKeys\n): { [K in TKeys[number]]: (...args: any[]) => any } {\n const storeRef = useRef(store);\n const actionsRef = useRef<Record<string, Function>>({});\n\n // Update store ref if it changes\n if (storeRef.current !== store) {\n storeRef.current = store;\n // Reset actions cache when store changes\n actionsRef.current = {};\n }\n\n // Get or cache actions\n const result: any = {};\n for (const name of actionNames) {\n if (!actionsRef.current[name]) {\n actionsRef.current[name] = (storeRef.current as any)[name];\n }\n result[name] = actionsRef.current[name];\n }\n\n return result;\n}\n\n/**\n * Hook for selecting multiple values with independent selectors.\n *\n * Each selector is tracked independently, so the component only\n * re-renders when a selector's output actually changes.\n *\n * @param store - The store instance\n * @param selectors - Object of named selectors\n * @returns An object with selected values\n *\n * @example\n * ```typescript\n * import { useStoreSelector } from '@oxog/state';\n *\n * function Dashboard() {\n * const { userCount, activeUsers, totalRevenue } = useStoreSelector(store, {\n * userCount: s => s.users.length,\n * activeUsers: s => s.users.filter(u => u.active).length,\n * totalRevenue: s => s.orders.reduce((sum, o) => sum + o.total, 0),\n * });\n *\n * return (\n * <div>\n * <p>Users: {userCount} ({activeUsers} active)</p>\n * <p>Revenue: ${totalRevenue}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useStoreSelector<\n TState,\n TSelectors extends Record<string, Selector<TState, any>>\n>(\n store: Store<TState>,\n selectors: TSelectors\n): { [K in keyof TSelectors]: ReturnType<TSelectors[K]> } {\n const prevResultRef = useRef<any>(null);\n\n // A new selectors object gives a new combined selector (so useStore\n // recomputes); the previous result is reused while every value is equal.\n const combinedSelector = useCallback((state: TState) => {\n const keys = Object.keys(selectors);\n const result: any = {};\n\n for (const key of keys) {\n const selector = selectors[key];\n if (selector) {\n result[key] = selector(state);\n }\n }\n\n // Check if result is equal to previous (shallow compare each key)\n const prev = prevResultRef.current;\n if (prev !== null && Object.keys(prev).length === keys.length) {\n let isEqual = true;\n for (const key of keys) {\n if (!(key in prev) || !shallowEqual(prev[key], result[key])) {\n isEqual = false;\n break;\n }\n }\n if (isEqual) {\n return prev;\n }\n }\n\n prevResultRef.current = result;\n return result;\n }, [selectors]);\n\n return useStore(store, combinedSelector);\n}\n\n/**\n * Hook for transient updates - subscribe without causing re-renders.\n *\n * Use this for side effects that don't need to update the UI.\n *\n * @param store - The store instance\n * @param selector - Selector function\n * @param callback - Callback to run on changes\n *\n * @example\n * ```typescript\n * import { useTransientSubscribe } from '@oxog/state';\n *\n * function Analytics() {\n * // Track page views without re-rendering\n * useTransientSubscribe(\n * store,\n * s => s.currentPage,\n * (page) => analytics.track('pageview', { page })\n * );\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useTransientSubscribe<TState, TSelected>(\n store: Store<TState>,\n selector: Selector<TState, TSelected>,\n callback: (value: TSelected, prevValue: TSelected) => void,\n equalityFn: EqualityFn<TSelected> = shallowEqual\n): void {\n const callbackRef = useRef(callback);\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n callbackRef.current = callback;\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Subscribe once per store; inline selectors/callbacks do not resubscribe.\n useEffect(() => {\n const unsubscribe = store.subscribe(\n (state: TState) => selectorRef.current(state),\n (value, prevValue) => callbackRef.current(value, prevValue),\n (a, b) => equalityFnRef.current(a, b)\n );\n\n return unsubscribe;\n }, [store]);\n}\n\n/**\n * Hook that returns the store's setState function with stable reference.\n *\n * @param store - The store instance\n * @returns The setState function\n *\n * @example\n * ```typescript\n * function Form() {\n * const setState = useSetState(store);\n *\n * const handleChange = (e) => {\n * setState({ [e.target.name]: e.target.value });\n * };\n *\n * return <input onChange={handleChange} />;\n * }\n * ```\n */\nexport function useSetState<TState>(\n store: Store<TState>\n): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void {\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n const setStateRef = useRef((partial: Partial<TState> | ((state: TState) => Partial<TState>)) => {\n storeRef.current.setState(partial);\n });\n\n return setStateRef.current;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/react.ts"],"names":["selector"],"mappings":";;;;AAqDO,SAAS,QAAA,CACd,KAAA,EACAA,SAAAA,GAAwC,QAAA,EACxC,aAAoC,YAAA,EACzB;AAEX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A,CAAQ,OAAO,SAAS,CAAA;AAAA,MAC1D,CAAC,CAAA,EAAG,CAAA,KAAM,aAAA,CAAc,OAAA,CAAQ,GAAG,CAAC;AAAA,KACtC;AAEA,IAAA,OAAO,WAAA;AAAA,EACT,CAAA,EAAG,CAAC,KAAK,CAAC,CAAA;AACZ;AAqBO,SAAS,YACd,KAAA,EAC2E;AAC3E,EAAA,MAAM,QAAA,GAAW,OAAO,KAAK,CAAA;AAC7B,EAAA,IAAI,QAAA,CAAS,YAAY,KAAA,EAAO;AAC9B,IAAA,QAAA,CAAS,OAAA,GAAU,KAAA;AAAA,EACrB;AAEA,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,CAAC,OAAA,KAAoE;AAC9F,IAAA,QAAA,CAAS,OAAA,CAAQ,SAAS,OAAO,CAAA;AAAA,EACnC,CAAC,CAAA;AAED,EAAA,OAAO,WAAA,CAAY,OAAA;AACrB","file":"index.js","sourcesContent":["import { useSyncExternalStore, useDebugValue, useEffect, useRef, useCallback } from 'react';\nimport type { EqualityFn, Selector, Store } from './types.js';\nimport { identity } from './utils/identity.js';\nimport { shallowEqual } from './utils/shallow-equal.js';\nimport { createStore as _createStore } from './store.js';\n\n/**\n * React hook for subscribing to store state changes.\n *\n * Uses useSyncExternalStore for optimal performance and SSR compatibility.\n *\n * @typeParam TState - The store state type\n * @typeParam TSelected - The selected state type\n * @param store - The store instance\n * @param selector - Optional selector to extract a slice of state\n * @param equalityFn - Optional custom equality function\n * @returns The selected state slice\n *\n * @example\n * ```typescript\n * import { createStore, useStore } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * name: 'John',\n * increment: (state) => ({ count: state.count + 1 }),\n * });\n *\n * function Counter() {\n * // Select entire state\n * const state = useStore(store);\n *\n * // Select with selector\n * const count = useStore(store, (state) => state.count);\n *\n * // Select with custom equality check\n * const user = useStore(\n * store,\n * (state) => state.user,\n * (a, b) => a?.id === b?.id\n * );\n *\n * // Select action\n * const increment = useStore(store, (state) => state.increment);\n *\n * return (\n * <button onClick={increment}>\n * Count: {count}\n * </button>\n * );\n * }\n * ```\n */\nexport function useStore<TState, TSelected = TState>(\n store: Store<TState>,\n selector: Selector<TState, TSelected> = identity as any,\n equalityFn: EqualityFn<TSelected> = shallowEqual\n): TSelected {\n // Latest selector / equality function (inline functions are fine).\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Last selection. getSnapshot must return the same reference while the\n // selection is unchanged, otherwise useSyncExternalStore re-renders forever\n // for selectors that build a new object/array.\n const cacheRef = useRef<{\n store: Store<TState>;\n state: TState;\n selector: Selector<TState, TSelected>;\n selected: TSelected;\n } | null>(null);\n\n const getSnapshot = useCallback((): TSelected => {\n const state = store.getState();\n const currentSelector = selectorRef.current;\n const cache = cacheRef.current;\n if (cache && cache.store === store && cache.state === state && cache.selector === currentSelector) {\n return cache.selected;\n }\n const next = currentSelector(state);\n if (cache && cache.store === store && equalityFnRef.current(cache.selected, next)) {\n cacheRef.current = { store, state, selector: currentSelector, selected: cache.selected };\n return cache.selected;\n }\n cacheRef.current = { store, state, selector: currentSelector, selected: next };\n return next;\n }, [store]);\n\n const subscribe = useCallback((callback: () => void) => store.subscribe(() => callback()), [store]);\n\n const selectedState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n // Debug value for React DevTools\n useDebugValue(selectedState);\n\n return selectedState;\n}\n\n/**\n * React hook for creating and using a store.\n *\n * Creates a store on first render and destroys it after the component\n * unmounts. Safe under React StrictMode (the simulated unmount/remount in\n * development does not destroy the store).\n *\n * @typeParam TState - The store state type\n * @param initialState - The initial state\n * @returns The store instance\n *\n * @example\n * ```typescript\n * import { useCreateStore } from '@oxog/state';\n *\n * function Component() {\n * const store = useCreateStore({ count: 0 });\n * const count = useStore(store, (s) => s.count);\n *\n * return <div>{count}</div>;\n * }\n * ```\n */\nexport function useCreateStore<TState>(initialState: TState): Store<TState> {\n const storeRef = useRef<Store<TState>>();\n const pendingDestroyRef = useRef<object | null>(null);\n\n if (storeRef.current === undefined) {\n storeRef.current = _createStore(initialState) as unknown as Store<TState>;\n }\n const store = storeRef.current;\n\n useEffect(() => {\n // (Re)mounted: cancel a destroy scheduled by a StrictMode cleanup.\n pendingDestroyRef.current = null;\n return () => {\n // Defer the destroy: StrictMode re-runs the effect synchronously after\n // this cleanup, which cancels it. A real unmount lets it run.\n const token = {};\n pendingDestroyRef.current = token;\n queueMicrotask(() => {\n if (pendingDestroyRef.current === token) {\n store.destroy();\n if (storeRef.current === store) {\n storeRef.current = undefined;\n }\n }\n });\n };\n }, [store]);\n\n return store;\n}\n\n/**\n * React hook for getting a store action.\n *\n * Convenience hook for selecting action functions from a store.\n *\n * @typeParam TState - The store state type\n * @typeParam TAction - The action type\n * @param store - The store instance\n * @param actionName - The name of the action\n * @returns The action function\n *\n * @example\n * ```typescript\n * import { createStore, useAction } from '@oxog/state';\n *\n * const store = createStore({\n * count: 0,\n * increment: (state) => ({ count: state.count + 1 }),\n * decrement: (state) => ({ count: state.count - 1 }),\n * });\n *\n * function Counter() {\n * const increment = useAction(store, 'increment');\n * const decrement = useAction(store, 'decrement');\n * const count = useStore(store, (s) => s.count);\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <span>{count}</span>\n * <button onClick={increment}>+</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useAction<TState, TAction extends (...args: any[]) => any>(\n store: Store<TState>,\n actionName: string\n): TAction {\n // Actions are methods on the store instance, not properties of state\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n // Get the action from the store instance\n const action = (storeRef.current as any)[actionName];\n\n // Return a stable reference to the action\n const actionRef = useRef(action);\n if (actionRef.current !== action) {\n actionRef.current = action;\n }\n\n return actionRef.current as TAction;\n}\n\n/**\n * Create a shallow equality wrapper for selectors.\n *\n * Use this hook to wrap selectors that return objects or arrays\n * and you want to avoid re-renders when the content hasn't changed.\n *\n * @param selector - The selector function to wrap\n * @returns A wrapped selector with shallow equality\n *\n * @example\n * ```typescript\n * import { useStore, useShallow } from '@oxog/state';\n *\n * function UserInfo() {\n * // Without useShallow - re-renders on every state change\n * const { name, email } = useStore(store, s => ({ name: s.name, email: s.email }));\n *\n * // With useShallow - only re-renders when name or email actually changes\n * const { name, email } = useStore(\n * store,\n * useShallow(s => ({ name: s.name, email: s.email }))\n * );\n * }\n * ```\n */\nexport function useShallow<TState, TSelected extends object>(\n selector: Selector<TState, TSelected>\n): Selector<TState, TSelected> {\n const prev = useRef<TSelected>();\n\n return (state: TState): TSelected => {\n const next = selector(state);\n\n if (prev.current === undefined) {\n prev.current = next;\n return next;\n }\n\n // Shallow compare\n if (shallowCompareObjects(prev.current, next)) {\n return prev.current;\n }\n\n prev.current = next;\n return next;\n };\n}\n\n/**\n * Shallow compare two objects.\n */\nfunction shallowCompareObjects<T extends object>(a: T, b: T): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n if (a === null || b === null) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if ((a as any)[key] !== (b as any)[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Hook for selecting multiple actions from a store.\n *\n * Returns stable references to actions that don't change between renders.\n *\n * @param store - The store instance\n * @param actionNames - Names of actions to select\n * @returns An object with the selected actions\n *\n * @example\n * ```typescript\n * import { useStoreActions } from '@oxog/state';\n *\n * function Counter() {\n * const { increment, decrement, reset } = useStoreActions(\n * store,\n * 'increment',\n * 'decrement',\n * 'reset'\n * );\n *\n * return (\n * <>\n * <button onClick={decrement}>-</button>\n * <button onClick={increment}>+</button>\n * <button onClick={reset}>Reset</button>\n * </>\n * );\n * }\n * ```\n */\nexport function useStoreActions<\n TState,\n TKeys extends string[]\n>(\n store: Store<TState>,\n ...actionNames: TKeys\n): { [K in TKeys[number]]: (...args: any[]) => any } {\n const storeRef = useRef(store);\n const actionsRef = useRef<Record<string, Function>>({});\n\n // Update store ref if it changes\n if (storeRef.current !== store) {\n storeRef.current = store;\n // Reset actions cache when store changes\n actionsRef.current = {};\n }\n\n // Get or cache actions\n const result: any = {};\n for (const name of actionNames) {\n if (!actionsRef.current[name]) {\n actionsRef.current[name] = (storeRef.current as any)[name];\n }\n result[name] = actionsRef.current[name];\n }\n\n return result;\n}\n\n/**\n * Hook for selecting multiple values with independent selectors.\n *\n * Each selector is tracked independently, so the component only\n * re-renders when a selector's output actually changes.\n *\n * @param store - The store instance\n * @param selectors - Object of named selectors\n * @returns An object with selected values\n *\n * @example\n * ```typescript\n * import { useStoreSelector } from '@oxog/state';\n *\n * function Dashboard() {\n * const { userCount, activeUsers, totalRevenue } = useStoreSelector(store, {\n * userCount: s => s.users.length,\n * activeUsers: s => s.users.filter(u => u.active).length,\n * totalRevenue: s => s.orders.reduce((sum, o) => sum + o.total, 0),\n * });\n *\n * return (\n * <div>\n * <p>Users: {userCount} ({activeUsers} active)</p>\n * <p>Revenue: ${totalRevenue}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useStoreSelector<\n TState,\n TSelectors extends Record<string, Selector<TState, any>>\n>(\n store: Store<TState>,\n selectors: TSelectors\n): { [K in keyof TSelectors]: ReturnType<TSelectors[K]> } {\n const prevResultRef = useRef<any>(null);\n\n // A new selectors object gives a new combined selector (so useStore\n // recomputes); the previous result is reused while every value is equal.\n const combinedSelector = useCallback((state: TState) => {\n const keys = Object.keys(selectors);\n const result: any = {};\n\n for (const key of keys) {\n const selector = selectors[key];\n if (selector) {\n result[key] = selector(state);\n }\n }\n\n // Check if result is equal to previous (shallow compare each key)\n const prev = prevResultRef.current;\n if (prev !== null && Object.keys(prev).length === keys.length) {\n let isEqual = true;\n for (const key of keys) {\n if (!(key in prev) || !shallowEqual(prev[key], result[key])) {\n isEqual = false;\n break;\n }\n }\n if (isEqual) {\n return prev;\n }\n }\n\n prevResultRef.current = result;\n return result;\n }, [selectors]);\n\n return useStore(store, combinedSelector);\n}\n\n/**\n * Hook for transient updates - subscribe without causing re-renders.\n *\n * Use this for side effects that don't need to update the UI.\n *\n * @param store - The store instance\n * @param selector - Selector function\n * @param callback - Callback to run on changes\n *\n * @example\n * ```typescript\n * import { useTransientSubscribe } from '@oxog/state';\n *\n * function Analytics() {\n * // Track page views without re-rendering\n * useTransientSubscribe(\n * store,\n * s => s.currentPage,\n * (page) => analytics.track('pageview', { page })\n * );\n *\n * return <div>...</div>;\n * }\n * ```\n */\nexport function useTransientSubscribe<TState, TSelected>(\n store: Store<TState>,\n selector: Selector<TState, TSelected>,\n callback: (value: TSelected, prevValue: TSelected) => void,\n equalityFn: EqualityFn<TSelected> = shallowEqual\n): void {\n const callbackRef = useRef(callback);\n const selectorRef = useRef(selector);\n const equalityFnRef = useRef(equalityFn);\n callbackRef.current = callback;\n selectorRef.current = selector;\n equalityFnRef.current = equalityFn;\n\n // Subscribe once per store; inline selectors/callbacks do not resubscribe.\n useEffect(() => {\n const unsubscribe = store.subscribe(\n (state: TState) => selectorRef.current(state),\n (value, prevValue) => callbackRef.current(value, prevValue),\n (a, b) => equalityFnRef.current(a, b)\n );\n\n return unsubscribe;\n }, [store]);\n}\n\n/**\n * Hook that returns the store's setState function with stable reference.\n *\n * @param store - The store instance\n * @returns The setState function\n *\n * @example\n * ```typescript\n * function Form() {\n * const setState = useSetState(store);\n *\n * const handleChange = (e) => {\n * setState({ [e.target.name]: e.target.value });\n * };\n *\n * return <input onChange={handleChange} />;\n * }\n * ```\n */\nexport function useSetState<TState>(\n store: Store<TState>\n): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void {\n const storeRef = useRef(store);\n if (storeRef.current !== store) {\n storeRef.current = store;\n }\n\n const setStateRef = useRef((partial: Partial<TState> | ((state: TState) => Partial<TState>)) => {\n storeRef.current.setState(partial);\n });\n\n return setStateRef.current;\n}\n"]}
|
package/dist/vanilla.cjs
CHANGED
|
@@ -1,268 +1,268 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkV6ASKKTH_cjs = require('./chunk-V6ASKKTH.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
Object.defineProperty(exports, "StoreError", {
|
|
8
8
|
enumerable: true,
|
|
9
|
-
get: function () { return
|
|
9
|
+
get: function () { return chunkV6ASKKTH_cjs.StoreError; }
|
|
10
10
|
});
|
|
11
11
|
Object.defineProperty(exports, "StoreErrorCode", {
|
|
12
12
|
enumerable: true,
|
|
13
|
-
get: function () { return
|
|
13
|
+
get: function () { return chunkV6ASKKTH_cjs.StoreErrorCode; }
|
|
14
14
|
});
|
|
15
15
|
Object.defineProperty(exports, "assertState", {
|
|
16
16
|
enumerable: true,
|
|
17
|
-
get: function () { return
|
|
17
|
+
get: function () { return chunkV6ASKKTH_cjs.assertState; }
|
|
18
18
|
});
|
|
19
19
|
Object.defineProperty(exports, "batch", {
|
|
20
20
|
enumerable: true,
|
|
21
|
-
get: function () { return
|
|
21
|
+
get: function () { return chunkV6ASKKTH_cjs.batch; }
|
|
22
22
|
});
|
|
23
23
|
Object.defineProperty(exports, "combineComputed", {
|
|
24
24
|
enumerable: true,
|
|
25
|
-
get: function () { return
|
|
25
|
+
get: function () { return chunkV6ASKKTH_cjs.combineComputed; }
|
|
26
26
|
});
|
|
27
27
|
Object.defineProperty(exports, "combineEffects", {
|
|
28
28
|
enumerable: true,
|
|
29
|
-
get: function () { return
|
|
29
|
+
get: function () { return chunkV6ASKKTH_cjs.combineEffects; }
|
|
30
30
|
});
|
|
31
31
|
Object.defineProperty(exports, "combineSlices", {
|
|
32
32
|
enumerable: true,
|
|
33
|
-
get: function () { return
|
|
33
|
+
get: function () { return chunkV6ASKKTH_cjs.combineSlices; }
|
|
34
34
|
});
|
|
35
35
|
Object.defineProperty(exports, "combineValidators", {
|
|
36
36
|
enumerable: true,
|
|
37
|
-
get: function () { return
|
|
37
|
+
get: function () { return chunkV6ASKKTH_cjs.combineValidators; }
|
|
38
38
|
});
|
|
39
39
|
Object.defineProperty(exports, "compose", {
|
|
40
40
|
enumerable: true,
|
|
41
|
-
get: function () { return
|
|
41
|
+
get: function () { return chunkV6ASKKTH_cjs.compose; }
|
|
42
42
|
});
|
|
43
43
|
Object.defineProperty(exports, "computed", {
|
|
44
44
|
enumerable: true,
|
|
45
|
-
get: function () { return
|
|
45
|
+
get: function () { return chunkV6ASKKTH_cjs.computed; }
|
|
46
46
|
});
|
|
47
47
|
Object.defineProperty(exports, "createAsyncValidator", {
|
|
48
48
|
enumerable: true,
|
|
49
|
-
get: function () { return
|
|
49
|
+
get: function () { return chunkV6ASKKTH_cjs.createAsyncValidator; }
|
|
50
50
|
});
|
|
51
51
|
Object.defineProperty(exports, "createDebouncedEffect", {
|
|
52
52
|
enumerable: true,
|
|
53
|
-
get: function () { return
|
|
53
|
+
get: function () { return chunkV6ASKKTH_cjs.createDebouncedEffect; }
|
|
54
54
|
});
|
|
55
55
|
Object.defineProperty(exports, "createEffect", {
|
|
56
56
|
enumerable: true,
|
|
57
|
-
get: function () { return
|
|
57
|
+
get: function () { return chunkV6ASKKTH_cjs.createEffect; }
|
|
58
58
|
});
|
|
59
59
|
Object.defineProperty(exports, "createFederatedComputed", {
|
|
60
60
|
enumerable: true,
|
|
61
|
-
get: function () { return
|
|
61
|
+
get: function () { return chunkV6ASKKTH_cjs.createFederatedComputed; }
|
|
62
62
|
});
|
|
63
63
|
Object.defineProperty(exports, "createFederatedSelector", {
|
|
64
64
|
enumerable: true,
|
|
65
|
-
get: function () { return
|
|
65
|
+
get: function () { return chunkV6ASKKTH_cjs.createFederatedSelector; }
|
|
66
66
|
});
|
|
67
67
|
Object.defineProperty(exports, "createFederation", {
|
|
68
68
|
enumerable: true,
|
|
69
|
-
get: function () { return
|
|
69
|
+
get: function () { return chunkV6ASKKTH_cjs.createFederation; }
|
|
70
70
|
});
|
|
71
71
|
Object.defineProperty(exports, "createFieldValidator", {
|
|
72
72
|
enumerable: true,
|
|
73
|
-
get: function () { return
|
|
73
|
+
get: function () { return chunkV6ASKKTH_cjs.createFieldValidator; }
|
|
74
74
|
});
|
|
75
75
|
Object.defineProperty(exports, "createLogger", {
|
|
76
76
|
enumerable: true,
|
|
77
|
-
get: function () { return
|
|
77
|
+
get: function () { return chunkV6ASKKTH_cjs.createLogger; }
|
|
78
78
|
});
|
|
79
79
|
Object.defineProperty(exports, "createMockStorage", {
|
|
80
80
|
enumerable: true,
|
|
81
|
-
get: function () { return
|
|
81
|
+
get: function () { return chunkV6ASKKTH_cjs.createMockStorage; }
|
|
82
82
|
});
|
|
83
83
|
Object.defineProperty(exports, "createNamespacedSlice", {
|
|
84
84
|
enumerable: true,
|
|
85
|
-
get: function () { return
|
|
85
|
+
get: function () { return chunkV6ASKKTH_cjs.createNamespacedSlice; }
|
|
86
86
|
});
|
|
87
87
|
Object.defineProperty(exports, "createSimpleEffect", {
|
|
88
88
|
enumerable: true,
|
|
89
|
-
get: function () { return
|
|
89
|
+
get: function () { return chunkV6ASKKTH_cjs.createSimpleEffect; }
|
|
90
90
|
});
|
|
91
91
|
Object.defineProperty(exports, "createSimpleMiddleware", {
|
|
92
92
|
enumerable: true,
|
|
93
|
-
get: function () { return
|
|
93
|
+
get: function () { return chunkV6ASKKTH_cjs.createSimpleMiddleware; }
|
|
94
94
|
});
|
|
95
95
|
Object.defineProperty(exports, "createSlice", {
|
|
96
96
|
enumerable: true,
|
|
97
|
-
get: function () { return
|
|
97
|
+
get: function () { return chunkV6ASKKTH_cjs.createSlice; }
|
|
98
98
|
});
|
|
99
99
|
Object.defineProperty(exports, "createStorage", {
|
|
100
100
|
enumerable: true,
|
|
101
|
-
get: function () { return
|
|
101
|
+
get: function () { return chunkV6ASKKTH_cjs.createStorage; }
|
|
102
102
|
});
|
|
103
103
|
Object.defineProperty(exports, "createStore", {
|
|
104
104
|
enumerable: true,
|
|
105
|
-
get: function () { return
|
|
105
|
+
get: function () { return chunkV6ASKKTH_cjs.createStore; }
|
|
106
106
|
});
|
|
107
107
|
Object.defineProperty(exports, "createSubscriber", {
|
|
108
108
|
enumerable: true,
|
|
109
|
-
get: function () { return
|
|
109
|
+
get: function () { return chunkV6ASKKTH_cjs.createSubscriber; }
|
|
110
110
|
});
|
|
111
111
|
Object.defineProperty(exports, "createTestStore", {
|
|
112
112
|
enumerable: true,
|
|
113
|
-
get: function () { return
|
|
113
|
+
get: function () { return chunkV6ASKKTH_cjs.createTestStore; }
|
|
114
114
|
});
|
|
115
115
|
Object.defineProperty(exports, "createValidator", {
|
|
116
116
|
enumerable: true,
|
|
117
|
-
get: function () { return
|
|
117
|
+
get: function () { return chunkV6ASKKTH_cjs.createValidator; }
|
|
118
118
|
});
|
|
119
119
|
Object.defineProperty(exports, "createWithMiddleware", {
|
|
120
120
|
enumerable: true,
|
|
121
|
-
get: function () { return
|
|
121
|
+
get: function () { return chunkV6ASKKTH_cjs.createWithMiddleware; }
|
|
122
122
|
});
|
|
123
123
|
Object.defineProperty(exports, "deepClone", {
|
|
124
124
|
enumerable: true,
|
|
125
|
-
get: function () { return
|
|
125
|
+
get: function () { return chunkV6ASKKTH_cjs.deepClone; }
|
|
126
126
|
});
|
|
127
127
|
Object.defineProperty(exports, "deepEqual", {
|
|
128
128
|
enumerable: true,
|
|
129
|
-
get: function () { return
|
|
129
|
+
get: function () { return chunkV6ASKKTH_cjs.deepEqual; }
|
|
130
130
|
});
|
|
131
131
|
Object.defineProperty(exports, "deepMerge", {
|
|
132
132
|
enumerable: true,
|
|
133
|
-
get: function () { return
|
|
133
|
+
get: function () { return chunkV6ASKKTH_cjs.deepMerge; }
|
|
134
134
|
});
|
|
135
135
|
Object.defineProperty(exports, "delay", {
|
|
136
136
|
enumerable: true,
|
|
137
|
-
get: function () { return
|
|
137
|
+
get: function () { return chunkV6ASKKTH_cjs.delay; }
|
|
138
138
|
});
|
|
139
139
|
Object.defineProperty(exports, "devtools", {
|
|
140
140
|
enumerable: true,
|
|
141
|
-
get: function () { return
|
|
141
|
+
get: function () { return chunkV6ASKKTH_cjs.devtools; }
|
|
142
142
|
});
|
|
143
143
|
Object.defineProperty(exports, "effects", {
|
|
144
144
|
enumerable: true,
|
|
145
|
-
get: function () { return
|
|
145
|
+
get: function () { return chunkV6ASKKTH_cjs.effects; }
|
|
146
146
|
});
|
|
147
147
|
Object.defineProperty(exports, "extendStore", {
|
|
148
148
|
enumerable: true,
|
|
149
|
-
get: function () { return
|
|
149
|
+
get: function () { return chunkV6ASKKTH_cjs.extendStore; }
|
|
150
150
|
});
|
|
151
151
|
Object.defineProperty(exports, "flushMicrotasks", {
|
|
152
152
|
enumerable: true,
|
|
153
|
-
get: function () { return
|
|
153
|
+
get: function () { return chunkV6ASKKTH_cjs.flushMicrotasks; }
|
|
154
154
|
});
|
|
155
155
|
Object.defineProperty(exports, "hasHistory", {
|
|
156
156
|
enumerable: true,
|
|
157
|
-
get: function () { return
|
|
157
|
+
get: function () { return chunkV6ASKKTH_cjs.hasHistory; }
|
|
158
158
|
});
|
|
159
159
|
Object.defineProperty(exports, "history", {
|
|
160
160
|
enumerable: true,
|
|
161
|
-
get: function () { return
|
|
161
|
+
get: function () { return chunkV6ASKKTH_cjs.history; }
|
|
162
162
|
});
|
|
163
163
|
Object.defineProperty(exports, "identity", {
|
|
164
164
|
enumerable: true,
|
|
165
|
-
get: function () { return
|
|
165
|
+
get: function () { return chunkV6ASKKTH_cjs.identity; }
|
|
166
166
|
});
|
|
167
167
|
Object.defineProperty(exports, "immer", {
|
|
168
168
|
enumerable: true,
|
|
169
|
-
get: function () { return
|
|
169
|
+
get: function () { return chunkV6ASKKTH_cjs.immer; }
|
|
170
170
|
});
|
|
171
171
|
Object.defineProperty(exports, "isFunction", {
|
|
172
172
|
enumerable: true,
|
|
173
|
-
get: function () { return
|
|
173
|
+
get: function () { return chunkV6ASKKTH_cjs.isFunction; }
|
|
174
174
|
});
|
|
175
175
|
Object.defineProperty(exports, "logger", {
|
|
176
176
|
enumerable: true,
|
|
177
|
-
get: function () { return
|
|
177
|
+
get: function () { return chunkV6ASKKTH_cjs.logger; }
|
|
178
178
|
});
|
|
179
179
|
Object.defineProperty(exports, "memoizeSelector", {
|
|
180
180
|
enumerable: true,
|
|
181
|
-
get: function () { return
|
|
181
|
+
get: function () { return chunkV6ASKKTH_cjs.memoizeSelector; }
|
|
182
182
|
});
|
|
183
183
|
Object.defineProperty(exports, "middlewareCompat", {
|
|
184
184
|
enumerable: true,
|
|
185
|
-
get: function () { return
|
|
185
|
+
get: function () { return chunkV6ASKKTH_cjs.middlewareCompat; }
|
|
186
186
|
});
|
|
187
187
|
Object.defineProperty(exports, "mockAction", {
|
|
188
188
|
enumerable: true,
|
|
189
|
-
get: function () { return
|
|
189
|
+
get: function () { return chunkV6ASKKTH_cjs.mockAction; }
|
|
190
190
|
});
|
|
191
191
|
Object.defineProperty(exports, "omit", {
|
|
192
192
|
enumerable: true,
|
|
193
|
-
get: function () { return
|
|
193
|
+
get: function () { return chunkV6ASKKTH_cjs.omit; }
|
|
194
194
|
});
|
|
195
195
|
Object.defineProperty(exports, "persist", {
|
|
196
196
|
enumerable: true,
|
|
197
|
-
get: function () { return
|
|
197
|
+
get: function () { return chunkV6ASKKTH_cjs.persist; }
|
|
198
198
|
});
|
|
199
199
|
Object.defineProperty(exports, "pick", {
|
|
200
200
|
enumerable: true,
|
|
201
|
-
get: function () { return
|
|
201
|
+
get: function () { return chunkV6ASKKTH_cjs.pick; }
|
|
202
202
|
});
|
|
203
203
|
Object.defineProperty(exports, "produce", {
|
|
204
204
|
enumerable: true,
|
|
205
|
-
get: function () { return
|
|
205
|
+
get: function () { return chunkV6ASKKTH_cjs.produce; }
|
|
206
206
|
});
|
|
207
207
|
Object.defineProperty(exports, "resetSlices", {
|
|
208
208
|
enumerable: true,
|
|
209
|
-
get: function () { return
|
|
209
|
+
get: function () { return chunkV6ASKKTH_cjs.resetSlices; }
|
|
210
210
|
});
|
|
211
211
|
Object.defineProperty(exports, "selector", {
|
|
212
212
|
enumerable: true,
|
|
213
|
-
get: function () { return
|
|
213
|
+
get: function () { return chunkV6ASKKTH_cjs.selector; }
|
|
214
214
|
});
|
|
215
215
|
Object.defineProperty(exports, "sessionStorage", {
|
|
216
216
|
enumerable: true,
|
|
217
|
-
get: function () { return
|
|
217
|
+
get: function () { return chunkV6ASKKTH_cjs.sessionStorage; }
|
|
218
218
|
});
|
|
219
219
|
Object.defineProperty(exports, "shallowEqual", {
|
|
220
220
|
enumerable: true,
|
|
221
|
-
get: function () { return
|
|
221
|
+
get: function () { return chunkV6ASKKTH_cjs.shallowEqual; }
|
|
222
222
|
});
|
|
223
223
|
Object.defineProperty(exports, "snapshot", {
|
|
224
224
|
enumerable: true,
|
|
225
|
-
get: function () { return
|
|
225
|
+
get: function () { return chunkV6ASKKTH_cjs.snapshot; }
|
|
226
226
|
});
|
|
227
227
|
Object.defineProperty(exports, "spyOnStore", {
|
|
228
228
|
enumerable: true,
|
|
229
|
-
get: function () { return
|
|
229
|
+
get: function () { return chunkV6ASKKTH_cjs.spyOnStore; }
|
|
230
230
|
});
|
|
231
231
|
Object.defineProperty(exports, "stateDiff", {
|
|
232
232
|
enumerable: true,
|
|
233
|
-
get: function () { return
|
|
233
|
+
get: function () { return chunkV6ASKKTH_cjs.stateDiff; }
|
|
234
234
|
});
|
|
235
235
|
Object.defineProperty(exports, "subscribeOnce", {
|
|
236
236
|
enumerable: true,
|
|
237
|
-
get: function () { return
|
|
237
|
+
get: function () { return chunkV6ASKKTH_cjs.subscribeOnce; }
|
|
238
238
|
});
|
|
239
239
|
Object.defineProperty(exports, "subscribeToMany", {
|
|
240
240
|
enumerable: true,
|
|
241
|
-
get: function () { return
|
|
241
|
+
get: function () { return chunkV6ASKKTH_cjs.subscribeToMany; }
|
|
242
242
|
});
|
|
243
243
|
Object.defineProperty(exports, "subscribeWithOptions", {
|
|
244
244
|
enumerable: true,
|
|
245
|
-
get: function () { return
|
|
245
|
+
get: function () { return chunkV6ASKKTH_cjs.subscribeWithOptions; }
|
|
246
246
|
});
|
|
247
247
|
Object.defineProperty(exports, "sync", {
|
|
248
248
|
enumerable: true,
|
|
249
|
-
get: function () { return
|
|
249
|
+
get: function () { return chunkV6ASKKTH_cjs.sync; }
|
|
250
250
|
});
|
|
251
251
|
Object.defineProperty(exports, "toMiddlewareApi", {
|
|
252
252
|
enumerable: true,
|
|
253
|
-
get: function () { return
|
|
253
|
+
get: function () { return chunkV6ASKKTH_cjs.toMiddlewareApi; }
|
|
254
254
|
});
|
|
255
255
|
Object.defineProperty(exports, "triggerSync", {
|
|
256
256
|
enumerable: true,
|
|
257
|
-
get: function () { return
|
|
257
|
+
get: function () { return chunkV6ASKKTH_cjs.triggerSync; }
|
|
258
258
|
});
|
|
259
259
|
Object.defineProperty(exports, "validate", {
|
|
260
260
|
enumerable: true,
|
|
261
|
-
get: function () { return
|
|
261
|
+
get: function () { return chunkV6ASKKTH_cjs.validate; }
|
|
262
262
|
});
|
|
263
263
|
Object.defineProperty(exports, "waitForFederated", {
|
|
264
264
|
enumerable: true,
|
|
265
|
-
get: function () { return
|
|
265
|
+
get: function () { return chunkV6ASKKTH_cjs.waitForFederated; }
|
|
266
266
|
});
|
|
267
267
|
//# sourceMappingURL=vanilla.cjs.map
|
|
268
268
|
//# sourceMappingURL=vanilla.cjs.map
|
package/dist/vanilla.d.cts
CHANGED
|
@@ -341,9 +341,9 @@ declare enum StoreErrorCode {
|
|
|
341
341
|
PLUGIN_EXISTS = "PLUGIN_EXISTS",
|
|
342
342
|
/** Required plugin dependency not found */
|
|
343
343
|
PLUGIN_DEPENDENCY_MISSING = "PLUGIN_DEPENDENCY_MISSING",
|
|
344
|
-
/**
|
|
344
|
+
/** `setState` got (or its updater returned) something other than an object, `null` or `undefined` */
|
|
345
345
|
INVALID_STATE_UPDATE = "INVALID_STATE_UPDATE",
|
|
346
|
-
/**
|
|
346
|
+
/** Reserved; not thrown. An error thrown by an action reaches the caller unchanged. */
|
|
347
347
|
ACTION_ERROR = "ACTION_ERROR",
|
|
348
348
|
/** `use()` was given an object without name, version or install function */
|
|
349
349
|
INVALID_PLUGIN = "INVALID_PLUGIN",
|
package/dist/vanilla.d.ts
CHANGED
|
@@ -341,9 +341,9 @@ declare enum StoreErrorCode {
|
|
|
341
341
|
PLUGIN_EXISTS = "PLUGIN_EXISTS",
|
|
342
342
|
/** Required plugin dependency not found */
|
|
343
343
|
PLUGIN_DEPENDENCY_MISSING = "PLUGIN_DEPENDENCY_MISSING",
|
|
344
|
-
/**
|
|
344
|
+
/** `setState` got (or its updater returned) something other than an object, `null` or `undefined` */
|
|
345
345
|
INVALID_STATE_UPDATE = "INVALID_STATE_UPDATE",
|
|
346
|
-
/**
|
|
346
|
+
/** Reserved; not thrown. An error thrown by an action reaches the caller unchanged. */
|
|
347
347
|
ACTION_ERROR = "ACTION_ERROR",
|
|
348
348
|
/** `use()` was given an object without name, version or install function */
|
|
349
349
|
INVALID_PLUGIN = "INVALID_PLUGIN",
|
package/dist/vanilla.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { StoreError, StoreErrorCode, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, validate, waitForFederated } from './chunk-
|
|
1
|
+
export { StoreError, StoreErrorCode, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, validate, waitForFederated } from './chunk-2QNZBQ4V.js';
|
|
2
2
|
//# sourceMappingURL=vanilla.js.map
|
|
3
3
|
//# sourceMappingURL=vanilla.js.map
|