-
-
Notifications
You must be signed in to change notification settings - Fork 567
/
contexts.ts
33 lines (27 loc) 路 1014 Bytes
/
contexts.ts
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
import { createContext } from 'react'
import type { Context } from 'react'
import type { Atom, Scope } from './atom'
import { createStore, createStoreForExport } from './store'
import type { Store } from './store'
type VersionedWrite = (write: (version?: object) => void) => void
export type ScopeContainer = {
s: Store
w?: VersionedWrite
}
export const createScopeContainer = (
initialValues?: Iterable<readonly [Atom<unknown>, unknown]>,
unstable_createStore?: typeof createStoreForExport
): ScopeContainer => {
const store = unstable_createStore
? unstable_createStore(initialValues).SECRET_INTERNAL_store
: createStore(initialValues)
return { s: store }
}
type ScopeContext = Context<ScopeContainer>
const ScopeContextMap = new Map<Scope | undefined, ScopeContext>()
export const getScopeContext = (scope?: Scope) => {
if (!ScopeContextMap.has(scope)) {
ScopeContextMap.set(scope, createContext(createScopeContainer()))
}
return ScopeContextMap.get(scope) as ScopeContext
}