Skip to content

Refactor event listener syntax for dark mode media query in ThemeManager #6443

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

Open
wants to merge 3 commits into
base: master
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
54 changes: 39 additions & 15 deletions src/html.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from "react";
import PropTypes from "prop-types";


export default function HTML(props) {
return (
<html lang="en" {...props.htmlAttributes}>
Expand All @@ -24,20 +23,45 @@ export default function HTML(props) {
{props.headComponents}
</head>
<body {...props.bodyAttributes}>
<script dangerouslySetInnerHTML={{
__html:
`(function() {
try {
var banner = sessionStorage.getItem('banner');
if (banner === null)
document.body.classList.add('banner1');
else
document.body.classList.add('banner' + banner);
} catch (e) {
return;
}
})();`,
}}
{/* Script for theme initialization - needs to run before React renders to prevent flicker */}
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
// Theme initialization
const darkThemeKey = 'theme';
let initialTheme = 'system';
try {
initialTheme = localStorage.getItem(darkThemeKey) || 'system';
} catch (e) {}

// Determine initial dark mode
let isDarkMode = false;
if (initialTheme === 'dark') {
isDarkMode = true;
} else if (initialTheme === 'system') {
isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

// Set initial color mode
document.documentElement.style.setProperty(
'--initial-color-mode',
isDarkMode ? 'dark' : 'light'
);

// Banner initialization
var banner = sessionStorage.getItem('banner');
if (banner === null)
document.body.classList.add('banner1');
else
document.body.classList.add('banner' + banner);
} catch (e) {
console.error('Error in theme initialization:', e);
}
})();
`,
}}
/>
{props.preBodyComponents}
<div
Expand Down
8 changes: 7 additions & 1 deletion src/theme/app/StyledThemeProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@ import React, { useContext } from "react";
import { ThemeProvider } from "styled-components";
import { ThemeManagerContext } from "./ThemeManager";

// Safe check for browser environment
const isBrowser = typeof window !== "undefined";

export const StyledThemeProvider = (props) => {
const { children, darkTheme, lightTheme } = props;
const { isDark, didLoad } = useContext(ThemeManagerContext);

// For SSR, we need to provide a consistent theme initially
// This ensures the server and client render the same thing initially
const currentTheme = isDark ? darkTheme : lightTheme;
const theme = {
...(didLoad ? currentTheme : transformTheme(currentTheme)),
...(didLoad || !isBrowser ? currentTheme : transformTheme(currentTheme)),
};

return (
Expand Down
23 changes: 21 additions & 2 deletions src/theme/app/ThemeManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@ const defaultState = {

export const ThemeManagerContext = createContext(defaultState);

// Safe check for browser environment
const isBrowser = typeof window !== "undefined";

const systemDarkModeSetting = () =>
window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null;
isBrowser && window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null;
const isDarkModeActive = () => {
// Assume that dark mode is not active if there's no system dark mode setting available
return !!systemDarkModeSetting()?.matches;
Expand All @@ -36,15 +39,29 @@ export const ThemeManagerProvider = (props) => {
const [isDark, setIsDark] = useState(false);

useEffect(() => {
if (!isBrowser) return;

const root = window.document.documentElement;
const initialColorValue = root.style.getPropertyValue(
"--initial-color-mode"
);
setIsDark(initialColorValue === ThemeSetting.DARK);
setDidLoad(true);
}, []);

// Add listener for system color scheme changes
const darkModeMediaQuery = systemDarkModeSetting();
if (darkModeMediaQuery && themeSetting === ThemeSetting.SYSTEM) {
const handleChange = (e) => {
setIsDark(e.matches);
};
darkModeMediaQuery.addEventListener("change", handleChange);
return () => darkModeMediaQuery.removeEventListener("change", handleChange);
}
}, [themeSetting]);

const toggleDark = (value) => {
if (!isBrowser) return;

const newIsDark = value ?? !isDark;
const theme = newIsDark ? ThemeSetting.DARK : ThemeSetting.LIGHT;
setIsDark(newIsDark);
Expand All @@ -53,6 +70,8 @@ export const ThemeManagerProvider = (props) => {
};

const changeThemeSetting = (setting) => {
if (!isBrowser) return;

switch (setting) {
case ThemeSetting.SYSTEM: {
setIsDark(isDarkModeActive());
Expand Down
Loading