Skip to content

Commit

Permalink
Make theme-color meta tag follow the app theme
Browse files Browse the repository at this point in the history
  • Loading branch information
Zwyx committed Apr 2, 2024
1 parent 3412bc7 commit beb5280
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 24 deletions.
22 changes: 13 additions & 9 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -201,19 +201,23 @@

var lightThemeName = "light";
var darkThemeName = "dark";

var storedTheme = localStorage.getItem("theme");
var theme;

try {
theme = localStorage.getItem("theme");
} catch {}

if (theme === lightThemeName || theme === darkThemeName) {
document.documentElement.classList.add(theme);
if (storedTheme === lightThemeName || storedTheme === darkThemeName) {
theme = storedTheme;
} else if (matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.classList.add(darkThemeName);
theme = darkThemeName;
} else {
document.documentElement.classList.add(lightThemeName);
theme = lightThemeName;
}

document.documentElement.classList.add(theme);

if (theme === lightThemeName) {
document
.querySelector('meta[name="theme-color"]')
?.setAttribute("content", "#ffffff");
}
</script>
</head>
Expand Down
29 changes: 14 additions & 15 deletions src/lib/ThemeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,20 @@ export const ThemeContextProvider = ({ children }: { children: ReactNode }) => {
}, [themeChoice]);

useEffect(() => {
if (themeScheme === "light") {
if (!document.documentElement.classList.contains(lightThemeName)) {
document.documentElement.classList.add(lightThemeName);
}
if (document.documentElement.classList.contains(darkThemeName)) {
document.documentElement.classList.remove(darkThemeName);
}
} else {
if (!document.documentElement.classList.contains(darkThemeName)) {
document.documentElement.classList.add(darkThemeName);
}
if (document.documentElement.classList.contains(lightThemeName)) {
document.documentElement.classList.remove(lightThemeName);
}
}
document.documentElement.classList.add(
themeScheme === "light" ? lightThemeName : darkThemeName,
);

document.documentElement.classList.remove(
themeScheme === "light" ? darkThemeName : lightThemeName,
);

document
.querySelector('meta[name="theme-color"]')
?.setAttribute(
"content",
themeScheme === "light" ? "#ffffff" : "#020817",
);
}, [themeScheme]);

const updateThemeChoice = useCallback((newThemeChoice: ThemeChoice) => {
Expand Down

0 comments on commit beb5280

Please sign in to comment.