-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1091 lines (936 loc) · 41.2 KB
/
index.html
File metadata and controls
1091 lines (936 loc) · 41.2 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
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swim Check - Oregon Swimming Motivational Times</title>
<meta name="description" content="Look up Oregon Swimming (OSI) motivational time standards. Check your times against A, B+, and B standards.">
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:url" content="https://swimcheck.org/">
<meta property="og:title" content="Swim Check - Oregon Swimming Motivational Times">
<meta property="og:description" content="Look up Oregon Swimming (OSI) motivational time standards. Check your times against A, B+, and B standards.">
<meta property="og:image" content="https://swimcheck.org/images/social-preview-v2.png">
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://swimcheck.org/">
<meta name="twitter:title" content="Swim Check - Oregon Swimming Motivational Times">
<meta name="twitter:description" content="Look up Oregon Swimming (OSI) motivational time standards. Check your times against A, B+, and B standards.">
<meta name="twitter:image" content="https://swimcheck.org/images/social-preview-v2.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
<style>
/* Custom styles */
.time-value {
font-family: 'Courier New', monospace;
text-align: center;
}
.button-group {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
margin-bottom: 1rem;
}
.button-group button {
flex: 1;
min-width: 80px;
}
/* Reduce padding for gender and course type buttons to prevent wrapping */
#genderButtons button,
#courseButtons button {
padding-left: 0.5rem;
padding-right: 0.5rem;
min-width: 60px;
}
.button-group button.active {
background-color: var(--pico-primary-background);
border-color: var(--pico-primary-border);
}
.event-grid {
overflow-x: auto;
margin-bottom: 2rem;
}
.event-table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
.event-table th,
.event-table td {
padding: 0.5rem;
border: 1px solid var(--pico-muted-border-color);
}
.event-table th {
text-align: center;
background-color: var(--pico-background-color);
position: sticky;
top: 0;
z-index: 10;
}
.event-table td {
text-align: center;
}
.event-table td:first-child {
text-align: left;
font-weight: 500;
}
.time-input {
width: 100%;
min-width: 120px;
font-family: 'Courier New', monospace;
text-align: center;
padding: 0.5rem;
margin: 0;
transition: all 0.3s ease;
}
.time-input.invalid {
border: 2px solid #dc3545;
}
/* Input border colors when standards are met */
tr.has-value.met-a .time-input {
border: 3px solid #28a745;
}
tr.has-value.met-b-plus .time-input {
border: 3px solid #17a2b8;
}
tr.has-value.met-b .time-input {
border: 3px solid #ffc107;
}
/* Row with entered value gets light gray background on all cells */
.event-table tr.has-value td {
background-color: rgba(128, 128, 128, 0.15);
transition: background-color 0.3s ease;
}
/* Row with invalid standard gets light yellow background on all cells */
.event-table tr.has-invalid-standard td {
background-color: #fff9e6;
transition: background-color 0.3s ease;
}
/* Standard cells */
.standard-cell {
font-family: 'Courier New', monospace;
transition: all 0.3s ease;
}
/* Highlight standards when met - these override the row gray background */
.standard-cell.met {
font-weight: 700;
border-width: 2px;
}
.standard-cell.met-a {
background-color: #28a745 !important;
color: white;
border-color: #1e7e34;
}
.standard-cell.met-b-plus {
background-color: #17a2b8 !important;
color: white;
border-color: #117a8b;
}
.standard-cell.met-b {
background-color: #ffc107 !important;
color: #856404;
border-color: #d39e00;
}
.app-header {
text-align: center;
margin-bottom: 2rem;
}
.season-info {
font-size: 0.9rem;
color: var(--pico-muted-color);
margin-bottom: 2rem;
}
select {
margin-bottom: 1rem;
}
.note-text {
font-size: 0.85rem;
font-style: italic;
color: var(--pico-muted-color);
margin-top: 0.5rem;
}
.clear-section {
text-align: center;
margin-top: 2rem;
margin-bottom: 2rem;
padding-top: 2rem;
border-top: 1px solid var(--pico-muted-border-color);
}
/* Footer */
.app-footer {
text-align: center;
margin-top: 1rem;
padding: 2rem 0 1rem 0;
border-top: 1px solid var(--pico-muted-border-color);
color: var(--pico-muted-color);
font-size: 0.9rem;
}
.footer-phrase {
margin-bottom: 1.5rem;
}
.footer-phrase .heart {
color: #dc3545;
}
.footer-support {
margin-bottom: 1rem;
font-size: 0.95rem;
}
.footer-support a {
color: var(--pico-primary);
text-decoration: none;
}
.footer-support a:hover {
text-decoration: underline;
}
.footer-buttons {
display: flex;
gap: 1rem;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin-top: 1rem;
}
</style>
<script data-goatcounter="https://ironprogrammer.goatcounter.com/count"
async src="//gc.zgo.at/count.js"></script>
<script defer src="https://cloud.umami.is/script.js" data-website-id="405f9ef9-9a18-4ad2-9051-2fc5fd905872"></script>
</head>
<body>
<main class="container">
<div class="app-header">
<h1>Swim Check 🏊</h1>
<h4>Motivational Times Lookup</h4>
<p class="season-info" id="seasonInfo">Loading...</p>
</div>
<!-- Controls Section -->
<section>
<label for="ageGroupSelect">Age Group</label>
<select id="ageGroupSelect" aria-label="Select age group">
<option value="">Select Age Group</option>
</select>
<label>Gender</label>
<div class="button-group" id="genderButtons" role="group" aria-label="Select gender">
</div>
<label>Course Type</label>
<div class="button-group" id="courseButtons" role="group" aria-label="Select course type">
<button type="button" class="secondary" data-course="SCY">SCY</button>
<button type="button" class="secondary" data-course="SCM">SCM</button>
<button type="button" class="secondary" data-course="LCM">LCM</button>
</div>
<div id="noteDisplay" class="note-text"></div>
</section>
<!-- Event Grid Section -->
<section class="event-grid">
<div id="timedFilterToggle" style="display: none; margin-bottom: 1rem;">
<label>
<input type="checkbox" id="showTimedOnlyToggle" role="switch" />
Show timed events only
</label>
</div>
<div id="eventsContainer">
<p style="text-align: center; color: var(--pico-muted-color);">
Please select age group, gender, and course type to view events.
</p>
</div>
</section>
<!-- Clear Times Section -->
<section class="clear-section">
<label style="margin: 1rem auto; display: block;">
<input type="checkbox" id="fastEntryToggle" role="switch" />
Fast entry mode (numbers only)
</label>
<button type="button" id="clearTimesBtn" class="secondary">Clear all times</button>
<p class="note-text" style="margin-bottom: 1rem;">
💡 Tip: Rotate your phone to landscape view for better table visibility.
</p>
<p class="note-text" style="margin-bottom: 1rem;">
Times marked with ⚠️ indicate source data issues or unexpected time progressions
(<a href="https://github.com/ironprogrammer/swimcheck" target="_blank" rel="noopener noreferrer">more details on GitHub</a>).
</p>
</section>
<!-- Clear Times Confirmation Modal -->
<dialog id="clearTimesModal">
<article>
<header>
<button aria-label="Close" rel="prev" id="closeModalBtn"></button>
<p><strong>Clear all times</strong></p>
</header>
<p>
Are you sure you want to clear all entered times? This cannot be undone.
</p>
<footer>
<button type="button" class="secondary" id="cancelClearBtn">Cancel</button>
<button type="button" id="confirmClearBtn">Clear all times</button>
</footer>
</article>
</dialog>
<!-- Footer -->
<footer class="app-footer">
<p class="footer-phrase" id="footerPhrase">Made with <span class="heart">❤️</span> in war-torn PDX</p>
<div class="footer-support">
<p><strong>Do you find Swim Check useful?</strong><br>Consider <a href="https://github.com/ironprogrammer/swimcheck" target="_blank" rel="noopener noreferrer">contributing on GitHub</a> or buying me a coffee! (aka helping pay for meet fees)</p>
</div>
<div class="footer-buttons">
<a href="https://www.buymeacoffee.com/ironprogrammer" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;"></a>
</div>
</footer>
</main>
<script>
// Constants
const CURRENT_DATA_VERSION = 2;
// App state
let swimData = null;
let appState = {
ageGroup: null,
gender: null,
courseType: 'SCY',
times: {},
dataVersion: CURRENT_DATA_VERSION,
fastEntryMode: false,
showTimedOnly: false,
lastModified: null
};
// Load JSON data
async function loadData() {
try {
// Try local file first
let response = await fetch('swim_time_standards.json');
// If local file doesn't exist, fall back to swimcheck.org
if (!response.ok) {
response = await fetch('https://swimcheck.org/swim_time_standards.json');
}
swimData = await response.json();
document.getElementById('seasonInfo').textContent = swimData.title;
initializeApp();
} catch (error) {
console.error('Failed to load swim data:', error);
document.getElementById('seasonInfo').textContent = 'Error loading data';
}
}
// Initialize the app
function initializeApp() {
initializeState();
populateAgeGroups();
populateGenderButtons();
setupEventListeners();
renderEvents();
}
// Local storage functions
function saveStateToStorage() {
appState.lastModified = Date.now();
localStorage.setItem('swimCheckState', JSON.stringify(appState));
updateURLFragment();
}
function loadStateFromStorage() {
const saved = localStorage.getItem('swimCheckState');
if (!saved) return null;
try {
return JSON.parse(saved);
} catch (e) {
console.error('Failed to parse localStorage:', e);
return null;
}
}
// Migrate old time keys from AGE_GENDER_COURSE_EVENT to GENDER_COURSE_EVENT format
function migrateOldTimeKeys() {
// Skip if already at current version or higher
if (appState.dataVersion >= CURRENT_DATA_VERSION) {
return;
}
// Data version is old (or missing), perform migration
if (!appState.times || Object.keys(appState.times).length === 0) {
// No times to migrate, just update version
appState.dataVersion = CURRENT_DATA_VERSION;
saveStateToStorage();
return;
}
const newTimes = {};
let migrated = false;
for (const [key, value] of Object.entries(appState.times)) {
// Count underscores to detect old format (3 underscores = 4 parts)
const underscoreCount = (key.match(/_/g) || []).length;
if (underscoreCount === 3) {
// Old format: AGE_GENDER_COURSE_EVENT
const parts = key.split('_');
const newKey = parts.slice(1).join('_'); // Remove first part (age)
newTimes[newKey] = value;
migrated = true;
} else {
// Already new format or keep as-is
newTimes[key] = value;
}
}
// Update to current version
appState.times = newTimes;
appState.dataVersion = CURRENT_DATA_VERSION;
saveStateToStorage();
if (migrated) {
console.log(`Migrated time keys to new format (v${CURRENT_DATA_VERSION})`);
}
}
// ============================================================================
// URL Fragment Persistence
// ============================================================================
// Encode state to URL-safe base64 string
function encodeStateToFragment(state) {
try {
const json = JSON.stringify(state);
const base64 = btoa(json);
// Make URL-safe: replace + with -, / with _, remove =
const urlSafe = base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
return urlSafe;
} catch (e) {
console.error('Failed to encode state:', e);
return null;
}
}
// Decode URL fragment back to state object
function decodeFragmentToState(fragment) {
try {
// Remove # if present
fragment = fragment.replace(/^#/, '');
if (!fragment) return null;
// Restore base64 padding and special chars
let base64 = fragment.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
const json = atob(base64);
const state = JSON.parse(json);
// Validate structure
if (typeof state !== 'object' || !state.dataVersion) {
console.warn('Invalid state structure in URL fragment');
return null;
}
return state;
} catch (e) {
console.error('Failed to decode URL fragment:', e);
return null;
}
}
// Update URL fragment without adding to browser history
let urlUpdateTimeout = null;
function updateURLFragment() {
// Debounce: only update URL after 1.5s of no changes
clearTimeout(urlUpdateTimeout);
urlUpdateTimeout = setTimeout(() => {
const fragment = encodeStateToFragment(appState);
if (fragment) {
history.replaceState(null, '', '#' + fragment);
}
}, 1500);
}
// Load state from URL fragment
function loadStateFromFragment() {
const hash = window.location.hash;
if (!hash || hash === '#') return null;
const state = decodeFragmentToState(hash);
return state;
}
// Sync logic: merge localStorage and URL fragment
function initializeState() {
const localState = loadStateFromStorage();
const fragmentState = loadStateFromFragment();
let sourceUsed = 'default';
// Both exist: use smart sync logic
if (localState && fragmentState) {
const localTime = localState.lastModified || 0;
const fragmentTime = fragmentState.lastModified || 0;
const localHasTimes = localState.times && Object.keys(localState.times).length > 0;
const fragmentHasTimes = fragmentState.times && Object.keys(fragmentState.times).length > 0;
// If localStorage has no timestamp, assume URL is newer (feature added later)
if (localTime === 0 && fragmentTime > 0) {
appState = { ...appState, ...fragmentState };
sourceUsed = 'url-fragment (localStorage has no timestamp)';
saveStateToStorage();
}
// If one has times and the other doesn't, prefer the one with times
// This allows restoring from URL after clearing times
else if (fragmentHasTimes && !localHasTimes) {
appState = { ...appState, ...fragmentState };
sourceUsed = 'url-fragment (has times, localStorage empty)';
saveStateToStorage();
}
else if (localHasTimes && !fragmentHasTimes) {
appState = { ...appState, ...localState };
sourceUsed = 'localStorage (has times, URL empty)';
updateURLFragment();
}
// Both have times (or both empty): use timestamp
else if (fragmentTime > localTime) {
appState = { ...appState, ...fragmentState };
sourceUsed = 'url-fragment (newer)';
saveStateToStorage();
} else {
appState = { ...appState, ...localState };
sourceUsed = 'localStorage (newer)';
updateURLFragment();
}
}
// Only URL fragment exists
else if (fragmentState) {
appState = { ...appState, ...fragmentState };
sourceUsed = 'url-fragment (only source)';
saveStateToStorage();
}
// Only localStorage exists
else if (localState) {
appState = { ...appState, ...localState };
sourceUsed = 'localStorage (only source)';
updateURLFragment();
}
// Neither exists: use defaults
else {
sourceUsed = 'defaults (first visit)';
updateURLFragment();
}
console.log(`State loaded from: ${sourceUsed}`);
// Run migration if needed
migrateOldTimeKeys();
}
// Populate age groups dropdown
function populateAgeGroups() {
const select = document.getElementById('ageGroupSelect');
swimData.ageGroups.forEach(group => {
const option = document.createElement('option');
option.value = group.age;
option.textContent = group.age;
select.appendChild(option);
});
if (appState.ageGroup) {
select.value = appState.ageGroup;
}
}
// Populate gender buttons
function populateGenderButtons() {
const container = document.getElementById('genderButtons');
const genders = new Set();
swimData.ageGroups.forEach(group => {
Object.keys(group.genders).forEach(gender => genders.add(gender));
});
genders.forEach(gender => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'secondary';
button.textContent = gender;
button.dataset.gender = gender;
if (appState.gender === gender) {
button.classList.add('active');
button.classList.remove('secondary');
}
container.appendChild(button);
});
}
// Setup event listeners
function setupEventListeners() {
// Age group selection
document.getElementById('ageGroupSelect').addEventListener('change', (e) => {
appState.ageGroup = e.target.value;
saveStateToStorage();
renderEvents();
});
// Gender buttons
document.getElementById('genderButtons').addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
document.querySelectorAll('#genderButtons button').forEach(btn => {
btn.classList.remove('active');
btn.classList.add('secondary');
});
e.target.classList.add('active');
e.target.classList.remove('secondary');
appState.gender = e.target.dataset.gender;
saveStateToStorage();
renderEvents();
}
});
// Course type buttons
document.getElementById('courseButtons').addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
document.querySelectorAll('#courseButtons button').forEach(btn => {
btn.classList.remove('active');
btn.classList.add('secondary');
});
e.target.classList.add('active');
e.target.classList.remove('secondary');
appState.courseType = e.target.dataset.course;
saveStateToStorage();
renderEvents();
}
});
// Set initial course button active state
if (appState.courseType) {
const courseBtn = document.querySelector(`[data-course="${appState.courseType}"]`);
if (courseBtn) {
courseBtn.classList.add('active');
courseBtn.classList.remove('secondary');
}
}
// Show timed only toggle
const showTimedOnlyToggle = document.getElementById('showTimedOnlyToggle');
showTimedOnlyToggle.checked = appState.showTimedOnly;
showTimedOnlyToggle.addEventListener('change', (e) => {
appState.showTimedOnly = e.target.checked;
saveStateToStorage();
applyTimedFilter();
});
// Fast entry mode toggle
const fastEntryToggle = document.getElementById('fastEntryToggle');
fastEntryToggle.checked = appState.fastEntryMode;
fastEntryToggle.addEventListener('change', (e) => {
appState.fastEntryMode = e.target.checked;
saveStateToStorage();
// Update inputmode on all existing time inputs
document.querySelectorAll('.time-input').forEach(input => {
if (appState.fastEntryMode) {
input.setAttribute('inputmode', 'numeric');
} else {
input.removeAttribute('inputmode');
}
});
});
// Clear times button - show modal
document.getElementById('clearTimesBtn').addEventListener('click', () => {
document.getElementById('clearTimesModal').showModal();
});
// Modal close button
document.getElementById('closeModalBtn').addEventListener('click', () => {
document.getElementById('clearTimesModal').close();
});
// Modal cancel button
document.getElementById('cancelClearBtn').addEventListener('click', () => {
document.getElementById('clearTimesModal').close();
});
// Modal confirm button
document.getElementById('confirmClearBtn').addEventListener('click', () => {
appState.times = {};
saveStateToStorage();
renderEvents();
document.getElementById('clearTimesModal').close();
});
}
// Render events table
function renderEvents() {
const container = document.getElementById('eventsContainer');
const noteDisplay = document.getElementById('noteDisplay');
noteDisplay.textContent = '';
if (!appState.ageGroup || !appState.gender || !appState.courseType) {
container.innerHTML = '<p style="text-align: center; color: var(--pico-muted-color);">Please select age group, gender, and course type to view events.</p>';
document.getElementById('timedFilterToggle').style.display = 'none';
return;
}
const ageGroupData = swimData.ageGroups.find(g => g.age === appState.ageGroup);
if (!ageGroupData || !ageGroupData.genders[appState.gender]) {
container.innerHTML = '<p style="text-align: center; color: var(--pico-muted-color);">No events found for selected criteria.</p>';
return;
}
// Display note if exists
if (ageGroupData.note) {
noteDisplay.textContent = ageGroupData.note;
}
const events = ageGroupData.genders[appState.gender].events;
const course = appState.courseType;
let tableHTML = `
<table class="event-table">
<thead>
<tr>
<th>Event</th>
<th>Time</th>
<th>A</th>
<th>B+</th>
<th>B</th>
</tr>
</thead>
<tbody>
`;
events.forEach((event, index) => {
const times = event[course];
// Skip events with no times for this course
if (!times || (times.A === null && times['B+'] === null && times.B === null)) {
return;
}
const eventKey = `${appState.gender}_${course}_${event.name}`;
const userTime = appState.times[eventKey] || '';
const qualification = userTime ? getQualification(userTime, times) : null;
// Add 'has-value' class to row if user has entered a time
// Add met class to row for input border styling
let rowClass = userTime ? 'has-value' : '';
// Add 'has-invalid-standard' class if any standard has warning emoji
if (hasInvalidStandard(times)) {
rowClass += ' has-invalid-standard';
}
if (qualification === 'a') {
rowClass += ' met-a';
} else if (qualification === 'b-plus') {
rowClass += ' met-b-plus';
} else if (qualification === 'b') {
rowClass += ' met-b';
}
// Determine standard cell classes
const aClass = qualification === 'a' ? 'standard-cell met met-a' : 'standard-cell';
const bPlusClass = qualification === 'b-plus' ? 'standard-cell met met-b-plus' : 'standard-cell';
const bClass = qualification === 'b' ? 'standard-cell met met-b' : 'standard-cell';
const inputModeAttr = appState.fastEntryMode ? 'inputmode="numeric"' : '';
tableHTML += `
<tr class="${rowClass}">
<td>${event.name}</td>
<td>
<input
type="text"
class="time-input"
${inputModeAttr}
placeholder="mm:ss.ms"
data-event-key="${eventKey}"
value="${userTime}"
aria-label="Enter time for ${event.name}"
>
</td>
<td class="${aClass} time-value" data-standard="a" data-event-key="${eventKey}">
${times.A || 'n/a'}
</td>
<td class="${bPlusClass} time-value" data-standard="b-plus" data-event-key="${eventKey}">
${times['B+'] || 'n/a'}
</td>
<td class="${bClass} time-value" data-standard="b" data-event-key="${eventKey}">
${times.B || 'n/a'}
</td>
</tr>
`;
});
tableHTML += `
</tbody>
</table>
`;
container.innerHTML = tableHTML;
document.getElementById('timedFilterToggle').style.display = '';
setupTimeInputHandlers();
applyTimedFilter();
}
// Setup time input event handlers
function setupTimeInputHandlers() {
const inputs = document.querySelectorAll('.time-input');
inputs.forEach(input => {
let timeout;
// Auto-select text on focus for easier replacement
input.addEventListener('focus', (e) => {
e.target.select();
// Prevent mouseup from repositioning cursor after select
const preventMouseUp = (event) => {
event.preventDefault();
e.target.removeEventListener('mouseup', preventMouseUp);
};
e.target.addEventListener('mouseup', preventMouseUp, { once: true });
});
input.addEventListener('input', (e) => {
// Real-time validation feedback
const value = e.target.value.trim();
if (value && !isValidTimeInput(value)) {
e.target.classList.add('invalid');
} else {
e.target.classList.remove('invalid');
}
clearTimeout(timeout);
timeout = setTimeout(() => {
handleTimeInput(e.target);
}, 500);
});
input.addEventListener('blur', (e) => {
clearTimeout(timeout);
handleTimeInput(e.target);
});
});
}
// Validate time input contains only valid characters
function isValidTimeInput(value) {
if (!value) return true;
return /^[0-9:.]+$/.test(value);
}
// Parse time input: strip non-digits, parse right-to-left to mm:ss.xx format
function parseTimeInput(value) {
if (!value) return '';
// Strip all non-digits and leading zeros
let digits = value.replace(/\D/g, '');
digits = digits.replace(/^0+/, '') || '0'; // Remove leading zeros, keep at least one digit
if (digits.length === 0) return '';
const len = digits.length;
if (len === 1) {
// Single digit: "5" → "00.05"
return `00.0${digits}`;
} else if (len === 2) {
// Two digits: "34" → "00.34"
return `00.${digits}`;
} else if (len === 3) {
// Three digits: "123" → "01.23"
return `0${digits[0]}.${digits.slice(1)}`;
} else if (len === 4) {
// Four digits: "1234" → "12.34"
return `${digits.slice(0, 2)}.${digits.slice(2)}`;
} else {
// Five or more digits: "12345" → "1:23.45", "123456" → "12:34.56"
const hundredths = digits.slice(-2);
const seconds = digits.slice(-4, -2);
const minutes = digits.slice(0, -4);
return `${minutes}:${seconds}.${hundredths}`;
}
}
// Handle time input
function handleTimeInput(input) {
const eventKey = input.dataset.eventKey;
const value = input.value.trim();
// Check for invalid characters
if (value && !isValidTimeInput(value)) {
input.classList.add('invalid');
delete appState.times[eventKey];
saveStateToStorage();
updateStandardHighlighting(input);
return;
}
// Remove invalid class if present
input.classList.remove('invalid');
// Parse and format the time
const parsedTime = parseTimeInput(value);
// Enforce max length of 9 characters (e.g., "190:38.98")
const finalTime = parsedTime.substring(0, 9);
if (finalTime) {
appState.times[eventKey] = finalTime;
input.value = finalTime;
} else {
delete appState.times[eventKey];
}
saveStateToStorage();
updateStandardHighlighting(input);
}
// Update standard cell highlighting
function updateStandardHighlighting(input) {
const eventKey = input.dataset.eventKey;
const value = input.value.trim();
// Find the row
const row = input.closest('tr');
// Get all standard cells in this row
const standardCells = row.querySelectorAll('.standard-cell');
// Remove all highlight classes from standard cells
standardCells.forEach(cell => {
cell.classList.remove('met', 'met-a', 'met-b-plus', 'met-b');
});
// Remove qualification classes from row
row.classList.remove('met-a', 'met-b-plus', 'met-b');
// Add or remove 'has-value' class on row based on input
if (value) {
row.classList.add('has-value');
} else {
row.classList.remove('has-value');
return;
}
// Skip comparison if input is invalid
if (input.classList.contains('invalid')) {
return;
}
// Find the event's times
const [gender, course, eventName] = eventKey.split('_');
const ageGroupData = swimData.ageGroups.find(g => g.age === appState.ageGroup);
if (!ageGroupData) return;
const event = ageGroupData.genders[gender].events.find(e => e.name === eventName);
if (!event) return;
const times = event[course];
const qualification = getQualification(value, times);
// Highlight the appropriate standard cell (if any)
// Row already has light gray background from 'has-value' class
if (qualification === 'a') {
const aCell = Array.from(standardCells).find(cell => cell.dataset.standard === 'a');
if (aCell) {
aCell.classList.add('met', 'met-a');
}
row.classList.add('met-a');
} else if (qualification === 'b-plus') {
const bPlusCell = Array.from(standardCells).find(cell => cell.dataset.standard === 'b-plus');
if (bPlusCell) {
bPlusCell.classList.add('met', 'met-b-plus');
}
row.classList.add('met-b-plus');
} else if (qualification === 'b') {
const bCell = Array.from(standardCells).find(cell => cell.dataset.standard === 'b');
if (bCell) {
bCell.classList.add('met', 'met-b');
}
row.classList.add('met-b');
}
// If qualification === 'none', just the row gray background shows (no cell highlighting)
applyTimedFilter();
}