feat: add multi-user support for favorites management and room clock synchronization

- Implemented a new API endpoint for retrieving and managing user favorites in /api/users.
- Added functionality for admins to edit the shared "main" user's favorites.
- Created a one-shot DB smoke test script for verifying multi-user kiosk migrations.
- Introduced a RoomClock class for synchronizing server time across clients using WebSocket.
This commit is contained in:
Marco Mooren
2026-05-13 13:53:12 +02:00
parent f6cdfd975c
commit 29423288ca
41 changed files with 4229 additions and 275 deletions

View File

@@ -17,21 +17,23 @@ import { api } from '../shared/api.js';
import { connectWs } from '../shared/ws.js';
import { el, clear } from '../shared/dom.js';
import { Player } from '../player.js';
import { RoomClock } from '../shared/clock.js';
import { mountVisualizer } from './visualizer.js';
import { showStartModal, autoplayDismissed } from '../shared/playGate.js';
import { mountDebugPane } from '../shared/debug.js';
// Fake list mirrors what a typical desktop sees. Used only when no native
// bridge is present (i.e. running in a normal browser tab, not Electron).
const FAKE_DEVICES = [
{ id: 'default', label: 'System default', kind: 'speakers' },
{ id: 'speakers-internal', label: 'Built-in speakers', kind: 'speakers' },
{ id: 'headphones-jack', label: 'Headphones (3.5mm)', kind: 'headphones' },
{ id: 'hdmi-tv', label: 'HDMI Living-room TV', kind: 'hdmi' },
{ id: 'bt-marshall', label: 'Bluetooth Marshall Stanmore', kind: 'bluetooth' },
{ id: 'usb-audient', label: 'USB Audient EVO 4', kind: 'usb' }
];
// The audio-output picker and the spectrum visualiser only work inside the
// Electron shell (real device enumeration, plus the CORS-rewrite that lets
// AnalyserNode read PCM from cross-origin radio streams). In a plain browser
// tab those features are hidden — the master still functions as the room's
// authoritative source for any connected kiosks.
const app = document.getElementById('app');
const state = {
user: null,
users: [], // public list of all users (for the tab strip + avatar picker)
mainUser: null, // the shared/house identity, e.g. morphix
device: { trusted: false, users: [] }, // trusted-device whitelist for fast switching
rooms: [],
roomSlug: null,
room: null,
@@ -42,15 +44,46 @@ const state = {
loading: false, volume: 0.7, error: null
},
voteStats: null,
favorites: [],
favorites: [], // current viewer's *own* favorites (write target, heart indicator)
tabUser: null, // username currently shown in the favorites strip (defaults to self)
tabFavorites: [], // favorites for the active tab (== state.favorites when tabUser is self)
tabLoading: false,
favGenre: '', // active genre filter for favorites browser
showOutputs: false, // output picker is hidden behind a button
showAvatars: false, // avatar / user-switch popover
session: null // { id, stationId, startedAt } for the open play_history row
};
const native = window.oradioNative || null;
let ws = null;
let player = null;
// Mandatory click-to-start in plain browsers — same scheme as the kiosk.
// Auto-resume on cold-boot (hello-state replay) must wait for the user to
// tap Start before calling player.audio.play(). Electron bypasses via
// autoplayDismissed().
let gestureUnlocked = false;
function markGesture() { gestureUnlocked = true; }
async function ensureGesture(stationName, subtitle) {
if (gestureUnlocked) return true;
if (autoplayDismissed()) { gestureUnlocked = true; return true; }
try {
await showStartModal({
stationName: stationName || 'Radio',
subtitle: subtitle || 'Tap Start to enable audio.',
onStart: () => { gestureUnlocked = true; }
});
return gestureUnlocked;
} catch {
return false;
}
}
// Master command de-dup: track the station id of the in-flight play (so a
// second cmd for the same id is a no-op) and a generation counter so a slow
// /api/stations/:id fetch from an OLD cmd can't call playStation() after a
// newer cmd has already been handled.
let _pendingStationId = null;
let _cmdGen = 0;
const clock = new RoomClock();
async function bootstrap() {
try { state.user = await api.get('/api/auth/me'); }
@@ -66,30 +99,105 @@ async function bootstrap() {
|| (state.rooms[0] && state.rooms[0].slug)
|| `u-${state.user.id}`;
// Initial device list.
if (native?.listOutputs) {
state.devices.list = await native.listOutputs();
state.devices.current = (await native.getCurrent()) || state.devices.list[0]?.id;
// Initial device list — Electron only. In the browser the picker is
// hidden, so we leave the list empty.
if (native?.isElectron && native.listOutputs) {
try {
state.devices.list = await native.listOutputs();
state.devices.current = (await native.getCurrent()) || state.devices.list[0]?.id || 'default';
} catch (err) {
console.warn('[master] listOutputs failed', err);
state.devices.list = [];
state.devices.current = 'default';
}
native.onCurrentChanged?.((id) => { state.devices.current = id; advertiseDevices(); render(); });
} else {
state.devices.list = FAKE_DEVICES;
state.devices.current = 'default';
state.devices.list = [];
state.devices.current = null;
}
player = new Player({
onState: (s) => {
// Capture the previous snapshot BEFORE merging so we can tell
// whether the change is actually worth broadcasting.
const prev = { ...state.np };
Object.assign(state.np, s);
// Push display truth out to the room.
sendState();
render();
// Push display truth out to the room ONLY on meaningful changes:
// station, playing flag, or volume. The Player emits during the
// loading phase (playing:false, loading:true) used to thrash the
// server-persisted state and cause all peers to see a
// playing-false flicker. We also intentionally do NOT send while
// `loading` is true — onPlayingOnce will send a single state
// with started_at once audio actually starts.
const station = state.np.stationId;
const playing = !!state.np.playing;
const volume = state.np.volume;
const stationOrPlayingChanged = station !== prev.stationId || playing !== !!prev.playing;
const volumeChanged = Math.abs((volume ?? 0) - (prev.volume ?? 0)) > 0.001;
const isLoading = s.loading === true;
// Defensive guard: Player.play() already swallows the pause
// event from its internal stop() via _silentStop, but if any
// other path produces a (stationId=null, playing=false) emit
// mid-switch (e.g. an `error` event), don't broadcast that
// ghost — the kiosks would briefly clear their UI.
const ghostStop = s.playing === false && s.stationId == null && _pendingStationId != null;
if (!isLoading && !ghostStop) {
if (stationOrPlayingChanged) {
// Station / playing transitions are user-visible — send now
// and drop any pending throttled volume broadcast (the
// state we send carries the latest volume).
if (_volumeBroadcastT) { clearTimeout(_volumeBroadcastT); _volumeBroadcastT = null; }
sendState();
} else if (volumeChanged) {
broadcastVolumeSoon();
}
}
scheduleRender();
}
});
// The master IS the anchor: when its <audio> reports its first decoded
// sample for a (new) station, re-broadcast started_at so every peer
// aligns on a real wall-clock instant instead of the server's
// command-time estimate.
player.onPlayingOnce = (station) => {
if (!ws || !station) return;
const startedAt = clock.now ? clock.now() : Date.now();
try {
ws.send({
type: 'state',
stationId: station.id,
playing: true,
volume: state.np.volume,
started_at: startedAt
});
} catch { /* ignore */ }
// Local sync engine should re-target too so the master's own output
// honours the shared deadline.
if (player.sync.enabled) player.updateSyncTarget(startedAt);
else applyMasterSync(startedAt);
};
// Load favorites so the touch browser + heart indicator work.
try { state.favorites = await api.get('/api/me/favorites'); }
catch { state.favorites = []; }
// Multi-user surface: list of all users (tab strip), the main/shared
// identity (pinned tab + "Follow main" target), and this device's
// trusted-user whitelist (for fast switching).
try { state.users = await api.get('/api/auth/users/public'); }
catch { state.users = []; }
try { state.mainUser = await api.get('/api/auth/main'); }
catch { state.mainUser = null; }
try { state.device = await api.get('/api/auth/devices/me'); }
catch { state.device = { trusted: false, users: [] }; }
// Default tab is yourself; the strip pins main first regardless.
state.tabUser = state.user.username;
state.tabFavorites = state.favorites;
openWs();
startSyncPosBroadcast();
mountDebugPane({ player, clock, getWs: () => ws, role: 'master' });
render();
}
@@ -101,15 +209,60 @@ if (typeof window !== 'undefined') {
function openWs() {
if (ws) { try { ws.close(); } catch { } }
clock.detach();
ws = connectWs(handleWs, {
room: state.roomSlug,
kind: 'display',
onOpen: () => advertiseDevices()
});
clock.attachWs(ws);
}
// Every 2 s while audio is actually playing, broadcast a sync-pos snapshot.
// Peers on non-HLS streams use this as the timeline anchor: at server-clock
// `atServerNow` the master's <audio>.currentTime was `masterCT`, so each
// peer projects its own expected position forward from that point. HLS
// peers prefer PROGRAM-DATE-TIME when available and ignore this; the
// snapshot is still useful as a fallback if PDT is missing or skewed.
let _syncPosTimer = null;
function startSyncPosBroadcast() {
if (_syncPosTimer) return;
_syncPosTimer = setInterval(() => {
if (!ws || !player) return;
if (player.audio.paused || player.audio.readyState < 2) return;
const station = state.np.stationId;
if (!Number.isFinite(station)) return;
try {
ws.send({
type: 'sync-pos',
stationId: station,
masterCT: player.audio.currentTime,
atServerNow: clock.now ? clock.now() : Date.now(),
pdtMs: player.hls?.playingDate?.getTime?.() ?? null,
bufferMs: player.sync?.bufferMs ?? null
});
} catch { /* ignore transient send errors */ }
}, 2000);
}
function stopSyncPosBroadcast() {
if (_syncPosTimer) { clearInterval(_syncPosTimer); _syncPosTimer = null; }
}
if (typeof window !== 'undefined') {
window.addEventListener('pagehide', stopSyncPosBroadcast);
}
// The master is the room's authoritative audio source, but it still routes
// its own output through a DelayNode so the shared room deadline
// (startedAt + bufferMs) gives every late-joining listener room to align.
function applyMasterSync(startedAt) {
if (!player) return;
if (startedAt) player.enableSync({ clock, startedAt });
else player.disableSync();
}
function handleWs(msg) {
if (!msg || !msg.type) return;
if (msg.type === 'clock-pong') { clock.handlePong(msg); return; }
switch (msg.type) {
case 'hello': {
state.room = msg.room;
@@ -128,9 +281,21 @@ function handleWs(msg) {
if (typeof rs?.volume === 'number') {
player.setVolume(rs.volume);
}
applyMasterSync(rs?.started_at || null);
render();
return;
}
case 'state': {
// Server echoes our own state plus its canonical started_at; the
// master uses that as the sync anchor too.
if (msg.started_at) {
if (player?.sync?.enabled) player.updateSyncTarget(msg.started_at);
else applyMasterSync(msg.started_at);
} else {
applyMasterSync(null);
}
return;
}
case 'presence':
state.peers = msg.peers || [];
render();
@@ -156,13 +321,31 @@ function handleCommand(msg) {
case 'play': {
const id = Number(msg.stationId);
if (!Number.isFinite(id)) return;
api.get(`/api/stations/${id}`).then((st) => playStation(st)).catch(() => { });
// Idempotency: ignore a play for the station already current OR
// already pending. Without these guards a flood of commands (e.g.
// multiple kiosks racing, or repeated clicks) would call
// playStation() in a loop, each one doing stop()+play() and
// producing audible start/stop thrashing.
if (id === state.np.stationId) return;
if (id === _pendingStationId) return;
_pendingStationId = id;
const gen = ++_cmdGen;
api.get(`/api/stations/${id}`).then((st) => {
// Bail if a newer command superseded this one while the
// station metadata fetch was in flight.
if (gen !== _cmdGen) return;
_pendingStationId = null;
playStation(st);
}).catch(() => {
if (gen === _cmdGen) _pendingStationId = null;
});
return;
}
case 'pause':
player.togglePause();
if (state.np.playing) player.togglePause();
return;
case 'stop':
if (!state.np.stationId) return;
player.stop();
endCurrentSession();
state.np.playing = false;
@@ -171,11 +354,21 @@ function handleCommand(msg) {
render();
return;
case 'volume':
if (typeof msg.value === 'number') player.setVolume(msg.value);
if (typeof msg.value === 'number' && Math.abs(msg.value - state.np.volume) > 0.001) {
player.setVolume(msg.value);
}
return;
case 'setSink':
setSink(String(msg.deviceId || ''));
return;
case 'setSyncBuffer':
if (Number.isFinite(msg.value) && player) {
player.setSyncBufferMs(msg.value);
// The next sync-pos broadcast (within 2s) carries the new
// bufferMs so late joiners and reconnecting peers pick it up
// from `hello.last_sync_pos`.
}
return;
default:
return;
}
@@ -183,6 +376,13 @@ function handleCommand(msg) {
async function playStation(station, { silent } = {}) {
if (!station) return;
// User-initiated playStation calls (station-card click) ARE the
// gesture. Silent/hello-resume paths leave gestureUnlocked false so
// ensureGesture below surfaces the Start modal.
if (!silent) markGesture();
// Any in-flight command for a different station is now stale.
_cmdGen++;
_pendingStationId = null;
// Close any previous session before swapping. We compute the duration
// locally so resumes-after-suspend don't get charged the whole gap.
endCurrentSession();
@@ -193,7 +393,16 @@ async function playStation(station, { silent } = {}) {
plays: station.plays || 0, score: station.score || 0
};
render();
// Mandatory gesture in plain browsers — silent/hello-resume paths
// would otherwise call audio.play() without one and iOS/Chromium
// would refuse. ensureGesture short-circuits once unlocked.
const ok = await ensureGesture(station.name, silent ? 'Tap Start to resume the group audio.' : 'Tap Start to play.');
if (!ok) return;
await player.play(station);
if (player.audio.paused) {
// Gesture confirmed but browser hasn't started yet — try once more.
player.audio.play().catch(() => { });
}
if (!silent) {
try {
const stats = await api.post(`/api/stations/${station.id}/play`);
@@ -229,16 +438,7 @@ function endCurrentSession({ beacon = false } = {}) {
}
function sendState() {
if (!ws || !state.np.stationId) {
ws?.send({
type: 'state',
stationId: state.np.stationId,
playing: !!state.np.playing,
volume: state.np.volume
});
return;
}
ws.send({
ws?.send({
type: 'state',
stationId: state.np.stationId,
playing: !!state.np.playing,
@@ -246,6 +446,55 @@ function sendState() {
});
}
// Volume changes from the slider can fire at 60+ Hz. Coalesce the broadcast
// onto a short trailing timer so dragging produces ~12 messages/sec instead
// of hundreds. Cleared when a station/playing change forces an immediate send.
let _volumeBroadcastT = null;
function broadcastVolumeSoon() {
if (_volumeBroadcastT) return;
_volumeBroadcastT = setTimeout(() => {
_volumeBroadcastT = null;
sendState();
}, 80);
}
// Single rAF gate around render() so a burst of state updates within the same
// frame collapses to one DOM rebuild. Without this, dragging the volume
// slider triggered a render per pointer event, tearing the slider out from
// under the user's pointer.
let _renderScheduled = false;
function scheduleRender() {
if (_renderScheduled) return;
_renderScheduled = true;
requestAnimationFrame(() => {
_renderScheduled = false;
render();
});
}
// `render()` does a full clear+rebuild of the DOM. If we re-render while the
// user is dragging a range slider, the slider element they're holding gets
// destroyed mid-drag and the browser drops the drag. Track active slider
// drags at the document level and have render() bail until the pointer is
// released. After release we trigger one catch-up render.
let _dragLockCount = 0;
function isRangeInput(t) {
return t instanceof HTMLInputElement && t.type === 'range';
}
if (typeof window !== 'undefined') {
document.addEventListener('pointerdown', (e) => {
if (isRangeInput(e.target)) _dragLockCount++;
}, true);
const release = (e) => {
if (isRangeInput(e.target) && _dragLockCount > 0) {
_dragLockCount--;
scheduleRender();
}
};
document.addEventListener('pointerup', release, true);
document.addEventListener('pointercancel', release, true);
}
function advertiseDevices() {
ws?.send({
type: 'devices',
@@ -261,10 +510,12 @@ async function setSink(deviceId) {
catch (err) { console.warn('[master] setOutput failed', err); return; }
}
state.devices.current = deviceId;
// Browser-only fallback: try `audio.setSinkId` if the device id maps to a
// real MediaDevices id. For the fake list this is a no-op visualisation.
if (player?.audio?.setSinkId && /^[a-f0-9]{16,}$/.test(deviceId)) {
try { await player.audio.setSinkId(deviceId); } catch { }
// Route both the audio element AND the AudioContext. Once the WebAudio
// graph is built (always, for the master) audio exits via the context's
// destination — setSinkId on the element alone is silently ignored.
if (native?.isElectron) {
try { await player.setSinkId(deviceId); }
catch (err) { console.warn('[master] setSinkId failed', err); }
}
advertiseDevices();
state.showOutputs = false;
@@ -278,6 +529,7 @@ function countDisplays(peers) {
// ---------- Favorites ----------
function isFavorite(stationId) {
// The heart always reflects the *viewer's* library, not the active tab.
return !!stationId && state.favorites.some((f) => f.id === stationId);
}
@@ -288,6 +540,8 @@ async function toggleFavorite(stationId) {
if (has) await api.del(`/api/me/favorites/${stationId}`);
else await api.put(`/api/me/favorites/${stationId}`, { position: state.favorites.length });
state.favorites = await api.get('/api/me/favorites');
// If you're currently viewing your own tab, refresh that view too.
if (state.tabUser === state.user.username) state.tabFavorites = state.favorites;
render();
} catch (err) {
console.warn('[master] toggleFavorite failed', err);
@@ -296,7 +550,7 @@ async function toggleFavorite(stationId) {
function favoriteGenres() {
const counts = new Map();
for (const s of state.favorites) {
for (const s of state.tabFavorites) {
for (const g of (s.genres || [])) counts.set(g, (counts.get(g) || 0) + 1);
}
return [...counts.entries()]
@@ -305,13 +559,105 @@ function favoriteGenres() {
}
function filteredFavorites() {
if (!state.favGenre) return state.favorites;
return state.favorites.filter((s) => (s.genres || []).includes(state.favGenre));
if (!state.favGenre) return state.tabFavorites;
return state.tabFavorites.filter((s) => (s.genres || []).includes(state.favGenre));
}
// ---------- Favorite tabs (users-as-folders) ----------
/** Ordered list of tabs: main first (★), then self if not main, then others. */
function favoriteTabs() {
const tabs = [];
const seen = new Set();
if (state.mainUser) {
tabs.push({ ...state.mainUser, main: true });
seen.add(state.mainUser.username);
}
if (state.user && !seen.has(state.user.username)) {
tabs.push({ ...state.user, self: true });
seen.add(state.user.username);
}
for (const u of state.users) {
if (!seen.has(u.username)) {
tabs.push(u);
seen.add(u.username);
}
}
// Annotate "self" on whichever tab matches the current viewer.
for (const t of tabs) if (t.username === state.user.username) t.self = true;
return tabs;
}
async function switchTab(username) {
if (!username || username === state.tabUser) return;
state.tabUser = username;
state.favGenre = '';
if (username === state.user.username) {
state.tabFavorites = state.favorites;
render();
return;
}
state.tabLoading = true;
render();
try {
state.tabFavorites = await api.get(`/api/users/${encodeURIComponent(username)}/favorites`);
} catch (err) {
console.warn('[master] failed to load favorites for', username, err);
state.tabFavorites = [];
} finally {
state.tabLoading = false;
render();
}
}
/** Can the viewer write into the currently-shown tab? */
function canEditCurrentTab() {
if (!state.tabUser) return false;
if (state.tabUser === state.user.username) return true;
// Admins can curate the shared/main tab.
return state.user.role === 'admin'
&& state.mainUser && state.tabUser === state.mainUser.username;
}
// ---------- User switching (avatar picker) ----------
async function switchUser(username) {
if (!username || username === state.user.username) {
state.showAvatars = false;
render();
return;
}
try {
await api.post('/api/auth/switch', { username });
} catch (err) {
console.warn('[master] switch failed', err);
alert(err.message || 'Could not switch user');
return;
}
// Hard reload: re-bootstrap so all per-user caches (rooms, favorites, WS) are reset.
location.reload();
}
// ---------- Follow main ----------
async function followMain() {
if (!state.mainUser) return;
const personalSlug = `u-${state.mainUser.id}`;
state.roomSlug = personalSlug;
history.replaceState(null, '', `?room=${encodeURIComponent(personalSlug)}`);
// Make sure it appears in the room dropdown by refetching.
try { state.rooms = await api.get('/api/rooms'); } catch { }
openWs();
render();
}
// ---------- Render ----------
function render() {
// Bail while the user is actively dragging a range slider — see
// `_dragLockCount` for the rationale. The next pointerup will schedule
// a catch-up render.
if (_dragLockCount > 0) return;
// Preserve scroll position of the favorites grid across re-renders so that
// tapping a tile (which triggers a full re-render) does not jump back to top.
const prevFavScroll = app.querySelector('.favs-grid')?.scrollLeft ?? 0;
@@ -337,15 +683,19 @@ function render() {
el('option', { value: r.slug, selected: r.slug === state.roomSlug }, r.name)))
),
el('div', { class: 'pill peers' }, `${state.peers.length} peer${state.peers.length === 1 ? '' : 's'}`),
el('div', { class: 'pill role-pill', title: 'This master is the authoritative audio source for the room.' },
'◉ Broadcasting'),
np.error ? el('div', { class: 'err-banner' }, np.error) : null,
el('div', { class: 'grow' }),
el('button', {
// Output picker: Electron only. In a browser tab the picker would
// be useless (no real device enumeration / sink switching).
native?.isElectron ? el('button', {
class: 'pill out-btn' + (state.showOutputs ? ' active' : ''),
title: 'Audio output',
onClick: () => { state.showOutputs = !state.showOutputs; render(); }
}, '🔊 ', currentDeviceLabel()),
el('div', { class: 'pill' }, native ? 'native' : 'browser'),
el('div', { class: 'pill' }, state.user.username),
}, '🔊 ', currentDeviceLabel()) : null,
renderFollowMainPill(),
renderUserPill(),
),
// Stage: now-playing block (with transport + volume embedded)
@@ -376,6 +726,9 @@ function render() {
}, fav ? '★' : '☆') : null
),
el('div', { class: 'genres' }, ...(st?.genres || []).slice(0, 6).map((g) => el('span', { class: 'tag' }, g))),
// Live spectrum analyser (Electron only). The canvas is
// hooked up after the DOM is appended (see below).
native?.isElectron ? el('canvas', { class: 'np-spectrum', 'data-spectrum': '1' }) : null,
state.voteStats ? el('div', { class: 'stats' },
el('span', {}, '▲ ', el('b', {}, String(state.voteStats.up || 0))),
el('span', {}, '▼ ', el('b', {}, String(state.voteStats.down || 0))),
@@ -388,13 +741,14 @@ function render() {
class: 'ctrl primary',
title: 'Play / pause',
disabled: !st,
onClick: () => player.togglePause()
onClick: () => { markGesture(); player.togglePause(); }
}, np.playing ? '❚❚' : '▶'),
el('button', {
class: 'ctrl',
title: 'Stop',
disabled: !st,
onClick: () => {
markGesture();
player.stop();
endCurrentSession();
state.np.playing = false;
@@ -406,7 +760,15 @@ function render() {
el('span', { class: 'vol-icon' }, '🔊'),
el('input', {
type: 'range', min: 0, max: 1, step: 0.01, value: np.volume,
onInput: (e) => player.setVolume(Number(e.target.value))
onInput: (e) => {
const v = Number(e.target.value);
player.setVolume(v);
// Update the % label inline so it tracks the
// slider while the drag-lock is suppressing
// full renders.
const valEl = e.target.parentNode?.querySelector('.val');
if (valEl) valEl.textContent = Math.round(v * 100) + '%';
}
}),
el('span', { class: 'val' }, Math.round(np.volume * 100) + '%')
)
@@ -419,7 +781,8 @@ function render() {
el('span', {}, p.user?.username || '?')
))
: [el('span', { class: 'peer' }, 'Just you.')])
)
),
renderZonesPanel()
)
)
),
@@ -430,7 +793,8 @@ function render() {
),
// Output picker popover (hidden by default; toggled by topbar button).
state.showOutputs ? renderOutputPopover() : null
native?.isElectron && state.showOutputs ? renderOutputPopover() : null,
state.showAvatars ? renderAvatarPopover() : null
);
app.appendChild(shell);
// Restore favorites grid scroll position after the DOM swap.
@@ -439,6 +803,11 @@ function render() {
if (prevFavScroll) favGrid.scrollLeft = prevFavScroll;
attachDragScroll(favGrid);
}
// Hook up the spectrum visualiser to the freshly-rendered canvas. The
// visualiser module guards against running outside Electron and against
// double-mounting on the same <audio> element.
const canvas = app.querySelector('canvas.np-spectrum');
if (canvas && player) mountVisualizer(canvas, player);
}
// Pointer-drag horizontal scrolling for the favorites strip. Mouse users can
@@ -500,12 +869,65 @@ function scrollFavs(direction) {
grid.scrollBy({ left: direction * delta, behavior: 'smooth' });
}
// Per-zone volume panel: one slider per non-display peer. Master can dim a
// specific kiosk's local audio without touching the room's master volume.
// Sends `command:peerVolume` which the server forwards only to that user.
const _zoneVolumes = new Map(); // userId -> last value (UI memory only)
function renderZonesPanel() {
if (!ws) return null;
const zones = (state.peers || []).filter((p) => p.kind !== 'display');
if (!zones.length) return null;
return el('div', { class: 'zones-panel', title: 'Per-zone (local) volume for each connected client.' },
el('div', { class: 'zones-label' }, 'Zones'),
...zones.map((p) => {
const uid = p.user?.id;
const username = p.user?.username || '?';
const cur = _zoneVolumes.get(uid) ?? 0.7;
return el('div', { class: 'zone-row' },
el('span', { class: 'zone-name', title: `${username} (${p.kind})` }, username),
el('input', {
type: 'range', min: 0, max: 1, step: 0.05, value: cur,
'aria-label': `Volume for ${username}`,
onInput: (e) => {
const v = Number(e.target.value);
_zoneVolumes.set(uid, v);
try { ws.send({ type: 'command', action: 'peerVolume', userId: uid, value: v }); } catch { /* ignore */ }
const valEl = e.target.parentNode?.querySelector('.zone-val');
if (valEl) valEl.textContent = Math.round(v * 100) + '%';
}
}),
el('span', { class: 'zone-val' }, Math.round(cur * 100) + '%')
);
})
);
}
function renderFavoritesCard() {
const tabs = favoriteTabs();
const editable = canEditCurrentTab();
const genres = favoriteGenres();
const favs = filteredFavorites();
const tabName = state.tabUser === state.user.username
? 'My favorites'
: (state.mainUser && state.tabUser === state.mainUser.username)
? `${state.tabUser} (main)`
: state.tabUser;
return el('div', { class: 'card favs-card' },
el('div', { class: 'fav-tabs' }, ...tabs.map((t) => el('button', {
class: 'fav-tab' + (t.username === state.tabUser ? ' active' : '') + (t.main ? ' main' : '') + (t.self ? ' self' : ''),
title: t.username + (t.main ? ' (main / shared)' : '') + (t.self ? ' (you)' : ''),
onClick: () => switchTab(t.username)
},
el('span', { class: 'fav-tab-glyph' }, t.main ? '★' : (t.avatar_emoji || '●')),
el('span', { class: 'fav-tab-name' }, t.username),
))),
el('div', { class: 'favs-header' },
el('h3', {}, `Favorites (${favs.length}${state.favGenre ? `/${state.favorites.length}` : ''})`),
el('h3', {},
tabName,
' ',
el('span', { class: 'fav-count' }, `(${favs.length}${state.favGenre ? `/${state.tabFavorites.length}` : ''})`),
!editable ? el('span', { class: 'fav-readonly', title: 'Read-only — switch to your own tab to edit' }, ' · read-only') : null
),
genres.length ? el('select', {
class: 'genre-filter',
title: 'Filter by genre',
@@ -526,22 +948,26 @@ function renderFavoritesCard() {
onClick: () => scrollFavs(1)
}, '')
),
el('div', { class: 'favs-grid' }, ...(favs.length ? favs.map((s) => {
const art = s.image_display_url || s.image_url;
const active = state.np.stationId === s.id;
return el('button', {
class: 'fav-tile' + (active ? ' active' : ''),
title: s.name,
onClick: () => playStation(s)
},
el('div', {
class: 'fav-art' + (art ? '' : ' empty'),
style: art ? { backgroundImage: `url("${art}")` } : {}
}),
el('div', { class: 'fav-name' }, s.name)
);
}) : [el('div', { class: 'favs-empty' },
state.favGenre ? 'No favorites in this genre.' : 'No favorites yet. Star a station to add it.')]))
el('div', { class: 'favs-grid' }, ...(state.tabLoading
? [el('div', { class: 'favs-empty' }, 'Loading…')]
: favs.length ? favs.map((s) => {
const art = s.image_display_url || s.image_url;
const active = state.np.stationId === s.id;
return el('button', {
class: 'fav-tile' + (active ? ' active' : ''),
title: s.name,
onClick: () => playStation(s)
},
el('div', {
class: 'fav-art' + (art ? '' : ' empty'),
style: art ? { backgroundImage: `url("${art}")` } : {}
}),
el('div', { class: 'fav-name' }, s.name)
);
}) : [el('div', { class: 'favs-empty' },
state.favGenre ? 'No favorites in this genre.'
: editable ? 'No favorites yet. Star a station to add it.'
: `${state.tabUser} has no favorites yet.`)]))
);
}
@@ -576,6 +1002,77 @@ function currentDeviceLabel() {
return d ? d.label : '—';
}
// ---------- User pill + avatar popover + follow-main ----------
function renderUserPill() {
const trusted = !!state.device.trusted;
const others = (state.device.users || []).filter((u) => u.username !== state.user.username);
const canSwitch = trusted && others.length > 0;
return el('button', {
class: 'pill user-pill' + (state.showAvatars ? ' active' : ''),
title: canSwitch ? 'Switch user' : (trusted ? 'No other users on this device' : 'This device is not trusted for fast switching'),
onClick: () => {
if (!canSwitch) return;
state.showAvatars = !state.showAvatars;
render();
}
},
el('span', {
class: 'avatar',
style: state.user.avatar_color ? { background: state.user.avatar_color } : {}
}, state.user.avatar_emoji || state.user.username.slice(0, 1).toUpperCase()),
el('span', {}, state.user.username),
canSwitch ? el('span', { class: 'caret' }, '▾') : null
);
}
function renderFollowMainPill() {
if (!state.mainUser) return null;
const mainSlug = `u-${state.mainUser.id}`;
const following = state.roomSlug === mainSlug;
const isMainHerself = state.user.id === state.mainUser.id;
if (isMainHerself && following) return null; // pointless when main controls main
return el('button', {
class: 'pill follow-pill' + (following ? ' active' : ''),
title: following ? `Following ${state.mainUser.username}'s group` : `Join ${state.mainUser.username}'s group (the house default)`,
onClick: () => { followMain(); }
}, following ? `◉ Following ${state.mainUser.username}` : `↗ Follow ${state.mainUser.username}`);
}
function renderAvatarPopover() {
const users = state.device.users || [];
return el('div', {
class: 'avatar-popover-wrap',
onClick: (e) => { if (e.target === e.currentTarget) { state.showAvatars = false; render(); } }
},
el('div', { class: 'avatar-popover card' },
el('div', { class: 'avatar-popover-head' },
el('h3', {}, 'Switch user'),
el('button', {
class: 'close', title: 'Close',
onClick: () => { state.showAvatars = false; render(); }
}, '×')
),
el('div', { class: 'avatar-list' }, ...users.map((u) => el('button', {
class: 'avatar-row' + (u.username === state.user.username ? ' active' : ''),
onClick: () => switchUser(u.username)
},
el('span', {
class: 'avatar lg',
style: u.avatar_color ? { background: u.avatar_color } : {}
}, u.avatar_emoji || u.username.slice(0, 1).toUpperCase()),
el('span', { class: 'avatar-name' },
u.username,
u.is_main ? el('span', { class: 'avatar-tag' }, ' ★ main') : null,
u.username === state.user.username ? el('span', { class: 'avatar-tag dim' }, ' (signed in)') : null
)
))),
el('div', { class: 'avatar-hint' },
'Add users via the admin panel → Trust device.')
)
);
}
function showLogin() {
clear(app);
app.appendChild(el('div', { class: 'login' },