grid-apps-cmms/src/moto/webui.js

131 lines
3 KiB
JavaScript
Raw Normal View History

2021-12-29 12:55:45 -05:00
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
"use strict";
gapp.register("moto.webui", [
2021-12-29 12:55:45 -05:00
"moto.license", // dep: moto.license
"add.array", // dep: add.array
2021-12-29 12:55:45 -05:00
], (root, exports) => {
2021-12-29 12:55:45 -05:00
let nextid = 1;
function build(data, context) {
if (Array.isArray(data)) {
let html = [];
for (let d of data) {
html.appendAll(build(d, context));
}
return html;
}
let { type, attr, innr } = data;
2022-01-06 15:10:03 -05:00
// auto text content
if (typeof attr === 'string') {
attr = { _: attr };
}
let elid;
let html = [];
let text
html.push(`<${type}`);
let func = {};
for (let [key, val] of Object.entries(attr || {})) {
let tov = typeof val;
if (key === '_') {
text = val;
} else if (key === 'id') {
2022-01-20 15:42:28 -05:00
elid = val ? (tov === 'object' ? val.join('_') : val) : undefined;
} else if (tov === 'function') {
func[key] = val;
elid = elid || `_${nextid++}`;
} else if (tov === 'object') {
2022-01-02 16:30:05 -05:00
if (val.length)
html.push(` ${key}="${val.filter(v => v !== undefined).join(' ')}"`);
} else if (tov !== 'undefined') {
html.push(` ${key}="${val}"`);
}
}
if (elid) {
html.push(` id="${elid}"`);
context.push({elid, func});
}
html.push('>');
if (innr) {
let snips = [];
if (innr.length) {
for (let i of innr) {
snips.push(build(i, context));
}
} else {
2022-01-06 17:28:57 -05:00
snips.push(build(innr, context));
}
html.appendAll(snips.flat());
}
if (text !== undefined) {
html.push(text);
}
html.push(`</${type}>`);
return html;
2021-12-29 12:55:45 -05:00
}
// core html builder funtions
let h = exports({
bind: (el, data, opt = {}) => {
let ctx = [];
let html = build(data, ctx).join('');
if (opt.append) {
el.innerHTML += html;
} else {
el.innerHTML = html;
}
let map = {};
for (let bind of ctx) {
let { elid, func } = bind;
let et = $(elid);
map[elid] = et;
for (let [name, fn] of Object.entries(func)) {
et[name] = fn;
}
}
return map;
},
el: (type, attr, innr) => {
if (Array.isArray(attr)) {
innr = attr;
attr = {};
}
return { type, attr, innr };
}
});
// window ui helpers
gapp.overlay(root, {
$: (id) => {
return document.getElementById(id);
},
$d: (id, v) => {
$(id).style.display = v;
},
$h: (id, h) => {
$(id).innerHTML = h;
},
h,
estop: (evt) => {
evt.stopPropagation();
evt.preventDefault();
}
});
// add common element types
2022-01-07 01:18:35 -05:00
["a", "i", "div", "span", "label", "input", "button", "svg"].forEach(type => {
h[type] = (attr, innr) => {
return h.el(type, attr, innr);
}
});
});