Open History to see the last commit
1import { InjectionToken, inject } from '@angular/core'
2import type { Provider } from '@angular/core'
3β
4/**
5 * Creates a typed Angular dependency-injection context for sharing a bundle of
6 * atoms and stores with a component subtree.
7 *
8 * The returned `provideStoreContext` function accepts a factory that creates the
9 * context value. Using a factory (rather than a static value) ensures each
10 * component instance β and each SSR request β receives its own state, avoiding
11 * cross-request pollution.
12 *
13 * Consumers call `injectStoreContext()` inside an injection context (typically a
14 * constructor or field initializer) to retrieve the contextual atoms and stores,
15 * then compose them with existing hooks like {@link injectSelector},
16 * {@link injectSelector}, and {@link injectAtom}.
17 *
18 * @example
19 * ```ts
20 * const { provideStoreContext, injectStoreContext } = createStoreContext<{
21 * countAtom: Atom<number>
22 * totalsStore: Store<{ count: number }>
23 * }>()
24 *
25 * // Parent component provides the context
26 * @Component({
27 * providers: [
28 * provideStoreContext(() => ({
29 * countAtom: createAtom(0),
30 * totalsStore: new Store({ count: 0 }),
31 * })),
32 * ],
33 * template: `<child-cmp />`,
34 * })
35 * class ParentComponent {}
36 *
37 * // Child component consumes the context
38 * @Component({ template: `{{ count() }}` })
39 * class ChildComponent {
40 * private ctx = injectStoreContext()
41 * count = injectSelector(this.ctx.countAtom)
42 * }
43 * ```
44 *
45 * @throws When `injectStoreContext()` is called without a matching
46 * `provideStoreContext()` in a parent component's providers.
47 */
48export function createStoreContext<TValue extends object>(): {
49 provideStoreContext: (factory: () => TValue) => Provider
50 injectStoreContext: () => TValue
51} {
52 const token = new InjectionToken<TValue>('StoreContext')
53β
54 function provideStoreContext(factory: () => TValue): Provider {
55 return { provide: token, useFactory: factory }
56 }
57β
58 function injectStoreContext(): TValue {
59 const value = inject(token, { optional: true })
60β
61 if (value === null) {
62 throw new Error(
63 "Missing StoreContext provider. Add provideStoreContext() to a parent component's providers array.",
64 )
65 }
66β
67 return value
68 }
69β
70 return { provideStoreContext, injectStoreContext }
71}