um/src/app.js

53 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-05-05 00:34:27 +00:00
export default function app(opts, selector = "body") {
// initial setup
let data = {};
let view = () => null;
let actions = {};
2024-05-05 00:34:27 +00:00
// query helper
const $ = document.querySelector.bind(document);
// state helper
const state = (state) => {
if(typeof state === "object") {
data = {...data, ...state};
}
// update ui
update();
2024-05-05 00:34:27 +00:00
// return current state
return data;
}
const update = () => {
$(selector).replaceChildren(view(data, actions));
2024-05-05 00:34:27 +00:00
}
// setup view function
2024-05-05 00:34:27 +00:00
if (opts.view && typeof opts.view === "function") {
view = opts?.view;
}
// setup data object
if (opts.state && typeof opts.state === "object") {
2024-05-05 00:34:27 +00:00
// wrap data in state object
data = state(opts.state);
2024-05-05 00:34:27 +00:00
}
// setup actions object
if (opts.actions && typeof opts.actions === "object") {
actions = opts.actions;
2024-05-05 00:34:27 +00:00
}
// mount view
if (opts.view && selector) {
update();
2024-05-05 00:34:27 +00:00
}
return {
state,
actions,
2024-05-05 00:34:27 +00:00
};
}