UNPKG

xtreme-ui

Version:

Collection of reusable components that can be used in web projects

41 lines (40 loc) 2.02 kB
"use client"; import { jsx as g } from "react/jsx-runtime"; import { useState as n, useEffect as h, createContext as v } from "react"; import { STORAGE as m, defaultColorPreset as u } from "../../../utils/constants/theme.js"; import "color-namer"; import "colord"; const l = { isDarkTheme: void 0, themeScheme: void 0, setThemeScheme: () => null, themeColor: void 0, setThemeColor: () => null }, T = v(l), x = ({ children: S }) => { const [o, a] = n(l.themeScheme), [r, s] = n(l.themeColor), f = () => matchMedia("(prefers-color-scheme: dark)").matches, [C, d] = n(o === "auto" ? f() : o === "dark"); return h(() => { let e = localStorage.getItem(m.themeScheme), t; try { t = JSON.parse(localStorage.getItem(m.themeColor) || "null") || u; } catch { t = u; } e || (e = document?.documentElement.getAttribute(m.themeSchemeAttr) ?? void 0), e && a(e), t && s(t); }, []), h(() => { if (!o || !r) return; const { h: e, s: t, l: i } = r; document.documentElement.setAttribute(m.themeSchemeAttr, o); const p = document.getElementById(m.themeColor) || document.head.appendChild(Object.assign(document.createElement("style"), { id: m.themeColor })); p.textContent = `:root{ --H: ${e}; --S: ${t}%; --L: ${i}% }`; let c = document.querySelector('meta[name="theme-color"]'); c || (c = document.createElement("meta"), c.name = "theme-color", document.head.appendChild(c)), c.content = `hsl(${e},${t}%,${i}%)`, localStorage.setItem(m.themeScheme, o), localStorage.setItem(m.themeColor, JSON.stringify(r)); }, [o, r]), h(() => { if (o !== "auto") return d(o === "dark"); const e = matchMedia("(prefers-color-scheme: dark)"), t = () => d(e.matches); return t(), e.addEventListener("change", t), () => e.removeEventListener("change", t); }, [o]), /* @__PURE__ */ g(T.Provider, { value: { isDarkTheme: C, themeScheme: o, setThemeScheme: a, themeColor: r, setThemeColor: s }, children: S }); }; export { T as ThemeContext, x as ThemeProvider };