forked from hackorum-dev/hackorum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdensity_controller.js
More file actions
48 lines (38 loc) · 1.29 KB
/
density_controller.js
File metadata and controls
48 lines (38 loc) · 1.29 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
import { Controller } from "@hotwired/stimulus"
const STORAGE_KEY = "hackorum-density"
const DEFAULT_DENSITY = "default"
const VALID_DENSITIES = ["tiny", "compact", "default", "comfortable", "spacious"]
export default class extends Controller {
static targets = ["button"]
connect() {
this.applyInitialDensity()
}
select(event) {
event.preventDefault()
const { densityValue } = event.currentTarget.dataset
this.setDensity(densityValue)
}
applyInitialDensity() {
const stored = window.localStorage.getItem(STORAGE_KEY)
const initial = VALID_DENSITIES.includes(stored) ? stored : DEFAULT_DENSITY
this.setDensity(initial, { persist: false })
}
setDensity(density, { persist = true } = {}) {
const normalized = VALID_DENSITIES.includes(density) ? density : DEFAULT_DENSITY
document.documentElement.dataset.density = normalized
if (persist) {
window.localStorage.setItem(STORAGE_KEY, normalized)
}
this.updateButtons(normalized)
}
updateButtons(density) {
if (this.hasButtonTarget) {
this.buttonTargets.forEach((button) => {
button.classList.toggle("is-active", button.dataset.densityValue === density)
})
}
}
get currentDensity() {
return document.documentElement.dataset.density || DEFAULT_DENSITY
}
}