-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
executable file
·3702 lines (3427 loc) · 162 KB
/
script.js
File metadata and controls
executable file
·3702 lines (3427 loc) · 162 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
/* global idb, Fuse, Sortable, mammoth, SongBinderSupabase */
// ==== THEME HANDLING ====
function updateLogoForTheme(theme) {
const nextSrc = theme === 'light' ? 'logoLight' : 'logoDark';
document.querySelectorAll('img[data-logo-light][data-logo-dark]').forEach((logo) => {
const src = logo.dataset[nextSrc];
if (src) {
logo.setAttribute('src', src);
}
});
}
function applyTheme(theme) {
const nextTheme = theme === 'light' ? 'light' : 'dark';
document.documentElement.dataset.theme = nextTheme;
updateLogoForTheme(nextTheme);
}
document.addEventListener('DOMContentLoaded', function() {
// Initialize theme with strict dark/light only
let savedTheme = localStorage.getItem('theme');
if (savedTheme !== 'dark' && savedTheme !== 'light') {
savedTheme = 'dark';
localStorage.setItem('theme', 'dark');
}
applyTheme(savedTheme);
InstallPrompt.init();
});
async function ensurePersistentStorage() {
try {
if (!navigator.storage || !navigator.storage.persist) return;
const alreadyPersisted = await navigator.storage.persisted?.();
if (alreadyPersisted) return;
const granted = await navigator.storage.persist();
if (!granted) {
console.warn('Persistent storage request was denied; data may be evicted under pressure.');
}
} catch (err) {
console.warn('Unable to request persistent storage', err);
}
}
ensurePersistentStorage();
// Register Service Worker without inline scripts (for CSP)
try {
if ('serviceWorker' in navigator) {
const showSwUpdateBanner = (registration) => {
if (document.getElementById('sw-update-banner')) return;
const banner = document.createElement('div');
banner.id = 'sw-update-banner';
banner.className = 'sw-update-banner';
banner.innerHTML = `
<span>Update available.</span>
<button type="button" class="btn sw-update-btn">Reload</button>
`;
banner.querySelector('.sw-update-btn')?.addEventListener('click', () => {
try { registration.waiting?.postMessage({ type: 'SKIP_WAITING' }); } catch {}
});
document.body.appendChild(banner);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('controllerchange', () => {
window.location.reload();
});
}
};
const swUrl = (() => {
try {
return new URL('sw.js', window.location.href).href;
} catch {
return 'sw.js';
}
})();
window.addEventListener('load', () => {
navigator.serviceWorker.register(swUrl).then((registration) => {
if (registration.waiting) {
showSwUpdateBanner(registration);
}
registration.addEventListener('updatefound', () => {
const worker = registration.installing;
if (!worker) return;
worker.addEventListener('statechange', () => {
if (worker.state === 'installed' && navigator.serviceWorker.controller) {
showSwUpdateBanner(registration);
}
});
});
}).catch(() => {});
});
}
} catch {}
// Small utility
function debounce(fn, delay = 200) {
let t;
return function debounced(...args) {
clearTimeout(t);
t = setTimeout(() => fn.apply(this, args), delay);
};
}
// Basic HTML escaping to prevent XSS when injecting user text
function escapeHTML(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function safeJSONParse(value, fallback) {
if (!value) return fallback;
try {
return JSON.parse(value);
} catch {
return fallback;
}
}
function safeParseFromStorage(key, fallback) {
let raw = null;
try {
raw = localStorage.getItem(key);
} catch {
return { value: fallback, valid: false, raw: null };
}
if (!raw) return { value: fallback, valid: true, raw };
try {
return { value: JSON.parse(raw), valid: true, raw };
} catch {
return { value: fallback, valid: false, raw };
}
}
const UI_TRANSITION_MS = 180;
function navigateWithTransition(url) {
document.body?.classList.add('page-transitioning');
window.setTimeout(() => {
window.location.href = url;
}, UI_TRANSITION_MS);
}
function showAnimatedModal(modal) {
if (!modal) return;
clearTimeout(modal.__hideTimer);
modal.style.display = 'flex';
modal.classList.remove('is-closing');
requestAnimationFrame(() => {
modal.classList.add('is-visible');
});
}
function hideAnimatedModal(modal) {
if (!modal) return;
modal.classList.remove('is-visible');
modal.classList.add('is-closing');
clearTimeout(modal.__hideTimer);
modal.__hideTimer = window.setTimeout(() => {
if (modal.classList.contains('is-visible')) return;
modal.style.display = 'none';
modal.classList.remove('is-closing');
}, UI_TRANSITION_MS);
}
function setGlobalBusyIndicator(isVisible, message = 'Syncing with cloud...') {
const indicator = document.getElementById('global-busy-indicator');
const text = document.getElementById('global-busy-text');
if (!indicator) return;
clearTimeout(indicator.__hideTimer);
if (text) text.textContent = message;
if (isVisible) {
indicator.hidden = false;
requestAnimationFrame(() => {
indicator.classList.add('is-visible');
});
return;
}
indicator.classList.remove('is-visible');
indicator.__hideTimer = window.setTimeout(() => {
if (indicator.classList.contains('is-visible')) return;
indicator.hidden = true;
}, UI_TRANSITION_MS);
}
const InstallPrompt = (() => {
let deferredPrompt = null;
let dismissedForSession = false;
const ui = {
banner: () => document.getElementById('install-banner'),
title: () => document.getElementById('install-banner-title'),
text: () => document.getElementById('install-banner-text'),
action: () => document.getElementById('install-banner-action'),
dismiss: () => document.getElementById('install-banner-dismiss'),
};
function isInstalled() {
try {
return window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
} catch {
return false;
}
}
function isIosSafari() {
const ua = window.navigator.userAgent || '';
const isIos = /iphone|ipad|ipod/i.test(ua);
const isSafari = /safari/i.test(ua) && !/crios|fxios|edgios|chrome|android/i.test(ua);
return isIos && isSafari;
}
function showBanner({ title, text, actionLabel, manual = false }) {
const banner = ui.banner();
const action = ui.action();
if (!banner || !action || dismissedForSession || isInstalled()) return;
ui.title().textContent = title;
ui.text().textContent = text;
action.textContent = actionLabel;
action.dataset.manual = manual ? '1' : '0';
banner.hidden = false;
requestAnimationFrame(() => {
banner.classList.add('is-visible');
});
}
function hideBanner() {
const banner = ui.banner();
if (!banner) return;
banner.classList.remove('is-visible');
window.setTimeout(() => {
if (banner.classList.contains('is-visible')) return;
banner.hidden = true;
}, UI_TRANSITION_MS);
}
async function handleInstallAction() {
if (isInstalled()) {
hideBanner();
return;
}
if (deferredPrompt) {
const promptEvent = deferredPrompt;
deferredPrompt = null;
await promptEvent.prompt();
try {
await promptEvent.userChoice;
} catch {}
if (!isInstalled()) {
showDefaultBanner();
}
return;
}
if (isIosSafari()) {
showBanner({
title: 'Install SongBinder',
text: 'Tap Share, then choose Add to Home Screen.',
actionLabel: 'Got it',
manual: true,
});
return;
}
showBanner({
title: 'Install SongBinder',
text: 'Use your browser menu to install this app on your device.',
actionLabel: 'Got it',
manual: true,
});
}
function showDefaultBanner() {
if (deferredPrompt) {
showBanner({
title: 'Install SongBinder',
text: 'Add SongBinder to your device for a faster app-like experience.',
actionLabel: 'Install',
});
return;
}
if (isIosSafari()) {
showBanner({
title: 'Install SongBinder',
text: 'Tap Share, then choose Add to Home Screen.',
actionLabel: 'How to install',
manual: true,
});
return;
}
showBanner({
title: 'Install SongBinder',
text: 'Use your browser menu to install this app on your device.',
actionLabel: 'How to install',
manual: true,
});
}
function init() {
ui.action()?.addEventListener('click', () => {
handleInstallAction().catch((error) => {
console.warn('Install prompt failed', error);
});
});
ui.dismiss()?.addEventListener('click', () => {
dismissedForSession = true;
hideBanner();
});
window.addEventListener('beforeinstallprompt', (event) => {
event.preventDefault();
deferredPrompt = event;
showDefaultBanner();
});
window.addEventListener('appinstalled', () => {
deferredPrompt = null;
hideBanner();
});
if (!isInstalled()) {
window.setTimeout(() => {
if (!deferredPrompt && !dismissedForSession && !isInstalled()) {
showDefaultBanner();
}
}, 900);
}
}
return { init };
})();
const AuthGate = (() => {
const ACCESS_MODE_KEY = 'songbinderAccessMode';
let client = null;
let appRef = null;
let started = false;
let currentSession = null;
let isAuthReady = false;
const ui = {
splash: () => document.getElementById('startup-splash'),
landing: () => document.getElementById('landing-screen'),
appShell: () => document.getElementById('app-shell'),
signInBtn: () => document.getElementById('google-signin-btn'),
offlineBtn: () => document.getElementById('continue-offline-btn'),
feedback: () => document.getElementById('auth-feedback'),
logoutBtn: () => document.getElementById('logout-btn'),
};
function isSupabaseConfigured() {
return !!window.SongBinderSupabase?.isConfigured?.();
}
function getRedirectUrl() {
return window.SongBinderSupabase?.getRedirectUrl?.() || window.location.href;
}
function getStoredMode() {
try {
return localStorage.getItem(ACCESS_MODE_KEY) || '';
} catch {
return '';
}
}
function setStoredMode(mode) {
try {
if (mode) localStorage.setItem(ACCESS_MODE_KEY, mode);
else localStorage.removeItem(ACCESS_MODE_KEY);
} catch {}
}
function setFeedback(message, type = 'info') {
const feedback = ui.feedback();
if (!feedback) return;
feedback.textContent = message;
feedback.dataset.state = type;
}
function setSession(session) {
currentSession = session || null;
}
function setAuthReady(ready) {
isAuthReady = !!ready;
const splash = ui.splash();
document.body?.classList.toggle('auth-resolving', !ready);
if (splash) splash.hidden = !!ready;
}
function setLoading(isLoading) {
const signInBtn = ui.signInBtn();
const offlineBtn = ui.offlineBtn();
if (signInBtn) signInBtn.disabled = !!isLoading;
if (offlineBtn) offlineBtn.disabled = !!isLoading;
}
function updateLogoutButton(mode, session) {
const logoutBtn = ui.logoutBtn();
if (!logoutBtn) return;
if (mode !== 'authenticated' || !session?.user) {
logoutBtn.hidden = true;
return;
}
logoutBtn.hidden = false;
logoutBtn.addEventListener('click', async () => {
if (!client) return;
setLoading(true);
try {
await client.auth.signOut();
setSession(null);
setStoredMode('');
window.location.reload();
} catch (err) {
console.error('Sign out failed', err);
setFeedback('Unable to sign out right now.', 'error');
} finally {
setLoading(false);
}
});
}
async function startApp(mode, session = null) {
setSession(session);
setAuthReady(true);
if (started) {
updateLogoutButton(mode, session);
return;
}
started = true;
updateLogoutButton(mode, session);
const landing = ui.landing();
const shell = ui.appShell();
if (landing) landing.hidden = true;
if (shell) shell.hidden = false;
if (appRef && typeof appRef.init === 'function') {
await appRef.init();
}
}
function showLanding(message, type = 'info') {
setAuthReady(true);
updateLogoutButton('', null);
const landing = ui.landing();
const shell = ui.appShell();
if (shell) shell.hidden = true;
if (landing) landing.hidden = false;
setFeedback(message, type);
}
function ensureClient() {
if (client || !isSupabaseConfigured()) return client;
client = window.SongBinderSupabase?.getClient?.() || null;
return client;
}
async function continueOffline() {
setStoredMode('offline');
await startApp('offline');
}
async function signInWithGoogle() {
const supabaseClient = ensureClient();
if (!supabaseClient) {
setFeedback('Google sign-in is not configured yet. Generate env.js from SUPABASE_URL and SUPABASE_ANON_KEY.', 'error');
return;
}
setLoading(true);
setFeedback('Redirecting to Google sign-in…');
try {
const { error } = await supabaseClient.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: getRedirectUrl(),
},
});
if (error) throw error;
} catch (err) {
console.error('Google sign-in failed', err);
setFeedback('Unable to start Google sign-in. Check your Supabase config and redirect URL.', 'error');
setLoading(false);
}
}
async function bootstrap(app) {
appRef = app;
setAuthReady(false);
ui.signInBtn()?.addEventListener('click', () => {
signInWithGoogle();
});
ui.offlineBtn()?.addEventListener('click', () => {
continueOffline();
});
if (!isSupabaseConfigured()) {
ui.signInBtn()?.setAttribute('disabled', 'disabled');
if (getStoredMode() === 'offline') {
await startApp('offline');
return;
}
showLanding('Google sign-in is available once env.js is generated from SUPABASE_URL and SUPABASE_ANON_KEY.');
return;
}
const supabaseClient = ensureClient();
supabaseClient.auth.onAuthStateChange((_event, session) => {
if (!isAuthReady) {
setSession(session);
return;
}
setSession(session);
if (session) {
setStoredMode('authenticated');
startApp('authenticated', session);
return;
}
if (getStoredMode() === 'offline') {
startApp('offline');
return;
}
showLanding('Sign in with Google or continue offline on this device.');
});
try {
const { data, error } = await supabaseClient.auth.getSession();
if (error) throw error;
if (data?.session) {
setSession(data.session);
setStoredMode('authenticated');
await startApp('authenticated', data.session);
return;
}
} catch (err) {
console.error('Session bootstrap failed', err);
showLanding('Sign-in is unavailable right now. You can still continue offline.', 'error');
return;
}
if (getStoredMode() === 'offline') {
await startApp('offline');
return;
}
showLanding('Sign in with Google or continue offline on this device.');
}
return {
bootstrap,
getSession: () => currentSession,
getUser: () => currentSession?.user || null,
isAuthenticated: () => !!currentSession?.user,
};
})();
// ==== DB MODULE (IndexedDB via idb) ====
/* global idb */
const DB = (() => {
const DB_NAME = 'hrr-setlist-db';
const DB_VERSION = 2; // bump when schema changes
const REQUIRED_STORES = ['songs', 'setlists', 'meta'];
let _db;
let _dbWasReset = false;
const hasRequiredStores = (db) =>
REQUIRED_STORES.every((name) => db.objectStoreNames.contains(name));
const upgradeSchema = (db) => {
if (!db.objectStoreNames.contains('songs')) {
const songs = db.createObjectStore('songs', { keyPath: 'id' });
if (songs.createIndex) songs.createIndex('title', 'title', { unique: false });
}
if (!db.objectStoreNames.contains('setlists')) {
const setlists = db.createObjectStore('setlists', { keyPath: 'id' });
if (setlists.createIndex) setlists.createIndex('name', 'name', { unique: false });
}
if (!db.objectStoreNames.contains('meta')) {
db.createObjectStore('meta'); // for flags like 'migrated'
}
};
async function backupExistingData(db) {
const backup = { songs: [], setlists: [] };
try {
const storeNames = Array.from(db.objectStoreNames);
if (storeNames.includes('songs')) backup.songs = await db.getAll('songs');
if (storeNames.includes('setlists')) backup.setlists = await db.getAll('setlists');
} catch (e) {
console.warn('Failed to backup data before DB reset', e);
}
return backup;
}
async function restoreBackup(db, backup) {
if (!backup) return;
try {
if (Array.isArray(backup.songs) && backup.songs.length) {
const tx = db.transaction('songs', 'readwrite');
for (const song of backup.songs) await tx.store.put(song);
await tx.done;
}
} catch (e) {
console.warn('Failed to restore songs after DB reset', e);
}
try {
if (Array.isArray(backup.setlists) && backup.setlists.length) {
const tx = db.transaction('setlists', 'readwrite');
for (const setlist of backup.setlists) await tx.store.put(setlist);
await tx.done;
}
} catch (e) {
console.warn('Failed to restore setlists after DB reset', e);
}
}
async function open() {
if (_db) return _db;
_db = await idb.openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
upgradeSchema(db);
}
});
if (!hasRequiredStores(_db)) {
const backup = await backupExistingData(_db);
try {
_db.close();
await idb.deleteDB(DB_NAME);
_db = await idb.openDB(DB_NAME, DB_VERSION, { upgrade: upgradeSchema });
_dbWasReset = true;
} catch (e) {
console.error('Failed to repair DB', e);
}
try {
await restoreBackup(_db, backup);
} catch (e) {
console.warn('Failed to restore DB backup', e);
}
}
return _db;
}
async function getMeta(key) {
const db = await open();
return db.get('meta', key);
}
async function setMeta(key, val) {
const db = await open();
return db.put('meta', val, key);
}
// Songs
async function getAllSongs() {
const db = await open();
return db.getAll('songs');
}
async function putSong(song) {
const db = await open();
return db.put('songs', song);
}
async function putSongs(songs) {
const db = await open();
const tx = db.transaction('songs', 'readwrite');
for (const s of songs) await tx.store.put(s);
await tx.done;
}
async function deleteSong(id) {
const db = await open();
return db.delete('songs', id);
}
async function clearSongs() {
const db = await open();
const tx = db.transaction('songs', 'readwrite');
await tx.store.clear();
await tx.done;
}
// Setlists
async function getAllSetlists() {
const db = await open();
return db.getAll('setlists');
}
async function getSetlist(id) {
const db = await open();
return db.get('setlists', id);
}
async function putSetlist(setlist) {
const db = await open();
return db.put('setlists', setlist);
}
async function deleteSetlist(id) {
const db = await open();
return db.delete('setlists', id);
}
return {
getMeta, setMeta,
getAllSongs, putSong, putSongs, deleteSong, clearSongs,
getAllSetlists, getSetlist, putSetlist, deleteSetlist,
wasReset: () => _dbWasReset,
};
})();
// ==== SETLIST MANAGER MODULE
function normalizeSmartQuotes(input) {
return String(input == null ? '' : input)
.replace(/[\u2018\u2019\u201A\u201B]/g, "'")
.replace(/[\u201C\u201D\u2033]/g, '"')
.replace(/[\u2013\u2014\u2212]/g, '-');
}
function normalizeSetlistName(name) {
let trimmed = normalizeSmartQuotes(name).replace(/\.[^.\s]+$/, '');
trimmed = trimmed.replace(/_/g, ' ');
trimmed = trimmed.replace(/\s+/g, ' ');
trimmed = trimmed.replace(/[\u0000-\u001F\u007F]/g, '');
trimmed = trimmed.trim();
if (!trimmed) return 'Untitled Setlist';
trimmed = trimmed.replace(/([a-z])([A-Z])/g, '$1 $2');
trimmed = trimmed.replace(/\w\S*/g, (word) =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
);
return trimmed;
}
function normalizeSongTitleValue(title) {
let t = normalizeSmartQuotes(title).replace(/\.[^.\s]+$/, '');
t = t.replace(/_/g, ' ');
t = t.replace(/\s+/g, ' ');
t = t.replace(/[\u0000-\u001F\u007F]/g, '');
t = t.trim();
if (!t) return '';
t = t.replace(/([a-z])([A-Z])/g, '$1 $2');
t = t.replace(/\w\S*/g, (word) =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
);
return t;
}
function stripDuplicateTitleFromLyrics(title, text) {
const normalizedTitle = String(title || '').trim().replace(/\s+/g, ' ').toLowerCase();
if (!normalizedTitle) return String(text || '').replace(/\r\n?/g, '\n');
const lines = String(text || '').replace(/\r\n?/g, '\n').split('\n');
let idx = 0;
while (idx < lines.length && lines[idx].trim() === '') idx++;
if (idx < lines.length) {
const first = lines[idx].trim().replace(/\s+/g, ' ').toLowerCase();
if (first === normalizedTitle) {
lines.splice(idx, 1);
while (idx < lines.length && lines[idx].trim() === '') {
lines.splice(idx, 1);
}
}
}
return lines.join('\n');
}
function normalizeLyricsBlock(title, lyrics) {
const normalized = String(lyrics || '')
.replace(/\r\n?/g, '\n')
.replace(/\u00A0/g, ' ')
.replace(/[ \t]+\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trimEnd();
return stripDuplicateTitleFromLyrics(title, normalized);
}
// ==== TOASTS ====
function showToast(message, type = 'success', timeout = 2500) {
const toast = document.createElement('div');
toast.className = `toast toast-${type} show`;
toast.textContent = message;
document.body.appendChild(toast);
requestAnimationFrame(() => {
toast.style.opacity = '1';
toast.style.transform = 'translateX(0)';
});
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(100%)';
setTimeout(() => toast.remove(), 300);
}, timeout);
}
function confirmDialog(message, onYes, onNo) {
const modal = document.createElement('div');
modal.className = 'modal';
modal.style.display = 'flex';
const content = document.createElement('div');
content.className = 'modal-content';
const h2 = document.createElement('h2');
h2.textContent = 'Confirm';
const p = document.createElement('p');
p.textContent = String(message || 'Are you sure?');
const actions = document.createElement('div');
actions.className = 'modal-actions';
const yes = document.createElement('button'); yes.className = 'btn'; yes.id = 'confirm-yes'; yes.textContent = 'Yes';
const no = document.createElement('button'); no.className = 'btn'; no.id = 'confirm-no'; no.textContent = 'No';
actions.appendChild(yes); actions.appendChild(no);
content.appendChild(h2); content.appendChild(p); content.appendChild(actions);
modal.appendChild(content);
document.body.appendChild(modal);
yes.onclick = () => { modal.remove(); onYes && onYes(); };
no.onclick = () => { modal.remove(); onNo && onNo(); };
}
// Toast with optional action button for undo
function showActionToast(message, { actionText, onAction, timeout = 4000, type = 'info' } = {}) {
const toast = document.createElement('div');
toast.className = `toast toast-${type} show`;
const span = document.createElement('span');
span.textContent = String(message || '');
toast.appendChild(span);
if (actionText && typeof onAction === 'function') {
const btn = document.createElement('button');
btn.className = 'btn toast-action';
btn.type = 'button';
btn.textContent = actionText;
btn.addEventListener('click', () => { try { onAction(); } finally { toast.remove(); } });
toast.appendChild(btn);
}
document.body.appendChild(toast);
requestAnimationFrame(() => { toast.style.opacity = '1'; toast.style.transform = 'translateX(0)'; });
setTimeout(() => { toast.style.opacity = '0'; toast.style.transform = 'translateX(100%)'; setTimeout(() => toast.remove(), 300); }, timeout);
}
const SetlistsManager = (() => {
let setlists = new Map();
async function load() {
try {
const arr = await DB.getAllSetlists();
const repaired = [];
for (const obj of (arr || [])) {
const fixed = { ...obj };
// Repair missing or malformed fields from older local data
if (!fixed || typeof fixed !== 'object') continue;
if (!fixed.id) {
fixed.id = (Date.now().toString() + Math.random().toString(16).slice(2));
fixed.updatedAt = Date.now();
try { await DB.putSetlist(fixed); } catch {}
}
if (!Array.isArray(fixed.songs)) fixed.songs = [];
repaired.push(fixed);
}
setlists = new Map(repaired.map(obj => [obj.id, obj]));
} catch (error) {
console.error('Failed loading setlists from DB', error);
setlists = new Map();
}
}
function save() { /* no-op; per-change writes to DB */ }
function getAllSetlists() {
return Array.from(setlists.values()).sort((a, b) => a.name.localeCompare(b.name));
}
function getSetlistById(id) {
return setlists.get(id) || null;
}
function addSetlist(name, songIds = []) {
const normalized = normalizeSetlistName(name);
const existing = Array.from(setlists.values()).find(s =>
s.name.toLowerCase() === normalized.toLowerCase()
);
let finalName = normalized;
if (existing) {
let counter = 1;
while (Array.from(setlists.values()).find(s =>
s.name.toLowerCase() === `${normalized} (${counter})`.toLowerCase()
)) { counter++; }
finalName = `${normalized} (${counter})`;
}
const setlist = {
id: (Date.now().toString() + Math.random().toString(16).slice(2)),
name: finalName,
songs: [...songIds],
createdAt: Date.now(),
updatedAt: Date.now()
};
setlists.set(setlist.id, setlist);
DB.putSetlist(setlist);
return setlist;
}
function renameSetlist(id, newName) {
const setlist = setlists.get(id);
if (setlist) {
const normalized = normalizeSetlistName(newName);
const existing = Array.from(setlists.values()).find(s =>
s.id !== id && s.name.toLowerCase() === normalized.toLowerCase()
);
if (existing) throw new Error(`A setlist named "${normalized}" already exists`);
setlist.name = normalized;
setlist.updatedAt = Date.now();
DB.putSetlist(setlist);
return setlist;
}
return null;
}
function duplicateSetlist(id) {
const orig = getSetlistById(id);
if (orig) return addSetlist(orig.name + ' Copy', orig.songs);
return null;
}
function deleteSetlist(id) {
const deleted = setlists.delete(id);
if (deleted) DB.deleteSetlist(id);
return deleted;
}
function updateSetlistSongs(id, songIds) {
const setlist = setlists.get(id);
if (setlist) {
setlist.songs = [...songIds];
setlist.updatedAt = Date.now();
DB.putSetlist(setlist);
return setlist;
}
return null;
}
function addSongToSetlist(setlistId, songId) {
const setlist = setlists.get(setlistId);
if (setlist && !setlist.songs.includes(songId)) {
setlist.songs.push(songId);
setlist.updatedAt = Date.now();
DB.putSetlist(setlist);
return setlist;
}
return null;
}
function removeSongFromSetlist(setlistId, songId) {
const setlist = setlists.get(setlistId);
if (setlist) {
const index = setlist.songs.indexOf(songId);
if (index > -1) {
setlist.songs.splice(index, 1);
setlist.updatedAt = Date.now();
DB.putSetlist(setlist);
return setlist;
}
}
return null;
}
function moveSongInSetlist(setlistId, songId, direction) {
const setlist = setlists.get(setlistId);
if (!setlist) return null;
const currentIndex = setlist.songs.indexOf(songId);
if (currentIndex === -1) return null;
const newIndex = currentIndex + direction;
if (newIndex < 0 || newIndex >= setlist.songs.length) return null;
[setlist.songs[currentIndex], setlist.songs[newIndex]] =
[setlist.songs[newIndex], setlist.songs[currentIndex]];
setlist.updatedAt = Date.now();
DB.putSetlist(setlist);
return setlist;
}
function importSetlistFromText(name, text, allSongs) {
// Normalize and trim setlist name
const normalizedName = String(name||'').trim();
if (!normalizedName) { showToast('Setlist name cannot be empty.', 'error'); return null; }
// Helpers for OCR cleanup and normalization
const cleanLine = (s) => String(s||'')
.replace(/[\u2018\u2019\u201A\u2032\u00B4]/g, "'")
.replace(/[\u201C\u201D\u2033]/g, '"')
.replace(/[\u2013\u2014\u2212]/g, '-')
.replace(/[\u2022\u2023\u25E6\u2043\u2219\u00B7]/g, '') // bullets/middots
.replace(/^\s*[•*\-–—]\s*/, '') // leading bullets/dashes
.replace(/^\s*\d+[\).\:\-]?\s*/, '') // leading numbering
.replace(/\s{2,}/g, ' ')
.trim();
const normalize = (s) => cleanLine(s)
.normalize('NFD')
.replace(/\p{Diacritic}+/gu, '')
.toLowerCase()
.replace(/[“”‘’]/g, '')
.replace(/[^a-z0-9\s]/g, ' ')
.replace(/\b0\b/g, 'o')
.replace(/\b1\b/g, 'l')
.replace(/\s{2,}/g, ' ')
.trim();
const isChordToken = (tok) => /^[A-G](#|b)?(maj|min|m|sus|add|dim|aug)?\d*(\/[A-G](#|b)?)?$/.test(tok);
const isChordLine = (line) => {
const toks = cleanLine(line).split(/\s+/).filter(Boolean);
if (toks.length < 2 || toks.length > 8) return false;
const chordCount = toks.filter(isChordToken).length;
return chordCount >= Math.max(2, Math.ceil(toks.length * 0.6));
};
const isProbableTitle = (line) => {
const t = cleanLine(line);
if (!t) return false;
if (t.length < 2 || t.length > 64) return false;
const letters = (t.match(/[A-Za-z]/g)||[]).length;