aboutsummaryrefslogtreecommitdiff
path: root/www/assets/color-scheme.ts
blob: db6a3aa65b7df39fec35ae77c59dbbb3e40b667c (plain)
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
104
105
106
107
108
109
110
function createResetTimer(cleanup: () => void, timeout = 1) {
  let tag = 0
  return () => {
    clearTimeout(tag)
    tag = setTimeout(() => {
      cleanup()
    }, timeout * 1000)
  }
}

function createToast(duration: number = 1): (text: string) => void {
  const toast = document.createElement("div")
  toast.className = "toast"

  const reset = createResetTimer(() => {
      toast.remove()
  }, duration)

  return (text) => {
    if (!toast.isConnected) {
      document.body.appendChild(toast)
    }
    toast.textContent = text
    reset()
  }
}

const setToast = createToast()

const key = "force-color-scheme"
const dark = "dark"
const light = "light"
type Scheme = typeof dark | typeof light

const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)")

function fromMediaQuery(value: boolean | null): Scheme {
  if (value == null) { value = mediaQuery.matches}
  return value ? dark : light
}

function opposite(scheme: Scheme): Scheme {
  return scheme === dark ? light : dark
}

function updateScheme(theme: Scheme | null): Scheme {
  if (theme == null) { theme = fromMediaQuery(null) }
  document.querySelector("html")!.dataset["theme"] = theme
  return theme
}

mediaQuery.addEventListener("change", (e) => updateScheme(current || fromMediaQuery(e.matches)))

let current: Scheme | null = null

{
  const saved = localStorage.getItem(key)
  if ([null, dark, light].includes(saved)) {
    current = saved as never
  } else {
    console.log(`invalid saved theme: ${saved}`)
    localStorage.removeItem(key)
  }
}

updateScheme(current)

function saveScheme(value: Scheme | null) {
  current = value

  if (value == null) {
    localStorage.removeItem(key)
  } else {
    localStorage.setItem(key, value)
  }

  const real = updateScheme(value)
  setToast(`theme: ${current == null ? "system" : "force"}(${real})`)
}

function next(): Scheme | null {
  const sys = fromMediaQuery(null)
  if (current == null) {
    return opposite(sys)
  } else {
    if (current === sys) {
      return null;
    } else {
      return opposite(current)
    }
  }
}

window.addEventListener("load", () => {
  const slogon = document.getElementById("slogan")!
  let clicks: number = 0

  const reset = createResetTimer(() => {
    clicks = 0
  })

  slogon.addEventListener("click", () => {
    reset()
    clicks += 1
    if (clicks === 3) {
      saveScheme(next())
      clicks = 0
    }
  })
})