Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
3755 lines (3347 loc) · 157 KB
/
Copy pathscript.js
File metadata and controls
3755 lines (3347 loc) · 157 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
// ============================================================================
// AI PLANNER CONFIGURATION
// ============================================================================
// The AI planner calls the Anthropic Messages API directly with the visitor's
// own API key. The default model can be overridden per browser in Settings.
const DEFAULT_AI_MODEL = 'claude-sonnet-5-5';
const ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';
const ANTHROPIC_API_VERSION = '2023-06-01';
// ============================================================================
// SESSION AND STORAGE
// ============================================================================
// RunTrack runs in one of two modes:
// guest - plans and runs are kept in this browser's localStorage only.
// account - optional sign-in; plans and runs sync through Cloud Firestore.
// Each mode has its own localStorage namespace (rt_guest_* or rt_<uid>_*), so
// guest data and account data never mix.
const SESSION_KEY = 'runtrack_session';
const IMPORT_OFFER_KEY = 'runtrack_offer_import';
const GUEST_DATA_KEY = 'rt_guest_data';
const DATA_VERSION = 1;
let session = null; // { mode: 'guest' } or { mode: 'account', uid, username }
let appData = { plans: [], runs: [], whoopRecovery: null };
let storageWarningShown = false;
function isAccountSession() {
return !!session && session.mode === 'account';
}
function lsKey(key) {
return `rt_${isAccountSession() ? session.uid : 'guest'}_${key}`;
}
function clearLocalNamespace(owner) {
const prefix = `rt_${owner}_`;
try {
Object.keys(localStorage).filter(k => k.startsWith(prefix)).forEach(k => localStorage.removeItem(k));
} catch (_) { /* storage unavailable */ }
}
function readGuestData() {
const raw = storageGet(GUEST_DATA_KEY);
if (!raw) return { plans: [], runs: [] };
try {
const parsed = JSON.parse(raw);
const isRecord = item => !!item && typeof item === 'object' && typeof item.id === 'string';
return {
plans: Array.isArray(parsed?.plans) ? parsed.plans.filter(isRecord) : [],
runs: Array.isArray(parsed?.runs) ? parsed.runs.filter(isRecord) : []
};
} catch (_) {
// Set unreadable data aside instead of overwriting it.
storageSet(`${GUEST_DATA_KEY}_unreadable`, raw);
storageRemove(GUEST_DATA_KEY);
return { plans: [], runs: [] };
}
}
function hasGuestData() {
const guest = readGuestData();
return guest.plans.length > 0 || guest.runs.length > 0;
}
function writeGuestData(data) {
const saved = storageSet(GUEST_DATA_KEY, JSON.stringify({ version: DATA_VERSION, plans: data.plans, runs: data.runs }));
if (!saved && !storageWarningShown) {
storageWarningShown = true;
showToast('This browser could not save your changes because its storage is full or turned off. Export your data from Settings to keep a copy.', 'error', 9000);
}
}
function getStorage() { return appData; }
function setStorage(data) {
data.plans = sortPlans(data.plans || []);
data.runs = data.runs || [];
appData = data;
if (isAccountSession()) CloudStore.save(data);
else if (session) writeGuestData(data);
}
// JSON with sorted object keys, so equal records always serialize the same way.
function stableStringify(value) {
return JSON.stringify(value, (key, val) => {
if (!val || typeof val !== 'object' || Array.isArray(val)) return val;
return Object.keys(val).sort().reduce((out, k) => { out[k] = val[k]; return out; }, {});
});
}
function snapshotOf(records) {
return new Map((records || []).map(record => [record.id, stableStringify(record)]));
}
function sameRecords(a, b) {
const left = snapshotOf(a), right = snapshotOf(b);
if (left.size !== right.size) return false;
for (const [id, json] of left) if (right.get(id) !== json) return false;
return true;
}
function replaceAppData(fresh) {
appData = { plans: sortPlans(fresh.plans), runs: fresh.runs, whoopRecovery: appData.whoopRecovery };
renderAll();
updateHeaderInfo();
}
// ============================================================================
// OPTIONAL ACCOUNTS AND CLOUD SYNC (FIREBASE)
// ============================================================================
// The Firebase SDK loads only when someone signs in, so guest mode sends
// nothing to Google. The Firebase project settings live in config.js.
const FIREBASE_SDK_URL = 'https://www.gstatic.com/firebasejs/10.12.2';
const USERNAME_PATTERN = /^[A-Za-z0-9_]{3,24}$/;
const CLOUD_BATCH_LIMIT = 450; // Firestore allows up to 500 writes per batch
const CLOUD_REFRESH_MS = 60 * 1000; // minimum gap between background refreshes
const UNSYNCED = ''; // snapshot marker for a write that must be retried
let auth = null;
let db = null;
let firebaseLoading = null;
let signingOut = false;
let lastCloudLoad = 0;
function firebaseConfig() {
const config = window.RUNTRACK_CONFIG && window.RUNTRACK_CONFIG.firebase;
return config && config.apiKey && config.projectId ? config : null;
}
function accountsEnabled() {
return !!firebaseConfig();
}
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = () => { script.remove(); reject(new Error(`Could not load ${src}`)); };
document.head.appendChild(script);
});
}
function ensureFirebase() {
if (!accountsEnabled()) return Promise.reject(new Error('Accounts are not enabled on this site.'));
if (!firebaseLoading) {
firebaseLoading = (async () => {
if (!window.firebase) await loadScript(`${FIREBASE_SDK_URL}/firebase-app-compat.js`);
const pending = [];
if (!firebase.auth) pending.push(loadScript(`${FIREBASE_SDK_URL}/firebase-auth-compat.js`));
if (!firebase.firestore) pending.push(loadScript(`${FIREBASE_SDK_URL}/firebase-firestore-compat.js`));
await Promise.all(pending);
if (!firebase.apps.length) firebase.initializeApp(firebaseConfig());
auth = firebase.auth();
db = firebase.firestore();
// Keep an offline copy so changes made without a connection sync later.
await db.enablePersistence({ synchronizeTabs: true }).catch(() => {});
})().catch(error => {
firebaseLoading = null;
throw error;
});
}
return firebaseLoading;
}
// Plans and runs are stored as users/{uid}/plans/{id} and users/{uid}/runs/{id}.
// Saves compare against the last synced snapshot and only write what changed,
// including deletes.
const CloudStore = {
uid: null,
synced: { plans: new Map(), runs: new Map() },
inflight: new Set(),
saveCount: 0,
lastErrorAt: 0,
ref(name, id) {
return db.collection('users').doc(this.uid).collection(name).doc(id);
},
async fetch(uid) {
const user = db.collection('users').doc(uid);
const [plans, runs] = await Promise.all([user.collection('plans').get(), user.collection('runs').get()]);
const toRecords = snap => snap.docs.map(doc => ({ ...doc.data(), id: doc.id }));
return { plans: toRecords(plans), runs: toRecords(runs) };
},
adopt(uid, data) {
this.uid = uid;
this.synced = { plans: snapshotOf(data.plans), runs: snapshotOf(data.runs) };
},
hasUnsynced() {
return [...this.synced.plans.values(), ...this.synced.runs.values()].includes(UNSYNCED);
},
busy() {
return this.inflight.size > 0 || this.hasUnsynced();
},
save(data) {
if (!this.uid || !db) return Promise.resolve(false);
this.saveCount++;
const ops = [];
for (const name of ['plans', 'runs']) {
const next = snapshotOf(data[name]);
const prev = this.synced[name];
next.forEach((json, id) => { if (prev.get(id) !== json) ops.push({ name, id, json }); });
prev.forEach((_, id) => { if (!next.has(id)) ops.push({ name, id, json: null }); });
this.synced[name] = next;
}
const commits = [];
for (let i = 0; i < ops.length; i += CLOUD_BATCH_LIMIT) {
const chunk = ops.slice(i, i + CLOUD_BATCH_LIMIT);
const batch = db.batch();
chunk.forEach(op => {
if (op.json === null) batch.delete(this.ref(op.name, op.id));
else batch.set(this.ref(op.name, op.id), JSON.parse(op.json));
});
const commit = batch.commit().then(() => true, error => {
chunk.forEach(op => this.synced[op.name].set(op.id, UNSYNCED));
this.reportError(error);
return false;
});
this.inflight.add(commit);
commit.then(() => this.inflight.delete(commit));
commits.push(commit);
}
return Promise.all(commits).then(results => results.every(Boolean));
},
// Retry failed writes and wait (up to timeoutMs) for the server to confirm.
flush(data, timeoutMs) {
this.save(data);
if (!this.inflight.size) return Promise.resolve(!this.hasUnsynced());
const confirmed = Promise.all([...this.inflight]).then(results => results.every(Boolean));
const timedOut = new Promise(resolve => setTimeout(() => resolve(false), timeoutMs));
return Promise.race([confirmed, timedOut]);
},
reportError(error) {
if (Date.now() - this.lastErrorAt < 30000) return;
this.lastErrorAt = Date.now();
showToast(error && error.code === 'permission-denied'
? 'Your account refused these changes. Export your data from Settings to keep a copy.'
: 'Some changes could not be saved to your account. RunTrack will retry with your next change.', 'error', 8000);
}
};
async function refreshFromCloud() {
if (!isAccountSession() || !db || Date.now() - lastCloudLoad < CLOUD_REFRESH_MS) return;
if (CloudStore.busy() || document.querySelector('.modal.active')) return;
lastCloudLoad = Date.now();
const { uid } = session;
const saves = CloudStore.saveCount;
try {
const fresh = await CloudStore.fetch(uid);
if (!isAccountSession() || session.uid !== uid || CloudStore.saveCount !== saves || CloudStore.busy()) return;
if (sameRecords(fresh.plans, appData.plans) && sameRecords(fresh.runs, appData.runs)) return;
CloudStore.adopt(uid, fresh);
replaceAppData(fresh);
} catch (_) { /* keep showing the data already on screen */ }
}
// ============================================================================
// SIGN-IN, SIGN-OUT AND GUEST MODE
// ============================================================================
const SIGN_OUT_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="18" height="18" aria-hidden="true"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>';
function usernameToEmail(username) {
return `${username.toLowerCase().trim()}@runtrack.local`;
}
function authErrorMessage(error, action) {
switch (error && error.code) {
case 'auth/invalid-credential':
case 'auth/invalid-login-credentials':
case 'auth/wrong-password':
case 'auth/user-not-found':
return 'Incorrect username or password.';
case 'auth/email-already-in-use':
return 'That username is taken. Try another one.';
case 'auth/invalid-email':
return 'Usernames can only use letters, numbers and underscores.';
case 'auth/weak-password':
return 'Use a password with at least 6 characters.';
case 'auth/too-many-requests':
return 'Too many attempts. Wait a few minutes and try again.';
case 'auth/network-request-failed':
return 'Could not reach the sign-in service. Check your connection and try again.';
case 'auth/operation-not-allowed':
return 'Username sign-in is not enabled for this site.';
default:
if (!error || !error.code) return 'Could not reach the sign-in service. Check your connection and try again.';
return action === 'register' ? 'Could not create your account. Please try again.' : 'Could not sign you in. Please try again.';
}
}
function setBusy(button, busy, label) {
button.disabled = busy;
button.textContent = label;
}
async function handleLogin(event) {
event.preventDefault();
const username = document.getElementById('loginUsername').value.trim();
const password = document.getElementById('loginPassword').value;
const errEl = document.getElementById('loginError');
const button = document.getElementById('loginBtn');
errEl.textContent = '';
if (!username || !password) { errEl.textContent = 'Enter your username and password.'; return; }
setBusy(button, true, 'Signing in…');
try {
await ensureFirebase();
await auth.signInWithEmailAndPassword(usernameToEmail(username), password);
finishSignIn();
} catch (error) {
errEl.textContent = authErrorMessage(error, 'sign-in');
setBusy(button, false, 'Sign in');
}
}
async function handleRegister(event) {
event.preventDefault();
const username = document.getElementById('registerUsername').value.trim();
const password = document.getElementById('registerPassword').value;
const confirmation = document.getElementById('registerConfirm').value;
const errEl = document.getElementById('registerError');
const button = document.getElementById('registerBtn');
errEl.textContent = '';
if (!USERNAME_PATTERN.test(username)) { errEl.textContent = 'Choose a username of 3 to 24 letters, numbers or underscores.'; return; }
if (password.length < 6) { errEl.textContent = 'Use a password with at least 6 characters.'; return; }
if (password !== confirmation) { errEl.textContent = 'The passwords do not match.'; return; }
setBusy(button, true, 'Creating account…');
try {
await ensureFirebase();
const credential = await auth.createUserWithEmailAndPassword(usernameToEmail(username), password);
try {
await db.collection('users').doc(credential.user.uid).set({
username,
createdAt: firebase.firestore.FieldValue.serverTimestamp()
});
} catch (_) { /* the profile only holds the display name */ }
finishSignIn();
} catch (error) {
errEl.textContent = authErrorMessage(error, 'register');
setBusy(button, false, 'Create account');
}
}
// Reload after signing in so account data never shares memory with guest data.
function finishSignIn() {
storageSet(SESSION_KEY, 'account');
if (hasGuestData()) {
try { sessionStorage.setItem(IMPORT_OFFER_KEY, '1'); } catch (_) { /* the offer is optional */ }
}
location.reload();
}
function toggleAuthMode() {
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const showRegister = !loginForm.hidden;
loginForm.hidden = showRegister;
registerForm.hidden = !showRegister;
document.getElementById(showRegister ? 'registerUsername' : 'loginUsername').focus();
}
async function signOut() {
if (!isAccountSession() || signingOut) return;
if (!confirm('Sign out on this device? You will need your password to sign back in.')) return;
showSplash('Signing out…');
const synced = await CloudStore.flush(appData, 5000);
if (!synced) {
hideSplash();
if (!confirm('Some changes have not reached your account yet, probably because you are offline. Sign out anyway and lose them?')) return;
showSplash('Signing out…');
}
signingOut = true;
const uid = session.uid;
try { await auth.signOut(); } catch (_) { /* still clear local state */ }
clearLocalNamespace(uid);
storageRemove(SESSION_KEY);
try {
await db.terminate();
await db.clearPersistence();
} catch (_) { /* another open tab may still use the offline cache */ }
location.reload();
}
function showSplash(message) {
const splash = document.getElementById('bootSplash');
splash.querySelector('.boot-splash-text').textContent = message || 'Loading…';
splash.hidden = false;
}
function hideSplash() {
document.getElementById('bootSplash').hidden = true;
}
function showApp() {
hideSplash();
document.getElementById('authOverlay').hidden = true;
document.getElementById('appShell').style.removeProperty('display');
}
function showLanding({ focusSignIn = false } = {}) {
hideSplash();
document.getElementById('appShell').style.display = 'none';
const overlay = document.getElementById('authOverlay');
overlay.hidden = false;
overlay.scrollTop = 0;
document.getElementById('accountPanel').hidden = !accountsEnabled();
document.getElementById('guestStartBtn').textContent =
session || hasGuestData() ? 'Continue as guest' : 'Start without an account';
document.getElementById('guestStartNote').textContent = accountsEnabled()
? 'Free, with no sign-up. Your data stays on this device unless you sign in.'
: 'Free, with no sign-up. Your data stays on this device.';
if (focusSignIn && accountsEnabled()) {
const loginHidden = document.getElementById('loginForm').hidden;
const field = document.getElementById(loginHidden ? 'registerUsername' : 'loginUsername');
field.scrollIntoView({ block: 'center' });
field.focus({ preventScroll: true });
}
}
function showSignIn() {
document.querySelectorAll('.modal.active').forEach(modal => closeModal(modal.id));
showLanding({ focusSignIn: true });
}
function continueAsGuest() {
if (session && session.mode === 'guest') showApp();
else startGuestSession();
}
function startGuestSession() {
session = { mode: 'guest' };
storageSet(SESSION_KEY, 'guest');
const guest = readGuestData();
appData = { plans: sortPlans(guest.plans), runs: guest.runs, whoopRecovery: null };
enterApp();
}
async function startAccountSession() {
showSplash('Loading your account…');
try {
await ensureFirebase();
} catch (_) {
showLanding();
showToast('Could not reach the sync service. Check your connection and reload, or continue without an account.', 'error', 8000);
return;
}
auth.onAuthStateChanged(handleAuthStateChange);
}
async function handleAuthStateChange(user) {
if (signingOut) return;
if (!user) {
const wasSignedIn = isAccountSession();
session = null;
storageRemove(SESSION_KEY);
if (wasSignedIn) location.reload();
else showLanding();
return;
}
if (isAccountSession()) {
// A different account signed in from another tab.
if (session.uid !== user.uid) location.reload();
return;
}
session = { mode: 'account', uid: user.uid, username: (user.email || '').split('@')[0] };
storageSet(SESSION_KEY, 'account');
showSplash('Loading your plans…');
const [profile, cloud] = await Promise.allSettled([
db.collection('users').doc(user.uid).get(),
CloudStore.fetch(user.uid)
]);
if (profile.status === 'fulfilled' && profile.value.exists) {
const name = profile.value.data().username;
if (typeof name === 'string' && name) session.username = name;
}
const loaded = cloud.status === 'fulfilled' ? cloud.value : { plans: [], runs: [] };
CloudStore.adopt(user.uid, loaded);
appData = { plans: sortPlans(loaded.plans), runs: loaded.runs, whoopRecovery: null };
lastCloudLoad = Date.now();
await enterApp();
if (cloud.status === 'rejected') {
showToast('Could not load your synced data. Check your connection and reload the page.', 'error', 9000);
} else {
offerGuestImport();
}
}
async function enterApp() {
showApp();
updateAccountChrome();
// Each handler returns null when the page was not opened by its OAuth
// redirect, otherwise whether the connection succeeded.
let fitbitResult = null, whoopResult = null;
try { fitbitResult = await handleFitbitCallback(); } catch (_) { fitbitResult = false; }
try { whoopResult = await handleWhoopCallback(); } catch (_) { whoopResult = false; }
renderAll();
updateHeaderInfo();
if (fitbitResult !== null) openDeviceSettings('fitbit', false);
else if (whoopResult !== null) openDeviceSettings('whoop', false);
if (isFitbitConnected()) syncFitbitRuns({ notify: fitbitResult === true }).catch(() => {});
if (isWhoopConnected()) syncWhoopData({ notify: whoopResult === true }).catch(() => {});
}
function updateAccountChrome() {
const header = document.getElementById('headerAccount');
const sidebar = document.getElementById('sidebarUser');
if (isAccountSession()) {
header.innerHTML = `
<span class="header-username">${escapeHtml(session.username)}</span>
<button class="btn-icon" onclick="signOut()" title="Sign out" aria-label="Sign out">${SIGN_OUT_ICON}</button>`;
sidebar.textContent = `Signed in as ${session.username}`;
} else {
header.innerHTML = `
<span class="session-chip" title="Your data is saved in this browser only">Guest</span>
${accountsEnabled() ? '<button class="btn btn-secondary btn-sm" onclick="showSignIn()"><span>Sign in<span class="hide-on-phone"> to sync</span></span></button>' : ''}`;
sidebar.textContent = 'Guest, saved in this browser';
}
}
// Counts what a guest import would add, without changing anything.
function previewGuestImport() {
const target = { plans: [...appData.plans], runs: [...appData.runs] };
return mergeRunTrackData(target, readGuestData());
}
function offerGuestImport() {
let requested = false;
try {
requested = sessionStorage.getItem(IMPORT_OFFER_KEY) === '1';
sessionStorage.removeItem(IMPORT_OFFER_KEY);
} catch (_) { /* the offer is optional */ }
if (requested) showGuestImportModal(false);
}
function showGuestImportModal(fromSettings = true) {
const { addedPlans, addedRuns } = previewGuestImport();
if (!addedPlans && !addedRuns) {
if (fromSettings) showToast('Everything from guest mode is already in your account.');
return;
}
document.getElementById('guestImportSummary').textContent =
`This browser has ${plural(addedPlans, 'plan')} and ${plural(addedRuns, 'run')} from guest mode that are not in your account. ` +
'Import them so they sync to your other devices? Nothing in your account is overwritten.';
openModal('guestImportModal');
}
function importGuestData() {
const { addedPlans, addedRuns } = mergeRunTrackData(appData, readGuestData());
setStorage(appData);
closeModal('guestImportModal');
renderAll();
updateHeaderInfo();
showToast(`Imported ${plural(addedPlans, 'plan')} and ${plural(addedRuns, 'run')} into your account.`, 'success');
}
function deleteGuestData() {
if (!confirm('Delete everything saved in this browser in guest mode, including plans, runs and settings? Your account is not affected.')) return;
clearLocalNamespace('guest');
renderSettings();
showToast('Guest data was deleted from this browser.');
}
function handleStorageEvent(event) {
if (event.key !== GUEST_DATA_KEY || !session || session.mode !== 'guest') return;
const fresh = readGuestData();
if (sameRecords(fresh.plans, appData.plans) && sameRecords(fresh.runs, appData.runs)) return;
replaceAppData(fresh);
}
function handleGlobalKeydown(event) {
if (event.key !== 'Escape') return;
const open = document.querySelectorAll('.modal.active');
if (open.length) closeModal(open[open.length - 1].id);
}
function boot() {
setTheme(getTheme());
updateThemeIcon();
restoreSidebarState();
setupNavListeners();
document.addEventListener('keydown', handleGlobalKeydown);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') refreshFromCloud();
});
window.addEventListener('storage', handleStorageEvent);
const mode = storageGet(SESSION_KEY);
if (mode === 'guest') {
startGuestSession();
} else if (mode === 'account' && accountsEnabled()) {
startAccountSession();
} else {
storageRemove(SESSION_KEY);
showLanding();
}
}
document.addEventListener('DOMContentLoaded', boot);
function getTheme() { return localStorage.getItem('runtrack_theme') || 'dark'; }
function setTheme(theme) {
localStorage.setItem('runtrack_theme', theme);
if (theme === 'light') document.documentElement.classList.add('light-mode');
else document.documentElement.classList.remove('light-mode');
}
// ============================================================================
// UTILITIES
// ============================================================================
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
// All plan dates are calendar dates (YYYY-MM-DD) in the visitor's local time zone.
function getToday() {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
}
function formatDate(date) {
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${date.getFullYear()}-${month}-${day}`;
}
function parseDate(dateStr) {
const [year, month, day] = dateStr.split('-');
return new Date(year, parseInt(month) - 1, day);
}
function isValidDateString(value) {
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) && formatDate(parseDate(value)) === value;
}
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// Whole days from one YYYY-MM-DD date to another (rounding absorbs DST shifts).
function daysBetween(fromStr, toStr) {
return Math.round((parseDate(toStr) - parseDate(fromStr)) / 86400000);
}
function formatDisplayDate(dateStr, options = { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }) {
return isValidDateString(dateStr) ? parseDate(dateStr).toLocaleDateString(undefined, options) : '';
}
// Parses "mm:ss", "h:mm:ss" or whole minutes ("45"). Returns NaN if invalid.
function timeStringToSeconds(timeStr) {
const value = String(timeStr || '').trim();
if (/^\d{1,4}$/.test(value)) return Number(value) * 60;
const match = value.match(/^(?:(\d{1,2}):)?(\d{1,4}):(\d{2})$/);
if (!match) return NaN;
const [, h, m, sec] = match;
if (Number(sec) > 59 || (h !== undefined && Number(m) > 59)) return NaN;
return Number(h || 0) * 3600 + Number(m) * 60 + Number(sec);
}
function secondsToTimeString(seconds) {
if (!seconds) return '';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
function calculatePace(distanceMiles, timeSeconds) {
if (!distanceMiles || !timeSeconds) return '';
const paceSeconds = Math.round(timeSeconds / distanceMiles);
return secondsToTimeString(paceSeconds);
}
function dayOfWeek(date) {
return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
}
function raceTypeLabel(raceType) {
const labels = { '5k': '5K', '10k': '10K', 'half_marathon': 'Half Marathon', 'marathon': 'Marathon', 'custom': 'Custom' };
return labels[raceType] || raceType;
}
function runTypeLabel(type) {
if (type === 'long') return 'Long Run';
if (type === 'race') return 'Race';
return 'Easy Run';
}
function getCSSVar(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
const RACE_TYPES = ['5k', '10k', 'half_marathon', 'marathon', 'custom'];
const WEEKDAY_KEYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
const WEEK_ORDER = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
const DAY_SHORT = { monday: 'Mon', tuesday: 'Tue', wednesday: 'Wed', thursday: 'Thu', friday: 'Fri', saturday: 'Sat', sunday: 'Sun' };
const RACE_DISTANCE_MI = { '5k': 3.1, '10k': 6.2, half_marathon: 13.1, marathon: 26.2, custom: 13.1 };
const PACE_SEC_PER_MI = { easy: 600, long: 660, race: 600 };
const PLAN_MAX_WEEKS = 30;
// Week counts and distances (miles) used to build template plans for each race.
const PLAN_RULES = {
'5k': { minWeeks: 4, recWeeks: 10, longStart: 3, longPeak: 6, easyStart: 2, easyMax: 4 },
'10k': { minWeeks: 6, recWeeks: 12, longStart: 4, longPeak: 9, easyStart: 2, easyMax: 5 },
half_marathon: { minWeeks: 8, recWeeks: 16, longStart: 4, longPeak: 12, easyStart: 2, easyMax: 6 },
marathon: { minWeeks: 12, recWeeks: 18, longStart: 6, longPeak: 20, easyStart: 3, easyMax: 8 },
custom: { minWeeks: 4, recWeeks: 12, longStart: 4, longPeak: 10, easyStart: 2, easyMax: 6 }
};
function capitalize(word) {
return word ? word[0].toUpperCase() + word.slice(1) : '';
}
// The active plan is always plans[0]: the most recently activated or created plan.
function sortPlans(plans) {
const rank = plan => Number(plan.activatedAt) || Date.parse(plan.createdAt) || 0;
return [...plans].sort((a, b) => rank(b) - rank(a));
}
function daysToRaceText(raceDate) {
const days = daysBetween(formatDate(getToday()), raceDate);
if (days > 1) return `${days} days to race`;
if (days === 1) return '1 day to race';
if (days === 0) return 'Race day';
return 'Race complete';
}
function plural(count, word) {
return `${count} ${word}${count === 1 ? '' : 's'}`;
}
function escapeHtml(value) {
return String(value ?? '').replace(/[&<>"']/g, ch => (
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]
));
}
// localStorage can throw (quota exceeded, storage disabled), so wrap access.
function storageGet(key) {
try { return localStorage.getItem(key); } catch (_) { return null; }
}
function storageSet(key, value) {
try { localStorage.setItem(key, value); return true; } catch (_) { return false; }
}
function storageRemove(key) {
try { localStorage.removeItem(key); } catch (_) { /* storage unavailable */ }
}
function showToast(message, type = 'info', timeoutMs = 4500) {
let host = document.getElementById('toastHost');
if (!host) {
host = document.createElement('div');
host.id = 'toastHost';
host.className = 'toast-host';
host.setAttribute('role', 'status');
host.setAttribute('aria-live', 'polite');
document.body.appendChild(host);
}
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = message;
host.appendChild(toast);
setTimeout(() => {
toast.classList.add('leaving');
setTimeout(() => toast.remove(), 300);
}, timeoutMs);
}
// ============================================================================
// PLAN GENERATION
// ============================================================================
function planWeekCount(startDate, raceDate) {
return Math.floor(daysBetween(startDate, raceDate) / 7) + 1;
}
// Build a template plan. Week N covers the 7 days starting at
// startDate + 7 * (N - 1), and the last week ends with the race on raceDate.
function generatePlanWeeks(startDate, raceDate, raceType, runDays, longRunDay) {
const rules = PLAN_RULES[raceType] || PLAN_RULES.custom;
const raceDist = RACE_DISTANCE_MI[raceType] || RACE_DISTANCE_MI.custom;
const start = parseDate(startDate);
const totalWeeks = Math.max(1, planWeekCount(startDate, raceDate));
const taperWeeks = totalWeeks >= 12 ? 3 : totalWeeks >= 6 ? 2 : 1;
const buildWeeks = totalWeeks - taperWeeks;
const peakWeek = buildWeeks - 1;
const makeRun = (date, type, distance) => ({
id: generateUUID(), date, type, plannedDistance: distance,
plannedTime: Math.round(distance * PACE_SEC_PER_MI[type]),
actualDistance: null, actualTime: null, effort: null, notes: ''
});
const weeks = [];
for (let w = 0; w < totalWeeks; w++) {
const weekStart = addDays(start, w * 7);
const isRaceWeek = w === totalWeeks - 1;
const isTaper = w >= buildWeeks;
const isRecovery = w > 0 && w < peakWeek && (w + 1) % 4 === 0;
const progress = Math.min(w / Math.max(peakWeek, 1), 1);
const taperStep = w - buildWeeks + 1;
const runs = [];
for (let offset = 0; offset < 7; offset++) {
const date = addDays(weekStart, offset);
const dateStr = formatDate(date);
if (dateStr === raceDate) { runs.push(makeRun(dateStr, 'race', raceDist)); break; }
if (dateStr > raceDate) break;
const day = WEEKDAY_KEYS[date.getDay()];
if (!runDays.includes(day)) continue;
let type = 'easy', distance;
if (isRaceWeek) {
distance = daysBetween(dateStr, raceDate) <= 2 ? 2 : 3;
} else if (day === longRunDay) {
type = 'long';
distance = isTaper
? rules.longPeak * (1 - 0.25 * taperStep)
: (rules.longStart + progress * (rules.longPeak - rules.longStart)) * (isRecovery ? 0.75 : 1);
} else {
const easy = rules.easyStart + progress * (rules.easyMax - rules.easyStart);
distance = easy * (isTaper ? 1 - 0.2 * taperStep : isRecovery ? 0.75 : 1);
}
runs.push(makeRun(dateStr, type, Math.max(1, Math.round(distance * 2) / 2)));
}
weeks.push({ weekNumber: w + 1, startDate: formatDate(weekStart), runs });
}
return weeks;
}
function defaultPlanName(raceType, raceDate) {
const when = formatDisplayDate(raceDate, { month: 'short', year: 'numeric' });
return `${when} ${raceTypeLabel(raceType)}`.trim();
}
// Suggested race day: the recommended number of weeks out, on a weekend day.
function recommendedRaceDate(startDate, raceType, longRunDay) {
const rules = PLAN_RULES[raceType] || PLAN_RULES.custom;
const target = WEEKDAY_KEYS.indexOf(['saturday', 'sunday'].includes(longRunDay) ? longRunDay : 'sunday');
let date = addDays(parseDate(startDate), 7 * (rules.recWeeks - 1));
while (date.getDay() !== target) date = addDays(date, 1);
return formatDate(date);
}
const RACE_PHRASE = { '5k': '5K', '10k': '10K', half_marathon: 'half marathon', marathon: 'marathon', custom: 'custom' };
function planScheduleChanged(plan, input) {
return plan.raceType !== input.raceType || plan.startDate !== input.startDate ||
plan.raceDate !== input.raceDate || plan.longRunDay !== input.longRunDay ||
[...plan.runDays].sort().join() !== [...input.runDays].sort().join();
}
// Returns a user-facing error message, or '' when the input is valid. When
// editing, the schedule rules only apply if the schedule would be rebuilt.
function validatePlanInput(input, original = null) {
if (!RACE_TYPES.includes(input.raceType)) return 'Choose a race distance.';
if (original && !planScheduleChanged(original, input)) return '';
if (!isValidDateString(input.startDate)) return 'Choose the date your plan starts.';
if (!isValidDateString(input.raceDate)) return 'Choose your race day.';
if (input.raceDate <= input.startDate) return 'Race day must be after the plan start date.';
if ((!original || original.raceDate !== input.raceDate) && input.raceDate < formatDate(getToday())) {
return 'Race day is in the past. Choose an upcoming date.';
}
const weeks = planWeekCount(input.startDate, input.raceDate);
const minimum = (PLAN_RULES[input.raceType] || PLAN_RULES.custom).minWeeks;
if (weeks < minimum) return `A ${RACE_PHRASE[input.raceType]} plan needs at least ${minimum} weeks. Move race day later or start earlier.`;
if (weeks > PLAN_MAX_WEEKS) return `Plans can be up to ${PLAN_MAX_WEEKS} weeks long. Start closer to race day.`;
if (input.runDays.length < 2) return 'Pick at least 2 days you can run.';
if (!input.runDays.includes(input.longRunDay)) return 'Pick a long run day from your run days.';
return '';
}
function planStatsMarkup(weeks) {
const runs = weeks.flatMap(w => w.runs);
const longest = runs.filter(r => r.type !== 'race').reduce((max, r) => Math.max(max, r.plannedDistance), 0);
const peakWeek = weeks.reduce((max, w) => Math.max(max, w.runs.reduce((sum, r) => sum + r.plannedDistance, 0)), 0);
return `
<div><strong>${weeks.length}</strong><span>weeks</span></div>
<div><strong>${runs.length}</strong><span>runs</span></div>
<div><strong>${longest}</strong><span>longest run (mi)</span></div>
<div><strong>${Math.round(peakWeek)}</strong><span>peak week (mi)</span></div>`;
}
function savePlanFromInput(input, existing) {
const data = getStorage();
const name = input.name || defaultPlanName(input.raceType, input.raceDate);
const schedule = () => generatePlanWeeks(input.startDate, input.raceDate, input.raceType, input.runDays, input.longRunDay);
if (existing) {
const plan = data.plans.find(p => p.id === existing.id);
if (!plan) return null;
const rebuild = planScheduleChanged(plan, input);
Object.assign(plan, {
name, raceType: input.raceType, startDate: input.startDate, raceDate: input.raceDate,
runDays: input.runDays, longRunDay: input.longRunDay
});
if (rebuild) { plan.weeks = schedule(); delete plan.source; }
setStorage(data);
return plan;
}
const plan = {
id: generateUUID(), name, raceType: input.raceType, startDate: input.startDate, raceDate: input.raceDate,
runDays: input.runDays, longRunDay: input.longRunDay,
createdAt: new Date().toISOString(), activatedAt: Date.now(),
weeks: schedule()
};
data.plans.unshift(plan);
setStorage(data);
return plan;
}
const PLAN_DISTANCE_CHOICES = [['5k', '5K'], ['10k', '10K'], ['half_marathon', 'Half marathon'], ['marathon', 'Marathon']];
const DEFAULT_RUN_DAYS = ['tuesday', 'thursday', 'saturday'];
let planFormSeq = 0;
// Plan form shared by onboarding, "New plan" and "Edit plan".
function mountPlanForm(host, { plan = null, submitLabel = 'Create plan', onSaved, onCancel, onDelete } = {}) {
if (!host) return;
const uid = `planform${++planFormSeq}`;
const choices = [...PLAN_DISTANCE_CHOICES];
if (plan && !choices.some(([value]) => value === plan.raceType)) choices.push([plan.raceType, raceTypeLabel(plan.raceType)]);
const state = {
raceType: plan ? plan.raceType : 'half_marathon',
runDays: plan ? WEEK_ORDER.filter(d => plan.runDays.includes(d)) : [...DEFAULT_RUN_DAYS],
longRunDay: plan ? plan.longRunDay : 'saturday',
raceTouched: !!plan
};
host.innerHTML = `
<form class="plan-form" novalidate>
<div class="form-group">
<span class="form-label" id="${uid}-dist">Race distance</span>
<div class="pill-group" role="radiogroup" aria-labelledby="${uid}-dist">
${choices.map(([value, label]) => `<button type="button" class="pill" role="radio" data-race="${value}">${label}</button>`).join('')}
</div>
</div>
<div class="form-row">
<div class="form-group">
<label class="form-label" for="${uid}-start">Plan starts</label>
<input type="date" class="form-input" id="${uid}-start" required />
</div>
<div class="form-group">
<label class="form-label" for="${uid}-race">Race day</label>
<input type="date" class="form-input" id="${uid}-race" required />
</div>
</div>
<div class="form-group">
<span class="form-label" id="${uid}-days">Days you can run</span>
<div class="pill-group day-pills" role="group" aria-labelledby="${uid}-days">
${WEEK_ORDER.map(day => `<button type="button" class="pill" data-day="${day}" aria-label="${capitalize(day)}">${DAY_SHORT[day]}</button>`).join('')}
</div>
</div>
<div class="form-row">
<div class="form-group">
<label class="form-label" for="${uid}-long">Long run day</label>
<select class="form-input" id="${uid}-long"></select>
</div>
<div class="form-group">
<label class="form-label" for="${uid}-name">Plan name (optional)</label>
<input type="text" class="form-input" id="${uid}-name" maxlength="80" autocomplete="off" />
</div>
</div>
<div class="stat-strip plan-summary" aria-live="polite"></div>
<div class="form-error" role="alert"></div>
${plan ? `<p class="form-note">Changing the distance, dates or run days rebuilds the schedule${plan.source === 'ai' ? ' from RunTrack\'s template' : ''}. Runs you have already logged are kept.</p>` : ''}
<div class="modal-actions">
${onCancel ? '<button type="button" class="btn btn-secondary" data-action="cancel">Cancel</button>' : ''}
${onDelete ? '<button type="button" class="btn btn-danger" data-action="delete">Delete plan</button>' : ''}