-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremote.html
More file actions
457 lines (439 loc) · 27.8 KB
/
Copy pathremote.html
File metadata and controls
457 lines (439 loc) · 27.8 KB
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
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1">
<title>DRAAI remote</title>
<style>
:root{
--ac:94 234 212; --ac2:45 212 191;
--tx:#f4f4f7; --dim:#9a9aa6; --dim2:#63636f;
--line:rgba(255,255,255,.075); --line2:rgba(255,255,255,.15);
--panel:rgba(255,255,255,.03); --panel2:rgba(255,255,255,.06);
--page:#08080b; --elev:rgb(11 11 14 / .72); --elev2:rgb(15 15 19 / .97);
--track-empty:rgba(255,255,255,.14); --play-ink:#08080b;
color-scheme:dark;
font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%}
body{background:var(--page);color:var(--tx);-webkit-font-smoothing:antialiased;letter-spacing:-.011em;
display:flex;flex-direction:column;height:100dvh;overflow:hidden;position:relative}
body::before{content:"";position:fixed;inset:0;z-index:0;pointer-events:none;
background:radial-gradient(60vw 46vh at 82% -8%,rgb(var(--ac) / .10),transparent 70%),
radial-gradient(70vw 40vh at 8% 108%,rgb(var(--ac2) / .08),transparent 70%)}
button{font:inherit;color:inherit;background:none;border:none;cursor:pointer}
input{font:inherit;color:inherit}
svg{display:block}
.ic{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex:none}
.ic.fill{fill:currentColor;stroke:none}
.mono{font-variant-numeric:tabular-nums;letter-spacing:0}
header,main,.dock,.tabs{position:relative;z-index:1}
/* header */
header{display:flex;align-items:center;gap:10px;
padding:calc(env(safe-area-inset-top) + 12px) 14px 12px;border-bottom:1px solid var(--line)}
.mark{width:30px;height:30px;border-radius:9px;flex:none;position:relative;
background:conic-gradient(from 210deg,rgb(var(--ac)),rgb(var(--ac2)),rgb(var(--ac)));
box-shadow:0 0 20px rgb(var(--ac) / .45),inset 0 0 0 1px rgba(255,255,255,.25)}
.mark::after{content:"";position:absolute;inset:8px;border-radius:4px;background:var(--page)}
.roomchip{flex:1;min-width:0;display:flex;align-items:center;gap:8px;
background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:8px 10px}
.roomchip .spk{width:16px;height:16px;color:rgb(var(--ac))}
.roomchip .cv{width:15px;height:15px;color:var(--dim2)}
.roomchip select{flex:1;min-width:0;background:transparent;border:0;color:var(--tx);font:inherit;
font-weight:560;appearance:none;-webkit-appearance:none;text-overflow:ellipsis}
.vol{display:flex;align-items:center;gap:8px;width:104px;flex:none}
.vol .ic{width:18px;height:18px;color:var(--dim)}
/* sliders (seek + volume) */
.slider{-webkit-appearance:none;appearance:none;height:4px;border-radius:4px;width:100%;
background:linear-gradient(90deg,rgb(var(--ac)) var(--v,50%),var(--track-empty) var(--v,50%));cursor:pointer}
.slider::-webkit-slider-thumb{-webkit-appearance:none;width:14px;height:14px;border-radius:50%;background:#fff;box-shadow:0 0 8px rgb(var(--ac))}
.slider::-moz-range-thumb{width:14px;height:14px;border:none;border-radius:50%;background:#fff;box-shadow:0 0 8px rgb(var(--ac))}
main{flex:1;min-height:0;overflow-y:auto;-webkit-overflow-scrolling:touch;padding:6px 12px 12px;display:flex;flex-direction:column}
/* now playing */
.now{display:flex;flex-direction:column;align-items:center;gap:20px;padding:22px 8px 8px;margin:auto 0}
.now .cover{width:min(72vw,320px);aspect-ratio:1;border-radius:20px;background:#15151b;overflow:hidden;
box-shadow:0 24px 60px rgba(0,0,0,.55),inset 0 0 0 1px rgba(255,255,255,.06)}
.now .cover img{width:100%;height:100%;object-fit:cover;display:none}
.now .ninfo{text-align:center;max-width:100%;padding:0 8px}
.now .ninfo b{font-size:20px;font-weight:600;line-height:1.25;display:block;
white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.now .ninfo small{font-size:14px;color:var(--dim);display:block;margin-top:3px;
white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.seekwrap{display:flex;align-items:center;gap:12px;width:100%;max-width:360px}
.seekwrap .t{font-size:11.5px;color:var(--dim);width:42px;flex:none}
.seekwrap .t.r{text-align:right}
/* rows (queue + browse) */
.rows{display:flex;flex-direction:column}
.row{display:flex;align-items:center;gap:12px;padding:8px 8px;border-radius:11px;
border-bottom:1px solid var(--line);position:relative}
.row:last-child{border-bottom:0}
.row.playing{background:linear-gradient(90deg,rgb(var(--ac) / .15),rgb(var(--ac) / .02) 62%);
box-shadow:inset 3px 0 0 rgb(var(--ac));border-bottom-color:transparent}
.rmain{flex:1;min-width:0;display:flex;align-items:center;gap:12px;cursor:pointer}
.rthumb{width:46px;height:46px;border-radius:9px;overflow:hidden;position:relative;flex:none;
background:#15151b;box-shadow:inset 0 0 0 1px rgba(255,255,255,.07);display:grid;place-items:center}
.rthumb img{width:100%;height:100%;object-fit:cover}
.rthumb .idx{font-size:12.5px;color:var(--dim2);font-variant-numeric:tabular-nums}
.tt{min-width:0;flex:1}
.tt b{font-size:14px;font-weight:520;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.row.playing .tt b{color:rgb(var(--ac))}
.tt small{font-size:12px;color:var(--dim);display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.qacts{display:flex;gap:2px;flex:none}
.iconbtn{width:38px;height:38px;border-radius:9px;display:grid;place-items:center;color:var(--dim);border:1px solid transparent;transition:.12s}
.iconbtn:active{color:var(--tx);background:var(--panel2)}
.iconbtn .ic{width:18px;height:18px}
.iconbtn:disabled{opacity:.32}
/* search */
.searchbar{display:flex;align-items:center;gap:10px;background:var(--panel);border:1px solid var(--line);
border-radius:13px;padding:10px 13px;margin:2px 0 10px}
.searchbar .ic{width:18px;height:18px;color:var(--dim2)}
.searchbar input{flex:1;min-width:0;background:transparent;border:0;color:var(--tx);font:inherit}
.searchbar input::placeholder{color:var(--dim2)}
/* empty states */
.empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;
padding:40px 24px;margin:auto 0;color:var(--dim2);text-align:center;line-height:1.5}
.empty .ic{width:34px;height:34px}
/* transport dock */
.dock{display:flex;align-items:center;justify-content:center;gap:14px;
margin:0 12px 6px;padding:9px 16px;border:1px solid var(--line);background:var(--elev);
backdrop-filter:blur(30px);-webkit-backdrop-filter:blur(30px);border-radius:18px;box-shadow:0 16px 40px rgba(0,0,0,.42)}
.cbtn{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;color:var(--dim);transition:.12s}
.cbtn:active{color:var(--tx)}
.cbtn .ic{width:22px;height:22px}
.cbtn:disabled{opacity:.3}
.play{width:56px;height:56px;border-radius:50%;background:var(--tx);color:var(--play-ink);
display:grid;place-items:center;box-shadow:0 6px 22px rgba(0,0,0,.45);transition:transform .15s}
.play:active{transform:scale(.94)}
.play .ic{width:26px;height:26px;fill:currentColor;stroke:none}
.play:disabled{opacity:.4}
/* bottom tabs */
.tabs{display:flex;border-top:1px solid var(--line);background:var(--elev);
backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);padding-bottom:env(safe-area-inset-bottom)}
.tabs button{flex:1;display:flex;flex-direction:column;align-items:center;gap:5px;padding:10px 0 12px;
color:var(--dim2);font-size:11px;font-weight:600;letter-spacing:.02em;position:relative}
.tabs button .ic{width:20px;height:20px}
.tabs button[aria-selected=true]{color:rgb(var(--ac))}
.tabs button[aria-selected=true]::before{content:"";position:absolute;top:0;left:50%;transform:translateX(-50%);
width:26px;height:2px;border-radius:0 0 2px 2px;background:rgb(var(--ac))}
/* toast + offline banner */
.toast{position:fixed;left:50%;bottom:154px;transform:translateX(-50%) translateY(6px);
background:var(--elev2);color:var(--tx);border:1px solid var(--line2);padding:10px 16px;border-radius:12px;
font-size:13px;opacity:0;transition:.2s;pointer-events:none;max-width:80%;box-shadow:0 12px 30px rgba(0,0,0,.45);z-index:30}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
.banner{position:absolute;top:0;left:0;right:0;z-index:20;background:rgb(58 17 19 / .96);color:#ffd9d9;
padding:calc(env(safe-area-inset-top) + 7px) 14px 7px;font-size:12.5px;text-align:center;display:none}
.banner.show{display:block}
</style>
</head><body data-remote="1">
<div class="banner" id="banner">Can't reach DRAAI — same Wi-Fi?</div>
<header>
<div class="mark" aria-hidden="true"></div>
<label class="roomchip">
<svg class="ic spk" viewBox="0 0 24 24"><rect x="6" y="3" width="12" height="18" rx="2.4"/><circle cx="12" cy="14" r="3.2"/><circle cx="12" cy="7" r="1"/></svg>
<select id="roomSel" aria-label="Room"></select>
<svg class="ic cv" viewBox="0 0 24 24"><path d="M6 9l6 6 6-6"/></svg>
</label>
<div class="vol">
<svg class="ic" viewBox="0 0 24 24"><path d="M11 5 6 9H2v6h4l5 4zM15.5 8.5a5 5 0 0 1 0 7M19 5a9 9 0 0 1 0 14"/></svg>
<input type="range" id="vol" class="slider" min="0" max="100" value="30">
</div>
</header>
<main id="view"></main>
<div class="dock" id="transport"></div>
<nav class="tabs" id="tabs">
<button data-tab="now" aria-selected="true"><svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3.4"/><circle cx="12" cy="12" r="0.8"/></svg><span>Now</span></button>
<button data-tab="queue" aria-selected="false"><svg class="ic" viewBox="0 0 24 24"><path d="M3 6h13M3 12h9M3 18h9M17 12v6M14 15h6"/></svg><span>Up next</span></button>
<button data-tab="browse" aria-selected="false"><svg class="ic" viewBox="0 0 24 24"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg><span>Browse</span></button>
</nav>
<div class="toast" id="toast"></div>
<script>
const $=s=>document.querySelector(s);
const enc=encodeURIComponent;
const esc=s=>String(s==null?"":s).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
const hash=str=>{ let h=0; str=String(str); for(let i=0;i<str.length;i++)h=(h*31+str.charCodeAt(i))|0; return Math.abs(h); };
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
let DEMO=false;
// self-contained fake backend — mirrors ui/90-boot.html's Demo IIFE, trimmed to what the remote calls
const Demo=(()=>{
const speakers0=[
{uuid:"Z_LIVING",name:"Living Room",ip:"192.168.1.21",members:[{uuid:"Z_LIVING",name:"Living Room",ip:"192.168.1.21",volume:32}]},
{uuid:"Z_KITCHEN",name:"Kitchen",ip:"192.168.1.22",members:[{uuid:"Z_KITCHEN",name:"Kitchen",ip:"192.168.1.22",volume:24}]},
{uuid:"Z_BED",name:"Bedroom (Symfonisk)",ip:"192.168.1.23",members:[{uuid:"Z_BED",name:"Bedroom",ip:"192.168.1.23",volume:18}]},
];
let speakers=JSON.parse(JSON.stringify(speakers0));
const albums=[
["Vaelo","Neon Meridian",190,["Meridian","Glass Arcade","Low Orbit","Cassette Sun","Nightform","Parallax","Afterglow"]],
["Marisa Quon","Slow Tide",210,["Slow Tide","Harbor Lights","Paper Boats","Undertow","Salt & Static","Low Country"]],
["Kessler","Concrete Garden",150,["Concrete Garden","Rooftop Rain","Ivy & Rebar","Static Bloom","Terrace","Grey Morning","Foundations"]],
["Sable","After Hours",175,["After Hours","Velvet Room","Last Call","Neon Cab","Dawn Drive","Closing Time"]],
];
let tracks=[], id=1;
function build(){ tracks=[]; id=1; for(const[ar,al,base,ts]of albums)for(const tt of ts) tracks.push({id:String(id++),title:tt,artist:ar,album:al,folder:ar+"/"+al,has_art:true,dur:base+hash(tt)%120}); }
build();
const folder="/Users/you/Music";
let queue=tracks.slice(0,6).map(t=>t.id), qidx=1, state="PLAYING", pos=48, vol=32, shuffle=false;
const cur=()=>tracks.find(t=>t.id===queue[qidx]);
setInterval(()=>{ if(state!=="PLAYING"||!queue.length)return; const t=cur(); if(!t)return; pos++; if(pos>=t.dur){ pos=0; qidx=shuffle?(Math.random()*queue.length)|0:(qidx+1)%queue.length; } },1000);
const hms=s=>{ s=Math.max(0,Math.round(s)); return ((s/3600)|0)+":"+String(((s%3600/60)|0)).padStart(2,"0")+":"+String(s%60).padStart(2,"0"); };
// gradient artwork per track (data URL) so it renders like the real thing
const artC={};
function art(tid){ if(artC[tid])return artC[tid]; const alb=(tracks.find(t=>String(t.id)===String(tid))||{}).album||tid;
const h=hash(alb)%360, c=document.createElement("canvas"); c.width=c.height=320; const x=c.getContext("2d");
const g=x.createLinearGradient(0,0,320,320); g.addColorStop(0,`hsl(${h} 68% 54%)`); g.addColorStop(.55,`hsl(${(h+30)%360} 55% 32%)`); g.addColorStop(1,`hsl(${(h+60)%360} 45% 14%)`);
x.fillStyle=g; x.fillRect(0,0,320,320);
const rg=x.createRadialGradient(90,80,10,90,80,260); rg.addColorStop(0,`hsl(${(h+20)%360} 85% 65% / .85)`); rg.addColorStop(1,"transparent"); x.fillStyle=rg; x.fillRect(0,0,320,320);
let s=hash(tid)||1; const rnd=()=>{s=(s*16807)%2147483647;return (s-1)/2147483646;};
x.globalAlpha=.10; x.fillStyle="#fff"; for(let i=0;i<3;i++){ x.beginPath(); x.arc(rnd()*320,rnd()*320,20+rnd()*90,0,7); x.fill(); } x.globalAlpha=1;
return artC[tid]=c.toDataURL();
}
async function route(path,body){ await new Promise(r=>setTimeout(r,70+Math.random()*120));
const [p,qs]=path.split("?"); const P=new URLSearchParams(qs||"");
switch(p){
case"/api/state": return {speakers:JSON.parse(JSON.stringify(speakers)),folder,track_count:tracks.length,last_speaker:speakers[0].uuid};
case"/api/tracks":{ const q=(P.get("q")||"").toLowerCase(); const l=tracks.filter(t=>!q||(t.title+" "+t.artist+" "+t.album).toLowerCase().includes(q)); return {tracks:l.slice(0,3000),total:l.length}; }
case"/api/status":{ const t=cur(); if(!t)return{state:"STOPPED",title:"",position:"0:00:00",duration:"0:00:00",volume:vol,track_no:0,track_id:null}; return {state,title:t.title,position:hms(pos),duration:hms(t.dur),volume:vol,track_no:qidx+1,track_id:t.id}; }
case"/api/queue": return {items:queue.map((qid,i)=>({no:i+1,id:qid,title:(tracks.find(t=>t.id===qid)||{}).title||qid})),total:queue.length};
case"/api/enqueue": queue.push(...body.ids); return{ok:true};
case"/api/queue_jump": qidx=clamp(body.no-1,0,queue.length-1); pos=0; state="PLAYING"; return{ok:true};
case"/api/queue_remove": if(body.no-1<qidx)qidx--; queue.splice(body.no-1,1); qidx=clamp(qidx,0,Math.max(0,queue.length-1)); return{ok:true};
case"/api/queue_move":{ const from=body.from-1, to=clamp(body.to-1,0,queue.length-1); const cur_id=queue[qidx];
const [moved]=queue.splice(from,1); queue.splice(to,0,moved); qidx=queue.indexOf(cur_id); return{ok:true}; }
case"/api/room_volume":{ for(const g of speakers)for(const m of (g.members||[])) if(m.uuid===body.speaker)m.volume=body.value; vol=body.value; return{ok:true}; }
case"/api/cmd":{ const a=body.action;
if(a==="pause")state="PAUSED_PLAYBACK"; else if(a==="resume")state="PLAYING";
else if(a==="next"){qidx=(qidx+1)%(queue.length||1);pos=0;} else if(a==="prev"){ if(pos>3)pos=0; else {qidx=(qidx-1+(queue.length||1))%(queue.length||1);pos=0;} }
else if(a==="volume")vol=body.value; else if(a==="seek")pos=body.value; else if(a==="shuffle")shuffle=body.value;
return{ok:true}; }
default: throw new Error("Not found: "+p);
}
}
return {route,art};
})();
// icon set — identical glyphs to the desktop player_ui.html
const IC={
shuffle:'<svg class="ic" viewBox="0 0 24 24"><path d="M16 3h5v5M4 20 21 3M21 16v5h-5M15 15l6 6M4 4l5 5"/></svg>',
prev:'<svg class="ic fill" viewBox="0 0 24 24"><rect x="5" y="5" width="2.3" height="14" rx="1"/><path d="M20 6v12a1 1 0 0 1-1.6.8L9 12l9.4-6.8A1 1 0 0 1 20 6z"/></svg>',
next:'<svg class="ic fill" viewBox="0 0 24 24"><path d="M4 6v12a1 1 0 0 0 1.6.8L15 12 5.6 5.2A1 1 0 0 0 4 6z"/><rect x="16.7" y="5" width="2.3" height="14" rx="1"/></svg>',
play:'<svg class="ic" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>',
pause:'<svg class="ic" viewBox="0 0 24 24"><path d="M7 5h3.2v14H7zM13.8 5H17v14h-3.2z"/></svg>',
up:'<svg class="ic" viewBox="0 0 24 24"><path d="M12 19V6M6 12l6-6 6 6"/></svg>',
queuePlus:'<svg class="ic" viewBox="0 0 24 24"><path d="M3 6h13M3 12h9M3 18h9M17 12v6M14 15h6"/></svg>',
add:'<svg class="ic" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',
x:'<svg class="ic" viewBox="0 0 24 24"><path d="M6 18 18 6M6 6l12 12"/></svg>',
search:'<svg class="ic" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>',
speaker:'<svg class="ic" viewBox="0 0 24 24"><rect x="6" y="3" width="12" height="18" rx="2.4"/><circle cx="12" cy="14" r="3.2"/><circle cx="12" cy="7" r="1"/></svg>',
};
const S={speaker:null, rooms:[], status:null, queue:[], tracks:[], trackMap:{}, tab:"now", query:""};
async function api(path, body){
if(DEMO) return Demo.route(path, body);
const opt = body!==undefined ? {method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)} : {};
const r = await fetch(path, opt);
const data = await r.json().catch(()=>({}));
if(!r.ok || data.error) throw new Error(data.error || ("HTTP "+r.status));
return data;
}
const artUrl=id=> DEMO ? Demo.art(id) : "/api/art?id="+enc(id);
function toast(msg){ const t=$("#toast"); t.textContent=msg; t.classList.add("show"); clearTimeout(toast._t); toast._t=setTimeout(()=>t.classList.remove("show"),2600); }
function online(ok){ $("#banner").classList.toggle("show", !ok); }
function fill(el){ if(el) el.style.setProperty("--v",(el.value/(el.max||100)*100)+"%"); } // colour the filled part of a slider
async function loadRooms(){
const st = await api("/api/state");
S.rooms = st.speakers||[];
if(!S.speaker){ S.speaker = st.last_speaker || (S.rooms[0] && S.rooms[0].uuid) || null; }
renderRooms();
}
function renderRooms(){
const sel=$("#roomSel");
sel.innerHTML = S.rooms.map(r=>`<option value="${esc(r.uuid)}" ${r.uuid===S.speaker?"selected":""}>${esc(r.name||r.uuid)}</option>`).join("")
|| `<option value="">No rooms found</option>`;
}
async function poll(){
try{
if(!S.rooms.length) await loadRooms();
if(S.speaker){
const [status] = await Promise.all([ api("/api/status?speaker="+enc(S.speaker)) ]);
S.status = status;
if(typeof status.volume==="number" && document.activeElement!==$("#vol")){ $("#vol").value=status.volume; fill($("#vol")); }
renderTransport(); // keep play/pause icon current on every tab, not just Now/Queue
if(S.tab==="now") updateNow(); // in-place patch — never rebuild #view here (would kill mid-drag seek + reload art)
if(S.tab==="queue") await refreshQueue();
}
online(true);
}catch(e){ online(false); }
finally{ setTimeout(poll, 1000); }
}
async function cmd(action, value){
if(!S.speaker){ toast("Pick a room first."); return; }
try{ await api("/api/cmd", value!==undefined ? {speaker:S.speaker,action,value} : {speaker:S.speaker,action}); }
catch(e){ toast(e.message); }
}
function renderTransport(){
const playing = S.status && S.status.state && /PLAYING/.test(S.status.state);
const dis = !S.speaker;
$("#transport").innerHTML =
`<button class="cbtn" id="tShuf" aria-label="Shuffle" ${dis?"disabled":""}>${IC.shuffle}</button>
<button class="cbtn" id="tPrev" aria-label="Previous" ${dis?"disabled":""}>${IC.prev}</button>
<button class="play" id="tPlay" aria-label="Play or pause" ${dis?"disabled":""}>${playing?IC.pause:IC.play}</button>
<button class="cbtn" id="tNext" aria-label="Next" ${dis?"disabled":""}>${IC.next}</button>
<div class="cbtn" aria-hidden="true"></div>`;
$("#tShuf").onclick=()=>cmd("shuffle", true);
$("#tPrev").onclick=()=>cmd("prev");
$("#tPlay").onclick=()=>cmd(playing?"pause":"resume");
$("#tNext").onclick=()=>cmd("next");
}
let _npBuilt=false; // has the Now DOM been built once? (rebuilt on tab entry/room change, patched in place on poll)
let _npArtId=null; // track_id whose art is currently loaded — only touch the <img> when this changes
function emptyView(icon, html){ $("#view").innerHTML=`<div class="empty">${icon}<div>${html}</div></div>`; }
function pickRoomView(){ emptyView(IC.speaker,"Pick a room to start."); _npBuilt=false; }
function renderNow(){
renderTransport();
if(!S.speaker){ pickRoomView(); return; }
$("#view").innerHTML=`
<div class="now">
<div class="cover"><img id="npArt" alt="" onerror="this.style.display='none'"></div>
<div class="ninfo"><b id="npTitle"></b><small id="npArtist"></small></div>
<div class="seekwrap">
<span class="t mono" id="npPos"></span>
<input type="range" id="seek" class="slider" min="0" max="1000" value="0">
<span class="t r mono" id="npDur"></span>
</div>
</div>`;
const seek=$("#seek");
seek.oninput=()=>fill(seek);
seek.onchange=()=>{ const dur=hms((S.status||{}).duration); if(dur>0) cmd("seek", Math.round(seek.value/1000*dur)); };
_npBuilt=true;
_npArtId=null;
updateNow();
}
function updateNow(){
// In-place patch for poll ticks — must never touch #seek.value mid-drag/focus or rebuild the <img> unless the track changed.
if(!S.speaker) return;
if(!_npBuilt || !$("#npTitle")){ renderNow(); return; } // structure not built yet (first entry) — build it, which also patches once
const s=S.status||{};
const t=S.trackMap[s.track_id]||{};
$("#npTitle").textContent = s.title || "Nothing playing"; // textContent — inherently escaped, no esc() needed
$("#npArtist").textContent = t.artist || "";
$("#npPos").textContent = s.position || "";
$("#npDur").textContent = s.duration || "";
if(s.track_id !== _npArtId){ // only reload art when the track actually changed — avoids refetch/flicker every tick
_npArtId = s.track_id;
const art = $("#npArt");
// skip the fetch when the library map says this track has no art; onerror hides it if a fetch 404s anyway
if(s.track_id && (S.trackMap[s.track_id]||{}).has_art!==false){ art.src = artUrl(s.track_id); art.style.display="block"; }
else { art.removeAttribute("src"); art.style.display="none"; }
}
const seek=$("#seek");
const pos=hms(s.position), dur=hms(s.duration);
if(dur>0 && document.activeElement!==seek){ seek.value=Math.round(pos/dur*1000); fill(seek); }
}
function hms(x){ if(!x)return 0; const p=String(x).split(":").map(Number); return p.reduce((a,b)=>a*60+b,0); }
async function refreshQueue(){
if(!S.speaker) return;
try{ const q=await api("/api/queue?speaker="+enc(S.speaker)); S.queue=q.items||[]; if(S.tab==="queue") renderQueue(); }
catch(e){ /* leave last queue; poll banner handles offline */ }
}
function renderQueue(){
renderTransport();
if(!S.speaker){ pickRoomView(); return; }
const cur = S.status && S.status.track_no; // 1-based current position
if(!S.queue.length){ emptyView(IC.queuePlus,"Nothing queued yet.<br>Add something from Browse."); return; }
$("#view").innerHTML = `<div class="rows">`+S.queue.map(it=>{
const isCur = cur && it.no===cur; // it.no is 1-based, same scale as track_no
const atTop = it.no===1;
const meta = S.trackMap[it.id]||{}; // pull artist from the library map when we have it
const sub = isCur ? "Now playing" : (meta.artist || "Up next");
const thumb = it.id
? `<div class="rthumb"><img loading="lazy" src="${esc(artUrl(it.id))}" alt="" onerror="this.remove()"></div>`
: `<div class="rthumb"><span class="idx">${it.no}</span></div>`;
return `<div class="row ${isCur?"playing":""}">
<div class="rmain" data-jump="${it.no}">
${thumb}
<div class="tt"><b>${esc(it.title||"(unknown)")}</b><small>${esc(sub)}</small></div>
</div>
<div class="qacts">
<button class="iconbtn" data-up="${it.no}" aria-label="Move up"${atTop?" disabled":""}>${IC.up}</button>
<button class="iconbtn" data-next="${it.no}" aria-label="Play next">${IC.queuePlus}</button>
<button class="iconbtn" data-rm="${it.no}" aria-label="Remove">${IC.x}</button>
</div>
</div>`;
}).join("")+`</div>`;
}
// Delegated queue actions:
$("#view").addEventListener("click", async e=>{
const j=e.target.closest("[data-jump]"), up=e.target.closest("[data-up]"),
nx=e.target.closest("[data-next]"), rm=e.target.closest("[data-rm]");
try{
if(j){ await api("/api/queue_jump",{speaker:S.speaker,no:+j.dataset.jump}); } // no is already 1-based
else if(up){ const n=+up.dataset.up; if(n>1) await api("/api/queue_move",{speaker:S.speaker,from:n,to:n-1}); }
else if(nx){ const n=+nx.dataset.next; const cur=(S.status&&S.status.track_no)||0; await api("/api/queue_move",{speaker:S.speaker,from:n,to:cur+1}); }
else if(rm){ await api("/api/queue_remove",{speaker:S.speaker,no:+rm.dataset.rm}); } // no is already 1-based
else return;
await refreshQueue();
}catch(err){ toast(err.message); }
});
let _searchT;
let _tracksReq=0; // monotonic token — lets a slower earlier /api/tracks response detect it's stale and bail
async function loadTracks(q){
S.query = q||"";
const reqId = ++_tracksReq;
let d;
try{ d = await api("/api/tracks"+(q?("?q="+enc(q)):"")); }
catch(e){ return; } // offline mid-search — poll's banner already surfaces this, nothing more to do here
if(reqId!==_tracksReq) return; // a newer search has started since; don't let this stale response clobber it
S.tracks=d.tracks||[];
S.trackMap=Object.fromEntries(S.tracks.map(t=>[t.id,t]));
if(S.tab!=="browse") return;
const list=$("#browseList");
if(list) list.innerHTML=browseRows(); // update rows only — never recreate #q (keeps value/focus/keyboard during live search)
else renderBrowse();
}
async function enqueue(id, next){
if(!S.speaker){ toast("Pick a room first."); return; }
try{ await api("/api/enqueue",{speaker:S.speaker,ids:[id],next:!!next}); toast(next?"Playing next":"Added to queue"); }
catch(e){ toast(e.message); }
}
function browseRows(){
if(!S.tracks.length) return `<div class="empty">${IC.search}<div>${S.query?"No matches.":"No music yet."}</div></div>`;
return `<div class="rows">`+S.tracks.slice(0,500).map(t=>{
const thumb = t.has_art
? `<div class="rthumb"><img loading="lazy" src="${esc(artUrl(t.id))}" alt="" onerror="this.remove()"></div>`
: `<div class="rthumb"></div>`;
return `<div class="row">
<div class="rmain">
${thumb}
<div class="tt"><b>${esc(t.title||"(unknown)")}</b><small>${esc(t.artist||"")}</small></div>
</div>
<div class="qacts">
<button class="iconbtn" data-add="${t.id}" aria-label="Add to queue">${IC.add}</button>
<button class="iconbtn" data-addnext="${t.id}" aria-label="Play next">${IC.queuePlus}</button>
</div>
</div>`;
}).join("")+`</div>`;
}
function renderBrowse(){
renderTransport();
$("#view").innerHTML =
`<div class="searchbar">${IC.search}<input id="q" placeholder="Search your library" value="${esc(S.query)}"></div>
<div id="browseList">${browseRows()}</div>`;
$("#q").oninput=e=>{ clearTimeout(_searchT); const v=e.target.value; _searchT=setTimeout(()=>loadTracks(v),250); };
}
// Delegated add actions (second listener — matches disjoint selectors from the queue handler above):
$("#view").addEventListener("click", e=>{
const a=e.target.closest("[data-add]"), an=e.target.closest("[data-addnext]");
if(a) enqueue(a.dataset.add, false);
else if(an) enqueue(an.dataset.addnext, true);
});
$("#roomSel").addEventListener("change", e=>{ S.speaker=e.target.value; S.status=null; render(); });
$("#vol").addEventListener("input", e=>fill(e.target));
$("#vol").addEventListener("change", e=>{ if(S.speaker) api("/api/room_volume",{speaker:S.speaker,value:+e.target.value}).catch(err=>toast(err.message)); });
$("#tabs").addEventListener("click", e=>{ const b=e.target.closest("button"); if(!b)return;
S.tab=b.dataset.tab; [...$("#tabs").children].forEach(x=>x.setAttribute("aria-selected", x===b)); render(); });
function render(){ if(S.tab==="now")renderNow(); else if(S.tab==="queue"){renderQueue();refreshQueue();} else renderBrowse(); }
fill($("#vol"));
(async()=>{
try{ const r=await fetch("/api/state"); if(!r.ok) throw 0; }catch(e){ DEMO=true; }
await Promise.all([loadRooms(), loadTracks("")]).catch(()=>online(false));
render(); poll();
})();
</script>
</body></html>