NGU-Web/src/components/ThemeToggle.tsx
Zaldimmar d81f7bd856 Adopt the new palette; square corners, superellipse buttons
The theme defaults (light and dark) come from the 16-color grid,
kept as PALETTE in src/lib/color.ts; every text pair passes the
admin's 4.5:1 check. Nothing is rounded any more except buttons,
which share one btn utility (Poppins Bold, a superellipse corner
where the browser has corner-shape) and true dots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:39 -05:00

69 lines
2.5 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
THEME TOGGLE
Light or dark. The theme lives on <html data-theme>, which
index.html sets before the first paint (from this browser's
choice, else the system setting) so a dark visitor never sees a
white flash. Pressing this makes an explicit choice and remembers
it; until then the site follows the system, including a change
made while the page is open. Colors come from the tokens in
index.css.
═══════════════════════════════════════════════════════════════ */
import { Sun, Moon } from '@phosphor-icons/react'
import { useEffect, useState } from 'react'
type Theme = 'light' | 'dark'
export const THEME_STORAGE_KEY = 'site-theme'
const current = (): Theme =>
document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light'
function chosen(): Theme | null {
try {
const value = localStorage.getItem(THEME_STORAGE_KEY)
return value === 'dark' || value === 'light' ? value : null
} catch {
return null
}
}
export default function ThemeToggle({ className = '' }: { className?: string }) {
const [theme, setTheme] = useState<Theme>(current)
// No choice made: follow the system as it changes.
useEffect(() => {
const media = window.matchMedia('(prefers-color-scheme: dark)')
const follow = () => {
if (chosen()) return
const next: Theme = media.matches ? 'dark' : 'light'
document.documentElement.dataset.theme = next
setTheme(next)
}
media.addEventListener('change', follow)
return () => media.removeEventListener('change', follow)
}, [])
const toggle = () => {
const next: Theme = theme === 'dark' ? 'light' : 'dark'
document.documentElement.dataset.theme = next
setTheme(next)
try {
localStorage.setItem(THEME_STORAGE_KEY, next)
} catch {}
}
const dark = theme === 'dark'
return (
<button
type="button"
onClick={toggle}
aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
title={dark ? 'Light mode' : 'Dark mode'}
className={`flex h-9 w-9 items-center justify-center btn transition-colors ${className}`}
>
{dark ? <Sun size={20} weight="bold" aria-hidden="true" /> : <Moon size={20} weight="bold" aria-hidden="true" />}
</button>
)
}