Files
tiny-worlds/web/widgets.mjs
T

241 lines
11 KiB
JavaScript
Raw Normal View History

// 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
2026-11-16 21:32:02 +00:00
// registry plus the sampling knobs (knobs.mjs owns the knob row
// and its definitions table); 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';
2026-11-16 21:32:02 +00:00
import { knobsBox } from './knobs.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
2026-11-15 22:37:06 +00:00
// not-the-owner 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; },
};
}
2026-11-16 21:32:02 +00:00
// the model registry, fetched once per session -- the selectors read
// the saved registry, never the live provider (discovery is the op's
// manual act; a listing fetch every render would hammer the endpoint
// for a list that rarely changes)
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let cachedRegistry = null;
/** @returns {Promise<import('./shapes.mjs').ModelsRegistryResponse>} */
export async function modelList() {
2026-11-16 21:32:02 +00:00
if (!cachedRegistry) cachedRegistry = /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ ({ phase: 'none', discovered: null, refined: null, curator: null, defaults: {}, models: [], job: null })));
return cachedRegistry;
}
// a context ceiling as the short human form: 1048576 -> "1M",
// 524288 -> "512K". Null when the provider stated nothing.
/** @param {?number} tokens @returns {?string} */
export function fmtCeiling(tokens) {
if (tokens == null || !Number.isFinite(tokens) || tokens <= 0) return null;
return tokens >= 1048576 ? `${Math.round(tokens / 1048576)}M` : `${Math.round(tokens / 1024)}K`;
}
// A select's "" value means "deployment default"; a current override
2026-11-16 21:32:02 +00:00
// missing from the registry stays selectable, so a stale pick never
// silently rewrites itself. The registry's usable models group by
// family; the label is the curator's (or the id before refinement),
// and the input ceiling rides along -- the user picks against the
// contwin, so the context limit belongs in the open.
/** @param {HTMLSelectElement} sel @param {?string} current @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {?string} [def] */
function fillSelect(sel, current, reg, 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)'}`);
2026-11-16 21:32:02 +00:00
const usableModels = reg.models.filter((m) => m.inference !== false && (m.roles?.player ?? true));
const extras = current && !usableModels.some((m) => m.id === current) ? [current] : [];
/** @type {Record<string, import('../server/shapes.mjs').RegistryModel[]>} */ const byFamily = {};
for (const m of usableModels) {
const f = m.family ?? m.id;
(byFamily[f] ??= []).push(m);
}
const families = Object.keys(byFamily).sort();
for (const f of families) {
const group = /** @type {HTMLOptGroupElement} */ (el('optgroup'));
group.label = f;
for (const m of byFamily[f]) {
const label = m.label ?? m.id;
const ceil = fmtCeiling(m.input);
const o = /** @type {HTMLOptionElement} */ (el('option', null, ceil ? `${label} \u00b7 ${ceil}` : label));
o.value = m.id;
group.appendChild(o);
}
sel.appendChild(group);
}
for (const x of extras) mk(x, `${x} (not in the registry)`);
sel.value = current ?? '';
}
2026-11-16 21:32:02 +00:00
// the models box: player/housekeeper selects over the registry, the
// sampling knobs per role (one shared hint bar under both rows), and
// one save. 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);
2026-11-16 21:32:02 +00:00
const knobHint = el('div', 'knob-hint'); // one bar, both roles
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
root.appendChild(playerKnobs.wrap);
root.appendChild(houseKnobs.wrap);
root.appendChild(knobHint);
if (!root.querySelector('.registry-hint')) {
const hint = el('div', 'hint registry-hint', '');
root.appendChild(hint);
}
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 {
2026-11-16 21:32:02 +00:00
// the knob read throws on an empty override -- same banner, nothing sent
const params = { player: playerKnobs.read(), housekeeper: houseKnobs.read() };
await api(`/runs/${state.runId}/model`, {
method: 'POST',
2026-11-16 21:32:02 +00:00
body: {
player: playerSel.value || null,
housekeeper: houseSel.value || null,
params,
},
});
saveState.textContent = 'saved';
} catch (e) {
banner(e.message);
saveState.textContent = 'not saved';
}
});
return {
2026-11-16 21:32:02 +00:00
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} params @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} paramDefaults @param {import('./shapes.mjs').ModelsRegistryResponse} reg */
fill(models, defaults, params, paramDefaults, reg) {
fillSelect(playerSel, models?.player ?? null, reg, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, reg, defaults?.housekeeper);
const pk = knobsBox('player', params?.player ?? undefined, paramDefaults?.player ?? undefined, knobHint);
const hk = knobsBox('housekeeper', params?.housekeeper ?? undefined, paramDefaults?.housekeeper ?? undefined, knobHint);
playerKnobs.wrap.replaceWith(pk.wrap);
houseKnobs.wrap.replaceWith(hk.wrap);
playerKnobs = pk;
houseKnobs = hk;
const hint = root.querySelector('.registry-hint');
if (hint) {
hint.textContent = reg.phase === 'none'
? 'no models discovered -- the op runs discovery from the admin block on home'
: reg.phase === 'preliminary'
? 'preliminary registry -- unrefined: the op can run refine to verify and label the models'
: '';
}
saveState.textContent = '';
},
};
}