Skip to content

Build your personal knowledge base with Trilium Notes

refactor(share): reduce duplication in theme management

Elian Doran1c832182d6ab
diff --git a/packages/share-theme/src/scripts/modules/theme.ts b/packages/share-theme/src/scripts/modules/theme.ts
index 27aa517371..36e7585ba6 100644
--- a/packages/share-theme/src/scripts/modules/theme.ts
+++ b/packages/share-theme/src/scripts/modules/theme.ts
@@ -1,11 +1,5 @@
const themeToLoad = getThemeToLoad();
-if (themeToLoad === "dark") {
- document.body.classList.add("theme-dark");
- document.body.classList.remove("theme-light");
-} else {
- document.body.classList.remove("theme-dark");
- document.body.classList.add("theme-light");
-}
+setTheme(themeToLoad);
export default function setupThemeSelector() {
const themeSwitch: HTMLInputElement = document.querySelector(".theme-selection input")!;
@@ -16,25 +10,31 @@ export default function setupThemeSelector() {
setTimeout(() => themeSelection.classList.remove("no-transition"), 400);
themeSwitch?.addEventListener("change", () => {
- if (themeSwitch.checked) {
- document.body.classList.add("theme-dark");
- document.body.classList.remove("theme-light");
- localStorage.setItem("theme", "dark");
- } else {
- document.body.classList.remove("theme-dark");
- document.body.classList.add("theme-light");
- localStorage.setItem("theme", "light");
- }
+ const theme = themeSwitch.checked ? "dark" : "light";
+ setTheme(theme);
+ localStorage.setItem("theme", theme);
});
}
+function setTheme(theme: string) {
+ if (theme === "dark") {
+ document.body.classList.add("theme-dark");
+ document.body.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) {
+ } else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// Fallback to browser's color preference otherwise.
- return window.matchMedia('(prefers-color-scheme: dark)').matches;
+ return "dark";
+ } else {
+ return "light";
}
}