Files
EpicNext-Cms/src/components/theme-switcher.tsx
T
SimoandCursor 0096c55f96
Local Build and Deploy / deploy (push) Successful in 53s
Fix theme switcher desync and auto-correct unreadable saved colors.
Sync dark-mode state from the DOM after mount so admin text no longer needs a double toggle, and normalize text/button colors against their surfaces on theme save.

Co-authored-by: Cursor <[email protected]>
2026-07-15 20:54:46 +02:00

46 lines
1.3 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
/**
* Light/dark toggle. The class lives on <html>; theme-init.js applies the
* saved choice before paint. We sync React state after mount so SSR hydration
* does not desync from the real DOM class (which forced a double-click before).
*/
export function ThemeSwitcher() {
const [dark, setDark] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => {
setDark(document.documentElement.classList.contains("dark"));
setReady(true);
}, []);
function toggle() {
const next = !document.documentElement.classList.contains("dark");
document.documentElement.classList.toggle("dark", next);
setDark(next);
try {
localStorage.setItem("theme", next ? "dark" : "light");
} catch {
/* private mode / storage disabled — runtime toggle still works */
}
}
return (
<button
type="button"
onClick={toggle}
className="nav-item cursor-pointer text-lg leading-none px-2"
aria-label={dark ? "Switch to light mode" : "Switch to dark mode"}
title={dark ? "Light mode" : "Dark mode"}
suppressHydrationWarning
style={{ visibility: ready ? "visible" : "hidden" }}
>
<span aria-hidden className="text-lg leading-none">
{dark ? "☀" : "☾"}
</span>
</button>
);
}