Back to Morse Tree
SOURCE / PINNED RELEASE

Made of little things.

Morse Tree

Release
52c388d28ec3…
Author-recorded commit
fd8192a198f7…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-6ab5aa84ba1

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

src/main.ts
import { STORAGE_DOMAIN, storage } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import {
  DASH_FROM_UNITS,
  LETTER_CODES,
  LETTER_GAP_UNITS,
  MAX_DEPTH,
  WORD_GAP_UNITS,
  accuracy,
  classifyGap,
  classifyMark,
  codeOf,
  ditMs,
  hasNode,
  idealUnits,
  letterAt,
  letterTreeCodes,
  schedule,
  treeSlots,
  type Gap,
  type Mark,
} from './morse.js';
import './styles.css';

const SVG_NS = 'http://www.w3.org/2000/svg';
const SPEEDS = [5, 8, 12, 16, 20];
const TAPE_LIMIT = 240;

// ------------------------------------------------------------------ elements

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

const el = {
  app: requireElement<HTMLElement>('#app'),
  stage: requireElement<HTMLElement>('#stage'),
  tree: requireElement<SVGSVGElement>('#tree'),
  compact: requireElement<HTMLDivElement>('#compact'),
  banner: requireElement<HTMLDivElement>('#banner'),
  tapeText: requireElement<HTMLDivElement>('#tapeText'),
  playTape: requireElement<HTMLButtonElement>('#playTape'),
  backspace: requireElement<HTMLButtonElement>('#backspace'),
  clearTape: requireElement<HTMLButtonElement>('#clearTape'),
  key: requireElement<HTMLButtonElement>('#morseKey'),
  meterFill: requireElement<HTMLSpanElement>('#meterFill'),
  strip: requireElement<SVGSVGElement>('#strip'),
  rhythm: requireElement<HTMLSpanElement>('#rhythm'),
  sea: requireElement<HTMLElement>('#sea'),
  house: requireElement<SVGSVGElement>('#sea .house'),
  boat: requireElement<SVGSVGElement>('#sea .boat'),
  quiz: requireElement<HTMLButtonElement>('#quizToggle'),
  lightQuiz: requireElement<HTMLButtonElement>('#lightQuizToggle'),
  speed: requireElement<HTMLButtonElement>('#speedToggle'),
  sound: requireElement<HTMLButtonElement>('#soundToggle'),
};

// ------------------------------------------------------------------ state

interface Saved {
  tape: string;
  wpm: number;
  sound: boolean;
  best: number;
}

const saved: Saved = { tape: '', wpm: 8, sound: true, best: 0 };

/** Code keyed so far for the letter being written. */
let cursor = '';

/** 'sound' plays the question as tones; 'light' only flashes it from the boat. */
type QuizMode = 'sound' | 'light';
let quiz: { target: string; streak: number; mode: QuizMode } | null = null;

const SAVE_KEY = 'morse-tree-state';
let saveTimer = 0;

function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
  let timer = 0;
  return Promise.race([
    promise,
    new Promise<T>((_, reject) => {
      timer = window.setTimeout(() => reject(new Error('timeout')), ms);
    }),
  ]).finally(() => window.clearTimeout(timer));
}

async function load(): Promise<void> {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  try {
    const raw = await withTimeout(storage.getItem(SAVE_KEY), 3000);
    if (!raw) return;
    const data = JSON.parse(raw) as Partial<Saved>;
    if (typeof data.tape === 'string') saved.tape = data.tape.slice(-TAPE_LIMIT);
    if (typeof data.wpm === 'number' && SPEEDS.includes(data.wpm)) saved.wpm = data.wpm;
    if (typeof data.sound === 'boolean') saved.sound = data.sound;
    if (typeof data.best === 'number' && data.best >= 0) saved.best = Math.floor(data.best);
  } catch {
    // Storage is optional; a fresh tape is a fine start.
  }
}

function save(): void {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  window.clearTimeout(saveTimer);
  saveTimer = window.setTimeout(() => {
    void withTimeout(storage.setItem(SAVE_KEY, JSON.stringify(saved)), 3000).catch(() => undefined);
  }, 400);
}

// ------------------------------------------------------------------ audio

let audio: AudioContext | null = null;
let master: GainNode | null = null;
const TONE_HZ = 640;

/** Create the audio graph on the first user gesture. */
function ensureAudio(): void {
  if (audio) {
    if (audio.state === 'suspended') void audio.resume();
    return;
  }
  try {
    audio = new AudioContext();
    master = audio.createGain();
    master.gain.value = 0.22;
    master.connect(audio.destination);
  } catch {
    audio = null;
  }
}

let liveTones: OscillatorNode[] = [];

function beep(atMs: number, lengthMs: number, hz = TONE_HZ, type: OscillatorType = 'sine'): void {
  if (!audio || !master || !saved.sound) return;
  const start = audio.currentTime + atMs / 1000 + 0.01;
  const end = start + lengthMs / 1000;
  const osc = audio.createOscillator();
  const gain = audio.createGain();
  osc.type = type;
  osc.frequency.value = hz;
  gain.gain.setValueAtTime(0, start);
  gain.gain.linearRampToValueAtTime(1, start + 0.006);
  gain.gain.setValueAtTime(1, Math.max(start + 0.006, end - 0.006));
  gain.gain.linearRampToValueAtTime(0, end);
  osc.connect(gain).connect(master);
  osc.start(start);
  osc.stop(end + 0.02);
  liveTones.push(osc);
  osc.onended = () => {
    liveTones = liveTones.filter((tone) => tone !== osc);
  };
}

function buzz(): void {
  beep(0, 90, 160, 'square');
  beep(110, 140, 120, 'square');
}

function chime(): void {
  beep(0, 70, 880, 'triangle');
  beep(80, 70, 1175, 'triangle');
  beep(160, 140, 1568, 'triangle');
}

// ------------------------------------------------------------------ lamps

// The boat flashes what we receive; the lamp on the house's balcony flashes
// what we send: the key, and the tape we wrote when it is played back.
function lamp(which: 'house' | 'boat', on: boolean): void {
  el[which].classList.toggle('lit', on);
}

// ------------------------------------------------------------------ playback

let playToken = 0;
let playTimers: number[] = [];

function stopPlayback(): void {
  playToken += 1;
  playTimers.forEach((timer) => window.clearTimeout(timer));
  playTimers = [];
  for (const tone of liveTones) {
    try {
      tone.stop();
    } catch {
      // Already stopped.
    }
  }
  liveTones = [];
  el.tapeText.querySelectorAll('.playing').forEach((node) => node.classList.remove('playing'));
  el.playTape.classList.remove('active');
  lamp('boat', false);
  lamp('house', false);
  showPath('');
}

function later(ms: number, token: number, action: () => void): void {
  playTimers.push(
    window.setTimeout(() => {
      if (token === playToken) action();
    }, ms),
  );
}

/**
 * Play a text and walk the tree in step with it. `onLetter` fires as each
 * letter starts, `onDone` after the last tone.
 */
function play(
  text: string,
  onLetter?: (letter: number) => void,
  onDone?: () => void,
  walk = true,
  silent = false,
  from: 'house' | 'boat' = 'boat',
): void {
  stopPlayback();
  ensureAudio();
  const token = playToken;
  const unit = ditMs(saved.wpm);
  const { tones, length } = schedule(text);
  const letters = [...text];
  for (const tone of tones) {
    const code = codeOf(letters[tone.letter]) ?? '';
    if (!silent) beep(tone.start * unit, tone.length * unit);
    later(tone.start * unit, token, () => lamp(from, true));
    later((tone.start + tone.length) * unit, token, () => lamp(from, false));
    if (!walk) continue;
    later(tone.start * unit, token, () => {
      if (tone.symbol === 0) {
        onLetter?.(tone.letter);
        showPath('');
      }
      travel(code.slice(0, tone.symbol + 1), tone.length * unit);
    });
  }
  later(length * unit + 450, token, () => {
    showPath('');
    onDone?.();
  });
}

// ------------------------------------------------------------------ tree

interface NodeView {
  group: SVGGElement;
  label: SVGTextElement;
  x: number;
  y: number;
  r: number;
}

const nodes = new Map<string, NodeView>();
const edges = new Map<string, SVGGElement>();
let spark: SVGCircleElement | null = null;
let ring: SVGCircleElement | null = null;
let layoutKey = '';

function svg<K extends keyof SVGElementTagNameMap>(
  tag: K,
  attrs: Record<string, string | number>,
  parent?: Element,
): SVGElementTagNameMap[K] {
  const node = document.createElementNS(SVG_NS, tag);
  for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value));
  parent?.append(node);
  return node;
}

function buildTree(): void {
  const width = el.stage.clientWidth;
  const height = el.stage.clientHeight;
  const compact = width < 170 || height < 120;
  el.stage.classList.toggle('is-compact', compact);
  const key = `${width}x${height}`;
  if (key === layoutKey) return;
  layoutKey = key;
  el.tree.replaceChildren();
  nodes.clear();
  edges.clear();
  if (compact || width === 0) {
    renderCompact();
    return;
  }

  el.tree.setAttribute('viewBox', `0 0 ${width} ${height}`);
  // Root at the top on wide frames; root on the left on tall, narrow ones so
  // the sixteen leaves get the long side.
  const vertical = width >= height * 0.85;
  const breadth = vertical ? width : height;
  const reach = vertical ? height : width;
  const { slots, count } = treeSlots();
  const leafGap = breadth / count;
  const pad = Math.min(reach * 0.1, 34);
  const levelGap = (reach - pad * 2) / MAX_DEPTH;
  const baseR = Math.max(7, Math.min(leafGap * 0.42, levelGap * 0.34, 30));
  // Levels one and two have room to spare; three and four sit a slot apart.
  const depthScale = [0.8, 1.3, 1.18, 1, 1];

  const place = (code: string) => {
    const depth = code.length;
    const along = ((slots.get(code) ?? 0) + 0.5) * leafGap;
    const down = pad + depth * levelGap;
    return vertical ? { x: along, y: down } : { x: down, y: along };
  };

  const edgeLayer = svg('g', { class: 'edges' }, el.tree);
  const nodeLayer = svg('g', { class: 'nodes' }, el.tree);

  for (const code of letterTreeCodes()) {
    const { x, y } = place(code);
    const depth = code.length;
    const r = baseR * depthScale[depth];
    const letter = letterAt(code);

    if (depth > 0) {
      const parent = place(code.slice(0, -1));
      const isDah = code.endsWith('-');
      const group = svg('g', { class: `edge ${isDah ? 'edge-dah' : 'edge-dit'}` }, edgeLayer);
      svg('line', { x1: parent.x, y1: parent.y, x2: x, y2: y, class: 'edge-under' }, group);
      svg('line', { x1: parent.x, y1: parent.y, x2: x, y2: y, class: 'edge-line' }, group);
      edges.set(code, group);
    }

    const group = svg(
      'g',
      {
        class: `node depth-${depth}${letter ? ' has-letter' : ''}${depth === 0 ? ' root' : ''}`,
        transform: `translate(${x} ${y})`,
      },
      nodeLayer,
    );
    if (letter) {
      // Leaves are small on phones; the invisible hit disc fills the gap to the neighbours.
      svg('circle', { r: Math.max(r, Math.min(leafGap, levelGap) * 0.5), class: 'node-hit' }, group);
    }
    const body = svg('g', { class: 'node-body' }, group);
    svg('circle', { r, class: 'node-disc' }, body);
    const label = svg(
      'text',
      { class: 'node-label', 'text-anchor': 'middle', 'dominant-baseline': 'central', 'font-size': r * 1.05 },
      body,
    );
    label.textContent = depth === 0 ? '' : (letter ?? '');
    if (depth === 0) {
      svg('circle', { r: r * 0.28, class: 'root-dot' }, body);
    }
    if (letter) {
      group.setAttribute('role', 'button');
      group.setAttribute('tabindex', '-1');
      group.setAttribute('aria-label', `${letter}: ${spoken(code)}`);
      group.addEventListener('pointerdown', (event) => {
        event.preventDefault();
        tapLetter(letter);
      });
    }
    nodes.set(code, { group, label, x, y, r });
  }

  // Dot and dash legends next to the root's two branches.
  const root = place('');
  const legendOffset = baseR * (vertical ? 1.9 : 3.2);
  const legends: [string, string, number, number][] = vertical
    ? [['legend legend-dit', '●  dot', root.x - legendOffset, root.y], ['legend legend-dah', 'dash  ▬', root.x + legendOffset, root.y]]
    : [['legend legend-dit', '● dot', root.x - baseR * 0.8, root.y - legendOffset], ['legend legend-dah', '▬ dash', root.x - baseR * 0.8, root.y + legendOffset]];
  // Flat trees leave no room beside the root; the key colours carry the meaning then.
  if (levelGap < baseR * 3) legends.length = 0;
  for (const [cls, text, x, y] of legends) {
    const legend = svg(
      'text',
      {
        class: cls,
        x,
        y,
        'text-anchor': vertical && cls.includes('dit') ? 'end' : 'start',
        'dominant-baseline': 'central',
        'font-size': Math.max(10, Math.min(15, baseR * 0.6)),
      },
      nodeLayer,
    );
    legend.textContent = text;
  }

  // Under the nodes: the spark runs along the edges and tucks in behind each disc.
  spark = svg('circle', { class: 'spark', r: Math.max(4, baseR * 0.3), cx: 0, cy: 0 }, edgeLayer);
  spark.style.transform = `translate(${root.x}px, ${root.y}px)`;
  ring = null;
  refreshTree();
}

function spoken(code: string): string {
  return [...code].map((symbol) => (symbol === '-' ? 'dah' : 'dit')).join(' ');
}

/** Mark the nodes and edges from the root to `code`. */
function showPath(code: string): void {
  for (const [nodeCode, view] of nodes) {
    view.group.classList.toggle('on-path', code.startsWith(nodeCode) && nodeCode.length <= code.length);
    view.group.classList.toggle('current', nodeCode === code && code !== '');
  }
  for (const [edgeCode, group] of edges) {
    group.classList.toggle('lit', code.startsWith(edgeCode));
  }
  if (code === '' && spark) {
    const root = nodes.get('');
    if (root) moveSpark(root, 0);
  }
  renderCompact(code);
}

function moveSpark(view: NodeView, ms: number): void {
  if (!spark) return;
  spark.style.transitionDuration = `${Math.round(ms)}ms`;
  spark.style.transform = `translate(${view.x}px, ${view.y}px)`;
  spark.classList.toggle('moving', ms > 0);
}

/** Light the path to `code` and slide the spark along its last edge. */
function travel(code: string, ms: number): void {
  showPath(code);
  const view = nodes.get(code);
  if (view) {
    moveSpark(view, ms);
    bounce(view.group);
  }
}

function bounce(group: Element): void {
  group.classList.remove('pop');
  // Restart the CSS animation.
  void (group as SVGGElement).getBBox?.();
  group.classList.add('pop');
}

function refreshTree(): void {
  showPath(cursor);
}

/** While the key is down: mark the node this press would reach if released now. */
function showPreview(code: string | null): void {
  for (const [nodeCode, view] of nodes) view.group.classList.toggle('preview', nodeCode === code);
  const stuck = code !== null && !hasNode(code);
  nodes.get(cursor)?.group.classList.toggle('preview-none', stuck);
  if (code === null) nodes.forEach((view) => view.group.classList.remove('preview-none'));
}

function reveal(code: string): void {
  const view = nodes.get(code);
  if (!view) return;
  view.group.classList.remove('reveal');
  void view.group.getBBox?.();
  view.group.classList.add('reveal');
  window.setTimeout(() => view.group.classList.remove('reveal'), 1400);
}

function shake(code: string): void {
  const view = nodes.get(code) ?? nodes.get('');
  if (!view) return;
  view.group.classList.remove('shake');
  void view.group.getBBox?.();
  view.group.classList.add('shake');
  window.setTimeout(() => view.group.classList.remove('shake'), 500);
}

function burst(code: string): void {
  const view = nodes.get(code);
  if (!view) return;
  const colors = ['#ff6b5a', '#1fb5a8', '#ffc83d', '#8b6cff'];
  const layer = svg('g', { class: 'burst', transform: `translate(${view.x} ${view.y})` }, el.tree);
  for (let i = 0; i < 14; i += 1) {
    const angle = (i / 14) * Math.PI * 2;
    const dist = view.r * (1.8 + Math.random() * 1.4);
    const piece = svg('circle', { r: Math.max(2, view.r * 0.16), fill: colors[i % colors.length] }, layer);
    piece.style.setProperty('--dx', `${Math.cos(angle) * dist}px`);
    piece.style.setProperty('--dy', `${Math.sin(angle) * dist}px`);
  }
  window.setTimeout(() => layer.remove(), 900);
}

/** Small frames show only the code and the letter it reaches. */
function renderCompact(code = cursor): void {
  if (!el.stage.classList.contains('is-compact')) return;
  const letter = letterAt(code);
  const shown = letter ?? '?';
  el.compact.innerHTML = '';
  const big = document.createElement('div');
  big.className = 'compact-letter';
  big.textContent = code === '' ? '' : shown;
  const symbols = document.createElement('div');
  symbols.className = 'compact-code';
  symbols.textContent = code === '' ? 'tap ● hold ▬' : [...code].map((s) => (s === '-' ? '▬' : '●')).join(' ');
  el.compact.append(big, symbols);
}

// ------------------------------------------------------------------ keying

// One straight key. The press length decides dot or dash and the silence after
// it decides whether the letter or the word is over, all at the ITU midpoints
// for the chosen speed (see morse.ts).

/** performance.now() when the key went down, 0 while it is up. */
let downAt = 0;
/** performance.now() when the last counted press ended, 0 after a long pause. */
let upAt = 0;
let holdFrame = 0;
let letterTimer = 0;
let wordTimer = 0;
/** The marks keyed since the last letter gap make no letter; wait for silence. */
let garbled = false;
let sidetone: { osc: OscillatorNode; gain: GainNode } | null = null;

function unitMs(): number {
  return ditMs(saved.wpm);
}

function toneOn(): void {
  if (!audio || !master || !saved.sound) return;
  const now = audio.currentTime;
  const osc = audio.createOscillator();
  const gain = audio.createGain();
  osc.frequency.value = TONE_HZ;
  gain.gain.setValueAtTime(0, now);
  gain.gain.linearRampToValueAtTime(1, now + 0.005);
  osc.connect(gain).connect(master);
  osc.start(now);
  sidetone = { osc, gain };
}

function toneOff(): void {
  if (!audio || !sidetone) return;
  const now = audio.currentTime;
  const { osc, gain } = sidetone;
  gain.gain.cancelScheduledValues(now);
  gain.gain.setValueAtTime(gain.gain.value, now);
  gain.gain.linearRampToValueAtTime(0, now + 0.005);
  osc.stop(now + 0.02);
  sidetone = null;
}

function clearGapTimers(): void {
  window.clearTimeout(letterTimer);
  window.clearTimeout(wordTimer);
  ring?.remove();
  ring = null;
}

function startCommitRing(ms: number): void {
  ring?.remove();
  ring = null;
  const view = nodes.get(cursor);
  if (!view || cursor === '') return;
  const r = view.r * 1.32;
  ring = svg('circle', { r, class: 'commit-ring', transform: 'rotate(-90)' }, view.group);
  const circumference = 2 * Math.PI * r;
  ring.style.strokeDasharray = `${circumference}`;
  ring.style.setProperty('--circ', `${circumference}`);
  ring.style.animationDuration = `${ms}ms`;
}

function press(): void {
  if (downAt) return;
  ensureAudio();
  stopPlayback();
  showPath(cursor);
  clearGapTimers();
  const now = performance.now();
  if (upAt) {
    const gap = now - upAt;
    const kind = classifyGap(gap, unitMs());
    // A word gap much longer than seven units is a pause, not timing.
    if (kind !== 'word' || gap < idealUnits('word') * 2 * unitMs()) record(kind, gap);
    else record('pause', gap);
  }
  downAt = now;
  toneOn();
  lamp('house', true);
  el.key.classList.add('down');
  el.meterFill.classList.remove('fade');
  holdFrame = requestAnimationFrame(hold);
}

/** Runs every frame while the key is down. */
function hold(): void {
  if (!downAt) return;
  const unit = unitMs();
  const ms = performance.now() - downAt;
  const dash = ms >= DASH_FROM_UNITS * unit;
  el.key.classList.toggle('is-dah', dash);
  el.meterFill.style.width = `${Math.min(1, ms / (4 * unit)) * 100}%`;
  showPreview(garbled ? null : cursor + (dash ? '-' : '.'));
  renderStrip(ms);
  holdFrame = requestAnimationFrame(hold);
}

function release(): void {
  if (!downAt) return;
  const now = performance.now();
  const ms = now - downAt;
  downAt = 0;
  cancelAnimationFrame(holdFrame);
  toneOff();
  lamp('house', false);
  el.key.classList.remove('down', 'is-dah');
  el.meterFill.classList.add('fade');
  showPreview(null);
  const unit = unitMs();
  const mark = classifyMark(ms, unit);
  if (!mark) {
    renderStrip();
    return;
  }
  upAt = now;
  record(mark, ms);
  letterTimer = window.setTimeout(endLetter, LETTER_GAP_UNITS * unit);
  wordTimer = window.setTimeout(endWord, WORD_GAP_UNITS * unit);
  if (garbled) return;

  const next = cursor + mark;
  if (!hasNode(next)) {
    // No letter has this code. Like a receiver, drop it and wait for the gap.
    garbled = true;
    shake(cursor);
    buzz();
    if (quiz) {
      cursor = '';
      answer(null, next);
    } else {
      setBanner(`${symbols(next)} is not a letter.`, 'warn');
      cursor = '';
      window.setTimeout(() => showPath(cursor), 260);
    }
    return;
  }
  cursor = next;
  travel(cursor, Math.min(ms, 180));
  if (!quiz) setBanner('');
  startCommitRing(LETTER_GAP_UNITS * unit);
}

/** Two units of silence: write the letter at the cursor. */
function endLetter(): void {
  ring?.remove();
  ring = null;
  garbled = false;
  if (cursor === '') return;
  const code = cursor;
  const letter = letterAt(code);
  cursor = '';
  record('char', 0, letter ?? '?');
  if (quiz) {
    answer(letter, code);
    return;
  }
  if (!letter) return;
  reveal(code);
  writeChar(letter);
  window.setTimeout(() => {
    if (cursor === '') showPath('');
  }, 350);
}

/** Five units of silence: the word is over. */
function endWord(): void {
  if (quiz || saved.tape === '' || saved.tape.endsWith(' ')) return;
  writeChar(' ');
}

function writeChar(char: string): void {
  saved.tape = (saved.tape + char).slice(-TAPE_LIMIT);
  renderTape(true);
  save();
}

function backspace(): void {
  stopPlayback();
  if (cursor) {
    clearGapTimers();
    cursor = '';
    upAt = 0;
    showPath(cursor);
    return;
  }
  if (saved.tape === '') return;
  saved.tape = saved.tape.slice(0, -1);
  renderTape(false);
  save();
}

function symbols(code: string): string {
  return [...code].map((s) => (s === '-' ? '▬' : '●')).join(' ');
}

// ------------------------------------------------------------------ timing strip

// A running record of the hand: each press drawn to scale against the ghost of
// its ideal length, gaps to scale between them, and the letters as they land.

type StripKind = Mark | Gap | 'pause' | 'char';
interface StripItem {
  kind: StripKind;
  ms: number;
  score: number | null;
  char?: string;
}

const STRIP_LIMIT = 80;
const strip: StripItem[] = [];
const scores: number[] = [];

function record(kind: StripKind, ms: number, char?: string): void {
  const timed = kind !== 'pause' && kind !== 'char';
  const score = timed ? accuracy(ms, unitMs(), kind) : null;
  strip.push({ kind, ms, score, char });
  if (strip.length > STRIP_LIMIT) strip.splice(0, strip.length - STRIP_LIMIT);
  if (score !== null) {
    scores.push(score);
    if (scores.length > 20) scores.shift();
  }
  renderStrip();
}

function renderStrip(heldMs = 0): void {
  const width = el.strip.clientWidth;
  const height = el.strip.clientHeight;
  if (width === 0 || height === 0) return;
  el.strip.setAttribute('viewBox', `0 0 ${width} ${height}`);
  el.strip.replaceChildren();
  const unit = unitMs();
  const px = Math.max(3, Math.min(12, width / 52));
  // Bars along the bottom, the letters above them.
  const barH = Math.min(14, height * 0.3);
  const barY = height - barH - Math.max(4, height * 0.15);
  const charSize = Math.max(8, Math.min(12, barY - 4));
  let x = width - 8;

  if (heldMs > 0) {
    const w = (heldMs / unit) * px;
    const dash = heldMs >= DASH_FROM_UNITS * unit;
    svg('rect', { x: x - w, y: barY, width: w, height: barH, rx: barH / 2, class: `strip-mark live ${dash ? 'dah' : 'dit'}` }, el.strip);
    x -= w;
  }

  for (let i = strip.length - 1; i >= 0 && x > 0; i -= 1) {
    const item = strip[i];
    if (item.kind === '.' || item.kind === '-') {
      const w = (item.ms / unit) * px;
      const ideal = idealUnits(item.kind) * px;
      const cls = item.kind === '-' ? 'dah' : 'dit';
      svg('rect', { x: x - ideal, y: barY - 3, width: ideal, height: barH + 6, rx: (barH + 6) / 2, class: `strip-ideal ${cls}` }, el.strip);
      svg('rect', { x: x - w, y: barY, width: w, height: barH, rx: barH / 2, class: `strip-mark ${cls} ${quality(item.score)}` }, el.strip);
      x -= Math.max(w, ideal);
    } else if (item.kind === 'char') {
      const label = svg('text', { x: x + 1.5 * px, y: barY - 4, class: 'strip-char', 'text-anchor': 'middle', 'font-size': charSize }, el.strip);
      label.textContent = item.char ?? '';
    } else if (item.kind === 'pause') {
      x -= 4 * px;
      svg('line', { x1: x + 2 * px, y1: barY - 4, x2: x + 2 * px, y2: barY + barH + 4, class: 'strip-pause' }, el.strip);
    } else {
      const w = Math.min(item.ms / unit, 9) * px;
      if (item.kind === 'word') {
        svg('line', { x1: x - w / 2, y1: barY - 4, x2: x - w / 2, y2: barY + barH + 4, class: 'strip-word' }, el.strip);
      }
      x -= w;
    }
  }
  renderRhythm();
}

function quality(score: number | null): string {
  if (score === null) return '';
  return score >= 0.75 ? 'good' : score >= 0.45 ? 'fair' : 'poor';
}

function renderRhythm(): void {
  if (scores.length < 3) {
    el.rhythm.textContent = 'rhythm';
    el.rhythm.className = 'rhythm';
    return;
  }
  const mean = scores.reduce((sum, score) => sum + score, 0) / scores.length;
  el.rhythm.textContent = `rhythm ${Math.round(mean * 100)}%`;
  el.rhythm.className = `rhythm ${quality(mean)}`;
}

// ------------------------------------------------------------------ tapping

function tapLetter(letter: string): void {
  ensureAudio();
  clearGapTimers();
  cursor = '';
  upAt = 0;
  const code = codeOf(letter) ?? '';
  if (quiz) {
    answer(letter, code);
    return;
  }
  setBanner(`${letter}  ${symbols(code)}`, 'info');
  reveal(code);
  play(letter);
}

// ------------------------------------------------------------------ tape

function renderTape(popLast: boolean): void {
  el.tapeText.replaceChildren();
  const chars = [...saved.tape];
  chars.forEach((char, index) => {
    const span = document.createElement('span');
    span.className = char === ' ' ? 'tape-char tape-space' : 'tape-char';
    span.textContent = char === ' ' ? ' ' : char;
    if (popLast && index === chars.length - 1) span.classList.add('pop');
    el.tapeText.append(span);
  });
  const caret = document.createElement('span');
  caret.className = 'tape-caret';
  el.tapeText.append(caret);
  if (chars.length === 0) {
    const hint = document.createElement('span');
    hint.className = 'tape-hint';
    hint.textContent = 'tap a letter, or hold the key';
    el.tapeText.append(hint);
  }
  el.tapeText.scrollLeft = el.tapeText.scrollWidth;
  el.playTape.disabled = saved.tape.trim() === '';
  el.backspace.disabled = saved.tape === '';
  el.clearTape.disabled = saved.tape === '';
}

function playTape(): void {
  if (el.playTape.classList.contains('active')) {
    stopPlayback();
    return;
  }
  const text = saved.tape;
  const spans = [...el.tapeText.querySelectorAll<HTMLSpanElement>('.tape-char')];
  play(
    text,
    (letter) => {
      spans.forEach((span, index) => span.classList.toggle('playing', index === letter));
      spans[letter]?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
    },
    () => {
      spans.forEach((span) => span.classList.remove('playing'));
      el.playTape.classList.remove('active');
    },
    true,
    false,
    'house',
  );
  el.playTape.classList.add('active');
}

// ------------------------------------------------------------------ quiz

const LETTERS = Object.keys(LETTER_CODES);

function quizPrompt(): string {
  const streak = quiz ? quiz.streak : 0;
  const ask = quiz?.mode === 'light' ? 'What did the boat flash?' : 'Which letter was that?';
  return `${ask} Tap it or key it.  ★ ${streak}  best ${saved.best}`;
}

function nextQuestion(): void {
  if (!quiz) return;
  let target = quiz.target;
  while (target === quiz.target) target = LETTERS[Math.floor(Math.random() * LETTERS.length)];
  quiz.target = target;
  setBanner(quizPrompt(), 'quiz');
  askQuestion();
}

/** Sound or light only: walking the tree would give the answer away. */
function askQuestion(): void {
  if (!quiz) return;
  play(quiz.target, undefined, undefined, false, quiz.mode === 'light');
}

function replayQuestion(): void {
  askQuestion();
}

function answer(letter: string | null, code: string): void {
  if (!quiz) return;
  stopPlayback();
  const target = quiz.target;
  const targetCode = codeOf(target) ?? '';
  if (letter === target) {
    quiz.streak += 1;
    if (quiz.streak > saved.best) {
      saved.best = quiz.streak;
      save();
    }
    reveal(targetCode);
    burst(targetCode);
    showPath(targetCode);
    chime();
    setBanner(`Yes, ${target}!  ★ ${quiz.streak}  best ${saved.best}`, 'ok');
    window.setTimeout(nextQuestion, 1100);
    return;
  }
  quiz.streak = 0;
  shake(code);
  buzz();
  const wrong = letter ? `That was ${letter}.` : 'No letter there.';
  setBanner(`${wrong} It was ${target}: ${symbols(targetCode)}`, 'warn');
  window.setTimeout(() => {
    if (!quiz) return;
    reveal(targetCode);
    play(target, undefined, () => window.setTimeout(nextQuestion, 500));
  }, 600);
}

/** Start the quiz in `mode`, switch to it from the other one, or stop it. */
function toggleQuiz(mode: QuizMode = 'sound'): void {
  ensureAudio();
  stopPlayback();
  cursor = '';
  clearGapTimers();
  if (quiz?.mode === mode) {
    quiz = null;
    setBanner('');
  } else {
    quiz = { target: '', streak: 0, mode };
    nextQuestion();
  }
  for (const [button, buttonMode] of [[el.quiz, 'sound'], [el.lightQuiz, 'light']] as const) {
    const on = quiz?.mode === buttonMode;
    button.setAttribute('aria-pressed', String(on));
    button.classList.toggle('active', on);
  }
  el.app.classList.toggle('quiz-mode', Boolean(quiz));
  el.app.classList.toggle('light-quiz', quiz?.mode === 'light');
}

// ------------------------------------------------------------------ banner

let bannerTimer = 0;

function setBanner(text: string, kind: 'info' | 'warn' | 'ok' | 'quiz' = 'info'): void {
  window.clearTimeout(bannerTimer);
  el.banner.className = `banner banner-${kind}${text ? ' show' : ''}`;
  el.banner.replaceChildren();
  if (!text) return;
  const span = document.createElement('span');
  span.textContent = text;
  el.banner.append(span);
  if (kind === 'quiz') {
    const replay = document.createElement('button');
    replay.type = 'button';
    replay.className = 'banner-replay';
    replay.textContent = '↻ again';
    replay.addEventListener('click', replayQuestion);
    el.banner.append(replay);
  }
  if (kind === 'info' || (kind === 'warn' && !quiz)) {
    bannerTimer = window.setTimeout(() => el.banner.classList.remove('show'), 2600);
  }
}

// ------------------------------------------------------------------ options

function renderOptions(): void {
  el.speed.textContent = String(saved.wpm);
  el.speed.title = `Speed: ${saved.wpm} words per minute`;
  el.speed.setAttribute('aria-label', `Speed ${saved.wpm} words per minute`);
  el.sound.textContent = saved.sound ? '🔊' : '🔇';
  el.sound.setAttribute('aria-pressed', String(saved.sound));
  el.sound.setAttribute('aria-label', saved.sound ? 'Sound on' : 'Sound off');
  refreshTree();
}

// ------------------------------------------------------------------ input

// The key acts on pointerdown and pointerup; capture keeps the release even if
// the finger slides off.
el.key.addEventListener('pointerdown', (event) => {
  if (event.button !== 0) return;
  event.preventDefault();
  el.key.setPointerCapture(event.pointerId);
  press();
});
el.key.addEventListener('pointerup', release);
el.key.addEventListener('pointercancel', release);
el.key.addEventListener('lostpointercapture', release);
el.key.addEventListener('contextmenu', (event) => event.preventDefault());

el.backspace.addEventListener('click', backspace);
el.playTape.addEventListener('click', () => {
  ensureAudio();
  playTape();
});
el.clearTape.addEventListener('click', () => {
  stopPlayback();
  saved.tape = '';
  renderTape(false);
  save();
});
el.quiz.addEventListener('click', () => toggleQuiz('sound'));
el.lightQuiz.addEventListener('click', () => toggleQuiz('light'));
el.speed.addEventListener('click', () => {
  saved.wpm = SPEEDS[(SPEEDS.indexOf(saved.wpm) + 1) % SPEEDS.length];
  renderOptions();
  renderStrip();
  save();
  const unit = Math.round(unitMs());
  setBanner(`${saved.wpm} wpm: dot ${unit} ms, dash from ${unit * DASH_FROM_UNITS} ms`, 'info');
});
el.sound.addEventListener('click', () => {
  saved.sound = !saved.sound;
  if (!saved.sound) stopPlayback();
  ensureAudio();
  renderOptions();
  save();
});

window.addEventListener('keydown', (event) => {
  if (event.ctrlKey || event.metaKey || event.altKey) return;
  const k = event.key;
  if (k === ' ') {
    // Space is the key: hold it like the button.
    event.preventDefault();
    if (!event.repeat) press();
  } else if (k === 'Backspace') {
    event.preventDefault();
    backspace();
  } else if (k === 'Escape') {
    if (quiz) toggleQuiz(quiz.mode);
    else stopPlayback();
  } else if (/^[a-zA-Z]$/.test(k) && !event.repeat) {
    const upper = k.toUpperCase();
    if (upper === 'Q' && event.shiftKey) toggleQuiz('sound');
    // Tiny frames hide the sea, and the light quiz with it.
    else if (upper === 'L' && event.shiftKey) {
      if (el.sea.offsetParent !== null) toggleQuiz('light');
    }
    else tapLetter(upper);
  }
});

window.addEventListener('keyup', (event) => {
  if (event.key === ' ') {
    event.preventDefault();
    release();
  }
});

// A clicked chip keeps focus, and Space would then press it instead of keying.
document.addEventListener('click', (event) => {
  if (event.detail > 0 && event.target instanceof Element) {
    event.target.closest('button')?.blur();
  }
});

// iOS Safari only unlocks audio from touchend/click, not from pointerdown.
document.addEventListener('touchend', ensureAudio, { passive: true });

window.addEventListener('blur', () => {
  // Do not leave the tone running or a half-keyed letter waiting in the background.
  release();
  clearGapTimers();
  if (cursor) endLetter();
});

new ResizeObserver(() => {
  buildTree();
  renderStrip();
}).observe(el.stage);

// ------------------------------------------------------------------ start

renderTape(false);
renderOptions();
buildTree();
renderStrip();
void load().then(() => {
  renderTape(false);
  renderOptions();
});