import './portal.css'; import { showMobSpawner } from './mob-spawner'; import { permanentTitles, progressionSummary } from './progression'; import { statsBreakdown, equipmentDetails } from './character-stats'; import { showCatalog, hasCatalogDraft } from './content-editor'; import { playerContent } from './player-content'; import { registerMenu } from './menu-focus'; import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type Command, type RecordCharacter, type World } from './portal-shared'; type Data = { worlds: World[]; characters: RecordCharacter[]; commands: Command[]; provisioningEnabled: boolean; characterLimit: number; auditLimit: number }; type Draft = { id: string; worldId: string; op: string; target: string; value: string }; let data: Data; let tab = 'worlds'; let busy = false; let draft: Draft; const commandMenu=registerMenu($('command-dialog'),()=>$('command-dialog').close()); const characterMenu=registerMenu($('character-dialog'),()=>$('character-dialog').close()); const labels: Record = { 'spawn-mobs':'Spawn mobs', 'create-world': 'New world', 'close-admissions': 'Close arrivals', 'open-admissions': 'Open arrivals', 'awaken-boss': 'Awaken Harbinger', 'end-world': 'End world permanently', rename: 'Rename character', heal: 'Restore health', unstuck: 'Return to sanctuary', retire: 'Retire character permanently', 'revoke-sessions': 'Revoke account sessions' }; Object.assign(labels, { 'grant-item':'Add item', 'remove-item':'Remove item', 'grant-title':'Add / restore title', 'revoke-title':'Remove title' }); function notify(message: string) { $('control-message').textContent = message; $('control-message').hidden = false; } function openCommand(op: string, worldId = '', target = '', value = '') { if(op==='spawn-mobs'){void showMobSpawner(worldId,()=>{notify('Mob spawn queued. Check the audit for its result.');void refresh()});return;} draft = { id: crypto.randomUUID(), worldId, op, target, value }; $('command-form').reset(); const create = op === 'create-world', rename = op === 'rename'; $('command-title').textContent = labels[op]; $('command-context').textContent = create ? 'Deployment: GitOps / ArgoCD' : `${worldId}${target ? ` / ${target}` : ''}`; $('world-input-label').hidden = !create; $('world-kind-label').hidden=!create; $('world-input').required = create; $('value-input-label').hidden = !create && !rename; $('value-caption').textContent = create ? 'Seed' : 'Character name'; const input = $('value-input'); input.required = create || rename; input.value = create ? String(crypto.getRandomValues(new Uint32Array(1))[0]) : value; input.pattern = create ? '[0-9]{1,15}' : '[A-Za-z0-9][A-Za-z0-9 _-]{1,23}'; input.maxLength = create ? 15 : 24; const dangerous = ['awaken-boss', 'end-world', 'retire'].includes(op); $('confirm-input-label').hidden = !dangerous; $('confirm-caption').textContent = `Confirm ${op === 'retire' ? 'character ID' : 'world ID'}: ${op === 'retire' ? target : worldId}`; $('confirm-input').required = dangerous; $('submit-command').classList.toggle('danger', dangerous); $('command-error').textContent = ''; const previous=document.activeElement;$('command-dialog').showModal();commandMenu.opened(previous); } function actions(world: string, options: string[], target = '', value = '', disabled = false) { const parent = el('div', '', 'row-actions'); const select = el('select'); select.setAttribute('aria-label', `Action for ${target || world}`); select.append(new Option('Actions', '')); for (const op of options) select.append(new Option(labels[op], op)); select.disabled = disabled; select.onchange = () => { const op = select.value; select.value = ''; if (op) openCommand(op, world, target, value); }; parent.append(select); return parent; } function detail(r: RecordCharacter) { $('detail-name').textContent = r.name; const parent = $('character-detail'); parent.replaceChildren(); parent.append(playerContent(r,['alive','eligible'].includes(r.state)&&!!data.worlds.find(w=>w.id===r.worldId)?.available,()=>{ $('character-dialog').close();notify('Player change queued. The audit log records its result.');void refresh(); })); const list = el('dl', '', 'details'); const v = r.character.view; const pairs: [string, string][] = [['Character ID', r.id], ['Account ID', r.account], ['World', r.worldId], ['State', r.state], ['Health', `${v.entity.hp} / ${v.entity.maxHp}`], ['Position', `${Math.round(v.entity.position.x)}, ${Math.round(v.entity.position.y)}, ${Math.round(v.entity.position.z)}`], ['Played today', `${Math.floor(r.character.dailySeconds / 60)} min`], ['Born', date(r.character.bornAt)], ['Died', r.character.diedAt ? date(r.character.diedAt) : '-'], ['Cause', r.character.deathReason || '-']]; for (const [key,value] of pairs) list.append(el('dt', key), el('dd', value)); parent.append(list); parent.append(el('h3', 'Progression'), progressionSummary(v), el('h3', 'Permanent titles'), permanentTitles(v.titles)); parent.append(el('h3','Full stats'),statsBreakdown(v),el('h3','Equipment'),equipmentDetails(v)); for (const [heading, items] of [['Inventory', v.inventory], ['Skills', v.skills]] as const) { parent.append(el('h3', heading)); const section = el('div', '', 'item-list'); for (const [key,value] of Object.entries(items)) { const item = el('span', key.replaceAll('_', ' ')); item.append(el('b', String(value))); section.append(item); } if (!section.children.length) section.append(el('span', 'None', 'muted')); parent.append(section); } const previous=document.activeElement;$('character-dialog').showModal();characterMenu.opened(previous); } function render() { if (!data) return; const search = $('search').value.trim().toLowerCase(), world = $('world-filter').value, state = $('state-filter').value; const matches = (fields: string[], recordWorld: string, recordState: string) => (!world || world === recordWorld) && (!state || state === recordState) && fields.join(' ').toLowerCase().includes(search); const parent = $('records'); document.querySelector('.table-tools')!.hidden = tab === 'content'; if (tab === 'content') { showCatalog(parent); $('record-count').textContent = ''; $('table-note').textContent = 'Content changes are versioned and audited.'; return; } parent.replaceChildren(); let count = 0; if (tab === 'worlds') { const { node, body } = table(['World', 'Status', 'Living / capacity', 'Fallen', 'Harbinger arrives', 'Actions']); for (const w of data.worlds.filter(w => matches([w.id,w.phase], w.id, w.phase))) { const row = body.insertRow(); const link = el('a', w.id, 'record-link'); link.href = gameURL(w.id); const worldName = el('div'); worldName.append(link, el('small', `Catalog ${w.catalogVersion ?? 0}`, 'muted block')); cell(row, worldName); const status = el('div', '', 'badge-group'); status.append(badge(w.phase)); if (!w.available) status.append(badge('offline')); else if (w.closed) status.append(badge('closed')); cell(row, status); cell(row, `${w.living} / ${w.capacity}`); cell(row, String(w.dead)); cell(row, date(w.bossAt)); const options = [w.closed ? 'open-admissions' : 'close-admissions']; if (w.phase === 'gathering') options.push('awaken-boss'); options.push('spawn-mobs','end-world'); cell(row, actions(w.id, options, '', '', !w.available || ['won','lost'].includes(w.phase))); count++; } parent.append(node); $('table-note').textContent = 'Availability reflects the world-owner lease. Living counts include offline characters.'; } else if (tab === 'characters') { const { node, body } = table(['Character', 'World', 'State', 'Health', 'Played today', 'Actions']); for (const r of data.characters.filter(r => matches([r.id,r.account,r.name,r.worldId], r.worldId,r.state))) { const row = body.insertRow(); const button = el('button', r.name, 'record-link'); button.onclick = () => detail(r); cell(row, button); cell(row, r.worldId); cell(row, badge(r.state)); cell(row, `${Math.ceil(r.character.view.entity.hp)} / ${r.character.view.entity.maxHp}`); cell(row, `${Math.floor(r.character.dailySeconds/60)} min`); const controls = actions(r.worldId, ['rename','heal','unstuck','retire'], r.id, r.name, r.state !== 'alive' || !data.worlds.find(w => w.id === r.worldId)?.available); const revoke = el('button', '', 'icon-button'); revoke.title = `Revoke sessions for ${r.name}`; revoke.setAttribute('aria-label', revoke.title); revoke.append(icon('log-out')); revoke.onclick = () => openCommand('revoke-sessions', r.worldId, r.account); controls.append(revoke); cell(row, controls); count++; } parent.append(node); $('table-note').textContent = `Up to ${data.characterLimit} records per world filter. Dead characters remain in history.`; } else { const { node, body } = table(['Requested', 'Action', 'World / target', 'Status', 'Reason / result']); for (const c of data.commands.filter(c => matches([c.id,c.actor,c.op,c.target,c.reason,c.result], c.worldId === '_provision' ? c.target : c.worldId,c.status))) { const row = body.insertRow(); cell(row, date(c.createdAt)); const op = el('div', labels[c.op] || c.op); op.title = `Request ${c.id}\nActor ${c.actor}`; if (['grant-item','remove-item','grant-title','revoke-title'].includes(c.op)) op.append(el('small',c.value,'muted block')); cell(row, op); const target = el('div', c.worldId === '_provision' ? c.target : c.worldId); if (c.target && c.worldId !== '_provision') target.append(el('small', c.target, 'muted block')); cell(row, target); cell(row, badge(c.status)); const reason = el('div', c.reason); if (c.result) reason.append(el('small', c.result, 'muted block')); cell(row, reason); count++; } parent.append(node); $('table-note').textContent = `Latest ${data.auditLimit} actions. Completed provisioning means committed to Git; world availability confirms startup.`; } if (!count) parent.append(el('p', 'No matching records.', 'empty')); $('record-count').textContent = `${count} records`; icons(); } function options(select: HTMLSelectElement, values: string[], all: string) { const current = select.value; select.replaceChildren(new Option(all, '')); for (const v of [...new Set(values)]) select.append(new Option(v, v)); select.value = values.includes(current) ? current : ''; } async function refresh() { if (busy) return; busy = true; try { const world = $('world-filter').value; data = await api(`/api/control?world=${encodeURIComponent(world)}`); $('access').hidden = true; $('workspace').hidden = false; $('admin-signout').hidden = false; const create = $('create-world'); create.disabled = !data.provisioningEnabled; create.title = data.provisioningEnabled ? 'Provision world through GitOps' : 'GitOps provisioning is not configured'; $('metric-worlds').textContent = String(data.worlds.filter(w => w.available).length); $('metric-living').textContent = String(data.worlds.reduce((n,w) => n+w.living, 0)); $('metric-dead').textContent = String(data.worlds.reduce((n,w) => n+w.dead, 0)); $('metric-pending').textContent = String(data.commands.filter(c => c.status === 'pending').length); options($('world-filter'), data.worlds.map(w => w.id), 'All worlds'); options($('state-filter'), tab === 'worlds' ? ['gathering','cataclysm','won','lost'] : tab === 'characters' ? ['alive','dead','eligible'] : ['pending','completed','rejected'], 'All states'); $('updated').textContent = `Updated ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`; render(); } catch (e) { if (!data || (e instanceof APIError && [401,403].includes(e.status))) { $('workspace').hidden = true; $('access').hidden = false; $('create-world').setAttribute('disabled', ''); $('access-title').textContent = e instanceof APIError && e.status === 403 ? 'Administrator access required' : e instanceof APIError && e.status === 401 ? 'Sign in to Control' : 'Control unavailable'; $('access-message').textContent = (e as Error).message; $('admin-login').hidden = false; } else notify((e as Error).message); } finally { busy = false; icons(); } } document.querySelectorAll('[data-tab]').forEach(button => button.onclick = () => { if (hasCatalogDraft()) { notify('Finish or cancel the open content draft before leaving.'); return; } tab = button.dataset.tab!; document.querySelectorAll('[data-tab]').forEach(b => b.classList.toggle('active', b === button)); $('view-title').textContent = tab === 'content' ? 'Game content' : tab === 'audit' ? 'Audit log' : tab === 'characters' ? 'Characters' : 'Worlds'; $('search').placeholder = `Search ${tab}`; $('state-filter').value = ''; void refresh(); }); $('search').oninput = render; $('state-filter').onchange = render; $('world-filter').onchange = () => void refresh(); $('refresh').onclick = () => void refresh(); $('create-world').onclick = () => openCommand('create-world'); for (const id of ['close-command','cancel-command']) $(id).onclick = () => commandMenu.close(); $('close-character').onclick = () => characterMenu.close(); $('command-form').onsubmit = async event => { event.preventDefault(); const submit = $('submit-command'); submit.disabled = true; const body = { ...draft, op:draft.op==='create-world'&&$('world-kind').value==='hub'?'create-hub':draft.op, worldId: draft.op === 'create-world' ? $('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $('value-input').value : '', reason: $('reason-input').value, confirm: $('confirm-input').value }; try { await api('/api/control/commands', body); $('command-dialog').close(); notify('Action queued. Execution status is recorded in the audit log.'); await refresh(); } catch (e) { $('command-error').textContent = (e as Error).message; } finally { submit.disabled = false; } }; $('admin-signout').onclick = async () => { try { await api('/auth/logout', {}); location.href = '/'; } catch(e) { notify((e as Error).message); } }; icons(); void refresh(); setInterval(() => { if (!document.hidden && !hasCatalogDraft() && !$('command-dialog').open && !$('character-dialog').open) void refresh(); }, 5000);