aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/theme.ts
blob: c05b24d8f70798866efc2ed4023fcba7b2974cc8 (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
import { createContext, useContext } from 'react'

export type ColorScheme = 'light' | 'dark'
export const themeStorageKey = 'react-spectrum-color-scheme'

export const ThemeContext = createContext<{
  colorScheme: ColorScheme
  setColorScheme: (colorScheme: ColorScheme) => void
} | null>(null)

export function getInitialColorScheme(): ColorScheme {
  try {
    const saved = localStorage.getItem(themeStorageKey)
    if (saved === 'light' || saved === 'dark') return saved
  } catch {
    // Storage may be unavailable; theme switching still works for this session.
  }
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

export function useTheme() {
  const theme = useContext(ThemeContext)
  if (!theme) throw new Error('useTheme must be used within ThemeContext')
  return theme
}