Skip to content

Commit

Permalink
feat(system-theme): add listener to update theme whenever system pref…
Browse files Browse the repository at this point in the history
…erences change
  • Loading branch information
wallpants committed Jun 5, 2024
1 parent 57f3533 commit b1f286a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
2 changes: 1 addition & 1 deletion app/.eslintrc.cjs → .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module.exports = {
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
project: [__dirname + "/tsconfig.json"],
project: [__dirname + "/app/tsconfig.json"],
},
extends: [
"eslint:recommended",
Expand Down
33 changes: 27 additions & 6 deletions app/web/components/theme-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext, useLayoutEffect, type ReactNode } from "react";
import { useCallback, useContext, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
import { type Theme } from "../../types";
import { myMermaid } from "./markdown/mermaid";
import { websocketContext } from "./websocket-provider/context";
Expand All @@ -12,8 +12,8 @@ export function ThemeProvider({ children, THEME }: { children: ReactNode; THEME:
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}

useLayoutEffect(() => {
function handleThemeChange(newTheme: "light" | "dark") {
const handleThemeChange = useCallback(
(newTheme: "light" | "dark") => {
const rootHtml = document.getElementsByTagName("html")[0]!;
let className = "pantsdown " + newTheme;
if (high_contrast) className += " high-contrast";
Expand All @@ -23,12 +23,33 @@ export function ThemeProvider({ children, THEME }: { children: ReactNode; THEME:
theme: newTheme === "light" ? "default" : "dark",
});
if (currentPath) wsRequest({ type: "get_entry", path: currentPath });
}
},
[currentPath, high_contrast, wsRequest],
);

useLayoutEffect(() => {
if (theme === "system") handleThemeChange(getSystemTheme());
else handleThemeChange(theme);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [theme, high_contrast, wsRequest]);
}, [theme, handleThemeChange]);

const changeEventHandler = useRef((event: MediaQueryListEvent) => {
const newTheme = event.matches ? "dark" : "light";
wsRequest({ type: "update_config", action: ["theme_name", "system"] });
handleThemeChange(newTheme);
});

useEffect(() => {
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", changeEventHandler.current);

return () => {
window
.matchMedia("(prefers-color-scheme: dark)")
// eslint-disable-next-line
.removeEventListener("change", changeEventHandler.current);
};
}, [changeEventHandler]);

return children;
}
Binary file modified bun.lockb
Binary file not shown.

0 comments on commit b1f286a

Please sign in to comment.