-
Notifications
You must be signed in to change notification settings - Fork 8
/
app.js
95 lines (75 loc) · 2.49 KB
/
app.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
/*
Copyright (c) 2020 - present, DITDOT Ltd. - MIT Licence
https://www.ditdot.hr/en
https://github.com/ditdot-dev/dark-mode-example
*/
function load() {
"use strict";
const switcher = document.querySelector("input");
const title = document.querySelector(".title");
const logo = document.querySelector(".logo");
String.prototype.format = function() {
let formatted = this;
for (let i = 0; i < arguments.length; i++) {
let regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
function calculatePath() {
const width = window.innerWidth;
const height = window.innerHeight;
const path =
'path("M {0}, {1} m -{2}, 0 a {2}, {1} 0 1, 0 {3}, 0 a {2}, {1} 0 1,0 -{3}, 0z")'.format(
width / 2 - 25,
height / 2,
width / 2,
width
);
return path;
}
// Checks & unchecks the switcher
function checkToggle(check) {
switcher.checked = check;
}
// Toggles the "dark-mode" class based on if the media query matches
function toggleDarkMode(state) {
checkToggle(state);
const hasClass = document.body.classList.contains("dark-mode");
if (state) {
if (!hasClass) {
document.body.classList.add("dark-mode");
}
title.textContent = "Dark mode";
logo.style.offsetPath = calculatePath();
} else {
if (hasClass) {
document.body.classList.remove("dark-mode");
}
title.textContent = "Light mode";
logo.style.offsetPath = "none";
}
}
// MediaQueryList object
const useDark = window.matchMedia("(prefers-color-scheme: dark)");
let darkModeState = useDark.matches;
// Listen for changes in the OS settings
// addListener is used because older versions of Safari don't support addEventListener
useDark.addListener(function(evt) {
toggleDarkMode(evt.matches);
});
// Initial setting depending on the prefers-color-mode
toggleDarkMode(darkModeState);
function switchListener() {
darkModeState = !darkModeState;
toggleDarkMode(darkModeState);
}
// Listen for switch change
switcher.addEventListener("change", switchListener);
}
document.addEventListener("DOMContentLoaded", load);
/* Rocket logo animation is based on the CSS Motion Path properties
(offset-*) which are not supported by Safari browsers.
A possible solution for animation along a motion path is Greensock
MotionPathPlugin https://greensock.com/motionpath
*/