Add theme toggle and update MineGeo branding
This commit is contained in:
59
components/ThemeToggle.tsx
Normal file
59
components/ThemeToggle.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
import { useI18n } from "./I18nProvider";
|
||||
import { themeStorageKey, type Theme } from "@/shared/theme";
|
||||
|
||||
function currentTheme(): Theme {
|
||||
return document.documentElement.dataset.theme === "light" ? "light" : "dark";
|
||||
}
|
||||
|
||||
function subscribe(onChange: () => void) {
|
||||
const observer = new MutationObserver(onChange);
|
||||
observer.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["data-theme"],
|
||||
});
|
||||
function syncStorage(event: StorageEvent) {
|
||||
if (event.key === themeStorageKey || event.key === null) {
|
||||
document.documentElement.dataset.theme =
|
||||
event.newValue === "light" ? "light" : "dark";
|
||||
}
|
||||
}
|
||||
window.addEventListener("storage", syncStorage);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
window.removeEventListener("storage", syncStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { t } = useI18n();
|
||||
const theme = useSyncExternalStore(subscribe, currentTheme, () => "dark");
|
||||
const label = t(
|
||||
theme === "light" ? "Turn on dark mode" : "Turn on light mode",
|
||||
);
|
||||
function toggle() {
|
||||
const next = currentTheme() === "light" ? "dark" : "light";
|
||||
document.documentElement.dataset.theme = next;
|
||||
try {
|
||||
localStorage.setItem(themeStorageKey, next);
|
||||
} catch {
|
||||
// Switching still works for this visit if browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="theme-toggle"
|
||||
onClick={toggle}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
aria-pressed={theme === "light"}
|
||||
>
|
||||
<Sun className="theme-sun" size={19} aria-hidden="true" />
|
||||
<Moon className="theme-moon" size={19} aria-hidden="true" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user