Files
2026-11-01 15:22:21 -05:00

133 lines
13 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let world, session, sending = false;
const $ = selector => document.querySelector(selector);
function el(tag, text, cls) { const node = document.createElement(tag); if (text !== undefined) node.textContent = text; if (cls) node.className = cls; return node; }
function link(text, type, id) { const a = el('a', text); a.href = `#${type}/${id}`; return a; }
function button(text, action, disabled = false) { const b = el('button', text); b.disabled = disabled || sending; b.addEventListener('click', action); return b; }
function section(title) { const s = el('section'); s.append(el('h2', title)); return s; }
const localTime = at => new Date(at).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' });
async function api(path, input) {
const response = await fetch(path, input === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': crypto.randomUUID() }, body: JSON.stringify(input) });
const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Request failed.'); return data;
}
async function mutate(path, input) {
if (sending) return; sending = true; $('#notice').textContent = '';
try { await api(path, input); world = await api('/api/world'); } catch (e) { $('#notice').textContent = e.message; }
finally { sending = false; render(); }
}
function navigation() {
const nav = $('#navigation'); nav.replaceChildren();
const query = $('#search').value.toLowerCase();
for (const [title, type, values] of [['THE VALLEY', 'place', world.places], ['PEOPLE YOU KNOW', 'character', world.characters], ['DISCOVERIES', 'creature', world.creatures], ['YOUR CHRONICLE', 'event', world.events.slice().reverse()]]) {
const matches = values.filter(v => (v.title || v.name).toLowerCase().includes(query));
if (!matches.length) continue; nav.append(el('h3', title));
for (const v of matches.slice(0, 15)) { const a = link(v.title || v.name, type, v.id); if (a.hash === location.hash) a.classList.add('active'); nav.append(a); }
}
}
function timeline(events) {
if (!events.length) return el('p', 'No recorded events are available to your character here.', 'empty');
const list = el('ol', undefined, 'timeline');
for (const e of events.slice().reverse().slice(0, 20)) { const item = el('li'); item.append(el('small', localTime(e.at)), link(e.title, 'event', e.id), el('p', e.text)); list.append(item); }
return list;
}
function action(type, text, extras = {}) { return button(text, () => mutate('/api/activity', { type, ...extras }), Boolean(world.self.activity)); }
function market() {
const s = section('The player exchange'); s.append(el('p', 'Goods are reserved here. Prices are set by players; payment and delivery settle together.'));
if (!world.orders.length) s.append(el('p', 'No open sell orders. Be the first to supply the valley.', 'empty'));
for (const o of world.orders) {
const row = el('div', undefined, 'order'), description = el('div', `${o.remaining} ${o.item} · ${o.price} crowns each`);
description.append(el('small', o.mine ? 'Your reserved stock' : 'Player offer · pickup at this market')); row.append(description);
if (o.mine) row.append(button('Withdraw', () => mutate('/api/withdraw', { orderId: o.id }), Boolean(world.self.activity)));
else { const quantity = el('input'); quantity.type = 'number'; quantity.min = '1'; quantity.max = String(o.remaining); quantity.value = '1'; quantity.setAttribute('aria-label', `Quantity of ${o.item} to buy`); row.append(quantity, button('Buy', () => mutate('/api/buy', { orderId: o.id, quantity: Number(quantity.value) }), Boolean(world.self.activity))); }
s.append(row);
}
const form = el('form'); form.append(el('h3', 'Create a sell order')); const grid = el('div', undefined, 'form-grid');
const item = el('select'); for (const name of ['timber', 'plank']) { const option = el('option', name); option.value = name; item.append(option); }
const quantity = el('input'), price = el('input'); for (const input of [quantity, price]) { input.type = 'number'; input.min = '1'; input.value = '1'; input.required = true; } quantity.max = '100'; price.max = '1000';
for (const [name, input] of [['Goods', item], ['Quantity', quantity], ['Unit price · crowns', price]]) { const label = el('label', name); label.append(input); grid.append(label); }
const submit = el('button', 'Reserve goods & list'); submit.type = 'submit'; submit.disabled = Boolean(world.self.activity) || sending;
form.append(grid, submit); form.addEventListener('submit', e => { e.preventDefault(); mutate('/api/order', { item: item.value, quantity: Number(quantity.value), price: Number(price.value) }); }); s.append(form); return s;
}
function renderPage() {
const page = $('#page'); page.replaceChildren();
const [type = 'place', id = world.self.location] = location.hash.slice(1).split('/');
page.append(el('div', `The Alder Chronicle / ${type === 'place' ? 'Places' : type === 'character' ? 'People' : type === 'event' ? 'History' : 'Discoveries'}`, 'breadcrumb'));
const entry = ({ place: world.places, character: world.characters, event: world.events, creature: world.creatures }[type] || []).find(e => e.id === id);
if (!entry) { page.append(el('h1', 'Page unavailable'), el('p', 'This page is not available in your character’s knowledge.')); return; }
page.append(el('span', type === 'place' ? 'WORLD ATLAS' : type === 'character' ? 'CHARACTER RECORD' : type === 'event' ? 'WITNESSED HISTORY' : 'FIELD NOTES', 'tag'), el('h1', entry.title || entry.name), el('p', entry.text || entry.bio, 'lead'));
if (type === 'place') {
const here = id === world.self.location && !world.self.activity?.destination;
const callout = el('div', undefined, 'callout'); callout.append(el('p', here ? 'You are here. What will you make of this place?' : 'A known place, not a live remote view. Travel here to observe its present state.')); page.append(callout);
if (entry.occupants) { const people = section('Visible presence'); for (const person of entry.occupants) { const c = world.characters.find(c => c.id === person); if (c) people.append(link(c.name, 'character', c.id), el('span', ' ')); } if (!entry.occupants.length) people.append(el('p', 'No visible occupants.', 'empty')); page.append(people); }
if (here) {
const actions = el('div', undefined, 'actions');
if (id === 'wood') actions.append(action('gather', 'Gather timber · 12s'), action('observe', 'Observe wildlife · 10s'));
actions.append(action('craft', '2 timber → 1 plank · 15s'), action('rest', 'Rest · 10s'));
if (id === 'crossing') { const project = section('Rebuild the crossing'); project.append(el('p', `${entry.bridge} of 6 planks contributed. A shared project, built one undertaking at a time.`)); const progress = el('progress'); progress.max = 6; progress.value = entry.bridge; project.append(progress); page.append(project); actions.append(action('build', 'Contribute a plank · 18s')); }
if (id === 'wood') page.append(el('p', `${entry.timber} gatherable timber remains. Supplies are finite in this prototype.`, 'empty'));
page.append(actions);
const travel = section('Paths from here'), paths = el('div', undefined, 'actions');
for (const destination of entry.neighbors) { const name = world.places.find(p => p.id === destination).title; paths.append(action('travel', `Travel to ${name} · 20s`, { destination }), action('travel', `Go concealed · ${name}`, { destination, hidden: true })); } travel.append(paths); page.append(travel);
if (id === 'market') page.append(market());
}
const history = section('The history you know'); history.append(timeline(world.events.filter(e => e.places.includes(id)))); page.append(history);
}
if (type === 'character') {
if (entry.location) page.append(link(world.places.find(p => p.id === entry.location).title, 'place', entry.location));
if (entry.id === world.self.id) { const form = el('form'); form.append(el('h2', 'Your public biography')); const bio = el('textarea'); bio.value = world.self.bio; bio.maxLength = 500; bio.setAttribute('aria-label', 'Public biography'); const save = el('button', 'Publish biography'); save.type = 'submit'; form.append(bio, save); form.addEventListener('submit', e => { e.preventDefault(); mutate('/api/biography', { bio: bio.value }); }); page.append(form); }
const history = section('A life in the chronicle'); history.append(timeline(world.events.filter(e => e.actor === id))); page.append(history);
}
if (type === 'event') {
page.append(el('p', localTime(entry.at), 'empty')); const actor = world.characters.find(c => c.id === entry.actor); if (actor) page.append(el('h2', 'Participant'), link(actor.name, 'character', actor.id));
page.append(el('h2', 'Where it happened')); for (const place of entry.places) page.append(link(world.places.find(p => p.id === place).title, 'place', place), el('span', ' '));
}
if (type === 'creature') page.append(link('Recorded in Alderwood', 'place', entry.place));
}
function render() {
if (!world) return;
navigation(); renderPage(); const c = world.self;
$('#clock').textContent = `Day ${world.clock.day} · ${String(world.clock.hour).padStart(2, '0')}:${String(world.clock.minute).padStart(2, '0')} · ${world.clock.phase} — next phase ${localTime(world.clock.nextPhaseAt)}`;
const character = $('#character'); character.replaceChildren(el('span', 'YOUR CHARACTER', 'eyebrow'), el('div', c.name[0], 'avatar'), el('h2', c.name), link('Read your character page →', 'character', c.id));
const activity = $('#activity'); activity.replaceChildren(el('h3', c.activity ? 'An undertaking in progress' : 'Available to act'));
if (c.activity) {
const remaining = Math.max(0, Math.ceil((c.activity.endsAt - world.now) / 1000));
activity.append(el('p', `${c.activity.type} · ${remaining}s remaining`)); const progress = el('progress'); progress.max = c.activity.endsAt - c.activity.startedAt; progress.value = world.now - c.activity.startedAt;
activity.append(progress, el('p', `Completes ${localTime(c.activity.endsAt)}. Work continues while offline.`), button('Cancel undertaking', () => { if (confirm('Stop this activity? Elapsed work is lost, reserved materials are refunded, and travel stops at its origin.')) mutate('/api/cancel', {}); }));
} else activity.append(el('p', c.hidden ? 'You remain concealed. Your next physical undertaking reveals you unless it is another concealed journey.' : 'Choose an undertaking on your location page.'));
const inventory = $('#inventory'); inventory.replaceChildren(el('h3', 'Carried goods & account'));
for (const [name, value] of [['Crowns', c.balance], ['Timber', c.inventory.timber], ['Planks', c.inventory.plank]]) { const row = el('div', undefined, 'row'); row.append(el('span', name), el('strong', String(value))); inventory.append(row); }
inventory.append(el('p', 'Reserved market stock is not carried.'));
}
function refreshTime() {
$('#clock').textContent = `Day ${world.clock.day} · ${String(world.clock.hour).padStart(2, '0')}:${String(world.clock.minute).padStart(2, '0')} · ${world.clock.phase} — next phase ${localTime(world.clock.nextPhaseAt)}`;
if (world.self.activity) {
const a = world.self.activity;
$('#activity p').textContent = `${a.type} · ${Math.max(0, Math.ceil((a.endsAt - world.now) / 1000))}s remaining`;
$('#activity progress').value = world.now - a.startedAt;
}
}
function signature(value) { const { now, clock, ...state } = value; return JSON.stringify(state); }
async function initialize() {
session = await api('/api/session');
$('#login').hidden = session.authenticated; $('#logout').hidden = !session.authenticated || session.mode === 'demo'; $('#account').hidden = session.mode !== 'demo';
$('#login-panel').hidden = session.authenticated; $('#play').hidden = !session.authenticated;
if (new URLSearchParams(location.search).get('login') === 'failed') $('#notice').textContent = 'Dex sign-in failed or expired. Please try again.';
if (!session.authenticated) return;
if (session.mode === 'demo') { const select = $('#account'); select.replaceChildren(); for (const a of session.demoAccounts) { const option = el('option', a.name); option.value = a.id; select.append(option); } select.addEventListener('change', () => mutate('/api/demo-account', { account: select.value })); }
world = await api('/api/world'); if (session.mode === 'demo') $('#account').value = world.self.name === 'Fern Ash' ? 'demo-fern' : 'demo-rowan';
if (!location.hash) location.hash = `place/${world.self.location}`; render();
setInterval(async () => {
if (sending || document.hidden || ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) return;
try {
const next = await api('/api/world'), changed = signature(next) !== signature(world);
// A mutation may have begun while this read was in flight; never overwrite it.
if (sending) return;
world = next;
if (changed) render(); else refreshTime();
} catch (e) { $('#notice').textContent = e.message; }
}, 2000);
}
$('#search').addEventListener('input', () => { if (world) navigation(); });
$('#logout').addEventListener('click', async () => { try { await api('/auth/logout', {}); location.reload(); } catch (e) { $('#notice').textContent = e.message; } });
window.addEventListener('hashchange', () => { if (world) render(); });
initialize().catch(e => { $('#notice').textContent = e.message; });