Back to The Bathyal Post
SOURCE / PINNED RELEASE

Made of little things.

The Bathyal Post

Release
fa6ce530b9f3…
Author-recorded commit
b255b3c9fd49…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-55c50b9a042

Archive hash verified: 03cf62191e7476c5…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/main.ts
import { identity, type Subscription } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import { BathyalChart } from './chart.js';
import { createSound, type SoundStatus } from './sound.js';
import { observeMotion } from './napplet-settings.js';
import { STOPS, RIGS, EDGES, forecast, travel, newVoyage, nextBag, deliveredCount, neighbours, huntingGround, tideName, type StopId, type Rig, type Mode } from './voyage.js';
import { icon, emblem, type IconName } from './icons.js';
import { PostOffice, freshLedger, newSeed } from './post-office.js';
import { escapeText as esc, stamp, pad, mailPage, guidePage, logPage, routesPage } from './folio.js';
import plateUrl from './art/specimens.webp?inline';
import './styles.css';

document.documentElement.style.setProperty('--specimen-sheet', 'url(' + plateUrl + ')');

function el<T extends HTMLElement = HTMLElement>(id: string) {
  const node = document.getElementById(id);
  if (!node) throw new Error('Missing ' + id);
  return node as T;
}
document.querySelectorAll<HTMLElement>('[data-icon]').forEach(node => node.innerHTML = icon(node.dataset.icon as IconName));
el('brandmark').innerHTML = emblem;

let ledger = freshLedger(newSeed());
let voyage = ledger.voyage;
let selected: StopId = 'medusa';
let mode: Mode = 'drift';
let rig: Rig = 'tanks';
let still = false;
let locked = false;
let changed = false;
let finishTimer = 0;
let noticeTimer = 0;
let openPage = '';
const office = new PostOffice();
const dialog = el<HTMLDialogElement>('folio');
const content = el('desk-content');
const chart = new BathyalChart(el<HTMLCanvasElement>('chart'), selectStation);
const sound = createSound(showSound);
const labels = Object.fromEntries(Object.values(STOPS).map(stop => [stop.id,stop.name]));
const depths = Object.fromEntries(Object.values(STOPS).map(stop => [stop.id,stop.depth]));

function showSound(status: SoundStatus) {
  const button = el<HTMLButtonElement>('audio');
  const label = {off:'Enable hydrophone sound',on:'Mute hydrophone sound',starting:'Opening hydrophone',unavailable:'Sound unavailable in this shell'}[status];
  button.innerHTML = icon(status === 'on' ? 'sound' : 'mute');
  button.setAttribute('aria-label',label);
  button.setAttribute('aria-pressed',String(status === 'on'));
  button.disabled = status === 'unavailable' || status === 'starting';
  button.title = label;
}
showSound(sound.status);

function chartState() {
  chart.update({
    current:voyage.at, selected:voyage.phase === 'sailing' ? selected : null,
    reachable:neighbours(voyage.at), routes:EDGES, labels, depths,
    course:voyage.phase === 'sailing' ? routeTo(selected) : [],
    letters:voyage.letters.filter(l => !l.delivered).map(l => l.to),
    visited:voyage.letters.filter(l => l.delivered).map(l => l.to),
    danger:voyage.wake >= 4, hunted:huntingGround(voyage), reducedMotion:still,
  });
}

function routeTo(goal: StopId): StopId[] {
  const paths: StopId[][] = [[voyage.at]];
  const seen = new Set<StopId>([voyage.at]);
  for (const path of paths) {
    const tail = path[path.length - 1];
    if (tail === goal) return path.slice(1);
    for (const next of neighbours(tail)) {
      if (!seen.has(next)) { seen.add(next); paths.push([...path,next]); }
    }
  }
  return [];
}

function suggested(): StopId {
  const mail = voyage.letters.filter(l => !l.delivered).map(l => l.to);
  if (!voyage.turn && mail.includes('medusa')) return 'medusa';
  if (deliveredCount(voyage) >= voyage.quota && (voyage.air <= 4 || mail.length === 0)) return 'buoy';
  return mail.sort((a,b)=>routeTo(a).length-routeTo(b).length)[0] ?? 'buoy';
}

function selectStation(id: StopId) {
  if (locked || voyage.phase !== 'sailing') return;
  if (id === voyage.at) { showFolio('routes'); return; }
  selected = id;
  sound.cue('select');
  render();
}

function instrument(label: string, symbol: IconName, value: number, max: number, color: string) {
  return `<div class="instrument"><div class="instrument-head"><span class="instrument-label">${icon(symbol)}${label}</span>
    <span class="readout">${pad(value)}<small> / ${pad(max)}</small></span></div>
    <div class="scale" style="--gauge:${color};--steps:${max};--cut:${100 - value/max*100}%"></div></div>`;
}

function passageDesk() {
  const stop = STOPS[selected];
  const path = routeTo(selected);
  const direct = path.length === 1;
  const next = path[0];
  const leg = next && forecast(voyage,next,mode);
  if (!leg) return '';
  const letter = voyage.letters.find(item => item.to === selected && !item.delivered);
  const current = {with:'Following tide',slack:'Slack water',against:'Opposing tide'}[leg.current];
  const service = selected === 'vent' ? (voyage.ventUsed ? 'Spent vent this dispatch' : 'Up to six air on arrival') :
    selected === 'wreck' ? (voyage.wreckUsed ? 'Already salvaged' : 'Salvage and sorting drawer') :
    selected === 'buoy' ? 'Return to the sorting office' : 'No letter aboard for this stop';
  const favors: Partial<Record<StopId,string>> = {medusa:'Silences two drives', whale:'Restores up to four air', garden:'Mends up to two hull', trench:'Clears your wake'};
  const wakeChange = leg.wakeAfter - voyage.wake;
  const wake = wakeChange === 0 ? '0' : wakeChange > 0 ? '+' + wakeChange : '−' + Math.abs(wakeChange);
  const adverse = leg.fatal || leg.attack || (next === 'buoy' && deliveredCount(voyage) < voyage.quota);
  const note = !direct ? `First leg via ${STOPS[next].name}. ` : '';
  let effect = '';
  if (leg.fatal || leg.hullCost || next === 'buoy' || next === 'vent' || next === 'wreck') {
    effect = leg.summary.split(' · ').slice(1).join(' · ') || 'Station service already used.';
    if (effect === 'salvage +0 hull') effect = 'Hull sound. Search the sorting drawer.';
  } else if (voyage.lace && mode === 'drive') effect = 'Medusa lace silences the screw.';
  else if (huntingGround(voyage) === next) effect = 'The Listener is hunting this station.';
  else if (letter && direct) effect = letter.condition + ' · +6 postage';
  else effect = direct ? 'No mail exchange on this leg.' : 'Recheck the tide at the next station.';
  return `<div class="ticket">
    <div class="ticket-type"><span>${icon('letter')} Passage slip</span><span>Nº ${pad(voyage.bag)}.${pad(voyage.turn+1)}</span></div>
    <div class="spec-head"><div><span class="small-label">Destination</span>
    <button class="destination" id="destinations" title="Choose destination" aria-label="Choose destination, ${stop.name}">${stop.name} ${icon('select')}</button>
    <div class="plate-no">${stop.depth.toLocaleString('en')} m · ${stop.kind === 'recipient' ? 'Mail stop' : stop.kind === 'home' ? 'Sorting office' : 'Service stop'}</div></div>${stamp(selected)}</div>
    <div class="enclosure"><span class="micro">${letter ? 'Enclosed letter' : 'Station service'}</span>${letter ? esc(letter.title) : service}</div>
    ${letter ? `<div class="arrival-favor">${favors[selected]} on delivery.</div>` : ''}
    </div>
    <div class="propulsion"><div class="mode-key">Propulsion</div><div class="seg" role="group" aria-label="Propulsion">
    <button id="drift" data-mode="drift" aria-pressed="${mode === 'drift'}">${icon('drift')}Drift</button>
    <button id="drive" data-mode="drive" aria-pressed="${mode === 'drive'}">${icon('drive')}Drive</button></div></div>
    <div class="forecast"><div class="forecast-head"><span class="forecast-label">Next crossing</span><em>${current}</em></div>
    <div class="costs"><div class="value-row">Air <strong>−${leg.airCost}</strong></div><div class="value-row">Wake <strong>${wake}</strong></div></div>
    <p class="detail-copy ${adverse ? 'warning' : ''}">${esc(note + effect)}</p></div>
    <button id="depart" class="action" ${locked ? 'disabled' : ''}><span>${locked ? 'Bell in transit…' : !direct ? 'Travel via ' + STOPS[next].name : next === 'buoy' ? 'Return to buoy' : 'Take passage'}</span>${icon('arrow')}</button>`;
}

function resultsDesk() {
  const docked = voyage.phase === 'docked';
  return `<div class="result"><div class="ticket"><div class="ticket-type">Sorting office receipt <span>Nº ${pad(voyage.bag)}</span></div>
    <h2>${esc(voyage.last.title)}</h2><p class="receipt-copy">${esc(voyage.last.text)}</p></div>
    <div class="log-stats"><div><b>${voyage.score}</b>Postage</div><div><b>${voyage.totalDelivered}</b>Delivered</div></div>
    ${docked ? `<label class="micro" for="refit">Refit for dispatch ${pad(voyage.bag+1)}</label>
    <select id="refit">${(['tanks','baffles','keel'] as Rig[]).map(id=>`<option value="${id}" ${id === rig ? 'selected' : ''}>${RIGS[id].name}</option>`).join('')}</select>
    <p id="rig-info" class="detail-copy">${RIGS[rig].description}</p>` : '<button id="retry" class="tool-action">Sail this tide again</button>'}
    <button class="action" id="proceed" ${locked ? 'disabled' : ''}>${docked ? 'Collect next mailbag' : 'Sail a new tide'}${icon('arrow')}</button></div>`;
}

function render() {
  el('shift').textContent = 'Dispatch ' + pad(voyage.bag) + ' / 03';
  el('watch').textContent = 'Watch ' + pad(voyage.turn);
  el('here').textContent = STOPS[voyage.at].name;
  const notice = voyage.last;
  const initial = notice.kind === 'launch' && voyage.bag === 1;
  el('wire').innerHTML = '<span class="wire-mark">' + icon(initial ? 'compass' : notice.kind === 'delivery' || notice.kind === 'secret' ? 'letter' : 'wake') + '</span><div><span class="wire-heading">' +
    (initial ? 'Pilot’s orders' : esc(notice.title)) + '</span><span class="wire-message">' +
    (initial ? 'Select a stop on the chart and compare the cost of a crossing.' : esc(notice.text)) + '</span></div>';
  el('tide').textContent = ({Flood:'Flood tide',Ebb:'Ebb tide','High water':'High water','Low water':'Low water'} as Record<string,string>)[tideName(voyage)];
  el('bag-count').textContent = String(voyage.letters.length - deliveredCount(voyage));
  el('instruments').innerHTML = instrument('Air','air',voyage.air,voyage.maxAir,voyage.air < 4 ? 'var(--orange)' : '#adcbb6') +
    instrument('Hull','hull',voyage.hull,voyage.maxHull,voyage.hull < 3 ? 'var(--orange)' : '#cfbd8e') + instrument('Wake','wake',voyage.wake,6,'var(--orange)');
  const done = deliveredCount(voyage);
  const mission = voyage.phase === 'sailing'
    ? done >= voyage.quota ? 'Quota met. Return to the buoy or finish the bag.' : 'Deliver ' + voyage.quota + (voyage.quota === 1 ? ' letter' : ' letters') + ', then return to the buoy.'
    : 'Shift ledger · ' + voyage.score + ' postage';
  el('objective').innerHTML = icon('letter') + '<span>' + mission + (voyage.lace && voyage.phase === 'sailing' ? ' · Lace ×' + voyage.lace : '') + '</span>';
  const priorFocus = content.contains(document.activeElement) ? document.activeElement?.id : '';
  content.innerHTML = voyage.phase === 'sailing' ? passageDesk() : resultsDesk();
  if (priorFocus) document.getElementById(priorFocus)?.focus({preventScroll:true});
  chartState();
  sound.environment(STOPS[voyage.at].depth/1180,voyage.wake/6);
  el('app').dataset.ready = 'true';
}

function note(text: string, toast = true) {
  el('announce').textContent = text;
  if (!toast) return;
  const node = el('chart-notice');
  node.textContent = text; node.hidden = false;
  clearTimeout(noticeTimer);
  noticeTimer = window.setTimeout(()=>node.hidden = true,3300);
}
function storageChanged() {
  const status = document.querySelector('[data-storage]');
  if (status) status.textContent = office.status;
}
function save() { office.save(()=>ledger); }

function recordVoyage() {
  changed = true;
  const marks = new Set(ledger.postmarks);
  voyage.letters.forEach(letter => { if (letter.delivered) marks.add(letter.id); });
  if (voyage.deadLetter === 'posted') marks.add('black');
  const returned = ['docked','won','retired'].includes(voyage.phase);
  ledger = {voyage, postmarks:[...marks], record:returned ? Math.max(ledger.record,voyage.score) : ledger.record};
  save();
}
function sail(confirmed = false) {
  if (locked || voyage.phase !== 'sailing' || dialog.open) return;
  const path = routeTo(selected);
  const next = path[0];
  const leg = next && forecast(voyage,next,mode);
  if (!leg) return;
  if (!confirmed && (leg.fatal || (next === 'buoy' && deliveredCount(voyage) < voyage.quota))) { showFolio('risk'); return; }
  const prior = voyage;
  const goal = selected;
  voyage = travel(prior,next,mode);
  locked = true;
  sound.cue(mode);
  recordVoyage();
  chartState();
  if (leg.hullCost) chart.pulse('danger');
  const btn = el<HTMLButtonElement>('depart');
  btn.disabled = true; btn.querySelector('span')!.textContent='Bell in transit…';
  finishTimer = window.setTimeout(()=>{
    locked = false;
    const kind = voyage.last.kind;
    if (leg.hullCost) sound.cue('danger');
    if (kind === 'delivery' || kind === 'secret') { chart.pulse('delivery'); sound.cue('deliver',next); }
    else if (kind === 'service') { chart.pulse('repair'); sound.cue('service'); }
    else if (kind === 'loss') sound.cue('lose');
    else if (kind === 'dock') sound.cue(voyage.phase === 'won' ? 'win' : 'dock');
    const arrivedLetter = voyage.letters.find(l => l.to === next && l.delivered && prior.letters.some(old => old.id === l.id && !old.delivered));
    const message = arrivedLetter ? 'Postmarked · ' + arrivedLetter.title : voyage.last.title;
    note(message);
    selected = goal !== next ? goal : suggested();
    render();
    if (dialog.open) fillFolio();
  },still ? 90 : leg.hullCost ? 1040 : 940);
}
function restart(seed: number) {
  voyage = newVoyage(seed); selected = 'medusa'; mode = 'drift'; rig = 'tanks';
  clearTimeout(noticeTimer); el('chart-notice').hidden = true;
  recordVoyage(); render();
}
function nextDispatch() {
  if (locked) return;
  if (voyage.phase === 'docked') {
    voyage = nextBag(voyage,rig); selected = suggested(); mode = 'drift';
    recordVoyage(); render(); note(voyage.last.text); sound.cue('dock');
  } else restart(newSeed());
}

function showFolio(page: string) {
  openPage = page;
  fillFolio();
  if (!dialog.open) dialog.showModal();
  dialog.scrollTop = 0;
}
function fillFolio() {
  const pages: Record<string,[string,()=>string]> = {
    mail:['The mailbag',()=>mailPage(ledger)],
    log:['Pilot’s logbook',()=>logPage(ledger,office)],
    help:['Field guide',guidePage],
    routes:['Choose a sounding',()=>routesPage(voyage,selected)],
    reset:['Start a new tide?',()=>'<p>The sorting office will replace your current voyage. Your postmark album and best return carry over.</p><button class="action" data-new>Start new voyage '+icon('arrow')+'</button>'],
    risk:['Confirm passage',()=>{
      const next = routeTo(selected)[0];
      const leg = forecast(voyage,next,mode);
      return `<p>${esc(leg?.summary ?? '')}.</p><button class="action" data-risk>Proceed with crossing ${icon('arrow')}</button>`;
    }],
  };
  const [title,body] = pages[openPage] ?? pages.help;
  el('folio-title').textContent = title; el('folio-body').innerHTML = body();
}
function moveFocusToDesk() {
  const target = document.getElementById('destinations') ?? document.getElementById('proceed');
  target?.focus({preventScroll:true});
}

dialog.addEventListener('click',event=>{
  const target = event.target as HTMLElement;
  if (target === dialog && (event.clientX < dialog.getBoundingClientRect().left || event.clientX > dialog.getBoundingClientRect().right || event.clientY < dialog.getBoundingClientRect().top || event.clientY > dialog.getBoundingClientRect().bottom)) { dialog.close(); return; }
  const button = target.closest('button');
  if (!button) return;
  if (button.id === 'close-folio') dialog.close();
  else if (button.dataset.plot) { dialog.close(); selectStation(button.dataset.plot as StopId); moveFocusToDesk(); }
  else if (button.hasAttribute('data-save')) { changed = true; save(); note('Saving this voyage',false); }
  else if (button.hasAttribute('data-new-confirm') && !locked) showFolio('reset');
  else if (button.hasAttribute('data-new') && !locked) { dialog.close(); restart(newSeed()); moveFocusToDesk(); }
  else if (button.hasAttribute('data-risk')) { dialog.close(); sail(true); }
});
content.addEventListener('click',event=>{
  const button = (event.target as HTMLElement).closest('button');
  if (!button || locked) return;
  if (button.dataset.mode) { mode = button.dataset.mode as Mode; sound.cue('select'); render(); }
  else if (button.id === 'destinations') showFolio('routes');
  else if (button.id === 'depart') sail();
  else if (button.id === 'proceed') nextDispatch();
  else if (button.id === 'retry') restart(voyage.seed);
});
content.addEventListener('change',event=>{
  const select = event.target as HTMLSelectElement;
  if (select.id === 'refit' && Object.hasOwn(RIGS,select.value)) {
    rig = select.value as Rig;
    el('rig-info').textContent = RIGS[rig].description;
  }
});
el('mailbag').onclick = ()=>showFolio('mail');
el('logbook').onclick = ()=>showFolio('log');
el('help').onclick = el('tide-info').onclick = ()=>showFolio('help');
el('audio').onclick = ()=>sound.toggle();
el('location').onclick = ()=>{ if (!locked) showFolio(voyage.phase === 'sailing' ? 'routes' : 'log'); };

const releaseMotion = observeMotion(value => { still = value; document.documentElement.dataset.still = String(value); chartState(); });
function loadLedger() {
  void office.load(entry=>{
    const resume = !changed && entry.voyage !== null;
    if (resume && entry.voyage) {
      voyage = entry.voyage;
      selected = suggested();
    }
    ledger = {voyage, record:Math.max(ledger.record,entry.record),
      postmarks:[...new Set([...entry.postmarks,...ledger.postmarks])]};
    if (resume) render();
    if (dialog.open) fillFolio();
    return resume;
  },storageChanged);
}
let identitySub: Subscription | undefined;
if (runtimeHasDomain('identity')) {
  try {
    identitySub = identity.onChanged(()=>{
      office.retire(); clearTimeout(finishTimer); clearTimeout(noticeTimer);
      el('chart-notice').hidden = true; if (dialog.open) dialog.close();
      locked = false; changed = false; mode = 'drift'; rig = 'tanks';
      ledger = freshLedger(newSeed()); voyage = ledger.voyage; selected = 'medusa'; render(); loadLedger();
    });
  } catch { /* Playing does not require a viewer identity. */ }
}
render(); loadLedger();
window.addEventListener('pagehide',()=>{
  clearTimeout(finishTimer); clearTimeout(noticeTimer);
  office.retire(); sound.dispose(); chart.dispose(); releaseMotion(); identitySub?.close();
},{once:true});