-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.ts
More file actions
289 lines (220 loc) · 5.79 KB
/
component.ts
File metadata and controls
289 lines (220 loc) · 5.79 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { Route } from './route';
import { Router } from './router';
import { RouteableRouteGroup, RouteGroup } from './route-group';
export class Component {
static directives: {
[ key: string ]: (element: Node, value, tag: string, attributes, ...content) => void
} = {};
private timers = {
intervals: [],
timeouts: []
};
loaded = true;
route: Route;
router: Router;
params: any;
parent?: Component;
rootNode: Node;
child?: Component;
childNode: Node;
get activeRoute() { return this.route; }
onload(): Promise<void> | void {}
onunload(): Promise<void> | void {}
onerror(error): Promise<void> | void {}
onparameterchange(params): Promise<void> | void {}
onchildchange(params, route: Route, component: Component): Promise<void> | void {}
renderLoader() {
return document.createComment(`* ${this.constructor.name} *`);
}
renderError(error: Error) {
console.error(error);
return this.createElement('section', null,
this.createElement('b', null, error.message),
this.createElement('pre', null, error.stack)
);
}
render(child?: Node): Node {
// create placeholder render
return this.createElement(
'component',
{ type: this.constructor.name },
'< ', this.constructor.name,
`(${Object.keys(this.params).map(key => `${key}: ${JSON.stringify(this.params[key])}`).join(', ')})`,
'{', child, '}',
' >'
);
}
createTimeout(handler: Function, time: number) {
const timer = setTimeout(() => {
this.timers.timeouts.splice(this.timers.timeouts.indexOf(timer), 1);
handler();
}, time);
this.timers.timeouts.push(timer);
}
createInterval(handler: Function, time: number, runOnStart = false) {
if (runOnStart) {
handler();
}
const timer = setTimeout(() => {
handler();
}, time);
this.timers.intervals.push(timer);
}
clearTimers() {
for (let timer of this.timers.timeouts) {
clearTimeout(timer);
}
this.timers.timeouts = [];
for (let timer of this.timers.intervals) {
clearInterval(timer);
}
this.timers.intervals = [];
}
update(child?: Node) {
if (arguments.length == 0) {
child = this.childNode;
} else {
this.childNode = child;
}
if (child?.parentElement) {
child.parentElement.removeChild(child);
}
const element = this.render(child);
if (this.rootNode?.parentNode) {
this.rootNode.parentNode.replaceChild(element, this.rootNode);
}
if (this.parent) {
this.parent.childNode = element;
}
this.rootNode = element;
return element;
}
async reload() {
await this.onload();
if (this.child) {
await this.child.reload();
}
await this.update();
}
async unload() {
this.loaded = false;
// stop all timers
for (let interval of this.timers.intervals) {
clearInterval(interval);
}
for (let timeout of this.timers.timeouts) {
clearTimeout(timeout);
}
if (this.child) {
await this.child.unload();
}
await this.onunload();
}
static createElement(tag, attributes, ...contents) {
throw 'cannot create element from uncompiled source';
}
createElement(tag, attributes, ...contents) {
const element = document.createElement(tag);
element.hostingComponent = this;
for (let item of contents) {
this.addToElement(item, element);
}
for (let key in attributes) {
if (key[0] != '_') {
const value = attributes[key];
if (key in Component.directives) {
Component.directives[key](element, value, tag, attributes, contents);
} else if (value !== null) {
element.setAttribute(key, value);
}
}
}
return element;
}
static accessor(get: Function, set: Function) {
return {
get() {
return get()
},
set(value) {
set(value);
}
}
}
private addToElement(item, element: Node) {
if (item instanceof Node) {
element.appendChild(item);
} else if (Array.isArray(item)) {
for (let child of item) {
this.addToElement(child, element);
}
} else if (item instanceof Component) {
const placeholder = item.renderLoader();
element.appendChild(placeholder);
item.parent = this;
item.route = this.route;
item.router = this.router;
(async () => {
await item.onload();
const child = item.render();
item.rootNode = child;
element.replaceChild(child, placeholder);
})();
} else if (item !== false && item !== undefined && item !== null) {
element.appendChild(document.createTextNode(item));
}
}
async host(parent: Node) {
await this.onload();
const root = this.render();
this.rootNode = root;
this.parent = null;
parent.appendChild(root);
}
navigate(path: string) {
Router.global.navigate(path, this);
return document.createComment(path);
}
remove() {
this.rootNode?.parentElement?.removeChild(this.rootNode);
}
static updating(handler: (index?: number) => string | number, interval) {
const element = document.createTextNode(`${handler(0)}`);
let i = 0;
setInterval(() => {
element.textContent = `${handler(++i)}`;
}, interval);
return element;
}
static route(path: string, component: RouteGroup) {
const tree: RouteableRouteGroup = {
component: this,
children: {
[path]: component
},
route(path: string, component: RouteGroup): RouteableRouteGroup {
tree.children[path] = component;
return tree;
}
}
return tree;
}
updateParameters(parameters) {
// update current parameter list
for (let key in parameters) {
if (parameters[key] === null) {
delete this.params[key];
} else {
this.params[key] = `${parameters[key]}`;
}
}
// re-generate parameter string
let path = this.route.matchingPath;
for (let key in this.params) {
path = path.replace(`:${key}`, this.params[key]);
}
this.route.path = path;
// push the state to the browser (will not call `onhashchange`)
history.pushState(null, null, `#${this.route.fullPath}`);
}
}