-
Notifications
You must be signed in to change notification settings - Fork 2
/
hydrate.ts
83 lines (72 loc) · 1.85 KB
/
hydrate.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// deno-lint-ignore-file no-explicit-any
import { options, VNode } from "preact";
declare module "preact" {
interface Options extends Record<string, (v: VNode) => void> {
"_render"?: (vnode: VNode) => void;
"__r"?: (vnode: VNode) => void;
}
interface VNode extends Record<string, any> {
"__ctx"?: Record<string, any>;
"__c"?: Record<string, any>;
"_component"?: Record<string, any>;
}
}
// Using some privates here, which might be shorted
// See preact's `mangle.json`
const ugly = {
_render: "__r",
_component: "__c",
_id: "__c",
};
const is_ugly = !options._render;
const _id = is_ugly ? ugly["_id"] : "_id";
const _render = is_ugly ? ugly["_render"] : "_render";
const _component = is_ugly ? ugly["_component"] : "_component";
let contextId = "cC0";
let provider: any = null;
let value = null;
const hook = options.vnode;
options.vnode = (vnode: VNode) => {
if (typeof vnode.type === "function") {
vnode.__ctx = {
[contextId]: provider,
};
}
hook?.(vnode);
};
const render = options[_render];
options[_render] = (vnode) => {
if (
vnode[_component] &&
vnode.__ctx
) {
vnode[_component].context = {
...vnode[_component].context,
...vnode.__ctx,
};
}
render?.(vnode);
};
/**
* @param Context
* @param state
*/
export default function hydrate(Context: any, state: { id: string }) {
const valid = document.querySelectorAll("#" + state.id).length <= 1;
if (!valid) {
throw new Error(
"Global context:\n Context.Provider must be used once during render." +
"The application must use only one global context",
);
}
const el = document.getElementById(state.id);
contextId = Context[_id];
value = JSON.parse(
el?.innerHTML || "{}",
);
provider = new Context.Provider({ value });
provider.props = { value };
setTimeout(() => {
el?.remove();
}, 0);
}