-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
46 lines (38 loc) · 1.3 KB
/
index.ts
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
/**
* watchFavicon watches the page's favicons and swaps them out for a dark-mode
* version when needed.
*/
function watchFavicon(): () => void {
if (
typeof window === "undefined" ||
typeof window.matchMedia === "undefined"
) {
return () => {};
}
const q = (selector: string): HTMLLinkElement | null =>
document.querySelector(selector);
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const fv = q("link[rel='shortcut icon']") || q("link[rel='icon']");
const mi = q("link[rel='mask-icon']");
const handleMediaMatch = (e: MediaQueryListEvent) => {
updateIcons(e.matches);
};
const updateIcons = (isDarkMode: boolean = false) => {
const str = isDarkMode ? "data-dark-" : "data-light-";
fv.href = fv.getAttribute(str + "href");
mi.setAttribute("color", mi.getAttribute(str + "color"));
};
// Copy the current value to a light data-* attribute.
if (!fv.hasAttribute("data-light-href")) {
fv.setAttribute("data-light-href", fv.href);
}
if (!mi.hasAttribute("data-light-color")) {
mi.setAttribute("data-light-color", mi.getAttribute("color"));
}
mq.addEventListener("change", handleMediaMatch);
updateIcons(mq.matches);
return () => {
mq.removeEventListener("change", handleMediaMatch);
};
}
export default watchFavicon();