You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.1 KiB
45 lines
1.1 KiB
2 years ago
|
import { createContext, useState, useEffect, useMemo } from "react";
|
||
2 years ago
|
|
||
|
let lastColor = false;
|
||
|
|
||
|
const getInitialColor = () => {
|
||
|
if (typeof window !== "undefined" && window.localStorage) {
|
||
|
const storedPrefs = window.localStorage.getItem("theme-color");
|
||
|
if (typeof storedPrefs === "string") {
|
||
|
lastColor = storedPrefs;
|
||
|
return storedPrefs;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return "slate"; // slate as the default color;
|
||
|
};
|
||
|
|
||
|
export const ColorContext = createContext();
|
||
|
|
||
2 years ago
|
export function ColorProvider({ initialTheme, children }) {
|
||
2 years ago
|
const [color, setColor] = useState(getInitialColor);
|
||
|
|
||
|
const rawSetColor = (rawColor) => {
|
||
|
const root = window.document.documentElement;
|
||
|
|
||
|
root.classList.remove(`theme-${lastColor}`);
|
||
|
root.classList.add(`theme-${rawColor}`);
|
||
|
|
||
|
localStorage.setItem("theme-color", rawColor);
|
||
|
|
||
|
lastColor = rawColor;
|
||
|
};
|
||
|
|
||
|
if (initialTheme) {
|
||
|
rawSetColor(initialTheme);
|
||
|
}
|
||
|
|
||
|
useEffect(() => {
|
||
|
rawSetColor(color);
|
||
|
}, [color]);
|
||
|
|
||
2 years ago
|
const value = useMemo(() => ({ color, setColor }), [color]);
|
||
|
|
||
|
return <ColorContext.Provider value={value}>{children}</ColorContext.Provider>;
|
||
|
}
|