Back to Proof of Work is dead
SOURCE / PINNED RELEASE

Made of little things.

Proof of Work is dead

Release
89cac09188df…
Author-recorded commit
8ef34170172d…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-abb751b60a6

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

src/main.ts
import { IDENTITY_DOMAIN, STORAGE_DOMAIN, identity, storage } from '@napplet/sdk';
import { assetBlob, assetUrl } from '../soy-assets.js';
import { runtimeHasDomain } from './domain-availability.js';
import * as R from './ring.js';
import './styles.css';

// App-owned colours: the furnace, the ring and the paper keep their palette in
// every host theme, so the optional theme domain is deliberately not read.

function $<T extends HTMLElement>(selector: string): T {
  const element = document.querySelector<T>(selector);
  if (!element) throw new Error(`Missing element: ${selector}`);
  return element;
}

const app = $<HTMLElement>('#app');
const root = document.documentElement;
const calmQuery = window.matchMedia?.('(prefers-reduced-motion: reduce)');
const calm = (): boolean => !!calmQuery?.matches;
const now = (): number => performance.now();
const whole = new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 });

function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
  return new Promise<T>((resolve, reject) => {
    const timer = window.setTimeout(() => reject(new Error('timeout')), ms);
    promise.then(
      (value) => {
        window.clearTimeout(timer);
        resolve(value);
      },
      (error: unknown) => {
        window.clearTimeout(timer);
        reject(error instanceof Error ? error : new Error(String(error)));
      },
    );
  });
}

/** Two significant digits, in words people read at a glance. */
function roughly(value: number): string {
  if (value >= 1e9) return `${trim(value / 1e9)} billion`;
  if (value >= 1e6) return `${trim(value / 1e6)} million`;
  if (value >= 1e4) return whole.format(Number(value.toPrecision(2)));
  return whole.format(Math.round(value));
}

function trim(value: number): string {
  return String(Number(value.toPrecision(2)));
}

function seconds(ms: number): string {
  return ms < 9950 ? (ms / 1000).toFixed(1) : String(Math.round(ms / 1000));
}

function randomIndex(size: number): number {
  const limit = Math.floor(0x1_0000_0000 / size) * size;
  const box = new Uint32Array(1);
  do crypto.getRandomValues(box);
  while (box[0] >= limit);
  return box[0] % size;
}

// ------------------------------------------------------------------- fonts

async function loadFont(family: string, id: string, descriptors: FontFaceDescriptors = {}): Promise<void> {
  let face: FontFace;
  try {
    // From bytes, which needs no font source in the host's content policy.
    face = new FontFace(family, await (await assetBlob(id)).arrayBuffer(), descriptors);
    await face.load();
  } catch {
    try {
      // The dev server serves the font as a file instead of embedding it.
      face = new FontFace(family, `url(${await assetUrl(id)})`, descriptors);
      await face.load();
    } catch {
      return; // The fallback stack stays.
    }
  }
  document.fonts.add(face);
}

const title = $<HTMLElement>('#burnTitle');
const furnace = $<HTMLElement>('#burn');

/** Size the headline to the frame: as wide as it gets, never taller than a good half. */
function fitTitle(): void {
  // Measured without the page breaks of the last layout; the layout that follows sets them again.
  for (const element of pushed.get(furnace) ?? []) element.style.marginTop = '';
  const probe = 100;
  title.style.fontSize = `${probe}px`;
  let widest = 1;
  for (const line of title.children) widest = Math.max(widest, (line as HTMLElement).offsetWidth);
  const tall = Math.max(1, title.offsetHeight);
  const style = getComputedStyle(furnace);
  const roomX = furnace.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
  // A good half of the frame at most, and never so tall that the counter below leaves the page.
  let below = 0;
  for (const child of furnace.children) if (child !== title && !child.classList.contains('stop')) below += (child as HTMLElement).offsetHeight;
  const gaps = (parseFloat(style.rowGap) || 0) * 2;
  const free = app.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom) - below - gaps;
  // In a frame too small for both, the headline takes the first page and the counter the second.
  const alone = app.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom);
  const roomY = Math.min(app.clientHeight * 0.56, free >= app.clientHeight * 0.28 ? free - 2 : alone);
  const size = Math.min(roomX / widest, roomY / tall) * probe;
  title.style.fontSize = `${Math.max(14, Math.floor(size))}px`;
}

// ---------------------------------------------------------------- the burn

const TARGET_BITS = 20;
const EXPECTED_HASHES = 2 ** TARGET_BITS;
const BURN_CAP_MS = 14_000;
const SLICE_MS = 9;
/** Hashing time needed before the measured rate is worth quoting. */
const MIN_MEASURE_MS = 250;
/** hashcat benchmark, SHA2-256 (mode 1400) on one RTX 4090: about 22,000 MH/s. */
const GPU_BLOCKS_PER_SECOND = 22e9;
const BURN_KEY = 'burn-v1';

interface BurnRecord {
  hashes: number;
  busyMs: number;
  wallMs: number;
  found: boolean;
  /** The viewer scrolled on before the miner was done. */
  left?: boolean;
  best: number;
  id: string;
  blocks: number;
}

const burnCount = $<HTMLOutputElement>('#burnCount');
const burnUnit = $<HTMLElement>('#burnUnit');
const burnLine = $<HTMLElement>('#burnLine');

let burnVisible = true;
let burnDone = false;
let stopped = false;

function setMelt(progress: number): void {
  const p = Math.min(1, Math.max(0, progress));
  // The axis runs to 2050, where the letters are puddles. 2038 is melted and still readable.
  title.style.setProperty('--year', (1979 + 59 * p).toFixed(1));
  furnace.style.setProperty('--heat', p.toFixed(3));
}

function isBurnRecord(value: unknown): value is BurnRecord {
  if (typeof value !== 'object' || value === null) return false;
  const record = value as Record<string, unknown>;
  return (
    ['hashes', 'busyMs', 'wallMs', 'best', 'blocks'].every(
      (key) => typeof record[key] === 'number' && Number.isFinite(record[key]) && (record[key] as number) > 0,
    ) &&
    typeof record.found === 'boolean' &&
    typeof record.id === 'string' &&
    /^[0-9a-f]{64}$/.test(record.id)
  );
}

async function recallBurn(): Promise<BurnRecord | null> {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return null;
  try {
    const saved = await withTimeout(storage.getItem(BURN_KEY), 1200);
    const parsed: unknown = saved ? JSON.parse(saved) : null;
    return isBurnRecord(parsed) ? parsed : null;
  } catch {
    return null; // Storage is a nicety here; without it the device just mines again.
  }
}

function rememberBurn(record: BurnRecord): void {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  withTimeout(storage.setItem(BURN_KEY, JSON.stringify(record)), 3000).catch(() => undefined);
}

function describeBurn(record: BurnRecord, remembered: boolean): void {
  burnCount.textContent = whole.format(record.hashes);
  const idStart = `${record.id.slice(0, 12)}…`;
  if (remembered) {
    burnUnit.textContent = 'hashes burned by this device on your last visit';
    burnLine.textContent = record.found
      ? `They found the id ${idStart} and proved only that somebody burned power. Once is enough.`
      : `They found nothing in ${seconds(record.wallMs)} s. Once is enough.`;
  } else {
    burnUnit.textContent = 'hashes burned by this device since the page opened';
    burnLine.textContent = record.found
      ? `Stamp found after ${seconds(record.wallMs)} s: ${idStart} All it proves is that somebody burned power.`
      : record.left
        ? `Stopped after ${seconds(record.wallMs)} s, when you moved on. The best id had ${record.best} of ${TARGET_BITS} zero bits.`
        : `Gave up after ${seconds(record.wallMs)} s. The best id had ${record.best} of ${TARGET_BITS} zero bits. A browser is not a mining rig.`;
  }
  describeRace(record, remembered);
}

let lastRace: { record: BurnRecord; remembered: boolean } | null = null;

function describeRace(record: BurnRecord, remembered: boolean): void {
  lastRace = { record, remembered };
  const rate = record.hashes / (record.busyMs / 1000);
  const gpu = GPU_BLOCKS_PER_SECOND / record.blocks;
  const ratio = gpu / rate;
  const track = $<HTMLElement>('#trackGpu').clientWidth || 600;
  $('#rateYou').textContent =
    `${roughly(rate)} note ids per second, measured in your browser ${remembered ? 'on your last visit' : 'just now'}`;
  $('#rateGpu').textContent = `about ${roughly(gpu)} per second, ${roughly(ratio)} times as many`;
  $('#raceLine').textContent =
    `The orange bar is to scale. Yours would be ${trim(track / ratio)} pixels wide, so it is drawn at one. ` +
    `A ${TARGET_BITS}-bit stamp takes this page ${seconds((EXPECTED_HASHES / rate) * 1000)} s on average. ` +
    `The GPU makes ${roughly(gpu / EXPECTED_HASHES)} of them every second.`;
  $('#gpuNote').textContent =
    'GPU figure: the hashcat SHA-256 benchmark for one RTX 4090, about 22 billion one-block hashes per second, ' +
    `divided by the ${record.blocks} blocks of the note mined here. A miner that caches the first block is about twice as fast again, ` +
    'so the comparison flatters your device.';
  requestLayout();
}

function animate(durationMs: number, frame: (progress: number) => void): Promise<void> {
  if (calm() || durationMs <= 0) {
    frame(1);
    return Promise.resolve();
  }
  return new Promise((resolve) => {
    const started = now();
    const tick = (): void => {
      if (stopped) return resolve();
      const progress = Math.min(1, (now() - started) / durationMs);
      frame(progress);
      if (progress < 1) requestAnimationFrame(tick);
      else resolve();
    };
    requestAnimationFrame(tick);
  });
}

async function replayBurn(record: BurnRecord): Promise<void> {
  await animate(2200, (progress) => {
    const eased = 1 - (1 - progress) ** 3;
    setMelt(eased);
    burnCount.textContent = whole.format(Math.round(record.hashes * eased));
  });
  describeBurn(record, true);
}

function mine(): Promise<BurnRecord> {
  const miner = new R.Miner(R.bytesToHex(R.newKey().pk), Math.floor(Date.now() / 1000), TARGET_BITS);
  let wallMs = 0;
  let last = now();
  let shownAt = 0;
  return new Promise((resolve) => {
    const tick = (): void => {
      if (stopped) return;
      const time = now();
      if (!document.hidden && (burnVisible || miner.busyMs < MIN_MEASURE_MS)) {
        // Long gaps are a throttled tab, not mining time.
        wallMs += Math.min(time - last, 100);
        miner.step(time + SLICE_MS, now);
      }
      last = time;
      const progress = Math.max(miner.hashes / EXPECTED_HASHES, wallMs / BURN_CAP_MS);
      if (!calm()) setMelt(progress);
      if (!calm() || time - shownAt > 500) {
        burnCount.textContent = whole.format(miner.hashes);
        shownAt = time;
      }
      // Nobody is watching the furnace any more: enough was measured, stop burning.
      const left = !burnVisible && miner.busyMs >= MIN_MEASURE_MS;
      if (miner.found || left || wallMs >= BURN_CAP_MS) {
        resolve({
          hashes: miner.hashes,
          busyMs: miner.busyMs,
          wallMs,
          found: miner.found,
          left: left && !miner.found,
          best: miner.best,
          id: miner.bestId || '0'.repeat(64),
          blocks: miner.blocks,
        });
        return;
      }
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  });
}

async function burn(): Promise<void> {
  const remembered = await recallBurn();
  if (remembered) {
    await replayBurn(remembered);
  } else {
    const record = await mine();
    const from = Math.max(record.hashes / EXPECTED_HASHES, record.wallMs / BURN_CAP_MS);
    describeBurn(record, false);
    // A burn the viewer walked away from is not worth replaying; next time it runs again.
    if (!record.left) rememberBurn(record);
    await animate(700, (progress) => setMelt(from + (1 - from) * progress));
  }
  setMelt(1);
  burnDone = true;
}

// ---------------------------------------------------------------- the ring

type Phase = 'making' | 'idle' | 'signing' | 'checking' | 'closed';

const canvas = $<HTMLCanvasElement>('#ringCanvas');
const context = canvas.getContext('2d');
const core = $<HTMLElement>('#ringCore');
const coreBig = $<HTMLElement>('#coreBig');
const coreSmall = $<HTMLElement>('#coreSmall');
const noteText = $<HTMLTextAreaElement>('#noteText');
const signButton = $<HTMLButtonElement>('#signButton');
const result = $<HTMLElement>('#result');
const demoBeat = $<HTMLElement>('#demo');
const noteCard = $<HTMLElement>('#noteCard');
const anotherButton = $<HTMLButtonElement>('#anotherButton');
const who = $<HTMLElement>('.who');
const noteProof = $<HTMLElement>('#noteProof');

const COLORS = { bone: '255, 244, 230', lemon: '#e6ff4f' };
const MAX_RING = 500;
/** Ring radius as a share of the canvas width. */
const RING_RADIUS = 0.43;
const MIN_PERSONAL_RING = 16;

const demo = {
  size: 250,
  /** How many keys the viewer follows, when the host shared that. */
  follows: 0,
  members: [] as R.Key[],
  ring: null as R.Ring | null,
  phase: 'making' as Phase,
  /** Keys made, links signed or links checked, depending on the phase. */
  progress: 0,
  pulseAt: 0,
};

const personal = (): boolean => demo.follows > 0;

function describeRing(): void {
  const n = whole.format(demo.size);
  if (personal()) {
    const all = whole.format(demo.follows);
    $('#ringStory').textContent =
      demo.follows > demo.size
        ? `You follow ${all} keys. A list that long is split into rings, and this one has ${n}. One of them is about to tell you something, and you will never find out which one.`
        : `You follow ${all} keys. One of them is about to tell you something, and you will never find out which one.`;
    $('#noteLabel').textContent = 'The note to you';
    $('#ringNote').textContent =
      `${n} stand-in keys made by this page${demo.follows > demo.size ? '' : ', as many as you follow'}. ` +
      'Only the size of your follow list was used and nothing was sent anywhere. The signature and the check are the real thing: ' +
      'secp256k1, the curve your nostr key already lives on.';
  }
  $('#howTitle').textContent = `Three steps. The other ${whole.format(demo.size - 1)} do nothing.`;
  canvas.setAttribute('aria-label', `A ring of ${n} public keys`);
  requestLayout();
}

function setCore(big: string, small: string, state = ''): void {
  coreBig.textContent = big;
  coreSmall.textContent = small;
  core.dataset.state = state;
}

function dotAngle(index: number): number {
  return -Math.PI / 2 + (index / demo.size) * Math.PI * 2;
}

let drawQueued = false;
function requestDraw(): void {
  if (drawQueued || stopped) return;
  drawQueued = true;
  requestAnimationFrame(() => {
    drawQueued = false;
    drawRing();
  });
}

function drawRing(): void {
  if (!context) return;
  const box = canvas.getBoundingClientRect();
  if (box.width < 2) return;
  const scale = Math.min(window.devicePixelRatio || 1, 3);
  const pixels = Math.round(box.width * scale);
  if (canvas.width !== pixels || canvas.height !== pixels) {
    canvas.width = pixels;
    canvas.height = pixels;
  }
  const size = box.width;
  const centre = size / 2;
  const radius = size * RING_RADIUS;
  const n = demo.size;
  const spacing = (radius * Math.PI * 2) / n;
  const dot = Math.max(1, Math.min(5, spacing * 0.36));
  const time = now();

  context.setTransform(scale, 0, 0, scale, 0, 0);
  context.clearRect(0, 0, size, size);

  const { phase, progress } = demo;
  const walked = phase === 'checking' ? progress : phase === 'closed' ? n : 0;
  const lit = COLORS.lemon;

  // The chain of challenges, drawn as the arc it has covered so far.
  if (walked > 0) {
    context.beginPath();
    context.arc(centre, centre, radius, dotAngle(0), dotAngle(0) + (walked / n) * Math.PI * 2);
    context.lineWidth = Math.max(1.5, dot * 0.9);
    context.strokeStyle = lit;
    context.globalAlpha = 0.55;
    context.stroke();
    context.globalAlpha = 1;
  }

  // The moment the last challenge lands on the first: one ripple outwards.
  if (phase === 'closed' && demo.pulseAt && !calm()) {
    const age = (time - demo.pulseAt) / 700;
    if (age < 1) {
      context.beginPath();
      context.arc(centre, centre, radius + age * size * 0.06, 0, Math.PI * 2);
      context.lineWidth = dot * 2.4 * (1 - age);
      context.strokeStyle = COLORS.lemon;
      context.globalAlpha = 1 - age;
      context.stroke();
      context.globalAlpha = 1;
      requestDraw();
    }
  }

  for (let index = 0; index < n; index++) {
    const angle = dotAngle(index);
    const x = centre + Math.cos(angle) * radius;
    const y = centre + Math.sin(angle) * radius;
    let fill = `rgba(${COLORS.bone}, 0.5)`;
    let size_ = dot;
    if (phase === 'making') {
      fill = `rgba(${COLORS.bone}, ${index < progress ? 0.5 : 0.12})`;
    } else if (phase === 'signing') {
      // Every key takes part in signing. Nothing here may hint at the signer.
      const flicker = calm() ? 0.5 : 0.25 + 0.6 * Math.abs(Math.sin(index * 12.9898 + time * 0.012));
      fill = `rgba(${COLORS.bone}, ${flicker.toFixed(2)})`;
    } else if (index < walked) {
      fill = lit;
      if (phase === 'checking' && index >= walked - 3) size_ = dot * 1.9;
    }
    context.beginPath();
    context.arc(x, y, size_, 0, Math.PI * 2);
    context.fillStyle = fill;
    context.fill();
  }

  if (phase === 'signing' && !calm()) requestDraw();
}

/** Run a stepped computation a slice per frame, so the page keeps painting. */
function runSteps<T>(
  steps: Generator<number, T>,
  perFrame: number,
  onProgress: (count: number) => void,
): Promise<{ value: T; computeMs: number }> {
  return new Promise((resolve, reject) => {
    let computeMs = 0;
    const tick = (): void => {
      if (stopped) return;
      const started = now();
      try {
        for (let count = 0; count < perFrame; count++) {
          const next = steps.next();
          if (next.done) {
            computeMs += now() - started;
            resolve({ value: next.value, computeMs });
            return;
          }
          onProgress(next.value);
          if (now() - started > 12) break;
        }
      } catch (error) {
        reject(error instanceof Error ? error : new Error(String(error)));
        return;
      }
      computeMs += now() - started;
      requestDraw();
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  });
}

function* makeKeys(count: number): Generator<number, R.Key[]> {
  const keys: R.Key[] = [];
  while (keys.length < count) {
    keys.push(R.newKey());
    yield keys.length;
  }
  return keys;
}

async function askHostForRingSize(): Promise<void> {
  if (!runtimeHasDomain(IDENTITY_DOMAIN)) return;
  try {
    const follows = await withTimeout(identity.getFollows(), 2000);
    if (!Array.isArray(follows)) return;
    const count = new Set(follows.filter((key) => typeof key === 'string' && /^[0-9a-f]{64}$/.test(key))).size;
    if (count < MIN_PERSONAL_RING) return;
    demo.follows = count;
    demo.size = Math.min(count, MAX_RING);
  } catch {
    // Signed out, declined or slow: Alice and her 250 follows tell the story.
  }
}

function showIdle(): void {
  demo.phase = 'idle';
  setCore(whole.format(demo.size), 'keys in the ring');
  signButton.disabled = false;
  signButton.textContent = `Sign as one of the ${whole.format(demo.size)}`;
  requestDraw();
}

async function prepareRing(): Promise<void> {
  await askHostForRingSize();
  describeRing();
  demo.phase = 'making';
  setCore(whole.format(demo.size), 'keys being made');
  requestDraw();
  const made = await runSteps(makeKeys(demo.size), 64, (count) => {
    demo.progress = count;
  });
  demo.members = made.value;
  demo.ring = R.makeRing(demo.members.map((member) => member.pk));
  showIdle();
}

function showResult(): void {
  result.hidden = false;
  anotherButton.hidden = false;
  // The story and the form made their point; their room goes to the note that came out.
  demoBeat.classList.add('has-result');
}

/** Back to the form, for another note. */
function showForm(): void {
  result.hidden = true;
  anotherButton.hidden = true;
  demoBeat.classList.remove('has-result');
  if (demo.phase === 'closed') showIdle();
}

function describeWho(): void {
  const n = whole.format(demo.size);
  const others = whole.format(demo.size - 1);
  const you = personal();
  $('#whoChecks').textContent =
    `Anyone: ${you ? 'you' : 'Alice'}, a relay, any client. It takes the note, its proof and the version of ` +
    `${you ? 'your' : 'her'} follow list it names. A key outside that list cannot make such a proof.`;
  $('#whoKnows').textContent =
    `Only the writer. The proof fits all ${n} keys equally well and tells ${you ? 'you' : 'Alice'} and the relay ` +
    `nothing about which one. Each of the other ${others} knows only that it was not them.`;
}

function setBusy(busy: boolean): void {
  signButton.disabled = busy;
  anotherButton.disabled = busy;
  noteText.readOnly = busy;
}

async function signNote(): Promise<void> {
  const ring = demo.ring;
  if (!ring || demo.phase === 'signing' || demo.phase === 'checking' || demo.phase === 'making') return;
  const n = demo.size;
  const text = noteText.value.trim() || 'gm';
  // Asked before the button is switched off, which takes the focus away from it.
  const keyboard = document.activeElement === signButton;
  setBusy(true);

  try {
    // 1. A throwaway key, and a ring signature that vouches for it.
    const throwaway = R.newKey();
    const scope = personal() ? 'follows:you' : 'follows:alice';
    const message = R.credentialMessage(throwaway.pk, scope);
    const signer = randomIndex(n);
    demo.phase = 'signing';
    demo.progress = 0;
    setCore('…', 'one of them is signing');
    requestDraw();
    // In a small frame the button can be a page below the ring; the ring is what to watch now.
    if (readerIn(demoBeat)) reveal(canvas);
    const signing = await runSteps(R.signSteps(ring, message, signer, demo.members[signer].sk), n, () => undefined);

    // 2. The note itself: an ordinary event by the throwaway key.
    const event = R.signEvent(
      {
        pubkey: R.bytesToHex(throwaway.pk),
        created_at: Math.floor(Date.now() / 1000),
        kind: 1,
        tags: [['ring', scope, R.bytesToHex(ring.digest)]],
        content: text,
      },
      throwaway.sk,
    );

    // 3. What every reader does: walk the ring once and see if it closes.
    demo.phase = 'checking';
    demo.progress = 0;
    const pace = calm() ? n : Math.max(1, Math.ceil(n / 80));
    const checking = await runSteps(R.verifySteps(ring, message, signing.value), pace, (count) => {
      demo.progress = count;
      setCore(whole.format(count), `of ${whole.format(n)} links checked`);
    });
    if (!checking.value || !R.verifyEvent(event)) throw new Error('The proof did not verify');

    demo.phase = 'closed';
    demo.pulseAt = now();
    setCore('Closed', 'the ring verifies', 'closed');
    noteCard.dataset.state = 'accepted';
    $('#noteFrom').textContent = !personal()
      ? `One of Alice's ${whole.format(n)} follows`
      : demo.follows > n
        ? `One of ${whole.format(n)} keys you follow`
        : `One of your ${whole.format(n)} follows`;
    noteProof.textContent =
      `Signed in ${whole.format(Math.max(1, Math.round(signing.computeMs)))} ms, checked in ` +
      `${whole.format(Math.max(1, Math.round(checking.computeMs)))} ms${calm() ? '' : '; the walk you saw was slowed down'}. ` +
      `${whole.format(R.signatureBytes(signing.value))} bytes of proof, no mining.`;
    describeWho();
    who.hidden = false;
    anotherButton.textContent = 'Sign another note';
  } catch {
    demo.phase = 'idle';
    setCore(whole.format(n), 'keys in the ring');
    noteCard.dataset.state = 'failed';
    $('#noteFrom').textContent = 'That did not work';
    noteProof.textContent = 'The signing step failed in this browser.';
    who.hidden = true;
    anotherButton.textContent = 'Back to the note';
  }
  $('#noteBody').textContent = text;
  showResult();
  setBusy(false);
  if (keyboard) anotherButton.focus({ preventScroll: true });
  requestDraw();
  // The beat changed shape: lay out its pages again, then show the one with the note on it,
  // unless the reader has paged on in the meantime.
  layoutStops();
  if (readerIn(demoBeat)) reveal(noteCard);
}

// A click handler, not a form: the host sandbox does not allow form submission.
signButton.addEventListener('click', () => void signNote());

anotherButton.addEventListener('click', () => {
  // A keyboard user stays on a control; the text field is not focused, so the arrows keep turning pages.
  const keyboard = document.activeElement === anotherButton;
  showForm();
  layoutStops();
  reveal(noteText);
  if (keyboard) signButton.focus({ preventScroll: true });
});

// --------------------------------------------------------------- the frame

// The page is a deck: every way of moving lands on a page. A beat that fits the
// frame is one page. A taller one is set like print: a paragraph that would
// cross the bottom edge is pushed to the top of the next page, so pages are
// whole frames and no line is cut. Only a paragraph taller than the frame is
// paged through line by line.

const beats = [...document.querySelectorAll<HTMLElement>('.beat')];
const pager = $<HTMLElement>('.pager');
const pageUp = $<HTMLButtonElement>('#pageUp');
const pageDown = $<HTMLButtonElement>('#pageDown');

/** Boxes that only arrange other boxes; everything else is kept whole on a page. */
const GROUPS = 'ul, ol, dl, div:not(.ring-stage, .race-track, .who-item, .note-form)';

/** Scroll offsets of all pages, top to bottom, and the beat and page within it that each one is. */
let stops: number[] = [0];
let places: Array<[beat: number, page: number]> = [[0, 0]];
/** The page a scroll is under way to, or -1. */
let aim = -1;
let aimTimer = 0;
/** When the page last moved, by any means. */
let scrolledAt = 0;
/** The page the reader is on or heading to, as an index into `stops`. */
let here = 0;
/** The layout has changed since the pages were set; scroll offsets mean nothing until they are set again. */
let stale = false;
let settleTimer = 0;

interface Block {
  element: HTMLElement;
  top: number;
  bottom: number;
}

/** Paragraphs that were pushed to a later page, per beat, to undo it before laying out again. */
const pushed = new Map<HTMLElement, HTMLElement[]>();

/** The boxes of a beat that belong on one page each, measured from the top of the beat. */
function blocksOf(beat: HTMLElement, opened: Set<Element>): Block[] {
  const origin = beat.getBoundingClientRect().top;
  const blocks: Block[] = [];
  const walk = (parent: Element): void => {
    for (const child of parent.children) {
      if (!(child instanceof HTMLElement) || child.classList.contains('stop')) continue;
      const box = child.getBoundingClientRect();
      if (box.height < 1) continue;
      if (child.matches(GROUPS) || opened.has(child)) walk(child);
      else blocks.push({ element: child, top: box.top - origin, bottom: box.bottom - origin });
    }
  };
  walk(beat);
  return blocks.sort((a, b) => a.top - b.top);
}

/** Lay one beat out in pages. Returns where they start, measured from the top of the beat. */
function paginate(beat: HTMLElement, view: number): number[] {
  for (const element of pushed.get(beat) ?? []) element.style.marginTop = '';
  const moved: HTMLElement[] = [];
  pushed.set(beat, moved);
  beat.classList.remove('paged');
  beat.style.minHeight = '';
  if (beat.offsetHeight <= view + 1) return [0];

  beat.classList.add('paged');
  const style = getComputedStyle(beat);
  const padTop = parseFloat(style.paddingTop) || 0;
  // The page buttons stand in the bottom padding; nothing may wait for its turn behind them.
  const usable = view - (parseFloat(style.paddingBottom) || 0);
  const opened = new Set<Element>();
  const pages = [0];
  let at = 0;
  let pushes = 0;
  let blocks = blocksOf(beat, opened);
  for (let guard = 0; guard < 300; guard++) {
    // The first box that does not end on this page.
    const cut = blocks.find((block) => block.bottom > at + usable + 1);
    if (!cut) break;
    if (cut.top > at + padTop + 2 && pushes < 12) {
      const target = at + view + padTop;
      if (cut.top < target - 1) {
        // It starts on this page: move it to the top of the next and look again.
        const margin = (parseFloat(cut.element.style.marginTop) || 0) + target - cut.top;
        cut.element.style.marginTop = `${margin}px`;
        if (!moved.includes(cut.element)) moved.push(cut.element);
        pushes++;
        blocks = blocksOf(beat, opened);
        continue;
      }
      at += view;
    } else if (!opened.has(cut.element) && cut.element.matches('li, article, .who-item') && cut.element.children.length > 0) {
      // Taller than a page, but made of parts: place the parts instead.
      opened.add(cut.element);
      blocks = blocksOf(beat, opened);
      continue;
    } else {
      // One paragraph taller than a page: go on inside it, repeating its last full line.
      const line = parseFloat(getComputedStyle(cut.element).lineHeight);
      const lines = line > 4 ? Math.floor((at + usable - cut.top) / line) - 1 : 0;
      const byLine = cut.top + lines * line - 2;
      at = Math.round(byLine > at + view * 0.3 ? byLine : at + usable * 0.85);
    }
    pushes = 0;
    pages.push(at);
  }
  beat.style.minHeight = `${at + view}px`;
  return pages;
}

function layoutStops(): void {
  const view = app.clientHeight;
  if (view < 1) return;
  // The place was noted while the old layout still held; the scroll offset may have moved since.
  const [heldBeat, heldPage] = places[here] ?? [0, 0];
  // While the beats are taken apart and set again, the browser must not snap to a half-built
  // page: it would follow that page's marker to wherever it ends up.
  app.style.scrollSnapType = 'none';
  const perBeat = beats.map((beat) => {
    const pages = paginate(beat, view);
    // The beat snaps at its own top; every further page gets a marker inside it.
    const marks = [...beat.querySelectorAll<HTMLElement>(':scope > .stop')];
    while (marks.length < pages.length - 1) {
      const mark = document.createElement('i');
      mark.className = 'stop';
      mark.setAttribute('aria-hidden', 'true');
      beat.append(mark);
      marks.push(mark);
    }
    while (marks.length > pages.length - 1) marks.pop()?.remove();
    pages.forEach((offset, index) => {
      if (index > 0) marks[index - 1].style.top = `${offset}px`;
    });
    return pages;
  });
  stops = [];
  places = [];
  let held = 0;
  perBeat.forEach((pages, beat) => {
    pages.forEach((offset, index) => {
      if (beat === heldBeat && index <= heldPage) held = stops.length;
      stops.push(beats[beat].offsetTop + offset);
      places.push([beat, index]);
    });
  });
  here = held;
  stale = false;
  // Laying out again must not turn the page under the reader.
  if (aim >= 0) goToStop(here);
  // A finger is dragging the page, or its snap is still running: it lands where it lands.
  else if (fingerBusy()) settle();
  else if (Math.abs(app.scrollTop - stops[here]) > 0.5) app.scrollTop = stops[here];
  app.style.scrollSnapType = '';
  showPlace();
}

let layoutQueued = false;
/** Call after anything that can change the height of a beat: its pages have to be set again. */
function requestLayout(): void {
  stale = true;
  if (layoutQueued || stopped) return;
  layoutQueued = true;
  requestAnimationFrame(() => {
    layoutQueued = false;
    layoutStops();
  });
}

function currentStop(): number {
  const top = app.scrollTop;
  let current = 0;
  stops.forEach((stop, index) => {
    if (Math.abs(stop - top) < Math.abs(stops[current] - top)) current = index;
  });
  return current;
}

/** Note the page the reader has come to rest on, for example after dragging there with a finger. */
function learnPlace(): void {
  if (stale || aim >= 0) return;
  const index = currentStop();
  if (Math.abs(stops[index] - app.scrollTop) <= 2) here = index;
}

/** After a layout under a moving finger: once the page has landed, make sure it landed on a page. */
function settle(): void {
  window.clearTimeout(settleTimer);
  if (aim >= 0) return;
  if (fingerBusy() || now() - scrolledAt <= 200) {
    settleTimer = window.setTimeout(settle, 220);
    return;
  }
  here = currentStop();
  if (Math.abs(app.scrollTop - stops[here]) > 0.5) app.scrollTop = stops[here];
  showPlace();
}

function setDisabled(button: HTMLButtonElement, other: HTMLButtonElement, off: boolean): void {
  // A button that switches off under the keyboard hands its focus to its neighbour.
  if (off && !button.disabled && document.activeElement === button) other.focus({ preventScroll: true });
  button.disabled = off;
}

function showPlace(): void {
  setDisabled(pageUp, pageDown, here <= 0);
  setDisabled(pageDown, pageUp, here >= stops.length - 1);
  pager.dataset.first = String(here === 0);
}

function goToStop(index: number): void {
  const to = Math.max(0, Math.min(stops.length - 1, index));
  here = to;
  aim = to;
  window.clearTimeout(aimTimer);
  aimTimer = window.setTimeout(() => {
    aim = -1;
    learnPlace();
    showPlace();
  }, 900);
  app.scrollTo({ top: stops[to], behavior: calm() ? 'auto' : 'smooth' });
  showPlace();
}

/** One page down or up. Presses during a scroll add up. */
function page(direction: 1 | -1): void {
  learnPlace();
  goToStop(here + direction);
}

/** Whether the reader is on a page of this beat. */
function readerIn(beat: HTMLElement): boolean {
  return places[here]?.[0] === beats.indexOf(beat);
}

/** Show the page of its beat that the element starts on. */
function reveal(element: HTMLElement): void {
  const beat = element.closest<HTMLElement>('.beat');
  if (!beat) return;
  const top = element.getBoundingClientRect().top - app.getBoundingClientRect().top + app.scrollTop;
  const own = beats.indexOf(beat);
  let found = -1;
  places.forEach(([index], stop) => {
    if (index === own && (found < 0 || stops[stop] <= top + 1)) found = stop;
  });
  if (found >= 0) goToStop(found);
}

app.addEventListener(
  'scroll',
  () => {
    scrolledAt = now();
    learnPlace();
    showPlace();
  },
  { passive: true },
);
app.addEventListener('scrollend', () => {
  window.clearTimeout(aimTimer);
  aim = -1;
  learnPlace();
  showPlace();
});

// A finger drags the page itself. It counts as busy until the snap that follows the lift has run.
const finger = { down: false, at: 0 };
const fingerBusy = (): boolean => finger.down || now() - finger.at < 600;
for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel'] as const) {
  app.addEventListener(
    type,
    (event) => {
      finger.down = event.touches.length > 0;
      finger.at = now();
    },
    { passive: true },
  );
}

// A new frame size moves the scroll offset before the pages are set again;
// until then that offset says nothing about where the reader is.
window.addEventListener('resize', () => {
  stale = true;
});

pageUp.addEventListener('click', () => page(-1));
pageDown.addEventListener('click', () => page(1));

window.addEventListener('keydown', (event) => {
  if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return;
  const target = event.target;
  if (target instanceof HTMLTextAreaElement) {
    // Arrows belong to the text while it is being edited; Escape hands them back to the pages.
    if (event.key === 'Escape') target.blur();
    return;
  }
  // Space stays a click on a focused button; anywhere else it turns the page.
  const space = event.key === ' ' && !(target instanceof HTMLButtonElement);
  const down = event.key === 'ArrowDown' || event.key === 'PageDown' || (space && !event.shiftKey);
  const up = event.key === 'ArrowUp' || event.key === 'PageUp' || (space && event.shiftKey);
  if (!down && !up && event.key !== 'Home' && event.key !== 'End') return;
  event.preventDefault();
  // A held key turns one page, not all of them.
  if (event.repeat) return;
  if (down) page(1);
  else if (up) page(-1);
  else goToStop(event.key === 'Home' ? 0 : stops.length - 1);
});

// The wheel: one page per push. A trackpad keeps sending smaller and smaller
// deltas after the fingers have left; those must not turn a second page, and
// neither may a slow drag that never pauses.
const wheel = { at: 0, size: 0, lockedUntil: 0 };

// On the window, so that it also works with the pointer over the page buttons.
window.addEventListener(
  'wheel',
  (event) => {
    if (event.ctrlKey) return; // pinch zoom
    const target = event.target;
    if (target instanceof HTMLTextAreaElement) {
      // A note longer than its field scrolls first; at its end the wheel turns the page.
      const room = event.deltaY > 0 ? target.scrollHeight - target.clientHeight - target.scrollTop : target.scrollTop;
      if (room > 1) return;
    }
    event.preventDefault();
    const size = Math.abs(event.deltaY);
    if (size < 1 || size < Math.abs(event.deltaX)) return;
    const time = now();
    const fresh = time - wheel.at > 180;
    // A second push on top of a fading one stands out clearly from the tail.
    const pushed = size > wheel.size * 2 + 8;
    // A wheel with notches reports whole lines, or whole multiples of 120 in the old unit.
    const old = (event as WheelEvent & { wheelDeltaY?: number }).wheelDeltaY;
    // A trackpad reports pixels, and its old-unit value is just three times that.
    const notched =
      event.deltaMode !== 0 ||
      (typeof old === 'number' && old !== 0 && Math.abs(old) % 120 === 0 && Math.abs(old) !== Math.round(size * 3));
    wheel.at = time;
    wheel.size = size;
    if (time < wheel.lockedUntil || !(fresh || pushed || notched)) return;
    wheel.lockedUntil = time + 550;
    page(event.deltaY > 0 ? 1 : -1);
  },
  { passive: false },
);

// A click on anything that is not a control turns the page, and so does a drag
// with the mouse. A finger drags the page itself and the snap points catch it.
const CONTROLS = 'button, textarea, label, a, input';
const SELECTABLE = '[data-napplet-select="text"]';
const press = { control: false, drag: false, x: 0, y: 0, turned: false };
let clickTimer = 0;
const selected = (): boolean => String(document.getSelection() ?? '') !== '';

app.addEventListener('pointerdown', (event) => {
  press.turned = false;
  press.control = !!(event.target as Element).closest(CONTROLS);
  press.drag = event.pointerType === 'mouse' && event.button === 0 && !press.control;
  press.x = event.clientX;
  press.y = event.clientY;
});

app.addEventListener('pointerup', (event) => {
  if (!press.drag) return;
  press.drag = false;
  const dx = event.clientX - press.x;
  const dy = event.clientY - press.y;
  if (Math.abs(dy) < 40 || Math.abs(dy) < Math.abs(dx) * 1.2 || selected()) return;
  press.turned = true;
  page(dy < 0 ? 1 : -1);
});

app.addEventListener('click', (event) => {
  window.clearTimeout(clickTimer);
  if (event.defaultPrevented || event.button !== 0) return;
  if (press.turned) {
    press.turned = false;
    return;
  }
  const target = event.target as Element;
  // A press that began in the note field or on a button belongs to it, wherever it ends.
  if (press.control || target.closest(CONTROLS)) return;
  // The second click of a double-click selects a word or is a slip; it is not a second page.
  if (event.detail > 1) return;
  if (target.closest(SELECTABLE)) {
    // Somebody selecting text is reading, not leaving.
    if (selected()) return;
    // This may be the first half of a double-click on a word: wait and see.
    clickTimer = window.setTimeout(() => {
      if (!selected()) page(1);
    }, 280);
    return;
  }
  // Elsewhere a click lets go of a selection, as it does on any page.
  if (selected()) document.getSelection()?.removeAllRanges();
  page(1);
});

$('#againButton').addEventListener('click', () => {
  showForm();
  layoutStops();
  reveal($('#demoTitle'));
  window.setTimeout(() => void signNote(), calm() ? 0 : 600);
});

new IntersectionObserver(
  (entries) => {
    for (const entry of entries) burnVisible = entry.isIntersecting;
  },
  { root: app, threshold: 0.01 },
).observe(furnace);

const resized = new ResizeObserver(() => {
  fitTitle();
  requestDraw();
  // The caption quotes a width in pixels of the bar as it is drawn now.
  if (lastRace) describeRace(lastRace.record, lastRace.remembered);
  // Not in here: laying out pages changes sizes, and this observer would report itself.
  requestLayout();
});
resized.observe(app);
resized.observe(canvas);
// Text that arrives later (the measured rates, the signed note) can make a beat taller.
for (const beat of beats) resized.observe(beat);

window.addEventListener('pagehide', (event) => {
  // A page parked in the back/forward cache comes back alive; only a real unload stops the loops.
  if (event.persisted) return;
  stopped = true;
  resized.disconnect();
});

async function start(): Promise<void> {
  await Promise.race([
    Promise.all([
      loadFont('Climate Crisis', 'display-font'),
      loadFont('Bricolage Grotesque', 'text-font', { weight: '200 800', stretch: '75% 100%' }),
    ]),
    new Promise((resolve) => window.setTimeout(resolve, 2500)),
  ]);
  root.classList.add('fonts-ready');
  fitTitle();
  layoutStops();
  void document.fonts.ready.then(() => {
    fitTitle();
    layoutStops();
  });
  if (calm()) setMelt(1);
  // The ring is prepared in small slices while the furnace runs.
  void prepareRing().catch(() => {
    signButton.textContent = 'The keys could not be made in this browser';
  });
  await burn();
}

if (import.meta.env.DEV) {
  // Test hook for the scripted walkthrough; absent from the published build.
  (window as unknown as { __pom: unknown }).__pom = { demo, done: () => burnDone };
}

void start();