about summary refs log tree commit diff
path: root/bskyembed/src/color-mode.ts
blob: b34624e312f62cd81194906ed94db81d45fc560b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export type ColorModeValues = 'system' | 'light' | 'dark'

export function assertColorModeValues(value: string): value is ColorModeValues {
  return ['system', 'light', 'dark'].includes(value)
}

export function applyTheme(theme: 'light' | 'dark') {
  document.documentElement.classList.remove('light', 'dark')
  document.documentElement.classList.add(theme)
}

export function initSystemColorMode() {
  applyTheme(
    window.matchMedia('(prefers-color-scheme: dark)').matches
      ? 'dark'
      : 'light',
  )
  window
    .matchMedia('(prefers-color-scheme: dark)')
    .addEventListener('change', mql => {
      applyTheme(mql.matches ? 'dark' : 'light')
    })
}