This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { getPublicSettings } from "../api/api";
|
||||
|
||||
type Theme = "dark" | "light";
|
||||
|
||||
@@ -13,6 +14,30 @@ const ThemeContext = createContext<ThemeContextValue>({
|
||||
toggleTheme: () => {},
|
||||
});
|
||||
|
||||
function hexToRgba(hex: string, alpha: number): string {
|
||||
const h = hex.replace("#", "");
|
||||
const r = parseInt(h.substring(0, 2), 16);
|
||||
const g = parseInt(h.substring(2, 4), 16);
|
||||
const b = parseInt(h.substring(4, 6), 16);
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
|
||||
function applyClientColors(s: { client_color_primary: string; client_color_secondary: string; client_color_success: string; client_color_danger: string; client_color_warning: string }) {
|
||||
const root = document.documentElement;
|
||||
if (s.client_color_primary) {
|
||||
root.style.setProperty("--primary", s.client_color_primary);
|
||||
root.style.setProperty("--primary-soft", hexToRgba(s.client_color_primary, 0.12));
|
||||
root.style.setProperty("--primary-glow", hexToRgba(s.client_color_primary, 0.25));
|
||||
}
|
||||
if (s.client_color_secondary) {
|
||||
root.style.setProperty("--cyan", s.client_color_secondary);
|
||||
root.style.setProperty("--cyan-soft", hexToRgba(s.client_color_secondary, 0.1));
|
||||
}
|
||||
if (s.client_color_danger) {
|
||||
root.style.setProperty("--red", s.client_color_danger);
|
||||
}
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>(() => {
|
||||
const stored = localStorage.getItem("theme");
|
||||
@@ -25,6 +50,21 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
localStorage.setItem("theme", theme);
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchColors = async () => {
|
||||
try {
|
||||
const settings = await getPublicSettings();
|
||||
applyClientColors(settings);
|
||||
} catch {}
|
||||
};
|
||||
fetchColors();
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === "visible") fetchColors();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
return () => document.removeEventListener("visibilitychange", onVisibility);
|
||||
}, []);
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user