Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example simple ad-hoc declarative ui framework
function createUiFramework() {
const isEvent = k => k.indexOf("on") === 0;
const eventName = k => k.substr(2).toLowerCase();
function attrs(el, obj) {
for (let k in obj) {
if (isEvent(k)) {
el.addEventListener(eventName(k), obj[k]);
} else if (k !== "class") {
el.setAttribute(k, obj[k]);
} else {
const classes = Array.isArray(obj[k]) ? obj[k] : [obj[k]];
el.classList.add(...classes);
}
}
return el;
}
return new Proxy(
{},
{
get(_, element) {
return function createElement(obj = {}, children = []) {
if (Array.isArray(obj)) {
children = obj;
obj = {};
}
const el = attrs(document.createElement(element), obj);
children.forEach(function(i) {
if (typeof i === "string") {
el.textContent = i;
} else {
el.appendChild(i);
}
});
return el;
};
}
}
);
}
const ui = createUiFramework();
function createConstructInputLi(cb) {
const { li, input, label } = ui;
return function(field) {
const title = field.getAttribute("title");
const slug = slugify(title);
const id = "input-" + slug;
return li([
label({ for: id }, [title]),
input({
name: id,
id,
type: field.getAttribute("type") || "text",
value: field.textContent,
required: true,
onInput(e) {
const val = e.currentTarget.value;
cb(field, val);
}
})
]);
};
}
function createConstructInputLi(cb) {
return function(field) {
const label = ce("label");
const title = field.getAttribute("title");
const slug = slugify(title);
const id = "input-" + slug;
label.setAttribute("for", id);
label.textContent = title;
const input = ce("input");
input.name = id;
input.id = id;
input.type = field.getAttribute("type") || "text";
input.value = field.textContent;
input.required = true;
const li = ce("li");
li.appendChild(label);
li.appendChild(input);
input.addEventListener("input", function(e) {
const val = e.currentTarget.value;
cb(field, val);
});
return li;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.