-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlightdark.py
103 lines (83 loc) · 2.19 KB
/
lightdark.py
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
from fasthtml.common import *
def atag(theme="auto"):
return A(href="#", data_theme_switcher=theme)
def AutoLink(*inner):
return atag("auto")(*inner)
def DarkLink(*inner):
return atag("dark")(*inner)
def LightLink(*inner):
return atag("light")(*inner)
def LightDarkScript():
return Script(
"""
/*!
* Minimal theme switcher
*
* Pico.css - https://picocss.com
* Copyright 2019-2024 - Licensed under MIT
*/
const themeSwitcher = {
// Config
_scheme: "auto",
menuTarget: "details.dropdown",
buttonsTarget: "a[data-theme-switcher]",
buttonAttribute: "data-theme-switcher",
rootAttribute: "data-theme",
localStorageKey: "picoPreferredColorScheme",
// Init
init() {
this.scheme = this.schemeFromLocalStorage;
this.initSwitchers();
},
// Get color scheme from local storage
get schemeFromLocalStorage() {
return window.localStorage?.getItem(this.localStorageKey) ?? this._scheme;
},
// Preferred color scheme
get preferredColorScheme() {
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
},
// Init switchers
initSwitchers() {
const buttons = document.querySelectorAll(this.buttonsTarget);
buttons.forEach((button) => {
button.addEventListener(
"click",
(event) => {
event.preventDefault();
// Set scheme
this.scheme = button.getAttribute(this.buttonAttribute);
// Close dropdown
document.querySelector(this.menuTarget)?.removeAttribute("open");
},
false
);
});
},
// Set scheme
set scheme(scheme) {
if (scheme == "auto") {
this._scheme = this.preferredColorScheme;
} else if (scheme == "dark" || scheme == "light") {
this._scheme = scheme;
}
this.applyScheme();
this.schemeToLocalStorage();
},
// Get scheme
get scheme() {
return this._scheme;
},
// Apply scheme
applyScheme() {
document.querySelector("html")?.setAttribute(this.rootAttribute, this.scheme);
},
// Store scheme to local storage
schemeToLocalStorage() {
window.localStorage?.setItem(this.localStorageKey, this.scheme);
},
};
// Init
themeSwitcher.init();
"""
)