-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathjsonml-html.js
More file actions
764 lines (671 loc) · 19.6 KB
/
jsonml-html.js
File metadata and controls
764 lines (671 loc) · 19.6 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
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
/*
jsonml-html.js
JsonML to HTML utility
Created: 2006-11-09-0116
Modified: 2012-11-24-1051
Copyright (c)2006-2012 Stephen M. McKamey
Distributed under The MIT License: http://jsonml.org/license
This file ensures a global JsonML object adding these methods:
JsonML.toHTML(JsonML, filter)
This method produces a tree of DOM elements from a JsonML tree. The
array must not contain any cyclical references.
The optional filter parameter is a function which can filter and
transform the results. It receives each of the DOM nodes, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted.
This is useful for binding unobtrusive JavaScript to the generated
DOM elements.
Example:
// Parses the structure. If an element has a specific CSS value then
// takes appropriate action: Remove from results, add special event
// handlers, or bind to a custom component.
var myUI = JsonML.toHTML(myUITemplate, function (elem) {
if (elem.className.indexOf('Remove-Me') >= 0) {
// this will remove from resulting DOM tree
return null;
}
if (elem.tagName && elem.tagName.toLowerCase() === 'a' &&
elem.className.indexOf('External-Link') >= 0) {
// this is the equivalent of target='_blank'
elem.onclick = function(evt) {
window.open(elem.href); return false;
};
} else if (elem.className.indexOf('Fancy-Widgit') >= 0) {
// bind to a custom component
FancyWidgit.bindDOM(elem);
}
return elem;
});
JsonML.toHTMLText(JsonML)
Converts JsonML to HTML text
// Implement onerror to handle any runtime errors while binding:
JsonML.onerror = function (ex, jml, filter) {
// display inline error message
return document.createTextNode('['+ex+']');
};
*/
const JsonML = {};
if (typeof document !== 'undefined') {
(function (JsonML, document) {
'use strict';
/**
* Attribute name map
*
* @private
* @constant
* @type {Object.<string>}
*/
var ATTR_MAP = {
'accesskey': 'accessKey',
'bgcolor': 'bgColor',
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'checked': 'defaultChecked',
'class': 'className',
'colspan': 'colSpan',
'contenteditable': 'contentEditable',
'defaultchecked': 'defaultChecked',
'for': 'htmlFor',
'formnovalidate': 'formNoValidate',
'hidefocus': 'hideFocus',
'ismap': 'isMap',
'maxlength': 'maxLength',
'novalidate': 'noValidate',
'readonly': 'readOnly',
'rowspan': 'rowSpan',
'spellcheck': 'spellCheck',
'tabindex': 'tabIndex',
'usemap': 'useMap',
'willvalidate': 'willValidate'
// can add more attributes here as needed
};
/**
* Attribute duplicates map
*
* @private
* @constant
* @type {Object.<string>}
*/
var ATTR_DUP = {
'enctype': 'encoding',
'onscroll': 'DOMMouseScroll'
// can add more attributes here as needed
};
/**
* Attributes to be set via DOM
*
* @private
* @constant
* @type {Object.<number>}
*/
var ATTR_DOM = {
'autocapitalize': 1,
'autocomplete': 1,
'autocorrect': 1
// can add more attributes here as needed
};
/**
* Boolean attribute map
*
* @private
* @constant
* @type {Object.<number>}
*/
var ATTR_BOOL = {
'async': 1,
'autofocus': 1,
'checked': 1,
'defaultchecked': 1,
'defer': 1,
'disabled': 1,
'formnovalidate': 1,
'hidden': 1,
'indeterminate': 1,
'ismap': 1,
'multiple': 1,
'novalidate': 1,
'readonly': 1,
'required': 1,
'spellcheck': 1,
'willvalidate': 1
// can add more attributes here as needed
};
/**
* Leading SGML line ending pattern
*
* @private
* @constant
* @type {RegExp}
*/
var LEADING = /^[\r\n]+/;
/**
* Trailing SGML line ending pattern
*
* @private
* @constant
* @type {RegExp}
*/
var TRAILING = /[\r\n]+$/;
/**
* @private
* @const
* @type {number}
*/
var NUL = 0;
/**
* @private
* @const
* @type {number}
*/
var FUN = 1;
/**
* @private
* @const
* @type {number}
*/
var ARY = 2;
/**
* @private
* @const
* @type {number}
*/
var OBJ = 3;
/**
* @private
* @const
* @type {number}
*/
var VAL = 4;
/**
* @private
* @const
* @type {number}
*/
var RAW = 5;
/**
* Wraps a data value to maintain as raw markup in output
*
* @private
* @this {Markup}
* @param {string} value The value
* @constructor
*/
function Markup(value) {
/**
* @type {string}
* @const
* @protected
*/
this.value = value;
}
/**
* Renders the value
*
* @public
* @ignore
* @override
* @this {Markup}
* @return {string} value
*/
Markup.prototype.toString = function () {
return this.value;
};
/**
* @ignore
* @param {string} value
* @return {Markup}
*/
JsonML.raw = function (value) {
return new Markup(value);
};
/**
* @ignore
* @param {*} value
* @return {boolean}
*/
var isMarkup = JsonML.isRaw = function (value) {
return (value instanceof Markup);
};
/**
* Determines if the value is an Array
*
* @private
* @param {*} val the object being tested
* @return {boolean}
*/
var isArray = Array.isArray || function (val) {
return (val instanceof Array);
};
/**
* Determines if the value is a function
*
* @private
* @param {*} val the object being tested
* @return {boolean}
*/
function isFunction(val) {
return (typeof val === 'function');
}
/**
* Determines the type of the value
*
* @private
* @param {*} val the object being tested
* @return {number}
*/
function getType(val) {
switch (typeof val) {
case 'object':
return !val ? NUL : (isArray(val) ? ARY : (isMarkup(val) ? RAW : ((val instanceof Date) ? VAL : OBJ)));
case 'function':
return FUN;
case 'undefined':
return NUL;
default:
return VAL;
}
}
/**
* Creates a DOM element
*
* @private
* @param {string} tag The element's tag name
* @return {Node}
*/
var createElement = function (tag) {
if (!tag) {
// create a document fragment to hold multiple-root elements
if (document.createDocumentFragment) {
return document.createDocumentFragment();
}
tag = '';
} else if (tag.charAt(0) === '!') {
return document.createComment(tag === '!' ? '' : tag.substr(1) + ' ');
}
if (tag.toLowerCase() === 'style' && document.createStyleSheet) {
// IE requires this interface for styles
return document.createStyleSheet();
}
return document.createElement(tag);
};
/**
* Adds an event handler to an element
*
* @private
* @param {Node} elem The element
* @param {string} name The event name
* @param {function(Event)} handler The event handler
*/
var addHandler = function (elem, name, handler) {
if (name.substr(0, 2) === 'on') {
name = name.substr(2);
}
switch (typeof handler) {
case 'function':
if (elem.addEventListener) {
// DOM Level 2
elem.addEventListener(name, handler, false);
} else if (elem.attachEvent && getType(elem[name]) !== NUL) {
// IE legacy events
elem.attachEvent('on' + name, handler);
} else {
// DOM Level 0
var old = elem['on' + name] || elem[name];
elem['on' + name] = elem[name] = !isFunction(old) ? handler :
function (e) {
return (old.call(this, e) !== false) && (handler.call(this, e) !== false);
};
}
break;
case 'string':
// inline functions are DOM Level 0
/*jslint evil:true */
elem['on' + name] = new Function('event', handler);
/*jslint evil:false */
break;
}
};
/**
* Apply styles to element
*
* @public
* @ignore
* @param {Node} elem The element
* @param {Object} css styles object
* @return {Node}
*/
var applyStyles = JsonML.applyStyles = function (elem, css) {
for (var key in css) {
if (css.hasOwnProperty(key)) {
elem.style[key] = css[key];
}
}
return elem;
};
/**
* Appends an attribute to an element
*
* @private
* @param {Node} elem The element
* @param {Object} attr Attributes object
* @return {Node}
*/
var addAttributes = function (elem, attr) {
if (attr.name && document.attachEvent && !elem.parentNode) {
try {
// IE fix for not being able to programatically change the name attribute
var alt = createElement('<' + elem.tagName + ' name="' + attr.name + '">');
// fix for Opera 8.5 and Netscape 7.1 creating malformed elements
if (elem.tagName === alt.tagName) {
elem = alt;
}
} catch (ex) { }
}
// for each attributeName
for (var name in attr) {
if (attr.hasOwnProperty(name)) {
// attributeValue
var value = attr[name],
type = getType(value);
if (name) {
if (type === NUL) {
value = '';
type = VAL;
}
name = ATTR_MAP[name.toLowerCase()] || name;
if (name === '$') {
value(elem);
}
else if (name == 'className') {
if (isArray(value)) {
for (var index = 0; index < value.length; index += 1) {
elem.className += " " + value[index];
}
} else {
elem.className += " " + value;
}
}
else if (name === 'style') {
if (getType(elem.style.cssText) !== NUL) {
if (typeof value == "string") {
elem.style.cssText = value;
} else {
applyStyles(elem, value);
}
} else {
elem.style = value;
}
} else if (name.substr(0, 2) === 'on') {
addHandler(elem, name, value);
// also set duplicated events
name = ATTR_DUP[name];
if (name) {
addHandler(elem, name, value);
}
} else if (!ATTR_DOM[name.toLowerCase()] && (type !== VAL || name.charAt(0) === '$' || getType(elem[name]) !== NUL || getType(elem[ATTR_DUP[name]]) !== NUL)) {
// direct setting of existing properties
elem[name] = value;
// also set duplicated properties
name = ATTR_DUP[name];
if (name) {
elem[name] = value;
}
} else if (ATTR_BOOL[name.toLowerCase()]) {
if (value) {
// boolean attributes
elem.setAttribute(name, name);
// also set duplicated attributes
name = ATTR_DUP[name];
if (name) {
elem.setAttribute(name, name);
}
}
} else {
// http://www.quirksmode.org/dom/w3c_core.html#attributes
// custom and 'data-*' attributes
elem.setAttribute(name, value);
// also set duplicated attributes
name = ATTR_DUP[name];
if (name) {
elem.setAttribute(name, value);
}
}
}
}
}
return elem;
};
/**
* Appends a child to an element
*
* @private
* @param {Node} elem The parent element
* @param {Node} child The child
*/
var appendDOM = JsonML.appendDOM = function (elem, child) {
if (child) {
var tag = (elem.tagName || '').toLowerCase();
if (elem.nodeType === 8) { // comment
if (child.nodeType === 3) { // text node
elem.nodeValue += child.nodeValue;
}
} else if (tag === 'table' && elem.tBodies) {
if (!child.tagName) {
// must unwrap documentFragment for tables
if (child.nodeType === 11) {
while (child.firstChild) {
appendDOM(elem, child.removeChild(child.firstChild));
}
}
return;
}
// in IE must explicitly nest TRs in TBODY
var childTag = child.tagName.toLowerCase();// child tagName
if (childTag && childTag !== 'tbody' && childTag !== 'thead') {
// insert in last tbody
var tBody = elem.tBodies.length > 0 ? elem.tBodies[elem.tBodies.length - 1] : null;
if (!tBody) {
tBody = createElement(childTag === 'th' ? 'thead' : 'tbody');
elem.appendChild(tBody);
}
tBody.appendChild(child);
} else if (elem.canHaveChildren !== false) {
elem.appendChild(child);
}
} else if (tag === 'style' && document.createStyleSheet) {
// IE requires this interface for styles
elem.cssText = child;
} else if (elem.canHaveChildren !== false) {
elem.appendChild(child);
} else if (tag === 'object' &&
child.tagName && child.tagName.toLowerCase() === 'param') {
// IE-only path
try {
elem.appendChild(child);
} catch (ex1) { }
try {
if (elem.object) {
elem.object[child.name] = child.value;
}
} catch (ex2) { }
}
}
};
/**
* Tests a node for whitespace
*
* @private
* @param {Node} node The node
* @return {boolean}
*/
var isWhitespace = function (node) {
return !!node && (node.nodeType === 3) && (!node.nodeValue || !/\S/.exec(node.nodeValue));
};
/**
* Trims whitespace pattern from the text node
*
* @private
* @param {Node} node The node
*/
var trimPattern = function (node, pattern) {
if (!!node && (node.nodeType === 3) && pattern.exec(node.nodeValue)) {
node.nodeValue = node.nodeValue.replace(pattern, '');
}
};
/**
* Removes leading and trailing whitespace nodes
*
* @private
* @param {Node} elem The node
*/
var trimWhitespace = function (elem) {
if (elem) {
while (isWhitespace(elem.firstChild)) {
// trim leading whitespace text nodes
elem.removeChild(elem.firstChild);
}
// trim leading whitespace text
trimPattern(elem.firstChild, LEADING);
while (isWhitespace(elem.lastChild)) {
// trim trailing whitespace text nodes
elem.removeChild(elem.lastChild);
}
// trim trailing whitespace text
trimPattern(elem.lastChild, TRAILING);
}
};
/**
* Converts the markup to DOM nodes
*
* @private
* @param {string|Markup} value The node
* @return {Node}
*/
var toDOM = function (value) {
var wrapper = createElement('div');
wrapper.innerHTML = '' + value;
// trim extraneous whitespace
trimWhitespace(wrapper);
// eliminate wrapper for single nodes
if (wrapper.childNodes.length === 1) {
return wrapper.firstChild;
}
// create a document fragment to hold elements
var frag = createElement('');
while (wrapper.firstChild) {
frag.appendChild(wrapper.firstChild);
}
return frag;
};
/**
* Default error handler
* @ignore
* @param {Error} ex
* @return {Node}
*/
var onError = function (ex) {
return document.createTextNode('[' + ex + ']');
};
/* override this to perform custom error handling during binding */
JsonML.onerror = null;
/**
* also used by JsonML.BST
* @ignore
* @param {Node} elem
* @param {*} jml
* @param {function} filter
* @return {Node}
*/
var patch = JsonML.patch = function (elem, jml, filter) {
for (var i = 1; i < jml.length; i += 1) {
if (isArray(jml[i]) || 'string' === typeof jml[i]) {
// append children
appendDOM(elem, toHTML(jml[i], filter));
} else if (isMarkup(jml[i])) {
appendDOM(elem, toDOM(jml[i].value));
} else if ('object' === typeof jml[i] && jml[i] !== null && elem.nodeType === 1) {
// add attributes
elem = addAttributes(elem, jml[i]);
}
}
return elem;
};
/**
* Main builder entry point
* @ignore
* @param {string|array} jml
* @param {function} filter
* @return {Node}
*/
var toHTML = JsonML.toHTML = function (jml, filter) {
try {
if (!jml) {
return null;
}
if ('string' === typeof jml) {
return document.createTextNode(jml);
}
if (isMarkup(jml)) {
return toDOM(jml.value);
}
if (!isArray(jml) || ('string' !== typeof jml[0])) {
throw new SyntaxError('invalid JsonML');
}
var tagName = jml[0]; // tagName
if (!tagName) {
// correctly handle a list of JsonML trees
// create a document fragment to hold elements
var frag = createElement('');
for (var i = 1; i < jml.length; i += 1) {
appendDOM(frag, toHTML(jml[i], filter));
}
// trim extraneous whitespace
trimWhitespace(frag);
// eliminate wrapper for single nodes
if (frag.childNodes.length === 1) {
return frag.firstChild;
}
return frag;
}
if (tagName.toLowerCase() === 'style' && document.createStyleSheet) {
// IE requires this interface for styles
patch(document.createStyleSheet(), jml, filter);
// in IE styles are effective immediately
return null;
}
var elem = patch(createElement(tagName), jml, filter);
// trim extraneous whitespace
trimWhitespace(elem);
return (elem && isFunction(filter)) ? filter(elem) : elem;
} catch (ex) {
try {
// handle error with complete context
var err = isFunction(JsonML.onerror) ? JsonML.onerror : onError;
return err(ex, jml, filter);
} catch (ex2) {
return document.createTextNode('[' + ex2 + ']');
}
}
};
/**
* Not super efficient.
* TODO: port render.js from DUEL
* @ignore
* @param {string|array} jml JsonML structure
* @return {string} HTML text
*/
JsonML.toHTMLText = function (jml, filter) {
var elem = toHTML(jml, filter);
if (elem.outerHTML) {
return elem.outerHTML;
}
var parent = createElement('div');
parent.appendChild(elem);
var html = parent.innerHTML;
parent.removeChild(elem);
return html;
};
})(JsonML, document);
}
export default JsonML;