Skip to content

Commit 6ed187e

Browse files
committed
Ensure color scheme updates propagate after theme toggle
1 parent 6247a6b commit 6ed187e

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

no-flash-color-mode-plugin.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,17 @@ export default function noFlashColorModePlugin(context) {
3131
document.documentElement.setAttribute('data-theme', theme);
3232
document.documentElement.setAttribute('data-theme-choice', storedTheme || (respectPrefersColorScheme ? 'system' : defaultMode));
3333
document.documentElement.style.colorScheme = theme;
34+
if (document.body) {
35+
document.body.style.colorScheme = theme;
36+
}
3437
3538
var observer = new MutationObserver(function() {
3639
var newTheme = document.documentElement.getAttribute('data-theme');
3740
if (newTheme) {
3841
document.documentElement.style.colorScheme = newTheme;
42+
if (document.body) {
43+
document.body.style.colorScheme = newTheme;
44+
}
3945
}
4046
});
4147

src/theme/Root.tsx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import React, {type PropsWithChildren, useEffect} from 'react';
2+
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
3+
4+
function applyColorScheme(nextTheme: string | null | undefined) {
5+
if (!ExecutionEnvironment.canUseDOM || !nextTheme) {
6+
return;
7+
}
8+
9+
const resolvedTheme = nextTheme === 'dark' ? 'dark' : 'light';
10+
document.documentElement.style.colorScheme = resolvedTheme;
11+
if (document.body) {
12+
document.body.style.colorScheme = resolvedTheme;
13+
}
14+
}
15+
16+
export default function Root({children}: PropsWithChildren): JSX.Element {
17+
useEffect(() => {
18+
if (!ExecutionEnvironment.canUseDOM) {
19+
return undefined;
20+
}
21+
22+
applyColorScheme(document.documentElement.getAttribute('data-theme'));
23+
24+
const observer = new MutationObserver(() => {
25+
applyColorScheme(document.documentElement.getAttribute('data-theme'));
26+
});
27+
28+
observer.observe(document.documentElement, {
29+
attributes: true,
30+
attributeFilter: ['data-theme'],
31+
});
32+
33+
return () => observer.disconnect();
34+
}, []);
35+
36+
return <>{children}</>;
37+
}

0 commit comments

Comments
 (0)