-
Notifications
You must be signed in to change notification settings - Fork 2
/
smvc.js
276 lines (230 loc) · 6.97 KB
/
smvc.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
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
// VirtualNode
// = { tag : string
// , properties : { property: string }
// , children : [VirtualNode]
// }
// | { text : string }
//
// Diff
// = { replace : VirtualNode }
// | { remove : true }
// | { create : VirtualNode }
// | { modify : { remove :: string[], set :: { property : value }, children :: Diff[] } }
// | { noop : true }
//
const SMVC = (function () {
function assert(predicate, ...args) {
if (!predicate) {
console.error(...args);
throw new Error("fatal");
}
}
const props = new Set([ "autoplay", "checked", "checked", "contentEditable", "controls",
"default", "hidden", "loop", "selected", "spellcheck", "value", "id", "title",
"accessKey", "dir", "dropzone", "lang", "src", "alt", "preload", "poster",
"kind", "label", "srclang", "sandbox", "srcdoc", "type", "value", "accept",
"placeholder", "acceptCharset", "action", "autocomplete", "enctype", "method",
"name", "pattern", "htmlFor", "max", "min", "step", "wrap", "useMap", "shape",
"coords", "align", "cite", "href", "target", "download", "download",
"hreflang", "ping", "start", "headers", "scope", "span" ]);
function setProperty(prop, value, el) {
if (props.has(prop)) {
el[prop] = value;
} else {
el.setAttribute(prop, value);
}
}
function listener(event) {
const el = event.currentTarget;
const handler = el._ui.listeners[event.type];
const enqueue = el._ui.enqueue;
assert(typeof enqueue == "function", "Invalid enqueue");
const msg = handler(event);
if (msg !== undefined) {
enqueue(msg);
}
}
function setListener(el, event, handle) {
assert(typeof handle == "function", "Event listener is not a function for event:", event);
if (el._ui.listeners[event] === undefined) {
el.addEventListener(event, listener);
}
el._ui.listeners[event] = handle;
}
function eventName(str) {
if (str.indexOf("on") == 0) {
return str.slice(2).toLowerCase();
}
return null;
}
// diff two virtual nodes
function diffOne(l, r) {
assert(r instanceof VirtualNode, "Expected an instance of VirtualNode, found", r);
const isText = l.text !== undefined;
if (isText) {
return l.text !== r.text
? { replace: r }
: { noop : true };
}
if (l.tag !== r.tag) {
return { replace: r };
}
const remove = [];
const set = {};
for (const prop in l.properties) {
if (r.properties[prop] === undefined) {
remove.push(prop);
}
}
for (const prop in r.properties) {
if (r.properties[prop] !== l.properties[prop]) {
set[prop] = r.properties[prop];
}
}
const children = diffList(l.children, r.children);
const noChildrenChange = children.every(e => e.noop);
const noPropertyChange =
(remove.length === 0) &&
(Array.from(Object.keys(set)).length == 0);
return (noChildrenChange && noPropertyChange)
? { noop : true }
: { modify: { remove, set, children } };
}
function diffList(ls, rs) {
assert(rs instanceof Array, "Expected an array, found", rs);
const length = Math.max(ls.length, rs.length);
return Array.from({ length })
.map((_,i) =>
(ls[i] === undefined)
? { create: rs[i] }
: (rs[i] == undefined)
? { remove: true }
: diffOne(ls[i], rs[i])
);
}
function create(enqueue, vnode) {
assert(vnode instanceof VirtualNode, "Expected an instance of VirtualNode, found", vnode);
if (vnode.text !== undefined) {
const el = document.createTextNode(vnode.text);
return el;
}
const el = document.createElement(vnode.tag);
el._ui = { listeners : {}, enqueue };
for (const prop in vnode.properties) {
const event = eventName(prop);
const value = vnode.properties[prop];
(event === null)
? setProperty(prop, value, el)
: setListener(el, event, value);
}
for (const childVNode of vnode.children) {
const child = create(enqueue, childVNode);
el.appendChild(child);
}
return el;
}
function modify(el, enqueue, diff) {
for (const prop of diff.remove) {
const event = eventName(prop);
if (event === null) {
el.removeAttribute(prop);
} else {
el._ui.listeners[event] = undefined;
el.removeEventListener(event, listener);
}
}
for (const prop in diff.set) {
const value = diff.set[prop];
const event = eventName(prop);
(event === null)
? setProperty(prop, value, el)
: setListener(el, event, value);
}
assert(diff.children.length >= el.childNodes.length, "unmatched children lengths");
apply(el, enqueue, diff.children);
}
function apply(el, enqueue, childrenDiff) {
const children = Array.from(el.childNodes);
childrenDiff.forEach((diff, i) => {
const action = Object.keys(diff)[0];
switch (action) {
case "remove":
children[i].remove();
break;
case "modify":
modify(children[i], enqueue, diff.modify);
break;
case "create": {
assert(i >= children.length, "adding to the middle of children", i, children.length);
const child = create(enqueue, diff.create);
el.appendChild(child);
break;
}
case "replace": {
const child = create(enqueue, diff.replace);
children[i].replaceWith(child);
break;
}
case "noop":
break;
default:
throw new Error("Unexpected diff option: " + Object.keys(diff));
}
});
}
class VirtualNode {
constructor(any) { Object.assign(this, any) }
}
// Create an HTML element description (a virtual node)
function h(tag, properties, children) {
assert(typeof tag === "string", "Invalid tag value:", tag);
assert(typeof properties === "object", "Expected properties object. Found:", properties);
assert(Array.isArray(children), "Expected children array. Found:", children);
return new VirtualNode({ tag, properties, children });
}
// Create a text element description (a virtual text node)
function text(content) {
return new VirtualNode({ text: content });
}
// Start managing the contents of an HTML element.
function init(root, initialState, update, view) {
let state = initialState; // client application state
let nodes = []; // virtual DOM nodes
let queue = []; // msg queue
function enqueue(msg) {
queue.push(msg);
}
// draws the current state
function draw() {
let newNodes = view(state);
apply(root, enqueue, diffList(nodes, newNodes));
nodes = newNodes;
}
function updateState() {
if (queue.length > 0) {
let msgs = queue;
queue = [];
msgs.forEach(msg => {
try {
state = update(state, msg, enqueue);
} catch (e) {
console.error(e);
}
});
draw();
}
window.requestAnimationFrame(updateState);
}
draw();
updateState();
return { enqueue };
}
return { init, h, text };
})();
if (typeof define !== 'undefined' && define.amd) { // AMD
define([], function () { return SMVC })
} else if (typeof module !== 'undefined' && module.exports) { // CommonJS
module.exports = SMVC
} else if (typeof window !== 'undefined') { // Script tag
window.SMVC = SMVC
}