koan-server 0.65.0

GraphQL, Subsonic REST, and MCP server for koan music player.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
// The web UI's own script: navigation that swaps only the page content so the
// player keeps playing, the transport and queue, and keeping the session alive.
(() => {
  const main = document.getElementById("content");
  document.documentElement.classList.add("js");
  // The server groups history by day, and only the browser knows whose day.
  document.cookie = `koan_tz=${-new Date().getTimezoneOffset()}; path=/; max-age=31536000; samesite=lax`;
  const all = (sel, root = document) => [...root.querySelectorAll(sel)];
  const fmt = (s) => {
    s = Math.max(0, Math.floor(s || 0));
    return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
  };

  // --- Session ---------------------------------------------------------------
  // The access cookie lasts minutes. Renewing spends the refresh cookie, which
  // only /auth routes receive, for fresh ones; no token is ever visible here.
  // Behind an authenticating proxy there is no refresh cookie: /ui/renew takes
  // the account from the proxy's header, and goes first, so a refresh cookie
  // left from before the proxy cannot keep a session the proxy did not vouch
  // for.
  const rawFetch = window.fetch.bind(window);
  let renewing = null;
  let renewedAt = Date.now();
  const post = (path) =>
    rawFetch(path, { method: "POST", credentials: "same-origin" }).then((r) => r.ok);
  const [first, then] = "proxied" in document.body.dataset
    ? ["/ui/renew", "/auth/renew"]
    : ["/auth/renew", "/ui/renew"];
  function renew() {
    renewing ??= post(first)
      .then((ok) => ok || post(then))
      .then((ok) => { if (ok) renewedAt = Date.now(); return ok; })
      .catch(() => false)
      .finally(() => { renewing = null; });
    return renewing;
  }
  const sameOrigin = (input) =>
    new URL(typeof input === "string" ? input : input.url, location.href).origin === location.origin;
  // Every request this page makes, Datastar's included, renews once on a 401
  // and retries; a session that cannot be renewed reloads into the sign-in form.
  // Responses name the stylesheet their markup was written for. A tab open
  // across an upgrade swaps it in rather than drawing new markup with the old
  // one, and keeps playing.
  const sheet = document.querySelector('link[rel=stylesheet][href^="/ui/assets/ui.css"]');
  function freshen(r) {
    const v = r.headers.get("X-Koan-Css");
    if (sheet && v && new URL(sheet.href).searchParams.get("v") !== v) {
      sheet.href = `/ui/assets/ui.css?v=${v}`;
    }
  }
  window.fetch = async (input, init) => {
    const r = await rawFetch(input, init);
    if (sameOrigin(input)) freshen(r);
    if (r.status !== 401 || !sameOrigin(input)) return r;
    if (await renew()) {
      const again = await rawFetch(input, init);
      freshen(again);
      if (again.status !== 401) return again;
    }
    location.reload();
    return r;
  };
  const RENEW_EVERY = 10 * 60 * 1000;
  setInterval(() => { if (Date.now() - renewedAt > RENEW_EVERY) renew(); }, 60 * 1000);
  document.addEventListener("visibilitychange", () => {
    if (!document.hidden && Date.now() - renewedAt > RENEW_EVERY) renew();
  });

  // --- Player ----------------------------------------------------------------
  const STORE = "koan.queue";
  const save = (from) => {
    const { queue, cur } = player.state();
    try { localStorage.setItem(STORE, JSON.stringify({ queue, cur, pos: from ?? player.position() })); } catch {}
  };
  // The queue's tracks as last drawn; see renderQueue.
  let queueKey = "";
  const player = window.KoanPlayer({ onChange: render, renew });

  function trackOf(li) {
    const d = li.dataset;
    const albumId = Number(d.albumId) || 0;
    return {
      id: Number(d.id), src: `/ui/stream/${d.id}`, dur: Number(d.dur) || 0,
      title: d.title, artist: d.artist, album: d.album, albumId,
      artistId: Number(d.artistId) || 0, cover: d.cover || null,
    };
  }

  function render({ queue, cur, playing, track }) {
    document.body.classList.toggle("playing", playing);
    for (const el of all("[data-np=title]")) el.textContent = track ? track.title : "Nothing playing";
    for (const el of all("[data-np=artist]")) {
      el.textContent = track ? track.artist : "";
      if (track && track.artistId) el.href = `/artist/${track.artistId}`;
      else el.removeAttribute("href");
    }
    for (const el of all("[data-np=sep]")) el.hidden = !(track && track.artist && track.album);
    for (const el of all("[data-np=album]")) {
      el.textContent = track ? track.album : "";
      if (track && track.albumId) el.href = `/album/${track.albumId}`;
      else el.removeAttribute("href");
    }
    for (const el of all("img[data-np=cover]")) {
      const src = track && track.cover;
      el.hidden = !src;
      if (src && el.getAttribute("src") !== src) { el.classList.remove("missing"); el.src = src; }
    }
    for (const el of all("[data-np=len]")) el.textContent = fmt(track ? track.dur : 0);
    for (const el of all("input[data-ctl=seek]")) el.max = track ? track.dur : 0;
    for (const el of all("progress[data-np=progress]")) el.max = track && track.dur ? track.dur : 1;
    for (const li of all("li[data-id]", main)) li.classList.toggle("playing", !!track && Number(li.dataset.id) === track.id);
    renderQueue(queue, cur);
    tick();
    save();
  }

  function renderQueue(queue, cur) {
    const list = document.getElementById("queue-list");
    if (!list) return;
    // A menu open on a queue row would act on the place it had, once the
    // queue itself changes.
    const key = queue.map((t) => t.id).join();
    const open = document.getElementById("track-menu");
    if (key !== queueKey && open && open.hasAttribute("data-queued") && open.matches(":popover-open")) open.hidePopover();
    queueKey = key;
    list.replaceChildren();
    if (!queue.length) {
      const p = document.createElement("li");
      p.className = "disc";
      p.textContent = "The queue is empty. Play an album to fill it.";
      list.append(p);
      return;
    }
    queue.forEach((t, i) => {
      const li = document.createElement("li");
      li.tabIndex = 0;
      li.dataset.q = i;
      Object.assign(li.dataset, {
        id: t.id, dur: t.dur, title: t.title, artist: t.artist ?? "", album: t.album ?? "",
        albumId: t.albumId || 0, artistId: t.artistId || 0, cover: t.cover ?? "",
      });
      li.classList.toggle("playing", i === cur);
      const n = document.createElement("span");
      n.className = "n";
      n.textContent = i + 1;
      const title = document.createElement("span");
      title.className = "t";
      title.textContent = t.title;
      const small = document.createElement("small");
      const names = [[t.artist, t.artistId, "artist"], [t.album, t.albumId, "album"]].filter(([name]) => name);
      names.forEach(([name, id, kind], j) => {
        if (j) small.append(" · ");
        if (!id) return small.append(name);
        const a = document.createElement("a");
        a.href = `/${kind}/${id}`;
        a.textContent = name;
        small.append(a);
      });
      title.append(small);
      const d = document.createElement("span");
      d.className = "d";
      d.textContent = fmt(t.dur);
      const rm = document.createElement("button");
      rm.className = "quiet";
      rm.dataset.act = "remove";
      rm.setAttribute("aria-label", "Remove from queue");
      rm.title = "Remove from queue";
      rm.textContent = "×";
      const more = document.createElement("button");
      more.className = "quiet wide:hidden";
      more.dataset.act = "menu";
      more.setAttribute("aria-haspopup", "menu");
      more.setAttribute("aria-label", "More");
      more.title = "More";
      more.textContent = "⋯";
      li.append(n, title, d, rm, more);
      list.append(li);
    });
  }

  // The range being dragged, which the clock must not move under the finger.
  // Focus is no guide: a clicked range keeps it long after the drag ends.
  let dragging = null;
  // How far a slider's accent runs; see styles/controls.css.
  const fill = (el) => el.style.setProperty("--fill", `${el.max > 0 ? (el.value / el.max) * 100 : 0}%`);
  const isSeek = (t) => t && t.matches && t.matches("input[data-ctl=seek]");
  for (const type of ["pointerdown", "touchstart"]) {
    document.addEventListener(type, (e) => { if (isSeek(e.target)) dragging = e.target; }, { passive: true });
  }
  for (const type of ["pointerup", "pointercancel", "touchend", "touchcancel", "change", "focusout"]) {
    document.addEventListener(type, () => { dragging = null; }, { passive: true });
  }

  let lastSave = 0;
  function tick() {
    const { track } = player.state();
    const p = track ? player.position() : 0;
    for (const el of all("[data-np=pos]")) el.textContent = fmt(p);
    for (const el of all("input[data-ctl=seek]")) {
      if (el !== dragging) el.value = p;
      fill(el);
    }
    for (const el of all("progress[data-np=progress]")) el.value = p;
    if (track && Date.now() - lastSave > 5000) { lastSave = Date.now(); save(p); }
  }
  setInterval(tick, 250);

  const shuffle = (a) => {
    for (let i = a.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  };
  const rowsOf = (el) => all("li[data-id]", el.closest("ol") || el.closest(".page") || main);

  function act(name, el) {
    const page = el.closest(".page");
    const albumRows = () => (page ? all("ol[data-context=album] li[data-id]", page) : []).map(trackOf);
    const row = el.closest("li");
    switch (name) {
      case "play": return player.play(albumRows(), 0);
      case "shuffle": return player.play(shuffle(albumRows()), 0);
      case "queue": return player.append(albumRows());
      case "add": return player.append([trackOf(row)]);
      case "menu": {
        const r = el.getBoundingClientRect();
        return openMenu(row, r.right, r.bottom);
      }
      case "remove": return player.remove(Number(row.dataset.q));
      case "clear": return player.clear();
    }
  }

  function pick(li) {
    if (li.dataset.q !== undefined) return player.playAt(Number(li.dataset.q));
    const ol = li.closest("ol");
    if (ol && ol.dataset.context === "album") {
      const rows = rowsOf(li);
      return player.play(rows.map(trackOf), rows.indexOf(li));
    }
    player.playNow([trackOf(li)]);
  }

  // --- Track menu ------------------------------------------------------------
  // What the apps' context menu offers on a track, for any track row: opened by
  // right-click, a long press, or the row's ⋯ on a phone. Favourite and share
  // press the row's own buttons, so they behave as those do.
  const menu = document.getElementById("track-menu");
  function item(label, run) {
    const b = document.createElement("button");
    b.className = "quiet";
    b.setAttribute("role", "menuitem");
    b.textContent = label;
    b.addEventListener("click", () => { menu.hidePopover(); run(); });
    return b;
  }
  const group = (items) => (items.length ? [document.createElement("hr"), ...items] : []);
  function openMenu(li, x, y) {
    if (!menu) return;
    const t = trackOf(li);
    const d = li.dataset;
    const heart = li.querySelector("[data-fav]");
    const share = li.querySelector("[data-act-share]");
    const mine = [];
    if (heart) {
      const on = heart.getAttribute("aria-pressed") === "true";
      mine.push(item(on ? "Remove Favourite" : "Favourite Track", () => heart.click()));
    }
    if (share) mine.push(item("Share Track", () => share.click()));
    // A play in History: forgotten through the page's own Forget, as the
    // apps' Remove from History is, so it is the one way plays leave.
    const play = li.closest("#history") && li.querySelector("input[type=checkbox][value]");
    const forget = play
      ? [item("Remove from History", () => {
          for (const box of all("#history input:checked")) box.checked = false;
          play.checked = true;
          play.dispatchEvent(new Event("change", { bubbles: true }));
          document.querySelector("[data-act-forget]")?.click();
        })]
      : [];
    const queued = li.dataset.q !== undefined
      ? [item("Remove from Queue", () => player.remove(Number(li.dataset.q)))]
      : [];
    const go = [];
    if (Number(d.albumId)) go.push(item("Go to Album", () => navigate(`/album/${d.albumId}`, true)));
    if (Number(d.artistId)) go.push(item("Go to Artist", () => navigate(`/artist/${d.artistId}`, true)));
    const about = [item("Properties…", () => showProperties(d.id))];
    const head = document.createElement("p");
    head.textContent = [t.title, t.artist].filter(Boolean).join(" · ");
    menu.replaceChildren(
      head,
      item("Play", () => pick(li)),
      item("Play Next", () => player.playNext([t])),
      item("Add to Queue", () => player.append([t])),
      ...group(mine),
      ...group(go),
      ...group(forget),
      ...group(queued),
      ...group(about),
    );
    // A queue row's place moves when the queue does; see renderQueue.
    menu.toggleAttribute("data-queued", li.dataset.q !== undefined);
    if (!menu.matches(":popover-open")) menu.showPopover();
    if (wide.matches) {
      const r = menu.getBoundingClientRect();
      menu.style.left = `${Math.max(8, Math.min(x, innerWidth - r.width - 8))}px`;
      menu.style.top = `${Math.max(8, Math.min(y, innerHeight - r.height - 8))}px`;
    } else {
      menu.style.left = menu.style.top = "";
    }
    menu.querySelector("button").focus();
  }
  // Opened at once, filled when the server answers; only the latest request
  // may fill it.
  const properties = document.getElementById("track-properties");
  const propertiesBody = document.getElementById("track-properties-body");
  let asked = 0;
  async function showProperties(id) {
    if (!properties) return;
    const mine = ++asked;
    const say = (text) => {
      const p = document.createElement("p");
      p.className = "text-muted";
      p.textContent = text;
      propertiesBody.replaceChildren(p);
    };
    say("Loading…");
    if (!properties.open) properties.showModal();
    try {
      const r = await fetch(`/track/${id}/properties`, { headers: { "x-koan-partial": "1" } });
      const html = r.ok ? await r.text() : null;
      if (mine !== asked) return;
      if (html === null) say(r.status === 404 ? "This track is no longer in the library." : "The server could not say.");
      else {
        // The page's content, without the section the UI's navigation swaps in.
        const t = document.createElement("template");
        t.innerHTML = html;
        propertiesBody.replaceChildren(...(t.content.querySelector("section.page") ?? t.content).childNodes);
      }
    } catch {
      if (mine === asked) say("The server could not be reached.");
    }
  }
  // A click on the backdrop lands on the dialog itself, as does one in its
  // padding or a selection dragged out of it, so only a press and release
  // both outside its box close it.
  const outside = (e) => {
    const r = properties.getBoundingClientRect();
    return e.target === properties &&
      (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom);
  };
  let pressedOutside = false;
  properties?.addEventListener("pointerdown", (e) => { pressedOutside = outside(e); });
  properties?.addEventListener("click", (e) => {
    if (pressedOutside && outside(e)) properties.close();
    pressedOutside = false;
  });
  // A manual popover: the press that opens it ends on the row (a touch stays
  // captured by what it went down on), which a light-dismissing popover would
  // take for a click outside. It closes on the next press outside it, Escape,
  // or leaving the page; the press that closes it does nothing else, as with
  // the apps' menus.
  let dismissed = false;
  const closeMenu = () => {
    if (!menu || !menu.matches(":popover-open")) return false;
    menu.hidePopover();
    return true;
  };
  document.addEventListener("pointerdown", (e) => {
    if (menu && !menu.contains(e.target) && closeMenu()) dismissed = true;
  }, true);
  document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeMenu(); });
  const menuRow = (e) => e.target.closest && e.target.closest("li[data-id]");
  document.addEventListener("contextmenu", (e) => {
    const li = menuRow(e);
    if (!li || e.target.closest("a:not(.t a), input")) return;
    e.preventDefault();
    // The keyboard's menu key has no pointer: open it at the row.
    const r = li.getBoundingClientRect();
    openMenu(li, e.clientX || r.left + 24, e.clientY || r.bottom);
  });
  // iOS fires no contextmenu on a long press, so a touch held still opens it,
  // and the click that follows the lift is not a pick.
  let press = 0, pressed = false, pressAt = null;
  document.addEventListener("pointerdown", (e) => {
    const li = e.pointerType === "touch" && menuRow(e);
    if (!li || e.target.closest("a:not(.t a), button, input, label")) return;
    pressAt = [e.clientX, e.clientY];
    pressed = false;
    press = setTimeout(() => { pressed = true; openMenu(li, e.clientX, e.clientY); }, 500);
  });
  document.addEventListener("pointermove", (e) => {
    if (pressAt && Math.hypot(e.clientX - pressAt[0], e.clientY - pressAt[1]) > 10) clearTimeout(press);
  });
  for (const type of ["pointerup", "pointercancel", "scroll"]) {
    document.addEventListener(type, () => {
      clearTimeout(press);
      pressAt = null;
      // Not every browser sends that click, so the guard lapses on its own.
      if (pressed || dismissed) setTimeout(() => { pressed = dismissed = false; }, 350);
    }, { passive: true, capture: true });
  }
  document.addEventListener("click", (e) => {
    if (pressed || dismissed) { pressed = dismissed = false; e.preventDefault(); e.stopPropagation(); }
  }, true);

  // --- Invites ---------------------------------------------------------------
  // The email goes out as rich text where the clipboard takes it, so pasting
  // into a mail client keeps the button; the share sheet gets the plain text.
  const inviteEmail = () => ({
    html: document.getElementById("invite-html")?.innerHTML ?? "",
    text: document.getElementById("invite-text")?.value ?? "",
    subject: document.getElementById("invite-text")?.dataset.subject ?? "",
  });
  async function copyEmail(button) {
    const { html, text } = inviteEmail();
    try {
      await navigator.clipboard.write([new ClipboardItem({
        "text/html": new Blob([html], { type: "text/html" }),
        "text/plain": new Blob([text], { type: "text/plain" }),
      })]);
    } catch {
      await navigator.clipboard.writeText(text);
    }
    button.textContent = "Copied";
  }
  function inviteClick(e) {
    const copy = e.target.closest("[data-copy]");
    if (copy) {
      const el = document.getElementById(copy.dataset.copy);
      navigator.clipboard.writeText(el.value ?? el.textContent).then(() => { copy.textContent = "Copied"; });
      return true;
    }
    const email = e.target.closest("[data-copy-email]");
    if (email) { copyEmail(email); return true; }
    const share = e.target.closest("[data-share-email]");
    if (share) {
      const { text, subject } = inviteEmail();
      navigator.share({ title: subject, text }).catch(() => {});
      return true;
    }
    return false;
  }

  document.addEventListener("click", (e) => {
    if (inviteClick(e)) return;
    const ctl = e.target.closest("[data-ctl]");
    if (ctl) {
      if (ctl.dataset.ctl === "play") player.toggle();
      else if (ctl.dataset.ctl === "prev") player.prev();
      else if (ctl.dataset.ctl === "next") player.next();
      return;
    }
    const a = e.target.closest("[data-act]");
    if (a) { e.preventDefault(); act(a.dataset.act, a); return; }
    const li = e.target.closest("li[data-id], li[data-q]");
    if (li && !e.target.closest("a, button, input, label")) pick(li);
  });
  document.addEventListener("keydown", (e) => {
    if (e.key !== "Enter" && e.key !== " ") return;
    const li = e.target.closest && e.target.closest("li[data-id], li[data-q]");
    if (li && e.target === li) { e.preventDefault(); pick(li); }
  });
  document.addEventListener("input", (e) => {
    if (e.target.matches("input[data-ctl=seek]")) {
      for (const el of all("[data-np=pos]")) el.textContent = fmt(Number(e.target.value));
      fill(e.target);
    }
  });
  document.addEventListener("change", (e) => {
    if (e.target.matches("input[data-ctl=seek]")) player.seek(Number(e.target.value));
  });
  document.addEventListener("focusin", (e) => { if (e.target.id === "share-url") e.target.select(); });
  // A cover that is not there leaves an empty tile rather than a broken image.
  document.addEventListener("error", (e) => {
    if (e.target.tagName !== "IMG") return;
    e.target.classList.add("missing");
    // With no source the image draws as its own empty box, not a broken icon.
    e.target.removeAttribute("src");
  }, true);

  // --- Navigation ------------------------------------------------------------
  const INTERNAL = /^\/(albums|tracks|album\/\d+|artists|artist\/\d+|search|queue|account|library|favourites|history|recent|scrobbling)?$/;
  let navigating = 0;

  async function navigate(url, push) {
    const n = ++navigating;
    let r;
    try {
      r = await fetch(url, { headers: { "X-Koan-Partial": "1" }, credentials: "same-origin" });
    } catch {
      location.href = url;
      return;
    }
    if (n !== navigating) return;
    if (!r.ok) { location.href = url; return; }
    const html = await r.text();
    if (n !== navigating) return;
    closeMenu();
    if (properties?.open) properties.close();
    main.innerHTML = html;
    if (push) history.pushState(null, "", url);
    settle();
    scrollTo(0, 0);
  }

  function settle() {
    const page = main.firstElementChild;
    const title = page && page.dataset.title;
    document.title = title ? `${title} · koan` : "koan";
    const section = { "": "albums", album: "albums", artist: "artists", playlist: "playlists" }[location.pathname.split("/")[1]]
      ?? location.pathname.split("/")[1];
    for (const a of all("a[data-nav]")) {
      // A phone's Library tab stands for several of the sidebar's links.
      if (a.dataset.nav.split(" ").includes(section)) a.setAttribute("aria-current", "page");
      else a.removeAttribute("aria-current");
    }
    const focus = main.querySelector("[autofocus]");
    if (focus) focus.focus();
    // The sort and filter row stands open on a wide screen; on a phone it is
    // one button that opens as a sheet.
    for (const d of all("details.browse", main)) d.open = wide.matches;
    render(player.state());
  }

  // --- Sort and filter ---------------------------------------------------------
  // The toolbar is a GET form; its state is the URL. On a wide screen a change
  // applies at once, on a phone the sheet's Apply does.
  const wide = matchMedia("(min-width: 721px)");
  function formUrl(form) {
    const params = new URLSearchParams();
    for (const [k, v] of new FormData(form)) if (String(v).trim()) params.append(k, v);
    const q = params.toString();
    return form.getAttribute("action") + (q ? `?${q}` : "");
  }
  document.addEventListener("change", (e) => {
    const form = e.target.closest && e.target.closest("form.toolbar");
    if (!form || !wide.matches || e.target.matches(TYPED)) return;
    navigate(formUrl(form), true);
  });
  document.addEventListener("submit", (e) => {
    if (!e.target.matches("form.toolbar")) return;
    e.preventDefault();
    clearTimeout(typing);
    navigate(formUrl(e.target), true);
  });
  // Typing filters as it goes, once the keys pause. Only the listing below the
  // toolbar is replaced, so the field keeps its focus and caret; the URL is
  // replaced rather than pushed, so back does not step through every keystroke.
  // A year applies only when it is whole, or cleared.
  const TYPED = "form.toolbar input[name=q], form.toolbar input[name=from], form.toolbar input[name=to]";
  let typing;
  document.addEventListener("input", (e) => {
    if (!wide.matches || !e.target.matches(TYPED)) return;
    const v = e.target.value.trim();
    if (e.target.name !== "q" && v && !/^\d{4}$/.test(v)) return;
    clearTimeout(typing);
    const form = e.target.form;
    typing = setTimeout(() => refilter(formUrl(form)), 250);
  });
  async function refilter(url) {
    const n = ++navigating;
    let r;
    try {
      r = await fetch(url, { headers: { "X-Koan-Partial": "1" }, credentials: "same-origin" });
    } catch {
      return;
    }
    if (n !== navigating || !r.ok) return;
    const html = await r.text();
    if (n !== navigating) return;
    const next = document.createElement("template");
    next.innerHTML = html;
    const bar = main.querySelector("details.browse");
    const fresh = next.content.querySelector("details.browse");
    if (!bar || !fresh) return;
    while (bar.nextSibling) bar.nextSibling.remove();
    while (fresh.nextSibling) bar.parentNode.append(fresh.nextSibling);
    history.replaceState(null, "", url);
    render(player.state());
  }
  // The search view's query lives in the URL too, so reload and back find it.
  document.addEventListener("input", (e) => {
    if (!e.target.matches(".search input[name=q]")) return;
    const q = e.target.value.trim();
    history.replaceState(null, "", q ? `/search?q=${encodeURIComponent(q)}` : "/search");
  });

  document.addEventListener("click", (e) => {
    if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
    const a = e.target.closest("a[href]");
    if (!a || a.target || a.hasAttribute("download")) return;
    const url = new URL(a.href, location.href);
    if (url.origin !== location.origin || !INTERNAL.test(url.pathname)) return;
    e.preventDefault();
    if (url.pathname + url.search !== location.pathname + location.search) navigate(url.pathname + url.search, true);
    else if (properties?.open) properties.close();
  });
  addEventListener("popstate", () => navigate(location.pathname + location.search, false));

  // Pick up where the last visit left off, paused.
  try {
    const saved = JSON.parse(localStorage.getItem(STORE) || "null");
    if (saved && Array.isArray(saved.queue)) player.set(saved.queue, saved.cur, saved.pos || 0);
  } catch {}
  settle();
})();