-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag.js
80 lines (62 loc) · 2.08 KB
/
tag.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
// modified from https://github.com/tsoding/grecha.js/blob/master/grecha.js
function tag(name, ...children) {
const result = document.createElement(name);
for (const child of children) {
if (typeof(child) === 'string') {
result.appendChild(document.createTextNode(child));
} else {
result.appendChild(child);
}
}
result.att$ = function(name, value) {
this.setAttribute(name, value);
return this;
};
result.onclick$ = function(callback) {
this.onclick = callback;
return this;
};
return result;
}
const MUNDANE_TAGS = ["canvas", "h1", "h2", "h3", "h4", "p", "a", "div", "span",
"select", "details", "summary", "pre", "button", "code",
"table", "thead", "tbody", "tr", "td", "th", "br"];
var tags = {}
for (let tagName of MUNDANE_TAGS) {
const funcName = tagName.toUpperCase();
window[funcName] = (...children) => tag(tagName, ...children);
}
function IMG(src) {
return tag("img").att$("src", src);
}
function INPUT(type) {
return tag("input").att$("type", type);
}
function TEXT(t) {
return document.createTextNode(t);
}
// TODO(#1): the router component should create the pages lazily
function router(routes) {
let result = div();
function syncHash() {
let hashLocation = document.location.hash.split('#')[1];
if (!hashLocation) {
hashLocation = '/';
}
if (!(hashLocation in routes)) {
// TODO(#2): make the route404 customizable in the router component
const route404 = '/404';
console.assert(route404 in routes);
hashLocation = route404;
}
while (result.firstChild) {
result.removeChild(result.lastChild);
}
result.appendChild(routes[hashLocation]);
return result;
};
syncHash();
// TODO(#3): there is way to "destroy" an instance of the router to make it remove it's "hashchange" callback
window.addEventListener("hashchange", syncHash);
return result;
}