Merge branch 'homepage-refactoring' into 'dev'
Homepage Refactoring - Pt .3 See merge request rheinsw/website!28
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
"use client";
|
||||
'use client';
|
||||
|
||||
import { createContext, useEffect, useState } from "react";
|
||||
import {createContext, useEffect, useState} from "react";
|
||||
import Cookies from "js-cookie";
|
||||
|
||||
// Define theme options
|
||||
type ThemeType = "light" | "dark";
|
||||
|
||||
export const ThemeContext = createContext<{
|
||||
@@ -11,43 +10,40 @@ export const ThemeContext = createContext<{
|
||||
toggleTheme: () => void;
|
||||
}>({
|
||||
theme: "light",
|
||||
toggleTheme: () => {},
|
||||
toggleTheme: () => {
|
||||
},
|
||||
});
|
||||
|
||||
export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const [theme, setTheme] = useState<ThemeType>("light");
|
||||
export const ThemeProvider = ({children}: { children: React.ReactNode }) => {
|
||||
const [theme, setTheme] = useState<ThemeType | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Get theme from cookies or system preference
|
||||
const savedTheme = Cookies.get("theme") as ThemeType | undefined;
|
||||
if (savedTheme === "dark" || savedTheme === "light") {
|
||||
setTheme(savedTheme);
|
||||
const saved = Cookies.get("theme") as ThemeType | undefined;
|
||||
if (saved === "dark" || saved === "light") {
|
||||
setTheme(saved);
|
||||
} else {
|
||||
// Detect system preference
|
||||
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
setTheme(prefersDark ? "dark" : "light");
|
||||
Cookies.set("theme", prefersDark ? "dark" : "light", { expires: 365 });
|
||||
const defaultTheme: ThemeType = prefersDark ? "dark" : "light";
|
||||
setTheme(defaultTheme);
|
||||
Cookies.set("theme", defaultTheme, {expires: 365});
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Apply the transition effect when theme changes
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.add("transition-theme");
|
||||
if (!theme) return;
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
|
||||
return () => {
|
||||
document.documentElement.classList.remove("transition-theme");
|
||||
};
|
||||
}, [theme]);
|
||||
|
||||
const toggleTheme = () => {
|
||||
const newTheme: ThemeType = theme === "dark" ? "light" : "dark";
|
||||
setTheme(newTheme);
|
||||
Cookies.set("theme", newTheme, { expires: 365 });
|
||||
const next = theme === "dark" ? "light" : "dark";
|
||||
setTheme(next);
|
||||
Cookies.set("theme", next, {expires: 365});
|
||||
};
|
||||
|
||||
if (!theme) return null;
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
||||
<ThemeContext.Provider value={{theme, toggleTheme}}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user