Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Avoid repeated theme DOM sync during startup (#2779)

Mika Cohen20f37f367a14
diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts
index 78d063a96..eec2e9c93 100644
--- a/apps/web/src/hooks/useTheme.ts
+++ b/apps/web/src/hooks/useTheme.ts
@@ -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);
};
}