-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy paththeme_controller.js
More file actions
75 lines (58 loc) · 2.01 KB
/
theme_controller.js
File metadata and controls
75 lines (58 loc) · 2.01 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
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["lightButton", "darkButton", "autoButton"]
#mediaQuery
#handleSystemThemeChange
connect() {
this.#mediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
this.#handleSystemThemeChange = () => this.#applyStoredTheme()
this.#mediaQuery.addEventListener("change", this.#handleSystemThemeChange)
this.#applyStoredTheme()
}
disconnect() {
this.#mediaQuery.removeEventListener("change", this.#handleSystemThemeChange)
}
setLight() {
this.#theme = "light"
}
setDark() {
this.#theme = "dark"
}
setAuto() {
this.#theme = "auto"
}
get #storedTheme() {
return localStorage.getItem("theme") || "auto"
}
get #resolvedTheme() {
const stored = this.#storedTheme
if (stored === "light" || stored === "dark") return stored
return this.#mediaQuery.matches ? "dark" : "light"
}
set #theme(theme) {
localStorage.setItem("theme", theme)
const resolved = this.#resolvedTheme
const currentTheme = document.documentElement.dataset.theme
const hasChanged = currentTheme !== resolved
const prefersReducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches
const animate = hasChanged && !prefersReducedMotion
const applyTheme = () => {
document.documentElement.dataset.theme = resolved
this.#updateButtons()
}
if (animate && document.startViewTransition) {
document.startViewTransition(applyTheme)
} else {
applyTheme()
}
}
#applyStoredTheme() {
this.#theme = this.#storedTheme
}
#updateButtons() {
const storedTheme = this.#storedTheme
if (this.hasLightButtonTarget) { this.lightButtonTarget.checked = (storedTheme === "light") }
if (this.hasDarkButtonTarget) { this.darkButtonTarget.checked = (storedTheme === "dark") }
if (this.hasAutoButtonTarget) { this.autoButtonTarget.checked = (storedTheme !== "light" && storedTheme !== "dark") }
}
}