-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy paththeme_toggle_controller.js
More file actions
38 lines (34 loc) · 1.19 KB
/
theme_toggle_controller.js
File metadata and controls
38 lines (34 loc) · 1.19 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
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="ruby-ui--theme-toggle"
// Expects to sit on the same element as ruby-ui--toggle and listen to its
// ruby-ui:toggle:change event. pressed = dark mode.
export default class extends Controller {
connect() {
this.applyTheme(this.currentTheme())
}
apply(event) {
const pressed = event.detail?.pressed
const theme = pressed ? "dark" : "light"
localStorage.theme = theme
this.applyTheme(theme)
}
currentTheme() {
if (localStorage.theme === "dark") return "dark"
if (localStorage.theme === "light") return "light"
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
}
applyTheme(theme) {
const html = document.documentElement
if (theme === "dark") {
html.classList.add("dark")
html.classList.remove("light")
} else {
html.classList.add("light")
html.classList.remove("dark")
}
const dark = theme === "dark"
this.element.setAttribute("aria-pressed", dark ? "true" : "false")
this.element.dataset.state = dark ? "on" : "off"
this.element.dataset["rubyUi--TogglePressedValue"] = dark ? "true" : "false"
}
}