forked from stasm/innerself
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (56 loc) · 1.89 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
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 null or undefined. null is
// loosely-equal only to undefined and itself.
.filter(value => value != null)
.join("");
}
export function createStore(reducer) {
let state = reducer();
const roots = new Map();
const prevs = new Map();
function render() {
const id = focused();
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, output);
root.innerHTML = output;
}
}
focus(id);
};
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();
},
};
}
const DOCUMENT_EXISTS = typeof document !== 'undefined';
function focused() {
const active = DOCUMENT_EXISTS && document.activeElement;
return active && active.id;
}
function focus(id) {
const element = DOCUMENT_EXISTS && document.getElementById(id);
element && element.focus();
}