-
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathinjectSelector.ts
More file actions
82 lines (72 loc) · 1.87 KB
/
injectSelector.ts
File metadata and controls
82 lines (72 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {
Injector,
assertInInjectionContext,
effect,
inject,
linkedSignal,
runInInjectionContext,
} from '@angular/core'
import type { CreateSignalOptions, Signal } from '@angular/core'
export interface InjectSelectorOptions<TSelected> extends Omit<
CreateSignalOptions<TSelected>,
'equal'
> {
compare?: (a: TSelected, b: TSelected) => boolean
injector?: Injector
}
export type SelectionSource<T> = {
get: () => T
subscribe: (listener: (value: T) => void) => {
unsubscribe: () => void
}
}
function resolveInjector(
fn: (...args: Array<never>) => unknown,
injector?: Injector,
) {
if (!injector) {
assertInInjectionContext(fn)
return inject(Injector)
}
return injector
}
/**
* Selects a slice of state from an atom or store and returns it as an Angular
* signal.
*
* This is the primary Angular read hook for TanStack Store.
*
* @example
* ```ts
* readonly count = injectSelector(counterStore, (state) => state.count)
* ```
*
* @example
* ```ts
* readonly doubled = injectSelector(countAtom, (value) => value * 2)
* ```
*/
export function injectSelector<TState, TSelected = NoInfer<TState>>(
source: SelectionSource<TState> | (() => SelectionSource<TState>),
selector: (state: NoInfer<TState>) => TSelected = (d) =>
d as unknown as TSelected,
options?: InjectSelectorOptions<TSelected>,
): Signal<TSelected> {
const injector = resolveInjector(
injectSelector,
options?.injector,
)
return runInInjectionContext(injector, () => {
const _source = typeof source === "function" ? source : (() => source)
const slice = linkedSignal(() => selector(_source().get()), {
equal: options?.compare,
})
effect((onCleanup) => {
const { unsubscribe } = _source().subscribe((state) => {
slice.set(selector(state))
})
onCleanup(unsubscribe)
})
return slice.asReadonly()
})
}