-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscript.js
974 lines (796 loc) · 28.9 KB
/
script.js
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
import { getResults } from './results.js';
import { FilterOptions } from './time-classes.js';
/**** Constants/globals ****/
const LS_HUE_VALUE_KEY = 'user-selected-hue';
const DAYS_IN_MONTH_NO_LEAP = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const MONTHS_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const MONTHS_LONG = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const DAYS_OF_THE_WEEK = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const CURR_YEAR = new Date().getFullYear();
const CURR_MONTH = String(new Date().getMonth() + 1).padStart(2, '0');
const currentTooltip = document.createElement('div');
currentTooltip.classList.add('svg-tip', 'svg-tip-one-line');
currentTooltip.style.pointerEvents = 'none'; // Remove pointer events to prevent tooltip flickering
currentTooltip.hidden = true;
document.body.appendChild(currentTooltip); // Add the tooltip to the DOM
/* Update max year */
const yearInput = document.getElementById('form-input-year');
yearInput.max = CURR_YEAR;
// Object where stored all current games, user, hue, year
const DEFAULT_CURRENT_DATA = Object.freeze({
year: 0,
user: '',
hue: '',
games: [],
});
let currentData = {
year: 0,
user: '',
hue: '',
games: [],
};
// Hue slider logic
const rangeInput = document.getElementById('form-input-hue');
const outputHue = document.getElementById('output-hue');
let dataCells; // updated in fetchData to all cells with data
const exampleCells = document.querySelectorAll('.exampleBox');
/**** End constants/globals ****/
function resetCurrentData() {
currentData = { ...DEFAULT_CURRENT_DATA };
}
function disableRangeInput() {
rangeInput.disabled = true;
rangeInput.style.opacity = 0.5;
}
function enableRangeInput() {
rangeInput.disabled = false;
rangeInput.style.opacity = 1;
}
function disableSubmitBtn() {
document.getElementById('submit-button').disabled = true;
}
function enableSubmitBtn() {
document.getElementById('submit-button').disabled = false;
}
function disableForm() {
disableRangeInput();
disableSubmitBtn();
FilterOptions.disable();
}
function enableForm() {
enableRangeInput();
enableSubmitBtn();
FilterOptions.enable();
}
function getHueValueFromLS() {
return localStorage.getItem(LS_HUE_VALUE_KEY);
}
function saveHueValueIntoLS(hue) {
localStorage.setItem(LS_HUE_VALUE_KEY, hue);
}
function updateHueVar(h) {
document.body.style.setProperty('--hue', h);
}
function applyHue(h) {
setHueField(h);
updateHueVar(h);
}
function setHue() {
// Update query parameter
const newUrl = new URL(window.location.href);
const hue = rangeInput.value;
saveHueValueIntoLS(hue);
newUrl.searchParams.set('hue', hue);
history.pushState({}, '', newUrl.toString());
outputHue.innerText = '(' + hue + '°' + ')';
updateHueVar(hue);
currentData.hue = hue;
if (dataCells) {
// Loop through each td element and update its hue
for (const td of dataCells) {
// if we find a cell with no HSL info we exit out of the loop since it means there was a previous bad input
if (!td.dataset.hsl) break;
const hslValues = td.dataset.hsl.split(',');
const saturation = hslValues[1];
const lightness = hslValues[2];
td.style.backgroundColor = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}
}
// Update example cells
exampleCells.forEach((ex) => {
const hslValues = ex.dataset.hsl.split(',');
const saturation = hslValues[1];
const lightness = hslValues[2];
ex.style.color = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
});
}
async function queryBasedOnQueryParams() {
// User, year, and hue query parameters
const mySearchParams = new URLSearchParams(window.location.search);
const user = mySearchParams.get('user');
const year = parseInt(mySearchParams.get('year'));
const hue = parseInt(mySearchParams.get('hue'));
// Get hue value from localStorage
const lsHue = getHueValueFromLS();
const DEFAULT_HUE = lsHue || 0;
// Set default of the year field to current year
// Set default hue to 0
setYearField(CURR_YEAR);
applyHue(DEFAULT_HUE);
// Use user, year, and hue query parameters to fetch data if valid
if (user) {
setUserField(user);
} else {
console.log('No user query parameter');
return;
}
if (year) {
if (isValidChessComYear(year)) {
setYearField(year);
} else {
console.error('Invalid year query parameter');
return;
}
}
let validHue;
if (hue) {
validHue = setValidHue(hue);
applyHue(validHue);
}
FilterOptions.reset();
runHeatMap({
user,
year: year || CURR_YEAR,
hue: validHue || DEFAULT_HUE,
fetchingFunc: fetchData,
});
}
function setUserField(user) {
const userField = document.getElementById('form-input-user');
userField.value = user.trim();
}
function setYearField(year) {
const yearField = document.getElementById('form-input-year');
yearField.value = year;
}
function setHueField(hue) {
const hueField = document.getElementById('form-input-hue');
const exampleBox1 = document.getElementById('exampleBox1');
exampleBox1.style.color = `hsl(${hue}, 70%, 66%)`;
exampleBox1.dataset.hsl = `${hue},70,66`;
const exampleBox2 = document.getElementById('exampleBox2');
exampleBox2.style.color = `hsl(${hue}, 62%, 37%)`;
exampleBox2.dataset.hsl = `${hue},62,37`;
const exampleBox3 = document.getElementById('exampleBox3');
exampleBox3.style.color = `hsl(${hue}, 58%, 24%)`;
exampleBox3.dataset.hsl = `${hue},58,24`;
const exampleBox4 = document.getElementById('exampleBox4');
exampleBox4.style.color = `hsl(${hue}, 51%, 11%)`;
exampleBox4.dataset.hsl = `${hue},51,11`;
hueField.value = hue;
}
function isPreviousYearFunc(year) {
return year < CURR_YEAR;
}
function isValidChessComYear(year) {
const minYear = 2007;
return !isNaN(year) && year >= minYear && year <= CURR_YEAR;
}
function setValidHue(value) {
const num_mod = value % 360;
if (num_mod < 0) return num_mod + 360;
return num_mod;
}
function createCoordsString(x, y) {
return `x-${x}-y-${y}`;
}
function generateTable() {
const container = document.getElementById('heatmap');
const descriptorSpan = document.createElement('span');
const table = document.createElement('table');
const tableCaption = document.createElement('caption');
const tableHeader = document.createElement('thead');
const tableHeaderTR = document.createElement('tr');
const tableHeaderTD = document.createElement('td');
const tableHeaderSpan = document.createElement('span');
const tableBody = document.createElement('tbody');
descriptorSpan.classList.add('sr-only');
descriptorSpan.setAttribute('id', 'games-played-graph-description');
descriptorSpan.setAttribute('aria-hidden', 'true');
descriptorSpan.innerText = 'User activity over one year of time. Each column is one week, with older weeks to the left.';
table.setAttribute('aria-readonly', 'true');
table.setAttribute('aria-describedby', 'games-played-graph-description');
table.style.width = 'max-content';
table.style.borderSpacing = '4px';
table.style.borderCollapse = 'separate';
table.style.overflow = 'hidden';
table.style.position = 'relative';
tableCaption.innerText = 'Games Played Graph';
tableCaption.classList.add('sr-only');
tableHeaderTR.style.height = '15px';
tableHeaderTD.style.width = '27px';
tableHeaderSpan.classList.add('sr-only');
tableHeaderSpan.innerText = 'Day of Week';
tableHeaderTD.appendChild(tableHeaderSpan);
tableHeaderTR.appendChild(tableHeaderTD);
for (let i = 0; i < 12; i++) {
const tdHeader = document.createElement('td');
const tdHeaderSpan = document.createElement('span');
const tdHeaderSpanHidden = document.createElement('span');
tdHeader.setAttribute('data-month', `month${i}`);
tdHeader.setAttribute('colspan', '3');
tdHeader.style.position = 'relative';
tdHeader.style.fontSize = '12px';
tdHeader.style.textAlign = 'left';
tdHeader.style.padding = '0.125em 0.5em 0.125em 0';
tdHeaderSpan.setAttribute('aria-hidden', 'true');
tdHeaderSpan.style.position = 'absolute';
tdHeaderSpan.style.top = '0';
tdHeaderSpanHidden.classList.add('sr-only');
tdHeader.appendChild(tdHeaderSpanHidden);
tdHeader.appendChild(tdHeaderSpan);
tableHeaderTR.appendChild(tdHeader);
}
for (let i = 0; i < 7; i++) {
const tr = document.createElement('tr');
const tdLabel = document.createElement('td');
const tdLabelSpan = document.createElement('span');
const tdLabelSpanHidden = document.createElement('span');
tr.style.height = '13px';
tdLabelSpanHidden.classList.add('sr-only');
tdLabelSpan.setAttribute('aria-hidden', 'true');
tdLabelSpan.style.position = 'absolute';
tdLabelSpan.style.bottom = '-2px';
tdLabelSpan.style.lineHeight = '1rem';
tdLabel.style.position = 'relative';
tdLabel.style.padding = '0.125em 0.5em 0.125em 0';
tdLabel.style.fontSize = '12px';
tdLabel.style.textAlign = 'left';
tdLabel.style.width = '27px';
const clipPathStyle = i % 2 === 0 ? 'Circle(0)' : 'None';
tdLabelSpanHidden.textContent = DAYS_OF_THE_WEEK[i];
tdLabelSpan.textContent = DAYS_OF_THE_WEEK[i].slice(0, 3);
tdLabelSpan.style.clipPath = clipPathStyle;
tdLabel.appendChild(tdLabelSpan);
tr.appendChild(tdLabel);
// Because it is possible to have a leap year that starts on a Saturday,
// the last day of that leap year could appear on column 54
for (let j = 0; j < 54; j++) {
const td = document.createElement('td');
const tdSpan = document.createElement('span');
td.style.width = '11px';
td.style.borderRadius = '2px';
td.style.backgroundColor = 'hsla(0, 0%, 50%, 0.15)';
td.setAttribute('data-coord', createCoordsString(j, i));
td.setAttribute('tabindex', '-1');
td.setAttribute('aria-selected', 'false');
td.classList.add(`anim${((i + j) % 4) + 1}`);
td.addEventListener('mouseover', showTooltip);
td.addEventListener('mouseleave', hideTooltip);
tdSpan.classList.add('sr-only');
tdSpan.innerText = 'No Data';
td.appendChild(tdSpan);
tr.appendChild(td);
}
tableHeader.appendChild(tableHeaderTR);
tableBody.appendChild(tr);
}
table.appendChild(tableCaption);
table.appendChild(tableHeader);
table.appendChild(tableBody);
container.appendChild(table);
container.appendChild(descriptorSpan);
}
function hideTooltip() {
if (currentTooltip) {
currentTooltip.hidden = true;
currentTooltip.innerText = 'No Data';
}
}
function showTooltip(event, cell) {
const el = event.target;
if (!(el instanceof HTMLElement || el instanceof SVGElement) && !cell) return;
hideTooltip();
function isTooFarLeft(graphContainerBounds, tooltipX) {
return graphContainerBounds.x > tooltipX;
}
function isTooFarRight(graphContainerBounds, tooltipX) {
return graphContainerBounds.x + graphContainerBounds.width < tooltipX + currentTooltip.offsetWidth;
}
const currentCell = el || cell;
const elCollection = currentCell.getElementsByTagName('span');
if (elCollection.length > 0) {
currentTooltip.innerText = elCollection[0].innerText;
} else {
currentTooltip.innerText = 'No Data';
}
// We have to show the tooltip before calculating it's position.
currentTooltip.hidden = false;
const tooltipWidth = currentTooltip.offsetWidth;
const tooltipHeight = currentTooltip.offsetHeight;
const bounds = currentCell.getBoundingClientRect();
const x = bounds.left + window.pageXOffset - tooltipWidth / 2 + bounds.width / 2;
const y = bounds.bottom + window.pageYOffset - tooltipHeight - bounds.height * 2;
const graphContainer = document.getElementById('heatmap');
const graphContainerBounds = graphContainer.getBoundingClientRect();
currentTooltip.style.top = `${y}px`;
if (isTooFarLeft(graphContainerBounds, x)) {
currentTooltip.style.left = `${x + currentTooltip.offsetWidth / 2 - bounds.width}px`;
currentTooltip.classList.add('left');
currentTooltip.classList.remove('right');
} else if (isTooFarRight(graphContainerBounds, x)) {
currentTooltip.style.left = `${x - currentTooltip.offsetWidth / 2 + bounds.width}px`;
currentTooltip.classList.add('right');
currentTooltip.classList.remove('left');
} else {
currentTooltip.style.left = `${x}px`;
currentTooltip.classList.remove('left');
currentTooltip.classList.remove('right');
}
}
function pulseCells() {
const targetDiv = document.getElementById('heatmap');
const tbodyCollection = targetDiv.getElementsByTagName('tbody')[0].children;
Array.from(tbodyCollection).map((elem) => {
const tdToUpdate = Array.from(elem.children).slice(1);
tdToUpdate.map((item) => {
item.classList.add('pulseOpacity');
});
});
}
function clearTable() {
const targetDiv = document.getElementById('heatmap');
const tbodyCollection = targetDiv.getElementsByTagName('tbody')[0].children;
Array.from(tbodyCollection).map((elem) => {
const tdToUpdate = Array.from(elem.children).slice(1);
tdToUpdate.map((item) => {
item.classList.remove('pulseOpacity');
item.style.backgroundColor = 'hsla(0, 0%, 50%, 0.15)';
item.getElementsByTagName('span')[0].innerText = 'No Data';
item.style.visibility = 'visible';
delete item.dataset.hsl;
delete item.dataset.text;
item.classList.remove('data-cell');
});
});
}
function easeInPowerBounded(x, yMin, yMax, power = 1) {
// Ensure that x is within the range of 0 and 1
x = Math.max(0, Math.min(1, x));
// Calculate y, the output value of the "ease in" function
// Scale and shift y to fit within the range of yMin and yMax
return x ** power * (yMax - yMin) + yMin;
}
function getDateStrings(currentDate) {
const startYear = currentDate.getFullYear() - 1;
const startMonth = String(currentDate.getMonth() + 1);
const startDate = new Date(startYear, startMonth, 1);
const dateStrings = [];
for (let d = startDate; d <= currentDate; d.setDate(d.getDate() + 1)) {
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const dateString = `${year}.${month}.${day}`;
dateStrings.push(dateString);
}
return dateStrings;
}
async function fetchUserArchives(username) {
const url = `https://api.chess.com/pub/player/${username}/games/archives`;
const options = getOptions();
const resp = await fetch(url, options);
if (!resp.ok) {
enableForm();
clearTable();
FilterOptions.disable();
alert(`User ${username} does not exist!`);
throw new Error('Failed to fetch data');
}
const { archives } = await resp.json();
return archives;
}
function makeNecessaryVars(year) {
const isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
const isPreviousYear = isPreviousYearFunc(year);
const today = isPreviousYear ? new Date(year, 11, 31) : new Date();
const oneYearAgo = isPreviousYear ? new Date(year, 0, 1) : new Date().setFullYear(today.getFullYear() - 1);
const dateArray = getDateStrings(today);
const nextMonth = isPreviousYear ? 1 : new Date().getMonth() + 2;
return {
isLeapYear,
isPreviousYear,
today,
oneYearAgo,
dateArray,
nextMonth,
};
}
async function fetchData(username, year) {
const { isPreviousYear, nextMonth } = makeNecessaryVars(year);
const user = String(username).trim().toLocaleLowerCase();
const archives = await fetchUserArchives(user);
const validArchives = [];
for (let i = 0; i < 12; i++) {
let loopMonth;
let loopYear;
if (nextMonth + i <= 12) {
loopMonth = String(nextMonth + i).padStart(2, '0');
loopYear = isPreviousYear ? String(year) : String(year - 1);
} else {
loopMonth = String(nextMonth + i - 12).padStart(2, '0');
loopYear = String(year);
}
const url = `https://api.chess.com/pub/player/${user}/games/${loopYear}/${loopMonth}`;
if (archives.includes(url)) {
validArchives.push({
url: url,
month: loopMonth,
year: loopYear,
});
}
}
for (let i = 0; i < validArchives.length; i++) {
const { url, month, year } = validArchives[i];
const isShouldSkipCaching = month === CURR_MONTH && year === String(CURR_YEAR);
const cacheData = await getData(url, isShouldSkipCaching);
const games = cacheData.games;
currentData.games = [...currentData.games, ...games];
}
}
function getCellNodeByDay(day) {
const x = Math.floor(day / 7);
const y = day % 7;
const id = createCoordsString(x, y);
return document.querySelector(`[data-coord="${id}"`);
}
function getCellNodeByCoords(x, y) {
return document.querySelector(`[data-coord="${createCoordsString(x, y)}"]`);
}
function getActiveCellNode() {
const cellIndex0 = document.querySelector('td[tabindex="0"]');
if (cellIndex0) {
if (cellIndex0.style.visibility !== 'hidden') return cellIndex0;
deactivateCell(cellIndex0);
}
const cells = document.querySelectorAll('[data-coord]');
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
const isCellVisible = cell.style.visibility !== 'hidden';
const isActive = cell.getAttribute('tabindex') === 0;
if (isActive && !isCellVisible) {
deactivateCell(cell);
const nextCell = cells[i + 1];
activateCell(nextCell);
}
if (isCellVisible) return cell;
}
}
function getActiveCellNodeCoords() {
const cell = getActiveCellNode();
const coords = cell?.dataset?.coord;
if (!coords) return;
const coordsArray = coords.split('-');
const x = Number(coordsArray[1]);
const y = Number(coordsArray[3]);
return { x, y };
}
function fillTableWithData({ games, user, year, hue }) {
const { isLeapYear, oneYearAgo, dateArray, nextMonth } = makeNecessaryVars(year);
let maxGamesPlayed = 0;
let daySum = 0;
let prevColSum = 0;
const gameData = {};
let totalWins = 0;
let totalLosses = 0;
let totalDraws = 0;
let totalGames = 0;
for (let j = 0; j < games.length; j++) {
const game = games[j];
const currGameDate = new Date(game.end_time * 1000);
const year = currGameDate.getFullYear();
const month = ('0' + (currGameDate.getMonth() + 1)).slice(-2);
const day = ('0' + currGameDate.getDate()).slice(-2);
const dateString = `${year}.${month}.${day}`;
let result = null;
// Remove Games Outside of Lower Bound Month
if (currGameDate < oneYearAgo) continue;
const playerBlack = game.black.username.toLowerCase();
const playerWhite = game.white.username.toLowerCase();
if (playerWhite === user.toLowerCase()) result = game.white.result;
if (playerBlack === user.toLowerCase()) result = game.black.result;
const [win, loss, draw] = getResults(result);
totalWins += win;
totalLosses += loss;
totalDraws += draw;
totalGames++;
if (gameData[dateString]) {
// Stats for the day
gameData[dateString]['win'] += win;
gameData[dateString]['loss'] += loss;
gameData[dateString]['draw'] += draw;
gameData[dateString]['total']++;
// Update max games played
if (gameData[dateString]['total'] > maxGamesPlayed) maxGamesPlayed = gameData[dateString]['total'];
} else {
gameData[dateString] = {
win: win,
loss: loss,
draw: draw,
total: 1,
};
}
}
// Get which day the heatmap grid will start at
const firstDateSplit = dateArray[0].split('.');
const firstDayOffset = new Date(parseInt(firstDateSplit[0]), parseInt(firstDateSplit[1]) - 1, parseInt(firstDateSplit[2])).getDay();
let dayIncrement = firstDayOffset;
clearTable();
const lightnessCiel = 66;
const lightnessFloor = 11;
const saturationCiel = 70;
const saturationFloor = 50;
const threshold = 4;
// Hide Cells that don't appear in the year (Before)
for (let cellCountBefore = 0; cellCountBefore < dayIncrement; cellCountBefore++) {
const dataCellBefore = document.querySelector(`[data-coord=${createCoordsString(0, cellCountBefore)}`);
dataCellBefore.style.visibility = 'hidden';
}
// Loop over all the dates in the rolling year
for (const dateString of dateArray) {
const dataCell = getCellNodeByDay(dayIncrement);
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
// Ensure cross-browser compatibility with standardized date
const dateParts = dateString.split('.');
const datePretty = new Date(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, parseInt(dateParts[2])).toLocaleDateString('en-US', options);
if (gameData.hasOwnProperty(dateString)) {
const totalGames = gameData[dateString]['total'];
const lightness = Math.floor(easeInPowerBounded(1 - (totalGames - threshold) / (maxGamesPlayed - threshold), lightnessFloor, lightnessCiel, 5));
const saturation = Math.floor(easeInPowerBounded(1 - (totalGames - threshold) / (maxGamesPlayed - threshold), saturationFloor, saturationCiel, 3));
const text = `[${gameData[dateString]['win']}-${gameData[dateString]['loss']}-${gameData[dateString]['draw']}] on ${datePretty}`;
dataCell.dataset.date = dateString;
dataCell.dataset.text = text;
// Update popup text
dataCell.querySelector('span').textContent = text;
if (totalGames >= 1) {
dataCell.classList.add('data-cell');
dataCell.style.backgroundColor = `hsl(${hue}, ${saturation}%, ${lightnessCiel}%)`;
// Store the HSL values as a custom attribute on the td element
dataCell.dataset.hsl = `${hue},${saturation},${lightness}`;
}
if (totalGames > threshold) {
dataCell.classList.add('data-cell');
dataCell.style.backgroundColor = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
dataCell.dataset.hsl = `${hue},${saturation},${lightness}`;
}
} else {
dataCell.querySelector('span').textContent = `[0-0-0] on ${datePretty}`;
dataCell.style.backgroundColor = 'hsla(0, 0%, 50%, 0.15)';
}
dayIncrement++;
}
// Hide Cells that don't appear in the year (After)
while (dayIncrement < 54 * 7) {
const dataCellAfter = getCellNodeByDay(dayIncrement);
dataCellAfter.style.visibility = 'hidden';
dayIncrement++;
}
// Set Width of Month Headers
for (let j = 0; j < 12; j++) {
const monthIndex = (j + nextMonth - 1) % 12;
daySum += DAYS_IN_MONTH_NO_LEAP[monthIndex] + (j === 0 ? firstDayOffset : 0) + (j === 1 && isLeapYear ? 1 : 0);
const colWidth = Math.floor(daySum / 7) - prevColSum;
const headElem = document.querySelector(`[data-month="month${j}"]`);
headElem.setAttribute('colspan', String(colWidth));
headElem.childNodes[0].innerText = MONTHS_LONG[monthIndex];
headElem.childNodes[1].innerText = MONTHS_SHORT[monthIndex];
prevColSum += colWidth;
}
// Set new data cells
dataCells = document.querySelectorAll('.data-cell');
// Update total wins/losses/draws/total and user/year
const winInfo = document.getElementById('winInfo');
winInfo.innerText = totalWins;
const yearInfo = document.getElementById('yearInfo');
if (year == CURR_YEAR) {
yearInfo.innerText = 'the past year';
} else {
yearInfo.innerText = year;
}
const userInfo = document.getElementById('usernameInfo');
userInfo.innerText = user;
const lossInfo = document.getElementById('lossInfo');
lossInfo.innerText = totalLosses;
const drawInfo = document.getElementById('drawInfo');
drawInfo.innerText = totalDraws;
const totalInfo = document.getElementById('totalGameInfo');
totalInfo.innerText = totalGames;
}
async function runHeatMap({ user, year, hue, fetchingFunc, timeClassToFilterBy }) {
// Hide tooltip
hideTooltip();
// Disable hue input and submit button until end
disableForm();
pulseCells();
if (fetchingFunc) {
currentData.year = year;
currentData.hue = hue;
currentData.user = user;
// Call the function that handles the chess.com requests
await fetchingFunc(currentData.user, currentData.year, currentData.hue);
}
let games;
if (timeClassToFilterBy) {
games = FilterOptions.filterGamesByTimeClass(currentData.games, timeClassToFilterBy);
} else {
games = currentData.games;
}
fillTableWithData({
games,
year: currentData.year,
hue: currentData.hue,
user: currentData.user,
});
// Re-enable hue input and submit button at end
enableForm();
}
function getOptions() {
// Compliance - https://www.chess.com/announcements/view/breaking-change-user-agent-contact-info-required
// If we want to use this, we'd want to have our own server send the requests rather than the browser
// then we'd set this header
// const email = '[email protected]';
const headers = new Headers();
// headers.append('User-Agent', `ChessHeat/1.0 (+${email})`);
const options = {
method: 'GET',
headers: headers,
};
return options;
}
// Try to get data from the cache, but fall back to fetching it live.
async function getData(url, skipCaching) {
const cacheVersion = 1;
const cacheName = `myapp-${cacheVersion}`;
if (!skipCaching) {
const cachedResponse = await getCachedData(cacheName, url);
if (cachedResponse) {
return cachedResponse.json();
}
}
const options = getOptions();
const response = await fetch(url, options);
if (!response.ok) {
enableForm();
throw new Error('Failed to fetch data');
}
if (!skipCaching) {
const cacheStorage = await caches.open(cacheName);
cacheStorage.put(url, response.clone());
}
return response.json();
}
// Get data from the cache.
async function getCachedData(cacheName, url) {
const cacheStorage = await caches.open(cacheName);
const cachedResponse = await cacheStorage.match(url);
if (cachedResponse && cachedResponse.ok) {
return cachedResponse;
}
return null;
}
// Init keyboard accessibility for chessheat table
function activateCell(cell) {
cell.setAttribute('tabindex', 0);
}
function deactivateCell(cell) {
cell.setAttribute('tabindex', -1);
}
function initKeyboardAccessibility() {
const firstCell = getCellNodeByCoords(0, 0);
activateCell(firstCell);
const moveFocus = (e, currentCell) => {
const { key } = e;
let nextX;
let nextY;
const { x: currentX, y: currentY } = getActiveCellNodeCoords();
if (key === 'ArrowLeft') {
nextX = currentX - 1;
nextY = currentY;
e.preventDefault();
} else if (key === 'ArrowUp') {
nextX = currentX;
nextY = currentY - 1;
e.preventDefault();
} else if (key === 'ArrowRight') {
nextX = currentX + 1;
nextY = currentY;
e.preventDefault();
} else if (key === 'ArrowDown') {
nextX = currentX;
nextY = currentY + 1;
e.preventDefault();
}
if (!nextX && !nextY) return;
const nextCell = getCellNodeByCoords(nextX, nextY);
if (!nextCell) return;
const isNextCellOutOfBounds = nextCell.style.visibility === 'hidden';
if (isNextCellOutOfBounds) return;
deactivateCell(currentCell);
activateCell(nextCell);
nextCell.focus();
showTooltip(false, nextCell);
};
document.addEventListener('keydown', (e) => {
const currentCell = getActiveCellNode();
moveFocus(e, currentCell);
});
document.addEventListener('click', () => {
hideTooltip();
});
}
generateTable();
FilterOptions.generate();
FilterOptions.disable();
queryBasedOnQueryParams();
initKeyboardAccessibility();
/**** Event listeners ****/
document.getElementById('form').addEventListener('submit', async (e) => {
// Prevent the form from refreshing the page
e.preventDefault();
resetCurrentData();
// Get the value of the inputs
const user = document.getElementById('form-input-user').value.toLowerCase();
const year = parseInt(document.getElementById('form-input-year').value);
const hue = parseInt(document.getElementById('form-input-hue').value);
// Validate user
if (user === '') {
alert('Username must not be empty.');
return;
}
// Validate year
if (!isValidChessComYear(year)) {
alert('Year must be greater than 2007 and not in the future.');
return;
}
// Validate hue
if (hue < 0 || hue > 360 || isNaN(hue) || !isFinite(hue)) {
alert('Hue must be between values 0 and 360');
return;
}
// Update query params of user/year without reload
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('user', user);
newUrl.searchParams.set('year', year);
history.pushState({}, '', newUrl.toString());
FilterOptions.reset();
runHeatMap({
user,
year,
hue,
fetchingFunc: fetchData,
});
});
document.getElementById('copy-button').addEventListener('click', async () => {
// Copy URL to clipboard
await navigator.clipboard.writeText(window.location.href);
// Alert the user that the link has been copied
alert('Link copied to clipboard!');
});
function handleFilterOptionsChange(e) {
const value = e.target.value;
runHeatMap({
timeClassToFilterBy: value,
});
}
// Debounce setHue function
let timerId = null;
rangeInput.addEventListener('input', function () {
clearTimeout(timerId);
timerId = setTimeout(setHue, 80);
});
FilterOptions.createChangeEventListener(handleFilterOptionsChange);
/**** End event listeners ****/