-
Notifications
You must be signed in to change notification settings - Fork 5
/
script.js
484 lines (435 loc) · 14.8 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
// Importing the Schedule, Settings, and Languages
import { formattedJSON, languageJSON, scheduleJSON, getSchedule, getEvent } from "./scheduleFormatting.js";
import { settings, settingsMenu } from "./settings.js";
import { customNames, namesMenu } from "./classNames.js";
var timeOffeset = dayjs.tz(scheduleJSON.timeOffset, "HH:mm:ss", scheduleJSON.timezone).local();
const rootStyle = document.querySelector(":root").style;
rootStyle.setProperty("--animated-background-intensity", settings.themeAnimationIntensity + "deg");
// Stores the user preference for how they display time
var timeFormat = (settings.twentyFourHour ? "HH" : "h") + ":mm" + (settings.showAMPM ? " A" : "");
// Find current Period
var currentPeriod = null;
var periodListComponent = PeriodListComponent(formattedJSON, false);
// Stores if a notification has been sent already
var notified = false;
periodListComponent.listPeriod.forEach((p) => {
if (p.isCurrent()) {
currentPeriod = p;
}
});
// Petite Vue interface
PetiteVue.createApp({
// Components
PeriodInformationComponent,
PeriodListComponent,
CalendarDay,
// All Pages
currentPage: "now",
backgroundColor: "hsl( 0, 50, 50)",
updatePage: true,
// Now Page
// periodList,
periodListComponent,
todaysGreeting: "",
listCount: 0,
getListCount() {
this.listCount++;
return this.listCount % 2 == 0;
},
currentPeriod,
currentTime: 0,
minutesLeft: 0,
percentCompleted: 0,
percentCompletedText: "",
// Calendar Page
showPopup: false,
// popupSchedule: periodList,
popupDate: null,
monthOffset: 0,
calendarToggle: true,
// Settings Page
settingsMenu,
settings,
changedSetting: true,
shareLink: "",
// Class Names Page
namesMenu,
customNames,
// Functions
switchPage(page) {
if (page == "now" || page == "calendar" || page == "settings" || page == "classNames" || page == "data") this.currentPage = page;
else {
this.currentPage = "now";
}
this.popupDate = null;
window.history.pushState("", this.currentPage, "/?" + this.currentPage);
if (window.innerWidth <= 767) {
if (page == "now") {
let el = document.getElementsByClassName("period-details-small")[0];
if (el != null) el.scrollIntoView({ behavior: "smooth", block: "center" });
}
}
},
changeSetting,
changeHue,
themeChange,
changeClassName,
translateWithInsert,
translate,
translateNoCustom,
getMonthText,
mod,
shareSettings,
shareClassNames,
getEvent,
// Update interval timer
interval: null,
startTimer() {
var url = new URLSearchParams(location.search);
var startReload = false;
if (url.has("setSettings")) {
localStorage.setItem("settings", url.get("setSettings"));
startReload = true;
}
if (url.has("setClassNames")) {
localStorage.setItem("customNamesJSON", url.get("setClassNames"));
startReload = true;
}
if (url.has("calendar")) {
this.switchPage("calendar");
} else if (url.has("settings")) {
this.switchPage("settings");
} else if (url.has("classNames")) {
this.switchPage("classNames");
} else if (url.has("data")) {
this.switchPage("data");
} else {
this.switchPage("now");
}
if (startReload) location.reload();
changeHue(settings.colorTheme);
this.update();
clearInterval(this.interval);
this.interval = setInterval(() => {
this.update();
}, 5000);
},
update() {
if (!this.currentPeriod.isCurrent()) {
if (this.currentPeriod.start.day() != dayjs().day()) {
location.reload();
}
// location.reload();
this.updatePage = false;
periodListComponent.listPeriod.forEach((p) => {
if (p.isCurrent()) {
this.currentPeriod = p;
}
});
setTimeout(() => {
this.updatePage = true;
}, 10);
// console.log("new Period");
// periodList.forEach((p) => {
// if(p.isCurrent()) {
// currentPeriod = p;
// }});
// periodList = periodList;
notified = false;
}
this.todaysGreeting = getTodaysGreeting();
this.minutesLeft = this.currentPeriod.end.diff(dayjs().subtract(timeOffeset.hour(), "hour").subtract(timeOffeset.minute(), "minute").subtract(timeOffeset.second(), "second"), "minutes") + 1;
this.percentCompleted = Math.trunc(100 - (this.minutesLeft / this.currentPeriod.end.diff(this.currentPeriod.start, "minutes")) * 100);
this.percentCompletedText = translateWithInsert("PERCENT_COMPLETED", this.percentCompleted);
this.currentTime = dayjs().format(timeFormat);
document.title = (this.minutesLeft >= 60 ? Math.trunc(this.minutesLeft / 60) + "hr. " : "") + (this.minutesLeft % 60) + "min. | LCHS Go";
sendNotification(this.currentPeriod, this.minutesLeft);
},
}).mount();
// Component - Period - Holds the name, start, end, and if passing
function PeriodComponent(setName, setStart, setEnd, setPassing) {
var varStart = dayjs(setStart, "hh:mm A"); //formats from the json
var varEnd = dayjs(setEnd, "hh:mm A");
return {
name: setName,
start: varStart,
end: varEnd,
passing: setPassing,
getStart() {
return varStart.format(timeFormat);
},
getEnd() {
return varEnd.format(timeFormat);
},
isCurrent() {
var now = dayjs().subtract(timeOffeset.hour(), "hour").subtract(timeOffeset.minute(), "minute").subtract(timeOffeset.second(), "second");
return now.isBetween(this.start, this.end);
},
isVisible() {
if (this.isCurrent() || settings.showExtraPeriods) {
return true;
} else {
if (this.name == "PERIOD_0" && !settings.zeroEnabled) {
return false;
} else if (this.name == "PERIOD_6" && !settings.sixthEnabled) {
return false;
} else if (setPassing) {
return false;
} else {
return true;
}
}
},
getName() {
if (this.passing) {
let tempName = this.name.split(",");
return translateWithInsert(tempName[0], translate(tempName[1]));
}
return translate(this.name);
},
};
}
// Component - CalendarDay - Holds the schedule for the day and the date
function CalendarDay(day, monthOffset) {
var dateS = dayjs()
.month(dayjs().month() + monthOffset)
.startOf("month");
var dateM = dateS.set("date", day - dateS.day());
return {
date: dateM,
schedule: getSchedule(dateM),
event: getEvent(dateM),
};
}
// Component - Period Information Template - Used to make a period information block
function PeriodInformationComponent(props) {
return {
$template: "#period-information-template",
};
}
// Component - Period List Template - Used to make a period list block
function PeriodListComponent(periods, isCal) {
var periodList = periods.map((p) => {
return PeriodComponent(p.name, p.start, p.end, p.passing);
});
return {
isCalendar: isCal,
listPeriod: periodList,
$template: "#period-list-template",
};
}
// Function - Get the translated greeting and schedule for the day
export function getTodaysGreeting() {
return getGreeting() + " " + translateWithInsert("TODAY_IS", translate(formattedJSON.scheduleType));
}
// Function - Get the translated current month for the calendar
export function getMonthText(month) {
var monthsDict = {
0: "JANUARY",
1: "FEBURARY",
2: "MARCH",
3: "APRIL",
4: "MAY",
5: "JUNE",
6: "JULY",
7: "AUGUST",
8: "SEPTEMBER",
9: "OCTOBER",
10: "NOVEMBER",
11: "DECEMBER",
};
return translate(monthsDict[dayjs().month(month).month()]);
}
// Function - Get the time of day for the greeting
function getGreeting() {
var hours = dayjs().hour();
if (hours < 12) {
return translate("MORNING");
} else if (hours < 18) {
return translate("AFTERNOON");
} else {
return translate("EVENING");
}
}
// Function - Set the local storage settings with an updated user setting
function changeSetting(setting, value) {
settings[setting] = value;
this.changedSetting = !this.changedSetting;
// Send a message for the extension to pick up on when the settings change
window.postMessage({ settingsChanged: true });
localStorage.setItem("settings", JSON.stringify(settings));
timeFormat = (settings.twentyFourHour ? "HH" : "h") + ":mm" + (settings.showAMPM ? " A" : "");
if (setting == "themeAnimationIntensity") rootStyle.setProperty("--animated-background-intensity", value + "deg");
if (setting == "notificationToggle" && value) {
if (!("Notification" in window)) {
// Check if the browser supports notifications
alert(translate("NOTIFY_UNSUPPORTED"));
} else if (Notification.permission === "granted") {
// Check whether notification permissions have already been granted;
// if so, create a notification
const notification = new Notification("LCHS Go", { body: translate("NOTIFY_ENABLED"), icon: "/faviconLarge.png" });
// …
} else if (Notification.permission !== "denied") {
// We need to ask the user for permission
Notification.requestPermission().then((permission) => {
// If the user accepts, let's create a notification
if (permission === "granted") {
const notification = new Notification("LCHS Go", { body: translate("NOTIFY_ENABLED"), icon: "/faviconLarge.png" });
// …
}
});
}
}
}
// Function - Called by the HTML to set the background color
function changeHue(hue) {
var value = hslToHex(hue, 50, 50);
document.getElementById("body").style.color = "white";
if (hue == 0) {
document.getElementById("body").style.color = "black";
value = hslToHex(0, 0, 90);
} else if (hue == 360) {
value = hslToHex(0, 0, 25);
} else if (hue == 359) {
value = hslToHex(0, 0, 0);
}
document.getElementById("background").style.backgroundColor = value;
var canvas = document.createElement("canvas");
canvas.width = 48;
canvas.height = 48;
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = "/faviconClear.png";
img.onload = function () {
ctx.fillStyle = value;
ctx.beginPath();
ctx.arc(24, 24, 24, 0, 2 * Math.PI);
ctx.fill();
if (hue == 0) {
ctx.filter = "invert(1)";
}
ctx.drawImage(img, 0, 0);
var link = document.createElement("link");
link.type = "image/x-icon";
link.rel = "shortcut icon";
link.href = canvas.toDataURL("image/x-icon");
document.getElementsByTagName("head")[0].appendChild(link);
};
// var iconImage
// if (settings.colorTheme == 0)
// iconImage = "/favicons/favicon0.ico"
// else if (settings.colorTheme >= 359)
// iconImage = "/favicons/favicon18.ico"
// else
// iconImage = ("/favicons/favicon" + Math.floor(settings.colorTheme / 360 * 17 + 1) + ".ico");
// changeIcon(iconImage);
}
var prevTime = Date.now();
function themeChange() {
if (Date.now() - prevTime < 100) {
document.getElementById("background").style.backgroundColor = "";
document.getElementById("background").style.backgroundImage = "linear-gradient(0,rgba(255, 0, 0, 1) 0%,rgba(255, 154, 0, 1) 10%,rgba(208, 222, 33, 1) 20%,rgba(79, 220, 74, 1) 30%,rgba(63, 218, 216, 1) 40%,rgba(47, 201, 226, 1) 50%,rgba(28, 127, 238, 1) 60%,rgba(95, 21, 242, 1) 70%,rgba(186, 12, 248, 1) 80%,rgba(251, 7, 217, 1) 90%,rgba(255, 0, 0, 1) 100%)";
}
prevTime = Date.now();
}
// Function - Helper for ^ to change HSL to Hex
function hslToHex(h, s, l) {
l /= 100;
const a = (s * Math.min(l, 1 - l)) / 100;
const f = (n) => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color)
.toString(16)
.padStart(2, "0"); // convert to Hex and prefix "0" if needed
};
return `#${f(0)}${f(8)}${f(4)}`;
}
function changeIcon(src) {
var link = document.createElement("link"),
oldLink = document.getElementById("dynamic-favicon");
link.id = "dynamic-favicon";
link.rel = "shortcut icon";
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}
// Function - Update the local storage for the customNames to the new custom names
function changeClassName(periodId, element) {
var newValue = element.value;
if (newValue == languageJSON[periodId] || newValue == "") {
newValue = languageJSON[periodId];
delete customNames[periodId];
element.value = newValue;
} else {
customNames[periodId] = newValue;
}
// Send a message to the extension to update custom names
window.postMessage({ namesChanged: true });
localStorage.setItem("customNamesJSON", JSON.stringify(customNames));
}
function shareSettings() {
var link = new URL(location.origin);
link.searchParams.set("setSettings", JSON.stringify(settings));
this.shareLink = link.href + "&settings";
}
function shareClassNames() {
var link = new URL(location.origin);
link.searchParams.set("setClassNames", JSON.stringify(customNames));
this.shareLink = link.href + "&settings";
}
// Function - Used to translate a key to the selected language.
export function translate(translateText) {
if (customNames[translateText] != null) {
return customNames[translateText];
} else {
return translateNoCustom(translateText);
}
}
export function translateNoCustom(translateText) {
if (languageJSON[translateText] == null) {
return translateText;
} else {
return languageJSON[translateText];
}
}
// Function - Used to translate a key to the selected language and insert other text if possible.
export function translateWithInsert(translateText, insertString) {
var returnText = translate(translateText);
var index = returnText.indexOf("{}");
if (index < 0) {
return translate(translateText);
}
return returnText.slice(0, index) + insertString + returnText.slice(index + 2);
}
// Notify the user before period starts or ends
export function sendNotification(period, timeLeft) {
if (settings.notificationToggle && !notified) {
var nextPeriod = null;
periodListComponent.listPeriod.forEach((p) => {
if (p.getStart() == period.getEnd()) {
nextPeriod = p;
}
});
if (nextPeriod && !nextPeriod.passing && nextPeriod.isVisible() && timeLeft == parseInt(settings.notificationStart)) {
// period start notif
const notification = new Notification("LCHS Go", { body: nextPeriod.getName() + translateWithInsert("NOTIFY_START", translate(settings.notificationStart)), icon: "/faviconLarge.png" });
notified = true;
} else if (!period.passing && period.isVisible() && timeLeft == parseInt(settings.notificationEnd)) {
// period end notif
const notification = new Notification("LCHS Go", { body: period.getName() + translateWithInsert("NOTIFY_END", translate(settings.notificationEnd)), icon: "/faviconLarge.png" });
notified = true;
}
}
}
export function mod(bigNum, smallNum) {
var output;
if (bigNum < 0) {
output = smallNum - (-bigNum % smallNum);
} else {
output = bigNum % smallNum;
}
return output;
}