fix(client): initialize theme during gatsby SSR (#61922)

This commit is contained in:
Huyen Nguyen
2025-08-25 21:35:14 +07:00
committed by GitHub
parent df9b21146f
commit 79f3ee2844
2 changed files with 40 additions and 1 deletions
+33
View File
@@ -62,3 +62,36 @@ export function getPostBodyComponents(superblock: string): JSX.Element[] {
return scripts.filter(Boolean);
}
export function getPreBodyThemeScript(): JSX.Element[] {
const script = (
<script
key='prebody-theme-init'
dangerouslySetInnerHTML={{
__html: `
(function(){
let theme = 'light';
const localTheme = localStorage.getItem('theme');
if (localTheme !== null) {
theme = localTheme === 'dark' ? 'dark' : 'light';
} else if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
theme = 'dark';
}
const bodyEl = document && document.body;
if (bodyEl && bodyEl.classList) {
bodyEl.classList.remove('light-palette');
bodyEl.classList.remove('dark-palette');
bodyEl.classList.add(theme + '-palette');
}
})();`
}}
/>
);
return [script];
}