-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathschedule.js
More file actions
1235 lines (1166 loc) · 42 KB
/
Copy pathschedule.js
File metadata and controls
1235 lines (1166 loc) · 42 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
const dialogs = document.querySelectorAll("dialog");
for (const dialog of dialogs) {
if (typeof dialog.showModal !== "function" && window.dialogPolyfill) {
dialogPolyfill.registerDialog(dialog);
}
}
function toUnix(date, time) {
return Math.floor(new Date(`${date}T${time}`).getTime() / 1000);
}
let schoolName = localStorage.getItem("schoolName");
let authorizationCode = localStorage.getItem("authorizationCode");
let accessToken = localStorage.getItem("access_token");
let userType = localStorage.getItem("userType");
let lastLessonEndMin;
let day = 0;
const timeline = document.createElement("div");
timeline.classList.add("timeline");
if (!schoolName && !accessToken) {
show("welcomeScreen", "Zermelo koppelen", "hideBack");
document
.querySelector("#dialog #closeBtn")
.setAttribute("onclick", "resetAfterWelcomeScreen()");
document.querySelector("#dialog").classList.add("welcome");
document.querySelector("#dialog").setAttribute("closedby", "none");
document.querySelector("#dialog #closeBtn").removeAttribute("command");
document.querySelector("#dialog #closeBtn").removeAttribute("commandfor");
document.querySelector("#dialog #closeBtn span").innerHTML = "Volgende";
document.getElementById("dialog").showModal();
}
setInterval(() => {
fetchSchedule(window.year, window.week);
}, 90000); // 1.5 minuut
function resetAfterWelcomeScreen() {
show("zermelo", "Zermelo koppelen");
document
.querySelector("#dialog #closeBtn")
.setAttribute("onclick", "show('submenus', 'Instellingen')");
}
async function fetchToken() {
try {
const url = `https://${schoolName}.zportal.nl/api/oauth/token?grant_type=authorization_code&code=${authorizationCode}&fields`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (!response.ok) {
errorMessage(data.response.message);
}
localStorage.setItem("access_token", data.access_token);
accessToken = localStorage.getItem("access_token");
} catch (error) {
console.error("Error fetching access token:", error.message);
} finally {
userInfo();
}
}
async function announcements() {
if (
!schoolName ||
!authorizationCode ||
localStorage.getItem("mededelingenAan") != "true"
)
return;
const url = `https://${schoolName}.zportal.nl/api/announcements?current=true&user=~me&fields=start,end,title,text`;
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
if (!response.ok) {
throw new Error(`Error ${response.status}: ${response.statusText}`);
}
const data = await response.json();
localStorage.setItem("announcements", JSON.stringify(data));
renderAnnouncements();
}
announcements();
async function userInfo() {
const response = await fetch(
`https://${schoolName}.zportal.nl/api/users/~me?fields=code,isEmployee,schoolInSchoolYears`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const data = await response.json();
let userType1 = "student";
if (data.response.data[0] && data.response.data[0].isEmployee === true) {
userType1 = "teacher";
} else if (!data.response.data[0]) {
console.error(data);
errorMessage(data.response.message);
} else {
schoolInSchoolYears(data.response.data[0].schoolInSchoolYears);
}
localStorage.setItem("userType", userType1);
userType = localStorage.getItem("userType");
fetchSchedule();
}
async function schoolInSchoolYears(years) {
const response = await fetch(
`https://${schoolName}.zportal.nl/api/schoolsinschoolyears?fields=id,year`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const data = await response.json();
const schoolYears = data.response.data;
const current = schoolYears.reduce(
(latest, item) =>
years.includes(item.id) && (!latest || item.year > latest.year)
? item
: latest,
null
);
localStorage.setItem("schoolInSchoolYear", current.id);
fetchTeachers();
}
async function fetchTeachers() {
const schoolYear = Number(localStorage.getItem("schoolInSchoolYear"));
let teacherTranslations = {};
return fetch(
`https://${schoolName}.zportal.nl/api/users?archived=false&schoolInSchoolYear=${schoolYear}&fields=code%2ClastName%2Cprefix&isEmployee=true`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
)
.then((r) => r.json())
.then((result) => {
let teachers = result.response.data;
teachers.forEach((teacher) => {
let prefix = teacher.prefix;
let lastName = teacher.lastName;
// For my school the format {2 letters last name}{2 letters first name} is used which can be used to find the initial letter of the first name, possibly other schools??
if (schoolName == "csvincentvangogh" && teacher.code.length == 4)
prefix = `${teacher.code.split("")[2].toUpperCase()}.${prefix ? " " + prefix : ""}`;
if (!lastName) {
return;
}
let commaIndex = lastName.indexOf(",");
if (commaIndex != -1) {
lastName = lastName.substring(0, commaIndex);
}
let fullName = (prefix ? prefix + " " : "") + lastName;
teacherTranslations[teacher.code] = fullName;
});
localStorage.setItem("teachers", JSON.stringify(teacherTranslations));
});
}
const inputs = document.querySelectorAll("input");
inputs.forEach((input) => {
if (localStorage.getItem(input.id)) {
if (input.type == "checkbox") {
if (localStorage.getItem(input.id) == "true")
input.checked = localStorage.getItem(input.id);
} else {
input.value = localStorage.getItem(input.id);
}
}
});
let mono = "";
if (!localStorage.getItem("theme")) {
localStorage.setItem("theme", "blue");
}
if (localStorage.getItem("mono") == "true") {
mono = " monochrome";
}
document
.querySelector("body")
.setAttribute("data-theme", localStorage.getItem("theme") + mono);
const u = () =>
document
.querySelector("meta[name=theme-color]")
.setAttribute(
"content",
getComputedStyle(document.body)
.getPropertyValue("--primary-background")
.trim()
);
u();
new MutationObserver(u).observe(document.body, {
attributes: 1,
attributeFilter: ["data-theme"],
});
// Save theme when changed
for (const radio of document.querySelectorAll("input[name='color']")) {
radio.checked = radio.value === localStorage.getItem("theme");
radio.addEventListener("change", (e) => {
if (e.target.checked) {
if (localStorage.getItem("mono") != "true") {
mono = "";
} else {
mono = " monochrome";
}
document
.querySelector("body")
.setAttribute("data-theme", e.target.value + mono);
localStorage.setItem("theme", e.target.value);
}
});
}
function save() {
inputs.forEach((input) => {
if (input.id && input.value) {
if (input.type == "radio") {
if (input.checked) {
localStorage.setItem("dayView", input.value);
}
} else if (input.value != "on") {
localStorage.setItem(input.id, input.value);
schoolName = localStorage.getItem("schoolName");
authorizationCode = localStorage.getItem("authorizationCode");
} else if (input.type == "checkbox") {
localStorage.setItem(input.id, input.checked);
}
} else if (input.id) {
localStorage.setItem(input.id, "");
}
});
}
function closeDialog() {
save();
if (window.innerWidth < 570) {
document.getElementById("submenus").style.display = "block";
document.querySelector("#content.container").style.display = "none";
}
if (localStorage.getItem("mono") == "true") {
if (
!document
.querySelector("body")
.getAttribute("data-theme")
.includes("monochrome")
) {
document
.querySelector("body")
.setAttribute(
"data-theme",
document.querySelector("body").getAttribute("data-theme") +
" monochrome"
);
}
} else if (
document
.querySelector("body")
.getAttribute("data-theme")
.includes("monochrome")
) {
document
.querySelector("body")
.setAttribute(
"data-theme",
document
.querySelector("body")
.getAttribute("data-theme")
.replace(" monochrome", "")
);
}
if (
localStorage.getItem("volVaknaam") == "true" &&
!localStorage.getItem("subjects")
) {
fetchFullSubjectNames();
}
if (
localStorage.getItem("viewOption") &&
localStorage.getItem("dag") != "false"
) {
document.getElementById("dayBtn").click();
}
fetchSchedule(window.year, window.week);
}
// Nodig voor correct sluiten dialoog
document.getElementById("dialog").addEventListener("close", () => {
closeDialog();
});
function viewTrans(func) {
if (!document.startViewTransition || window.innerWidth < 570) {
func();
return;
}
document.startViewTransition(() => {
func();
});
}
let prevId = null;
let prevTitle = null;
function show(id, title, hideBack) {
if (id == "back") {
if (window.innerWidth < 570) {
document.getElementById("submenus").style.display = "block";
document.querySelector("#content.container").style.display = "none";
} else if (prevId) {
show(prevId, prevTitle);
}
return;
}
if (!hideBack) {
prevId = document.querySelector(".selectedSubmenu").classList[0];
prevTitle = document
.querySelector(".selectedSubmenu")
.getAttribute("data-title");
}
document.getElementById("submenus").style.display = "";
document.querySelector("#content.container").style.display = "";
if (document.querySelector(`.${id}`)) {
const current = document.querySelector(".selectedSubmenu");
if (current) current.classList.remove("selectedSubmenu");
document.querySelector(`.${id}`).classList.add("selectedSubmenu");
}
const content = document.querySelector(".container");
const children = content.querySelectorAll("div");
viewTrans(() => {
children.forEach((div) => {
if (div.id === id) {
div.style.display = "block";
} else {
div.removeAttribute("style");
}
});
if (id !== "submenus" && !hideBack) {
document.querySelector("#dialog #content h2").innerHTML =
'<button style="all: unset" onclick="show(`back`)"><p height="24px" width="24px" class="back">arrow_back</p></button>' +
title;
} else {
document.querySelector("#dialog #content h2").innerHTML = title;
if (!hideBack) {
document.querySelector("#dialog").classList.remove("welcome");
document.querySelector("#dialog").setAttribute("closedby", "any");
document.querySelector("#dialog #closeBtn span").innerHTML = "Sluiten";
document
.querySelector("#dialog #closeBtn")
.setAttribute("command", "close");
document
.querySelector("#dialog #closeBtn")
.setAttribute("commandfor", "dialog");
}
}
});
}
function errorMessage(e) {
document.querySelector("#error p").innerText = e;
document.getElementById("error").showModal();
}
function renderAnnouncements() {
const content = document.querySelector("#announcements #content");
content.innerHTML = "";
const stored = localStorage.getItem("announcements");
if (!stored) {
content.textContent = "Geen mededelingen gevonden.";
return;
}
const data = JSON.parse(stored);
const announcements = data.response?.data;
if (!Array.isArray(announcements) || announcements.length === 0) {
content.textContent = "Geen actuele mededelingen.";
return;
}
announcements.forEach((item) => {
const article = document.createElement("div");
article.classList.add("announcement");
article.innerHTML = `
<strong>${item.title || "Mededeling"}</strong>
<small>${
item.start
? new Date(item.start * 1000).toLocaleString([], {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})
: ""
}</small>
<p class="change">${item.text || ""}</p>
`;
content.appendChild(article);
});
}
function showAnnouncements() {
const button = document.getElementById("announcementsButton");
const checkbox = document.getElementById("mededelingenAan");
if (!button || !checkbox) return;
const update = () => {
const enabled = localStorage.getItem("mededelingenAan") === "true";
button.hidden = !enabled;
};
checkbox.checked = localStorage.getItem("mededelingenAan") === "true";
update();
checkbox.addEventListener("change", () => {
localStorage.setItem("mededelingenAan", checkbox.checked);
update();
});
}
showAnnouncements();
function showAddAppointment() {
const button = document.getElementById("addCustomAppointment");
const checkbox = document.getElementById("addAppointmentOn");
if (!button || !checkbox) return;
const update = () => {
const enabled = localStorage.getItem("addAppointmentOn") === "true";
button.style.display = enabled ? "flex" : "none";
};
checkbox.checked = localStorage.getItem("addAppointmentOn") === "true";
update();
checkbox.addEventListener("change", () => {
localStorage.setItem("addAppointmentOn", checkbox.checked);
update();
});
}
showAddAppointment();
Date.prototype.getWeek = function () {
const date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7));
const week1 = new Date(date.getFullYear(), 0, 4);
return (
1 +
Math.round(
((date.getTime() - week1.getTime()) / 86400000 -
3 +
((week1.getDay() + 6) % 7)) /
7
)
);
};
window.week = new Date().getWeek();
window.year = new Date().getFullYear();
const currentDay = new Date().getDay();
if (currentDay == 6 || currentDay == 0) {
window.week = window.week + 1;
}
if (window.week == 53) {
window.week = 1;
}
if (week === 1 && new Date().getMonth() === 11) year++; // Week 1 can start in december
fetchSchedule(window.year, window.week, "firstLoad");
function getYearWeekFromDate(dateStr) {
const d = new Date(dateStr);
return {
year: d.getFullYear(),
week: d.getWeek(),
};
}
async function fetchSchedule(year, week, isFirstLoad) {
if (!year) year = new Date().getFullYear();
if (!week) week = new Date().getWeek();
window.week = week;
window.year = year;
document.getElementById("weekInput").value = week;
if (week < 10) week = `0${week}`; // Voeg een voorloopnul toe aan enkelcijferige weken
if (!schoolName || !authorizationCode) return;
if (!accessToken) {
fetchToken();
return;
}
const response = await fetch(
`https://${schoolName}.zportal.nl/api/liveschedule?${userType}=~me&week=${year}${week}&fields=week,user,appointments,replacements,status`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
const data = await response.json();
if (!response.ok) {
errorMessage(data.response.message);
}
const appointments = data.response.data[0].appointments;
const schedule = document.getElementById("schedule");
schedule.innerHTML = "";
const grouped = {};
// Aangepaste afspraken
const customData = JSON.parse(
localStorage.getItem("customAppointments") || "[]"
);
customData.forEach((item) => {
const { year, week } = getYearWeekFromDate(item.date);
if (year !== window.year || week !== window.week) return;
appointments.push({
appointmentInstance: item.id,
start: toUnix(item.date, item.start),
end: toUnix(item.date, item.end),
subjects: [item.title],
appointmentType: "custom",
locations: item.locations || [],
teachers: item.teachers || [],
groups: item.groups || [],
cancelled: item.cancelled === true,
status: item.status || "",
repeat: item.repeat || "none",
actions: [],
type: "appointment",
content: item.content || "",
});
});
// Always show Monday to Friday
for (let i = 0; i < 5; i++) {
const d = new Date(year, 0, 1 + (week - 1) * 7);
d.setDate(d.getDate() - ((d.getDay() + 6) % 7) + i);
const key = d.toLocaleDateString([], {
weekday: "long",
month: "long",
day: "numeric",
});
grouped[key] = { date: formatDateLabel(d), items: [] };
}
appointments.forEach((a) => {
let dateFull = new Date(a.start * 1000).toLocaleDateString([], {
weekday: "long",
month: "long",
day: "numeric",
});
if (grouped[dateFull]) grouped[dateFull].items.push(a);
});
const fmt = (ts, regex) =>
new Date(ts * 1000)
.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
.replace(regex || /^0+/, "");
const hoursToMinutes = (time) =>
Number.parseInt(time.split(":")[0]) * 60 +
Number.parseInt(time.split(":")[1]);
for (const [dateFull, { date, items }] of Object.entries(grouped)) {
const dayDiv = document.createElement("div");
dayDiv.classList.add("day");
const currentDate = new Date().toLocaleDateString([], {
weekday: "long",
month: "long",
day: "numeric",
});
let svg = "";
if (currentDate == dateFull) {
svg = `<svg viewBox="0 0 380 380" fill="none" xmlns="http://www.w3.org/2000/svg" width="14" height="14" id="soft_burst">
<path d="M175.147 33.1508C181.983 22.2831 198.017 22.2831 204.853 33.1508L221.238 59.2009C225.731 66.3458 234.797 69.2506 242.692 66.0751L271.475 54.4972C283.482 49.6671 296.455 58.9613 295.507 71.7154L293.235 102.288C292.612 110.673 298.215 118.278 306.494 120.284L336.681 127.601C349.275 130.653 354.23 145.692 345.861 155.461L325.8 178.877C320.298 185.3 320.298 194.7 325.8 201.123L345.861 224.539C354.23 234.308 349.275 249.347 336.681 252.399L306.494 259.716C298.215 261.722 292.612 269.327 293.235 277.712L295.507 308.285C296.455 321.039 283.482 330.333 271.475 325.503L242.692 313.925C234.797 310.749 225.731 313.654 221.238 320.799L204.853 346.849C198.017 357.717 181.983 357.717 175.147 346.849L158.762 320.799C154.269 313.654 145.203 310.749 137.308 313.925L108.525 325.503C96.5177 330.333 83.5454 321.039 84.4931 308.285L86.7649 277.712C87.388 269.327 81.785 261.722 73.5056 259.716L43.3186 252.399C30.7252 249.347 25.7702 234.308 34.1391 224.539L54.1997 201.123C59.7018 194.7 59.7018 185.3 54.1997 178.877L34.1391 155.461C25.7702 145.692 30.7252 130.653 43.3186 127.601L73.5056 120.284C81.785 118.278 87.388 110.673 86.7649 102.288L84.4931 71.7154C83.5454 58.9613 96.5177 49.6671 108.525 54.4972L137.308 66.0751C145.203 69.2506 154.269 66.3458 158.762 59.201L175.147 33.1508Z"></path>
</svg> `;
}
dayDiv.innerHTML = `<div><strong class="date">${svg}<span>${date}</span></strong></div><section><div class="les" style="--height: 2.01px; opacity: 0; pointer-events: none;"></div></section>`;
const contentDiv = document.createElement("div");
items.sort((a, b) => a.start - b.start);
let section = [],
lastEnd = null;
const flush = () => {
if (!section.length) return;
contentDiv.innerHTML += `${section
.map((a, i) => {
const firstLesson = i == 0;
const lastLesson = i == section.length - 1;
let marginTop;
let sectionBeginning = "";
let height;
if (a.startTimeSlot != a.endTimeSlot)
a.startTimeSlot += `-${a.endTimeSlot}`;
if (!a.startTimeSlot) a.startTimeSlot = "";
const start = fmt(a.start),
end = fmt(a.end);
const startMin = hoursToMinutes(start);
const endMin = hoursToMinutes(end);
let startTime = hoursToMinutes(
localStorage.getItem("startTime") || "08:15"
);
a.teachers.sort();
if (firstLesson) {
if (!lastLessonEndMin || startMin - lastLessonEndMin < 0) {
if (startMin < startTime || !localStorage.getItem("startTime")) {
localStorage.setItem("startTime", fmt(a.start, "noRegex"));
}
startTime = hoursToMinutes(
localStorage.getItem("startTime") || "08:15"
);
lastLessonEndMin = startTime;
}
sectionBeginning = "<section>";
}
if (lastLesson) {
lastLessonEndMin = endMin;
}
let cancelled = "";
if (!a.content) {
a.content = "";
}
let warning = a.changeDescription + a.schedulerRemark + a.content;
let warningSymbol = warning
? `<svg width="24" height="24" fill="none" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" id="warningIcon" data-tooltip="${warning}"><path d="M10.909 2.782a2.25 2.25 0 0 1 2.975.74l.083.138 7.759 14.009a2.25 2.25 0 0 1-1.814 3.334l-.154.006H4.242A2.25 2.25 0 0 1 2.2 17.812l.072-.143L10.03 3.66a2.25 2.25 0 0 1 .879-.878ZM12 16.002a.999.999 0 1 0 0 1.997.999.999 0 0 0 0-1.997Zm-.002-8.004a1 1 0 0 0-.993.884L11 8.998 11 14l.007.117a1 1 0 0 0 1.987 0l.006-.117L13 8.998l-.007-.117a1 1 0 0 0-.994-.883Z"></path></svg>`
: "";
if (!a.cancelled && (a.schedulerRemark || a.content)) {
warningSymbol = warning
? `<span id="icon" data-tooltip="${warning}">info</span>`
: "";
}
if (
!a.appointmentInstance &&
a.actions[0] &&
!a.actions[0].appointment.plannedAttendance
) {
// Check used by Zermelo to see if unenrolled from lesson
// Lesson info in a.actions[0].appointment instead of a
a = a.actions[0].appointment;
cancelled = "notEnrolled";
warning = "Afgemeld";
warningSymbol = warning
? `<span id="icon" data-tooltip="${warning}">block</span>`
: "";
} else if (a.cancelled == true) {
cancelled = "cancelled";
}
if (a.appointmentType == "conflict") {
a.subjects = a.actions.flatMap(
(action) => action.appointment.subjects
);
a.locations = a.actions.flatMap(
(action) => action.appointment.locations
);
a.teachers = a.actions.flatMap(
(action) => action.appointment.teachers
);
a.groups = a.actions.flatMap((action) => action.appointment.groups);
}
const subjAbbrev = a.subjects;
if (localStorage.getItem("volVaknaam") === "true") {
const fullSubjectNames = JSON.parse(
localStorage.getItem("subjects")
);
const matches = fullSubjectNames
.filter((item) => a.subjects.includes(item.code))
.map((item) => item.name);
if (matches.length) a.subjects = matches;
} else if (localStorage.getItem("afkortingHl") === "true") {
a.subjects = a.subjects.map((subject) => subject.toUpperCase());
}
if (localStorage.getItem("afkortingHl") === "true") {
a.teachers = a.teachers.map((teacher) => teacher.toUpperCase());
}
a.groups.forEach((group, index) => {
if (group.startsWith(localStorage.getItem("prefix-group"))) {
a.groups[index] = group.slice(
localStorage.getItem("prefix-group").length
); //groups[index] instead of group is necessary to actually change the value of group
}
});
a.locations.forEach((loc, index) => {
if (loc.startsWith(localStorage.getItem("prefix-location"))) {
a.locations[index] = loc.slice(
localStorage.getItem("prefix-location").length
);
}
});
let styles = "";
let warningStyles = "";
marginTop = ((startMin - startTime) * 1.1) / 16;
height = ((endMin - startMin) * 1.1) / 16;
if (height < 3) {
styles = "line-height: 1.1;";
warningStyles = "bottom: 2px";
}
return `${sectionBeginning}<div id="${
a.appointmentInstance + "div"
}" class="les ${cancelled} ${
a.appointmentType
}" style="--height: ${height}rem; --margin: ${marginTop}rem;${styles}"><button id="${
a.appointmentInstance
}" class="innerSpan"
commandfor="info" command="show-modal" onclick='showLessonInfo(this, ${JSON.stringify(
a
)})'><strong class="subject">${
a.subjects
}</strong><strong class="subjAbbrev">${subjAbbrev}</strong><strong class="lesuur">${
a.startTimeSlot
}</strong><hr style="height: 0;"><p class="lestijden" style="margin-right: 6px">${start}<span class="longExtraExtra">-${end}</span></p><p>${
a.locations
}<span class="teachersAndGroups">${
a.teachers.length != 0 ? ` (${a.teachers.join(", ")})` : ""
}<span class="groups">${
localStorage.getItem("klas") == "true" ? ` ${a.groups}` : ""
}</span></span></p></button><span class="warning" style="${warningStyles}">${warningSymbol}</span></div>`;
})
.join("")}</section>`;
dayDiv.appendChild(contentDiv);
section = [];
};
for (const a of items) {
if (lastEnd !== null && a.start !== lastEnd) flush();
section.push(a);
lastEnd = a.end;
}
flush();
schedule.appendChild(dayDiv);
}
// Vakanties
if (!appointments[0]) {
const d = new Date(year, 0, 1 + (week - 1) * 7);
d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
const month = d.getMonth() + 1;
const holidays = {
10: ["temp_preferences_eco", "Herfstvakantie!"],
12: ["snowflake", "Kerstvakantie!"],
2: ["cruelty_free", "Voorjaarsvakantie!"],
4: ["deceased", "Meivakantie!"],
7: ["beach_access", "Zomervakantie!"],
8: ["beach_access", "Zomervakantie!"],
};
if (holidays[month]) {
const [icon, label] = holidays[month];
schedule.innerHTML = `<h2 class="date"><span class="icon">${icon}</span>${label}</h2>`;
}
}
if (isFirstLoad === "firstLoad") {
day = new Date().getDay() - 1;
if (day === 5 || day === -1) day = 0;
document
.querySelector("body")
.scrollTo({ left: window.innerWidth * day, behavior: "instant" });
}
const startMin = hoursToMinutes(new Date().toLocaleTimeString());
const startTime = hoursToMinutes(
localStorage.getItem("startTime") || "08:15"
);
let marginTop = ((startMin - startTime) * 1.1) / 16;
timeline.style = `--top: ${marginTop}rem`;
document.getElementById("schedule").appendChild(timeline);
document.getElementById("schedule").style.opacity = "";
const tip = document.getElementById("tooltip");
function formatDateLabel(d) {
const weekday = d.toLocaleDateString([], { weekday: "long" });
const day = d.toLocaleDateString([], { day: "numeric" });
const month = d.toLocaleDateString([], { month: "long" });
// "maart" is an exception: use "mrt" abbreviation
if (month === "maart") {
return `${weekday.slice(0, 2)}<span class="long">${weekday.slice(2)}</span> ${day}<span class="longExtraExtraExtra"> m<span class="long">aa</span>rt</span>`;
}
return `${weekday.slice(0, 2)}<span class="long">${weekday.slice(2)}</span> ${day}<span class="longExtraExtraExtra"> ${month.slice(0, 3)}</span><span class="long">${month.slice(3)}</span>`;
}
function positionTip(btn) {
tip.textContent = btn.getAttribute("data-tooltip");
const rect = btn.getBoundingClientRect();
const tipRect = tip.getBoundingClientRect();
let top = rect.bottom + 2;
let left = rect.right - tipRect.width + 6;
if (top + tipRect.height > window.innerHeight)
top = rect.top - tipRect.height - 8;
if (left < 0) left = 8;
if (left + tipRect.width > window.innerWidth)
left = window.innerWidth - tipRect.width - 8;
tip.style.top = `${top}px`;
tip.style.left = `${left}px`;
}
document.querySelectorAll("[data-tooltip]").forEach((btn) => {
btn.addEventListener("mouseenter", () => {
positionTip(btn);
tip.setAttribute("data-show", "");
});
btn.addEventListener("mouseleave", () => tip.removeAttribute("data-show"));
});
let maxMinutes = -Infinity;
document.querySelectorAll(".lestijden .longExtraExtra").forEach((lestijd) => {
const endMin = hoursToMinutes(lestijd.innerHTML.slice(1));
if (endMin > maxMinutes) {
maxMinutes = endMin;
}
});
if (startMin > maxMinutes) {
timeline.style.display = "none";
} else {
timeline.style.display = "";
}
window.addEventListener("resize", () => {
if (tip.hasAttribute("data-show")) {
const active = document.querySelector("[data-tooltip]:hover");
if (active) positionTip(active);
}
});
}
async function fetchFullSubjectNames() {
const result = await fetch(
`https://${schoolName}.zportal.nl/api/subjectselectionsubjects?fields=code,name`,
{
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
}
).then((r) => r.json());
let subjects = result.response.data.map((subject) => {
let { name, code } = subject;
const capitalCount = (name.match(/[A-Z]/g) || []).length;
// Lowercase unless it ends in a consonant + "s" (e.g. Frans, Duits),
// contains "taal en ", is Latijn/English, or has multiple capitals
if (
!/[bdfghjklmnpqrtvwxyz]s$/i.test(name) &&
!name.includes("taal en ") &&
code !== "la" &&
code !== "eng" &&
capitalCount <= 1
) {
name = name.toLowerCase();
}
const overrides = {
ontw: "ontwerpen",
men: "mentorles",
nask: "NaSk",
cko: "Culturele en Kunstzinnige Oriëntatie",
pko: "Profiel Keuze Oriëntatie",
ch: "chemistry",
kvdbw: "Voeding en Beweging",
eio: "Europese en internationale oriëntatie",
bp: "begeleidingsprogramma",
cra: "creatieve activiteiten",
ph: "physics",
};
if (overrides[code]) name = overrides[code];
return { ...subject, name };
});
localStorage.setItem("subjects", JSON.stringify(subjects));
}
function clearUserData() {
localStorage.clear();
location.reload();
}
function switchDay(dir) {
let behavior = "smooth";
const days = document.querySelectorAll(".day");
let dayLength = days.length;
if (!document.getElementById("schedule").className.includes("dayEnabled")) {
dayLength = 1;
}
let week = window.week;
if (dir == "next") {
day++;
week++;
} else {
day--;
week--;
}
if (week > 52) {
week = 1;
window.year++;
} else if (week == 0) {
week = 52;
window.year--;
}
if (day == -1) {
day = 4;
behavior = "instant";
if (document.getElementById("schedule").classList.contains("dayEnabled")) {
document.getElementById("schedule").style.opacity = 0;
}
if (!document.startViewTransition) {
fetchSchedule(window.year, week);
} else {
document.startViewTransition(() => fetchSchedule(window.year, week));
}
} else if (day > dayLength - 1) {
day = 0;
behavior = "instant";
if (document.getElementById("schedule").classList.contains("dayEnabled")) {
document.getElementById("schedule").style.opacity = 0;
}
if (!document.startViewTransition) {
fetchSchedule(window.year, week);
} else {
document.startViewTransition(() => fetchSchedule(window.year, week));
}
}
document.querySelector("body").scrollTo({
left: window.innerWidth * day,
behavior: behavior,
});
}
window.addEventListener("resize", () => {
document.querySelector("body").scrollTo({
left: window.innerWidth * day,
behavior: "instant",
});
if (window.innerWidth < 346) {
document.getElementById("dayBtn").click();
}
if (
window.innerHeight < 565 &&
document.getElementById("schedule").classList == "ltrEnabled"
) {
document.getElementById("ltr").click();
}
});
document.getElementById("nextDay").addEventListener("click", () => {
switchDay("next");
});
document.getElementById("previousDay").addEventListener("click", () => {
switchDay("prev");
});
document.getElementById("dayBtn").addEventListener("click", () => {
localStorage.setItem("dag", "true");
});
document.getElementById("weekBtn").addEventListener("click", () => {
localStorage.setItem("dag", "false");
});
document.getElementById("weekInput").addEventListener("change", () => {
fetchSchedule(window.year, document.getElementById("weekInput").value);
});
window.addEventListener("keydown", (event) => {
// Prevent switching when in dialog
const dialogOpen = [...dialogs].some((dialog) => dialog.open);
if (dialogOpen) return;
switch (event.key) {
case "ArrowLeft":
switchDay("prev");
break;
case "ArrowRight":
switchDay("next");
break;
}
});
let touchstartX = 0;
let touchstartY = 0;
let touchendX = 0;
let touchendY = 0;
document.addEventListener("touchstart", (event) => {
touchstartX = event.touches[0].clientX;
touchstartY = event.touches[0].clientY;
});
document.addEventListener("touchend", (event) => {
touchendX = event.changedTouches[0].clientX;
touchendY = event.changedTouches[0].clientY;
handleGesture();
});
function handleGesture() {
// Prevent switching when in dialog
const dialogOpen = [...dialogs].some((dialog) => dialog.open);
if (dialogOpen) return;
if (touchendX - touchstartX < -50) {
switchDay("next");
}
if (touchendX - touchstartX > 50) {
switchDay("prev");
}
}
document.getElementById("dayBtn").addEventListener("click", () => {
document.getElementById("schedule").classList = "dayEnabled";
if (localStorage.getItem("viewOption") == "list") {
document.getElementById("schedule").classList = "listEnabled";
}
document.getElementById("ltr").style.opacity = "0";
document.getElementById("ltr").style.visibility = "hidden";
document.getElementById("weekBtn").classList.remove("selected");
document.getElementById("dayBtn").classList.add("selected");
document.querySelector("body").scrollTo({
left: window.innerWidth * day,
behavior: "instant",
});
});