Files
mute 0ddb9a218d the package-authoring round: fork is the verb, the scaffold flag is the ready-to-run gate, the package editor is the owner's surface, and /packages is the launchpad
The design conversation settled the verb question (developer, 2026-11-19): a "create new package" with a base selector is fork under another name, so the SPA gains one list at /packages with three acts per card -- start (the run-create flow, unchanged), fork (any package, system or user, by anyone: the copy lands in state/packages owned by the forker, pc stripped, display name asked inline, the fork landing straight in the editor -- nobody forks to immediately start), and edit (the owner's own user packages only). /new retires to a redirect onto /packages; the source link (code.fleshless.org/hackmaster/tiny-worlds) rides the header.

The template's unplayability became machinery instead of a naming special-case: settings.json carries the "scaffold" flag (the records-bool precedent -- authored content carries the marker, machinery reads it). Create refuses a scaffold loudly on both ends ("fork it to author, then flip scaffold off in the editor"), the listing marks it, the SPA disables its start. The developer's ruling over my clear-the-flag draft: the flag RIDES FORKS UNTOUCHED -- a scaffold fork stays a scaffold until its author flips it off, so the flag is the package's doneness state, and publishing your own scaffold for others to fork is free. The settings editor is raw JSON for now (native UI later, the developer's "ready to run" toggle its eventual shape), with a hint teaching the keys.

The package editor (/packages/:name): every file of a user package is authoring material -- settings included -- with the cheap save lints (memory.json and settings.json must parse as JSON objects; the carryover passes the authored lint, the run surface's exact gate), the deep checks staying at the start gate where they already lived. The gates mirror the run precedent: system packages are repo-side and refuse ("fork to edit"); an ownerless user package is readable, forkable, never editable -- and an ownerless package IS forkable, the copy is yours.

The refactor the editor forced: the setup view's file-editor machinery (nav, textarea + the sigil/var highlight overlay, drafts, dirty marks, the save flow) extracted into widgets.mjs's fileEditor factory, parameterized over DOM ids and a PUT call -- setup keeps its run-side couplings (the phase-gated rw, the addressed session), the package editor is the simpler parameterization, and the editor CSS generalized from id selectors to classes so both surfaces share it.

En-route bug found and fixed: cmdCreate always copied the REPO's handbook.md into the run, so a user package's handbook -- which save-package faithfully copies out -- was silently ignored on re-create; the author's craft edit died in the round-trip. Create now prefers the package's own handbook when it carries one, else the repo's shared copy. The smoke proves the round-trip: a handbook marker authored through the package editor surfaces in the created run's files.

Browser-pass find: the pkgedit header state span and the editor's save-state span shared the id pkgedit-state, so the widget's select() wiped the header line -- the editor's span renamed (pkgedit-edit-state), verified rendering.

Verified: typecheck green both programs; smoke ALL PASS (+20 -- the fork battery: the template fork owner-stamped scaffold-preserved pc-stripped, create refusing the scaffold on both ends, the playable fork carrying no scaffold, fork validation, the editor gates owner-200/non-owner-403/system-repo-side-403/unknown-404, the raw-JSON and carryover save lints, the ready-to-run flip, create from the flipped fork, the handbook round-trip; and the ownerless pair: the editor refuses, the fork succeeds); restart + reminder checks green (6 runs); a browser pass on --mock --debug end to end -- the paste token re-landing after the state wipe, /new redirecting with the URL honest, the template card disabled with the scaffold note, boutique disabled as incomplete, the fork form prefill and submit landing in the editor, the scaffold state line, the settings flip and save making the card startable, the start-form flow intact, zero console errors; check-repo clean; the debug server back on the real state. Docs: README's packages passage (fork, scaffold, the editor, the gates), the booting flow, the layout tree (the clerk's fork-package verb, the view list, widgets.mjs); DICTIONARY's package, scaffold, and fork entries. The developer's queue line ('"create new package" in SPA') is struck by them in the same round. packages/detention stays untracked WIP, untouched.
2026-11-19 11:11:23 +00:00

550 lines
24 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 spec picks -- {provider, model, effort}
// per role, no unset effort, no stored params (the <mind> verb is
// the only sampling source); 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 { EFFORT_LEVELS } 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 sheet pane: the same stage-and-ride pattern as the block panes,
// JSON-typed -- the GM's ledger of arbitrated run state (developer,
// 2026-11-17: the model reads it, never writes it; her proposals
// arrive in prose). A record is a whole set: staging replaces the
// entire object, an empty object is a deliberate empty ledger. Bad
// JSON refuses at the stage -- the server would refuse it at the turn.
/** @typedef {{ set: (next?: ?Record<string, unknown>) => void, setEditable: (ok: boolean) => void, reset: () => void, staged: ?Record<string, unknown>, clearStaged: () => void }} SheetPane */
/** @param {string} section @param {string} body @returns {SheetPane} */
export function sheetEditor(section, body) {
const sec = $(section);
const bodyEl = $(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 = 6;
area.placeholder = 'the sheet is JSON -- the GM\'s ledger of the run\'s objective state';
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);
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 {?Record<string, unknown>} */ let sheet = null; // the current truth (never a falsy check -- {} is a live empty ledger)
/** @type {?Record<string, unknown>} */ 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 ?? sheet;
bodyEl.textContent = show == null ? 'nothing tracked' : JSON.stringify(show, null, 2);
bodyEl.classList.toggle('empty', show == null);
};
const openEditor = () => {
area.value = JSON.stringify(staged ?? sheet ?? {}, null, 2);
open = true;
sync();
area.focus();
};
const cancel = () => { open = false; sync(); };
const doSave = () => {
try {
const parsed = JSON.parse(area.value);
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
banner('the sheet wants a JSON object');
return;
}
staged = /** @type {Record<string, unknown>} */ (parsed);
} catch (e) {
banner(`the sheet is JSON -- ${String(e.message ?? e).split('\n')[0]}`);
return;
}
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) { sheet = next ?? null; renderBody(); },
setEditable(ok) { mayEdit = ok; cancel(); if (!ok) dropStaged(); },
reset() { cancel(); dropStaged(); },
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
// 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} */ ({ providers: [] })));
return cachedRegistry;
}
/** Invalidate the cached registry -- provider state changed (the op
* added, removed, discovered, or refined), the next modelList
* refetches. */
export function dropModelCache() {
cachedRegistry = null;
}
// 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`;
}
// the model picks: per role a full spec {provider, model, effort} --
// there is no unset effort (developer, 2026-11-18), and the params layer is
// the <mind> verb's alone (per-turn, nothing stored). The health
// line under the rows is the invalidation surface: a pick the server
// no longer carries names what died and stays visible until the GM
// sets it up again. A housekeeper with no pick inherits (the player
// spec's provider default) -- the '' provider option says so.
/** @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));
/** @typedef {{ prov: HTMLSelectElement, mod: HTMLSelectElement, eff: HTMLSelectElement }} Row */
/** @param {string} role @returns {Row} */
const mkRow = (role) => {
const prov = /** @type {HTMLSelectElement} */ (el('select'));
const mod = /** @type {HTMLSelectElement} */ (el('select'));
const eff = /** @type {HTMLSelectElement} */ (el('select'));
const field = el('label', 'field', `${role} `);
field.appendChild(prov);
field.appendChild(mod);
field.appendChild(eff);
root.appendChild(field);
return { prov, mod, eff };
};
const player = mkRow('player');
const house = mkRow('housekeeper');
const healthLine = el('div', 'hint');
root.appendChild(healthLine);
const hint = el('div', '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);
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let reg = null;
/** @param {HTMLSelectElement} sel @param {string} v @param {string} label */
const opt = (sel, v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
// one provider's usable player models; a stale pick stays selectable
// (a stale pick never silently rewrites itself)
/** @param {HTMLSelectElement} sel @param {string} slug @param {?string} current */
const fillModels = (sel, slug, current) => {
const section = reg?.providers.find((p) => p.slug === slug) ?? null;
sel.textContent = '';
opt(sel, '', '(no model picked)');
const usable = (section?.models ?? []).filter((m) => m.inference !== false && (m.roles?.player ?? true));
const sorted = [...usable].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
for (const m of sorted) {
const ceil = fmtCeiling(m.input);
opt(sel, m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
}
if (current && !sorted.some((m) => m.id === current)) opt(sel, current, `${current} (not in this provider's registry)`);
sel.value = current ?? '';
};
// the effort select: the ladder, the '' option naming the measured
// default when the registry carries one
/** @param {HTMLSelectElement} sel @param {string} slug @param {?string} modelId @param {?string} current */
const fillEffort = (sel, slug, modelId, current) => {
const m = reg?.providers.find((p) => p.slug === slug)?.models.find((x) => x.id === modelId) ?? null;
sel.textContent = '';
opt(sel, '', m?.effortDefault ? `(measured default: ${m.effortDefault})` : '(pick a level)');
for (const lv of EFFORT_LEVELS) opt(sel, lv, lv);
sel.value = EFFORT_LEVELS.includes(String(current)) ? String(current) : '';
};
// a provider or model change re-derives the dependent options (the
// effort choice survives a model switch -- it is the pick's, not
// the model's)
for (const row of [player, house]) {
row.prov.addEventListener('change', () => {
fillModels(row.mod, row.prov.value, null);
fillEffort(row.eff, row.prov.value, row.mod.value, row.eff.value);
});
row.mod.addEventListener('change', () => {
fillEffort(row.eff, row.prov.value, row.mod.value, row.eff.value);
});
}
saveBtn.addEventListener('click', async () => {
try {
/** @param {Row} row @param {string} role @returns {?{ provider: string, model: string, effort: string }} */
const specOf = (row, role) => {
if (!row.prov.value) return null;
if (!row.mod.value) throw new Error(`${role}: pick a model (or clear the provider)`);
if (!row.eff.value) throw new Error(`${role}: pick an effort level -- there is no unset effort`);
return { provider: row.prov.value, model: row.mod.value, effort: row.eff.value };
};
await api(`/runs/${state.runId}/model`, {
method: 'POST',
body: { player: specOf(player, 'player'), housekeeper: specOf(house, 'housekeeper') },
});
saveState.textContent = 'saved';
} catch (e) {
banner(e.message);
saveState.textContent = 'not saved';
}
});
return {
/** @param {{ player?: ?{ provider: string, model: string, effort: string }, housekeeper?: ?{ provider: string, model: string, effort: string } }} models run.json verbatim (the spec picks)
* @param {?{ player?: ?import('./shapes.mjs').RoleHealth, housekeeper?: ?import('./shapes.mjs').RoleHealth }} modelState the resolved truth
* @param {?{ slug: string, default: ?{ model: string, effort: string } }[]} providerDefaults
* @param {import('./shapes.mjs').ModelsRegistryResponse} theReg */
fill(models, modelState, providerDefaults, theReg) {
reg = theReg;
/** @param {Row} row @param {'player'|'housekeeper'} role */
const fillRole = (row, role) => {
// the prefill is the run's OWN stored pick only -- an
// inherited housekeeper stays '' (saving an explicit pick is
// a deliberate act; the health line states what inherits)
const raw = models?.[role];
const spec = raw && typeof raw === 'object' && !Array.isArray(raw)
? /** @type {{ provider?: unknown, model?: unknown, effort?: unknown }} */ (raw) : null;
const pick = spec && typeof spec.provider === 'string' && typeof spec.model === 'string' && typeof spec.effort === 'string'
? { provider: spec.provider, model: spec.model, effort: spec.effort } : null;
row.prov.textContent = '';
opt(row.prov, '', role === 'housekeeper' ? '(inherit -- the player provider\'s default)' : '(no provider picked)');
const slugs = (reg?.providers ?? []).map((p) => p.slug);
if (pick && !slugs.includes(pick.provider)) opt(row.prov, pick.provider, `${pick.provider} (no longer configured)`);
for (const s of slugs) opt(row.prov, s, s);
row.prov.value = pick?.provider ?? '';
if (pick) {
fillModels(row.mod, pick.provider, pick.model);
fillEffort(row.eff, pick.provider, pick.model, pick.effort);
return;
}
// no stored pick: the player pre-selects the first provider's
// default (the create flow lands an explicit pick); the
// housekeeper inherits, so it stays ''
if (role === 'player' && slugs.length) {
const withDef = providerDefaults?.find((x) => x.default && slugs.includes(x.slug)) ?? null;
const slug = withDef?.slug ?? slugs[0];
row.prov.value = slug;
fillModels(row.mod, slug, withDef?.default?.model ?? null);
fillEffort(row.eff, slug, withDef?.default?.model ?? null, withDef?.default?.effort ?? null);
} else {
fillModels(row.mod, row.prov.value, null);
fillEffort(row.eff, row.prov.value, null, null);
}
};
fillRole(player, 'player');
fillRole(house, 'housekeeper');
// the health line: the invalidation notes and the inheritance
const notes = [];
for (const role of /** @type {('player'|'housekeeper')[]} */ (['player', 'housekeeper'])) {
const st = modelState?.[role];
if (!st) continue;
if (st.ok && st.inherited && st.spec) notes.push(`${role}: inherits ${st.spec.provider}'s default (${st.spec.model} at ${st.spec.effort})`);
if (!st.ok && st.note) notes.push(`${role}: ${st.note}`);
}
healthLine.textContent = notes.join(' \u00b7 ');
const providers = reg?.providers ?? [];
hint.textContent = !providers.length
? 'no providers configured -- the op fixes this from the admin block on home'
: providers.every((p) => p.phase === 'none')
? 'providers configured but nothing discovered -- the op discovers from the admin block on home'
: providers.some((p) => p.phase === 'preliminary')
? 'a preliminary registry is unrefined: the op can run refine to verify and label its models'
: '';
saveState.textContent = '';
},
};
}
// --- the file editor ------------------------------------------------------------
//
// The shared editor surface: a file nav, a textarea with the sigil/var
// highlight overlay, per-file hints, a save bar. Extracted from the
// setup view (2026-11-19) when the package editor needed the same
// machinery -- the host supplies the DOM ids, the ordered file specs,
// and the PUT call; drafts, dirty marks, the highlight, and the save
// flow live here. The deep validation stays server-side (the
// save-time lints refuse at the PUT).
/** One file as the editor sees it.
* @typedef {{ name: string, mode: string, exists: boolean, content: string }} EditorFile */
/** @typedef {{ load: (specs: EditorFile[]) => void, select: (name: string) => void, saveCurrent: () => Promise<void>, saveDirty: () => Promise<void>, isDirty: () => boolean, current: () => ?string }} FileEditor */
/** @param {{ nav: string, edit: string, hl: string, save: string, state: string, hint: string }} ids
* @param {{ put: (file: string, content: string) => Promise<unknown>, hints?: Record<string, string> }} opts
* @returns {FileEditor} */
export function fileEditor(ids, { put, hints = {} }) {
const nav = $(ids.nav);
const ta = /** @type {HTMLTextAreaElement} */ ($(ids.edit));
const hl = $(ids.hl);
const saveBtn = /** @type {HTMLButtonElement} */ ($(ids.save));
const stateEl = $(ids.state);
const hintEl = $(ids.hint);
/** @type {Record<string, EditorFile>} */ let files = {};
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
/** @type {?string} */ let current = null;
// the highlight overlay: known sigils (gold) and every $VAR (green)
// light up in place; unknown @-words are the author's own text and
// stay plain -- @ syntax is not owned here
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
const esc = ta.value.replace(/[&<>]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
+ '\n\u200b'; // keep the trailing empty line's height honest
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
}
/** @param {string} f */
function stashDraft(f) {
if (files[f]?.mode !== 'rw') return; // read-only files never become drafts
const v = ta.value;
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
drafts[f] = v;
markNav();
}
function markNav() {
for (const item of /** @type {HTMLElement[]} */ (Array.from(nav.children))) {
const name = (/** @type {HTMLElement} */ (item.querySelector('.file-name'))).textContent.replace(' (new)', '');
const dirty = drafts[name] !== undefined;
item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the
// rendered text must match the source (house rule, 2026-11-15)
(/** @type {HTMLElement} */ (item.querySelector('.file-dirty'))).textContent = dirty ? '*' : '';
item.classList.toggle('current', name === current);
}
}
/** @param {string} f */
function select(f) {
const prev = current;
if (prev === f) return;
if (prev && files[prev]?.mode === 'rw') stashDraft(prev);
current = f;
const spec = files[f] ?? { name: f, mode: 'rw', exists: false, content: '' };
ta.value = drafts[f] ?? spec.content ?? '';
ta.disabled = spec.mode !== 'rw';
saveBtn.hidden = spec.mode !== 'rw';
stateEl.textContent = spec.mode === 'rw' ? '' : 'read-only';
const hint = hints[f] ?? '';
hintEl.textContent = hint;
hintEl.hidden = !hint;
renderHighlight();
markNav();
}
/** @param {EditorFile[]} specs */
function load(specs) {
drafts = {};
current = null;
files = {};
nav.textContent = '';
for (const spec of specs) {
files[spec.name] = spec;
const item = el('button', `file-item${spec.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
item.appendChild(el('span', 'file-name', spec.name + (spec.exists ? '' : ' (new)')));
item.appendChild(el('span', 'file-dirty', ''));
item.addEventListener('click', () => select(spec.name));
nav.appendChild(item);
}
}
/** @returns {Promise<void>} */
async function saveCurrent() {
const f = current;
if (!f) return;
saveBtn.disabled = true;
try {
await put(f, ta.value);
files[f].content = ta.value;
files[f].exists = true;
delete drafts[f];
stateEl.textContent = 'saved';
markNav();
} catch (e) {
banner(/** @type {Error} */ (e).message);
stateEl.textContent = 'not saved';
}
saveBtn.disabled = false;
}
// flush every draft (start and publish flows): a refusal stops the
// flow -- the caller decides what to tell the author
/** @returns {Promise<void>} */
async function saveDirty() {
if (current != null) stashDraft(current);
for (const [f, content] of Object.entries({ ...drafts })) {
await put(f, content);
files[f].content = content;
files[f].exists = true;
delete drafts[f];
}
markNav();
}
saveBtn.addEventListener('click', saveCurrent);
ta.addEventListener('input', () => {
if (current) stashDraft(current);
stateEl.textContent = 'unsaved';
renderHighlight();
});
ta.addEventListener('scroll', () => {
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
});
return {
load,
select,
saveCurrent,
saveDirty,
isDirty: () => Object.keys(drafts).length > 0,
current: () => current,
};
}