mirror of
https://github.com/vercel/commerce.git
synced 2025-07-31 05:51:23 +00:00
.github
.vscode
@
app
components
cart
grid
icons
layout
product
store
themeContext.tsx
carousel.tsx
combox.tsx
label.tsx
loading-dots.tsx
logo-square.tsx
logo-type.tsx
opengraph-image.tsx
price.tsx
prose.tsx
constants
fonts
lib
public
.env.example
.eslintrc.js
.gitignore
.nvmrc
.prettierignore
README.md
components.json
license.md
next.config.js
package.json
pnpm-lock.yaml
postcss.config.js
prettier.config.js
tailwind.config.js
tsconfig.json
63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import { createContext, ReactElement, useEffect, useState } from "react";
|
|
|
|
const ThemeContext = createContext({
|
|
isDarkTheme: true,
|
|
toggleThemeHandler: () => {},
|
|
});
|
|
|
|
interface ThemePropsInterface {
|
|
children?: JSX.Element | Array<JSX.Element>;
|
|
}
|
|
|
|
export function MyThemeContextProvider(
|
|
props: ThemePropsInterface
|
|
): ReactElement {
|
|
const [isDarkTheme, setIsDarkTheme] = useState(true);
|
|
useEffect(() => initialThemeHandler());
|
|
|
|
function isLocalStorageEmpty(): boolean {
|
|
return !localStorage.getItem("isDarkTheme");
|
|
}
|
|
|
|
function initialThemeHandler(): void {
|
|
if (isLocalStorageEmpty()) {
|
|
localStorage.setItem("isDarkTheme", `true`);
|
|
document!.querySelector("body")!.classList.add("dark");
|
|
setIsDarkTheme(true);
|
|
} else {
|
|
const isDarkTheme: boolean = JSON.parse(
|
|
localStorage.getItem("isDarkTheme")!
|
|
);
|
|
isDarkTheme && document!.querySelector("body")!.classList.add("dark");
|
|
setIsDarkTheme(() => {
|
|
return isDarkTheme;
|
|
});
|
|
}
|
|
}
|
|
|
|
function toggleThemeHandler(): void {
|
|
const isDarkTheme: boolean = JSON.parse(
|
|
localStorage.getItem("isDarkTheme")!
|
|
);
|
|
setIsDarkTheme(!isDarkTheme);
|
|
toggleDarkClassToBody();
|
|
setValueToLocalStorage();
|
|
}
|
|
|
|
function toggleDarkClassToBody(): void {
|
|
document!.querySelector("body")!.classList.toggle("dark");
|
|
}
|
|
|
|
function setValueToLocalStorage(): void {
|
|
localStorage.setItem("isDarkTheme", `${!isDarkTheme}`);
|
|
}
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ isDarkTheme: true, toggleThemeHandler }}>
|
|
{props.children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
}
|
|
|
|
export default ThemeContext;
|