UNPKG

2.17 kBJavaScriptView Raw
1var document = require('global/document')
2var hyperx = require('hyperx')
3var morphdom = require('morphdom')
4
5var SET_ATTR_PROPS = {
6 class: 1,
7 value: 1
8}
9var BOOL_PROPS = {
10 autofocus: 1,
11 checked: 1,
12 defaultChecked: 1,
13 disabled: 1,
14 formNoValidate: 1,
15 indeterminate: 1,
16 readOnly: 1,
17 required: 1,
18 willValidate: 1
19}
20
21var hx = hyperx(function createElement (tag, props, children) {
22 var el = document.createElement(tag)
23 for (var p in props) {
24 if (props.hasOwnProperty(p)) {
25 var val = props[p]
26 // If a property is boolean, set itself to the key
27 if (BOOL_PROPS[p]) {
28 if (val === 'true') val = p
29 else if (val === 'false') continue
30 }
31 // If a property prefers setAttribute instead
32 if (SET_ATTR_PROPS[p] || BOOL_PROPS[p]) {
33 el.setAttribute(p, val)
34 } else {
35 el[p] = val
36 }
37 }
38 }
39 function appendChild (childs) {
40 if (!Array.isArray(childs)) return
41 for (var i = 0; i < childs.length; i++) {
42 var node = childs[i]
43 if (Array.isArray(node)) {
44 appendChild(node)
45 continue
46 }
47
48 // TODO: Escaping?
49
50 if (typeof node === 'number' ||
51 typeof node === 'boolean' ||
52 node instanceof Date ||
53 node instanceof RegExp) {
54 node = node.toString()
55 }
56
57 if (typeof node === 'string') {
58 node = document.createTextNode(node)
59 }
60
61 if (node && node.nodeName && node.nodeType) {
62 el.appendChild(node)
63 }
64 }
65 }
66 appendChild(children)
67
68 // TODO: Validation checks
69 // TODO: Check for a11y things
70
71 return el
72})
73
74// TODO: SVG Support
75
76var id = 0
77
78module.exports = function bel () {
79 var el = hx.apply(this, arguments)
80 if (!el.id) {
81 el.id = 'e' + id
82 id += 1
83 }
84 el.update = function (newel) {
85 if (typeof newel === 'function') {
86 newel = newel()
87 }
88 // TODO: Someday eliminate the need for this
89 // We need to look up the actual element in the DOM because a parent element
90 // could have called .update() and replaced the child node
91 el = document.getElementById(el.id)
92 newel.id = el.id
93 morphdom(el, newel)
94 }
95 return el
96}