Skip to content

Commit 1813fa4

Browse files
authored
Merge pull request #645 from AliAkrem/main
fix: allow theme state to be persisted
2 parents 879b11e + d797ff5 commit 1813fa4

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

web/src/components/top-bar.tsx

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React from "react";
2-
import { useMemo } from "react";
2+
import { useMemo, useLayoutEffect, useState, useCallback } from "react";
33
import { useLocation } from "react-router-dom";
44
import logoWide from "src/assets/svg/logo-wide.svg";
55
import logoSquare from "src/assets/svg/logo-square.svg";
@@ -41,6 +41,26 @@ export function TopBar({ version, links }: TopBarProps): JSX.Element {
4141

4242
const { localize } = useLocale();
4343

44+
const [isDark, setIsDark] = useState(() => {
45+
const savedTheme = localStorage.getItem("theme");
46+
const isDark = savedTheme === "dark";
47+
return savedTheme ? isDark : true; // default should be dark
48+
});
49+
50+
useLayoutEffect(() => {
51+
const theme = localStorage.getItem("theme");
52+
if (theme) {
53+
document.documentElement.setAttribute("data-theme", theme);
54+
}
55+
}, []);
56+
57+
const toggleTheme = useCallback(() => {
58+
const newTheme = isDark ? "light" : "dark";
59+
setIsDark(!isDark);
60+
localStorage.setItem("theme", newTheme);
61+
document.documentElement.setAttribute("data-theme", newTheme);
62+
}, [isDark, setIsDark]);
63+
4464
return (
4565
<div className="bg-neutral">
4666
<div className="m-auto flex max-w-7xl flex-row gap-4 p-4 items-center">
@@ -113,10 +133,12 @@ export function TopBar({ version, links }: TopBarProps): JSX.Element {
113133
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
114134
</svg>
115135
<input
136+
onClick={toggleTheme}
116137
id="theme-toggle"
117138
type="checkbox"
118139
value="dzcodeLight"
119140
className="theme-controller toggle"
141+
checked={!isDark}
120142
/>
121143
<svg
122144
xmlns="http://www.w3.org/2000/svg"

0 commit comments

Comments
 (0)