diff options
author | Jo-Philipp Wich <jo@mein.io> | 2018-05-28 14:56:15 +0200 |
---|---|---|
committer | Jo-Philipp Wich <jo@mein.io> | 2018-05-28 15:18:45 +0200 |
commit | 79c82237e373b9d9a101858e0cab96e4bd548f0c (patch) | |
tree | df071dea2e9f8ca0ca5efd9d69828c0182de8a03 | |
parent | 97a640c836163523f532dd87de9e9882bd375409 (diff) |
luci-base: add element creation helper to cbi.js
Add a new helper function `E()` to cbi.js which can be used to conveniently
build HTML markup.
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
-rw-r--r-- | modules/luci-base/htdocs/luci-static/resources/cbi.js | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/modules/luci-base/htdocs/luci-static/resources/cbi.js b/modules/luci-base/htdocs/luci-static/resources/cbi.js index 6c35372cdd..47eead5d8a 100644 --- a/modules/luci-base/htdocs/luci-static/resources/cbi.js +++ b/modules/luci-base/htdocs/luci-static/resources/cbi.js @@ -1566,3 +1566,75 @@ String.nobr = function() a.push(arguments[i]); return ''.nobr.apply(arguments[0], a); } + + +var dummyElem, domParser; + +function isElem(e) +{ + return (typeof(e) === 'object' && e !== null && 'nodeType' in e); +} + +function toElem(s) +{ + var elem; + + try { + domParser = domParser || new DOMParser(); + elem = domParser.parseFromString(s, 'text/html').body.firstChild; + } + catch(e) {} + + if (!elem) { + try { + dummyElem = dummyElem || document.createElement('div'); + dummyElem.innerHTML = s; + elem = dummyElem.firstChild; + } + catch (e) {} + } + + return elem || null; +} + +function E() +{ + var html = arguments[0], + attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null, + data = attr ? arguments[2] : arguments[1], + elem; + + if (isElem(html)) + elem = html; + else if (html.charCodeAt(0) === 60) + elem = toElem(html); + else + elem = document.createElement(html); + + if (!elem) + return null; + + if (attr) + for (var key in attr) + if (attr.hasOwnProperty(key)) + elem.setAttribute(key, attr[key]); + + if (typeof(data) === 'function') + data = data(elem); + + if (isElem(data)) { + elem.appendChild(data); + } + else if (Array.isArray(data)) { + for (var i = 0; i < data.length; i++) + if (isElem(data[i])) + elem.appendChild(data[i]); + else + elem.appendChild(document.createTextNode('' + data[i])); + } + else if (data !== null && data !== undefined) { + elem.innerHTML = '' + data; + } + + return elem; +} |