@doitian/dsh-music 0.1.10 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/panel.html CHANGED
@@ -241,9 +241,20 @@
241
241
  .about .writing { color: var(--muted); margin: 0; }
242
242
  .details .source { align-self: flex-start; font-size: 12px; }
243
243
 
244
+ /* Notices float over the page just below the header instead of taking
245
+ a place in it: one that comes and goes, such as the autoplay banner,
246
+ must not move what the listener is about to click. */
247
+ header { position: relative; }
248
+ #notices {
249
+ position: absolute; top: calc(100% + 8px); left: 50%; transform: translateX(-50%); z-index: 30;
250
+ width: max-content; max-width: calc(100% - 2 * var(--gap));
251
+ display: flex; flex-direction: column; gap: 6px; pointer-events: none;
252
+ }
253
+ #notices > * { pointer-events: auto; }
244
254
  .need-gesture {
245
- background: var(--accent-soft); border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
255
+ background: color-mix(in srgb, var(--accent) 13%, var(--bg)); border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
246
256
  border-radius: var(--radius); padding: 8px 12px; font-size: 12px;
257
+ box-shadow: 0 6px 20px color-mix(in srgb, #000 18%, transparent);
247
258
  }
248
259
 
249
260
  /* -------------------------------------------------------------- side */
@@ -353,11 +364,11 @@
353
364
  <button id="scrobble-toggle" class="switch" role="switch" aria-labelledby="history-label"></button>
354
365
  </div>
355
366
  <div id="account"></div>
367
+ <div id="notices" aria-live="polite"></div>
356
368
  </header>
357
369
 
358
370
  <main>
359
371
  <section class="stage">
360
- <div id="notices"></div>
361
372
  <div class="np">
362
373
  <div class="cover"><span id="cover-icon"></span><img id="cover" alt="" /></div>
363
374
  <div class="np-text">
@@ -469,6 +480,7 @@
469
480
  <div class="toast" id="toast"></div>
470
481
 
471
482
  <script src="__BASE__/vendor/qrcode.js"></script>
483
+ <script src="__BASE__/playback.js"></script>
472
484
  <script>
473
485
  // ------------------------------------------------------------------ setup
474
486
  const BASE = '__BASE__';
@@ -796,6 +808,28 @@
796
808
  el.innerHTML = icon(name, options);
797
809
  }
798
810
 
811
+ /** The markup `setHtml` last wrote into each element. */
812
+ const painted = new WeakMap();
813
+
814
+ /**
815
+ * Replace `el`'s markup only when it differs from what was last written.
816
+ * Rewriting identical rows on every update replaced every node in them,
817
+ * which dropped hover, focus and a click caught mid-swap.
818
+ *
819
+ * @returns {boolean} whether the markup was written.
820
+ */
821
+ function setHtml(el, html) {
822
+ if (!el || painted.get(el) === html) return false;
823
+ painted.set(el, html);
824
+ el.innerHTML = html;
825
+ return true;
826
+ }
827
+
828
+ /** Set `el`'s text only when it changes; a rewrite clears a selection in it. */
829
+ function setText(el, text) {
830
+ if (el && el.textContent !== text) el.textContent = text;
831
+ }
832
+
799
833
  function t(key, vars) {
800
834
  let text = DICT[LANG]?.[key] ?? DICT.en[key] ?? key;
801
835
  if (vars) {
@@ -831,7 +865,7 @@
831
865
  render();
832
866
  // The taste titles carry no `data-i18n`, and `render()` needs a state
833
867
  // document, so they are painted here as well — otherwise a zh shell
834
- // shows them in English until the first poll lands.
868
+ // shows them in English until the first state lands.
835
869
  paintTaste();
836
870
  paintDjModelHeader();
837
871
  paintDjModelToggle();
@@ -900,6 +934,8 @@
900
934
  let detailsRequest = 0;
901
935
  /** Details already fetched, by track id, so switching back is instant. */
902
936
  const detailsCache = new Map();
937
+ /** Details being fetched, by track id, so a prefetch and a load share one request. */
938
+ const detailsLoads = new Map();
903
939
  /**
904
940
  * Model-written introductions by `<track id>:<language>`: `'pending'`
905
941
  * while one is being written, then `{text}`, empty when none could be.
@@ -920,6 +956,30 @@
920
956
  };
921
957
  const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
922
958
 
959
+ /** Whether the host's event stream is open; see the boot section. */
960
+ let streaming = false;
961
+ /** The newest snapshot version adopted; see {@link newest}. */
962
+ let versionFloor = 0;
963
+
964
+ /**
965
+ * `next`, unless it is older than the state already shown — then the
966
+ * state shown. A request's answer and a pushed frame travel on different
967
+ * connections, so one read earlier can land later, and adopting it would
968
+ * undo the newer one with nothing coming to repair it. Answers are
969
+ * ordered by `version`, which moves with anything shown — not `rev`,
970
+ * which a setting or a resolved like leaves alone. Only while the stream
971
+ * is open: without it the next poll repairs any such swap, and a
972
+ * reconnect drops the floor, since a restarted host counts its versions
973
+ * from zero again.
974
+ */
975
+ function newest(next) {
976
+ const version = Number(next?.version);
977
+ if (!Number.isFinite(version)) return next;
978
+ if (streaming && version < versionFloor) return state;
979
+ versionFloor = version;
980
+ return next;
981
+ }
982
+
923
983
  let toastTimer;
924
984
  function toast(message) {
925
985
  const el = $('toast');
@@ -1008,124 +1068,54 @@
1008
1068
  return localTransport;
1009
1069
  }
1010
1070
 
1071
+ /**
1072
+ * Origin that serves audio bytes. Under the desktop shell this page runs on
1073
+ * the `dsh-app://` custom scheme, which Chromium cannot byte-range, so seeks
1074
+ * restart the track; the shell publishes its HTTP origin on the parent
1075
+ * window instead. Without one, relative URLs keep the page's own origin.
1076
+ */
1077
+ function streamOrigin() {
1078
+ try {
1079
+ const base = window.parent?.__DSH_TRANSPORT__?.streamBaseUrl;
1080
+ if (typeof base === 'string' && base) return new URL(base).origin;
1081
+ } catch { /* a cross-origin parent, or a malformed base */ }
1082
+ return '';
1083
+ }
1084
+
1011
1085
  /**
1012
1086
  * The fallback transport: this page owns an `<audio>` element.
1013
1087
  *
1014
- * It reconciles on `transportRev`, but enforces play/pause on every poll
1015
- * — a refused `play()` does not change the revision, so gating the retry
1016
- * would stop the music for good after the first browser refusal.
1088
+ * It runs the shell engine's playback core, `playback.js`, which this
1089
+ * page loads from its own host rather than from the bundle — the bundle
1090
+ * is exactly what this fallback cannot trust. The core reconciles on
1091
+ * `transportRev` but enforces play/pause on every update, as the engine
1092
+ * does: a refused `play()` does not change the revision, so gating the
1093
+ * retry would stop the music for good after the first browser refusal.
1017
1094
  */
1018
1095
  function createLocalTransport() {
1019
- const audio = document.createElement('audio');
1020
- audio.preload = 'auto';
1021
- audio.style.display = 'none';
1022
- document.body.appendChild(audio);
1023
-
1024
- let applied = -1;
1025
- let busy = false;
1026
- let disposed = false;
1027
-
1028
- function attemptPlay() {
1029
- if (busy || disposed) return;
1030
- busy = true;
1031
- const done = () => { busy = false; };
1032
- audio.play().then(done, done);
1033
- }
1034
-
1035
- function reconcile(next) {
1036
- if (!next || next.transportRev === applied) return;
1037
- applied = next.transportRev;
1038
- if (next.pendingSeek !== null && next.pendingSeek !== undefined) {
1039
- try { audio.currentTime = next.pendingSeek / 1000; } catch { /* not seekable yet */ }
1040
- api('/seek-consumed', { method: 'POST', body: {} }).catch(() => {});
1041
- }
1042
- }
1043
-
1044
- /**
1045
- * Pick the resource to play. Every poll, not just on a transport change:
1046
- * the resource identity includes the streaming quality, so a quality
1047
- * switch has to be noticed without waiting for the revision to move.
1048
- * The level rides in the URL because the same track at two levels is two
1049
- * different files — range-requesting offsets across encodings would
1050
- * corrupt the stream.
1051
- */
1052
- function applySource(next) {
1053
- const track = next.current;
1054
- if (!track) {
1055
- if (audio.dataset.trackKey !== undefined) {
1056
- delete audio.dataset.trackKey;
1057
- delete audio.dataset.trackId;
1058
- audio.pause();
1059
- audio.removeAttribute('src');
1060
- audio.load();
1061
- }
1062
- return;
1063
- }
1064
- const level = next.audio?.preferred ?? 'exhigh';
1065
- const key = track.id + ':' + level;
1066
- if (audio.dataset.trackKey === key) return;
1067
-
1068
- const sameTrack = audio.dataset.trackId === String(track.id);
1069
- const resumeAt = sameTrack ? audio.currentTime : 0;
1070
- audio.dataset.trackKey = key;
1071
- audio.dataset.trackId = String(track.id);
1072
- if (resumeAt > 0.5) {
1073
- audio.addEventListener('loadedmetadata', () => {
1074
- try { audio.currentTime = resumeAt; } catch { /* not seekable */ }
1075
- }, { once: true });
1076
- }
1077
- audio.src = BASE + '/stream/' + track.id + '?level=' + encodeURIComponent(level);
1078
- audio.load();
1079
- }
1080
-
1081
- function apply(next) {
1082
- if (disposed || !next) return;
1083
- reconcile(next);
1084
- applySource(next);
1085
- audio.volume = next.muted ? 0 : next.volume;
1086
- if (!next.current) return;
1087
- if (next.playing && audio.paused) attemptPlay();
1088
- else if (!next.playing && !audio.paused) audio.pause();
1089
- }
1090
-
1091
- async function report(extra) {
1092
- if (!state?.current) return;
1093
- try {
1094
- await api('/report', {
1096
+ const playback = window.__dshMusicPlayback.createPlayback({
1097
+ base: BASE,
1098
+ streamOrigin,
1099
+ call: api,
1100
+ report(extra) {
1101
+ if (!state?.current) return;
1102
+ api('/report', {
1095
1103
  method: 'POST',
1096
- body: {
1097
- trackId: state.current.id,
1098
- position: Math.round((audio.currentTime || 0) * 1000),
1099
- duration: Number.isFinite(audio.duration) ? Math.round(audio.duration * 1000) : undefined,
1100
- playing: !audio.paused,
1101
- ...extra,
1102
- },
1103
- });
1104
- } catch { /* the host will be re-read on the next poll */ }
1105
- }
1106
-
1107
- audio.addEventListener('ended', () => report({ ended: true }));
1108
- audio.addEventListener('error', () => {
1109
- if (audio.dataset.trackId) report({ error: 'audio element error (track unavailable or network)' });
1104
+ body: { trackId: state.current.id, ...playback.progress(), ...extra },
1105
+ }).catch(() => { /* the next update carries the host's view */ });
1106
+ },
1110
1107
  });
1111
- audio.addEventListener('timeupdate', () => { paintProgress(); paintLyrics(); });
1108
+ playback.audio.addEventListener('timeupdate', () => { paintProgress(); paintLyrics(); });
1112
1109
 
1113
1110
  return {
1114
1111
  playback: true,
1115
1112
  local: true,
1116
- apply,
1117
- sync() { apply(state); },
1118
- playNow() { attemptPlay(); },
1119
- /** Exact position: this transport owns the element. */
1120
- position: () => (audio.currentTime || 0) * 1000,
1121
- dispose() {
1122
- disposed = true;
1123
- try {
1124
- audio.pause();
1125
- audio.removeAttribute('src');
1126
- audio.remove();
1127
- } catch { /* the document may already be gone */ }
1128
- },
1113
+ apply: playback.apply,
1114
+ sync() { playback.apply(state); },
1115
+ playNow: playback.playNow,
1116
+ /** Exact position: this transport owns the element. A held seek counts as already there. */
1117
+ position: playback.position,
1118
+ dispose: playback.dispose,
1129
1119
  };
1130
1120
  }
1131
1121
 
@@ -1137,14 +1127,14 @@
1137
1127
  } catch { /* a failing transport must not break rendering */ }
1138
1128
  }
1139
1129
 
1140
- /** Ask the active transport to act now instead of on its next poll. */
1130
+ /** Ask the active transport to act now instead of on its next update. */
1141
1131
  function pokeEngine() {
1142
1132
  try { transport().sync?.(); } catch { /* best effort across documents */ }
1143
1133
  }
1144
1134
 
1145
1135
  async function control(body) {
1146
1136
  try {
1147
- state = await api('/control', { method: 'POST', body });
1137
+ state = newest(await api('/control', { method: 'POST', body }));
1148
1138
  render();
1149
1139
  applyTransport();
1150
1140
  } catch (error) { toast(error.message); }
@@ -1154,9 +1144,11 @@
1154
1144
  /**
1155
1145
  * Playback position.
1156
1146
  *
1157
- * A local element knows exactly; the shell engine reports about once a
1158
- * second, which is too coarse for a smooth bar, so the time since its
1159
- * report is added back.
1147
+ * The transport reads its own element when it can — the local one, and
1148
+ * the shell engine, whose document this page can reach. An engine from
1149
+ * an older bundle has no `position()`, so its last report to the host is
1150
+ * used, with the time since added back; the host pushes no frame for a
1151
+ * report that only moves the position, so that report can be minutes old.
1160
1152
  */
1161
1153
  function positionMs() {
1162
1154
  const active = transport();
@@ -1175,19 +1167,16 @@
1175
1167
  }
1176
1168
 
1177
1169
  /**
1178
- * The host wants playback, and the transport's own report for *this*
1179
- * track says it is not playing. In practice that means the browser
1180
- * refused to start audio until the page has been interacted with.
1170
+ * The host wants playback, and the transport reported that the browser
1171
+ * refused to start it until the page is interacted with.
1172
+ *
1173
+ * Only the refusal counts. "Wanted but not playing" alone is also true
1174
+ * for the half second after any Play click, before the transport has
1175
+ * caught up — which flashed this hint on every press.
1181
1176
  */
1182
1177
  function autoplayBlocked() {
1183
1178
  const reported = state?.reported;
1184
- return Boolean(
1185
- state?.playing &&
1186
- state?.current &&
1187
- reported?.playing === false &&
1188
- Number(reported.at) > 0 &&
1189
- reported.trackId === state.current.id,
1190
- );
1179
+ return Boolean(state?.playing && state?.current && reported?.blocked === true && reported.playing === false);
1191
1180
  }
1192
1181
 
1193
1182
  /**
@@ -1214,21 +1203,26 @@
1214
1203
  function render() {
1215
1204
  if (!state) return;
1216
1205
  const track = state.current;
1217
- $('cover').src = track?.picUrl || '';
1218
- $('cover').style.visibility = track?.picUrl ? 'visible' : 'hidden';
1219
- $('np-title').textContent = track ? track.name : t('nothingPlaying');
1220
- $('np-artists').textContent = track ? (track.artists || []).join(' / ') : '';
1221
- $('np-album').textContent = track ? track.album || '' : '';
1206
+ const cover = track?.picUrl || '';
1207
+ // Setting the same `src` again restarts the image load.
1208
+ if ($('cover').dataset.src !== cover) {
1209
+ $('cover').dataset.src = cover;
1210
+ $('cover').src = cover;
1211
+ }
1212
+ $('cover').style.visibility = cover ? 'visible' : 'hidden';
1213
+ setText($('np-title'), track ? track.name : t('nothingPlaying'));
1214
+ setText($('np-artists'), track ? (track.artists || []).join(' / ') : '');
1215
+ setText($('np-album'), track ? track.album || '' : '');
1222
1216
  // Details and lyrics belong to the track, and this page fetches them
1223
- // itself on every poll — not from the local transport's `applySource`,
1217
+ // itself on every update — not from the local transport's `applySource`,
1224
1218
  // which only ever runs when this page owns the audio element. In the
1225
1219
  // normal case the shell engine plays, so that path is dead and the
1226
1220
  // pane stayed empty forever.
1227
1221
  syncInfo(track?.id ?? null);
1228
1222
  loadIntro();
1223
+ prefetchNextDetails();
1229
1224
  setIcon($('play'), state.playing ? 'pause' : 'play', { filled: true });
1230
- $('mode').textContent = { list: t('modeList'), single: t('modeSingle'), shuffle: t('modeShuffle') }[state.mode] || t('modeList');
1231
- $('counts').textContent = state.counts ? `(${state.counts.queued})` : '';
1225
+ setText($('mode'), { list: t('modeList'), single: t('modeSingle'), shuffle: t('modeShuffle') }[state.mode] || t('modeList'));
1232
1226
  $('queue-clear').disabled = (state.queue?.length ?? 0) <= (state.current ? 1 : 0);
1233
1227
  $('dj-toggle').classList.toggle('on', Boolean(state.dj?.enabled));
1234
1228
  paintHistory();
@@ -1238,21 +1232,23 @@
1238
1232
 
1239
1233
  // Account chip
1240
1234
  const account = state.account;
1241
- $('account').innerHTML = account
1235
+ const chip = account
1242
1236
  ? `${account.avatar ? `<img src="${esc(account.avatar)}" alt="">` : ''}<span>${esc(account.nickname)}${account.vip ? ' · VIP' : ''}</span>`
1243
1237
  : `<button id="signin">${esc(t('signin'))}</button>`;
1244
- const signin = $('signin');
1245
- if (signin) signin.onclick = openLogin;
1238
+ if (setHtml($('account'), chip)) {
1239
+ const signin = $('signin');
1240
+ if (signin) signin.onclick = openLogin;
1241
+ }
1246
1242
 
1247
1243
  // DJ status
1248
1244
  const dj = state.dj || {};
1249
- $('dj-status').innerHTML = dj.enabled || dj.lastPlan
1245
+ setHtml($('dj-status'), dj.enabled || dj.lastPlan
1250
1246
  ? `<div class="plan">${dj.busy ? esc(t('djPlanning')) : dj.error ? `AI DJ: ${esc(dj.error)}` : ''}${
1251
1247
  dj.lastPlan
1252
1248
  ? `<div><b>+${dj.lastPlan.added}</b> ${esc(dj.lastPlan.vibe || '')}</div><div class="muted">${esc((dj.lastPlan.names || []).slice(-3).join(' · '))}</div>`
1253
1249
  : ''
1254
1250
  }${dj.modelError && !dj.lastPlan?.route ? `<div class="muted">${esc(t('modelTierUnavailable'))}: ${esc(dj.modelError)}</div>` : ''}${dj.lastPlan?.source === 'heuristic' ? `<div class="muted">${esc(t('heuristics'))}</div>` : ''}</div>`
1255
- : '';
1251
+ : '');
1256
1252
 
1257
1253
  if (autoplayBlocked()) {
1258
1254
  if (!$('gesture')) {
@@ -1299,8 +1295,15 @@
1299
1295
  function renderQueue() {
1300
1296
  if (!state) return;
1301
1297
  const queue = state.queue || [];
1298
+ const total = state.counts ? `(${state.counts.queued})` : '';
1302
1299
  if (queue.length === 0) {
1303
- $('queue').innerHTML = `<div class="empty">${esc(t('queueEmpty'))}</div>`;
1300
+ setText($('counts'), total);
1301
+ // Emptying the list dropped its scroll position, so a queue restored
1302
+ // with the same song playing has to be revealed again.
1303
+ if (setHtml($('queue'), `<div class="empty">${esc(t('queueEmpty'))}</div>`)) {
1304
+ revealedRow = null;
1305
+ revealing = null;
1306
+ }
1304
1307
  return;
1305
1308
  }
1306
1309
  // A window of at most MAX_VISIBLE_ROWS rows that always includes the
@@ -1310,10 +1313,8 @@
1310
1313
  const cursor = state.index < 0 ? 0 : state.index;
1311
1314
  const start = Math.max(0, Math.min(cursor - 4, queue.length - MAX_VISIBLE_ROWS));
1312
1315
  const end = Math.min(queue.length, start + MAX_VISIBLE_ROWS);
1313
- if (end - start < queue.length) {
1314
- $('counts').textContent = `(${start + 1}–${end} / ${queue.length})`;
1315
- }
1316
- $('queue').innerHTML = queue
1316
+ setText($('counts'), end - start < queue.length ? `(${start + 1}–${end} / ${queue.length})` : total);
1317
+ setHtml($('queue'), queue
1317
1318
  .slice(start, end)
1318
1319
  .map((track, offset) => {
1319
1320
  const index = start + offset;
@@ -1328,7 +1329,93 @@
1328
1329
  <span class="acts"><button data-remove="${index}" title="${esc(t('remove'))}">${icon('x', { small: true })}</button></span>
1329
1330
  </div>`;
1330
1331
  })
1331
- .join('');
1332
+ .join(''));
1333
+ revealPlayingRow();
1334
+ }
1335
+
1336
+ /** The playing row the queue last scrolled to, as `index:trackId`. */
1337
+ let revealedRow = null;
1338
+
1339
+ /**
1340
+ * A smooth reveal still under way: the list edge the row is headed for
1341
+ * and the scroll position that lands it there.
1342
+ */
1343
+ let revealing = null;
1344
+
1345
+ // A reveal ends when the list comes to rest, or when the user scrolls it
1346
+ // themselves.
1347
+ for (const type of ['scrollend', 'wheel', 'touchstart', 'pointerdown', 'keydown']) {
1348
+ $('queue').addEventListener(type, () => { revealing = null; }, { passive: true });
1349
+ }
1350
+
1351
+ /**
1352
+ * Bring the playing row into the queue's view when a new song starts.
1353
+ *
1354
+ * Only on a change of song: the list is re-rendered on every update, and
1355
+ * scrolling then would yank it back while the user browses what comes
1356
+ * next. Only the list itself scrolls — stacked in a narrow window the list
1357
+ * does not scroll on its own, and moving the whole page for it would lose
1358
+ * whatever the user is reading on the stage. A row already in view stays
1359
+ * put; the first paint jumps, later songs glide.
1360
+ */
1361
+ function revealPlayingRow() {
1362
+ const list = $('queue');
1363
+ const row = list.querySelector('.row.playing');
1364
+ if (!row || list.offsetParent === null) return;
1365
+ const key = `${state.index}:${state.current?.id}`;
1366
+ if (key === revealedRow) {
1367
+ followReveal(list, row);
1368
+ return;
1369
+ }
1370
+ const first = revealedRow === null;
1371
+ revealedRow = key;
1372
+ revealing = null;
1373
+ const view = list.getBoundingClientRect();
1374
+ const box = row.getBoundingClientRect();
1375
+ const edge = box.top < view.top ? 'top' : box.bottom > view.bottom ? 'bottom' : null;
1376
+ if (!edge) return;
1377
+ const top = revealTarget(list, row, edge);
1378
+ if (first || matchMedia('(prefers-reduced-motion: reduce)').matches) {
1379
+ list.scrollTo({ top, behavior: 'instant' });
1380
+ return;
1381
+ }
1382
+ revealing = { edge, top };
1383
+ list.scrollTo({ top, behavior: 'smooth' });
1384
+ }
1385
+
1386
+ /**
1387
+ * Keep a glide aimed at the row when a repaint moves it.
1388
+ *
1389
+ * Songs landing in a short queue slide the painted window, and the row
1390
+ * with it, while the list is still scrolling to where the row was. A glide
1391
+ * that has arrived is left alone: from then on a moving row is a change of
1392
+ * queue, not of song.
1393
+ */
1394
+ function followReveal(list, row) {
1395
+ if (!revealing) return;
1396
+ if (Math.abs(list.scrollTop - revealing.top) < 1) {
1397
+ revealing = null;
1398
+ return;
1399
+ }
1400
+ const top = revealTarget(list, row, revealing.edge);
1401
+ if (Math.abs(top - revealing.top) < 1) return;
1402
+ revealing.top = top;
1403
+ list.scrollTo({ top, behavior: 'smooth' });
1404
+ }
1405
+
1406
+ /**
1407
+ * The scroll position that puts the row at one edge of the list, with
1408
+ * half a row of its neighbours showing so it does not land flush against
1409
+ * the card's edge.
1410
+ */
1411
+ function revealTarget(list, row, edge) {
1412
+ const view = list.getBoundingClientRect();
1413
+ const box = row.getBoundingClientRect();
1414
+ const margin = box.height / 2;
1415
+ const top = edge === 'top'
1416
+ ? list.scrollTop + box.top - view.top - margin
1417
+ : list.scrollTop + box.bottom - view.bottom + margin;
1418
+ return Math.max(0, Math.min(top, list.scrollHeight - list.clientHeight));
1332
1419
  }
1333
1420
 
1334
1421
  /**
@@ -1364,7 +1451,7 @@
1364
1451
  function paintBoosts() {
1365
1452
  const boosts = state?.boosts ?? [];
1366
1453
  const now = Date.now();
1367
- $('boosts').innerHTML = boosts.length
1454
+ setHtml($('boosts'), boosts.length
1368
1455
  ? `<span>${esc(t('boostsTitle'))}:</span>` +
1369
1456
  boosts
1370
1457
  .map((boost) => {
@@ -1372,14 +1459,14 @@
1372
1459
  return `<span class="boost">${icon(boost.direction === 'more' ? 'more' : 'less', { small: true })} ${esc(boost.name)} · ${esc(t('boostMinutes', { n: minutes }))}<button data-unboost="${boost.id}" title="${esc(t('boostClear'))}">${icon('x', { small: true })}</button></span>`;
1373
1460
  })
1374
1461
  .join('')
1375
- : '';
1462
+ : '');
1376
1463
  }
1377
1464
 
1378
1465
  /** Boost a track, or clear its boost with `none`, and adopt the host's answer. */
1379
1466
  async function sendBoost(trackId, direction, button) {
1380
1467
  if (button) button.disabled = true;
1381
1468
  try {
1382
- state = await api('/boost', { method: 'POST', body: { trackId, direction } });
1469
+ state = newest(await api('/boost', { method: 'POST', body: { trackId, direction } }));
1383
1470
  render();
1384
1471
  applyTransport();
1385
1472
  toast(t(direction === 'more' ? 'boostedMore' : direction === 'less' ? 'boostedLess' : 'boostCleared'));
@@ -1411,7 +1498,7 @@
1411
1498
  // mid-flight is locked out, exactly as the transport switchers do.
1412
1499
  if (button) button.disabled = true;
1413
1500
  try {
1414
- state = await api('/queue', { method: 'POST', body: { action: 'remove', index } });
1501
+ state = newest(await api('/queue', { method: 'POST', body: { action: 'remove', index } }));
1415
1502
  // Read the answer off the new queue: an index that named a row someone
1416
1503
  // else had already dropped must not claim a removal that did not happen.
1417
1504
  return !(state.queue || []).some((entry) => entry.id === track.id);
@@ -1437,7 +1524,7 @@
1437
1524
  // promised.
1438
1525
  if (button) button.disabled = true;
1439
1526
  try {
1440
- state = await api('/taste', { method: 'POST', body: { trackId: track.id, level } });
1527
+ state = newest(await api('/taste', { method: 'POST', body: { trackId: track.id, level } }));
1441
1528
  render();
1442
1529
  applyTransport();
1443
1530
  return true;
@@ -1458,8 +1545,8 @@
1458
1545
  if (document.activeElement !== $('seek')) {
1459
1546
  $('seek').value = duration > 0 ? String(Math.round((position / duration) * 1000)) : '0';
1460
1547
  }
1461
- $('t-cur').textContent = fmt(position);
1462
- $('t-dur').textContent = fmt(duration);
1548
+ setText($('t-cur'), fmt(position));
1549
+ setText($('t-dur'), fmt(duration));
1463
1550
  }
1464
1551
 
1465
1552
  // ------------------------------------------------------ details + lyrics
@@ -1535,27 +1622,67 @@
1535
1622
  if (prose) prose.classList.toggle('open');
1536
1623
  };
1537
1624
 
1625
+ /** One track's details, fetched once however many ask, and kept. */
1626
+ function fetchDetails(id) {
1627
+ if (!detailsLoads.has(id)) {
1628
+ const load = api('/info/' + id)
1629
+ .then((info) => {
1630
+ detailsCache.set(id, info);
1631
+ if (detailsCache.size > 30) detailsCache.delete(detailsCache.keys().next().value);
1632
+ return info;
1633
+ })
1634
+ .finally(() => detailsLoads.delete(id));
1635
+ detailsLoads.set(id, load);
1636
+ }
1637
+ return detailsLoads.get(id);
1638
+ }
1639
+
1640
+ /**
1641
+ * Fetch the next track's details ahead, so they show the moment it
1642
+ * starts. Lazy like the introduction: only after the shown track's
1643
+ * details have painted, and only while the details are shown.
1644
+ * Shuffle has no known next track, and repeat-one's next is this one.
1645
+ */
1646
+ function prefetchNextDetails() {
1647
+ if (infoView !== 'details' || !detailsTrackId || !detailsCache.has(detailsTrackId)) return;
1648
+ if (!state || state.mode !== 'list') return;
1649
+ const next = state.queue?.[state.index + 1];
1650
+ if (!next?.id || detailsCache.has(next.id) || detailsLoads.has(next.id)) return;
1651
+ fetchDetails(next.id).catch(() => { /* the track's own load retries */ });
1652
+ }
1653
+
1538
1654
  async function loadDetails(id) {
1539
1655
  const request = ++detailsRequest;
1540
1656
  introSource = 'ai';
1541
1657
  const cached = detailsCache.get(id);
1542
1658
  if (cached) {
1543
1659
  paintDetails(cached);
1660
+ setTimeout(afterDetails);
1544
1661
  return;
1545
1662
  }
1546
1663
  $('details').innerHTML = `<p class="hint">${esc(t('loading'))}</p>`;
1547
1664
  try {
1548
- const info = await api('/info/' + id);
1549
- detailsCache.set(id, info);
1550
- if (detailsCache.size > 30) detailsCache.delete(detailsCache.keys().next().value);
1665
+ const info = await fetchDetails(id);
1551
1666
  if (request !== detailsRequest) return;
1552
1667
  paintDetails(info);
1668
+ setTimeout(afterDetails);
1553
1669
  } catch (error) {
1554
1670
  if (request !== detailsRequest) return;
1555
1671
  $('details').innerHTML = `<p class="hint">${esc(error.message)}</p>`;
1556
1672
  }
1557
1673
  }
1558
1674
 
1675
+ /**
1676
+ * What waits for the details to paint: the introduction and the next
1677
+ * track's details. Its own turn, so neither is asked for before the
1678
+ * facts are on screen, and not tied to the next update from the host,
1679
+ * which may be minutes away now that it only comes on a change.
1680
+ */
1681
+ function afterDetails() {
1682
+ loadIntro();
1683
+ prefetchNextDetails();
1684
+ }
1685
+
1559
1686
  /** Paint the shown track's details again: a language switch, an introduction, the switch. */
1560
1687
  function repaintDetails(options) {
1561
1688
  const info = detailsCache.get(detailsTrackId);
@@ -1565,8 +1692,8 @@
1565
1692
  /**
1566
1693
  * Ask for the shown track's introduction, once its details are painted.
1567
1694
  *
1568
- * Lazy on purpose: a model call takes seconds, so it waits for the poll
1569
- * after the details land — playback and the NetEase facts never wait on
1695
+ * Lazy on purpose: a model call takes seconds, so it waits until the
1696
+ * details have painted — playback and the NetEase facts never wait on
1570
1697
  * it — and it is asked only for the track the visible pane shows.
1571
1698
  */
1572
1699
  async function loadIntro() {
@@ -1979,7 +2106,7 @@
1979
2106
 
1980
2107
  async function saveModelRoute(provider, model, message) {
1981
2108
  try {
1982
- state = await api('/dj', { method: 'POST', body: { provider, model } });
2109
+ state = newest(await api('/dj', { method: 'POST', body: { provider, model } }));
1983
2110
  render();
1984
2111
  await loadModelPicker();
1985
2112
  toast(message);
@@ -2053,12 +2180,12 @@
2053
2180
  const last = state?.audio?.last;
2054
2181
  const preferred = state?.audio?.preferred;
2055
2182
  if (!last || (preferred && last.requested !== preferred && last.trackId !== state?.current?.id)) {
2056
- $('quality-info').textContent = '';
2183
+ setText($('quality-info'), '');
2057
2184
  return;
2058
2185
  }
2059
2186
  const kbps = last.br ? ` · ${Math.round(last.br / 1000)} kbps` : '';
2060
- $('quality-info').textContent =
2061
- `▶ ${String(last.type ?? '').toUpperCase()}${kbps}` + (last.downgraded ? ` (${last.served}, ${t('downgraded')})` : '');
2187
+ setText($('quality-info'),
2188
+ `▶ ${String(last.type ?? '').toUpperCase()}${kbps}` + (last.downgraded ? ` (${last.served}, ${t('downgraded')})` : ''));
2062
2189
  }
2063
2190
 
2064
2191
  async function loadQuality() {
@@ -2078,7 +2205,7 @@
2078
2205
 
2079
2206
  $('quality').onchange = async (event) => {
2080
2207
  try {
2081
- state = await api('/quality', { method: 'POST', body: { level: event.target.value } });
2208
+ state = newest(await api('/quality', { method: 'POST', body: { level: event.target.value } }));
2082
2209
  render();
2083
2210
  applyTransport();
2084
2211
  pokeEngine();
@@ -2107,6 +2234,8 @@
2107
2234
  }
2108
2235
  };
2109
2236
  $('volume').onchange = (event) => control({ action: 'volume', value: Number(event.target.value) });
2237
+ // Sent at once: the transport silences on the first seek and debounces
2238
+ // the resume, so delaying here would only let the old position play on.
2110
2239
  $('seek').onchange = (event) => {
2111
2240
  control({ action: 'seek', value: Math.round((Number(event.target.value) / 1000) * durationMs()) });
2112
2241
  };
@@ -2149,7 +2278,7 @@
2149
2278
  const button = event?.currentTarget;
2150
2279
  if (button) button.disabled = true;
2151
2280
  try {
2152
- state = await api('/scrobble', { method: 'POST', body: { enabled: next } });
2281
+ state = newest(await api('/scrobble', { method: 'POST', body: { enabled: next } }));
2153
2282
  render();
2154
2283
  toast(t(next ? 'scrobbleOn' : 'scrobbleOff'));
2155
2284
  } catch (error) {
@@ -2162,17 +2291,17 @@
2162
2291
  $('dj-toggle').onclick = async () => {
2163
2292
  try {
2164
2293
  const data = await api('/dj', { method: 'POST', body: { enabled: !state?.dj?.enabled, prompt: $('dj-prompt').value } });
2165
- state = data;
2294
+ state = newest(data);
2166
2295
  render();
2167
2296
  toast(state.dj?.enabled ? t('djOn') : t('djOff'));
2168
2297
  } catch (error) { toast(error.message); }
2169
2298
  };
2170
- $('dj-prompt').onchange = () => api('/dj', { method: 'POST', body: { prompt: $('dj-prompt').value, enabled: state?.dj?.enabled } }).then((data) => { state = data; render(); }).catch((error) => toast(error.message));
2299
+ $('dj-prompt').onchange = () => api('/dj', { method: 'POST', body: { prompt: $('dj-prompt').value, enabled: state?.dj?.enabled } }).then((data) => { state = newest(data); render(); }).catch((error) => toast(error.message));
2171
2300
 
2172
2301
  // Not row-by-row removal, which reads each row as a dislike.
2173
2302
  $('queue-clear').onclick = async () => {
2174
2303
  try {
2175
- state = await api('/queue', { method: 'POST', body: { action: 'clear', keepCurrent: true } });
2304
+ state = newest(await api('/queue', { method: 'POST', body: { action: 'clear', keepCurrent: true } }));
2176
2305
  render();
2177
2306
  pokeEngine();
2178
2307
  } catch (error) { toast(failureText(error)); }
@@ -2196,7 +2325,7 @@
2196
2325
  // The confirm names the click, not that side effect of it.
2197
2326
  if (await removeFromList(Number(remove.dataset.remove), remove)) toast(t('removed'));
2198
2327
  } else if (jump !== undefined) {
2199
- state = await api('/queue', { method: 'POST', body: { action: 'jump', index: Number(jump) } });
2328
+ state = newest(await api('/queue', { method: 'POST', body: { action: 'jump', index: Number(jump) } }));
2200
2329
  } else return;
2201
2330
  render();
2202
2331
  pokeEngine();
@@ -2204,29 +2333,81 @@
2204
2333
  };
2205
2334
 
2206
2335
  // ------------------------------------------------------------------ boot
2336
+ /**
2337
+ * The host pushes its state over `/events` whenever something here would
2338
+ * change. `/state` is re-read every `POLL_MS` only while that stream is
2339
+ * down — a browser without EventSource, a host that predates the route,
2340
+ * a reconnect under way — and every `STREAM_POLL_MS` while it is up, as
2341
+ * a safety net that also ages the boosts' minutes left.
2342
+ */
2343
+ const POLL_MS = 1500;
2344
+ const STREAM_POLL_MS = 30_000;
2345
+ /** A stream the browser gave up on (an error answer) is opened again after this. */
2346
+ const RELISTEN_MS = 10_000;
2347
+ let events = null;
2348
+ let receivedAt = 0;
2349
+
2350
+ function adopt(next) {
2351
+ receivedAt = Date.now();
2352
+ if (newest(next) !== next) return;
2353
+ state = next;
2354
+ render();
2355
+ applyTransport();
2356
+ }
2357
+
2207
2358
  async function refresh() {
2208
2359
  try {
2209
- state = await api('/state');
2210
- render();
2211
- applyTransport();
2360
+ adopt(await api('/state'));
2212
2361
  } catch (error) {
2213
- $('np-title').textContent = t('connectFailed') + error.message;
2362
+ setText($('np-title'), t('connectFailed') + error.message);
2214
2363
  }
2215
2364
  }
2216
2365
 
2366
+ function listen() {
2367
+ const Source = window.EventSource;
2368
+ if (typeof Source !== 'function') return;
2369
+ events = new Source(API + '/events');
2370
+ events.onopen = () => {
2371
+ streaming = true;
2372
+ // The host may have restarted, and its versions with it.
2373
+ versionFloor = 0;
2374
+ };
2375
+ events.onerror = () => {
2376
+ streaming = false;
2377
+ // A dropped connection is retried by the browser; an error status
2378
+ // closes the stream for good, so it is opened again from here.
2379
+ if (events.readyState === Source.CLOSED) {
2380
+ events = null;
2381
+ setTimeout(listen, RELISTEN_MS);
2382
+ }
2383
+ };
2384
+ events.addEventListener('state', (event) => {
2385
+ try { adopt(JSON.parse(event.data)); } catch { /* the next frame or poll repairs it */ }
2386
+ });
2387
+ }
2388
+
2217
2389
  paintStaticIcons();
2218
2390
  applyLocale();
2219
2391
  watchShellLocale();
2220
2392
  syncShellTheme();
2221
2393
  refresh();
2222
- setInterval(refresh, 1500);
2394
+ listen();
2395
+ setInterval(() => {
2396
+ if (!streaming || Date.now() - receivedAt >= STREAM_POLL_MS) refresh();
2397
+ // A refused play changes nothing on the host, so no update would come
2398
+ // to retry it: a page that owns its audio retries on this clock.
2399
+ else applyTransport();
2400
+ }, POLL_MS);
2223
2401
  void loadModelPicker();
2224
2402
  void loadQuality();
2225
- // Progress and lyric highlighting interpolate locally between the
2226
- // engine's reports, so they need their own repaint clock now that the
2227
- // audio element lives in the shell document.
2403
+ // Progress and lyric highlighting follow the audio element, which lives
2404
+ // in the shell document and reports nothing here, so they need their own
2405
+ // repaint clock.
2228
2406
  setInterval(() => { paintProgress(); paintLyrics(); }, 250);
2229
- window.addEventListener('beforeunload', () => { clearInterval(qrTimer); });
2407
+ window.addEventListener('beforeunload', () => {
2408
+ clearInterval(qrTimer);
2409
+ events?.close();
2410
+ });
2230
2411
  </script>
2231
2412
  </body>
2232
2413
  </html>