Skip to content

Commit

Permalink
Add guard to localStorage access, to avoid SSR violations in CI build
Browse files Browse the repository at this point in the history
  • Loading branch information
holly-cummins committed May 16, 2024
1 parent 48bd6c1 commit e03d2b7
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/components/util/dark-mode-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,22 @@ const dark = "dark"
const system = "system"

export function getDisplayModeFromLocalStorageNoDefault() {
return localStorage.getItem(localStorageKey)
if (typeof localStorage !== `undefined`) {
return localStorage.getItem(localStorageKey)
}
}

export const getDisplayModeFromLocalStorage = () => {
return getDisplayModeFromLocalStorageNoDefault() || light
}

function adjustCssClasses(storedTheme) {
if (storedTheme === dark || (storedTheme === system && prefersDarkMode())) {
document.documentElement.classList.add(dark)
} else {
document.documentElement.classList.remove(dark)
if (typeof document !== `undefined`) {
if (storedTheme === dark || (storedTheme === system && prefersDarkMode())) {
document.documentElement.classList.add(dark)
} else {
document.documentElement.classList.remove(dark)
}
}
}

Expand All @@ -29,8 +33,10 @@ export const initialiseDisplayModeFromLocalStorage = () => {
}

export const setDisplayMode = (newTheme) => {
localStorage.setItem(localStorageKey, newTheme)
adjustCssClasses(newTheme)
const themeMetadata = document.querySelector("meta[name=\"theme-color\"]")
if (themeMetadata) themeMetadata.content = newTheme
if (typeof localStorage !== `undefined`) {
localStorage.setItem(localStorageKey, newTheme)
adjustCssClasses(newTheme)
const themeMetadata = document.querySelector("meta[name=\"theme-color\"]")
if (themeMetadata) themeMetadata.content = newTheme
}
}

0 comments on commit e03d2b7

Please sign in to comment.