forked from MithrilJS/mithril-node-render
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·107 lines (90 loc) · 2.5 KB
/
index.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
'use strict';
var VOID_TAGS = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr',
'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
function isArray(thing) {
return Object.prototype.toString.call(thing) === '[object Array]';
}
function camelToDash(str) {
return str.replace(/\W+/g, '-')
.replace(/([a-z\d])([A-Z])/g, '$1-$2');
}
// shameless stolen from https://github.com/punkave/sanitize-html
function escapeHtml(s, replaceDoubleQuote) {
if (s === 'undefined') {
s = '';
}
if (typeof(s) !== 'string') {
s = s + '';
}
s = s.replace(/\&/g, '&').replace(/</g, '<').replace(/\>/g, '>');
if (replaceDoubleQuote) {
return s.replace(/\"/g, '"');
}
return s;
}
function createAttrString(attrs) {
if (!attrs || !Object.keys(attrs).length) {
return '';
}
return Object.keys(attrs).map(function(name) {
if (typeof attrs[name] === 'function') {
return;
}
if (typeof attrs[name] === 'boolean') {
return attrs[name] ? ' ' + name : '';
}
if (name === 'style') {
var styles = attrs.style;
if (typeof styles === 'object') {
styles = Object.keys(styles).map(function(property) {
return [camelToDash(property).toLowerCase(), styles[property]].join(':');
}).join(';');
}
return ' style="' + escapeHtml(styles, true) + '"';
}
return ' ' + escapeHtml(name === 'className' ? 'class' : name) + '="' + escapeHtml(attrs[name], true) + '"';
}).join('');
}
function createChildrenContent(view) {
if(isArray(view.children) && !view.children.length) {
return '';
}
return render(view.children);
}
function render(view) {
var type = typeof view;
if (type === 'string') {
return escapeHtml(view);
}
if(type === 'number' || type === 'boolean') {
return view;
}
if (!view) {
return '';
}
if (isArray(view)) {
return view.map(render).join('');
}
//compontent
if (view.view) {
var scope = view.controller ? new view.controller : {};
var result = render(view.view(scope));
if (scope.onunload) {
scope.onunload();
}
return result;
}
if (view.$trusted) {
return '' + view;
}
var children = createChildrenContent(view);
if (!children && VOID_TAGS.indexOf(view.tag.toLowerCase()) >= 0) {
return '<' + view.tag + createAttrString(view.attrs) + '>';
}
return [
'<', view.tag, createAttrString(view.attrs), '>',
children,
'</', view.tag, '>',
].join('');
}
module.exports = render;