Files
tiny-worlds/web/widgets.mjs
T

177 lines
6.9 KiB
JavaScript

// web/widgets.mjs -- the small factories the views share.
//
// Three patterns that were hand-copied per use, now one each:
// - armedButton: the two-click confirm (no JS confirm() -- it blocks
// the embedded pane; every destructive act is armed instead)
// - paneEditor: the status/agenda pattern -- a body line, an edit
// button, an inline editor; the section shell stays in index.html
// - modelsBox: the per-run player/housekeeper selects over the
// upstream listing; setup and the play aside each carry one
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { render } from './router.mjs';
// two-click confirm -- the second click within 5s fires; anything
// else disarms. Each button owns its own arm state.
/** @param {HTMLElement} btn @param {{ label: string, confirm: string, fire: () => Promise<void> }} opts */
export function armedButton(btn, { label, confirm, fire }) {
/** @type {?ReturnType<typeof setTimeout>} */ let timer = null;
btn.addEventListener('click', async () => {
if (timer === null) {
btn.textContent = confirm;
timer = setTimeout(() => { timer = null; btn.textContent = label; }, 5000);
return;
}
clearTimeout(timer);
timer = null;
btn.textContent = label;
await fire();
});
}
// a pane: body line + edit button + inline editor. save(items)
// resolves on success and throws on failure -- a failed save keeps
// the editor open, nothing was changed. setEditable(false) is the
// spectator state: no edit button, an open editor cancels.
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[], save: (items: string[]) => Promise<unknown> }} PaneOpts */
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[] }} Pane */
/** @param {PaneOpts} opts @returns {Pane} */
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body;
const editBtn = el('button', null, 'edit');
(/** @type {HTMLElement} */ (sec.querySelector('.pane-head'))).appendChild(editBtn);
const editor = el('div', 'pane-editor');
editor.hidden = true;
const area = /** @type {HTMLTextAreaElement} */ (el('textarea'));
area.rows = rows;
area.placeholder = placeholder;
const actions = el('div', 'pane-editor-actions');
const saveBtn = el('button', null, 'save');
const cancelBtn = el('button', null, 'cancel');
actions.appendChild(saveBtn);
actions.appendChild(cancelBtn);
editor.appendChild(area);
editor.appendChild(actions);
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
/** @type {string[]} */ let items = [];
let mayEdit = false;
let open = false;
const sync = () => {
bodyEl.hidden = open;
editBtn.hidden = open || !mayEdit;
editor.hidden = !open;
};
const renderBody = () => {
bodyEl.textContent = items.length ? format(items) : empty;
bodyEl.classList.toggle('empty', !items.length);
};
const openEditor = () => {
area.value = toText(items);
open = true;
sync();
area.focus();
};
const cancel = () => { open = false; sync(); };
const doSave = async () => {
const next = fromText(area.value);
try {
await save(next);
} catch (e) {
banner(e.message);
return; // stay in the editor -- nothing was changed
}
items = next;
cancel();
render(); // the server's truth re-renders the panes
};
editBtn.addEventListener('click', openEditor);
cancelBtn.addEventListener('click', cancel);
saveBtn.addEventListener('click', doSave);
return {
set(next) { items = next ?? []; renderBody(); },
setEditable(ok) { mayEdit = ok; cancel(); },
reset() { cancel(); },
get items() { return items; },
};
}
// the upstream model listing, fetched once per session -- a live
// /models call every render would hammer the endpoint for a list
// that rarely changes
/** @type {?string[]} */ let cachedModels = null;
/** @returns {Promise<string[]>} */
export async function modelList() {
if (!cachedModels) cachedModels = /** @type {string[]} */ (await api('/models').catch(() => []));
return cachedModels;
}
// A select's "" value means "deployment default"; a current override
// missing from the listing stays selectable, so a stale pick never
// silently rewrites itself.
/** @param {HTMLSelectElement} sel @param {?string} current @param {string[]} list @param {?string} [def] */
function fillSelect(sel, current, list, def) {
sel.textContent = '';
/** @param {string} v @param {string} label */
const mk = (v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
mk('', `deployment default${def ? ` -- ${def}` : ' (unset)'}`);
const opts = [...list];
if (current && !opts.includes(current)) opts.push(current);
for (const m of opts) mk(m, m);
sel.value = current ?? '';
}
// the models box: player/housekeeper selects + save, posting the
// per-run overrides. The mount keeps its id -- the CSS panels it.
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';
root.appendChild(el('h2', null, title));
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper ');
hField.appendChild(houseSel);
root.appendChild(pField);
root.appendChild(hField);
const saveBtn = el('button', null, 'save models');
const saveState = el('span', 'save-state');
const actions = el('div', 'form-actions');
actions.appendChild(saveBtn);
actions.appendChild(saveState);
root.appendChild(actions);
saveBtn.addEventListener('click', async () => {
try {
await api(`/runs/${state.runId}/model`, {
method: 'POST',
body: { player: playerSel.value || null, housekeeper: houseSel.value || null },
});
saveState.textContent = 'saved';
} catch (e) {
banner(e.message);
saveState.textContent = 'not saved';
}
});
return {
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {string[]} list */
fill(models, defaults, list) {
fillSelect(playerSel, models?.player ?? null, list, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper);
saveState.textContent = '';
},
};
}