2024-05-05 00:34:27 +00:00
|
|
|
export default function app(opts, selector = "body") {
|
|
|
|
// initial setup
|
|
|
|
let data = {};
|
|
|
|
let view = () => null;
|
2024-05-05 00:47:34 +00:00
|
|
|
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
|
2024-05-05 00:47:34 +00:00
|
|
|
update();
|
2024-05-05 00:34:27 +00:00
|
|
|
|
|
|
|
// return current state
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
|
2024-05-05 00:47:34 +00:00
|
|
|
const update = () => {
|
|
|
|
$(selector).replaceChildren(view(data, actions));
|
2024-05-05 00:34:27 +00:00
|
|
|
}
|
|
|
|
|
2024-05-05 00:47:34 +00:00
|
|
|
// setup view function
|
2024-05-05 00:34:27 +00:00
|
|
|
if (opts.view && typeof opts.view === "function") {
|
|
|
|
view = opts?.view;
|
|
|
|
}
|
|
|
|
|
2024-05-05 00:47:34 +00:00
|
|
|
// setup data object
|
|
|
|
if (opts.state && typeof opts.state === "object") {
|
2024-05-05 00:34:27 +00:00
|
|
|
// wrap data in state object
|
2024-05-05 00:47:34 +00:00
|
|
|
data = state(opts.state);
|
2024-05-05 00:34:27 +00:00
|
|
|
}
|
|
|
|
|
2024-05-05 00:47:34 +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) {
|
2024-05-05 00:47:34 +00:00
|
|
|
update();
|
2024-05-05 00:34:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
state,
|
2024-05-05 00:47:34 +00:00
|
|
|
actions,
|
2024-05-05 00:34:27 +00:00
|
|
|
};
|
|
|
|
}
|