forked from lazy-guy/tomodoro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1594 lines (1425 loc) · 41.3 KB
/
index.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
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
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("./sw.js");
}
let timerWorker = new Worker("./worker.js");
let root = document.documentElement;
let mainel = document.getElementById("main");
let statisticsDiv = document.getElementById("statistics");
let menu = document.getElementById("menu");
let manageTasks = document.getElementById("managetasks");
let timediv = document.getElementById("time");
let timer = document.getElementById("timer");
let roundnoDiv = document.getElementById("roundno");
let pauseplaybtn = document.getElementById("pauseplay");
let progress = document.getElementById("progress");
let nextbtn = document.getElementById("next");
let menubtn = document.getElementById("menubtn");
let taskSelect = document.getElementById("task-select");
const timerInputs = {
focus: document.getElementById("focus-input"),
short: document.getElementById("short-input"),
long: document.getElementById("long-input"),
rounds: document.getElementById("rounds-input"),
};
let colorsDiv = document.getElementById("colors");
let pipActive = false;
const fullname = {
focus: "Focus",
short: "Short Break",
long: "Long Break",
};
let viewState = "timer";
let config = {
focus: 1500,
short: 300,
long: 900,
longGap: 4,
};
let audioType = "";
const audioTypes = ["noise"];
let roundInfo = {
t: 0,
focusNum: 1,
current: "focus",
running: false,
};
//#region Time
function setTime() {
let seconds = config[roundInfo.current] - roundInfo.t;
if (seconds < 0) {
nextRound();
return;
}
let timestr =
Math.floor(seconds / 60)
.toString()
.padStart(2, "0") +
":" +
(seconds % 60).toString().padStart(2, "0");
timediv.innerText = timestr;
document.title = `${timestr} ${fullname[roundInfo.current]} - Tomodoro`;
progress.style.strokeDashoffset = (roundInfo.t / config[roundInfo.current]) * 100;
if (pipActive) loop();
}
timerWorker.addEventListener("message", (e) => {
roundInfo.t = e.data.t;
setTime();
if (!e.data.running) {
timer.style.setProperty("--progress", "0");
nextRound();
}
});
//#endregion
//#region Timer Actions
function nextRound() {
let finished = fullname[roundInfo.current];
let body = "Begin ";
if (roundInfo.current === "focus") {
if (audioType === "noise") {
fadeOut();
}
focusEnd(roundInfo.t);
finished += " Round";
if (roundInfo.focusNum >= config.longGap) {
roundInfo.current = "long";
roundInfo.focusNum = 0;
} else {
roundInfo.current = "short";
}
body += "a " + Math.floor(config[roundInfo.current] / 60) + " minute " + fullname[roundInfo.current];
} else {
roundInfo.current = "focus";
roundInfo.focusNum++;
roundnoDiv.innerText = roundInfo.focusNum + "/" + config.longGap;
body += "focusing for " + Math.floor(config.focus / 60) + " minutes";
}
timer.className = "t-" + roundInfo.current;
roundInfo.t = 0;
setTime();
if (roundInfo.running) {
if (roundInfo.current === "focus" && audioType === "noise") {
fadeIn();
}
timerWorker.postMessage({
type: "start",
maxDuration: config[roundInfo.current],
});
}
notify(`${finished} Complete`, body);
}
function pauseplay() {
if (roundInfo.current === "none") {
nextRound();
pauseplaybtn.className = "playing";
return;
}
if (roundInfo.running) {
if (roundInfo.current === "focus" && audioType === "noise") {
fadeOut();
}
timerWorker.postMessage({ type: "stop" });
roundInfo.running = false;
pauseplaybtn.title = "Start Timer";
pauseplaybtn.className = "paused";
} else {
if (roundInfo.current === "focus" && audioType === "noise") {
fadeIn();
}
timerWorker.postMessage({
type: "start",
t: roundInfo.t,
maxDuration: config[roundInfo.current],
});
roundInfo.running = true;
pauseplaybtn.title = "Pause Timer";
pauseplaybtn.className = "playing";
}
}
pauseplaybtn.addEventListener("click", pauseplay);
nextbtn.addEventListener("click", () => {
nextRound();
});
document.getElementById("resetround").addEventListener("click", () => {
if (roundInfo.running) pauseplay();
roundInfo.t = 0;
setTime();
});
document.addEventListener("keydown", (event) => {
if (event.isComposing || event.keyCode === 229) {
return;
}
if (event.code === "Space") {
if (document.activeElement === pauseplaybtn || viewState !== "timer") {
return;
}
pauseplaybtn.focus();
pauseplay();
}
});
//#endregion
//#region Notifications
let notificationEnabled = true;
let notificationSilent = false;
let notification;
let notifSelect = document.getElementById("notif-select");
function setNotif(pomoNotif) {
if (pomoNotif === "disabled") {
notificationEnabled = false;
} else if (pomoNotif === "silent") {
notificationEnabled = true;
notificationSilent = true;
} else {
notificationEnabled = true;
notificationSilent = false;
}
notifSelect.value = pomoNotif;
}
if (localStorage.getItem("pomo-notif")) {
setNotif(localStorage.getItem("pomo-notif"));
}
notifSelect.addEventListener("change", function () {
setNotif(this.value);
localStorage.setItem("pomo-notif", this.value);
});
function notify(title, message) {
if (!notificationEnabled) return;
if (!("Notification" in window)) {
return;
} else if (Notification.permission === "granted") {
if (notification) notification.close();
notification = new Notification(title, {
body: message,
icon: "./icons/icon192.png",
silent: notificationSilent,
});
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then(function (permission) {
if (permission === "granted") {
notification = new Notification(title, {
body: message,
icon: "./icons/icon192.png",
silent: notificationSilent,
});
}
});
}
}
function setup() {
if ("Notification" in window) {
if (Notification.permission !== "denied" && Notification.permission !== "granted") {
Notification.requestPermission();
}
}
setTime();
roundnoDiv.innerText = roundInfo.focusNum + "/" + config.longGap;
}
setup();
//#endregion
//#region Audio
let audioSelect = document.getElementById("audio-select");
if (localStorage.getItem("pomo-audio-type")) {
let audioTypeL = localStorage.getItem("pomo-audio-type");
if (audioTypes.includes(audioTypeL)) {
audioType = audioTypeL;
audioSelect.value = audioType;
}
} else {
audioSelect.value = "disabled";
}
let audioCtx;
let noiseSource;
let gain;
let noiseTimeout;
let isWhiteNoiseRunning = false;
let isFadingOut = false;
audioSelect.addEventListener("change", () => {
audioType = audioSelect.value;
if(audioType !== "noise" && isWhiteNoiseRunning) {
fadeOut()
}
localStorage.setItem("pomo-audio-type", audioType);
});
function initNoise() {
if (!audioCtx) {
audioCtx = new AudioContext();
}
const bufferSize = audioCtx.sampleRate * 3;
const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
let data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1;
}
noiseSource = audioCtx.createBufferSource();
noiseSource.buffer = buffer;
gain = audioCtx.createGain();
gain.gain = 0.5;
noiseSource.connect(gain);
gain.connect(audioCtx.destination);
}
function playNoise() {
noiseSource.loop = true;
noiseSource.start();
isWhiteNoiseRunning = true;
}
function stopNoise() {
noiseSource.stop();
isWhiteNoiseRunning = false;
isFadingOut = false;
}
function fadeOut() {
if (!isWhiteNoiseRunning) return;
isFadingOut = true;
gain.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 1);
noiseTimeout = setTimeout(stopNoise, 1000);
}
function fadeIn() {
clearTimeout(noiseTimeout);
if (!isFadingOut) {
initNoise();
gain.gain.setValueAtTime(0, audioCtx.currentTime);
gain.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 1);
playNoise(0);
} else {
gain.gain.setValueAtTime(gain.gain.value, audioCtx.currentTime);
gain.gain.linearRampToValueAtTime(0.5, audioCtx.currentTime + 1);
}
}
//#endregion
//#region Current View
const animations = {
out: [
{ opacity: "1", transform: "translateY(0)" },
{
opacity: "0",
transform: "translateY(50px)",
},
],
in: [
{
opacity: "0",
transform: "translateY(50px)",
},
{ opacity: "1", transform: "translateY(0)" },
],
animoptions: {
duration: 200,
fill: "forwards",
},
};
let lastanim;
menubtn.addEventListener("click", () => {
if (lastanim) lastanim.cancel();
if (viewState === "menu") {
mainel.style.display = "flex";
lastanim = menu.animate(animations.out, animations.animoptions);
lastanim.onfinish = () => {
menu.style.display = "none";
};
menubtn.title = "Open Settings";
menubtn.classList.remove("cross");
viewState = "timer";
} else {
if (viewState !== "timer") return;
menu.style.display = "flex";
menu.scroll({ top: 0 });
lastanim = menu.animate(animations.in, animations.animoptions);
lastanim.onfinish = () => (mainel.style.display = "none");
menubtn.classList.add("cross");
menubtn.title = "Close Settings";
viewState = "menu";
}
});
document.getElementById("managetaskbtn").addEventListener("click", function () {
if (lastanim) lastanim.cancel();
if (viewState !== "timer") return;
manageTasks.style.display = "flex";
manageTasks.scroll({ top: 0 });
lastanim = manageTasks.animate(animations.in, animations.animoptions);
lastanim.onfinish = () => (mainel.style.display = "none");
viewState = "tasks";
});
document.getElementById("closetasks").addEventListener("click", function () {
if (lastanim) lastanim.cancel();
if (viewState === "tasks") {
mainel.style.display = "flex";
lastanim = manageTasks.animate(animations.out, animations.animoptions);
lastanim.onfinish = () => {
manageTasks.style.display = "none";
};
viewState = "timer";
}
});
document.getElementById("statbtn").addEventListener("click", function () {
if (lastanim) lastanim.cancel();
if (viewState !== "timer") return;
statisticsDiv.style.display = "flex";
statisticsDiv.scroll({ top: 0 });
lastanim = statisticsDiv.animate(animations.in, animations.animoptions);
lastanim.onfinish = () => (mainel.style.display = "none");
viewState = "statistics";
loadStatistics();
});
document.getElementById("closestats").addEventListener("click", function () {
if (lastanim) lastanim.cancel();
if (viewState === "statistics") {
mainel.style.display = "flex";
lastanim = statisticsDiv.animate(animations.out, animations.animoptions);
lastanim.onfinish = () => {
statisticsDiv.style.display = "none";
};
viewState = "timer";
}
});
//#endregion
//#region Statistics
let tasks = ["Default Task"];
let selectedTask = "Default Task";
let taskContainer = document.getElementById("task-container");
let filterContainer = document.getElementById("filters");
let filteredTasks = new Set();
let db;
let statTimeSelect = document.getElementById("stat-time-select");
function loadTasks() {
navigator.storage.persist();
if (localStorage.getItem("pomo-tasks")) {
tasks = JSON.parse(localStorage.getItem("pomo-tasks"));
if (!(tasks instanceof Array)) {
localStorage.removeItem("pomo-tasks");
tasks = ["Default Task"];
}
}
if (localStorage.getItem("pomo-records")) {
let records = JSON.parse(localStorage.getItem("pomo-records"));
records.forEach((r) => saveRecord(r));
localStorage.removeItem("pomo-records");
}
if (localStorage.getItem("pomo-selected-task")) {
if (tasks.includes(localStorage.getItem("pomo-selected-task"))) {
selectedTask = localStorage.getItem("pomo-selected-task");
taskSelect.value = selectedTask;
}
}
if (localStorage.getItem("pomo-stat-period")) {
statTimeSelect.value = localStorage.getItem("pomo-stat-period");
}
return new Promise((resolve) => {
let tr = indexedDB.open("pomo-db", 1);
tr.onupgradeneeded = (ev) => {
db = ev.target.result;
let recordStore = db.createObjectStore("records", { keyPath: "d" });
recordStore.createIndex("task", "n", { unique: false });
recordStore.transaction.oncomplete = (event) => {
resolve();
};
};
tr.onsuccess = (ev) => {
db = ev.target.result;
resolve();
};
});
}
async function getRecords(time) {
let result = [];
return new Promise((resolve) => {
if (filteredTasks.size === 0) {
resolve(result);
} else if (filteredTasks.size === tasks.length) {
let tr = db.transaction("records", "readonly").objectStore("records").index("task").getAll();
tr.onsuccess = () => resolve(tr.result);
} else {
let filteredArray = Array.from(filteredTasks);
filteredArray.forEach((task, i) => {
let tr = db
.transaction("records", "readonly")
.objectStore("records")
.index("task")
.getAll(IDBKeyRange.only(task));
tr.onsuccess = (ev) => {
result.push(...tr.result);
if (i === filteredArray.length - 1) {
resolve(result);
}
};
});
}
});
}
function saveRecord(r) {
let tr = db.transaction("records", "readwrite").objectStore("records").add(r);
tr.onsuccess = () => console.log("Added new record!");
}
function deleteRecords(task) {
db
.transaction("records", "readwrite")
.objectStore("records")
.index("task")
.openCursor(IDBKeyRange.only(task)).onsuccess = (ev) => {
let cursor = ev.target.result;
if (cursor) {
cursor.delete();
cursor.continue();
}
};
}
function deleteRecord(d) {
db.transaction("records", "readwrite").objectStore("records").delete(d);
}
function saveTasks() {
localStorage.setItem("pomo-tasks", JSON.stringify(tasks));
}
function focusEnd(t) {
let minutes = Math.round(t / 60);
if (minutes <= 0) return;
if (tasks.includes(selectedTask)) {
saveRecord({
t: minutes,
d: Date.now(),
n: selectedTask,
});
}
}
document.getElementById("create-backup").addEventListener("click", () => {
let tr = db.transaction("records", "readonly").objectStore("records").index("task").getAll();
tr.onsuccess = () => {
let res = tr.result;
let blob = new Blob([JSON.stringify(res)], { type: "application/json" });
let url = URL.createObjectURL(blob);
let link = document.createElement("a");
link.href = url;
link.download = "tomodorobackup.json";
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
};
});
document.getElementById("backup-restore").addEventListener("change", function () {
let files = this.files;
if (files.length !== 0) {
let file = files[0];
file.text().then((res) => {
try {
let dbBackup = JSON.parse(res);
let rec = dbBackup.map((r) => {
if (!tasks.includes(r.n)) {
tasks.push(r.n);
createTaskEl(r.n);
if (!tasks.includes(selectedTask)) {
selectedTask = r.n;
taskSelect.value = r.n;
}
}
return { t: r.t, d: r.d, n: r.n };
});
saveTasks();
noTaskManager();
console.log(rec, tasks);
let tr = db.transaction("records", "readwrite");
tr.oncomplete = () => alert("Backup restored successfully!");
let objstore = tr.objectStore("records");
rec.forEach((r) => objstore.add(r));
} catch (error) {
console.log(error);
alert("An error occured! Make sure that you are restoring a valid backup file.");
}
});
}
});
let allCheckbox = document.getElementById("all");
let pieCardContainer = document.getElementById("pie-card-container");
let timeSpentChart = document.getElementById("timespent");
let timeSixHourlyChart = document.getElementById("timesixhourly");
let timeDailyChart = document.getElementById("timedaily");
let timeMonthlyChart = document.getElementById("timemonthly");
let timeYearlyChart = document.getElementById("timeyearly");
statTimeSelect.addEventListener("change", () => {
localStorage.setItem("pomo-stat-period", statTimeSelect.value);
loadStatistics();
});
let taskBars = {};
let pieCards = {};
function createTaskEl(task) {
filteredTasks.add(task);
let op = document.createElement("option");
op.value = op.innerText = task;
taskSelect.appendChild(op);
let tel = document.createElement("div");
tel.className = "task";
let tname = document.createElement("div");
tname.className = "task-name";
tname.innerText = task;
tel.appendChild(tname);
let chip = document.createElement("label");
chip.className = "task-chip";
let chipCheckbox = document.createElement("input");
chipCheckbox.className = "task-checkbox";
chipCheckbox.type = "checkbox";
chipCheckbox.defaultChecked = true;
let namespan = document.createElement("span");
namespan.className = "chip-task-name";
namespan.innerText = task;
chip.append(chipCheckbox, namespan);
filterContainer.appendChild(chip);
taskBars[task] = barGenerator(task);
timeSpentChart.appendChild(taskBars[task]);
pieCards[task] = pieCardGenerator(task);
pieCardContainer.appendChild(pieCards[task]);
chipCheckbox.addEventListener("change", function () {
if (this.checked) {
filteredTasks.add(task);
taskBars[task].style.display = "flex";
pieCards[task].style.display = "block";
if (filteredTasks.size === tasks.length) allCheckbox.checked = true;
} else {
filteredTasks.delete(task);
taskBars[task].style.display = "none";
pieCards[task].style.display = "none";
if (filteredTasks.size < tasks.length) allCheckbox.checked = false;
}
loadStatistics();
});
let tdel = document.createElement("button");
tdel.className = "task-delete-btn crossbtn";
tdel.title = "Delete this task";
tdel.addEventListener("click", () => {
let p = confirm(
'Are you sure you want to delete the task "' +
task +
'"? All the data related to this task will be deleted.'
);
if (!p) return;
tasks.splice(tasks.indexOf(task), 1);
op.remove();
tel.remove();
chip.remove();
filteredTasks.delete(task);
if (filteredTasks.size === 0) {
allCheckbox.checked = false;
}
if (filteredTasks.size === tasks.length) {
allCheckbox.checked = true;
}
taskBars[task].remove();
delete taskBars[task];
pieCards[task].remove();
delete pieCards[task];
if (selectedTask === task) {
if (tasks.length > 0) {
selectedTask = tasks[0];
taskSelect.value = selectedTask;
}
}
noTaskManager();
deleteRecords(task);
saveTasks();
});
tel.appendChild(tdel);
taskContainer.appendChild(tel);
}
let noTaskTitle = document.getElementById("no-task-title");
function noTaskManager() {
if (tasks.length === 0) {
taskSelect.style.display = "none";
noTaskTitle.style.display = "block";
} else {
taskSelect.style.display = "initial";
noTaskTitle.style.display = "none";
}
}
async function taskInit() {
await loadTasks();
taskSelect.innerHTML = "";
noTaskManager();
tasks.forEach((task) => createTaskEl(task));
allCheckbox.addEventListener("change", function () {
if (this.checked) {
document.querySelectorAll(".task-checkbox").forEach((el) => (el.checked = true));
tasks.forEach((task) => {
filteredTasks.add(task);
taskBars[task].style.display = "flex";
pieCards[task].style.display = "block";
});
} else {
document.querySelectorAll(".task-checkbox").forEach((el) => (el.checked = false));
tasks.forEach((task) => {
filteredTasks.delete(task);
taskBars[task].style.display = "none";
pieCards[task].style.display = "none";
});
}
loadStatistics();
});
}
taskInit();
document.getElementById("newtask").addEventListener("submit", function (ev) {
ev.preventDefault();
let formdata = new FormData(this);
let tname = formdata.get("taskname").trim();
if (tname === "") {
alert("Please Enter a Valid Name!");
this.reset();
return;
}
if (tasks.includes(tname)) {
alert("Task already exists!");
return;
}
tasks.push(tname);
createTaskEl(tname);
if (!tasks.includes(selectedTask)) {
selectedTask = tname;
taskSelect.value = tname;
}
saveTasks();
noTaskManager();
this.reset();
});
taskSelect.addEventListener("change", function () {
selectedTask = this.value;
localStorage.setItem("pomo-selected-task", selectedTask);
});
let format = new Intl.DateTimeFormat(undefined, {
dateStyle: "full",
timeStyle: "short",
});
function pieCardGenerator(task) {
let el = document.createElement("div");
el.className = "pie-card";
let pieName = document.createElement("div");
pieName.className = "pie-card-name";
pieName.innerText = task;
el.appendChild(pieName);
let timeHolder = document.createElement("div");
let text = document.createElement("span");
text.innerText = "Time Spent: ";
let timeSpan = document.createElement("span");
timeSpan.className = "pie-card-time";
let ee = document.createElement("div");
ee.className = "pie-card-time-div";
let totaltime = document.createElement("span");
totaltime.className = "pie-card-time-text";
ee.append(document.createTextNode("("), totaltime, document.createTextNode(")"));
let roundno = document.createElement("div");
roundno.className = "pie-card-rounds";
let roundnospan = document.createElement("span");
roundnospan.className = "pie-card-rounds-span";
roundno.append(document.createTextNode("Number of Rounds: "), roundnospan);
timeHolder.append(text, timeSpan, ee, roundno);
el.appendChild(timeHolder);
return el;
}
function barGenerator(task) {
let taskBarContainer = document.createElement("div");
taskBarContainer.className = "task-bar-container";
let legend = document.createElement("div");
legend.className = "legend";
legend.innerText = task;
let barContainer = document.createElement("div");
barContainer.className = "bar-container";
let bar = document.createElement("div");
bar.className = "bar";
barContainer.appendChild(bar);
let tooltip = document.createElement("div");
tooltip.className = "tooltip";
tooltip.innerText = task;
let valueEl = document.createElement("div");
valueEl.className = "stat-value";
bar.append(tooltip, valueEl);
taskBarContainer.append(legend, barContainer);
taskBarContainer.dataset.task = task;
return taskBarContainer;
}
function roundEntryGen(entry) {
let roundEntry = document.createElement("div");
roundEntry.className = "round-entry";
let roundEntryName = document.createElement("div");
roundEntryName.className = "round-entry-name";
roundEntryName.innerText = entry.n;
let roundEntryDuration = document.createElement("round-entry-duration");
roundEntryDuration.className = "round-entry-duration";
roundEntryDuration.innerText = hmstrFull(entry.t);
let roundEntryTime = document.createElement("div");
roundEntryTime.className = "round-entry-time";
roundEntryTime.innerText = format.format(entry.d);
let entryDelete = document.createElement("button");
entryDelete.className = "entry-delete";
entryDelete.innerText = "Delete";
entryDelete.addEventListener("click", () => {
let p = confirm("Are you sure you want to delete this record? This cannot be undone.");
if (!p) return;
deleteRecord(entry.d);
roundEntry.remove();
loadStatistics(false);
});
roundEntry.append(roundEntryName, roundEntryDuration, roundEntryTime, entryDelete);
return roundEntry;
}
let hourlyNames = ["0-6", "6-12", "12-18", "18-24"];
let hourlyFullNames = ["00:00 - 00:06", "06:00 - 12:00", "12:00 - 18:00", "18:00 - 24:00"];
let hourlyBars = hourlyNames.map((d) => document.getElementById("hourly-" + d));
let dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
let dayBars = dayNames.map((d) => document.getElementById("day-" + d));
let monthNames = [
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december",
];
let monthBars = monthNames.map((d) => document.getElementById("month-" + d));
let pieSVG = document.querySelector("#pie svg");
let statSummaryTotal = document.getElementById("stat-summary-total");
let statSummaryRounds = document.getElementById("stat-summary-rounds");
let statSummaryAverage = document.getElementById("stat-summary-average");
let statSummaryShortest = document.getElementById("stat-summary-shortest");
let statSummaryLongest = document.getElementById("stat-summary-longest");
let remarkHourly = document.getElementById("remark-hourly");
let remarkMonthly = document.getElementById("remark-monthly");
let remarkDaily = document.getElementById("remark-daily");
let roundEntries = document.getElementById("round-entries");
async function loadStatistics(updateEntryCards = true) {
let timeValue = statTimeSelect.value;
let rec = await getRecords();
if (!(timeValue === "all")) {
let tt = Date.now() - parseInt(timeValue) * 24 * 60 * 60 * 1000;
rec = rec.filter((r) => r.d >= tt && filteredTasks.has(r.n));
}
let charts = [];
let maxvalue = 0;
let minRoundValue = 0;
let maxRoundValue = 0;
let totalValue = 0;
let hourlyTimes = new Array(4).fill(0);
let dayTimes = new Array(7).fill(0);
let monthTimes = new Array(12).fill(0);
for (let task of filteredTasks) {
let chart = {
t: 0,
task: task,
n: 0,
};
rec.filter((r) => r.n === task).forEach((r) => {
chart.t += r.t;
totalValue += r.t;
let d = new Date(r.d);
hourlyTimes[Math.floor(d.getHours() / 6)] += r.t;
dayTimes[d.getDay()] += r.t;
monthTimes[d.getMonth()] += r.t;
chart.n++;
if (minRoundValue === 0) {
minRoundValue = r.t;
} else {
minRoundValue = minRoundValue > r.t ? r.t : minRoundValue;
}
maxRoundValue = maxRoundValue < r.t ? r.t : maxRoundValue;
});
maxvalue = maxvalue < chart.t ? chart.t : maxvalue;
charts.push(chart);
}
statSummaryTotal.innerText = hmstrFull(totalValue);
statSummaryRounds.innerText = rec.length;
statSummaryAverage.innerText = hmstrFull(totalValue / (rec.length === 0 ? 1 : rec.length));
statSummaryShortest.innerText = hmstrFull(minRoundValue);
statSummaryLongest.innerText = hmstrFull(maxRoundValue);
if (totalValue === 0) {
remarkDaily.style.display = remarkHourly.style.display = remarkMonthly.style.display = "none";
} else {
remarkDaily.style.display = remarkHourly.style.display = remarkMonthly.style.display = "block";
let maxH = 1;
let maxHV = 0;
hourlyTimes.forEach((v, i) => {
if (v > maxHV) {
maxHV = v;
maxH = i;
}
});
remarkHourly.querySelector(".remark-value").innerText = hourlyFullNames[maxH];
let maxD = 1;
let maxDV = 0;
dayTimes.forEach((v, i) => {
if (v > maxDV) {
maxDV = v;
maxD = i;
}
});
remarkDaily.querySelector(".remark-value").innerText = dayNames[maxD] + "s";
let maxM = 1;
let maxMV = 0;
monthTimes.forEach((v, i) => {
if (v > maxMV) {
maxMV = v;
maxM = i;
}
});
remarkMonthly.querySelector(".remark-value").innerText = monthNames[maxM];
}
pieSVG.innerHTML = "";
let sumOfPrev = 0;
charts
.sort((a, b) => b.t - a.t)
.forEach((chart, i) => {
taskBars[chart.task].querySelector(".stat-value").innerText = hmstr(chart.t);
taskBars[chart.task].querySelector(".bar").style.width = (chart.t / maxvalue) * 100 + "%";
taskBars[chart.task].style.order = i + 1;
pieCards[chart.task].style.order = i + 1;
pieCards[chart.task].querySelector(".pie-card-time").innerText = `${(
(chart.t / (totalValue === 0 ? 1 : totalValue)) *
100
).toFixed(2)}%`;
pieCards[chart.task].querySelector(".pie-card-time-text").innerText = hmstrFull(chart.t);
pieCards[chart.task].querySelector(".pie-card-rounds-span").innerText = chart.n;
let pie = document.createElementNS("http://www.w3.org/2000/svg", "path");
let a = (sumOfPrev / totalValue) * Math.PI * 2;
let p1 = [60 + Math.sin(a) * 50, 60 - Math.cos(a) * 50];
let b = ((sumOfPrev + chart.t) / totalValue) * Math.PI * 2;
let p2 = [60 + Math.sin(b) * 50, 60 - Math.cos(b) * 50];
let normal = (a + b) / 2;
if (totalValue === chart.t) {
pie.setAttribute("d", `M60,10 A50 50 0 1 1 60 110 A50 50 0 1 1 60 10 z`);