-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.js
54 lines (48 loc) · 1.86 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
export default function html([first, ...strings], ...values) {
// Weave the literal strings and the interpolations.
// We don't have to explicitly handle array-typed values
// because concat will spread them flat for us.
return values.reduce(
(acc, cur) => acc.concat(cur, strings.shift()),
[first])
// Filter out interpolations which are bools, null or undefined.
.filter(x => x && x !== true || x === 0)
.join("");
}
export function createStore(reducer) {
let state = reducer();
const roots = new Map();
const prevs = new Map();
function render() {
for (const [root, component] of roots) {
const output = component();
// Poor man's Virtual DOM implementation :) Compare the new output
// with the last output for this root. Don't trust the current
// value of root.innerHTML as it may have been changed by other
// scripts or extensions.
if (output !== prevs.get(root)) {
prevs.set(root, root.innerHTML = output);
// Dispatch an event on the root to give developers a chance to
// do some housekeeping after the whole DOM is replaced under
// the root. You can re-focus elements in the listener to this
// event. See example03.
root.dispatchEvent(
new CustomEvent("render", {detail: state}));
}
}
};
return {
attach(component, root) {
roots.set(root, component);
render();
},
connect(component) {
// Return a decorated component function.
return (...args) => component(state, ...args);
},
dispatch(action, ...args) {
state = reducer(state, action, args);
render();
},
};
}