UNPKG

xtreme-ui

Version:

Collection of reusable components that can be used in web projects

40 lines (39 loc) 2.03 kB
"use client"; import { jsx as p } from "react/jsx-runtime"; import { createContext as v, useState as n, useEffect as h } from "react"; import { STORAGE as m, defaultColorPreset as u } from "../../../utils/constants/theme.js"; import "color-namer"; const l = { isDarkTheme: void 0, themeScheme: void 0, setThemeScheme: () => null, themeColor: void 0, setThemeColor: () => null }, T = v(l), $ = ({ 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 == null ? void 0 : 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 g = document.getElementById(m.themeColor) || document.head.appendChild(Object.assign(document.createElement("style"), { id: m.themeColor })); g.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__ */ p(T.Provider, { value: { isDarkTheme: C, themeScheme: o, setThemeScheme: a, themeColor: r, setThemeColor: s }, children: S }); }; export { T as ThemeContext, $ as ThemeProvider };