fix(share): flash while theme is loading

This commit is contained in:
Elian Doran 2025-10-29 19:00:03 +02:00
parent b06aa29ea3
commit eeec3e440d
No known key found for this signature in database
3 changed files with 15 additions and 22 deletions

View File

@ -1,12 +1,11 @@
const themeToLoad = getThemeToLoad();
setTheme(themeToLoad);
const themeRootEl = document.documentElement;
export default function setupThemeSelector() {
const themeSwitch: HTMLInputElement = document.querySelector(".theme-selection input")!;
const themeSelection: HTMLDivElement = document.querySelector(".theme-selection")!;
themeSelection.classList.add("no-transition");
themeSwitch.checked = (themeToLoad === "dark");
themeSwitch.checked = (themeRootEl.classList.contains("theme-dark"));
setTimeout(() => themeSelection.classList.remove("no-transition"), 400);
themeSwitch?.addEventListener("change", () => {
@ -18,23 +17,10 @@ export default function setupThemeSelector() {
function setTheme(theme: string) {
if (theme === "dark") {
document.body.classList.add("theme-dark");
document.body.classList.remove("theme-light");
themeRootEl.classList.add("theme-dark");
themeRootEl.classList.remove("theme-light");
} else {
document.body.classList.remove("theme-dark");
document.body.classList.add("theme-light");
}
}
function getThemeToLoad() {
const storedTheme = localStorage.getItem("theme");
if (storedTheme) {
// Respect user's choice if one has already been made.
return storedTheme;
} else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// Fallback to browser's color preference otherwise.
return "dark";
} else {
return "light";
themeRootEl.classList.remove("theme-dark");
themeRootEl.classList.add("theme-light");
}
}

View File

@ -30,7 +30,7 @@ Accent Color Ideas
--text-link: #FFB628;
*/
body.theme-light {
html.theme-light {
--background-primary: #FFFFFF;
--background-secondary: #F3F3F3;
--background-highlight: #DDDDDD;
@ -42,7 +42,7 @@ body.theme-light {
color-scheme: light;
}
body.theme-dark {
html.theme-dark {
--background-primary: #333333;
--background-secondary: #1F1F1F;
--background-highlight: #484848;

View File

@ -55,6 +55,13 @@
%>
<title><%= pageTitle %></title>
<script>
// Load dark/light theme as soon as possible to avoid color flashes.
let theme = localStorage.getItem("theme");
if (!theme) {
theme = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light";
}
document.documentElement.classList.add(`theme-${theme}`);
window.glob = {
isStatic: <%= !!isStatic %>
};