Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [ts-starter #6] implement theming infrastructure #10

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
"test:unit": "jest test/unit",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"

},
"keywords": [],
"author": "",
Expand Down Expand Up @@ -71,6 +70,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.13",
"sanitize.css": "^13.0.0",
"styled-components": "^6.1.8"
}
}
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 5 additions & 11 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { memo } from "react";
import styled from "styled-components";
import GlobalStyles from "./globalStyles";

const Title = styled.h1`
color: #666;
`;
import ThemeProvider from "./components/ThemeProvider";
import TestPage from "./pages/test";

function App() {
return (
<>
<GlobalStyles />
<Title>Welcome</Title>
<p>Use this as a starting point to develop your own application :-)</p>
</>
<ThemeProvider>
<TestPage />
</ThemeProvider>
);
}

Expand Down
25 changes: 25 additions & 0 deletions src/components/ThemeProvider/globalStyles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createGlobalStyle } from "styled-components";
// import "./reset.css";

const GlobalStyles = createGlobalStyle`
:root {
font-size: 14px;
font-family:"Roboto", sans-serif;

--color-primary: ${props => props.theme.colorPrimary};
--color-link: ${props => props.theme.colorLink};
--color-bg-container: ${props => props.theme.colorBgContainer};
--color-bg-elevated: ${props => props.theme.colorBgElevated};
--color-text: ${props => props.theme.colorText};
--color-text-secondary: ${props => props.theme.colorTextSecondary};
--color-white: ${props => props.theme.colorWhite};
}

body {
margin: 0;
padding: 1rem;
font-family: Open-Sans, Helvetica, Sans-Serif;
}
`;

export default GlobalStyles;
103 changes: 103 additions & 0 deletions src/components/ThemeProvider/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import {
createContext,
useState,
type PropsWithChildren,
type ReactElement,
useContext,
useEffect,
useCallback,
} from "react";
import { ThemeProvider as ScThemeProvider } from "styled-components";
import type { EmptyObject } from "../../types";
import GlobalStyles from "./globalStyles";
import { darkTheme, lightTheme } from "./theme";
import type { DefaultTheme } from "styled-components/dist/types";
import { throwError } from "../../utils/errorHandling";

export type Theme = "system" | "light" | "dark";
const supportedThemes: Theme[] = ["system", "light", "dark"];

interface ThemeContextType {
selectTheme: (theme: Theme) => void;
supportedThemes: Theme[];
currentThemeName: Theme;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function useThemeContext(): ThemeContextType {
return (
useContext(ThemeContext) ?? throwError("Theme context must be initialized")
);
}

const getStoredTheme = (): Theme => {
let theme = localStorage.getItem("theme") as Theme | null;
if (theme === null) {
localStorage.setItem("theme", "system");
theme = "system";
}
return theme;
};

export default function ThemeProvider({
children,
}: PropsWithChildren<EmptyObject>): ReactElement {
const [currentThemeName, setCurrentThemeName] =
useState<Theme>(getStoredTheme());
const [currentTheme, setCurrentTheme] = useState(() =>
selectInitialTheme(currentThemeName),
);

const selectInitialTheme = useCallback((theme: Theme) => {
if (theme === "system") {
return detectSystemTheme();
} else if (theme === "dark") {
return darkTheme;
} else {
return lightTheme;
}
}, []);

const selectTheme = useCallback(
(theme: Theme) => {
setCurrentThemeName(theme);
localStorage.setItem("theme", theme);
setCurrentTheme(selectInitialTheme(theme));
},
[selectInitialTheme],
);

function detectSystemTheme(): DefaultTheme {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
return darkTheme;
} else {
return lightTheme;
}
}

useEffect(() => {
const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (currentThemeName === "system") {
setCurrentTheme(detectSystemTheme());
}
};
mediaQueryList.addEventListener("change", handleChange);
return () => mediaQueryList.removeEventListener("change", handleChange);
}, [currentThemeName]);

return (
<ThemeContext.Provider
value={{
selectTheme,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • memoize value

Passing value unmemoized is a horrible thing to do. Every component that makes use of the theme object will be rerendered everytime App.tsx is rerendered because of this. value absolutely must be memoized for that not to happen! You need to know where not memoizing things will cascade down and cause a lot of unnecessary rerenders. Contexts, especially those high up the react tree are one of those candidates.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The selectTheme function has been created using useCallback. I thought that should be enough to prevent the reference from changing.

supportedThemes,
currentThemeName,
}}
>
<ScThemeProvider theme={currentTheme}>
<GlobalStyles />
{children}
</ScThemeProvider>
</ThemeContext.Provider>
);
}
20 changes: 20 additions & 0 deletions src/components/ThemeProvider/reset.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
@import "~sanitize.css";

ul {
margin: 0;
padding: 0;
list-style: none;
}

h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
}

p {
margin: 0;
}
25 changes: 25 additions & 0 deletions src/components/ThemeProvider/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { DefaultTheme } from "styled-components";

const defaultTheme: DefaultTheme = {
colorPrimary: "#000000",
colorLink: "#1c64ff",
colorBgContainer: "#f0f0f0",
colorBgElevated: "#e5e5e5",
colorText: "#000000",
colorTextSecondary: "#888888",
colorWhite: "#ffffff",
};

export const lightTheme: DefaultTheme = {
...defaultTheme,
};

export const darkTheme: DefaultTheme = {
...defaultTheme,
colorPrimary: "#ededed",
colorLink: "#48baf7",
colorBgContainer: "#3d3d3d",
colorBgElevated: "#333333",
colorText: "#ffffff",
colorTextSecondary: "#888888",
};
12 changes: 0 additions & 12 deletions src/globalStyles.ts

This file was deleted.

107 changes: 107 additions & 0 deletions src/pages/test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import type { ReactElement } from "react";
import styled from "styled-components";
import { useThemeContext } from "../components/ThemeProvider";
import type { Theme } from "../components/ThemeProvider";

const MainContainer = styled.div`
background: var(--color-bg-container);
display: flex;
flex-direction: column;
align-items: center;
`;

const MainSection = styled.div`
background: var(--color-bg-elevated);
margin: 40px;
width: 50%;
padding: 20px;
`;

const Header = styled.div`
background: var(--color-bg-elevated);
display: flex;
`;

const Menu = styled.ul`
display: flex;
gap: 40px;
margin: 10px 5px;

a {
text-decoration: none;
}
`;

const MainTitle = styled.h1`
color: var(--color-text);
text-align: center;
`;

const SubTitle = styled.h2`
color: var(--color-text-secondary);
text-align: center;
`;

const Link = styled.a`
color: var(--color-link);
`;

const TypographySample = styled.p`
color: var(--color-text);
`;

export default function TestPage(): ReactElement {
const themeContext = useThemeContext();

const handleThemeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
themeContext.selectTheme(event.target.value as Theme);
};

return (
<MainContainer>
<MainTitle>The Main Title</MainTitle>
<SubTitle>This page has been created for testing themes</SubTitle>
<Header>
<Menu>
<li>
<Link href="#">Home</Link>
</li>
<li>
<Link href="#">Products</Link>
</li>
<li>
<Link href="#">Contact</Link>
</li>
<li>
<Link href="#">About us</Link>
</li>
</Menu>
</Header>
<MainSection>
<select
id="themeSelect"
value={themeContext.currentThemeName}
onChange={handleThemeChange}
>
{themeContext.supportedThemes.map(theme => (
<option value={theme} key={theme}>
{theme}
</option>
))}
</select>
<TypographySample>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio
facilis repudiandae enim corporis quod molestias eius nostrum quos
dolore, ipsum animi quo, in neque, architecto iure sed ratione
recusandae optio. Cumque officiis tempore culpa tenetur? Ipsa quam
obcaecati nisi quae labore aperiam recusandae aliquam quibusdam,
quaerat dolorem, veniam in neque? Et beatae voluptas mollitia quod
unde sint odit dolorum. Fugiat! Temporibus et aspernatur laudantium
dolores ex illum quis, amet consectetur ipsa, at delectus voluptatibus
enim obcaecati quod. Beatae aperiam, atque delectus incidunt suscipit,
nemo error minus tempora quos, saepe obcaecati.
</TypographySample>
</MainSection>
</MainContainer>
);
}
18 changes: 16 additions & 2 deletions src/styled.d.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
import "styled-components";

// see https://styled-components.com/docs/api#usage-with-typescript
import {} from "styled-components/cssprop";
import type { CSSProp } from "styled-components/cssprop";

declare module "react" {
interface Attributes {
css?: CSSProp;
}
}

// see https://styled-components.com/docs/api#create-a-declarations-file
declare module "styled-components" {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DefaultTheme {}
export interface DefaultTheme {
colorPrimary: string;
colorLink: string;
colorBgContainer: string;
colorBgElevated: string;
colorText: string;
colorTextSecondary: string;
colorWhite: string;
}
}
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type EmptyObject = Record<never, never>;
7 changes: 7 additions & 0 deletions src/utils/errorHandling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function throwError(reason: string): never {
throw Error(reason);
}

export function mustNotHappen(): never {
throwError("This is a bug. Please report it.");
}
Loading