-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·78 lines (71 loc) · 1.9 KB
/
index.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
75
76
77
78
import React from 'react';
function isObservable(o) {
return typeof o === "function" && typeof o.observe === "function";
}
export function isJadeletRoot(o) {
return (
typeof o === "object" &&
typeof o.children === "object" &&
o.observed instanceof Set
);
}
function incOrWrap(n) {
return n === Number.MAX_SAFE_INTEGER ? Number.MIN_SAFE_INTEGER : n + 1;
}
function useForceUpdate() {
const [, update] = React.useState(Number.MIN_SAFE_INTEGER);
const cb = React.useCallback(() => update(incOrWrap), [update]);
return cb;
}
export function JadeletWrapper({ template, presenter, ...rest }) {
const root = template({ ...presenter, ...rest });
const forceUpdate = useForceUpdate();
React.useEffect(() => {
root.observed.forEach(observable => observable.observe(forceUpdate));
return () => {
root.observed.forEach(observable => observable.stopObserving(forceUpdate));
};
});
return React.createElement(React.Fragment, {}, ...root.children);
}
function createSubRoot(rootProto, self) {
const root = Object.create(rootProto, {
children: {
value: []
}
});
return {
buffer(o) {
if (isJadeletRoot(o)) {
Array.from(o.observed).forEach((observable) => {
root.observed.add(observable);
});
o = o.children[0];
}
root.children.push(o);
},
element(tag, _, attrs, childFn) {
const subRoot = createSubRoot(rootProto, self);
childFn.call(self, subRoot);
return React.createElement(tag, attrs, ...subRoot.root.children);
},
get root() {
return root;
}
};
}
export function runtime(self) {
const rootProto = {
observed: new Set()
};
const selfProxy = new Proxy(self, {
get(target, prop) {
const v = target[prop];
if (isObservable(v)) {
rootProto.observed.add(v);
}
return v;
}
});
return createSubRoot(rootProto, selfProxy);
}