mirror of
https://github.com/DI0IK/homepage-plus.git
synced 2025-07-13 08:20:34 +00:00
add theme switcher
This commit is contained in:
parent
5711b22b4e
commit
1b2fa720c6
8 changed files with 469 additions and 53 deletions
42
src/utils/color-context.js
Normal file
42
src/utils/color-context.js
Normal file
|
@ -0,0 +1,42 @@
|
|||
import { createContext, useState, useEffect } from "react";
|
||||
|
||||
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();
|
||||
|
||||
export const ColorProvider = ({ initialTheme, children }) => {
|
||||
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]);
|
||||
|
||||
return <ColorContext.Provider value={{ color, setColor }}>{children}</ColorContext.Provider>;
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue