UNPKG

@kwiz/fluentui

Version:
50 lines 1.74 kB
"use client"; import { deleteCookie, dispatchCustomEvent, getCookie, getGlobal, isNullOrUndefined, setCookie } from "@kwiz/common"; import { useEffect, useId, useState } from "react"; import { useIsInPrint } from "./hooks-events"; const $themeCookie = "KWTheme"; function getDefaultThemeInfo() { const themeInfo = { auto: true, scheme: window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light" }; return themeInfo; } function getThemeInfo() { let themeInfo = null; const cookie = getCookie($themeCookie); if (isNullOrUndefined(cookie)) { themeInfo = getDefaultThemeInfo(); } else { themeInfo = { auto: false, scheme: cookie === "dark" ? "dark" : "light" }; } return themeInfo; } const globals = getGlobal("g_theme", { theme: getThemeInfo() }); export function setThemeInfo(themeInfo) { const newThemeInfo = (themeInfo.auto && isNullOrUndefined(themeInfo.scheme)) ? getDefaultThemeInfo() : themeInfo; if (!themeInfo.auto) { setCookie($themeCookie, themeInfo.scheme, 365); } else { deleteCookie($themeCookie); } globals.theme = newThemeInfo; dispatchCustomEvent(globalThis, "OnThemeChanged"); } export function useTheme() { const [theme, setTheme] = useState(globals.theme); const isInPrint = useIsInPrint(); const id = useId(); useEffect(() => { const listener = () => { setTheme(globals.theme); }; window.addEventListener("OnThemeChanged", listener); return () => { window.removeEventListener("OnThemeChanged", listener); }; }, [id]); return isInPrint ? { auto: false, scheme: "light" } : theme; } //# sourceMappingURL=use-theme.js.map