@doitian/dsh-music 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,1105 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <!--
7
+ The page/engine boundary this document implements. The engine reads it
8
+ here rather than trusting the host's own version, because *this document*
9
+ is what decides whether to defer audio ownership — and unlike the running
10
+ host module, it is re-read from disk on every plugin mount. Keep it in
11
+ step with PANEL_CONTRACT in lib/client.js and lib/router.js.
12
+ -->
13
+ <meta name="dsh-music-panel-contract" content="2" />
14
+ <title>Music · music.163.com</title>
15
+ <style>
16
+ :root {
17
+ color-scheme: light dark;
18
+ --bg: var(--dsh-background, #ffffff);
19
+ --fg: var(--dsh-foreground, #1b1c1e);
20
+ --muted: color-mix(in srgb, var(--fg) 55%, transparent);
21
+ --line: color-mix(in srgb, var(--fg) 14%, transparent);
22
+ --panel: color-mix(in srgb, var(--fg) 4%, transparent);
23
+ --accent: #e8503a;
24
+ --radius: 10px;
25
+ }
26
+ * { box-sizing: border-box; }
27
+ html, body { margin: 0; height: 100%; }
28
+ body {
29
+ font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
30
+ "Microsoft YaHei", sans-serif;
31
+ background: var(--bg); color: var(--fg); overflow: hidden;
32
+ }
33
+ button, input, select { font: inherit; color: inherit; }
34
+ button {
35
+ background: var(--panel); border: 1px solid var(--line); border-radius: 8px;
36
+ padding: 5px 10px; cursor: pointer; white-space: nowrap;
37
+ }
38
+ button:hover:not(:disabled) { border-color: color-mix(in srgb, var(--fg) 30%, transparent); }
39
+ button:disabled { opacity: 0.45; cursor: default; }
40
+ button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
41
+ input, select {
42
+ background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 9px;
43
+ }
44
+ input:focus, select:focus { outline: 2px solid color-mix(in srgb, var(--accent) 45%, transparent); }
45
+
46
+ #app { display: flex; flex-direction: column; height: 100%; }
47
+
48
+ header {
49
+ display: flex; align-items: center; gap: 8px; padding: 10px 14px;
50
+ border-bottom: 1px solid var(--line); flex-wrap: wrap;
51
+ }
52
+ .brand { font-weight: 650; letter-spacing: 0.2px; }
53
+ .brand small { font-weight: 400; color: var(--muted); margin-left: 6px; }
54
+ .spacer { flex: 1; }
55
+ #dj-prompt { min-width: 200px; flex: 0 1 260px; }
56
+ #dj-toggle.on { background: var(--accent); border-color: var(--accent); color: #fff; }
57
+ #account { display: flex; align-items: center; gap: 7px; color: var(--muted); }
58
+ #account img { width: 22px; height: 22px; border-radius: 50%; }
59
+
60
+ main { display: flex; flex: 1; min-height: 0; }
61
+ .left { flex: 1 1 46%; min-width: 0; display: flex; flex-direction: column; border-right: 1px solid var(--line); }
62
+ .right { flex: 1 1 54%; min-width: 0; display: flex; flex-direction: column; }
63
+
64
+ .tabs { display: flex; gap: 4px; padding: 9px 12px 0; }
65
+ .tabs button { border-radius: 999px; }
66
+ .tabs button.on { background: color-mix(in srgb, var(--accent) 16%, transparent); border-color: color-mix(in srgb, var(--accent) 40%, transparent); }
67
+ .searchbar { display: flex; gap: 6px; padding: 9px 12px; }
68
+ .searchbar input { flex: 1; min-width: 0; }
69
+
70
+ .scroll { overflow: auto; padding: 0 8px 16px; flex: 1; }
71
+ .scroll::-webkit-scrollbar { width: 9px; }
72
+ .scroll::-webkit-scrollbar-thumb { background: color-mix(in srgb, var(--fg) 18%, transparent); border-radius: 9px; }
73
+
74
+ .row {
75
+ display: flex; align-items: center; gap: 10px; padding: 6px 8px; border-radius: 8px; cursor: pointer;
76
+ }
77
+ .row:hover { background: var(--panel); }
78
+ .row.playing { background: color-mix(in srgb, var(--accent) 12%, transparent); }
79
+ .row .idx { width: 22px; text-align: right; color: var(--muted); font-variant-numeric: tabular-nums; flex: none; }
80
+ .row img { width: 34px; height: 34px; border-radius: 6px; object-fit: cover; flex: none; background: var(--panel); }
81
+ .row .meta { min-width: 0; flex: 1; }
82
+ .row .name { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
83
+ .row .sub { display: block; color: var(--muted); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
84
+ .row .tag { font-size: 10px; border: 1px solid var(--line); border-radius: 4px; padding: 1px 4px; color: var(--muted); flex: none; }
85
+ .row .dur { color: var(--muted); font-variant-numeric: tabular-nums; flex: none; font-size: 12px; }
86
+ .row .acts { display: none; gap: 4px; flex: none; }
87
+ .row:hover .acts { display: flex; }
88
+ .card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(126px, 1fr)); gap: 10px; padding: 4px 8px; }
89
+ .card { cursor: pointer; }
90
+ .card img { width: 100%; aspect-ratio: 1; border-radius: 8px; object-fit: cover; background: var(--panel); }
91
+ .card .name { font-size: 12px; margin-top: 5px; line-height: 1.35; max-height: 2.7em; overflow: hidden; }
92
+ .card .sub { color: var(--muted); font-size: 11px; }
93
+
94
+ .now { padding: 14px; border-bottom: 1px solid var(--line); }
95
+ .now-top { display: flex; gap: 14px; }
96
+ .now-top img { width: 104px; height: 104px; border-radius: 10px; object-fit: cover; background: var(--panel); flex: none; }
97
+ .now-title { font-size: 16px; font-weight: 650; line-height: 1.3; }
98
+ .now-artists { color: var(--muted); margin-top: 3px; }
99
+ .now-album { color: var(--muted); font-size: 12px; margin-top: 2px; }
100
+ .bar { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }
101
+ input[type="range"] { -webkit-appearance: none; appearance: none; background: transparent; padding: 0; height: 16px; flex: 1; min-width: 0; }
102
+ input[type="range"]::-webkit-slider-runnable-track { height: 4px; border-radius: 4px; background: color-mix(in srgb, var(--fg) 18%, transparent); }
103
+ input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; margin-top: -4px; border-radius: 50%; background: var(--accent); }
104
+ .controls { display: flex; align-items: center; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
105
+ .controls .grow { flex: 1; }
106
+ .icon { font-size: 15px; line-height: 1; }
107
+ #volume { flex: 0 0 88px; }
108
+ .mode { font-size: 12px; }
109
+
110
+ .section-title { padding: 12px 14px 4px; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.6px; }
111
+ .lyrics { max-height: 34%; overflow: auto; padding: 0 14px 12px; }
112
+ .lyrics p { margin: 0; padding: 2px 0; color: var(--muted); transition: color 0.15s; }
113
+ .lyrics p.on { color: var(--fg); font-weight: 600; }
114
+ .queue { flex: 1; min-height: 0; display: flex; flex-direction: column; }
115
+ .queue .scroll { padding-top: 0; }
116
+ .dj-status { margin: 0 14px 12px; padding: 9px 11px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); font-size: 12px; }
117
+ .dj-status b { color: var(--accent); }
118
+ .curator-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
119
+ .row-inline { display: flex; gap: 6px; margin-top: 6px; align-items: center; }
120
+ .row-inline select, .row-inline input { flex: 1 1 0; min-width: 0; font-size: 12px; padding: 4px 6px; }
121
+ .row-inline button { font-size: 12px; padding: 4px 8px; }
122
+ .empty { padding: 24px 14px; color: var(--muted); text-align: center; }
123
+ .toast {
124
+ position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%);
125
+ background: #1b1c1e; color: #fff; padding: 8px 14px; border-radius: 9px; font-size: 12px;
126
+ opacity: 0; pointer-events: none; transition: opacity 0.2s; z-index: 40; max-width: 80%;
127
+ }
128
+ .toast.on { opacity: 0.94; }
129
+ dialog {
130
+ border: 1px solid var(--line); border-radius: 14px; background: var(--bg); color: var(--fg);
131
+ padding: 18px; width: min(340px, 88vw);
132
+ }
133
+ dialog::backdrop { background: rgba(0, 0, 0, 0.45); }
134
+ #qr { display: block; margin: 12px auto; width: 220px; height: 220px; image-rendering: pixelated; border-radius: 8px; background: #fff; padding: 8px; }
135
+ .hint { color: var(--muted); font-size: 12px; text-align: center; }
136
+ .row-actions { display: flex; gap: 6px; justify-content: flex-end; margin-top: 14px; }
137
+ .need-gesture { background: color-mix(in srgb, var(--accent) 14%, transparent); border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent); border-radius: var(--radius); padding: 8px 11px; margin: 0 14px 12px; font-size: 12px; }
138
+ </style>
139
+ </head>
140
+ <body>
141
+ <div id="app">
142
+ <header>
143
+ <div class="brand">音乐<small>music.163.com</small></div>
144
+ <div class="spacer"></div>
145
+ <input id="dj-prompt" placeholder="AI DJ 心情 / mood, e.g. rainy afternoon jazz" />
146
+ <button id="dj-toggle" title="Continuous AI DJ: keep the queue stocked">AI DJ</button>
147
+ <div id="account"></div>
148
+ </header>
149
+
150
+ <main>
151
+ <section class="left">
152
+ <div class="tabs">
153
+ <button data-tab="search" class="on">搜索 Search</button>
154
+ <button data-tab="charts">榜单 Charts</button>
155
+ <button data-tab="foryou">推荐 For you</button>
156
+ </div>
157
+ <div class="searchbar" id="searchbar">
158
+ <input id="q" placeholder="搜索歌曲、歌手、专辑 / search songs" />
159
+ <button id="go" class="primary">搜索</button>
160
+ </div>
161
+ <div class="scroll" id="browser"></div>
162
+ </section>
163
+
164
+ <section class="right">
165
+ <div class="now">
166
+ <div class="now-top">
167
+ <img id="cover" alt="" />
168
+ <div style="min-width: 0; flex: 1">
169
+ <div class="now-title" id="np-title">未播放 / nothing playing</div>
170
+ <div class="now-artists" id="np-artists"></div>
171
+ <div class="now-album" id="np-album"></div>
172
+ </div>
173
+ </div>
174
+ <div class="bar">
175
+ <span id="t-cur">0:00</span>
176
+ <input type="range" id="seek" min="0" max="1000" value="0" step="1" />
177
+ <span id="t-dur">0:00</span>
178
+ </div>
179
+ <div class="controls">
180
+ <button id="prev" title="上一首 previous">⏮</button>
181
+ <button id="play" class="primary" title="播放/暂停 play/pause">▶</button>
182
+ <button id="next" title="下一首 next">⏭</button>
183
+ <button id="mode" class="mode" title="播放模式 mode">列表</button>
184
+ <select id="quality" class="mode" title="流媒体音质 / streaming quality"></select>
185
+ <span id="quality-info" class="mode" style="color: var(--muted)"></span>
186
+ <span class="grow"></span>
187
+ <button id="like" title="喜欢 like">♡</button>
188
+ <button id="dislike" title="不喜欢 dislike">✕</button>
189
+ <button id="mute" title="静音 mute">🔊</button>
190
+ <input type="range" id="volume" min="0" max="1" step="0.01" value="0.8" />
191
+ </div>
192
+ </div>
193
+
194
+ <div class="section-title">歌词 Lyrics</div>
195
+ <div class="lyrics" id="lyrics"><p class="hint">—</p></div>
196
+
197
+ <div class="section-title">播放队列 Queue <span id="counts"></span></div>
198
+ <div class="queue"><div class="scroll" id="queue"></div></div>
199
+ <div id="dj-status"></div>
200
+
201
+ <div class="dj-status" id="dj-model">
202
+ <div class="curator-head">
203
+ <span>AI DJ 模型 / curator model</span>
204
+ <span id="dj-model-source" style="color: var(--muted)"></span>
205
+ </div>
206
+ <div class="row-inline">
207
+ <select id="dj-provider" title="provider route"></select>
208
+ <select id="dj-model-select" title="model"></select>
209
+ </div>
210
+ <div class="row-inline">
211
+ <input id="dj-model-custom" placeholder="自定义 model id / custom model id" style="display: none" />
212
+ </div>
213
+ <div class="row-inline">
214
+ <button id="dj-model-save" class="primary">保存 Save</button>
215
+ <button id="dj-model-test">测试 Test</button>
216
+ <button id="dj-model-clear" title="回退到 profile 配置 / revert to the profile patch">回退 Revert</button>
217
+ </div>
218
+ <div id="dj-model-status" style="color: var(--muted)"></div>
219
+ </div>
220
+ </section>
221
+ </main>
222
+ </div>
223
+
224
+ <dialog id="login">
225
+ <div style="font-weight: 650">网易云音乐登录 / Sign in</div>
226
+ <canvas id="qr" width="220" height="220"></canvas>
227
+ <div class="hint" id="qr-state">正在获取二维码… / fetching QR…</div>
228
+ <div class="row-actions">
229
+ <button id="qr-refresh">刷新 Refresh</button>
230
+ <button id="qr-close" class="primary">关闭 Close</button>
231
+ </div>
232
+ </dialog>
233
+
234
+ <div class="toast" id="toast"></div>
235
+
236
+ <script src="__BASE__/vendor/qrcode.js"></script>
237
+ <script>
238
+ // ------------------------------------------------------------------ setup
239
+ const BASE = '__BASE__';
240
+ const API = BASE + '/api';
241
+ const $ = (id) => document.getElementById(id);
242
+
243
+ /** Last state document from the host. */
244
+ let state = null;
245
+ let lyric = null;
246
+ let lyricLine = -1;
247
+ let tab = 'search';
248
+ let volumePostAt = 0;
249
+
250
+ const fmt = (ms) => {
251
+ const total = Math.max(Math.floor((ms || 0) / 1000), 0);
252
+ return Math.floor(total / 60) + ':' + String(total % 60).padStart(2, '0');
253
+ };
254
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
255
+
256
+ let toastTimer;
257
+ function toast(message) {
258
+ const el = $('toast');
259
+ el.textContent = message;
260
+ el.classList.add('on');
261
+ clearTimeout(toastTimer);
262
+ toastTimer = setTimeout(() => el.classList.remove('on'), 2600);
263
+ }
264
+
265
+ async function api(path, options) {
266
+ const response = await fetch(API + path, {
267
+ headers: { 'Content-Type': 'application/json' },
268
+ ...options,
269
+ ...(options && options.body ? { body: JSON.stringify(options.body) } : {}),
270
+ });
271
+ const text = await response.text();
272
+ let data;
273
+ try { data = text ? JSON.parse(text) : {}; } catch { data = { error: text.slice(0, 200) }; }
274
+ if (!response.ok) throw new Error(data.error || data.message || 'HTTP ' + response.status);
275
+ return data;
276
+ }
277
+
278
+ // ------------------------------------------------------------- transport
279
+ /**
280
+ * Who plays the audio.
281
+ *
282
+ * Normally the client plugin's engine in the shell document owns it: the
283
+ * layout renders only the ACTIVE `main` slot entry, so this document is
284
+ * unmounted the moment the user opens a session, and playback has to
285
+ * outlive that. The page is then a remote control over the host's state.
286
+ *
287
+ * The engine is not guaranteed to exist or to be usable, though: this
288
+ * page is re-read from disk on every plugin mount, while the browser
289
+ * bundle it pairs with is pinned to its own revision. When they disagree
290
+ * the engine declares itself inert. Rather than go silent, this page then
291
+ * owns the `<audio>` element itself — the older behaviour, which still
292
+ * plays, only without surviving a panel switch.
293
+ */
294
+ function shellEngine() {
295
+ try {
296
+ const candidate = window.parent?.__dshMusicEngine;
297
+ // Only an engine that declares it actually plays is authoritative;
298
+ // anything else (including an older bundle's engine) would leave the
299
+ // audio element unowned.
300
+ return candidate?.playback === true ? candidate : undefined;
301
+ } catch {
302
+ return undefined;
303
+ }
304
+ }
305
+
306
+ /** @type {object | undefined} */
307
+ let localTransport;
308
+
309
+ /** The active transport, creating the local fallback on first use. */
310
+ function transport() {
311
+ const engine = shellEngine();
312
+ if (engine) {
313
+ if (localTransport) {
314
+ localTransport.dispose();
315
+ localTransport = undefined;
316
+ }
317
+ return engine;
318
+ }
319
+ if (!localTransport) {
320
+ // Stand down any engine that cannot play, so exactly one transport
321
+ // owns the audio element and nothing plays twice.
322
+ try { window.parent?.__dshMusicEngine?.dispose?.(); } catch { /* ignore */ }
323
+ localTransport = createLocalTransport();
324
+ }
325
+ return localTransport;
326
+ }
327
+
328
+ /**
329
+ * The fallback transport: this page owns an `<audio>` element.
330
+ *
331
+ * It reconciles on `transportRev`, but enforces play/pause on every poll
332
+ * — a refused `play()` does not change the revision, so gating the retry
333
+ * would stop the music for good after the first browser refusal.
334
+ */
335
+ function createLocalTransport() {
336
+ const audio = document.createElement('audio');
337
+ audio.preload = 'auto';
338
+ audio.style.display = 'none';
339
+ document.body.appendChild(audio);
340
+
341
+ let applied = -1;
342
+ let busy = false;
343
+ let disposed = false;
344
+
345
+ function attemptPlay() {
346
+ if (busy || disposed) return;
347
+ busy = true;
348
+ const done = () => { busy = false; };
349
+ audio.play().then(done, done);
350
+ }
351
+
352
+ function reconcile(next) {
353
+ if (!next || next.transportRev === applied) return;
354
+ applied = next.transportRev;
355
+ if (next.pendingSeek !== null && next.pendingSeek !== undefined) {
356
+ try { audio.currentTime = next.pendingSeek / 1000; } catch { /* not seekable yet */ }
357
+ api('/seek-consumed', { method: 'POST', body: {} }).catch(() => {});
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Pick the resource to play. Every poll, not just on a transport change:
363
+ * the resource identity includes the streaming quality, so a quality
364
+ * switch has to be noticed without waiting for the revision to move.
365
+ * The level rides in the URL because the same track at two levels is two
366
+ * different files — range-requesting offsets across encodings would
367
+ * corrupt the stream.
368
+ */
369
+ function applySource(next) {
370
+ const track = next.current;
371
+ if (!track) {
372
+ if (audio.dataset.trackKey !== undefined) {
373
+ delete audio.dataset.trackKey;
374
+ delete audio.dataset.trackId;
375
+ audio.pause();
376
+ audio.removeAttribute('src');
377
+ audio.load();
378
+ }
379
+ return;
380
+ }
381
+ const level = next.audio?.preferred ?? 'exhigh';
382
+ const key = track.id + ':' + level;
383
+ if (audio.dataset.trackKey === key) return;
384
+
385
+ const sameTrack = audio.dataset.trackId === String(track.id);
386
+ const resumeAt = sameTrack ? audio.currentTime : 0;
387
+ audio.dataset.trackKey = key;
388
+ audio.dataset.trackId = String(track.id);
389
+ if (resumeAt > 0.5) {
390
+ audio.addEventListener('loadedmetadata', () => {
391
+ try { audio.currentTime = resumeAt; } catch { /* not seekable */ }
392
+ }, { once: true });
393
+ }
394
+ audio.src = BASE + '/stream/' + track.id + '?level=' + encodeURIComponent(level);
395
+ audio.load();
396
+ // Lyrics belong to the track, so only fetch them on a real change.
397
+ if (!sameTrack) loadLyrics(track.id);
398
+ }
399
+
400
+ function apply(next) {
401
+ if (disposed || !next) return;
402
+ reconcile(next);
403
+ applySource(next);
404
+ audio.volume = next.muted ? 0 : next.volume;
405
+ if (!next.current) return;
406
+ if (next.playing && audio.paused) attemptPlay();
407
+ else if (!next.playing && !audio.paused) audio.pause();
408
+ }
409
+
410
+ async function report(extra) {
411
+ if (!state?.current) return;
412
+ try {
413
+ await api('/report', {
414
+ method: 'POST',
415
+ body: {
416
+ trackId: state.current.id,
417
+ position: Math.round((audio.currentTime || 0) * 1000),
418
+ duration: Number.isFinite(audio.duration) ? Math.round(audio.duration * 1000) : undefined,
419
+ playing: !audio.paused,
420
+ ...extra,
421
+ },
422
+ });
423
+ } catch { /* the host will be re-read on the next poll */ }
424
+ }
425
+
426
+ audio.addEventListener('ended', () => report({ ended: true }));
427
+ audio.addEventListener('error', () => {
428
+ if (audio.dataset.trackId) report({ error: 'audio element error (track unavailable or network)' });
429
+ });
430
+ audio.addEventListener('timeupdate', () => { paintProgress(); paintLyrics(); });
431
+
432
+ return {
433
+ playback: true,
434
+ local: true,
435
+ apply,
436
+ sync() { apply(state); },
437
+ playNow() { attemptPlay(); },
438
+ /** Exact position: this transport owns the element. */
439
+ position: () => (audio.currentTime || 0) * 1000,
440
+ dispose() {
441
+ disposed = true;
442
+ try {
443
+ audio.pause();
444
+ audio.removeAttribute('src');
445
+ audio.remove();
446
+ } catch { /* the document may already be gone */ }
447
+ },
448
+ };
449
+ }
450
+
451
+ /** Push the latest host state into whichever transport is active. */
452
+ function applyTransport() {
453
+ const active = transport();
454
+ try {
455
+ active.apply?.(state);
456
+ } catch { /* a failing transport must not break rendering */ }
457
+ }
458
+
459
+ /** Ask the active transport to act now instead of on its next poll. */
460
+ function pokeEngine() {
461
+ try { transport().sync?.(); } catch { /* best effort across documents */ }
462
+ }
463
+
464
+ async function control(body) {
465
+ try {
466
+ state = await api('/control', { method: 'POST', body });
467
+ render();
468
+ applyTransport();
469
+ } catch (error) { toast(error.message); }
470
+ pokeEngine();
471
+ }
472
+
473
+ /**
474
+ * Playback position.
475
+ *
476
+ * A local element knows exactly; the shell engine reports about once a
477
+ * second, which is too coarse for a smooth bar, so the time since its
478
+ * report is added back.
479
+ */
480
+ function positionMs() {
481
+ const active = transport();
482
+ if (typeof active.position === 'function') return active.position();
483
+ const reported = state?.reported ?? {};
484
+ const base = Number(reported.position) || 0;
485
+ if (!state?.playing || !reported.playing) return base;
486
+ const at = Number(reported.at) || 0;
487
+ return at ? base + Math.max(Date.now() - at, 0) : base;
488
+ }
489
+
490
+ /** Duration the transport knows, falling back to the track's metadata. */
491
+ function durationMs() {
492
+ const reported = Number(state?.reported?.duration) || 0;
493
+ return reported > 0 ? reported : Number(state?.current?.duration) || 0;
494
+ }
495
+
496
+ /**
497
+ * The host wants playback, and the transport's own report for *this*
498
+ * track says it is not playing. In practice that means the browser
499
+ * refused to start audio until the page has been interacted with.
500
+ */
501
+ function autoplayBlocked() {
502
+ const reported = state?.reported;
503
+ return Boolean(
504
+ state?.playing &&
505
+ state?.current &&
506
+ reported?.playing === false &&
507
+ Number(reported.at) > 0 &&
508
+ reported.trackId === state.current.id,
509
+ );
510
+ }
511
+
512
+ /**
513
+ * Start audio from inside this click.
514
+ *
515
+ * The gesture grants sticky user activation to the document that owns the
516
+ * element — this one for the local transport, the shell document for the
517
+ * engine, as activation propagates up the same-origin frame tree.
518
+ * `playNow()` fires the attempt synchronously; the repeats cover the
519
+ * propagation order and any attempt already in flight.
520
+ */
521
+ function resumeWithGesture() {
522
+ const attempt = () => {
523
+ try { transport().playNow?.(); } catch { /* ignore */ }
524
+ pokeEngine();
525
+ };
526
+ attempt();
527
+ setTimeout(attempt, 200);
528
+ setTimeout(attempt, 800);
529
+ toast('正在恢复播放… / resuming…');
530
+ }
531
+
532
+ // ---------------------------------------------------------------- render
533
+ function render() {
534
+ if (!state) return;
535
+ const track = state.current;
536
+ $('cover').src = track?.picUrl || '';
537
+ $('cover').style.visibility = track?.picUrl ? 'visible' : 'hidden';
538
+ $('np-title').textContent = track ? track.name : '未播放 / nothing playing';
539
+ $('np-artists').textContent = track ? (track.artists || []).join(' / ') : '';
540
+ $('np-album').textContent = track ? track.album || '' : '';
541
+ $('play').textContent = state.playing ? '⏸' : '▶';
542
+ $('mode').textContent = { list: '列表', single: '单曲', shuffle: '随机' }[state.mode] || '列表';
543
+ $('counts').textContent = state.counts ? `(${state.counts.queued})` : '';
544
+ $('dj-toggle').classList.toggle('on', Boolean(state.dj?.enabled));
545
+ // The mood brief is persisted player setting, not part of the DJ status
546
+ // block, so it comes from `settings`.
547
+ if (document.activeElement !== $('dj-prompt')) $('dj-prompt').value = state.settings?.djPrompt ?? '';
548
+
549
+ // Account chip
550
+ const account = state.account;
551
+ $('account').innerHTML = account
552
+ ? `${account.avatar ? `<img src="${esc(account.avatar)}" alt="">` : ''}<span>${esc(account.nickname)}${account.vip ? ' · VIP' : ''}</span>`
553
+ : `<button id="signin">登录 Sign in</button>`;
554
+ const signin = $('signin');
555
+ if (signin) signin.onclick = openLogin;
556
+
557
+ // DJ status
558
+ const dj = state.dj || {};
559
+ $('dj-status').innerHTML = dj.enabled || dj.lastPlan
560
+ ? `<div class="dj-status">${dj.busy ? 'AI DJ 正在选曲… / planning…' : dj.error ? `AI DJ: ${esc(dj.error)}` : ''}${
561
+ dj.lastPlan
562
+ ? `<div><b>${esc(dj.lastPlan.source === 'model' ? 'AI DJ' : 'AI DJ (heuristic)')}</b>${dj.lastPlan.route ? ` <span style="color:var(--muted)">${esc(dj.lastPlan.route)}</span>` : ''} +${dj.lastPlan.added}: ${esc(dj.lastPlan.vibe || '')}</div><div style="color:var(--muted)">${esc((dj.lastPlan.names || []).slice(-3).join(' · '))}</div>`
563
+ : ''
564
+ }${dj.modelError && !dj.lastPlan?.route ? `<div style="color:var(--muted)">模型层不可用 / model tier unavailable: ${esc(dj.modelError)}</div>` : ''}${dj.enabled ? '<div style="color:var(--muted);margin-top:4px">持续补歌中 / keeping the queue stocked</div>' : ''}</div>`
565
+ : '';
566
+
567
+ if (autoplayBlocked()) {
568
+ if (!$('gesture')) {
569
+ const el = document.createElement('div');
570
+ el.id = 'gesture';
571
+ el.className = 'need-gesture';
572
+ el.innerHTML = '浏览器需要你先与页面交互一次才会播放声音 / Chromium needs one interaction with this window before it will play audio — <button id="gesture-go" class="primary">点击播放 / Play</button> <span style="color:var(--muted)">在窗口任意处点击也可以 / clicking anywhere works too</span>';
573
+ $('dj-status').before(el);
574
+ el.querySelector('#gesture-go').onclick = resumeWithGesture;
575
+ }
576
+ } else {
577
+ $('gesture')?.remove();
578
+ }
579
+
580
+ // The engine owns the real volume; mirror it unless the user is
581
+ // mid-drag, when overwriting the thumb would fight the pointer.
582
+ if (document.activeElement !== $('volume')) $('volume').value = state.volume;
583
+ $('mute').textContent = state.muted || state.volume === 0 ? '🔇' : '🔊';
584
+
585
+ // Same for quality: the host is authoritative, the select mirrors it.
586
+ const preferredLevel = state.audio?.preferred;
587
+ if (
588
+ preferredLevel &&
589
+ document.activeElement !== $('quality') &&
590
+ qualityLevels.some((entry) => entry.id === preferredLevel)
591
+ ) {
592
+ $('quality').value = preferredLevel;
593
+ }
594
+ paintQualityInfo();
595
+
596
+ renderQueue();
597
+ paintProgress();
598
+ }
599
+
600
+ function renderQueue() {
601
+ if (!state) return;
602
+ const queue = state.queue || [];
603
+ if (queue.length === 0) {
604
+ $('queue').innerHTML = '<div class="empty">队列为空,搜索或打开 AI DJ / queue empty</div>';
605
+ return;
606
+ }
607
+ $('queue').innerHTML = queue
608
+ .map((track, index) => {
609
+ const playing = index === state.index;
610
+ return `<div class="row ${playing ? 'playing' : ''}" data-jump="${index}">
611
+ <span class="idx">${playing ? '▶' : index + 1}</span>
612
+ <img src="${esc(track.picUrl || '')}" alt="" loading="lazy">
613
+ <span class="meta"><span class="name">${esc(track.name)}</span><span class="sub">${esc((track.artists || []).join(' / '))}</span></span>
614
+ ${track.vip ? '<span class="tag">VIP</span>' : ''}
615
+ <span class="dur">${fmt(track.duration)}</span>
616
+ <span class="acts"><button data-remove="${index}" title="移除">✕</button></span>
617
+ </div>`;
618
+ })
619
+ .join('');
620
+ }
621
+
622
+ function paintProgress() {
623
+ if (!state || !state.current) return;
624
+ const position = positionMs();
625
+ const duration = durationMs();
626
+ if (document.activeElement !== $('seek')) {
627
+ $('seek').value = duration > 0 ? String(Math.round((position / duration) * 1000)) : '0';
628
+ }
629
+ $('t-cur').textContent = fmt(position);
630
+ $('t-dur').textContent = fmt(duration);
631
+ }
632
+
633
+ // ---------------------------------------------------------------- lyrics
634
+ async function loadLyrics(id) {
635
+ lyric = null;
636
+ $('lyrics').innerHTML = '<p class="hint">加载中… / loading…</p>';
637
+ try {
638
+ const data = await api('/lyric/' + id);
639
+ if (data.noLyric || !data.lrc) {
640
+ $('lyrics').innerHTML = '<p class="hint">纯音乐,无歌词 / instrumental</p>';
641
+ return;
642
+ }
643
+ const lines = [];
644
+ for (const raw of data.lrc.split('\n')) {
645
+ const matches = [...raw.matchAll(/\[(\d+):(\d+(?:[.:]\d+)?)\]/g)];
646
+ const text = raw.replace(/\[[^\]]*\]/g, '').trim();
647
+ if (matches.length === 0) continue;
648
+ for (const match of matches) {
649
+ const seconds = Number(match[1]) * 60 + Number(String(match[2]).replace(':', '.'));
650
+ lines.push({ at: seconds * 1000, text });
651
+ }
652
+ }
653
+ lines.sort((a, b) => a.at - b.at);
654
+ lyric = lines;
655
+ $('lyrics').innerHTML = lines.map((line, index) => `<p data-line="${index}">${esc(line.text || '♪')}</p>`).join('');
656
+ } catch (error) {
657
+ $('lyrics').innerHTML = `<p class="hint">${esc(error.message)}</p>`;
658
+ }
659
+ }
660
+
661
+ function paintLyrics() {
662
+ if (!lyric) return;
663
+ const at = positionMs();
664
+ let active = -1;
665
+ for (let index = 0; index < lyric.length; index++) {
666
+ if (lyric[index].at <= at) active = index; else break;
667
+ }
668
+ // `timeupdate` fires ~4x/s; only touch the DOM and scroll when the
669
+ // highlighted line actually changes, or smooth scrolling thrashes.
670
+ if (active === lyricLine) return;
671
+ lyricLine = active;
672
+ for (const el of $('lyrics').querySelectorAll('p')) el.classList.toggle('on', Number(el.dataset.line) === active);
673
+ const current = $('lyrics').querySelector('p.on');
674
+ if (current) current.scrollIntoView({ block: 'center', behavior: 'smooth' });
675
+ }
676
+
677
+ // --------------------------------------------------------------- browser
678
+ function trackRow(track, index, context) {
679
+ return `<div class="row" data-play="${track.id}">
680
+ <span class="idx">${index + 1}</span>
681
+ <img src="${esc(track.picUrl || '')}" alt="" loading="lazy">
682
+ <span class="meta"><span class="name">${esc(track.name)}</span><span class="sub">${esc((track.artists || []).join(' / '))}${track.album ? ' · ' + esc(track.album) : ''}</span></span>
683
+ ${track.vip ? '<span class="tag">VIP</span>' : ''}
684
+ <span class="dur">${fmt(track.duration)}</span>
685
+ <span class="acts"><button data-queue="${track.id}" title="加入队列">+</button></span>
686
+ </div>`;
687
+ }
688
+
689
+ async function renderBrowser() {
690
+ const el = $('browser');
691
+ if (tab === 'search') {
692
+ if (!el.dataset.done) el.innerHTML = '<div class="empty">搜索歌曲开始播放 / search to begin</div>';
693
+ return;
694
+ }
695
+ el.dataset.done = '';
696
+ el.innerHTML = '<div class="empty">加载中… / loading…</div>';
697
+ try {
698
+ if (tab === 'charts') {
699
+ const [charts, forYou] = await Promise.all([api('/charts'), api('/playlists')]);
700
+ el.innerHTML =
701
+ '<div class="section-title" style="padding-left:8px">官方榜单 Charts</div><div class="card-grid">' +
702
+ charts.map((chart) => `<div class="card" data-chart="${chart.id}"><img src="${esc(chart.cover || '')}" alt="" loading="lazy"><div class="name">${esc(chart.name)}</div><div class="sub">${esc(chart.updateFrequency || '')}</div></div>`).join('') +
703
+ '</div><div class="section-title" style="padding-left:8px">推荐歌单 Playlists</div><div class="card-grid">' +
704
+ forYou.map((list) => `<div class="card" data-list="${list.id}"><img src="${esc(list.cover || '')}" alt="" loading="lazy"><div class="name">${esc(list.name)}</div><div class="sub">${list.trackCount} 首</div></div>`).join('') +
705
+ '</div>';
706
+ } else {
707
+ const fresh = await api('/new');
708
+ el.innerHTML = '<div class="section-title" style="padding-left:8px">新歌推荐 New songs</div>' + fresh.map((track, index) => trackRow(track, index)).join('');
709
+ }
710
+ } catch (error) {
711
+ el.innerHTML = `<div class="empty">${esc(error.message)}</div>`;
712
+ }
713
+ }
714
+
715
+ async function doSearch() {
716
+ const query = $('q').value.trim();
717
+ if (!query) return;
718
+ tab = 'search';
719
+ document.querySelectorAll('.tabs button').forEach((b) => b.classList.toggle('on', b.dataset.tab === 'search'));
720
+ $('browser').innerHTML = '<div class="empty">搜索中… / searching…</div>';
721
+ try {
722
+ const data = await api('/search?q=' + encodeURIComponent(query));
723
+ $('browser').innerHTML = data.tracks.length
724
+ ? `<div class="section-title" style="padding-left:8px">${data.total} 个结果</div>` + data.tracks.map((track, index) => trackRow(track, index)).join('')
725
+ : '<div class="empty">没有结果 / no results</div>';
726
+ } catch (error) {
727
+ $('browser').innerHTML = `<div class="empty">${esc(error.message)}</div>`;
728
+ }
729
+ }
730
+
731
+ async function playTracks(tracks, startIndex) {
732
+ state = await api('/play', { method: 'POST', body: { tracks, startIndex: startIndex || 0 } });
733
+ render();
734
+ pokeEngine();
735
+ }
736
+
737
+ // -------------------------------------------------------------- QR login
738
+ function drawQr(text) {
739
+ const canvas = $('qr');
740
+ const context = canvas.getContext('2d');
741
+ context.fillStyle = '#fff';
742
+ context.fillRect(0, 0, canvas.width, canvas.height);
743
+ if (typeof qrcode !== 'function') {
744
+ context.fillStyle = '#000';
745
+ context.font = '12px sans-serif';
746
+ context.fillText('QR library unavailable', 12, 24);
747
+ return;
748
+ }
749
+ const qr = qrcode(0, 'M');
750
+ qr.addData(text);
751
+ qr.make();
752
+ const count = qr.getModuleCount();
753
+ const quiet = 2;
754
+ const size = Math.floor(canvas.width / (count + quiet * 2));
755
+ const offset = Math.floor((canvas.width - size * count) / 2);
756
+ context.fillStyle = '#000';
757
+ for (let row = 0; row < count; row++) {
758
+ for (let col = 0; col < count; col++) {
759
+ if (qr.isDark(row, col)) context.fillRect(offset + col * size, offset + row * size, size, size);
760
+ }
761
+ }
762
+ }
763
+
764
+ let qrTimer;
765
+ async function openLogin() {
766
+ const dialog = $('login');
767
+ dialog.showModal();
768
+ $('qr-state').textContent = '正在获取二维码… / fetching QR…';
769
+ try {
770
+ const data = await api('/login/qr', { method: 'POST', body: {} });
771
+ drawQr(data.loginUrl);
772
+ $('qr-state').textContent = '用网易云音乐 App 扫码 / scan with the NetEase app';
773
+ } catch (error) {
774
+ $('qr-state').textContent = error.message;
775
+ }
776
+ clearInterval(qrTimer);
777
+ qrTimer = setInterval(pollLogin, 2000);
778
+ }
779
+
780
+ async function pollLogin() {
781
+ try {
782
+ const data = await api('/login/poll', { method: 'POST', body: {} });
783
+ if (data.state === 'success') {
784
+ clearInterval(qrTimer);
785
+ $('login').close();
786
+ toast('登录成功 / signed in');
787
+ await refresh();
788
+ return;
789
+ }
790
+ if (data.loginUrl) drawQr(data.loginUrl);
791
+ $('qr-state').textContent = data.message || data.state;
792
+ } catch (error) {
793
+ $('qr-state').textContent = error.message;
794
+ }
795
+ }
796
+
797
+ $('qr-refresh').onclick = openLogin;
798
+ $('qr-close').onclick = () => { clearInterval(qrTimer); $('login').close(); };
799
+ $('login').addEventListener('close', () => clearInterval(qrTimer));
800
+
801
+ // ---------------------------------------------------------- curator model
802
+ /**
803
+ * The curator picker.
804
+ *
805
+ * Routes and their catalogued models come from the host's LLM service.
806
+ * The catalogue is advisory — core resolution accepts unlisted ids — so
807
+ * "其他… / Other…" reveals a text field for any id the route serves. A
808
+ * saved choice persists in the session document and takes precedence over
809
+ * the profile patch, which "回退 Revert" falls back to.
810
+ */
811
+ let curatorRoutes = [];
812
+ let curatorSelected = { provider: null, model: null };
813
+ let curatorConfigured = { provider: null, model: null };
814
+ const CUSTOM = '__custom__';
815
+ const CURATOR_CONTROLS = [
816
+ 'dj-provider',
817
+ 'dj-model-select',
818
+ 'dj-model-custom',
819
+ 'dj-model-save',
820
+ 'dj-model-test',
821
+ 'dj-model-clear',
822
+ ];
823
+
824
+ /** Enable or disable every picker control at once. */
825
+ function setCuratorEnabled(enabled) {
826
+ for (const id of CURATOR_CONTROLS) {
827
+ const node = $(id);
828
+ if (node) node.disabled = !enabled;
829
+ }
830
+ }
831
+
832
+ function renderModelOptions() {
833
+ const provider = $('dj-provider').value;
834
+ const route = curatorRoutes.find((entry) => entry.provider === provider);
835
+ const models = route?.models ?? [];
836
+ const select = $('dj-model-select');
837
+ select.innerHTML =
838
+ models.map((model) => `<option value="${esc(model.id)}">${esc(model.name || model.id)}</option>`).join('') +
839
+ `<option value="${CUSTOM}">其他… / Other…</option>`;
840
+
841
+ const pinned = curatorSelected.provider === provider ? curatorSelected.model : null;
842
+ const custom = $('dj-model-custom');
843
+ if (pinned && models.some((model) => model.id === pinned)) {
844
+ select.value = pinned;
845
+ custom.style.display = 'none';
846
+ } else if (pinned) {
847
+ // Pinned to an id outside the catalogue; keep it rather than lose it.
848
+ select.value = CUSTOM;
849
+ custom.style.display = '';
850
+ custom.value = pinned;
851
+ } else {
852
+ custom.style.display = 'none';
853
+ }
854
+ if (route?.error) $('dj-model-status').textContent = route.error;
855
+ }
856
+
857
+ async function loadCurator() {
858
+ try {
859
+ const data = await api('/dj/models');
860
+ setCuratorEnabled(true);
861
+ curatorRoutes = data.routes ?? [];
862
+ curatorSelected = data.selected ?? { provider: null, model: null };
863
+ curatorConfigured = data.configured ?? { provider: null, model: null };
864
+
865
+ const providers = curatorRoutes.map((route) => route.provider);
866
+ // Keep a value the catalogue does not list, so a working pin is not
867
+ // silently replaced by whatever the adapter happens to offer.
868
+ for (const value of [curatorSelected.provider, curatorConfigured.provider]) {
869
+ if (value && !providers.includes(value)) providers.push(value);
870
+ }
871
+ const select = $('dj-provider');
872
+ select.innerHTML = providers.length
873
+ ? providers.map((provider) => `<option value="${esc(provider)}">${esc(provider)}</option>`).join('')
874
+ : '<option value="">(无 provider / none)</option>';
875
+ select.value = curatorSelected.provider ?? curatorConfigured.provider ?? providers[0] ?? '';
876
+ renderModelOptions();
877
+
878
+ $('dj-model-source').textContent =
879
+ { panel: '面板 / panel', config: '配置 / profile', discovered: '自动 / auto' }[data.source] ?? data.source ?? '';
880
+ $('dj-model-status').textContent = data.error ?? '';
881
+ } catch (error) {
882
+ // A 404 here means this page is newer than the host module: the page
883
+ // is re-read from disk on every plugin mount, while Node keeps
884
+ // serving the cached module. Only a process restart reunites them, so
885
+ // say that instead of showing a bare "unknown endpoint".
886
+ if (/unknown endpoint|\b404\b/.test(error.message)) {
887
+ setCuratorEnabled(false);
888
+ $('dj-model-status').textContent =
889
+ '宿主模块早于本功能:请完全退出并重新启动 Harness(关闭窗口不够,它会留在托盘里)/ ' +
890
+ 'the host module predates this feature — fully quit and relaunch the harness ' +
891
+ '(closing the window is not enough; it stays running in the tray)';
892
+ } else {
893
+ $('dj-model-status').textContent = error.message;
894
+ }
895
+ }
896
+ }
897
+
898
+ /** The model the form currently points at. */
899
+ function chosenModel() {
900
+ return $('dj-model-select').value === CUSTOM
901
+ ? $('dj-model-custom').value.trim()
902
+ : $('dj-model-select').value;
903
+ }
904
+
905
+ async function saveCurator(provider, model, message) {
906
+ try {
907
+ state = await api('/dj', { method: 'POST', body: { provider, model } });
908
+ render();
909
+ await loadCurator();
910
+ toast(message);
911
+ } catch (error) {
912
+ toast(error.message);
913
+ }
914
+ }
915
+
916
+ $('dj-provider').onchange = renderModelOptions;
917
+ $('dj-model-select').onchange = () => {
918
+ $('dj-model-custom').style.display = $('dj-model-select').value === CUSTOM ? '' : 'none';
919
+ };
920
+ $('dj-model-save').onclick = () => {
921
+ const provider = $('dj-provider').value;
922
+ const model = chosenModel();
923
+ if (!provider || !model) {
924
+ toast('请先选择 provider 与 model / pick a provider and a model');
925
+ return;
926
+ }
927
+ void saveCurator(provider, model, `已保存 / saved ${provider}/${model}`);
928
+ };
929
+ $('dj-model-clear').onclick = () =>
930
+ void saveCurator('', '', '已回退到 profile 配置 / reverted to the profile config');
931
+ $('dj-model-test').onclick = async () => {
932
+ $('dj-model-status').textContent = '测试中… / testing…';
933
+ try {
934
+ const result = await api('/dj/test', { method: 'POST', body: {} });
935
+ if (result.source === 'model') {
936
+ $('dj-model-status').textContent =
937
+ `✓ ${result.route} — ${(result.picked ?? []).join(' · ')}${result.vibe ? ` (${result.vibe})` : ''}`;
938
+ } else {
939
+ $('dj-model-status').textContent =
940
+ `✗ ${result.modelError ?? result.note ?? 'model tier unavailable'} — 已用启发式 / heuristics`;
941
+ }
942
+ } catch (error) {
943
+ $('dj-model-status').textContent = error.message;
944
+ }
945
+ };
946
+
947
+ // ------------------------------------------------------ streaming quality
948
+ /**
949
+ * The quality picker.
950
+ *
951
+ * NetEase refuses a level per track and per entitlement, and the host
952
+ * walks down a ladder when it does, so the caption reports what was
953
+ * *actually* served — including when that is lower than what was asked
954
+ * for. A richer level means a much larger file: Hi-Res ran 51–63 MB per
955
+ * track against 320 kbps MP3 at ~10 MB.
956
+ */
957
+ let qualityLevels = [];
958
+
959
+ /** Caption for what the last stream actually served. */
960
+ function paintQualityInfo() {
961
+ const last = state?.audio?.last;
962
+ const preferred = state?.audio?.preferred;
963
+ if (!last || (preferred && last.requested !== preferred && last.trackId !== state?.current?.id)) {
964
+ $('quality-info').textContent = '';
965
+ return;
966
+ }
967
+ const kbps = last.br ? ` · ${Math.round(last.br / 1000)} kbps` : '';
968
+ $('quality-info').textContent =
969
+ `▶ ${String(last.type ?? '').toUpperCase()}${kbps}` + (last.downgraded ? ` (${last.served}, 已降级/downgraded)` : '');
970
+ }
971
+
972
+ async function loadQuality() {
973
+ try {
974
+ const data = await api('/quality');
975
+ qualityLevels = data.levels ?? [];
976
+ $('quality').innerHTML = qualityLevels
977
+ .map((entry) => `<option value="${esc(entry.id)}">${esc(entry.label || entry.id)}</option>`)
978
+ .join('');
979
+ $('quality').value = data.preferred ?? 'exhigh';
980
+ paintQualityInfo();
981
+ } catch (error) {
982
+ // A host without this endpoint is older than this page; say so once.
983
+ $('quality-info').textContent = /unknown endpoint|\b404\b/.test(error.message)
984
+ ? '宿主模块早于本功能 / host module predates this feature'
985
+ : error.message;
986
+ }
987
+ }
988
+
989
+ $('quality').onchange = async (event) => {
990
+ try {
991
+ state = await api('/quality', { method: 'POST', body: { level: event.target.value } });
992
+ render();
993
+ applyTransport();
994
+ pokeEngine();
995
+ paintQualityInfo();
996
+ toast('音质已设为 / quality set to ' + event.target.value);
997
+ } catch (error) {
998
+ toast(error.message);
999
+ }
1000
+ };
1001
+
1002
+ // ------------------------------------------------------------------ wiring
1003
+ $('play').onclick = () => control({ action: 'toggle' });
1004
+ $('next').onclick = () => control({ action: 'next' });
1005
+ $('prev').onclick = () => control({ action: 'previous' });
1006
+ $('mode').onclick = () => control({ action: 'mode', value: { list: 'shuffle', shuffle: 'single', single: 'list' }[state?.mode || 'list'] });
1007
+ $('mute').onclick = () => control({ action: 'mute', value: !state?.muted });
1008
+ $('volume').oninput = (event) => {
1009
+ const value = Number(event.target.value);
1010
+ // The engine owns the real gain; mirror it locally and throttle the
1011
+ // round-trip while the pointer is still down.
1012
+ if (state) state.volume = value;
1013
+ $('mute').textContent = value === 0 ? '🔇' : '🔊';
1014
+ if (Date.now() - volumePostAt > 150) {
1015
+ volumePostAt = Date.now();
1016
+ control({ action: 'volume', value });
1017
+ }
1018
+ };
1019
+ $('volume').onchange = (event) => control({ action: 'volume', value: Number(event.target.value) });
1020
+ $('seek').onchange = (event) => {
1021
+ control({ action: 'seek', value: Math.round((Number(event.target.value) / 1000) * durationMs()) });
1022
+ };
1023
+ $('like').onclick = () => state?.current && api('/feedback', { method: 'POST', body: { kind: 'likes', trackId: state.current.id } }).then(() => toast('已喜欢 / liked'));
1024
+ $('dislike').onclick = () => state?.current && api('/feedback', { method: 'POST', body: { kind: 'dislikes', trackId: state.current.id } }).then(() => { toast('不再推荐 / disliked'); control({ action: 'next' }); });
1025
+ $('go').onclick = doSearch;
1026
+ $('q').onkeydown = (event) => { if (event.key === 'Enter') doSearch(); };
1027
+
1028
+ $('dj-toggle').onclick = async () => {
1029
+ try {
1030
+ const data = await api('/dj', { method: 'POST', body: { enabled: !state?.dj?.enabled, prompt: $('dj-prompt').value } });
1031
+ state = data;
1032
+ render();
1033
+ toast(state.dj?.enabled ? 'AI DJ 已开启 / AI DJ on' : 'AI DJ 已关闭 / AI DJ off');
1034
+ } catch (error) { toast(error.message); }
1035
+ };
1036
+ $('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));
1037
+
1038
+ document.querySelectorAll('.tabs button').forEach((button) => {
1039
+ button.onclick = () => {
1040
+ tab = button.dataset.tab;
1041
+ document.querySelectorAll('.tabs button').forEach((b) => b.classList.toggle('on', b === button));
1042
+ $('searchbar').style.display = tab === 'search' ? 'flex' : 'none';
1043
+ $('browser').dataset.done = '';
1044
+ renderBrowser();
1045
+ };
1046
+ });
1047
+
1048
+ $('browser').onclick = async (event) => {
1049
+ const playId = event.target.closest('[data-play]')?.dataset.play;
1050
+ const queueId = event.target.closest('[data-queue]')?.dataset.queue;
1051
+ const chartId = event.target.closest('[data-chart]')?.dataset.chart;
1052
+ const listId = event.target.closest('[data-list]')?.dataset.list;
1053
+ try {
1054
+ if (playId) {
1055
+ const data = await api('/track/' + playId);
1056
+ await playTracks([data.track], 0);
1057
+ } else if (queueId) {
1058
+ const data = await api('/track/' + queueId);
1059
+ state = await api('/queue', { method: 'POST', body: { action: 'append', tracks: [data.track] } });
1060
+ render(); pokeEngine(); toast('已加入队列 / queued');
1061
+ } else if (chartId || listId) {
1062
+ const data = await api('/playlist/' + (chartId || listId));
1063
+ await playTracks(data.tracks, 0);
1064
+ toast('播放歌单 ' + data.name);
1065
+ }
1066
+ } catch (error) { toast(error.message); }
1067
+ };
1068
+
1069
+ $('queue').onclick = async (event) => {
1070
+ const jump = event.target.closest('[data-jump]')?.dataset.jump;
1071
+ const remove = event.target.closest('[data-remove]')?.dataset.remove;
1072
+ try {
1073
+ if (remove !== undefined) {
1074
+ state = await api('/queue', { method: 'POST', body: { action: 'remove', index: Number(remove) } });
1075
+ } else if (jump !== undefined) {
1076
+ state = await api('/queue', { method: 'POST', body: { action: 'jump', index: Number(jump) } });
1077
+ } else return;
1078
+ render();
1079
+ pokeEngine();
1080
+ } catch (error) { toast(error.message); }
1081
+ };
1082
+
1083
+ // ------------------------------------------------------------------ boot
1084
+ async function refresh() {
1085
+ try {
1086
+ state = await api('/state');
1087
+ render();
1088
+ applyTransport();
1089
+ } catch (error) {
1090
+ $('np-title').textContent = '连接失败 / cannot reach the host: ' + error.message;
1091
+ }
1092
+ }
1093
+
1094
+ refresh();
1095
+ setInterval(refresh, 1500);
1096
+ void loadCurator();
1097
+ void loadQuality();
1098
+ // Progress and lyric highlighting interpolate locally between the
1099
+ // engine's reports, so they need their own repaint clock now that the
1100
+ // audio element lives in the shell document.
1101
+ setInterval(() => { paintProgress(); paintLyrics(); }, 250);
1102
+ window.addEventListener('beforeunload', () => { clearInterval(qrTimer); });
1103
+ </script>
1104
+ </body>
1105
+ </html>