-
Notifications
You must be signed in to change notification settings - Fork 3
/
context.js
74 lines (70 loc) · 1.52 KB
/
context.js
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
import { Stack, Top} from "./stateful.js"
import { Args} from "./symbol.js"
export class Context{
constructor(){
}
}
//
const _contexts= new WeakMap()
function walkContextsTo( ctx, stack= Stack()){
while( stack.length){
const
ctxs= _contexts.get( stack),
value= ctx&& ctx.get( ctx)
if( value){
return {
ctx,
stateful: stack[ stack.length- 1],
value
}
}
stack= stack[ stack.length- 2]
}
}
let currentContext= new WeakMap()
export function useContext( ctx){
const
top= Top(),
cached= currentContext.get( top),
provider= walkContextsTo( ctx),
value= provider&& provider.value
if( cached!== value){
currentContext.set( top, value)
if( cached){
// de-listen to whomever we were listening to & listen to this new
const
listeners= cached.listeners,
i= listeners.indexOf( cached)
if( i!== -1){
listeners.splice( i, 1)
}
}
if( provider&& provider.value){
provider.value.listeners.push( top)
}
}
return provider&& provider.value&& provider.value.value
}
export function provideContext( ctx, value){
const
stack= Stack(),
hadCtxs= _contexts.get( stack),
newCtxs= !hadCtxs&& new WeakMap(),
ctxs= hadCtxs|| newCtxs,
oldCtx= hadCtxs&& hadCtxs.get( ctx),
changed= oldCtx&& oldCtx.value!== value
if( newCtxs){
_contexts.set( stack, newCtxs)
}
if( !oldCtx){
ctxs.set( ctx, { value, listeners: []})
}else{
oldCtx.value= value
}
if( changed){
for( let listener of oldCtx.listeners){
const args= listener[ Args]
listener( ...args)
}
}
}