-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3170 lines (2724 loc) · 112 KB
/
script.js
File metadata and controls
3170 lines (2724 loc) · 112 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
// Initialize IndexedDB
const dbName = 'musicPlayerDB';
const dbVersion = 2; // Increased version number to force upgrade
let db;
// Audio Context and Analyzer setup
let audioContext;
let audioSource;
let analyzer;
const FFT_SIZE = 256;
let dataArray;
let canvas;
let canvasCtx;
// Audio analysis variables (simplified for basic bar visualizer)
// Error Handling System
class ErrorHandler {
constructor() {
this.container = document.getElementById('error-toast-container');
this.activeToasts = new Set();
}
showError(error, options = {}) {
const {
title = 'Error',
message = 'An unexpected error occurred',
type = 'error',
duration = 8000,
actions = [],
showClose = true
} = options;
// Parse error message for better user experience
const parsedError = this.parseError(error);
// If parseError returns null, skip showing the toast (likely null/undefined error)
if (!parsedError) {
console.log('Skipping error toast for null/undefined error');
return null;
}
const finalMessage = parsedError.message || message;
const finalTitle = parsedError.title || title;
const toast = this.createToast({
title: finalTitle,
message: finalMessage,
type: parsedError.type || type,
duration,
actions,
showClose
});
this.container.appendChild(toast);
this.activeToasts.add(toast);
// Trigger animation
requestAnimationFrame(() => {
toast.classList.add('show');
});
// Auto-remove after duration
if (duration > 0) {
setTimeout(() => {
this.hideToast(toast);
}, duration);
}
return toast;
}
showSuccess(message, options = {}) {
return this.showError(null, {
title: 'Success',
message,
type: 'success',
duration: 4000,
...options
});
}
showWarning(message, options = {}) {
return this.showError(null, {
title: 'Warning',
message,
type: 'warning',
duration: 6000,
...options
});
}
parseError(error) {
if (!error) {
// Log this case to help debug when null/undefined errors are passed
console.warn('ErrorHandler.parseError called with null/undefined error');
return null; // Return null to indicate we should skip showing a toast
}
// Handle different error types
if (typeof error === 'string') {
return { message: error, type: 'error' };
}
if (error instanceof Error) {
const message = error.message;
// ElevenLabs API specific error parsing
if (message.includes('Status code: 402')) {
return {
title: 'Upgrade Required',
message: 'The Music API requires a paid ElevenLabs plan. Please upgrade your account to generate music.',
type: 'warning',
actions: [
{
text: 'Upgrade Account',
action: () => window.open('https://elevenlabs.io/pricing', '_blank')
}
]
};
}
if (message.includes('Status code: 401') || message.includes('unauthorized')) {
return {
title: 'Invalid API Key',
message: 'Please check your ElevenLabs API key and try again.',
type: 'error',
actions: [
{
text: 'Get API Key',
action: () => window.open('https://elevenlabs.io/app/developers/api-keys', '_blank')
}
]
};
}
if (message.includes('Status code: 403') || message.includes('forbidden')) {
return {
title: 'Access Denied',
message: 'Your ElevenLabs account doesn\'t have access to the Music API.',
type: 'error'
};
}
if (message.includes('Status code: 400')) {
return {
title: 'Invalid Request',
message: 'There was an issue with your request. Please check your prompt and try again.',
type: 'error'
};
}
if (message.includes('Status code: 429')) {
return {
title: 'Rate Limit Exceeded',
message: 'You\'ve hit the rate limit. Please wait a moment before trying again.',
type: 'warning'
};
}
if (message.includes('Status code: 500')) {
return {
title: 'Server Error',
message: 'ElevenLabs servers are experiencing issues. Please try again later.',
type: 'error'
};
}
if (message.includes('NetworkError') || message.includes('Failed to fetch')) {
return {
title: 'Connection Error',
message: 'Unable to connect to the server. Please check your internet connection.',
type: 'error'
};
}
// Generic error parsing
if (message.includes('Invalid API key')) {
return {
title: 'Invalid API Key',
message: 'Please check your ElevenLabs API key and try again.',
type: 'error'
};
}
// Handle ElevenLabs TOS violation messages
if (message.includes('violated our Terms of Service') || message.includes('bad_prompt')) {
return {
title: 'Content Policy Violation',
message: 'Your prompt appears to have violated our Terms of Service. Please try again with a different prompt.',
type: 'warning'
};
}
if (message.includes('Rate limit exceeded')) {
return {
title: 'Rate Limit Exceeded',
message: 'Please wait a moment before trying again.',
type: 'warning'
};
}
return { message, type: 'error' };
}
// Handle response objects from server
if (error.type) {
let result = {
message: error.message || error.error || 'An error occurred',
type: error.type === 'api_error' ? 'error' : error.type
};
// Handle specific error types from server
if (error.type === 'bad_prompt') {
result.title = 'Content Policy Violation';
result.message = 'Your prompt appears to have violated our Terms of Service. Please try again with a different prompt.';
result.type = 'warning';
// Add prompt suggestion if available
if (error.promptSuggestion) {
result.actions = [
{
text: 'Use Suggested Prompt',
primary: true,
action: () => {
const musicPromptInput = document.getElementById('music-prompt');
if (musicPromptInput) {
musicPromptInput.value = error.promptSuggestion;
musicPromptInput.focus();
}
}
}
];
}
} else if (error.type === 'limited_access') {
result.title = 'Access Limited';
result.type = 'warning';
} else if (error.statusCode === 400) {
result.title = 'Invalid Request';
result.type = 'error';
}
return result;
}
// Legacy response object handling
if (error.detail && error.detail.message) {
return {
message: error.detail.message,
type: error.detail.status === 'limited_access' ? 'warning' : 'error'
};
}
if (error.error) {
return { message: error.error, type: 'error' };
}
return { message: 'An unexpected error occurred', type: 'error' };
}
createToast({ title, message, type, duration, actions, showClose }) {
const toast = document.createElement('div');
toast.className = `error-toast ${type}-toast`;
const icon = this.getIcon(type);
toast.innerHTML = `
${showClose ? '<button class="error-toast-close" aria-label="Close">×</button>' : ''}
<div class="error-toast-header">
<span class="error-toast-icon">${icon}</span>
<span class="error-toast-title">${title}</span>
</div>
<div class="error-toast-message">${message}</div>
${actions.length > 0 ? `
<div class="error-toast-actions">
${actions.map(action =>
`<button class="error-toast-button ${action.primary ? 'primary' : ''}" data-action="${action.text}">${action.text}</button>`
).join('')}
</div>
` : ''}
`;
// Add event listeners
if (showClose) {
const closeBtn = toast.querySelector('.error-toast-close');
closeBtn.addEventListener('click', () => this.hideToast(toast));
}
actions.forEach(action => {
const btn = toast.querySelector(`[data-action="${action.text}"]`);
if (btn) {
btn.addEventListener('click', action.action);
}
});
return toast;
}
getIcon(type) {
const icons = {
error: '⚠️',
warning: '⚠️',
success: '✅',
info: 'ℹ️'
};
return icons[type] || icons.error;
}
hideToast(toast) {
if (!toast || !this.activeToasts.has(toast)) return;
toast.classList.add('hide');
this.activeToasts.delete(toast);
setTimeout(() => {
if (toast.parentNode) {
toast.parentNode.removeChild(toast);
}
}, 300);
}
clearAll() {
this.activeToasts.forEach(toast => {
this.hideToast(toast);
});
}
}
// Initialize error handler
const errorHandler = new ErrorHandler();
// Make errorHandler globally available
window.errorHandler = errorHandler;
// Global error handler for unhandled errors
window.addEventListener('error', (event) => {
console.error('Unhandled error:', event.error);
errorHandler.showError(event.error, {
title: 'Unexpected Error',
message: 'An unexpected error occurred. Please try again.',
type: 'error',
duration: 10000
});
});
// Global handler for unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled promise rejection:', event.reason);
console.log('Event object:', event);
console.log('Reason type:', typeof event.reason);
console.log('Reason value:', event.reason);
// Only show error toast for actual errors, not for expected cases like autoplay failures
const reason = event.reason;
if (reason && (
(reason.message && reason.message.includes('play')) ||
(typeof reason === 'string' && reason.includes('play'))
)) {
// Likely an autoplay failure, just log it and prevent default browser behavior
console.warn('Suppressed autoplay-related promise rejection:', reason);
event.preventDefault();
return;
}
errorHandler.showError(event.reason, {
title: 'Request Failed',
message: 'A request failed unexpectedly. Please try again.',
type: 'error',
duration: 10000
});
event.preventDefault(); // Prevent the default browser behavior
});
// Helper function to extract text content from ID3v2 frames
const getTextFrameContent = (uint8Array, start, length, encoding) => {
// Encoding: 0x00 = ISO-8859-1, 0x01 = UTF-16
let contentBytes = uint8Array.slice(start, start + length);
if (encoding === 0x01) {
// UTF-16: skip BOM if present (0xFF 0xFE or 0xFE 0xFF)
if (contentBytes[0] === 0xFE && contentBytes[1] === 0xFF) {
contentBytes = contentBytes.slice(2);
} else if (contentBytes[0] === 0xFF && contentBytes[1] === 0xFE) {
contentBytes = contentBytes.slice(2);
}
return new TextDecoder('utf-16').decode(contentBytes).replace(/\0/g, '').trim();
} else {
// Default to ISO-8859-1 (latin1) for 0x00 and other unknown encodings
return new TextDecoder('latin1').decode(contentBytes).replace(/\0/g, '').trim();
}
};
// Function to delete the database if needed
const deleteDatabase = () => {
return new Promise((resolve, reject) => {
const deleteRequest = indexedDB.deleteDatabase(dbName);
deleteRequest.onsuccess = () => resolve();
deleteRequest.onerror = () => reject(deleteRequest.error);
});
};
const initDB = async () => {
try {
// First try to open the database
const request = indexedDB.open(dbName, dbVersion);
request.onerror = async (event) => {
console.error('Database error:', event.target.error);
// If there's an error, try to delete and recreate the database
await deleteDatabase();
// Retry database creation
initDB();
};
request.onupgradeneeded = (event) => {
db = event.target.result;
window.db = db; // Make db globally accessible
// Create stores if they don't exist
if (!db.objectStoreNames.contains('audio')) {
db.createObjectStore('audio', { keyPath: 'id' });
}
if (!db.objectStoreNames.contains('settings')) {
db.createObjectStore('settings', { keyPath: 'id' });
}
// New store for playlists (supports nesting via parentId)
if (!db.objectStoreNames.contains('playlists')) {
db.createObjectStore('playlists', { keyPath: 'id' });
}
};
request.onsuccess = async (event) => {
db = event.target.result;
window.db = db; // Make db globally accessible
console.log('Database initialized successfully');
// Verify stores exist
if (!db.objectStoreNames.contains('audio') || !db.objectStoreNames.contains('settings') || !db.objectStoreNames.contains('playlists')) {
console.log('Required stores missing, recreating database...');
db.close();
await deleteDatabase();
// Retry database creation
initDB();
return;
}
// Load last played song or first available song
await loadInitialSong();
};
} catch (error) {
console.error('Fatal database error:', error);
}
};
// Simple IndexedDB helpers
function idbPut(storeName, value) {
return new Promise((resolve, reject) => {
const tx = db.transaction([storeName], 'readwrite');
const store = tx.objectStore(storeName);
const req = store.put(value);
req.onsuccess = () => resolve(value);
req.onerror = () => reject(req.error);
});
}
function idbGetAll(storeName) {
return new Promise((resolve, reject) => {
const tx = db.transaction([storeName], 'readonly');
const store = tx.objectStore(storeName);
const req = store.getAll();
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
}
function idbGet(storeName, key) {
return new Promise((resolve, reject) => {
const tx = db.transaction([storeName], 'readonly');
const store = tx.objectStore(storeName);
const req = store.get(key);
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
});
}
// Playlist helpers
function idbDelete(storeName, key) {
return new Promise((resolve, reject) => {
const tx = db.transaction([storeName], 'readwrite');
const store = tx.objectStore(storeName);
const req = store.delete(key);
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
async function createPlaylist({ name, cover = null, parentId = null }) {
const id = `pl_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const playlist = {
id,
name: name && name.trim() ? name.trim() : await getDefaultPlaylistName(),
cover: cover || null,
parentId: parentId || null,
description: '',
createdAt: Date.now(),
updatedAt: Date.now()
};
await idbPut('playlists', playlist);
return playlist;
}
async function getDefaultPlaylistName() {
const all = await idbGetAll('playlists');
const index = all.length;
return `Playlist ${index + 1}`;
}
async function renamePlaylist(id, newName) {
const pl = await idbGet('playlists', id);
if (!pl) return null;
pl.name = newName && newName.trim() ? newName.trim() : pl.name;
pl.updatedAt = Date.now();
await idbPut('playlists', pl);
return pl;
}
async function updatePlaylist(id, updates) {
const pl = await idbGet('playlists', id);
if (!pl) return null;
const next = { ...pl, ...updates, updatedAt: Date.now() };
await idbPut('playlists', next);
return next;
}
async function deletePlaylist(id, { deleteSongs = false } = {}) {
// When deleting, optionally move songs out to root or delete them
const items = await idbGetAll('audio');
const updated = [];
for (const item of items) {
if (item.playlistId === id) {
if (deleteSongs) {
await idbDelete('audio', item.id);
} else {
delete item.playlistId;
updated.push(item);
}
}
}
for (const u of updated) {
await idbPut('audio', u);
}
// Move or delete child playlists (keep nesting; reparent to deleted's parent)
const playlists = await idbGetAll('playlists');
const toReparent = playlists.filter(p => p.parentId === id);
const parent = playlists.find(p => p.id === id);
const newParentId = parent ? parent.parentId || null : null;
for (const child of toReparent) {
child.parentId = newParentId;
child.updatedAt = Date.now();
await idbPut('playlists', child);
}
await idbDelete('playlists', id);
}
async function moveSongToPlaylist(songId, targetPlaylistId = null) {
const song = await idbGet('audio', songId);
if (!song) return null;
if (targetPlaylistId) {
const target = await idbGet('playlists', targetPlaylistId);
if (!target) return null;
song.playlistId = targetPlaylistId;
// Inherit cover art: if the playlist has no cover yet, use the first added song's cover
if (!target.cover && song.cover instanceof Blob) {
target.cover = song.cover;
target.updatedAt = Date.now();
await idbPut('playlists', target);
}
} else {
delete song.playlistId; // move to root
}
await idbPut('audio', song);
return song;
}
async function movePlaylist(playlistId, newParentId = null) {
if (playlistId === newParentId) return null;
const pl = await idbGet('playlists', playlistId);
if (!pl) return null;
if (newParentId) {
// Prevent cycles
let checkId = newParentId;
while (checkId) {
if (checkId === playlistId) return null;
const next = await idbGet('playlists', checkId);
checkId = next ? next.parentId : null;
}
}
pl.parentId = newParentId || null;
pl.updatedAt = Date.now();
await idbPut('playlists', pl);
return pl;
}
// Initialize the database when the script loads
initDB();
// Function to preload demo songs
async function preloadDemoSongs() {
try {
const response = await fetch('assets/demo/OST.mp3');
const blob = await response.blob();
const file = new File([blob], 'OST.mp3', { type: 'audio/mpeg' });
// Process the file like a normal upload
await processAudioFile(file);
} catch (error) {
console.error('Error preloading demo songs:', error);
}
}
// Helper function to get settings
async function getSetting(key) {
try {
const setting = await idbGet('settings', key);
return setting ? setting.value : null;
} catch (error) {
console.error('Error getting setting:', error);
return null;
}
}
// Helper function to save settings
async function saveSetting(key, value) {
try {
await idbPut('settings', { id: key, value });
} catch (error) {
console.error('Error saving setting:', error);
}
}
// Update record appearance
async function updateRecordAppearance(imageUrl = null) {
const root = document.documentElement;
try {
if (imageUrl) {
// If we have a new image URL, use it
if (imageUrl.startsWith('linear-gradient')) {
// For gradients, set directly without url()
root.style.setProperty('--record-bg-image', imageUrl);
recordInner.style.backgroundImage = imageUrl;
} else {
// For actual images, wrap in url()
root.style.setProperty('--record-bg-image', `url('${imageUrl}')`);
recordInner.style.backgroundImage = `url('${imageUrl}')`;
}
// Only store in lastCoverUrl if it's a gradient (not an object URL)
if (!imageUrl.startsWith('blob:')) {
await saveSetting('lastCoverUrl', imageUrl);
}
} else {
// Try to get last stored background
const lastCoverUrl = await getSetting('lastCoverUrl');
if (lastCoverUrl) {
// Only use lastCoverUrl if it's a gradient (not an object URL)
if (!lastCoverUrl.startsWith('blob:')) {
if (lastCoverUrl.startsWith('linear-gradient')) {
// For gradients, set directly without url()
root.style.setProperty('--record-bg-image', lastCoverUrl);
recordInner.style.backgroundImage = lastCoverUrl;
} else {
// For actual images, wrap in url()
root.style.setProperty('--record-bg-image', `url('${lastCoverUrl}')`);
recordInner.style.backgroundImage = `url('${lastCoverUrl}')`;
}
} else {
// If it was an object URL, clear it as it's no longer valid
await saveSetting('lastCoverUrl', null);
const gradient = generateRandomGradient();
root.style.setProperty('--record-bg-image', gradient);
recordInner.style.backgroundImage = gradient;
}
} else {
// Generate a new gradient if no valid lastCoverUrl
const gradient = generateRandomGradient();
root.style.setProperty('--record-bg-image', gradient);
recordInner.style.backgroundImage = gradient;
}
}
} catch (error) {
console.error('Error updating record appearance:', error);
// Fallback to random gradient
const gradient = generateRandomGradient();
root.style.setProperty('--record-bg-image', gradient);
recordInner.style.backgroundImage = gradient;
}
}
// Set default state
async function setDefaultState() {
songTitleElement.textContent = 'NO SONGS';
songAuthorElement.textContent = 'Drop a song to begin';
await updateRecordAppearance();
// Hide progress bar when no songs
if (progressBarContainer) {
progressBarContainer.classList.remove('visible');
}
}
// Load initial song (last played or first available)
async function loadInitialSong() {
try {
// Check if we have any songs
const songs = await idbGetAll('audio');
if (songs.length === 0) {
// No songs - set default state and try to preload demo
await setDefaultState();
await preloadDemoSongs();
return;
}
// Try to get last played song
const lastPlayedId = await getSetting('lastPlayedId');
let songToLoad = null;
if (lastPlayedId) {
songToLoad = await idbGet('audio', lastPlayedId);
}
// If no last played or it wasn't found, use first song
if (!songToLoad) {
songToLoad = songs[0];
}
// Load the song without playing
if (songToLoad) {
await loadSong(songToLoad, false);
} else {
await setDefaultState();
}
} catch (error) {
console.error('Error loading initial song:', error);
await setDefaultState();
}
}
// DOM Elements
const record = document.querySelector('.record');
const recordInner = document.querySelector('.record-inner');
const dropZone = document.querySelector('.drop-zone');
const songTitleElement = document.querySelector('.song-title');
const songAuthorElement = document.querySelector('.song-author');
// Make these globally accessible
window.songTitleElement = songTitleElement;
window.songAuthorElement = songAuthorElement;
const songsButton = document.querySelector('.songs-button');
const songsPanel = document.querySelector('.songs-panel');
const songsList = document.querySelector('.songs-list');
let songCoverObjectUrls = [];
let currentRecordCoverUrl = null; // Track the current record's cover URL separately
// Progress Bar Elements
const progressBarContainer = document.querySelector('.progress-bar-container');
const progressBar = document.querySelector('.progress-bar');
const progressBarTrack = document.querySelector('.progress-bar-track');
const progressBarFill = document.querySelector('.progress-bar-fill');
const progressBarHandle = document.querySelector('.progress-bar-handle');
const progressTimeCurrentElement = document.querySelector('.progress-time-current');
const progressTimeTotalElement = document.querySelector('.progress-time-total');
const playPauseButton = document.querySelector('.play-pause-button');
const nextTrackButton = document.querySelector('.next-track-button');
// Set up canvas for visualization
canvas = document.createElement('canvas');
canvas.className = 'audio-visualizer';
document.body.appendChild(canvas);
// Ensure canvas has fixed size
function resizeCanvas() {
// Size for bottom bar visualizer
canvas.width = window.innerWidth;
canvas.height = 160;
// Update canvas context properties
canvasCtx = canvas.getContext('2d', { alpha: true });
canvasCtx.lineCap = 'round';
canvasCtx.lineJoin = 'round';
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
canvasCtx = canvas.getContext('2d');
// Drag state tracking
let dragCounter = 0;
let debounceTimer = null;
// Audio Context
let currentAudio = null;
let isPlaying = false;
// Rotation state
let rotationAngle = 0;
let animationId = null;
let lastTime = 0;
const ROTATION_SPEED = 180; // degrees per second (half rotation per second)
// Dragging state for scrubbing
let isDragging = false;
let dragStartAngle = 0;
let initialPlaybackTime = 0;
let recordRect; // To store the bounding rectangle of the record
let cumulativeRotations = 0; // Track total rotations including fractions
let lastAngle = 0; // Track last angle for rotation counting
let rotationDisplay = document.createElement('div'); // Element to show rotation count
let wasPlaying = false; // Track if audio was playing when scrub started
let mouseDownTime = 0; // Track when mouse was pressed
let mouseStartX = 0; // Track initial mouse position
let mouseStartY = 0;
let isScrubbing = false; // Track if we're actually scrubbing vs clicking
// Progress Bar state
let isProgressBarDragging = false;
let progressBarRect;
let progressBarWasPlaying = false;
let progressAnimationId = null;
// Add frame rate control variables
let lastDrawTime = 0;
const FRAME_INTERVAL = 1000 / 30; // Cap at 30 FPS during scrubbing
const NORMAL_FRAME_INTERVAL = 1000 / 60; // 60 FPS during normal playback
// Style the rotation display
rotationDisplay.style.position = 'absolute';
rotationDisplay.style.top = '10px';
rotationDisplay.style.left = '10px';
rotationDisplay.style.background = 'rgba(0, 0, 0, 0.7)';
rotationDisplay.style.color = 'white';
rotationDisplay.style.padding = '5px 10px';
rotationDisplay.style.borderRadius = '5px';
rotationDisplay.style.display = 'none';
document.body.appendChild(rotationDisplay);
// Add click handler for playback
record.addEventListener('click', (e) => {
// Only handle click if we weren't scrubbing
if (!isScrubbing) {
handlePlayback();
}
});
// Add space bar control for playback
window.addEventListener('keydown', (e) => {
// Check if it's the space bar and we're not in an input field
if (e.code === 'Space' && !(e.target.matches('input, textarea'))) {
e.preventDefault(); // Prevent page scroll
handlePlayback();
}
});
// Add keyboard navigation for songs panel
window.addEventListener('keydown', (e) => {
// Tab to toggle songs panel (only if no edit dialog is open)
if (e.code === 'Tab') {
// If edit dialog is open, allow default Tab behavior for form navigation
if (contextMenu && contextMenu.isEditDialogOpen()) {
return; // Let default Tab behavior handle form navigation
}
e.preventDefault(); // Prevent default tab behavior
if (songsPanel) {
const isOpen = songsPanel.classList.contains('open');
if (!isOpen) {
renderSongs();
songsPanel.classList.add('open');
songsPanel.setAttribute('aria-hidden', 'false');
// Focus the first song when opening
const firstSong = songsList.querySelector('.song-item');
if (firstSong) {
firstSong.focus();
}
} else {
songsPanel.classList.remove('open');
songsPanel.setAttribute('aria-hidden', 'true');
clearSongObjectUrls();
}
}
}
// Arrow key navigation when songs panel is open
if (songsPanel && songsPanel.classList.contains('open')) {
const songs = Array.from(songsList.querySelectorAll('.song-item'));
const currentSong = document.activeElement;
let currentIndex = songs.indexOf(currentSong);
if (e.code === 'ArrowDown' || e.code === 'ArrowRight') {
e.preventDefault();
if (songs.length === 0) return;
if (currentIndex < songs.length - 1 && currentIndex !== -1) {
songs[currentIndex + 1].focus();
} else if (currentIndex === songs.length - 1) {
// If at bottom, go to top
songs[0]?.focus();
} else if (currentIndex === -1) {
// If no song is focused, focus the first one
songs[0]?.focus();
}
} else if (e.code === 'ArrowUp' || e.code === 'ArrowLeft') {
e.preventDefault();
if (songs.length === 0) return;
if (currentIndex > 0) {
songs[currentIndex - 1].focus();
} else if (currentIndex === 0) {
// If at top, go to bottom
songs[songs.length - 1]?.focus();
} else if (currentIndex === -1) {
// If no song is focused, focus the last one
songs[songs.length - 1]?.focus();
}
} else if (e.code === 'Enter' && currentIndex !== -1) {
// Load and play the selected song on Enter
const songId = songs[currentIndex].dataset.id;
idbGet('audio', songId).then(item => {
if (item) {
loadSong(item);
songsPanel.classList.remove('open');
songsPanel.setAttribute('aria-hidden', 'true');
}
});
}
}
});
// Add mouse handlers for scrubbing
record.addEventListener('mousedown', handleScrubStart);
record.addEventListener('mousemove', handleScrubbing);
record.addEventListener('mouseup', handleScrubEnd);
record.addEventListener('mouseleave', handleScrubEnd); // End scrub if mouse leaves record
// Prevent default drag behaviors and handle drop zone
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
document.body.addEventListener(eventName, preventDefaults, { capture: true });
});
// Handle drag enter/leave with counter
document.body.addEventListener('dragenter', (e) => {
preventDefaults(e);
// Only handle audio files
const items = e.dataTransfer?.items;
if (items && items[0]?.type.startsWith('audio/')) {
dragCounter++;
if (dragCounter === 1) {
clearTimeout(debounceTimer);
highlight();
}
}
}, { capture: true });
document.body.addEventListener('dragleave', (e) => {
preventDefaults(e);
// Ignore if not at boundary
if (!e.relatedTarget || !document.body.contains(e.relatedTarget)) {
dragCounter--;
if (dragCounter === 0) {
debounceTimer = setTimeout(unhighlight, 50);
}
}
}, { capture: true });
document.body.addEventListener('drop', (e) => {
preventDefaults(e);
dragCounter = 0;
unhighlight();
handleDrop(e);
}, { capture: true });
// Handle window focus/blur to manage drop zone visibility
window.addEventListener('blur', () => {
// Reset drag state when window loses focus
dragCounter = 0;
clearTimeout(debounceTimer);
unhighlight();
});
window.addEventListener('focus', () => {
// Ensure clean state when window regains focus
dragCounter = 0;
clearTimeout(debounceTimer);
unhighlight();
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function highlight() {
dropZone.classList.add('active');
}