This repository has been archived by the owner on Mar 5, 2020. It is now read-only.
/
viperhtml.js
573 lines (524 loc) · 15.7 KB
/
viperhtml.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
'use strict';
/*! (C) 2017 Andrea Giammarchi @WebReflection (MIT) */
// friendly destructuring
viper.viper = viper;
// magic entry point for most operations (bind, wire)
function viper(HTML) {
return arguments.length < 2 ?
(HTML == null || typeof HTML === 'string' ?
render.bind({}) :
('raw' in HTML ?
render.bind({})(HTML) :
wireWeakly(HTML, 'html'))) :
('raw' in HTML ?
render.bind({}) : viper.wire
).apply(null, arguments);
}
// viperHTML \o/
//
// var render = viperHTML.bind(object);
// render`
// <h1>⚡️ viperHTML ⚡️</h1>
// <p>
// ${(new Date).toLocaleString()}
// </p>
// `;
function render(template) {
var viper = vipers.get(this);
if (
!viper ||
viper.template !== template
) {
viper = upgrade.apply(this, arguments);
vipers.set(this, viper);
}
return (this instanceof Async ? this.update : update)
.apply(viper, arguments);
}
// A wire ➰ is a shortcut to relate a specific object,
// or a runtime created one, to a specific template.
//
// var render = viperHTML.wire();
// render`
// <div>Hello Wired!</div>
// `;
viper.wire = function wire(obj, type) {
return arguments.length < 1 || obj == null ?
render.bind({}) :
wireWeakly(obj, type || 'html');
};
// An asynchronous wire ➰ is a weakly referenced callback,
// to be invoked right before the template literals
// to return a rendered capable of resolving chunks.
viper.async = function getAsync(obj) {
return arguments.length < 1 ?
createAsync() :
(asyncs.get(obj) || set(asyncs, obj, createAsync()));
};
// viper.Component([initialState]) 🍻
// An overly-simplified Component class.
class Component {
handleEvent() { /* noop by default */ }
get html() { return (this.html = render.bind(this)); }
set html(value) { defineValue(this, 'html', value); }
get svg() { return (this.svg = render.bind(this)); }
set svg(value) { defineValue(this, 'svg', value); }
get state() { return (this.state = this.defaultState); }
set state(value) { defineValue(this, 'state', value); }
get defaultState() { return {}; }
setState(state) {
var target = this.state;
var source = typeof state === 'function' ? state.call(this, target) : state;
for (var key in source) target[key] = source[key];
this.render();
}
// the render must be defined when extending hyper.Component
// the render **must** return either comp.html or comp.svg wire
// render() { return this.html`<p>that's it</p>`; }
}
viper.Component = Component;
// - - - - - - - - - - - - - - - - - - - - - - -
// -------------------------
// Helpers
// -------------------------
// used to force html output
function asHTML(html) {
return {html: html};
}
// parse all comments at once and sanitize them
function comments($0, $1, $2, $3) {
return $1 + $2.replace(FIND_ATTRIBUTES, sanitizeAttributes) + $3;
}
// instrument a wire to work asynchronously
// passing along an optional resolved chunks
// interceptor callback
function createAsync() {
var
wired = new Async,
wire = render.bind(wired),
chunksReceiver
;
wired.update = function () {
this.callback = chunksReceiver;
return chunks.apply(this, arguments);
};
return function (callback) {
chunksReceiver = callback || String;
return wire;
};
}
// set a configurable, non enumerable, non writable property
function defineValue(self, key, value) {
Object.defineProperty(self, key, {configurable: true, value: value});
}
// splice 0 - length an array and join its content
function empty(array) {
return array.splice(0, array.length).join('');
}
// ensure String value and escape it
function escape(s) {
return htmlEscape(String(s));
}
// given a list of updates
// create a copy with the right update for HTML
function fixUpdates(updates) {
for (var
update,
i = 0,
length = updates.length,
out = [];
i < length; i++
) {
update = updates[i];
out.push(update === getUpdateForHTML ? update.call(this) : update);
}
return out;
}
// if an interpolated value is an Array
// return Promise or join by empty string
function getUpdateForHTML() {
return this instanceof Async ? identity : asTemplateValue;
}
// pass along a generic value
function identity(value) {
return value;
}
// use a placeholder and resolve with the right callback
function invokeAtDistance(value) {
if ('text' in value) {
return Promise.resolve(value.text).then(String).then(asTemplateValue);
} else if ('any' in value) {
return Promise.resolve(value.any).then(asTemplateValue);
} else if ('html' in value) {
return Promise.resolve(value.html).then(asHTML).then(asTemplateValue);
} else {
return Promise.resolve(invokeTransformer(value)).then(asTemplateValue);
}
}
// last attempt to transform content
function invokeTransformer(object) {
for (var key, i = 0, length = transformersKeys.length; i < length; i++) {
key = transformersKeys[i];
if (object.hasOwnProperty(key)) {
// noop is passed to respect hyperHTML API but it won't have
// any effect at distance for the time being
return transformers[key](object[key], noop);
}
}
}
// literally
function noop() {}
// multiple content joined as single string
function asTemplateValue(value, isAttribute) {
var presuf = isAttribute ? '' : createHyperComment();
switch(typeof value) {
case 'string': return presuf + escape(value) + presuf;
case 'boolean':
case 'number': return presuf + value + presuf;
case 'object':
if (value instanceof Buffer) return presuf + value + presuf;
if (value instanceof Component) return asTemplateValue(value.render(), isAttribute);
case 'undefined':
if (value == null) return presuf + '' + presuf;
default:
if (isArray(value)) {
for (var i = 0, length = value.length; i < length; i++) {
if (value[i] instanceof Component) {
value[i] = value[i].render();
}
}
return presuf + value.join('') + presuf;
}
if ('placeholder' in value) return invokeAtDistance(value);
if ('text' in value) return presuf + escape(value.text) + presuf;
if ('any' in value) return asTemplateValue(value.any, isAttribute);
if ('html' in value) return presuf + [].concat(value.html).join('') + presuf;
return asTemplateValue(invokeTransformer(value), isAttribute);
}
}
// sanitizes quotes around attributes
function sanitizeAttributes($0, $1, $2) {
return $1 + ($2 || '"') + UID + ($2 || '"');
}
// weakly relate a generic object to a genric value
function set(map, object, value) {
map.set(object, value);
return value;
}
// join a template via unique comment
// look for comments in attributes and content
// define updates to be invoked for this template
// sanitize and clean the layout too
function transform(template) {
var tagName = '';
var isCDATA = false;
var current = [];
var chunks = [];
var updates = [];
var content = new Parser({
onopentag: function (name, attributes) {
tagName = name;
current.push('<', name);
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) {
var value = attributes[key];
var isPermutation = value === UID;
var isSpecial = SPECIAL_ATTRIBUTE.test(key);
var isEvent = isPermutation && ATTRIBUTE_EVENT.test(key);
if (isPermutation) {
if (isSpecial) {
if (isEvent) {
current.push(' ', key, '="');
updates.push(updateEvent);
} else {
updates.push(updateBoolean(key));
}
} else {
current.push(' ', key, '="');
updates.push(updateAttribute);
}
chunks.push(empty(current));
if (!isSpecial || isEvent) current.push('"');
} else {
if (isSpecial && value.length === 0) {
current.push(' ', key);
} else {
var quote = value.indexOf('"') < 0 ? '"' : "'";
current.push(' ', key, '=', quote, value, quote);
}
}
}
}
current.push('>');
},
oncdatastart: function () {
current.push('<![CDATA[');
isCDATA = true;
},
oncdataend: function () {
current.push(']]>');
isCDATA = false;
},
onprocessinginstruction: function (name, data) {
current.push('<', data, '>');
},
onclosetag: function (name) {
if (!VOID_ELEMENT.test(name)) {
current.push('</', name, '>');
}
tagName = '';
},
ontext: function (text) {
var length = updates.length - 1;
switch (true) {
case isCDATA:
case /^code|input|textarea|pre$/i.test(tagName):
current.push(text);
break;
case /^script$/i.test(tagName):
current.push(minifyJS(text));
break;
case /^style$/i.test(tagName):
current.push(minifyCSS(text));
break;
default:
current.push(adoptable ? text : text.trim());
break;
}
},
oncomment: function (data) {
if (data === UID) {
chunks.push(empty(current));
updates.push(getUpdateForHTML);
} else {
current.push('<!--' + data + '-->');
}
},
onend: function () {
chunks.push(empty(current));
}
}, {
decodeEntities: false,
xmlMode: true
});
content.write(template.join(UIDC).replace(NO, comments));
content.end();
return {
chunks: chunks,
updates: updates
};
}
// same as escape but specific for attributes
function updateAttribute(s) {
return htmlEscape(String(s));
}
// return the right callback to update a boolean attribute
// after modifying the template to ignore such attribute if falsy
function updateBoolean(name) {
name = ' ' + name;
function update(value) {
switch (value) {
case true:
case 'true':
return name;
}
return '';
}
update[UID] = true;
return update;
}
// return the right callback to invoke an event
// stringifying the callback and invoking it
// to simulate a proper DOM behavior
function updateEvent(value) {
switch (typeof value) {
case 'function': return 'return (' + escape(
JS_SHORTCUT.test(value) && !JS_FUNCTION.test(value) ?
('function ' + value) :
value
) + ').call(this, event)';
case 'object': return '';
default: return escape(value || '');
}
}
// -------------------------
// Minifiers
// -------------------------
function minifyCSS() {
return csso.minify.apply(csso, arguments).css;
}
function minifyJS(code, options) {
var result = uglify.minify(code, Object.assign({
// uglify-js defaults
output: {comments: /^!/}
}, options));
return result.error ? code : result.code;
}
// -------------------------
// Template setup
// -------------------------
// resolves through promises and
// invoke a notifier per each resolved chunk
// the context will be a viper
function chunks() {
for (var
update,
out = [],
updates = this.updates,
template = this.chunks,
callback = this.callback,
all = Promise.resolve(template[0]),
chain = function (after) {
return all.then(function (through) {
notify(through);
return after;
});
},
getSubValue = function (value) {
if (isArray(value)) {
value.forEach(getSubValue);
} else {
all = chain(
Promise.resolve(value)
.then(resolveArray)
);
}
},
getValue = function (value) {
if (isArray(value)) {
var hc = Promise.resolve(createHyperComment());
all = chain(hc);
value.forEach(getSubValue);
all = chain(hc);
} else {
all = chain(
Promise.resolve(value)
.then(resolveAsTemplateValue(update))
.then(update === asTemplateValue ? identity : update)
);
}
},
notify = function (chunk) {
out.push(chunk);
callback(chunk);
},
i = 1,
length = arguments.length; i < length; i++
) {
update = updates[i - 1];
getValue(arguments[i]);
all = chain(template[i]);
}
return all.then(notify).then(function () { return out; });
}
// tweaks asTemplateValue to think the value is an Array
// but without needing to add the suffix.
// Used to place an hyper comment after a group of values has been resolved
// instead of per each resolved value.
function resolveArray(value) {
return asTemplateValue(isArray(value) ? value : [value], true);
}
// invokes at distance asTemplateValue
// passing the "isAttribute" flag
function resolveAsTemplateValue(update) {
return function (value) {
return asTemplateValue(
value,
update === updateAttribute ||
update === updateEvent ||
UID in update
);
};
}
// each known viperHTML update is
// kept as simple as possible.
// the context will be a viper
function update() {
for (var
updates = this.updates,
template = this.chunks,
i = 1,
length = arguments.length,
out = [template[0]];
i < length; i++
) {
out.push(updates[i - 1](arguments[i]), template[i]);
}
return Buffer.from(out.join(''));
}
// but the first time, it needs to be setup.
// From now on, only update(tempalte) will be called
// unless this context won't be used for other renderings.
function upgrade(template) {
var info = templates.get(template) ||
set(templates, template, transform(template));
return {
template: template,
updates: fixUpdates.call(this, info.updates),
chunks: info.chunks
};
}
// -------------------------
// Wires
// -------------------------
function wireWeakly(obj, id) {
var wire = wires.get(obj) || set(wires, obj, new Dict);
return wire[id] || (wire[id] = render.bind({}));
}
function createHyperComment() {
return adoptable ? ('<!--\x01:' + (++hyperComment).toString(36) + '-->') : '';
}
// -------------------------
// local variables
// -------------------------
var
VOID_ELEMENT = /^area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr$/i,
UID = '_viperHTML: ' + require('crypto').randomBytes(16).toString('hex') + ';',
UIDC = '<!--' + UID + '-->',
ATTRIBUTE_EVENT = /^on\S+$/,
JS_SHORTCUT = /^[a-z$_]\S*?\(/,
JS_FUNCTION = /^function\S*?\(/,
SPECIAL_ATTRIBUTE = /^(?:(?:on|allow)[a-z]+|async|autofocus|autoplay|capture|checked|controls|default|defer|disabled|formnovalidate|hidden|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected|truespeed|typemustmatch|usecache)$/,
NO = /(<[a-z]+[a-z0-9:_-]*)((?:[^\S]+[a-z0-9:_-]+(?:=(?:'.*?'|".*?"|<.+?>|\S+))?)+)([^\S]*\/?>)/gi,
FIND_ATTRIBUTES = new RegExp('([^\\S][a-z]+[a-z0-9:_-]*=)([\'"]?)' + UIDC + '\\2', 'gi'),
csso = require('csso'),
uglify = require("uglify-js"),
Parser = require('htmlparser2').Parser,
htmlEscape = require('html-escaper').escape,
templates = new Map(),
asyncs = new WeakMap(),
vipers = new WeakMap(),
wires = new WeakMap(),
isArray = Array.isArray,
transformers = {},
transformersKeys = [],
hyperComment = 0,
adoptable = false
;
// traps function bind once (useful in destructuring)
viper.bind = function bind(context) { return render.bind(context); };
viper.minify = {
css: minifyCSS,
js: minifyJS
};
viper.define = function define(transformer, callback) {
if (!(transformer in transformers)) {
transformersKeys.push(transformer);
}
transformers[transformer] = callback;
// TODO: else throw ? console.warn ? who cares ?
};
Object.defineProperty(viper, 'adoptable', {
get: function () {
return adoptable;
},
set: function (value) {
adoptable = !!value;
}
});
module.exports = viper;
// local class to easily recognize async wires
function Async() {}
// local class to easily create wires
function Dict() {}
Dict.prototype = Object.create(null);