Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2083 lines (1871 loc) · 99.3 KB
/
Copy pathscript.js
File metadata and controls
2083 lines (1871 loc) · 99.3 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
/* ============================================================
NEXA — script.js | SaaS Productivity Platform v3 + Auth
Firebase Authentication layer prepended.
All original features 100% preserved.
Data is UID-scoped so every user has isolated storage.
============================================================ */
'use strict';
/* ════════════════════════════════════════════════════════════
① FIREBASE CONFIG
════════════════════════════════════════════════════════════
HOW TO GET THESE VALUES:
1. https://console.firebase.google.com → your project
2. Gear ⚙ → Project Settings → "Your apps" tab
3. Click your Web app (or "Add app" → Web)
4. Copy every value from the firebaseConfig shown
5. Paste below, replacing each placeholder string
ENABLE AUTH PROVIDERS (Firebase Console):
Build → Authentication → Get started → Sign-in method
• Email/Password → Enable → Save
• Google → Enable → pick support email → Save
AUTHORISED DOMAINS:
Authentication → Settings → Authorised domains
→ add your production hostname (localhost is pre-added)
FUTURE FIRESTORE SYNC ARCHITECTURE:
When you're ready to move from localStorage to Firestore:
• Uncomment the Firestore SDK <script> in index.html
• Replace load(LS.TASKS, []) with:
await db.collection('users').doc(AUTH.currentUser.uid)
.collection('tasks').get()
• Replace saveWithIndicator(LS.TASKS, tasks) with:
batch-write to users/{uid}/tasks/{taskId}
• All state keys below already use uid-prefixed keys,
so the migration is purely a swap of read/write fns.
════════════════════════════════════════════════════════════ */
const FIREBASE_CONFIG = {
apiKey: "AIzaSyCd_pwMAWDm-0S81tbY9Zc4KhMfR_DHTR0",
authDomain: "velora-os-5fc9e.firebaseapp.com",
projectId: "velora-os-5fc9e",
storageBucket: "velora-os-5fc9e.firebasestorage.app",
messagingSenderId: "744879781525",
appId: "1:744879781525:web:e17623b6b8e11e9a800d9c",
};
/* Initialise Firebase (only once) */
firebase.initializeApp(FIREBASE_CONFIG);
const AUTH = firebase.auth();
/* Google provider */
const GOOGLE_PROVIDER = new firebase.auth.GoogleAuthProvider();
GOOGLE_PROVIDER.addScope('email');
GOOGLE_PROVIDER.addScope('profile');
/* Persist session across browser restarts */
AUTH.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
/* ── Current authenticated user (set by onAuthStateChanged) ── */
let currentUser = null;
/* ─────────────────────────────────────────────────────────
requireAuth(action)
Single centralized auth check. Call this before any
action that needs a real user. Returns true if authed.
In guest mode: shows auth modal + toast, returns false.
─────────────────────────────────────────────────────────*/
function requireAuth(action = "use this feature") {
if (currentUser) return true;
showAuthModal();
authShowToast(`Sign in to ${action}`, "warn");
return false;
}
/* ════════════════════════════════════════════════════════════
② AUTH UI HELPERS (Preview-first system)
The app is ALWAYS visible. Auth gate is now an in-app modal
shown only when a guest clicks a locked feature.
════════════════════════════════════════════════════════════ */
const authGate = document.getElementById('auth-gate');
const authLoader = document.getElementById('auth-loader');
const appWrapper = document.getElementById('app-wrapper');
const showAuthLoader = (text = 'Loading…') => {
document.getElementById('auth-loader-text').textContent = text;
authLoader.classList.remove('auth-loader-hidden');
};
const hideAuthLoader = () => authLoader.classList.add('auth-loader-hidden');
/* Show/hide auth as an in-app modal (NOT a blocking gate) */
const showAuthModal = () => {
authGate.classList.remove('auth-gate-hidden');
};
const hideAuthModal = () => {
authGate.classList.add('auth-gate-hidden');
/* Reset any loading states on auth buttons */
document.querySelectorAll('.auth-submit-btn, .auth-google-btn').forEach(b => setBtnLoading(b, false));
};
/* Legacy alias */
const showAuthGate = showAuthModal;
/* showApp: only hides the modal, never needed to show appWrapper
(appWrapper is always visible — loader covers it during boot) */
const showApp = () => {
hideAuthModal();
};
/* Button loading state */
const setBtnLoading = (btn, on) => {
btn.disabled = on;
btn.classList.toggle('auth-btn-loading', on);
};
/* Auth error → friendly message */
const authErrMsg = code => ({
'auth/invalid-email': 'Please enter a valid email address.',
'auth/user-not-found': 'No account found with that email.',
'auth/wrong-password': 'Incorrect password. Try again.',
'auth/invalid-credential': 'Invalid email or password.',
'auth/email-already-in-use': 'That email is already registered. Sign in instead.',
'auth/weak-password': 'Password must be at least 6 characters.',
'auth/too-many-requests': 'Too many attempts — please wait a moment.',
'auth/network-request-failed':'Network error. Check your connection.',
'auth/popup-closed-by-user': null, /* user cancelled — stay silent */
'auth/popup-blocked': 'Popup was blocked. Allow popups for this site.',
'auth/account-exists-with-different-credential':
'An account already exists with this email using a different sign-in method.',
}[code] || `Something went wrong (${code}).`);
/* ════════════════════════════════════════════════════════════
③ AUTH TAB SWITCHING
════════════════════════════════════════════════════════════ */
document.querySelectorAll('.auth-tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.auth-tab').forEach(t => {
t.classList.remove('active');
t.setAttribute('aria-selected', 'false');
});
tab.classList.add('active');
tab.setAttribute('aria-selected', 'true');
document.querySelectorAll('.auth-panel').forEach(p => p.classList.remove('active'));
document.getElementById(`auth-panel-${tab.dataset.authTab}`).classList.add('active');
});
});
/* ── Password show/hide toggles ── */
document.querySelectorAll('.auth-pw-eye').forEach(btn => {
btn.addEventListener('click', () => {
const inp = document.getElementById(btn.dataset.target);
inp.type = inp.type === 'password' ? 'text' : 'password';
btn.textContent = inp.type === 'password' ? '👁' : '🙈';
});
});
/* ── Enter key on auth inputs ── */
['auth-login-email', 'auth-login-pass'].forEach(id => {
document.getElementById(id).addEventListener('keydown', e => {
if (e.key === 'Enter') document.getElementById('auth-login-btn').click();
});
});
['auth-signup-name', 'auth-signup-email', 'auth-signup-pass'].forEach(id => {
document.getElementById(id).addEventListener('keydown', e => {
if (e.key === 'Enter') document.getElementById('auth-signup-btn').click();
});
});
/* ════════════════════════════════════════════════════════════
④ EMAIL / PASSWORD — SIGN IN
════════════════════════════════════════════════════════════ */
document.getElementById('auth-login-btn').addEventListener('click', async () => {
const email = document.getElementById('auth-login-email').value.trim();
const pass = document.getElementById('auth-login-pass').value;
const btn = document.getElementById('auth-login-btn');
if (!email) return authShowToast('Please enter your email address.', 'warn');
if (!pass) return authShowToast('Please enter your password.', 'warn');
setBtnLoading(btn, true);
try {
await AUTH.signInWithEmailAndPassword(email, pass);
/* onAuthStateChanged will fire and boot the app */
} catch (err) {
const msg = authErrMsg(err.code);
if (msg) authShowToast(msg, 'error');
setBtnLoading(btn, false);
}
});
/* ════════════════════════════════════════════════════════════
⑤ EMAIL / PASSWORD — SIGN UP
════════════════════════════════════════════════════════════ */
document.getElementById('auth-signup-btn').addEventListener('click', async () => {
const name = document.getElementById('auth-signup-name').value.trim();
const email = document.getElementById('auth-signup-email').value.trim();
const pass = document.getElementById('auth-signup-pass').value;
const btn = document.getElementById('auth-signup-btn');
if (!name) return authShowToast('Please enter your name.', 'warn');
if (!email) return authShowToast('Please enter your email address.', 'warn');
if (pass.length < 6)return authShowToast('Password must be at least 6 characters.', 'warn');
setBtnLoading(btn, true);
try {
const cred = await AUTH.createUserWithEmailAndPassword(email, pass);
await cred.user.updateProfile({ displayName: name });
await cred.user.reload();
/* onAuthStateChanged fires next */
} catch (err) {
const msg = authErrMsg(err.code);
if (msg) authShowToast(msg, 'error');
setBtnLoading(btn, false);
}
});
/* ════════════════════════════════════════════════════════════
⑥ GOOGLE SIGN-IN (shared by both panels)
════════════════════════════════════════════════════════════ */
const handleGoogleSignIn = async btnId => {
const btn = document.getElementById(btnId);
setBtnLoading(btn, true);
try {
await AUTH.signInWithPopup(GOOGLE_PROVIDER);
} catch (err) {
const msg = authErrMsg(err.code);
if (msg) authShowToast(msg, 'error');
setBtnLoading(btn, false);
}
};
document.getElementById('auth-google-login-btn') .addEventListener('click', () => handleGoogleSignIn('auth-google-login-btn'));
document.getElementById('auth-google-signup-btn').addEventListener('click', () => handleGoogleSignIn('auth-google-signup-btn'));
/* ════════════════════════════════════════════════════════════
⑦ FORGOT PASSWORD
════════════════════════════════════════════════════════════ */
document.getElementById('auth-forgot-btn').addEventListener('click', async () => {
const email = document.getElementById('auth-login-email').value.trim();
if (!email) return authShowToast('Enter your email above, then click "Forgot password".', 'warn');
try {
await AUTH.sendPasswordResetEmail(email);
authShowToast('Password reset email sent — check your inbox.', 'success');
} catch (err) {
const msg = authErrMsg(err.code);
if (msg) authShowToast(msg, 'error');
}
});
/* ════════════════════════════════════════════════════════════
⑧ SIGN OUT (called from sidebar chip + settings card)
════════════════════════════════════════════════════════════ */
const handleSignOut = async () => {
try {
await AUTH.signOut();
/* onAuthStateChanged fires → showAuthGate() */
} catch (err) {
showToast('Sign-out failed. Please try again.', 't-warning');
}
};
/* ════════════════════════════════════════════════════════════
⑨ AUTH-GATE TOAST (small inline toasts on the auth card,
separate from the main app toast system)
════════════════════════════════════════════════════════════ */
let _authToastTimer = null;
const authShowToast = (msg, type = 'info') => {
let el = document.getElementById('auth-inline-toast');
if (!el) {
el = document.createElement('div');
el.id = 'auth-inline-toast';
document.getElementById('auth-card').appendChild(el);
}
el.textContent = msg;
el.className = `auth-inline-toast auth-toast-${type} auth-toast-show`;
clearTimeout(_authToastTimer);
_authToastTimer = setTimeout(() => el.classList.remove('auth-toast-show'), 4500);
};
/* ════════════════════════════════════════════════════════════
GLOBAL AUTH STATE (Preview-first LOCK SYSTEM)
════════════════════════════════════════════════════════════ */
/* ════════════════════════════════════════════════════════════
GLOBAL AUTH STATE — DETERMINISTIC, NO FLICKER
─────────────────────────────────────────────────────────
Flow:
1. Auth loader covers the app during Firebase boot
2. onAuthStateChanged fires exactly once after boot
3. If user → bootApp(uid), remove guest-mode
4. If no user → bootGuestMode(), add guest-mode
5. Loader hides — app is fully visible, no flicker
════════════════════════════════════════════════════════════ */
let _authBooted = false; /* prevent double-boot on hot reloads */
/* ── NUCLEAR FALLBACK: if ANYTHING blocks Firebase from responding
(wrong authDomain, network issue, Vercel config, cold start offline)
this timer fires after 5s and boots the app no matter what.
Without this, a single Firebase hiccup = infinite loading screen. ── */
const _authFallbackTimer = setTimeout(() => {
if (_authBooted) return; /* Firebase already responded — do nothing */
_authBooted = true;
console.warn('[NEXA] Firebase Auth did not respond within 5s — forcing boot.');
hideAuthLoader();
/* Try to recover a cached Firebase user from localStorage */
let cachedUser = null;
try {
const fbKey = Object.keys(localStorage)
.find(k => k.startsWith('firebase:authUser:') || k.includes(':authUser:'));
if (fbKey) {
const parsed = JSON.parse(localStorage.getItem(fbKey));
if (parsed && parsed.uid) cachedUser = parsed;
}
} catch (_) { /* ignore */ }
if (cachedUser) {
/* Restore session from cache — user won't need to re-login */
currentUser = cachedUser;
document.body.classList.remove('guest-mode');
hideAuthModal();
try { populateUserUI(cachedUser); } catch(_) {}
bootApp(cachedUser.uid);
showToast('📶 Offline mode — showing your cached data', 't-info', 4000);
} else {
/* No cached session — boot as guest so app is usable */
currentUser = null;
document.body.classList.add('guest-mode');
bootGuestMode();
}
}, 5000);
AUTH.onAuthStateChanged(user => {
/* Firebase responded — cancel the fallback timer immediately */
clearTimeout(_authFallbackTimer);
/* If fallback already ran, handle sign-in/out transitions only */
if (_authBooted) {
currentUser = user || null;
if (user) {
document.body.classList.remove('guest-mode');
hideAuthModal();
populateUserUI(user);
bootApp(user.uid);
} else {
document.body.classList.add('guest-mode');
bootGuestMode();
}
return;
}
/* Normal first-boot path */
_authBooted = true;
hideAuthLoader();
currentUser = user || null;
if (user) {
document.body.classList.remove('guest-mode');
hideAuthModal();
populateUserUI(user);
bootApp(user.uid);
} else {
document.body.classList.add('guest-mode');
bootGuestMode();
}
});
/* ════════════════════════════════════════════════════════════
⑪ USER UI — populate sidebar chip + settings profile card
════════════════════════════════════════════════════════════ */
const getInitials = name => {
if (!name) return '?';
return name.trim().split(/\s+/).map(w => w[0].toUpperCase()).slice(0, 2).join('');
};
const populateUserUI = user => {
const name = user.displayName || user.email.split('@')[0];
const email = user.email || '';
const initials = getInitials(name);
const photoURL = user.photoURL;
const provider = (user.providerData[0]?.providerId || 'password') === 'google.com' ? 'Google' : 'Email';
/* Sidebar chip */
const ava = document.getElementById('suc-avatar');
if (photoURL) {
ava.innerHTML = `<img src="${photoURL}" alt="${escH(name)}" referrerpolicy="no-referrer" style="width:100%;height:100%;object-fit:cover;border-radius:50%"/>`;
} else {
ava.textContent = initials;
}
document.getElementById('suc-name').textContent = name;
document.getElementById('suc-email').textContent = email;
/* Settings account card */
const sa = document.getElementById('settings-avatar');
if (sa) {
if (photoURL) {
sa.innerHTML = `<img src="${photoURL}" alt="" referrerpolicy="no-referrer" style="width:100%;height:100%;object-fit:cover;border-radius:50%"/>`;
} else {
sa.textContent = initials;
}
}
const setText = (id, val) => { const el = document.getElementById(id); if (el) el.textContent = val; };
setText('settings-display-name', name);
setText('settings-email', email);
setText('settings-provider-tag', provider);
setText('settings-uid', user.uid);
setText('settings-verified', user.emailVerified ? '✓ Yes' : '✗ No');
setText('settings-created', user.metadata?.creationTime
? new Date(user.metadata.creationTime).toLocaleDateString('en-US', {year:'numeric',month:'short',day:'numeric'})
: '—');
setText('settings-lastlogin', user.metadata?.lastSignInTime
? new Date(user.metadata.lastSignInTime).toLocaleDateString('en-US', {year:'numeric',month:'short',day:'numeric'})
: '—');
};
/* ── Sidebar user chip flyout ── */
const sucFlyout = document.getElementById('suc-flyout');
const sucMenuBtn = document.getElementById('suc-menu-btn');
sucMenuBtn.addEventListener('click', e => {
e.stopPropagation();
sucFlyout.classList.toggle('hidden');
});
document.addEventListener('click', () => sucFlyout.classList.add('hidden'));
document.getElementById('suc-signout-btn').addEventListener('click', handleSignOut);
document.getElementById('suc-profile-btn').addEventListener('click', () => {
sucFlyout.classList.add('hidden');
switchTab('settings');
});
/* ════════════════════════════════════════════════════════════
⑪b AUTH MODAL CONTROLS
Close button, backdrop click, guest sign-in buttons
════════════════════════════════════════════════════════════ */
document.getElementById('auth-modal-close').addEventListener('click', hideAuthModal);
authGate.addEventListener('click', e => { if (e.target === authGate) hideAuthModal(); });
/* All "Sign In" triggers throughout the guest UI */
const wireGuestSignIn = (id) => {
const el = document.getElementById(id);
if (el) el.addEventListener('click', showAuthModal);
};
wireGuestSignIn('sidebar-guest-btn');
wireGuestSignIn('guest-banner-btn');
/* ════════════════════════════════════════════════════════════
⑪c GUEST MODE — CAPTURE-PHASE INTERCEPTOR
Intercepts clicks on locked interactive elements
before any existing handlers can fire.
════════════════════════════════════════════════════════════ */
const LOCKED_SELECTORS = [
'#add-btn', '.task-input', '.edit-btn', '.delete-btn', '.task-check',
'.notes-btn', '.drag-handle',
'#pomo-start', '#pomo-reset', '#pomo-skip',
'#fs-start', '#fs-reset', '#fs-skip',
'#fullscreen-btn',
'#bulk-toggle-btn', '#bulk-complete', '#bulk-delete', '#bulk-priority-btn',
'#export-btn', '#import-btn',
'#settings-export', '#settings-import', '#settings-clear',
'.settings-action-btn', '.toggle-btn',
'.pomo-mode-btn', '.set-input',
'.p-chip', '.date-input', '#due-date', '#recur-select',
];
document.addEventListener('click', e => {
if (currentUser) return; /* authenticated — allow everything */
/* Never intercept navigation — nav items must always work in guest mode */
if (e.target.closest('.nav-item')) return;
if (e.target.closest('.sidebar-guest-btn')) return;
if (e.target.closest('.guest-banner-btn')) return;
if (e.target.closest('.auth-modal-close')) return;
if (e.target.closest('#hamburger')) return;
if (e.target.closest('#sidebar-close')) return;
if (e.target.closest('#theme-toggle')) return;
if (e.target.closest('#sound-toggle')) return;
if (e.target.closest('#cmd-trigger')) return;
const isLocked = LOCKED_SELECTORS.some(sel => e.target.closest(sel));
if (isLocked) {
e.preventDefault();
e.stopImmediatePropagation();
showAuthModal();
}
}, true); /* ← capture phase */
/* Also block keyboard entry in task input for guests */
document.addEventListener('keydown', e => {
if (currentUser) return;
const inTaskInput = e.target.closest('#task-input');
if (inTaskInput && e.key !== 'Tab') {
e.preventDefault();
e.stopImmediatePropagation();
showAuthModal();
}
}, true);
/* Block drag events for guests */
document.addEventListener('dragstart', e => {
if (currentUser) return;
if (e.target.closest('.task-item')) {
e.preventDefault();
e.stopImmediatePropagation();
}
}, true);
/* Block touch-swipe actions for guests */
let _guestTouchBlocked = false;
document.addEventListener('touchstart', e => {
if (currentUser) return;
if (e.target.closest('.task-item .task-check') ||
e.target.closest('.task-item .edit-btn') ||
e.target.closest('.task-item .delete-btn')) {
_guestTouchBlocked = true;
}
}, { capture: true, passive: true });
document.addEventListener('touchend', e => {
if (_guestTouchBlocked) {
_guestTouchBlocked = false;
showAuthModal();
}
}, { capture: true, passive: true });
/* ════════════════════════════════════════════════════════════
⑫ UID-SCOPED STORAGE KEYS
Every key is prefixed with the user's UID so multiple
accounts on the same browser stay completely isolated.
Swap these read/write helpers for Firestore calls later.
════════════════════════════════════════════════════════════ */
let LS = {
TASKS: 'taskr_tasks',
FILTER: 'taskr_filter',
THEME: 'taskr_theme',
STREAK: 'taskr_streak',
HISTORY: 'taskr_history',
POMO: 'taskr_pomo_sets',
};
const scopeStorageKeys = uid => {
LS = {
TASKS: `taskr_${uid}_tasks`,
FILTER: `taskr_${uid}_filter`,
THEME: `taskr_theme`, /* theme is device-level, not per-user */
STREAK: `taskr_${uid}_streak`,
HISTORY: `taskr_${uid}_history`,
POMO: `taskr_${uid}_pomo_sets`,
};
};
/* ════════════════════════════════════════════════════════════
════════════════════════════════════════════════════════════
ORIGINAL TASKR APPLICATION CODE — 100% PRESERVED
Only changes:
• LS keys are now UID-scoped (set in bootApp below)
• INIT block moved into bootApp() so it runs post-auth
• initSettingsPage() wires signout buttons
════════════════════════════════════════════════════════════
════════════════════════════════════════════════════════════ */
/* ── Helpers ── */
const isGuest = () => document.body.classList.contains('guest-mode');
const uid = () => Math.random().toString(36).slice(2, 9);
const today = () => new Date().toISOString().slice(0, 10);
const escH = s => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
const fmt = s => { if (!s) return ''; const d = new Date(s + 'T00:00:00'); return d.toLocaleDateString('en-US', {month:'short',day:'numeric',year:'numeric'}); };
const fmtShort= s => { if (!s) return ''; const d = new Date(s + 'T00:00:00'); return d.toLocaleDateString('en-US', {month:'short',day:'numeric'}); };
const overdue = s => { if (!s) return false; const t = new Date(); t.setHours(0,0,0,0); return new Date(s+'T00:00:00') < t; };
const rel = ts => {
const d=Date.now()-ts, m=Math.floor(d/6e4), h=Math.floor(d/36e5), dy=Math.floor(d/864e5);
if (m < 1) return 'just now'; if (m < 60) return m+'m ago';
if (h < 24) return h+'h ago'; if (dy < 7) return dy+'d ago';
return new Date(ts).toLocaleDateString('en-US',{month:'short',day:'numeric'});
};
/* ── Load / Save ── */
const load = (k, def) => { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : def; } catch { return def; } };
const save = (k, v) => localStorage.setItem(k, JSON.stringify(v));
/* ── STATE (declared here, populated in bootApp) ── */
let tasks = [];
Object.defineProperty(window, 'tasks', { get: () => tasks, configurable: true });
let filter = 'all';
let selPri = 'low';
let dragId = null;
let lastAllDone = false;
let history = {};
let streak = { count: 0, lastDate: '' };
let searchQuery = '';
let bulkMode = false;
let bulkSelected = new Set();
let soundOn = localStorage.getItem('taskr_sound') !== '0';
let undoStack = [];
let undoTimer = null;
let calWeekOffset = 0;
let animationsReduced = localStorage.getItem('taskr_reduce_anim') === '1';
/* ── DOM shortcuts ── */
const $ = id => document.getElementById(id);
const tl = $('task-list');
const inp = $('task-input');
const addBtn = $('add-btn');
const ddInp = $('due-date');
const empState = $('empty-state');
const pFill = $('progress-fill');
const pPct = $('progress-pct');
const sDone = $('stat-done');
const sTotal = $('stat-total');
const sDoneTop = $('stat-done-top');
const sTotalTop = $('stat-total-top');
const confCanvas = $('confetti-canvas');
const confCtx = confCanvas.getContext('2d');
const inputBar = $('input-bar');
const taskTpl = $('task-tpl');
const searchInput= $('search-input');
const searchClear= $('search-clear');
const toastCont = $('toast-container');
const autoSaveEl = $('autosave-indicator');
const autoSaveLbl= $('autosave-label');
const cmdOverlay = $('cmd-overlay');
const cmdInput = $('cmd-input');
const cmdResults = $('cmd-results');
const bulkBar = $('bulk-bar');
const bulkCount = $('bulk-count');
const bulkToggle = $('bulk-toggle-btn');
const undoBanner = $('undo-banner');
const undoMsg = $('undo-msg');
const undoBar = $('undo-bar');
const ringFill = $('ring-fill');
const pomoTime = $('pomo-time');
const pomoLabel = $('pomo-label');
const pomoStart = $('pomo-start');
const pomoDots = $('pomo-dots');
const pomoCount = $('pomo-count');
/* ═══════════════════════════════════════════
THEME
═══════════════════════════════════════════ */
const applyTheme = t => {
document.documentElement.setAttribute('data-theme', t);
const metaTheme = $('meta-theme');
if (metaTheme) metaTheme.content = t === 'dark' ? '#0c0e12' : '#f0f2f6';
save(LS.THEME, t);
const st = $('settings-theme-toggle');
if (st) st.classList.toggle('on', t === 'dark');
};
const toggleTheme = () => {
const cur = document.documentElement.getAttribute('data-theme');
applyTheme(cur === 'dark' ? 'light' : 'dark');
};
$('theme-toggle').addEventListener('click', toggleTheme);
applyTheme(load('taskr_theme', 'dark')); /* theme loads immediately, pre-auth */
/* ═══════════════════════════════════════════
SOUND
═══════════════════════════════════════════ */
const updateSoundBtn = () => {
const sb = $('sound-toggle');
if (sb) { sb.textContent = soundOn ? '🔊' : '🔇'; sb.title = soundOn ? 'Sound on' : 'Sound off'; }
const st = $('settings-sound-toggle');
if (st) st.classList.toggle('on', soundOn);
};
updateSoundBtn();
$('sound-toggle').addEventListener('click', () => {
soundOn = !soundOn;
localStorage.setItem('taskr_sound', soundOn ? '1' : '0');
updateSoundBtn();
showToast(soundOn ? 'Sound enabled' : 'Sound muted', 't-info', 2000);
});
const playClick = (freq = 660, dur = 0.12) => {
if (!soundOn) return;
try {
const ac = new (window.AudioContext || window.webkitAudioContext)();
const osc = ac.createOscillator(); const gain = ac.createGain();
osc.connect(gain); gain.connect(ac.destination);
osc.type = 'sine'; osc.frequency.value = freq;
gain.gain.setValueAtTime(0.15, ac.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, ac.currentTime + dur);
osc.start(); osc.stop(ac.currentTime + dur);
} catch {}
};
const playBeep = () => {
try {
const ac = new (window.AudioContext || window.webkitAudioContext)();
const osc = ac.createOscillator(); const gain = ac.createGain();
osc.connect(gain); gain.connect(ac.destination);
osc.type = 'sine'; osc.frequency.value = 880;
gain.gain.setValueAtTime(.4, ac.currentTime);
gain.gain.exponentialRampToValueAtTime(.001, ac.currentTime + .8);
osc.start(); osc.stop(ac.currentTime + .8);
} catch {}
};
/* ═══════════════════════════════════════════
SIDEBAR NAVIGATION
═══════════════════════════════════════════ */
const sidebar = $('sidebar');
const sidebarOverlay = $('sidebar-overlay');
const hamburger = $('hamburger');
const sidebarClose = $('sidebar-close');
const openSidebar = () => {
sidebar.classList.add('open');
sidebarOverlay.classList.add('visible');
hamburger.setAttribute('aria-expanded', 'true');
document.body.classList.add('sidebar-open');
};
const closeSidebar = () => {
sidebar.classList.remove('open');
sidebarOverlay.classList.remove('visible');
hamburger.setAttribute('aria-expanded', 'false');
document.body.classList.remove('sidebar-open');
};
hamburger.addEventListener('click', () => {
sidebar.classList.contains('open') ? closeSidebar() : openSidebar();
});
sidebarClose.addEventListener('click', closeSidebar);
/* Overlay: close sidebar only when tapping the dark backdrop area,
never when the tap originated inside the sidebar itself. */
sidebarOverlay.addEventListener('click', closeSidebar);
/* ═══════════════════════════════════════════
TAB SWITCHING
═══════════════════════════════════════════ */
const PAGE_TITLES = {
tasks:'Tasks', analytics:'Analytics', calendar:'Calendar', focus:'Focus', settings:'Settings',
};
const switchTab = name => {
document.querySelectorAll('.nav-item').forEach(b => {
const active = b.dataset.tab === name;
b.classList.toggle('active', active);
b.setAttribute('aria-selected', active ? 'true' : 'false');
});
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
const panel = $('tab-' + name);
if (panel) panel.classList.add('active');
inputBar.classList.toggle('hidden', name !== 'tasks');
const tt = $('topbar-title');
if (tt) tt.textContent = PAGE_TITLES[name] || name;
/* Close sidebar first on mobile so overlay is gone before render */
if (window.innerWidth <= 768) closeSidebar();
if (name === 'analytics') renderDashboardFull();
if (name === 'focus') syncPomoTaskList();
if (name === 'calendar') renderCalendar();
if (name === 'settings') initSettingsPage();
};
/* Expose switchTab globally so sidebar-mobile-fix.js and other modules can call it */
window.switchTab = switchTab;
document.querySelectorAll('.nav-item').forEach(btn => {
const onNav = e => {
e.stopPropagation();
switchTab(btn.dataset.tab);
};
btn.addEventListener('click', onNav);
});
/* ═══════════════════════════════════════════
PRIORITY CHIPS
═══════════════════════════════════════════ */
document.querySelectorAll('.p-chip').forEach(c => {
c.addEventListener('click', () => {
document.querySelectorAll('.p-chip').forEach(x => x.classList.remove('active'));
c.classList.add('active');
selPri = c.dataset.p;
});
});
/* ═══════════════════════════════════════════
STREAK
═══════════════════════════════════════════ */
const updateStreak = () => {
const d = today();
if (streak.lastDate === d) return;
const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1);
const yStr = yesterday.toISOString().slice(0, 10);
streak.count = (streak.lastDate === yStr || streak.lastDate === '') ? streak.count + 1 : 1;
streak.lastDate = d;
save(LS.STREAK, streak);
};
/* ═══════════════════════════════════════════
AUTOSAVE INDICATOR
═══════════════════════════════════════════ */
let autoSaveTimer = null;
const showAutosave = () => {
autoSaveEl.classList.add('saving', 'visible');
autoSaveLbl.textContent = 'Saving…';
clearTimeout(autoSaveTimer);
autoSaveTimer = setTimeout(() => {
autoSaveEl.classList.remove('saving');
autoSaveLbl.textContent = 'Saved';
autoSaveTimer = setTimeout(() => autoSaveEl.classList.remove('visible'), 1400);
}, 600);
};
const saveWithIndicator = (k, v) => { save(k, v); if (k === LS.TASKS) showAutosave(); };
/* ═══════════════════════════════════════════
TOAST SYSTEM
═══════════════════════════════════════════ */
const showToast = (msg, type = 't-info', duration = 3200) => {
const icons = { 't-success':'✓', 't-delete':'✕', 't-warning':'⚠', 't-info':'ℹ' };
const el = document.createElement('div');
el.className = `toast ${type}`;
el.setAttribute('role', 'alert');
el.innerHTML = `
<span class="toast-icon">${icons[type] || 'ℹ'}</span>
<span class="toast-msg">${msg}</span>
<button class="toast-close" aria-label="Dismiss">✕</button>
<div class="toast-progress" style="animation-duration:${duration}ms"></div>`;
const dismiss = () => {
el.classList.add('toast-out');
el.addEventListener('animationend', () => el.remove(), { once: true });
};
el.querySelector('.toast-close').addEventListener('click', dismiss);
el.addEventListener('click', dismiss);
toastCont.appendChild(el);
const t = setTimeout(dismiss, duration);
el.addEventListener('mouseenter', () => clearTimeout(t));
el.addEventListener('mouseleave', () => setTimeout(dismiss, 800));
};
/* ═══════════════════════════════════════════
UNDO SYSTEM
═══════════════════════════════════════════ */
const showUndo = (msg, restoreFn) => {
clearTimeout(undoTimer);
undoStack = [restoreFn];
undoMsg.textContent = msg;
undoBanner.classList.remove('hidden');
undoBar.style.animation = 'none';
void undoBar.offsetWidth;
undoBar.style.animation = 'undo-timer 5s linear forwards';
undoTimer = setTimeout(() => undoBanner.classList.add('hidden'), 5000);
};
$('undo-btn').addEventListener('click', () => {
if (undoStack.length) undoStack.pop()();
undoBanner.classList.add('hidden');
clearTimeout(undoTimer);
});
/* ═══════════════════════════════════════════
VISIBLE FILTER
═══════════════════════════════════════════ */
const visible = () => {
const todayStr = today();
if (filter === 'active') return tasks.filter(t => !t.done);
if (filter === 'done') return tasks.filter(t => t.done);
if (filter === 'high') return tasks.filter(t => t.pri === 'high' || t.pri === 'urgent');
if (filter === 'today') return tasks.filter(t => t.due === todayStr && !t.done);
if (filter === 'overdue') return tasks.filter(t => overdue(t.due) && !t.done);
return [...tasks];
};
/* ═══════════════════════════════════════════
BUILD TASK ELEMENT
═══════════════════════════════════════════ */
const buildTaskEl = t => {
const clone = taskTpl.content.cloneNode(true);
const li = clone.querySelector('.task-item');
li.dataset.id = t.id; li.dataset.p = t.pri;
if (t.done) li.classList.add('done');
if (overdue(t.due) && !t.done) li.classList.add('overdue');
li.querySelector('.task-text').innerHTML = escH(t.text);
const pm = { high:'● High', medium:'● Med', low:'● Low', urgent:'⚡ Urgent' };
li.querySelector('.priority-badge').textContent = pm[t.pri] || '';
const db = li.querySelector('.due-badge');
if (t.due) db.textContent = `📅 ${fmt(t.due)}${overdue(t.due) && !t.done ? ' ⚠' : ''}`;
li.querySelector('.created-badge').textContent = rel(t.at);
const rb = li.querySelector('.recur-badge');
if (t.recur) rb.textContent = `↻ ${t.recur}`;
if (t.notes) {
const ta = document.createElement('textarea');
ta.className = 'task-notes-textarea'; ta.placeholder = 'Add notes…'; ta.value = t.notes;
li.querySelector('.task-notes-content').appendChild(ta);
li.classList.add('notes-open');
ta.addEventListener('blur', () => { t.notes = ta.value; save(LS.TASKS, tasks); });
}
li.querySelector('.notes-btn').addEventListener('click', () => {
const wrap = li.querySelector('.task-notes-content');
const isOpen = li.classList.toggle('notes-open');
if (isOpen && !wrap.querySelector('textarea')) {
const ta = document.createElement('textarea');
ta.className = 'task-notes-textarea'; ta.placeholder = 'Add notes…'; ta.value = t.notes || '';
wrap.appendChild(ta);
requestAnimationFrame(() => ta.focus());
ta.addEventListener('blur', () => { t.notes = ta.value; save(LS.TASKS, tasks); });
}
});
const bellBtn = li.querySelector('.reminder-btn');
if (bellBtn) bellBtn.dataset.taskId = t.id;
return li;
};
window._nexaRender = () => render(); // expose render for reminders.js
/* ═══════════════════════════════════════════
RENDER
═══════════════════════════════════════════ */
const render = () => {
Array.from(tl.children).forEach(c => { if (!c.classList.contains('removing')) c.remove(); });
let vis = visible();
if (searchQuery) {
vis = vis.filter(t =>
t.text.toLowerCase().includes(searchQuery) ||
(t.notes && t.notes.toLowerCase().includes(searchQuery))
);
}
vis.forEach(t => tl.appendChild(buildTaskEl(t)));
const hasTasks = vis.length > 0;
empState.classList.toggle('hidden', hasTasks || !!searchQuery);
$('search-empty-state').classList.toggle('hidden', !searchQuery || hasTasks);
const tot = tasks.length, don = tasks.filter(t => t.done).length;
const pct = tot ? Math.round(don / tot * 100) : 0;
if (sDone) sDone.textContent = don;
if (sTotal) sTotal.textContent = tot;
if (sDoneTop) sDoneTop.textContent = don;
if (sTotalTop) sTotalTop.textContent = tot;
const statStreak = $('stat-streak');
if (statStreak) statStreak.textContent = streak.count + '🔥';
if (pFill) pFill.style.width = pct + '%';
if (pPct) pPct.textContent = pct + '%';
$('fc-all').textContent = tasks.length;
$('fc-act').textContent = tasks.filter(t => !t.done).length;
$('fc-don').textContent = tasks.filter(t => t.done).length;
$('fc-hi').textContent = tasks.filter(t => t.pri === 'high' || t.pri === 'urgent').length;
$('fc-today').textContent = tasks.filter(t => t.due === today() && !t.done).length;
$('fc-overdue').textContent = tasks.filter(t => overdue(t.due) && !t.done).length;
const navBadgeTasks = $('nav-badge-tasks');
const navBadgeCalendar = $('nav-badge-calendar');
if (navBadgeTasks) navBadgeTasks.textContent = tasks.filter(t => !t.done).length || '';
if (navBadgeCalendar) navBadgeCalendar.textContent = tasks.filter(t => overdue(t.due) && !t.done).length || '';
};
/* ═══════════════════════════════════════════
CONFETTI
═══════════════════════════════════════════ */
const checkAllDone = () => {
if (!tasks.length) { lastAllDone = false; return; }
const allDone = tasks.every(t => t.done);
if (allDone && !lastAllDone) { lastAllDone = true; launchConfetti(); }
else if (!allDone) lastAllDone = false;
};
const launchConfetti = () => {
confCanvas.width = window.innerWidth; confCanvas.height = window.innerHeight;
const COLS = ['#b8ff00','#ff4d6d','#3dd6f5','#ffb300','#fff','#8fc800'];
const ps = Array.from({length: 200}, () => ({
x: Math.random() * confCanvas.width,
y: Math.random() * confCanvas.height - confCanvas.height,
w: 5 + Math.random() * 9, h: 3 + Math.random() * 5,
r: Math.random() * Math.PI * 2, rd: (Math.random() - .5) * .14,
vx: (Math.random() - .5) * 4, vy: 1.5 + Math.random() * 4,
col: COLS[Math.floor(Math.random() * COLS.length)],
}));
let raf;
const draw = () => {
confCtx.clearRect(0, 0, confCanvas.width, confCanvas.height);
let alive = 0;
ps.forEach(p => {
if (p.y > confCanvas.height + 20) return; alive++;
p.x += p.vx; p.y += p.vy; p.r += p.rd; p.vy += .055;
confCtx.save(); confCtx.translate(p.x, p.y); confCtx.rotate(p.r);
confCtx.globalAlpha = Math.max(0, 1 - p.y / (confCanvas.height * 1.1));
confCtx.fillStyle = p.col; confCtx.fillRect(-p.w/2, -p.h/2, p.w, p.h);
confCtx.restore();
});
if (alive > 0) raf = requestAnimationFrame(draw);
else confCtx.clearRect(0, 0, confCanvas.width, confCanvas.height);
};
cancelAnimationFrame(raf); draw();
setTimeout(() => { cancelAnimationFrame(raf); confCtx.clearRect(0, 0, confCanvas.width, confCanvas.height); }, 4500);
};
/* ═══════════════════════════════════════════
ADD TASK
═══════════════════════════════════════════ */
const addTask = () => {
const text = inp.value.trim();
const recur = $('recur-select')?.value || '';
if (!text) {
inp.classList.remove('shake'); void inp.offsetWidth; inp.classList.add('shake');
inp.addEventListener('animationend', () => inp.classList.remove('shake'), { once: true });
inp.focus(); playClick(220, 0.15); return;
}
const t = { id: uid(), text, done: false, pri: selPri, due: ddInp.value || null, recur: recur || null, notes: '', at: Date.now() };
tasks.unshift(t);
saveWithIndicator(LS.TASKS, tasks);
inp.value = ''; ddInp.value = '';
if ($('recur-select')) $('recur-select').value = '';
inp.focus();
render(); syncPomoTaskList(); checkAllDone();
playClick(660, 0.1);
};
addBtn.addEventListener('click', addTask);
inp.addEventListener('keydown', e => { if (e.key === 'Enter') addTask(); });