-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom-helper.js
86 lines (73 loc) · 2.4 KB
/
dom-helper.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
export default (doc, customRenderers = {}) => {
const adjustKey = (key) => {
if (key.toLowerCase() === 'classname') {
key = 'class'
}
return key
}
const getCustomTypeRenderer = (renderers, type) => {
const renderer = renderers[type]
if (!Boolean(renderer)) {
throw new Error(`No renderer specified for type ${type}.
Pass customRenderers object with key of ${type} and function as value that is capable of rendering element type.`)
}
return renderer
}
const createEl = (tag, attrs, content, children) => {
var el = doc.createElement(tag)
if (attrs) {
Object.keys(attrs).forEach(key => {
if (typeof attrs[key] !== 'function') {
el.setAttribute(adjustKey(key), attrs[key])
} else {
if (!el.events) {
el.events = {}
}
el.events[key] = attrs[key]
el.addEventListener(key, function(ev) {
attrs[key](ev, this)
})
}
})
}
if (content) {
el.appendChild(
doc.createTextNode(content))
}
if (children) {
children.forEach((child, i) => {
if (Array.isArray(child)) {
child.map(subChild => {
el.appendChild(subChild)
})
} else {
if (Boolean(child['render_type'])) {
const renderer = getCustomTypeRenderer(customRenderers, child['render_type'])
el.appendChild(renderer(child, i))
} else if (typeof child === 'string') {
el.appendChild(doc.createTextNode(child))
} else {
el.appendChild(child)
}
}
})
}
return el
}
var methods = {}
new Array('span', 'a', 'p', 'div', 'h1', 'h2', 'h3', 'strong', 'li', 'ul', 'img', 'form', 'input', 'label', 'textarea', 'button').forEach(function(tagName) {
methods[tagName] = function(attrs, content, children) {
if (Array.isArray(content)) {
children = content
content = null
} else if (typeof content !== 'string') {
children = Array.prototype.slice.apply(arguments).slice(1, arguments.length)
content = null
} else if (typeof content === 'string') {
children = Array.prototype.slice.apply(arguments).slice(2, arguments.length)
}
return createEl(tagName, attrs, content, children)
}
})
return Object.create(Object.assign(doc, methods), { doc: {value: doc} })
}