Avoid repeated theme DOM sync during startup (#2779)

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Mika CohenandJulius Marminge authored and GitHub committed 2026-06-19 05:46:12 +00:00
1 parent 804d44cfb1
commit 20f37f367a
1 file changed
+17 -5
+17 -5
View File
@@ -18,6 +18,7 @@ const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
let lastDesktopTheme: Theme | null = null;
let lastAppliedTheme: ThemeSnapshot | null = null;
function emitChange() {
for (const listener of listeners) listener();
@@ -28,7 +29,11 @@ function hasThemeStorage() {
}
function getSystemDark() {
return typeof window !== "undefined" && window.matchMedia(MEDIA_QUERY).matches;
return (
typeof window !== "undefined" &&
typeof window.matchMedia === "function" &&
window.matchMedia(MEDIA_QUERY).matches
);
}
function getStored(): Theme {
@@ -89,11 +94,18 @@ export function syncBrowserChromeTheme() {
function applyTheme(theme: Theme, suppressTransitions = false) {
if (typeof document === "undefined" || typeof window === "undefined") return;
const systemDark = theme === "system" ? getSystemDark() : false;
if (lastAppliedTheme?.theme === theme && lastAppliedTheme.systemDark === systemDark) {
syncDesktopTheme(theme);
return;
}
if (suppressTransitions) {
document.documentElement.classList.add("no-transitions");
}
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
const isDark = theme === "dark" || (theme === "system" && systemDark);
document.documentElement.classList.toggle("dark", isDark);
lastAppliedTheme = { theme, systemDark };
syncBrowserChromeTheme();
syncDesktopTheme(theme);
if (suppressTransitions) {
@@ -148,12 +160,12 @@ function subscribe(listener: () => void): () => void {
listeners.push(listener);
// Listen for system preference changes
const mq = window.matchMedia(MEDIA_QUERY);
const mq = typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY) : null;
const handleChange = () => {
if (getStored() === "system") applyTheme("system", true);
emitChange();
};
mq.addEventListener("change", handleChange);
mq?.addEventListener("change", handleChange);
// Listen for storage changes from other tabs
const handleStorage = (e: StorageEvent) => {
@@ -166,7 +178,7 @@ function subscribe(listener: () => void): () => void {
return () => {
listeners = listeners.filter((l) => l !== listener);
mq.removeEventListener("change", handleChange);
mq?.removeEventListener("change", handleChange);
window.removeEventListener("storage", handleStorage);
};
}