-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.js
More file actions
2394 lines (2074 loc) · 85.7 KB
/
Copy pathui.js
File metadata and controls
2394 lines (2074 loc) · 85.7 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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ui.js — Final UI Controller
*
* Features:
* • Custom cursor with hover states
* • 3D card tilt on mouse move
* • Ripple effect on buttons
* • Intersection Observer scroll reveals
* • Now Playing fullscreen overlay
* • Queue panel
* • Keyboard shortcuts modal
* • Scroll-to-top
* • Ambient glow
* • Duration badges on cards
*/
import * as Player from './player.js';
import * as Storage from './storage.js';
import * as Api from './api.js';
import * as Vis from './visualizer.js';
const $ = (s) => document.querySelector(s);
const $$ = (s) => document.querySelectorAll(s);
/* ── DOM Refs ── */
const viewHome = $('#view-home');
const viewSearch = $('#view-search');
const viewLiked = $('#view-liked');
const viewPlaylists = $('#view-playlists');
const viewHistory = $('#view-history');
const viewDetail = $('#view-detail');
const searchInput = $('#search-input');
const searchResultsTitle = $('#search-results-title');
const searchResultsGrid = $('#search-results-grid');
const likedGrid = $('#liked-songs-grid');
const likedEmpty = $('#liked-empty');
const historyGrid = $('#history-grid');
const historyEmpty = $('#history-empty');
const playerSong = $('#player-song');
const playerArtist = $('#player-artist');
const playerArt = $('#player-art');
const artWrap = $('.player-bar__art-wrap');
const playerLikeBtn = $('#player-like-btn');
const playerLikeIcon = $('#player-like-icon');
const playerDlBtn = $('#player-dl-btn');
const btnHome = $('#btn-home');
const btnLiked = $('#btn-liked');
const btnPlaylists = $('#btn-playlists');
const btnHistory = $('#btn-history');
const toastBox = $('#toast-container');
const ambientGlow = $('#ambient-glow');
/* ── State ── */
let currentSearchQuery = '';
let currentSearchPage = 1;
let isFetchingMore = false;
let currentPlaylistSong = null; // For modal
/* HELPERS */
function decode(str) {
const t = document.createElement('textarea');
t.innerHTML = str || '';
return t.value;
}
function escapeHTML(str) {
return String(str).replace(/[&<>'"]/g, tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag));
}
function fmtTime(s) {
if (!s || isNaN(s)) return '0:00';
const m = Math.floor(s / 60);
return `${m}:${Math.floor(s % 60).toString().padStart(2, '0')}`;
}
function fmtDuration(sec) {
if (!sec) return '';
return fmtTime(sec);
}
/* ── Custom Confirm (replaces native confirm() blocked by Chrome) ── */
function showConfirm(title, message, confirmLabel = 'Delete') {
return new Promise((resolve) => {
const modal = $('#confirm-modal');
const titleEl = $('#confirm-title');
const msgEl = $('#confirm-message');
const okBtn = $('#confirm-ok');
const cancelBtn = $('#confirm-cancel');
if (!modal) { resolve(false); return; }
titleEl.textContent = title;
msgEl.textContent = message;
okBtn.textContent = confirmLabel;
modal.classList.remove('hidden');
function cleanup(result) {
modal.classList.add('hidden');
okBtn.removeEventListener('click', onOk);
cancelBtn.removeEventListener('click', onCancel);
modal.removeEventListener('click', onBackdrop);
resolve(result);
}
function onOk() { cleanup(true); }
function onCancel() { cleanup(false); }
function onBackdrop(e) { if (e.target === modal) cleanup(false); }
okBtn.addEventListener('click', onOk);
cancelBtn.addEventListener('click', onCancel);
modal.addEventListener('click', onBackdrop);
});
}
/* ── Toast ── */
export function showToast(msg, icon = 'ph ph-check-circle') {
const t = document.createElement('div');
t.className = 'toast';
t.innerHTML = `<i class="${icon}"></i><span>${escapeHTML(msg)}</span>`;
toastBox.appendChild(t);
setTimeout(() => {
t.classList.add('toast--removing');
t.addEventListener('animationend', () => t.remove());
}, 3000);
}
/* ── Download ── */
async function downloadSong(song, btn = null) {
if (!song?.streamUrl) { showToast('No download URL', 'ph ph-warning-circle'); return; }
const name = decode(song.title).replace(/[<>:"/\\|?*]+/g, '').trim();
const art = decode(song.artist).replace(/[<>:"/\\|?*]+/g, '').trim();
const file = `${name} - ${art}.m4a`;
if (btn) { btn.classList.add('downloading'); const i = btn.querySelector('i'); if (i) i.className = 'ph ph-spinner'; }
showToast(`Downloading…`, 'ph ph-download-simple');
try {
const res = await fetch(song.streamUrl, { mode: 'cors' });
if (!res.ok) throw 0;
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = file;
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(url), 5000);
showToast('Downloaded ✓', 'ph ph-check-circle');
} catch {
const a = document.createElement('a');
a.href = song.streamUrl; a.download = file; a.target = '_blank'; a.rel = 'noopener';
document.body.appendChild(a); a.click(); a.remove();
showToast('Opened in new tab — save from there', 'ph ph-arrow-square-out');
} finally {
if (btn) { btn.classList.remove('downloading'); const i = btn.querySelector('i'); if (i) i.className = 'ph ph-download-simple'; }
}
}
/* ── Bulk Download All Songs in Playlist ── */
let isBulkDownloading = false;
async function bulkDownloadPlaylist(songs, playlistName, btn) {
if (isBulkDownloading) {
showToast('A bulk download is already in progress', 'ph ph-warning-circle');
return;
}
if (!songs?.length) {
showToast('Playlist is empty', 'ph ph-warning-circle');
return;
}
isBulkDownloading = true;
const icon = btn.querySelector('i');
const label = btn.querySelector('span');
btn.classList.add('downloading');
if (icon) icon.className = 'ph ph-spinner';
const total = songs.length;
let success = 0;
let failed = 0;
showToast(`Starting bulk download of ${total} songs…`, 'ph ph-download-simple');
for (let i = 0; i < total; i++) {
const song = songs[i];
if (label) label.textContent = `${i + 1}/${total}`;
if (!song?.streamUrl) { failed++; continue; }
const name = decode(song.title).replace(/[<>:"/\\|?*]+/g, '').trim();
const art = decode(song.artist).replace(/[<>:"/\\|?*]+/g, '').trim();
const file = `${name} - ${art}.m4a`;
try {
const res = await fetch(song.streamUrl, { mode: 'cors' });
if (!res.ok) throw 0;
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = file;
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(url), 5000);
success++;
} catch {
const a = document.createElement('a');
a.href = song.streamUrl; a.download = file; a.target = '_blank'; a.rel = 'noopener';
document.body.appendChild(a); a.click(); a.remove();
success++;
}
// Small delay between downloads so the browser doesn't choke
if (i < total - 1) await new Promise(r => setTimeout(r, 1200));
}
btn.classList.remove('downloading');
if (icon) icon.className = 'ph ph-download-simple';
if (label) label.textContent = 'Download All';
isBulkDownloading = false;
if (failed > 0) {
showToast(`Downloaded ${success}/${total} songs (${failed} failed)`, 'ph ph-warning-circle');
} else {
showToast(`All ${total} songs downloaded ✓`, 'ph ph-check-circle');
}
}
/* ── Ambient Glow ── */
function updateGlow(img) {
if (!ambientGlow) return;
if (!img) { ambientGlow.classList.remove('active'); return; }
ambientGlow.style.background = `url("${img}") center/cover no-repeat`;
ambientGlow.classList.add('active');
}
/* ── Dynamic Colors ── */
function extractAndSetColors(url) {
if (!url || typeof ColorThief === 'undefined') return;
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = url;
img.onload = () => {
try {
const ct = new ColorThief();
const palette = ct.getPalette(img, 3);
if (palette && palette.length >= 3) {
document.documentElement.style.setProperty('--accent', `rgb(${palette[0].join(',')})`);
document.documentElement.style.setProperty('--pink', `rgb(${palette[1].join(',')})`);
document.documentElement.style.setProperty('--sky', `rgb(${palette[2].join(',')})`);
}
} catch (e) {
console.warn("ColorThief failed or canvas tainted", e);
}
};
}
/* Custom cursor removed — native cursor is smoother */
/* RIPPLE EFFECT */
function addRipple(el, e) {
const rect = el.getBoundingClientRect();
const ripple = document.createElement('span');
const size = Math.max(rect.width, rect.height);
ripple.className = 'ripple';
ripple.style.width = ripple.style.height = size + 'px';
ripple.style.left = (e.clientX - rect.left - size / 2) + 'px';
ripple.style.top = (e.clientY - rect.top - size / 2) + 'px';
el.appendChild(ripple);
ripple.addEventListener('animationend', () => ripple.remove());
}
/* 3D CARD TILT */
function initCardTilt(card) {
card.addEventListener('mousemove', (e) => {
const rect = card.getBoundingClientRect();
const x = (e.clientX - rect.left) / rect.width - 0.5;
const y = (e.clientY - rect.top) / rect.height - 0.5;
card.style.transform = `perspective(600px) rotateY(${x * 12}deg) rotateX(${-y * 12}deg) translateY(-4px)`;
});
card.addEventListener('mouseleave', () => {
card.style.transform = '';
});
}
/* SCROLL REVEAL */
function initReveal() {
const observer = new IntersectionObserver((entries) => {
entries.forEach(en => {
if (en.isIntersecting) {
en.target.classList.add('visible');
observer.unobserve(en.target);
}
});
}, { threshold: 0.1 });
$$('.reveal').forEach(el => observer.observe(el));
}
/* SCROLL TO TOP */
function initScrollTop() {
const btn = $('#scroll-top');
if (!btn) return;
window.addEventListener('scroll', () => {
btn.classList.toggle('hidden', window.scrollY < 400);
});
btn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
/* SONG CARD */
function renderArtistsHtml(artists) {
if (!artists || !artists.length) return '<span>Unknown Artist</span>';
return artists.map(a =>
a.id ? `<span class="artist-link" data-id="${a.id}">${decode(a.name)}</span>` : `<span>${decode(a.name)}</span>`
).join(', ');
}
function attachArtistLinks(container) {
container.querySelectorAll('.artist-link').forEach(link => {
link.addEventListener('click', (e) => {
e.stopPropagation();
openArtist(link.dataset.id);
if (document.body.classList.contains('np-active')) {
document.body.classList.remove('np-active');
}
if ($('#queue-panel') && !$('#queue-panel').classList.contains('hidden')) {
$('#queue-panel').classList.add('hidden');
}
});
});
}
function createAlbumCard(album) {
const card = document.createElement('div');
card.className = 'album-card';
const imgStr = (Array.isArray(album.image) && album.image.length > 0) ?
(album.image.find(i => i.quality === '150x150')?.url || album.image[album.image.length - 1].url) :
(typeof album.image === 'string' ? album.image : '');
card.innerHTML = `
<div class="album-card__img-wrap">
<img src="${imgStr}" loading="lazy" alt="Cover" />
</div>
<div class="album-card__title" title="${decode(album.title || album.name)}">${decode(album.title || album.name)}</div>
<div class="album-card__artist">${decode(album.description || album.language || 'Album')}</div>
`;
card.addEventListener('click', () => openAlbum(album.id));
return card;
}
function createArtistCard(artist) {
const card = document.createElement('div');
card.className = 'artist-card';
const imgStr = (Array.isArray(artist.image) && artist.image.length > 0) ?
(artist.image.find(i => i.quality === '150x150')?.url || artist.image[artist.image.length - 1].url) :
(typeof artist.image === 'string' ? artist.image : '');
card.innerHTML = `
<div class="artist-card__img-wrap">
<img src="${imgStr}" loading="lazy" alt="Artist" />
</div>
<div class="artist-card__name" title="${decode(artist.title || artist.name)}">${decode(artist.title || artist.name)}</div>
`;
card.addEventListener('click', () => openArtist(artist.id));
return card;
}
function createSongCard(song, list, idx, playlistId = null) {
const card = document.createElement('div');
card.className = 'song-card';
card.dataset.songId = song.id;
const liked = Storage.isLiked(song.id);
const dur = fmtDuration(song.duration);
card.innerHTML = `
<div class="song-card__img-wrap">
<img class="song-card__img" src="${song.image}" alt="${decode(song.title)}"
loading="lazy" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22200%22 height=%22200%22%3E%3Crect width=%22200%22 height=%22200%22 fill=%22%23181822%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%23444%22 font-size=%2250%22%3E♫%3C/text%3E%3C/svg%3E'" />
<div class="song-card__overlay">
<button class="song-card__play-btn" aria-label="Play"><i class="ph-fill ph-play"></i></button>
</div>
${dur ? `<span class="song-card__duration">${dur}</span>` : ''}
<button class="song-card__like-btn ${liked ? 'liked' : ''}" aria-label="Like"><i class="${liked ? 'ph-fill' : 'ph'} ph-heart"></i></button>
<button class="song-card__playlist-btn" aria-label="${playlistId ? 'Remove from Playlist' : 'Add to Playlist'}"><i class="${playlistId ? 'ph-bold ph-minus' : 'ph-bold ph-plus'}"></i></button>
<button class="song-card__share-btn" aria-label="Share Song"><i class="ph ph-share-network"></i></button>
<button class="song-card__dl-btn" aria-label="Download"><i class="ph ph-download-simple"></i></button>
</div>
<div class="song-card__info">
<div class="song-card__title${song.albumId ? ' clickable' : ''}" title="${decode(song.title)}">${decode(song.title)}</div>
<div class="song-card__artist" title="${decode(song.artist)}">${renderArtistsHtml(song.artists)}</div>
</div>
`;
// Play
const play = () => Player.playSong(song, list, idx);
card.querySelector('.song-card__play-btn').addEventListener('click', (e) => { addRipple(e.currentTarget, e); play(); });
card.addEventListener('click', (e) => {
if (e.target.closest('button')) return;
play();
});
// Navigate to Album / Artist
const titleEl = card.querySelector('.song-card__title');
if (song.albumId) {
titleEl.addEventListener('click', (e) => {
e.stopPropagation();
openAlbum(song.albumId);
});
}
attachArtistLinks(card);
// Like
card.querySelector('.song-card__like-btn').addEventListener('click', (e) => {
e.stopPropagation();
const l = Storage.toggleLike(song);
syncCardLike(card, l);
syncPlayerLike();
showToast(l ? `Liked "${decode(song.title)}"` : 'Removed', l ? 'ph-fill ph-heart' : 'ph ph-heart-break');
});
// Playlist Add / Remove
card.querySelector('.song-card__playlist-btn').addEventListener('click', (e) => {
e.stopPropagation();
if (playlistId) {
if (Storage.removeFromPlaylist(playlistId, song.id)) {
showToast('Removed from playlist', 'ph ph-trash');
showPlaylists();
}
} else {
openPlaylistModal(song);
}
});
// Share
card.querySelector('.song-card__share-btn').addEventListener('click', (e) => {
e.stopPropagation();
const url = `${window.location.origin}/track/${song.id}`;
navigator.clipboard.writeText(url).then(() => {
showToast('Link copied to clipboard!', 'ph ph-link');
});
});
// Download
const dlBtn = card.querySelector('.song-card__dl-btn');
dlBtn.addEventListener('click', (e) => { e.stopPropagation(); downloadSong(song, dlBtn); });
// 3D tilt
initCardTilt(card);
return card;
}
function syncCardLike(card, liked) {
const btn = card.querySelector('.song-card__like-btn');
const ico = btn?.querySelector('i');
if (!btn || !ico) return;
btn.classList.toggle('liked', liked);
ico.className = liked ? 'ph-fill ph-heart' : 'ph ph-heart';
}
/* RENDER */
export function renderSongRow(container, songs) {
container.innerHTML = '';
if (!songs?.length) {
container.innerHTML = '<p style="color:var(--text-muted);padding:8px;font-size:0.8rem;">No songs found</p>';
return;
}
const frag = document.createDocumentFragment();
songs.forEach((s, i) => frag.appendChild(createSongCard(s, songs, i)));
container.appendChild(frag);
highlightPlaying();
}
/* Append more songs to an existing horizontal row (infinite scroll) */
export function appendSongRow(container, songs) {
if (!songs?.length || !container) return;
const existing = container.querySelectorAll('.song-card');
const offset = existing.length;
// Build a combined list for context (existing ids + new)
const allSongs = [...songs]; // new songs form their own mini-list for now
const frag = document.createDocumentFragment();
songs.forEach((s, i) => frag.appendChild(createSongCard(s, allSongs, i)));
container.appendChild(frag);
highlightPlaying();
}
/* VIEW MANAGEMENT */
function hideAll() {
[viewHome, viewSearch, viewLiked, viewPlaylists, viewHistory, viewDetail].forEach(v => v?.classList.add('hidden'));
btnHome?.classList.remove('active');
// Clean up artist infinite scroll if active
if (typeof cleanupArtistObserver === 'function') cleanupArtistObserver();
// Close settings if navigating
$('#settings-panel')?.classList.add('hidden');
}
export function showHome() {
hideAll();
viewHome.classList.remove('hidden');
btnHome.classList.add('active');
searchInput.value = '';
initReveal();
}
let searchObserver = null;
export function showSearchResults(results, query, isAppend = false) {
hideAll();
viewSearch.classList.remove('hidden');
searchResultsTitle.textContent = `Results for "${query}"`;
const wrapper = $('#search-content-wrapper');
if (!isAppend) {
wrapper.innerHTML = '';
currentSearchQuery = query;
currentSearchPage = 1;
isFetchingMore = false;
}
// Actually results comes in as { songs, albums, artists } from searchAll
const isEmpty = (!results || (!results.songs?.length && !results.albums?.length && !results.artists?.length));
if (isEmpty) {
if (!isAppend) {
$('#search-empty').classList.remove('hidden');
}
$('#search-loading-spinner')?.classList.add('hidden');
return;
}
$('#search-empty').classList.add('hidden');
if (results.songs?.length) {
let s = isAppend ? wrapper.querySelector('#search-songs-scroll') : null;
if (!s) {
const sec = document.createElement('div');
sec.className = 'search-section';
sec.innerHTML = `<h3 class="search-section-title">Songs</h3><div class="search-h-scroll" id="search-songs-scroll"></div>`;
wrapper.appendChild(sec);
s = sec.querySelector('#search-songs-scroll');
}
results.songs.forEach((song, i) => s.appendChild(createSongCard(song, results.songs, i)));
}
if (results.albums?.length && !isAppend) {
const sec = document.createElement('div');
sec.className = 'search-section';
sec.innerHTML = `<h3 class="search-section-title">Albums</h3><div class="search-h-scroll" id="search-albums-scroll"></div>`;
wrapper.appendChild(sec);
const s = sec.querySelector('#search-albums-scroll');
results.albums.forEach(album => s.appendChild(createAlbumCard(album)));
}
if (results.artists?.length && !isAppend) {
const sec = document.createElement('div');
sec.className = 'search-section';
sec.innerHTML = `<h3 class="search-section-title">Artists</h3><div class="search-h-scroll" id="search-artists-scroll"></div>`;
wrapper.appendChild(sec);
const s = sec.querySelector('#search-artists-scroll');
results.artists.forEach(artist => s.appendChild(createArtistCard(artist)));
}
// Show spinner and mount observer for infinite scrolling Songs
const spinner = $('#search-loading-spinner');
if (spinner && results.songs?.length) {
spinner.classList.remove('hidden');
if (!searchObserver) {
searchObserver = new IntersectionObserver(async (entries) => {
if (entries[0].isIntersecting && !isFetchingMore && currentSearchQuery) {
isFetchingMore = true;
currentSearchPage++;
// When paginating, we only care about songs, so searchSongs directly.
const nextSongs = await Api.searchSongs(currentSearchQuery, 20, currentSearchPage);
if (nextSongs?.length) {
// fake the searchAll object structure for appending
showSearchResults({ songs: nextSongs, albums: [], artists: [] }, currentSearchQuery, true);
} else {
spinner.classList.add('hidden'); // no more results
}
isFetchingMore = false;
}
}, { rootMargin: '100px' });
searchObserver.observe(spinner);
}
}
}
function showLiked() {
hideAll();
viewLiked.classList.remove('hidden');
btnLiked.classList.add('active');
const liked = Storage.getLiked();
likedGrid.innerHTML = '';
if (!liked.length) { likedEmpty.classList.remove('hidden'); return; }
likedEmpty.classList.add('hidden');
liked.forEach((s, i) => likedGrid.appendChild(createSongCard(s, liked, i)));
}
function showHistory() {
hideAll();
viewHistory.classList.remove('hidden');
btnHistory.classList.add('active');
const hist = Storage.getHistory();
historyGrid.innerHTML = '';
if (!hist.length) { historyEmpty.classList.remove('hidden'); return; }
historyEmpty.classList.add('hidden');
hist.forEach((s, i) => historyGrid.appendChild(createSongCard(s, hist, i)));
}
function showPlaylists() {
hideAll();
viewPlaylists.classList.remove('hidden');
btnPlaylists.classList.add('active');
const pContainer = $('#playlists-container');
const emptyState = $('#playlists-empty');
const pList = Storage.getPlaylists();
pContainer.innerHTML = '';
if (!pList.length) {
emptyState.classList.remove('hidden');
return;
}
emptyState.classList.add('hidden');
pList.forEach(p => {
// Render Playlist Header
const hdr = document.createElement('div');
hdr.style.marginBottom = '20px';
hdr.style.display = 'flex';
hdr.style.alignItems = 'center';
hdr.style.gap = '12px';
hdr.innerHTML = `
<h3 style="font-family: var(--font-display); font-size: 1.2rem; margin: 0;">${escapeHTML(decode(p.name))}</h3>
<span style="font-size:0.75rem; color:var(--text-muted);">${p.songs.length} songs</span>
<button class="playlist-share-btn" data-id="${p.id}" title="Share Playlist" style="background:rgba(255,255,255,0.05); border:none; border-radius:6px; padding:6px 8px; color:#fff; cursor:pointer; display:inline-flex; align-items:center; gap:4px; transition: background 0.2s;" aria-label="Share Playlist"><i class="ph ph-share-network"></i></button>
<button class="playlist-dl-all-btn" data-id="${p.id}" title="Download All Songs" style="background: linear-gradient(135deg, rgba(var(--accent-rgb, 139,92,246), 0.15), rgba(var(--accent-rgb, 139,92,246), 0.05)); border:1px solid rgba(var(--accent-rgb, 139,92,246), 0.25); border-radius:6px; padding:6px 12px; color:#fff; cursor:pointer; display:inline-flex; align-items:center; gap:6px; font-size:0.75rem; font-weight:500; transition: all 0.2s;" aria-label="Download All Songs">
<i class="ph ph-download-simple"></i>
<span>Download All</span>
</button>
<button class="playlist-delete-btn" data-id="${p.id}" title="Delete Playlist" style="background:rgba(255,80,80,0.08); border:1px solid rgba(255,80,80,0.15); border-radius:6px; padding:6px 8px; color:#ff5050; cursor:pointer; display:inline-flex; align-items:center; gap:4px; transition: all 0.2s; margin-left:auto;" aria-label="Delete Playlist"><i class="ph ph-trash"></i></button>
`;
pContainer.appendChild(hdr);
// Bind share event
const shareBtn = hdr.querySelector('.playlist-share-btn');
shareBtn.addEventListener('click', () => {
const ids = p.songs.map(s => s.id);
const b64 = btoa(JSON.stringify(ids));
const url = `${window.location.origin}/?pName=${encodeURIComponent(p.name)}&pData=${encodeURIComponent(b64)}`;
navigator.clipboard.writeText(url).then(() => {
showToast('Playlist link copied!', 'ph ph-link');
});
});
// Bind download all event
const dlAllBtn = hdr.querySelector('.playlist-dl-all-btn');
dlAllBtn.addEventListener('click', () => {
bulkDownloadPlaylist(p.songs, p.name, dlAllBtn);
});
// Bind delete event
const delBtn = hdr.querySelector('.playlist-delete-btn');
delBtn.addEventListener('click', async () => {
const confirmed = await showConfirm(
`Delete "${decode(p.name)}"?`,
"This can't be undone. All songs in this playlist will be lost.",
'Delete'
);
if (confirmed) {
Storage.deletePlaylist(p.id);
showToast(`Deleted "${decode(p.name)}"`, 'ph ph-trash');
showPlaylists();
}
});
// Hover effects for buttons
[shareBtn, dlAllBtn, delBtn].forEach(b => {
b.addEventListener('mouseenter', () => { b.style.filter = 'brightness(1.3)'; });
b.addEventListener('mouseleave', () => { b.style.filter = ''; });
});
// Render Playlist Songs Grid
const grid = document.createElement('div');
grid.className = 'search-results-grid'; // Reusing grid class
grid.style.padding = '0 0 16px 0';
if (!p.songs.length) {
grid.innerHTML = '<p style="color:var(--text-muted); font-size: 0.85rem;">Empty playlist</p>';
} else {
p.songs.forEach((s, i) => grid.appendChild(createSongCard(s, p.songs, i, p.id)));
}
pContainer.appendChild(grid);
});
}
/* PLAYER UI SYNC */
export function updatePlayerUI(song) {
if (!song) return;
playerSong.textContent = decode(song.title);
playerArtist.innerHTML = renderArtistsHtml(song.artists);
attachArtistLinks(playerArtist);
playerArt.src = song.image || '';
playerArt.onerror = () => { playerArt.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='56' height='56'%3E%3Crect width='56' height='56' fill='%23181822'/%3E%3Ctext x='50%25' y='54%25' dominant-baseline='middle' text-anchor='middle' fill='%23444' font-size='22'%3E♫%3C/text%3E%3C/svg%3E"; };
syncPlayerLike();
updateGlow(song.image);
extractAndSetColors(song.image);
document.title = `${decode(song.title)} — Clash Musics`;
// Now Playing overlay
const npArt = $('#np-art');
const npBg = $('#np-bg');
const npTitle = $('#np-title');
const npArtist = $('#np-artist');
if (npArt) npArt.src = song.image || '';
if (npBg) npBg.style.backgroundImage = `url("${song.image}")`;
if (npTitle) npTitle.textContent = decode(song.title);
if (npArtist) {
npArtist.innerHTML = renderArtistsHtml(song.artists);
attachArtistLinks(npArtist);
}
}
function syncPlayerLike() {
const s = Player.getCurrentSong();
if (!s) return;
const liked = Storage.isLiked(s.id);
playerLikeBtn.classList.toggle('liked', liked);
playerLikeIcon.className = liked ? 'ph-fill ph-heart' : 'ph ph-heart';
}
export function setPlayingState(playing) {
const icon = $('#play-icon');
const npIcon = $('#np-play-icon');
if (icon) icon.className = playing ? 'ph-fill ph-pause' : 'ph-fill ph-play';
if (npIcon) npIcon.className = playing ? 'ph-fill ph-pause' : 'ph-fill ph-play';
artWrap?.classList.toggle('spinning', playing);
}
export function updateProgress(pct) {
const bar = $('#progress-bar');
if (bar) bar.style.width = `${pct}%`;
}
export function updateTime(cur, dur) {
const el = $('#player-time');
if (el) el.textContent = `${fmtTime(cur)} / ${fmtTime(dur)}`;
const npCur = $('#np-time-current');
const npDur = $('#np-time-duration');
const npSeek = $('#np-seek');
if (npCur) npCur.textContent = fmtTime(cur);
if (npDur) npDur.textContent = fmtTime(dur);
if (npSeek && dur) npSeek.value = (cur / dur) * 100;
}
export function highlightPlaying() {
const cur = Player.getCurrentSong();
$$('.song-card').forEach(c => c.classList.toggle('is-playing', c.dataset.songId === cur?.id));
}
/* QUEUE PANEL */
function renderQueue() {
const list = $('#queue-list');
const panel = $('#queue-panel');
if (!list || !panel) return;
const pl = Player.getPlaylist();
const ci = Player.getCurrentIdx();
list.innerHTML = '';
if (!pl.length) {
list.innerHTML = '<p style="color:var(--text-muted);padding:20px;text-align:center;font-size:0.8rem;">Queue is empty</p>';
return;
}
let dragIdx = null;
pl.forEach((song, i) => {
const item = document.createElement('div');
item.className = `queue-item${i === ci ? ' active' : ''}`;
item.draggable = true;
item.dataset.idx = i;
item.innerHTML = `
<span class="queue-item__drag" title="Drag to reorder"><i class="ph ph-dots-six-vertical"></i></span>
<span class="queue-item__num">${i + 1}</span>
<img class="queue-item__art" src="${song.image}" alt="" loading="lazy" onerror="this.style.display='none'" />
<div class="queue-item__text">
<div class="queue-item__title">${decode(song.title)}</div>
<div class="queue-item__artist">${renderArtistsHtml(song.artists)}</div>
</div>
<button class="queue-item__add-btn" aria-label="Add to Playlist" title="Add to Playlist" style="background:transparent; border:none; color:var(--text-muted); cursor:pointer; padding: 4px; border-radius: 4px; display: flex; align-items: center; justify-content: center;"><i class="ph ph-list-plus" style="font-size: 1.2rem;"></i></button>
`;
// Drag events
item.addEventListener('dragstart', (e) => {
dragIdx = i;
item.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
});
item.addEventListener('dragend', () => {
item.classList.remove('dragging');
list.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
dragIdx = null;
});
item.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
list.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
item.classList.add('drag-over');
});
item.addEventListener('dragleave', () => item.classList.remove('drag-over'));
item.addEventListener('drop', (e) => {
e.preventDefault();
item.classList.remove('drag-over');
const toIdx = parseInt(item.dataset.idx);
if (dragIdx !== null && dragIdx !== toIdx) {
Player.reorderQueue(dragIdx, toIdx);
renderQueue();
showToast('Queue reordered', 'ph ph-arrows-down-up');
}
});
// Touch drag for mobile
let touchStartY = 0;
let touchClone = null;
const dragHandle = item.querySelector('.queue-item__drag');
dragHandle?.addEventListener('touchstart', (e) => {
dragIdx = i;
touchStartY = e.touches[0].clientY;
item.classList.add('dragging');
}, { passive: true });
dragHandle?.addEventListener('touchmove', (e) => {
const touch = e.touches[0];
const target = document.elementFromPoint(touch.clientX, touch.clientY)?.closest('.queue-item');
list.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
if (target && target !== item) target.classList.add('drag-over');
}, { passive: true });
dragHandle?.addEventListener('touchend', () => {
item.classList.remove('dragging');
const overEl = list.querySelector('.drag-over');
if (overEl) {
const toIdx = parseInt(overEl.dataset.idx);
overEl.classList.remove('drag-over');
if (dragIdx !== null && dragIdx !== toIdx) {
Player.reorderQueue(dragIdx, toIdx);
renderQueue();
showToast('Queue reordered', 'ph ph-arrows-down-up');
}
}
dragIdx = null;
});
item.addEventListener('click', (e) => {
if (e.target.closest('.artist-link') || e.target.closest('.queue-item__drag') || e.target.closest('.queue-item__add-btn')) return;
Player.playSong(song, pl, i);
});
item.querySelector('.queue-item__add-btn')?.addEventListener('click', (e) => {
e.stopPropagation();
openPlaylistModal(song);
});
attachArtistLinks(item);
list.appendChild(item);
});
}
function toggleQueue() {
const panel = $('#queue-panel');
if (!panel) return;
const showing = !panel.classList.contains('hidden');
if (showing) {
panel.classList.add('hidden');
} else {
renderQueue();
panel.classList.remove('hidden');
}
}
/* NOW PLAYING OVERLAY */
let npOpen = false;
function openNowPlaying() {
const overlay = $('#np-overlay');
if (!overlay || npOpen) return;
npOpen = true;
overlay.classList.remove('hidden');
overlay.style.animation = 'npSlideIn 0.45s var(--ease) forwards';
document.body.style.overflow = 'hidden';
startNPVisualizer();
}
function closeNowPlaying() {
const overlay = $('#np-overlay');
if (!overlay || !npOpen) return;
overlay.style.animation = 'npSlideOut 0.35s var(--ease) forwards';
overlay.addEventListener('animationend', function handler() {
overlay.removeEventListener('animationend', handler);
overlay.classList.add('hidden');
overlay.style.animation = '';
document.body.style.overflow = '';
npOpen = false;
stopNPVisualizer();
});
}
function toggleNowPlaying() {
npOpen ? closeNowPlaying() : openNowPlaying();
}
/* PLAYLIST MODAL & LYRICS */
function openPlaylistModal(song) {
currentPlaylistSong = song;
const modal = $('#playlist-modal');
if (!modal) return;
modal.classList.remove('hidden');
renderPlaylistsInModal();
}
function closePlaylistModal() {
const modal = $('#playlist-modal');
if (modal) modal.classList.add('hidden');
currentPlaylistSong = null;
}
function renderPlaylistsInModal() {
const listParams = $('#playlist-list');
if (!listParams) return;
listParams.innerHTML = '';
const pList = Storage.getPlaylists();
if (!pList.length) {
listParams.innerHTML = '<p style="font-size:0.8rem; color:var(--text-muted); padding: 10px;">No playlists yet. Create one above!</p>';
return;
}
pList.forEach(p => {
const row = document.createElement('div');
row.className = 'playlist-rowItem';
row.innerHTML = `<span>${escapeHTML(decode(p.name))}</span> <span style="font-size:0.7rem; color:var(--text-muted);">${p.songs.length} ♫</span>`;
// Add logic
row.addEventListener('click', () => {
const res = Storage.addToPlaylist(p.id, currentPlaylistSong);
if (res === 'added') {
showToast(`Added to "${decode(p.name)}"`, 'ph ph-check-circle');
} else if (res === 'full') {
showToast('Playlist is full (Max 50)', 'ph ph-warning-limit');
} else {
showToast(`Already in "${decode(p.name)}"`, 'ph ph-info');
}
closePlaylistModal();
});
listParams.appendChild(row);
});
}
function toggleLyricsPanel() {
const pnl = $('#np-lyrics-panel');
if (!pnl) return;
const isHidden = pnl.classList.contains('hidden');
if (isHidden) {
const song = Player.getCurrentSong();
if (!song) return;
const ctn = $('#np-lyrics-content');
ctn.textContent = 'Loading lyrics...';
pnl.classList.remove('hidden');
Api.getLyrics(song.id, decode(song.title), decode(song.artist), decode(song.album), song.duration).then(lyrics => {
if (!lyrics) ctn.textContent = "Lyrics not available for this track.";
else {
// Remove [00:15.22] style LRC timestamps for clear reading
const plainLyrics = lyrics.replace(/\[\d{2}:\d{2}\.\d{2,3}\]/g, '').trim();
ctn.textContent = plainLyrics.replace(/<br\s*\/?>/gi, '\n');
}
}).catch(() => { ctn.textContent = "Error fetching lyrics."; });
} else {
pnl.classList.add('hidden');
}
}
/* SHUFFLE / REPEAT UI */
function syncShuffleUI() {
const btn = $('#btn-shuffle');