sonda/web/src/theme/theme.ts
tgiachi abeef4e30f feat(web): four themes with a contrast test
- Sonda, Tokyo Night, Gruvbox dark and Gruvbox light as CSS variables with shadcn token names
- contrast test: text 4.5:1, accent and form outlines 3:1 in every theme
- Gruvbox dark muted text lightened to pass
- theme choice is stored in localStorage and survives it being blocked
2026-11-12 11:17:41 +01:00

62 lines
1.5 KiB
TypeScript

import { useSyncExternalStore } from 'react'
export type ThemeId = 'sonda' | 'tokyo-night' | 'gruvbox-dark' | 'gruvbox-light'
export const THEMES: readonly { id: ThemeId; labelKey: string }[] = [
{ id: 'sonda', labelKey: 'theme.sonda' },
{ id: 'tokyo-night', labelKey: 'theme.tokyo-night' },
{ id: 'gruvbox-dark', labelKey: 'theme.gruvbox-dark' },
{ id: 'gruvbox-light', labelKey: 'theme.gruvbox-light' },
]
const KEY = 'sonda.theme'
const DEFAULT: ThemeId = 'sonda'
let current: ThemeId = DEFAULT
const listeners = new Set<() => void>()
function isThemeId(value: unknown): value is ThemeId {
return THEMES.some((t) => t.id === value)
}
function readStored(): string | null {
try {
return localStorage.getItem(KEY)
} catch {
return null
}
}
function apply(id: ThemeId) {
current = id
document.documentElement.dataset.theme = id
listeners.forEach((fn) => fn())
}
export function getTheme(): ThemeId {
return current
}
export function setTheme(id: ThemeId): void {
apply(id)
try {
localStorage.setItem(KEY, id)
} catch {
// The choice still applies for this page view.
}
}
export function initTheme(): void {
const stored = readStored()
apply(isThemeId(stored) ? stored : DEFAULT)
}
function subscribe(fn: () => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
export function useTheme(): { theme: ThemeId; setTheme: (id: ThemeId) => void } {
const theme = useSyncExternalStore(subscribe, getTheme)
return { theme, setTheme }
}