Skip to content

Commit

Permalink
apply light/dark theme immediately as ims.js is run
Browse files Browse the repository at this point in the history
this prevents the flickering seen in the current approach, since
it waits until after the body is drawn to determine whether the
page should be light or dark
  • Loading branch information
srabraham committed Dec 11, 2024
1 parent 25313fc commit effb10d
Showing 1 changed file with 20 additions and 20 deletions.
40 changes: 20 additions & 20 deletions src/ims/element/static/ims.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,29 +17,25 @@
//
// Adapted from https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript
// Under Creative Commons Attribution 3.0 Unported License
const getStoredTheme = () => localStorage.getItem("theme");
const setStoredTheme = theme => localStorage.setItem("theme", theme);
const getPreferredTheme = () => {
const storedTheme = getStoredTheme();
if (storedTheme) {
return storedTheme;
}
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
};
const setTheme = theme => {
if (theme === "auto") {
document.documentElement.setAttribute("data-bs-theme", (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"));
} else {
document.documentElement.setAttribute("data-bs-theme", theme);
}
};
function applyTheme() {
"use strict";

const getStoredTheme = () => localStorage.getItem("theme");
const setStoredTheme = theme => localStorage.setItem("theme", theme);

const getPreferredTheme = () => {
const storedTheme = getStoredTheme();
if (storedTheme) {
return storedTheme;
}

return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
};

const setTheme = theme => {
if (theme === "auto") {
document.documentElement.setAttribute("data-bs-theme", (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"));
} else {
document.documentElement.setAttribute("data-bs-theme", theme);
}
};

setTheme(getPreferredTheme());

const showActiveTheme = (theme, focus = false) => {
Expand Down Expand Up @@ -88,6 +84,10 @@ function applyTheme() {
});
});
}
// Set the theme immediately, before the rest of the page loads. We need to come back later
// to invoke applyTheme(), as that will only work once the navbar has been drawn (with its
// dropdown theme selector.
setTheme(getPreferredTheme());


//
Expand Down

0 comments on commit effb10d

Please sign in to comment.