Migrate to Vite + ES module architecture
Split monolithic app.js (~1850 lines) into maintainable ES modules: - src/state.js — shared mutable state (S object) - src/utils.js — md5, esc, formatDur, toast - src/api.js — Subsonic API, Navidrome REST, iTunes API - src/player.js — playback, transport, queue, media session, preview - src/views.js — navigation, page loaders, card makers, search - src/ui.js — all modals, overlays, sidebar, settings - src/pwa.js — service worker registration + update banner - src/main.js — app init, connect, window globals Updated Dockerfile to multi-stage (Node build → nginx serve). Static assets (sw.js, manifest.json, icon.svg) moved to public/. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
ce53c48835
commit
9aded56713
18 files changed
+3134
-2
No files matched your search
+354
@@ -0,0 +1,354 @@
|
||||
import { S } from './state.js';
|
||||
import { esc, formatDur, toast } from './utils.js';
|
||||
import { api, streamUrl, coverUrl, downloadUrl } from './api.js';
|
||||
// views.js circular import — safe because only used inside function bodies
|
||||
import { loadRecommendations } from './views.js';
|
||||
|
||||
// ─── PLAYBACK ───
|
||||
export function playQueue(songs, startIdx) {
|
||||
S.queue = songs.map(s => ({...s}));
|
||||
S.qIdx = startIdx;
|
||||
playCurrent();
|
||||
renderQueue();
|
||||
if(S.radioMode) fillRadioQueue();
|
||||
}
|
||||
|
||||
export function playCurrent() {
|
||||
if(S.qIdx < 0 || S.qIdx >= S.queue.length) return;
|
||||
const s = S.queue[S.qIdx];
|
||||
S.audio.src = streamUrl(s.id);
|
||||
S.audio.play();
|
||||
updatePlayerUI(s);
|
||||
renderQueue();
|
||||
}
|
||||
|
||||
export function updatePlayerUI(s) {
|
||||
document.getElementById('player-title').textContent = s.title;
|
||||
document.getElementById('player-artist-name').textContent = s.artist || '—';
|
||||
document.getElementById('player-album-sep').style.display = s.album ? '' : 'none';
|
||||
document.getElementById('player-album-name').textContent = s.album || '';
|
||||
const art = document.getElementById('player-art');
|
||||
const cv = coverUrl(s.coverArt, 100);
|
||||
art.innerHTML = cv ? `<img src="${cv}" style="width:100%;height:100%;object-fit:cover">` : '<div class="no-art">♪</div>';
|
||||
updateStarBtn();
|
||||
document.title = `${s.title} — NovaSonic`;
|
||||
updateMediaSession(s);
|
||||
if(document.getElementById('page-recommendations').classList.contains('active')) loadRecommendations();
|
||||
try {
|
||||
localStorage.setItem('ns_last_played', JSON.stringify({
|
||||
song: { id:s.id, title:s.title, artist:s.artist, album:s.album, albumId:s.albumId,
|
||||
artistId:s.artistId, coverArt:s.coverArt, duration:s.duration, _starred:s._starred||false },
|
||||
queue: S.queue.map(t => ({ id:t.id, title:t.title, artist:t.artist, album:t.album,
|
||||
albumId:t.albumId, artistId:t.artistId, coverArt:t.coverArt,
|
||||
duration:t.duration, _starred:t._starred||false })),
|
||||
qIdx: S.qIdx,
|
||||
}));
|
||||
} catch {}
|
||||
_syncNpDirect(s);
|
||||
}
|
||||
|
||||
export function _syncNpDirect(s) {
|
||||
if(!S.npOpen || !s) return;
|
||||
const cv = coverUrl(s.coverArt, 400);
|
||||
const cover = document.getElementById('np-cover');
|
||||
const bg = document.getElementById('np-bg');
|
||||
if(cover) cover.innerHTML = cv ? `<img src="${cv}" style="width:100%;height:100%;object-fit:cover">` : '<div class="no-art">♪</div>';
|
||||
if(bg) bg.style.backgroundImage = cv ? `url('${cv}')` : 'none';
|
||||
const t = document.getElementById('np-title'); if(t) t.textContent = s.title || '—';
|
||||
const an = document.getElementById('np-artist-name'); if(an) an.textContent = s.artist || '—';
|
||||
const asep = document.getElementById('np-album-sep'); if(asep) asep.style.display = s.album ? '' : 'none';
|
||||
const aln = document.getElementById('np-album-name'); if(aln) aln.textContent = s.album || '';
|
||||
syncNpStar();
|
||||
}
|
||||
|
||||
// ─── TRANSPORT ───
|
||||
export function togglePlay() { if(S.audio.src) S.audio.paused ? S.audio.play() : S.audio.pause(); }
|
||||
|
||||
export function setPlayIcon(playing) {
|
||||
document.getElementById('play-icon').innerHTML = playing
|
||||
? '<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>'
|
||||
: '<polygon points="5 3 19 12 5 21 5 3"/>';
|
||||
if(S.npOpen) {
|
||||
document.getElementById('np-play-icon').innerHTML = playing
|
||||
? '<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>'
|
||||
: '<polygon points="5 3 19 12 5 21 5 3"/>';
|
||||
const cover = document.getElementById('np-cover');
|
||||
if(cover) cover.classList.toggle('playing', playing);
|
||||
}
|
||||
}
|
||||
|
||||
export function prevSong() {
|
||||
if(S.audio.currentTime > 3) { S.audio.currentTime = 0; return; }
|
||||
if(S.qIdx > 0) { S.qIdx--; playCurrent(); }
|
||||
}
|
||||
|
||||
export function nextSong() {
|
||||
if(S.shuffle) S.qIdx = Math.floor(Math.random() * S.queue.length);
|
||||
else if(S.qIdx < S.queue.length - 1) S.qIdx++;
|
||||
else if(S.repeat) S.qIdx = 0;
|
||||
else if(S.radioMode) { fillRadioQueue().then(() => { if(S.qIdx < S.queue.length-1) { S.qIdx++; playCurrent(); } }); return; }
|
||||
else return;
|
||||
if(S.radioMode && S.queue.length - S.qIdx < 5) fillRadioQueue();
|
||||
playCurrent();
|
||||
}
|
||||
|
||||
export function onEnded() {
|
||||
if(S.repeat === 'one') { S.audio.currentTime = 0; S.audio.play(); return; }
|
||||
nextSong();
|
||||
}
|
||||
|
||||
export function toggleShuffle() {
|
||||
S.shuffle = !S.shuffle;
|
||||
document.getElementById('btn-shuffle').classList.toggle('active', S.shuffle);
|
||||
document.getElementById('np-shuffle-btn')?.classList.toggle('active', S.shuffle);
|
||||
document.getElementById('badge-shuffle')?.classList.toggle('on', S.shuffle);
|
||||
}
|
||||
|
||||
export function toggleRepeat() {
|
||||
S.repeat = S.repeat === false ? 'all' : S.repeat === 'all' ? 'one' : false;
|
||||
document.getElementById('btn-repeat').classList.toggle('active', S.repeat !== false);
|
||||
document.getElementById('btn-repeat').classList.toggle('repeat-one', S.repeat === 'one');
|
||||
const nb = document.getElementById('np-repeat-btn');
|
||||
if(nb) { nb.classList.toggle('active', S.repeat !== false); nb.classList.toggle('repeat-one', S.repeat === 'one'); }
|
||||
const badge = document.getElementById('badge-repeat');
|
||||
if(badge) { badge.classList.toggle('on', S.repeat !== false); badge.textContent = S.repeat === 'one' ? '🔂 Einmal' : '🔁 Repeat'; }
|
||||
}
|
||||
|
||||
// ─── RADIO ───
|
||||
export function _applyRadioBtn() {
|
||||
const btn = document.getElementById('btn-radio-mode');
|
||||
if(btn) { btn.classList.toggle('active', S.radioMode); btn.style.color = S.radioMode ? 'var(--blue)' : ''; }
|
||||
const nb = document.getElementById('np-radio-btn');
|
||||
if(nb) { nb.classList.toggle('active', S.radioMode); nb.style.color = S.radioMode ? 'var(--blue)' : ''; }
|
||||
}
|
||||
|
||||
export async function toggleRadioMode() {
|
||||
S.radioMode = !S.radioMode;
|
||||
localStorage.setItem('ns_radio', S.radioMode ? '1' : '0');
|
||||
_applyRadioBtn();
|
||||
if(S.radioMode) await fillRadioQueue();
|
||||
}
|
||||
|
||||
export async function fillRadioQueue() {
|
||||
if(!S.radioMode) return;
|
||||
try {
|
||||
const r = await api('getRandomSongs', '&size=20');
|
||||
S.queue.push(...(r.randomSongs?.song || []));
|
||||
renderQueue();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// ─── PROGRESS & SCRUBBING ───
|
||||
export function updateProgress() {
|
||||
if(!S.audio.duration || S._scrubbing) return;
|
||||
syncMediaSessionPosition();
|
||||
const p = (S.audio.currentTime / S.audio.duration) * 100;
|
||||
document.getElementById('progress-fill').style.width = p + '%';
|
||||
document.getElementById('time-cur').textContent = formatDur(S.audio.currentTime);
|
||||
document.getElementById('time-total').textContent = formatDur(S.audio.duration);
|
||||
if(S.npOpen) {
|
||||
const fill = document.getElementById('np-fill');
|
||||
const cur = document.getElementById('np-cur');
|
||||
const tot = document.getElementById('np-tot');
|
||||
if(fill) fill.style.width = p + '%';
|
||||
if(cur) cur.textContent = formatDur(S.audio.currentTime);
|
||||
if(tot) tot.textContent = formatDur(S.audio.duration);
|
||||
}
|
||||
}
|
||||
|
||||
export function seekTo(e) {
|
||||
const bar = document.getElementById('progress-bar');
|
||||
const rect = bar.getBoundingClientRect();
|
||||
S.audio.currentTime = ((e.clientX - rect.left) / rect.width) * S.audio.duration;
|
||||
}
|
||||
|
||||
export function initProgressScrub() {
|
||||
_initBarScrub(
|
||||
document.getElementById('progress-bar'),
|
||||
document.getElementById('progress-fill'),
|
||||
pos => { document.getElementById('time-cur').textContent = formatDur(pos * S.audio.duration); }
|
||||
);
|
||||
_initBarScrub(
|
||||
document.getElementById('np-bar'),
|
||||
document.getElementById('np-fill'),
|
||||
pos => { const el = document.getElementById('np-cur'); if(el) el.textContent = formatDur(pos * S.audio.duration); }
|
||||
);
|
||||
}
|
||||
|
||||
function _initBarScrub(bar, fill, onMove) {
|
||||
if(!bar || !fill) return;
|
||||
function getPos(clientX) { const r = bar.getBoundingClientRect(); return Math.max(0, Math.min(1, (clientX-r.left)/r.width)); }
|
||||
function startScrub(pos) { S._scrubbing=true; fill.style.transition='none'; fill.style.width=(pos*100)+'%'; onMove(pos); }
|
||||
function moveScrub(pos) { fill.style.width=(pos*100)+'%'; onMove(pos); }
|
||||
function endScrub(pos) { S._scrubbing=false; fill.style.transition=''; if(S.audio.duration) S.audio.currentTime=pos*S.audio.duration; }
|
||||
bar.addEventListener('touchstart', e => { startScrub(getPos(e.touches[0].clientX)); e.stopPropagation(); }, {passive:true});
|
||||
bar.addEventListener('touchmove', e => { if(S._scrubbing) moveScrub(getPos(e.touches[0].clientX)); }, {passive:true});
|
||||
bar.addEventListener('touchend', e => { if(S._scrubbing) endScrub(getPos(e.changedTouches[0].clientX)); }, {passive:true});
|
||||
bar.addEventListener('mousedown', e => {
|
||||
startScrub(getPos(e.clientX)); e.preventDefault();
|
||||
const mm = e2 => { if(S._scrubbing) moveScrub(getPos(e2.clientX)); };
|
||||
const mu = e2 => { if(S._scrubbing) endScrub(getPos(e2.clientX)); document.removeEventListener('mousemove',mm); document.removeEventListener('mouseup',mu); };
|
||||
document.addEventListener('mousemove', mm);
|
||||
document.addEventListener('mouseup', mu);
|
||||
});
|
||||
}
|
||||
|
||||
export function setVolume(v) { S.audio.volume = v/100; S.previewAudio.volume = v/100; }
|
||||
|
||||
// ─── MEDIA SESSION ───
|
||||
export function updateMediaSession(s) {
|
||||
if(!navigator.mediaSession) return;
|
||||
const artwork = s.coverArt ? [
|
||||
{ src: coverUrl(s.coverArt,96), sizes:'96x96', type:'image/jpeg' },
|
||||
{ src: coverUrl(s.coverArt,300), sizes:'300x300', type:'image/jpeg' },
|
||||
{ src: coverUrl(s.coverArt,512), sizes:'512x512', type:'image/jpeg' },
|
||||
] : [];
|
||||
navigator.mediaSession.metadata = new MediaMetadata({ title:s.title, artist:s.artist||'', album:s.album||'', artwork });
|
||||
navigator.mediaSession.setActionHandler('play', togglePlay);
|
||||
navigator.mediaSession.setActionHandler('pause', togglePlay);
|
||||
navigator.mediaSession.setActionHandler('previoustrack', prevSong);
|
||||
navigator.mediaSession.setActionHandler('nexttrack', nextSong);
|
||||
navigator.mediaSession.setActionHandler('seekbackward', d => { S.audio.currentTime = Math.max(0, S.audio.currentTime-(d.seekOffset||10)); });
|
||||
navigator.mediaSession.setActionHandler('seekforward', d => { S.audio.currentTime = Math.min(S.audio.duration||0, S.audio.currentTime+(d.seekOffset||10)); });
|
||||
navigator.mediaSession.setActionHandler('seekto', d => { if(d.seekTime!=null) S.audio.currentTime = d.seekTime; });
|
||||
}
|
||||
|
||||
export function syncMediaSessionPosition() {
|
||||
if(!navigator.mediaSession?.setPositionState || !S.audio.duration || isNaN(S.audio.duration)) return;
|
||||
const now = Date.now();
|
||||
if(now - S._msPosLast < 1000) return;
|
||||
S._msPosLast = now;
|
||||
try { navigator.mediaSession.setPositionState({ duration:S.audio.duration, playbackRate:S.audio.playbackRate||1, position:Math.min(S.audio.currentTime, S.audio.duration) }); } catch {}
|
||||
}
|
||||
|
||||
// ─── STAR ───
|
||||
export async function toggleStar(song, btn) {
|
||||
try {
|
||||
await api(song._starred ? 'unstar' : 'star', `&id=${song.id}`);
|
||||
song._starred = !song._starred;
|
||||
if(btn) {
|
||||
btn.classList.toggle('starred', song._starred);
|
||||
btn.querySelector('svg')?.setAttribute('fill', song._starred ? 'currentColor' : 'none');
|
||||
}
|
||||
if(S.queue[S.qIdx]?.id === song.id) updateStarBtn();
|
||||
} catch(e) { toast('Fehler: ' + e.message); }
|
||||
}
|
||||
|
||||
export function starCurrent() {
|
||||
if(S.qIdx < 0 || !S.queue[S.qIdx]) return;
|
||||
toggleStar(S.queue[S.qIdx], document.getElementById('btn-star-current'));
|
||||
}
|
||||
|
||||
export function updateStarBtn() {
|
||||
const s = S.queue[S.qIdx];
|
||||
const icon = document.getElementById('star-icon');
|
||||
if(!icon) return;
|
||||
const isStarred = s && (s._starred || s.starred);
|
||||
icon.setAttribute('fill', isStarred ? 'var(--accent)' : 'none');
|
||||
icon.setAttribute('stroke', isStarred ? 'var(--accent)' : 'var(--text3)');
|
||||
}
|
||||
|
||||
export function syncNpStar() {
|
||||
if(!S.npOpen) return;
|
||||
const s = S.queue[S.qIdx];
|
||||
const icon = document.getElementById('np-star-icon');
|
||||
if(!icon || !s) return;
|
||||
const starred = s._starred || s.starred;
|
||||
icon.setAttribute('fill', starred ? 'var(--accent)' : 'none');
|
||||
icon.setAttribute('stroke', starred ? 'var(--accent)' : 'rgba(255,255,255,.5)');
|
||||
}
|
||||
|
||||
export function npToggleStar() {
|
||||
const s = S.queue[S.qIdx];
|
||||
if(!s) return;
|
||||
api(s._starred || s.starred ? 'unstar' : 'star', `&id=${s.id}`)
|
||||
.then(() => { s._starred = !(s._starred || s.starred); s.starred = null; syncNpStar(); updateStarBtn(); })
|
||||
.catch(e => toast('Fehler: ' + e.message));
|
||||
}
|
||||
|
||||
// ─── QUEUE PANEL ───
|
||||
export function renderQueue() {
|
||||
const el = document.getElementById('queue-list');
|
||||
el.innerHTML = '';
|
||||
if(!S.queue.length) { el.innerHTML='<div class="empty-state" style="padding:40px 16px"><div class="icon">🎵</div><p>Leer</p></div>'; return; }
|
||||
S.queue.forEach((s, i) => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'queue-item' + (i === S.qIdx ? ' active' : '');
|
||||
item.innerHTML = `<div class="qi-idx">${i+1}</div><div class="qi-info"><div class="qi-title">${esc(s.title)}</div><div class="qi-artist">${esc(s.artist||'')}</div></div>`;
|
||||
item.onclick = () => { S.qIdx = i; playCurrent(); };
|
||||
el.appendChild(item);
|
||||
});
|
||||
el.querySelector('.active')?.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
export function toggleQueue() {
|
||||
S.queueOpen = !S.queueOpen;
|
||||
document.getElementById('queue-panel').classList.toggle('open', S.queueOpen);
|
||||
if(S.queueOpen) renderQueue();
|
||||
}
|
||||
|
||||
// ─── DOWNLOAD ───
|
||||
export function dlSongLocal(s) {
|
||||
const a = document.createElement('a');
|
||||
a.href = downloadUrl(s.id);
|
||||
a.download = `${s.artist||'Unknown'} - ${s.title}.${s.suffix||'mp3'}`;
|
||||
document.body.appendChild(a); a.click(); document.body.removeChild(a);
|
||||
toast(`⬇ ${s.title}`);
|
||||
}
|
||||
|
||||
export function downloadCurrent() {
|
||||
if(S.qIdx >= 0 && S.queue[S.qIdx]) dlSongLocal(S.queue[S.qIdx]);
|
||||
}
|
||||
|
||||
// ─── PREVIEW ───
|
||||
export function playPreview(track) {
|
||||
if(!track.previewUrl) { toast('Kein Preview verfügbar'); return; }
|
||||
const wasPlaying = !S.audio.paused;
|
||||
if(wasPlaying) S.audio.pause();
|
||||
S.previewCurrent = track;
|
||||
S.previewCurrent._resumeMain = wasPlaying;
|
||||
S.previewAudio.volume = S.audio.volume;
|
||||
S.previewAudio.src = track.previewUrl;
|
||||
S.previewAudio.play();
|
||||
document.getElementById('preview-title').innerHTML = esc(track.trackName||'—') + '<span class="preview-badge">30s Preview</span>';
|
||||
document.getElementById('preview-sub').textContent = (track.artistName||'') + (track.collectionName?' · '+track.collectionName:'');
|
||||
const art = track.artworkUrl100 || track.artworkUrl60 || '';
|
||||
document.getElementById('preview-art').innerHTML = art ? `<img src="${art}" style="width:100%;height:100%;object-fit:cover">` : '<div class="no-art" style="font-size:16px">♪</div>';
|
||||
document.getElementById('preview-bar').classList.add('visible');
|
||||
document.getElementById('preview-fill').style.width = '0%';
|
||||
}
|
||||
|
||||
export function stopPreview(resume) {
|
||||
const shouldResume = resume !== false && S.previewCurrent?._resumeMain;
|
||||
S.previewAudio.pause(); S.previewAudio.src = '';
|
||||
document.getElementById('preview-bar').classList.remove('visible');
|
||||
document.getElementById('preview-fill').style.width = '0%';
|
||||
S.previewCurrent = null;
|
||||
if(shouldResume && S.audio.src) S.audio.play();
|
||||
}
|
||||
|
||||
export function updatePreviewProgress() {
|
||||
if(!S.previewAudio.duration) return;
|
||||
document.getElementById('preview-fill').style.width = (S.previewAudio.currentTime / S.previewAudio.duration * 100) + '%';
|
||||
}
|
||||
|
||||
// ─── RESTORE LAST PLAYED ───
|
||||
export function _restoreLastPlayed() {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem('ns_last_played') || 'null');
|
||||
if(!saved || !saved.song) return;
|
||||
S.queue = saved.queue || [saved.song];
|
||||
S.qIdx = saved.qIdx || 0;
|
||||
const s = S.queue[S.qIdx];
|
||||
if(!s) return;
|
||||
document.getElementById('player-title').textContent = s.title || '—';
|
||||
document.getElementById('player-artist-name').textContent = s.artist || '—';
|
||||
document.getElementById('player-album-sep').style.display = s.album ? '' : 'none';
|
||||
document.getElementById('player-album-name').textContent = s.album || '';
|
||||
const art = document.getElementById('player-art');
|
||||
const cv = coverUrl(s.coverArt, 100);
|
||||
art.innerHTML = cv ? `<img src="${cv}" style="width:100%;height:100%;object-fit:cover">` : '<div class="no-art">♪</div>';
|
||||
updateStarBtn();
|
||||
document.title = `${s.title} — NovaSonic`;
|
||||
} catch {}
|
||||
}
|
||||
Reference in new issue
Block a user