Server: Phase 2 (REVIEW not respected yet)
This commit is contained in:
1 parent
5d16ded553
commit
142b47674d
4271 files changed
+1203269
No files matched your search
+43
@@ -0,0 +1,43 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useSelector } from './useSelector'
|
||||
import type { Store, StoreActionMap } from '@tanstack/store'
|
||||
import type { UseSelectorOptions } from './useSelector'
|
||||
|
||||
/**
|
||||
* Experimental combined read+write hook for stores, mirroring useAtom's tuple
|
||||
* pattern.
|
||||
*
|
||||
* Returns `[selected, actions]` when the store has an actions factory, or
|
||||
* `[selected, setState]` for plain stores.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* // Store with actions
|
||||
* const [cats, { addCat }] = _useStore(petStore, (s) => s.cats)
|
||||
*
|
||||
* // Store without actions
|
||||
* const [count, setState] = _useStore(plainStore, (s) => s)
|
||||
* setState((prev) => prev + 1)
|
||||
* ```
|
||||
*/
|
||||
/* eslint-disable react-hooks/rules-of-hooks, @eslint-react/rules-of-hooks -- experimental API with underscore prefix */
|
||||
export function _useStore<
|
||||
TState,
|
||||
TActions extends StoreActionMap,
|
||||
TSelected = NoInfer<TState>,
|
||||
>(
|
||||
store: Store<TState, TActions>,
|
||||
selector: (state: NoInfer<TState>) => TSelected,
|
||||
options?: UseSelectorOptions<TSelected>,
|
||||
): [
|
||||
TSelected,
|
||||
[TActions] extends [never] ? Store<TState>['setState'] : TActions,
|
||||
] {
|
||||
const selected = useSelector(store, selector, options)
|
||||
const actionsOrSetState = useMemo(
|
||||
() => (store.actions as StoreActionMap | undefined) ?? store.setState,
|
||||
[store],
|
||||
) as [TActions] extends [never] ? Store<TState>['setState'] : TActions
|
||||
|
||||
return [selected, actionsOrSetState]
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
import type { PropsWithChildren, ReactElement } from 'react'
|
||||
|
||||
/**
|
||||
* Creates a typed React context for sharing a bundle of atoms and stores with a subtree.
|
||||
*
|
||||
* The returned `StoreProvider` only transports the provided object through
|
||||
* React context. Consumers destructure the contextual atoms and stores, then
|
||||
* compose them with the existing hooks like {@link useSelector},
|
||||
* {@link useSelector} and {@link useAtom}.
|
||||
*
|
||||
* The object shape is preserved exactly, so keyed atoms and stores remain fully
|
||||
* typed when read back with `useStoreContext()`.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { StoreProvider, useStoreContext } = createStoreContext<{
|
||||
* countAtom: Atom<number>
|
||||
* totalsStore: Store<{ count: number }>
|
||||
* }>()
|
||||
*
|
||||
* function CountButton() {
|
||||
* const { countAtom, totalsStore } = useStoreContext()
|
||||
* const count = useSelector(countAtom)
|
||||
* const total = useSelector(totalsStore, (state) => state.count)
|
||||
*
|
||||
* return (
|
||||
* <button
|
||||
* type="button"
|
||||
* onClick={() => totalsStore.setState((state) => ({ ...state, count: state.count + 1 }))}
|
||||
* >
|
||||
* {count} / {total}
|
||||
* </button>
|
||||
* )
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @throws When `useStoreContext()` is called outside the matching `StoreProvider`.
|
||||
*/
|
||||
export function createStoreContext<TValue extends object>(): {
|
||||
StoreProvider: (
|
||||
props: {
|
||||
value: TValue
|
||||
} & PropsWithChildren,
|
||||
) => ReactElement
|
||||
useStoreContext: () => TValue
|
||||
} {
|
||||
const Context = createContext<TValue | null>(null)
|
||||
Context.displayName = 'StoreContext'
|
||||
|
||||
// eslint-disable-next-line @eslint-react/component-hook-factories
|
||||
function StoreProvider({
|
||||
children,
|
||||
value,
|
||||
}: PropsWithChildren<{
|
||||
value: TValue
|
||||
}>) {
|
||||
// eslint-disable-next-line @eslint-react/no-context-provider
|
||||
return <Context.Provider value={value}>{children}</Context.Provider>
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @eslint-react/component-hook-factories
|
||||
function useStoreContext() {
|
||||
// eslint-disable-next-line @eslint-react/no-use-context
|
||||
const value = useContext(Context)
|
||||
|
||||
if (value === null) {
|
||||
throw new Error('Missing StoreProvider for StoreContext')
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
return {
|
||||
StoreProvider,
|
||||
useStoreContext,
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
export * from '@tanstack/store'
|
||||
|
||||
// create hooks
|
||||
export * from './createStoreContext'
|
||||
export * from './useCreateAtom'
|
||||
export * from './useCreateStore'
|
||||
|
||||
// read hooks
|
||||
export * from './useSelector'
|
||||
|
||||
// tuple hooks - [state, setState]
|
||||
export * from './useAtom'
|
||||
export * from './_useStore' // will replace old useStore hook in next major version
|
||||
|
||||
export * from './useStore' // @deprecated in favor of useSelector
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { useSelector } from './useSelector'
|
||||
import type { Atom } from '@tanstack/store'
|
||||
import type { UseSelectorOptions } from './useSelector'
|
||||
|
||||
/**
|
||||
* Returns the current atom value together with a stable setter.
|
||||
*
|
||||
* This is the writable-atom convenience hook for components that need to both
|
||||
* read and update the same atom.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const [count, setCount] = useAtom(countAtom)
|
||||
* ```
|
||||
*/
|
||||
export function useAtom<TValue>(
|
||||
atom: Atom<TValue>,
|
||||
options?: UseSelectorOptions<TValue>,
|
||||
): [TValue, Atom<TValue>['set']] {
|
||||
const value = useSelector(atom, undefined, options)
|
||||
|
||||
return [value, atom.set]
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { useState } from 'react'
|
||||
import { createAtom } from '@tanstack/store'
|
||||
import type { Atom, AtomOptions, ReadonlyAtom } from '@tanstack/store'
|
||||
|
||||
/**
|
||||
* Creates a stable atom instance for the lifetime of the component.
|
||||
*
|
||||
* Pass an initial value to create a writable atom, or a getter function to
|
||||
* create a readonly derived atom. This hook mirrors the overloads from
|
||||
* {@link createAtom}, but ensures the atom is only created once per mount.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const countAtom = useCreateAtom(0)
|
||||
* ```
|
||||
*/
|
||||
export function useCreateAtom<T>(
|
||||
getValue: (prev?: NoInfer<T>) => T,
|
||||
options?: AtomOptions<T>,
|
||||
): ReadonlyAtom<T>
|
||||
export function useCreateAtom<T>(
|
||||
initialValue: T,
|
||||
options?: AtomOptions<T>,
|
||||
): Atom<T>
|
||||
export function useCreateAtom<T>(
|
||||
valueOrFn: T | ((prev?: T) => T),
|
||||
options?: AtomOptions<T>,
|
||||
): Atom<T> | ReadonlyAtom<T> {
|
||||
const [atom] = useState<Atom<T> | ReadonlyAtom<T>>(() => {
|
||||
if (typeof valueOrFn === 'function') {
|
||||
return createAtom(valueOrFn as (prev?: NoInfer<T>) => T, options)
|
||||
}
|
||||
|
||||
return createAtom(valueOrFn, options)
|
||||
})
|
||||
|
||||
return atom
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { useState } from 'react'
|
||||
import { createStore } from '@tanstack/store'
|
||||
import type {
|
||||
ReadonlyStore,
|
||||
Store,
|
||||
StoreActionMap,
|
||||
StoreActionsFactory,
|
||||
} from '@tanstack/store'
|
||||
|
||||
type NonFunction<T> = T extends (...args: Array<any>) => any ? never : T
|
||||
|
||||
/**
|
||||
* Creates a stable store instance for the lifetime of the component.
|
||||
*
|
||||
* Pass an initial value to create a writable store, or a getter function to
|
||||
* create a readonly derived store. This hook mirrors the overloads from
|
||||
* {@link createStore}, but ensures the store is only created once per mount.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const counterStore = useCreateStore({ count: 0 })
|
||||
* ```
|
||||
*/
|
||||
export function useCreateStore<T>(
|
||||
getValue: (prev?: NoInfer<T>) => T,
|
||||
): ReadonlyStore<T>
|
||||
export function useCreateStore<T>(initialValue: T): Store<T>
|
||||
export function useCreateStore<T, TActions extends StoreActionMap>(
|
||||
initialValue: NonFunction<T>,
|
||||
actions: StoreActionsFactory<T, TActions>,
|
||||
): Store<T, TActions>
|
||||
export function useCreateStore<T, TActions extends StoreActionMap>(
|
||||
valueOrFn: T | ((prev?: T) => T),
|
||||
actions?: StoreActionsFactory<T, TActions>,
|
||||
): Store<T, TActions> | Store<T> | ReadonlyStore<T> {
|
||||
const [store] = useState<Store<T, TActions> | Store<T> | ReadonlyStore<T>>(
|
||||
() => {
|
||||
if (typeof valueOrFn === 'function') {
|
||||
return createStore(valueOrFn as (prev?: NoInfer<T>) => T)
|
||||
}
|
||||
|
||||
if (actions) {
|
||||
return createStore(valueOrFn as NonFunction<T>, actions)
|
||||
}
|
||||
|
||||
return createStore(valueOrFn)
|
||||
},
|
||||
)
|
||||
|
||||
return store
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'
|
||||
|
||||
export interface UseSelectorOptions<TSelected> {
|
||||
compare?: (a: TSelected, b: TSelected) => boolean
|
||||
}
|
||||
|
||||
type SyncExternalStoreSubscribe = Parameters<
|
||||
typeof useSyncExternalStoreWithSelector
|
||||
>[0]
|
||||
|
||||
type SelectionSource<T> = {
|
||||
get: () => T
|
||||
subscribe: (listener: (value: T) => void) => {
|
||||
unsubscribe: () => void
|
||||
}
|
||||
}
|
||||
|
||||
function defaultCompare<T>(a: T, b: T) {
|
||||
return a === b
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a slice of state from an atom or store and subscribes the component
|
||||
* to that selection.
|
||||
*
|
||||
* This is the primary React read hook for TanStack Store. It works with any
|
||||
* source that exposes `get()` and `subscribe()`, including atoms, readonly
|
||||
* atoms, stores, and readonly stores.
|
||||
*
|
||||
* Omit the selector to subscribe to the whole value.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const count = useSelector(counterStore, (state) => state.count)
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const value = useSelector(countAtom)
|
||||
* ```
|
||||
*/
|
||||
export function useSelector<TSource, TSelected = NoInfer<TSource>>(
|
||||
source: SelectionSource<TSource>,
|
||||
selector: (snapshot: TSource) => TSelected = (s) => s as unknown as TSelected,
|
||||
options?: UseSelectorOptions<TSelected>,
|
||||
): TSelected {
|
||||
const compare = options?.compare ?? defaultCompare
|
||||
|
||||
const subscribe: SyncExternalStoreSubscribe = useCallback(
|
||||
(handleStoreChange) => {
|
||||
const { unsubscribe } = source.subscribe(handleStoreChange)
|
||||
return unsubscribe
|
||||
},
|
||||
[source],
|
||||
)
|
||||
|
||||
const getSnapshot = useCallback(() => source.get(), [source])
|
||||
|
||||
return useSyncExternalStoreWithSelector(
|
||||
subscribe,
|
||||
getSnapshot,
|
||||
getSnapshot,
|
||||
selector,
|
||||
compare,
|
||||
)
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { useSelector } from './useSelector'
|
||||
|
||||
/**
|
||||
* Deprecated alias for {@link useSelector}.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const count = useStore(counterStore, (state) => state.count)
|
||||
* ```
|
||||
*
|
||||
* @deprecated Use `useSelector` instead.
|
||||
*/
|
||||
export const useStore = <TSource, TSelected = NoInfer<TSource>>(
|
||||
source: {
|
||||
get: () => TSource
|
||||
subscribe: (listener: (value: TSource) => void) => {
|
||||
unsubscribe: () => void
|
||||
}
|
||||
},
|
||||
selector: (snapshot: TSource) => TSelected = (s) => s as unknown as TSelected,
|
||||
compare?: (a: TSelected, b: TSelected) => boolean,
|
||||
) => useSelector(source, selector, { compare })
|
||||
Reference in new issue
Block a user