SPB Git

Repository Public

ThemeToggle.tsx 1.7 KB 32 lines tsx

1"use client";2import { useEffect } from "react";3import { Icon } from "@/components/ui/Icon";4import { update, useAtlas, useHydrated } from "@/lib/client/store";5import { setPrefs } from "@/modules/learning-engine/state";67const ORDER = ["system", "light", "dark"] as const;8const LABEL = { system: "automatique", light: "clair", dark: "sombre" } as const;9const ICON = { system: "auto", light: "sun", dark: "moon" } as const;1011/** Runs before first paint (inline in <head>): applies the stored theme, or the system preference. */12export const THEME_SCRIPT = `(function(){var d=document.documentElement,t;try{t=(JSON.parse(localStorage.getItem("atlas.v1")||"{}").prefs||{}).theme}catch(e){}if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";d.dataset.theme=t})()`;1314export function ThemeToggle() {15  const hydrated = useHydrated();16  const theme = useAtlas().prefs.theme ?? "system";17  useEffect(() => {18    const mq = window.matchMedia("(prefers-color-scheme: dark)");19    const apply = () => { document.documentElement.dataset.theme = theme === "system" ? (mq.matches ? "dark" : "light") : theme; };20    apply();21    mq.addEventListener("change", apply);22    return () => mq.removeEventListener("change", apply);23  }, [theme]);24  const shown = hydrated ? theme : "system";25  const next = ORDER[(ORDER.indexOf(shown) + 1) % ORDER.length]!;26  return (27    <button type="button" className="btn btn-quiet btn-sm !px-2.5" onClick={() => update((s) => setPrefs(s, { theme: next }))} aria-label={`Thème ${LABEL[shown]}. Passer au thème ${LABEL[next]}.`} title={`Thème : ${LABEL[shown]}`} data-testid="theme-toggle">28      <Icon name={ICON[shown]} size={18} />29    </button>30  );31}32
Files main
Menu

Theme