-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreact.ts
61 lines (54 loc) · 1.53 KB
/
react.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
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
import { type Context, createContext, useContext, useEffect } from "react";
import {
type Bunja,
type BunjaStore,
createBunjaStore,
createScope,
type HashFn,
type ReadScope,
type Scope,
} from "./bunja.ts";
export const BunjaStoreContext: Context<BunjaStore> = createContext(
createBunjaStore(),
);
export const scopeContextMap: Map<Scope<any>, Context<any>> = new Map();
export function bindScope(scope: Scope<any>, context: Context<any>): void {
scopeContextMap.set(scope, context);
}
export function createScopeFromContext<T>(
context: Context<T>,
hash?: HashFn<T>,
): Scope<T> {
const scope = createScope(hash);
bindScope(scope, context);
return scope;
}
const defaultReadScope: ReadScope = (scope) => {
const context = scopeContextMap.get(scope)!;
return useContext(context);
};
export function useBunja<T>(
bunja: Bunja<T>,
readScope: ReadScope = defaultReadScope,
): T {
const store = useContext(BunjaStoreContext);
const { value, mount, deps } = store.get(bunja, readScope);
useEffect(mount, deps);
return value;
}
export type ScopePair<T> = [Scope<T>, T];
export function inject<const T extends ScopePair<any>[]>(
overrideTable: T,
): ReadScope {
const map = new Map(overrideTable);
return (scope) => {
if (map.has(scope)) return map.get(scope);
const context = scopeContextMap.get(scope);
if (!context) {
throw new Error(
"Unable to read the scope. Please inject the value explicitly or bind scope to the React context.",
);
}
return useContext(context);
};
}