258 lines
13 KiB
JavaScript
258 lines
13 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 edit stages, the send rides it
|
|
// with the turn; the section shell stays in index.html
|
|
// - modelsBox: the per-run player/housekeeper selects over the
|
|
// 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 { 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. The edit does
|
|
// not save anywhere -- it STAGES a block edit that rides the next
|
|
// GM turn (the server logs the override on the turn; the composition
|
|
// overwrites her newest blocks with it). setEditable(false) is the
|
|
// not-live state: no edit button, an open editor cancels, a staged
|
|
// edit drops -- dormancy edits the carryover, not the panes.
|
|
/** @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[] }} PaneOpts */
|
|
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[], staged: ?string[], clearStaged: () => void }} Pane */
|
|
/** @param {PaneOpts} opts @returns {Pane} */
|
|
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText }) {
|
|
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, 'stage');
|
|
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)
|
|
const pending = el('div', 'pane-pending');
|
|
pending.hidden = true;
|
|
pending.appendChild(el('span', null, 'edited -- rides your next turn'));
|
|
const dropBtn = el('button', null, 'discard edit');
|
|
pending.appendChild(dropBtn);
|
|
editor.after(pending);
|
|
|
|
/** @type {string[]} */ let items = [];
|
|
/** @type {?string[]} */ let staged = null;
|
|
let mayEdit = false;
|
|
let open = false;
|
|
|
|
const sync = () => {
|
|
bodyEl.hidden = open;
|
|
editBtn.hidden = open || !mayEdit;
|
|
editor.hidden = !open;
|
|
pending.hidden = staged === null;
|
|
};
|
|
const renderBody = () => {
|
|
const show = staged ?? items;
|
|
bodyEl.textContent = show.length ? format(show) : empty;
|
|
bodyEl.classList.toggle('empty', !show.length);
|
|
};
|
|
const openEditor = () => {
|
|
area.value = toText(staged ?? items);
|
|
open = true;
|
|
sync();
|
|
area.focus();
|
|
};
|
|
const cancel = () => { open = false; sync(); };
|
|
const doSave = () => { staged = fromText(area.value); cancel(); renderBody(); };
|
|
const dropStaged = () => { staged = null; sync(); renderBody(); };
|
|
|
|
editBtn.addEventListener('click', openEditor);
|
|
cancelBtn.addEventListener('click', cancel);
|
|
saveBtn.addEventListener('click', doSave);
|
|
dropBtn.addEventListener('click', dropStaged);
|
|
|
|
return {
|
|
set(next) { items = next ?? []; renderBody(); },
|
|
setEditable(ok) { mayEdit = ok; cancel(); if (!ok) dropStaged(); },
|
|
reset() { cancel(); dropStaged(); },
|
|
get items() { return items; },
|
|
get staged() { return staged; },
|
|
clearStaged: dropStaged,
|
|
};
|
|
}
|
|
|
|
// 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() {
|
|
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
|
|
// missing from the registry stays selectable, so a stale pick never
|
|
// silently rewrites itself. One plain list, sorted by id (GM,
|
|
// 2026-11-16: the family grouping left the user guessing what a
|
|
// family name means, and the curator's tier labels only made sense
|
|
// inside their groups -- the id is the self-describing name). 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)'}`);
|
|
const usableModels = reg.models.filter((m) => m.inference !== false && (m.roles?.player ?? true));
|
|
const extras = current && !usableModels.some((m) => m.id === current) ? [current] : [];
|
|
for (const m of [...usableModels].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
|
|
const ceil = fmtCeiling(m.input);
|
|
mk(m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
|
|
}
|
|
for (const x of extras) mk(x, `${x} (not in the registry)`);
|
|
sel.value = current ?? '';
|
|
}
|
|
|
|
// 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. The knob
|
|
// rows rebuild when the model select changes: the effort knob's
|
|
// default is measured per model, so switching the model switches the
|
|
// honest default.
|
|
/** @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 knobHint = el('div', 'knob-hint'); // one bar, both roles
|
|
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
|
|
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
|
|
root.appendChild(playerKnobs.wrap);
|
|
root.appendChild(houseKnobs.wrap);
|
|
root.appendChild(knobHint);
|
|
// the latest fill's inputs -- the select-change refresh rebuilds
|
|
// the knob rows against them (the effort context follows the
|
|
// newly-picked model)
|
|
/** @type {?{ params: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, paramDefaults: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, reg: import('./shapes.mjs').ModelsRegistryResponse }} */ let last = null;
|
|
// the effort knob's context: the currently-selected model's
|
|
// measured ladder (null when the registry has none for it)
|
|
/** @param {'player'|'housekeeper'} role @param {import('./shapes.mjs').ModelsRegistryResponse} reg @returns {?{ measured: Record<string, number>, fallback: ?string }} */
|
|
const effortOf = (role, reg) => {
|
|
const id = (role === 'player' ? playerSel.value : houseSel.value)
|
|
|| reg.defaults?.[role] || null;
|
|
const m = id ? reg.models.find((x) => x.id === id) : null;
|
|
return m?.efforts ? { measured: m.efforts, fallback: m.effortDefault ?? null } : null;
|
|
};
|
|
/** rebuild both knob rows against the current selects and the
|
|
* latest fill (fill and select-change both land here) */
|
|
function rebuildKnobs() {
|
|
if (!last) return;
|
|
const pk = knobsBox('player', last.params?.player ?? undefined, last.paramDefaults?.player ?? undefined, knobHint, effortOf('player', last.reg));
|
|
const hk = knobsBox('housekeeper', last.params?.housekeeper ?? undefined, last.paramDefaults?.housekeeper ?? undefined, knobHint, effortOf('housekeeper', last.reg));
|
|
playerKnobs.wrap.replaceWith(pk.wrap);
|
|
houseKnobs.wrap.replaceWith(hk.wrap);
|
|
playerKnobs = pk;
|
|
houseKnobs = hk;
|
|
}
|
|
playerSel.addEventListener('change', rebuildKnobs);
|
|
houseSel.addEventListener('change', rebuildKnobs);
|
|
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 {
|
|
// 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',
|
|
body: {
|
|
player: playerSel.value || null,
|
|
housekeeper: houseSel.value || null,
|
|
params,
|
|
},
|
|
});
|
|
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 {?{ 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);
|
|
last = { params: params ?? null, paramDefaults: paramDefaults ?? null, reg };
|
|
rebuildKnobs();
|
|
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 = '';
|
|
},
|
|
};
|
|
}
|