Compare commits

...
Author SHA1 Message Date
Cursor Agent 57ebd82da6 Fix appearance/settings bugs: remove harmful effect cleanup, fix theme migration ordering, remove redundant reset call
- Remove useEffect cleanup that called removeThemeTokens() in useAppearance,
  which would delete the shared global <style> element when any component
  using the hook unmounted, breaking themes on navigation.

- Move t3code:theme localStorage migration before the OLD_SETTINGS_KEY guard
  in migrateLocalSettingsToServer, so users who already migrated old settings
  (or never had them) still get their theme preference migrated.

- Remove redundant updateSettings() call before resetSettings() in
  useSettingsRestore, since resetSettings already applies all defaults
  including appearance values.
2026-03-29 19:02:02 +00:00
Julius Marminge f4ab7ebe21 Add appearance settings and theme system
- Move theme control into a dedicated appearance settings panel
- Add built-in themes, accent overrides, and desktop IPC sync
- Migrate settings and update components to use unified appearance state
2026-03-29 11:49:29 -07:00
19 changed files with 778 additions and 193 deletions

No files matched your search

+12
View File
@@ -50,6 +50,7 @@ syncShellEnvironment();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const SET_APPEARANCE_CHANNEL = "desktop:set-appearance";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -1160,6 +1161,17 @@ function registerIpcHandlers(): void {
nativeTheme.themeSource = theme;
});
ipcMain.removeHandler(SET_APPEARANCE_CHANNEL);
ipcMain.handle(SET_APPEARANCE_CHANNEL, async (_event, raw: unknown) => {
if (typeof raw !== "object" || raw === null) return;
const appearance = raw as Record<string, unknown>;
const mode = getSafeTheme(appearance.mode);
if (!mode) return;
nativeTheme.themeSource = mode;
// themeId and accentHue are stored for future Electron shell styling
// (title bar tint, vibrancy, etc.)
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
+2
View File
@@ -4,6 +4,7 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const SET_APPEARANCE_CHANNEL = "desktop:set-appearance";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -22,6 +23,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
setAppearance: (appearance) => ipcRenderer.invoke(SET_APPEARANCE_CHANNEL, appearance),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
+2 -2
View File
@@ -20,7 +20,7 @@ import { openInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { readNativeApi } from "../nativeApi";
@@ -236,7 +236,7 @@ function SuspenseShikiCodeBlock({
}
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const markdownComponents = useMemo<Components>(
() => ({
+2 -2
View File
@@ -79,7 +79,7 @@ import {
type TurnDiffSummary,
} from "../types";
import { basenameOfPath } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import BranchToolbar from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
@@ -262,7 +262,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
strict: false,
select: (params) => parseDiffRouteSearch(params),
});
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const composerDraft = useComposerThreadDraft(threadId);
+2 -2
View File
@@ -25,7 +25,7 @@ import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -165,7 +165,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
const settings = useSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
@@ -1,7 +1,7 @@
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
import { useEffect, useMemo, type ReactNode } from "react";
import { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
@@ -29,7 +29,7 @@ function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
}
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const workerPoolSize = useMemo(() => {
const cores =
@@ -60,6 +60,9 @@ function createBaseServerConfig(): ServerConfig {
enableAssistantStreaming: false,
defaultThreadEnvMode: "local" as const,
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
colorMode: "system" as const,
activeThemeId: "t3code",
accentHue: null,
providers: {
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
@@ -0,0 +1,289 @@
import { CheckIcon } from "lucide-react";
import { useCallback, useRef } from "react";
import type { ColorMode } from "@t3tools/contracts/settings";
import { useAppearance } from "../../hooks/useAppearance";
import {
ACCENT_PRESETS,
BUILT_IN_THEMES,
DEFAULT_THEME_ID,
type ThemeDefinition,
type ThemeTokenMap,
} from "../../lib/themes";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import {
SettingResetButton,
SettingsPageContainer,
SettingsRow,
SettingsSection,
} from "./SettingsPanels";
// ── Constants ────────────────────────────────────────────────────
const COLOR_MODE_OPTIONS = [
{ value: "system", label: "System" },
{ value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
] as const;
// ── Swatch preview ──────────────────────────────────────────────
const SWATCH_TOKENS: Array<keyof ThemeTokenMap> = [
"primary",
"destructive",
"success",
"warning",
"info",
];
/** Render 5 small color dots for a theme preview. */
function ThemeSwatch({ tokens }: { tokens: ThemeTokenMap }) {
return (
<div className="flex gap-1.5">
{SWATCH_TOKENS.map((token) => {
const color = tokens[token];
return color ? (
<span
key={token}
className="size-3 rounded-full border border-border/40"
style={{ background: color }}
/>
) : (
<span key={token} className="size-3 rounded-full border border-border/40 bg-muted" />
);
})}
</div>
);
}
// ── Theme card ───────────────────────────────────────────────────
function ThemeCard({
theme,
isSelected,
onSelect,
}: {
theme: ThemeDefinition;
isSelected: boolean;
onSelect: () => void;
}) {
return (
<button
type="button"
aria-pressed={isSelected}
className={cn(
"flex flex-col items-start gap-2 rounded-xl border p-3 text-left transition-colors",
isSelected
? "border-primary bg-primary/5 ring-2 ring-primary/30"
: "border-border bg-card hover:border-primary/40",
)}
onClick={onSelect}
>
<div className="flex w-full items-center justify-between">
<span className="text-sm font-medium text-foreground">{theme.name}</span>
{isSelected ? <CheckIcon className="size-4 text-primary" /> : null}
</div>
<p className="text-xs text-muted-foreground">{theme.description}</p>
<ThemeSwatch tokens={{ ...theme.light, ...theme.dark }} />
</button>
);
}
// ── Accent preset circle ─────────────────────────────────────────
function AccentCircle({
hue,
isSelected,
label,
onClick,
}: {
hue: number;
isSelected: boolean;
label: string;
onClick: () => void;
}) {
return (
<button
type="button"
aria-pressed={isSelected}
aria-label={label}
title={label}
className={cn(
"flex size-8 shrink-0 items-center justify-center rounded-full border-2 transition-shadow",
isSelected
? "border-primary ring-2 ring-primary/30"
: "border-border hover:border-primary/40",
)}
style={{ background: `oklch(0.55 0.2 ${hue})` }}
onClick={onClick}
>
{isSelected ? <CheckIcon className="size-3.5 text-white drop-shadow-sm" /> : null}
</button>
);
}
// ── Main panel ───────────────────────────────────────────────────
export function AppearanceSettingsPanel() {
const { colorMode, activeTheme, accentHue, setColorMode, setThemeId, setAccentHue } =
useAppearance();
const colorInputRef = useRef<HTMLInputElement>(null);
const handleCustomAccentChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
// Convert hex to approximate oklch hue via HSL
const hex = e.target.value;
const hue = hexToApproxHue(hex);
setAccentHue(hue);
},
[setAccentHue],
);
return (
<SettingsPageContainer>
{/* Section 1: Color Mode */}
<SettingsSection title="Color Mode">
<SettingsRow
title="Mode"
description="Choose how T3 Code looks across the app."
resetAction={
colorMode !== "system" ? (
<SettingResetButton label="color mode" onClick={() => setColorMode("system")} />
) : null
}
control={
<Select
value={colorMode}
onValueChange={(value) => {
if (value === "system" || value === "light" || value === "dark") {
setColorMode(value as ColorMode);
}
}}
>
<SelectTrigger className="w-full sm:w-40" aria-label="Color mode preference">
<SelectValue>
{COLOR_MODE_OPTIONS.find((o) => o.value === colorMode)?.label ?? "System"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{COLOR_MODE_OPTIONS.map((option) => (
<SelectItem hideIndicator key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectPopup>
</Select>
}
/>
</SettingsSection>
{/* Section 2: Theme */}
<SettingsSection title="Theme">
<div className="px-4 py-4 sm:px-5">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
{BUILT_IN_THEMES.map((theme) => (
<ThemeCard
key={theme.id}
theme={theme}
isSelected={activeTheme.id === theme.id}
onSelect={() => setThemeId(theme.id)}
/>
))}
</div>
{activeTheme.id !== DEFAULT_THEME_ID ? (
<div className="mt-3 flex justify-end">
<SettingResetButton
label="appearance theme"
onClick={() => setThemeId(DEFAULT_THEME_ID)}
/>
</div>
) : null}
</div>
</SettingsSection>
{/* Section 3: Accent Color */}
<SettingsSection title="Accent Color">
<div className="px-4 py-4 sm:px-5">
<p className="mb-3 text-xs text-muted-foreground">
Override the primary color across the app.
</p>
<div className="flex flex-wrap items-center gap-2">
{/* Default pill */}
<button
type="button"
aria-pressed={accentHue === null}
className={cn(
"rounded-full border px-3 py-1 text-xs font-medium transition-colors",
accentHue === null
? "border-primary bg-primary/10 text-primary"
: "border-border text-muted-foreground hover:border-primary/40",
)}
onClick={() => setAccentHue(null)}
>
Default
</button>
{/* Preset circles */}
{ACCENT_PRESETS.map((preset) => (
<AccentCircle
key={preset.name}
hue={preset.hue}
isSelected={accentHue === preset.hue}
label={preset.name}
onClick={() => setAccentHue(preset.hue)}
/>
))}
{/* Custom color picker */}
<Button
variant="outline"
size="xs"
className="relative overflow-hidden"
onClick={() => colorInputRef.current?.click()}
>
Custom
<input
ref={colorInputRef}
type="color"
className="absolute inset-0 cursor-pointer opacity-0"
onChange={handleCustomAccentChange}
tabIndex={-1}
/>
</Button>
</div>
{accentHue !== null ? (
<div className="mt-3 flex justify-end">
<SettingResetButton label="accent color" onClick={() => setAccentHue(null)} />
</div>
) : null}
</div>
</SettingsSection>
</SettingsPageContainer>
);
}
// ── Utilities ────────────────────────────────────────────────────
/**
* Convert a hex color string to an approximate hue (0-360).
* Good enough for a color-picker UX — exact oklch conversion isn't needed.
*/
function hexToApproxHue(hex: string): number {
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const delta = max - min;
if (delta === 0) return 0;
let hue: number;
if (max === r) hue = ((g - b) / delta) % 6;
else if (max === g) hue = (b - r) / delta + 2;
else hue = (r - g) / delta + 4;
hue = Math.round(hue * 60);
if (hue < 0) hue += 360;
return hue;
}
@@ -33,7 +33,6 @@ import { ProviderModelPicker } from "../chat/ProviderModelPicker";
import { TraitsPicker } from "../chat/TraitsPicker";
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
import { isElectron } from "../../env";
import { useTheme } from "../../hooks/useTheme";
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
import { useThreadActions } from "../../hooks/useThreadActions";
import {
@@ -60,21 +59,6 @@ import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { ProjectFavicon } from "../ProjectFavicon";
const THEME_OPTIONS = [
{
value: "system",
label: "System",
},
{
value: "light",
label: "Light",
},
{
value: "dark",
label: "Dark",
},
] as const;
const TIMESTAMP_FORMAT_LABELS = {
locale: "System default",
"12-hour": "12-hour",
@@ -213,7 +197,7 @@ function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }
);
}
function SettingsSection({
export function SettingsSection({
title,
icon,
headerAction,
@@ -240,7 +224,7 @@ function SettingsSection({
);
}
function SettingsRow({
export function SettingsRow({
title,
description,
status,
@@ -279,7 +263,7 @@ function SettingsRow({
);
}
function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
export function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
return (
<Tooltip>
<TooltipTrigger
@@ -303,7 +287,7 @@ function SettingResetButton({ label, onClick }: { label: string; onClick: () =>
);
}
function SettingsPageContainer({ children }: { children: ReactNode }) {
export function SettingsPageContainer({ children }: { children: ReactNode }) {
return (
<div className="flex-1 overflow-y-auto p-6">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6">{children}</div>
@@ -439,7 +423,6 @@ function AboutVersionSection() {
}
export function useSettingsRestore(onRestored?: () => void) {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { resetSettings } = useUpdateSettings();
@@ -455,7 +438,9 @@ export function useSettingsRestore(onRestored?: () => void) {
const changedSettingLabels = useMemo(
() => [
...(theme !== "system" ? ["Theme"] : []),
...(settings.colorMode !== "system" ? ["Color mode"] : []),
...(settings.activeThemeId !== "t3code" ? ["Appearance theme"] : []),
...(settings.accentHue !== null ? ["Accent color"] : []),
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
? ["Time format"]
: []),
@@ -480,13 +465,15 @@ export function useSettingsRestore(onRestored?: () => void) {
[
areProviderSettingsDirty,
isGitWritingModelDirty,
settings.accentHue,
settings.activeThemeId,
settings.colorMode,
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.defaultThreadEnvMode,
settings.diffWordWrap,
settings.enableAssistantStreaming,
settings.timestampFormat,
theme,
],
);
@@ -500,10 +487,9 @@ export function useSettingsRestore(onRestored?: () => void) {
);
if (!confirmed) return;
setTheme("system");
resetSettings();
onRestored?.();
}, [changedSettingLabels, onRestored, resetSettings, setTheme]);
}, [changedSettingLabels, onRestored, resetSettings]);
return {
changedSettingLabels,
@@ -512,7 +498,6 @@ export function useSettingsRestore(onRestored?: () => void) {
}
export function GeneralSettingsPanel() {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
@@ -738,39 +723,6 @@ export function GeneralSettingsPanel() {
return (
<SettingsPageContainer>
<SettingsSection title="General">
<SettingsRow
title="Theme"
description="Choose how T3 Code looks across the app."
resetAction={
theme !== "system" ? (
<SettingResetButton label="theme" onClick={() => setTheme("system")} />
) : null
}
control={
<Select
value={theme}
onValueChange={(value) => {
if (value === "system" || value === "light" || value === "dark") {
setTheme(value);
}
}}
>
<SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">
<SelectValue>
{THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{THEME_OPTIONS.map((option) => (
<SelectItem hideIndicator key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectPopup>
</Select>
}
/>
<SettingsRow
title="Time format"
description="System default follows your browser or OS clock preference."
@@ -1,5 +1,5 @@
import type { ComponentType } from "react";
import { ArchiveIcon, ArrowLeftIcon, Settings2Icon } from "lucide-react";
import { ArchiveIcon, ArrowLeftIcon, PaletteIcon, Settings2Icon } from "lucide-react";
import { useNavigate } from "@tanstack/react-router";
import {
@@ -12,7 +12,10 @@ import {
SidebarSeparator,
} from "../ui/sidebar";
export type SettingsSectionPath = "/settings/general" | "/settings/archived";
export type SettingsSectionPath =
| "/settings/general"
| "/settings/appearance"
| "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
@@ -20,6 +23,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
icon: ComponentType<{ className?: string }>;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
{ label: "Appearance", to: "/settings/appearance", icon: PaletteIcon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
+167
View File
@@ -0,0 +1,167 @@
/**
* Unified appearance hook — replaces `useTheme`.
*
* All appearance state (colorMode, activeThemeId, accentHue) is
* server-authoritative and pushed to every client via `serverConfigUpdated`.
*
* A localStorage write-through cache prevents FOUC: module-scope code below
* reads the cache synchronously and applies the `.dark` class + theme tokens
* before React mounts.
*/
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import type { ColorMode } from "@t3tools/contracts/settings";
import type { DesktopAppearance } from "@t3tools/contracts";
import { applyThemeTokens, findThemeById, BUILT_IN_THEMES } from "~/lib/themes";
import { useSettings, useUpdateSettings } from "./useSettings";
// ── Constants ────────────────────────────────────────────────────
const APPEARANCE_CACHE_KEY = "t3code:appearance-cache";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
// ── Helpers ──────────────────────────────────────────────────────
function getSystemDark(): boolean {
return window.matchMedia(MEDIA_QUERY).matches;
}
function suppressTransitions(fn: () => void) {
document.documentElement.classList.add("no-transitions");
fn();
// Force reflow so the no-transitions class takes effect before removal
// oxlint-disable-next-line no-unused-expressions
document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
}
// ── Desktop bridge relay ─────────────────────────────────────────
let lastDesktopAppearance: string | null = null;
function syncDesktopAppearance(appearance: DesktopAppearance): void {
const bridge = window.desktopBridge;
if (!bridge) return;
const key = JSON.stringify(appearance);
if (lastDesktopAppearance === key) return;
lastDesktopAppearance = key;
if (typeof bridge.setAppearance === "function") {
void bridge.setAppearance(appearance).catch(() => {
if (lastDesktopAppearance === key) lastDesktopAppearance = null;
});
} else {
// Fallback for older Electron builds that only expose setTheme
void bridge.setTheme(appearance.mode).catch(() => {
if (lastDesktopAppearance === key) lastDesktopAppearance = null;
});
}
}
// ── FOUC prevention (module scope — runs before React mounts) ───
try {
const cached = JSON.parse(localStorage.getItem(APPEARANCE_CACHE_KEY) ?? "null") as {
colorMode?: string;
activeThemeId?: string;
accentHue?: number | null;
} | null;
if (cached) {
const isDark =
cached.colorMode === "dark" || (cached.colorMode === "system" && getSystemDark());
document.documentElement.classList.toggle("dark", isDark);
const theme = findThemeById(cached.activeThemeId ?? "t3code");
if (theme) applyThemeTokens(theme, cached.accentHue ?? null);
}
} catch {
// Cache unreadable — fall through to React reconciliation.
}
// ── System-dark external store (for "system" mode live updates) ──
let systemDarkListeners: Array<() => void> = [];
let cachedSystemDark: boolean | null = null;
function getSystemDarkSnapshot(): boolean {
if (cachedSystemDark === null) cachedSystemDark = getSystemDark();
return cachedSystemDark;
}
function subscribeSystemDark(listener: () => void): () => void {
systemDarkListeners.push(listener);
const mq = window.matchMedia(MEDIA_QUERY);
const handler = () => {
cachedSystemDark = mq.matches;
for (const l of systemDarkListeners) l();
};
mq.addEventListener("change", handler);
return () => {
systemDarkListeners = systemDarkListeners.filter((l) => l !== listener);
mq.removeEventListener("change", handler);
};
}
// ── Hook ─────────────────────────────────────────────────────────
export function useAppearance() {
const { colorMode, activeThemeId, accentHue } = useSettings((s) => ({
colorMode: s.colorMode,
activeThemeId: s.activeThemeId,
accentHue: s.accentHue,
}));
const { updateSettings } = useUpdateSettings();
const activeTheme = findThemeById(activeThemeId) ?? BUILT_IN_THEMES[0]!;
// Track system dark preference reactively
const systemDark = useSyncExternalStore(subscribeSystemDark, getSystemDarkSnapshot);
const resolvedTheme: "light" | "dark" = useMemo(
() => (colorMode === "system" ? (systemDark ? "dark" : "light") : colorMode),
[colorMode, systemDark],
);
// Apply .dark class, theme tokens, cache, and relay to Electron
useEffect(() => {
suppressTransitions(() => {
document.documentElement.classList.toggle("dark", resolvedTheme === "dark");
applyThemeTokens(activeTheme, accentHue);
});
// Write-through cache for FOUC prevention on next load
localStorage.setItem(
APPEARANCE_CACHE_KEY,
JSON.stringify({ colorMode, activeThemeId, accentHue }),
);
// Sync to Electron
syncDesktopAppearance({ mode: colorMode, themeId: activeThemeId, accentHue });
}, [resolvedTheme, activeTheme, accentHue, colorMode, activeThemeId]);
const setColorMode = useCallback(
(mode: ColorMode) => updateSettings({ colorMode: mode }),
[updateSettings],
);
const setThemeId = useCallback(
(id: string) => updateSettings({ activeThemeId: id }),
[updateSettings],
);
const setAccentHue = useCallback(
(hue: number | null) => updateSettings({ accentHue: hue }),
[updateSettings],
);
return {
colorMode,
resolvedTheme,
activeTheme,
accentHue,
setColorMode,
setThemeId,
setAccentHue,
} as const;
}
+15 -3
View File
@@ -70,9 +70,7 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
* only re-render when the slice they care about changes.
*/
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
selector?: (s: UnifiedSettings) => T,
): T {
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
const { data: serverConfig } = useQuery(serverConfigQueryOptions());
const [clientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
@@ -237,6 +235,20 @@ export function buildLegacyClientSettingsMigrationPatch(
export function migrateLocalSettingsToServer(): void {
if (typeof window === "undefined") return;
// Migrate old t3code:theme localStorage key to server colorMode.
// This runs independently of OLD_SETTINGS_KEY since the old useTheme hook
// wrote t3code:theme separately.
try {
const oldTheme = localStorage.getItem("t3code:theme");
if (oldTheme === "light" || oldTheme === "dark" || oldTheme === "system") {
const api = ensureNativeApi();
void api.server.updateSettings({ colorMode: oldTheme });
localStorage.removeItem("t3code:theme");
}
} catch {
// Best-effort — don't block startup
}
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
if (!raw) return;
-121
View File
@@ -1,121 +0,0 @@
import { useCallback, useEffect, useSyncExternalStore } from "react";
type Theme = "light" | "dark" | "system";
type ThemeSnapshot = {
theme: Theme;
systemDark: boolean;
};
const STORAGE_KEY = "t3code:theme";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
let lastDesktopTheme: Theme | null = null;
function emitChange() {
for (const listener of listeners) listener();
}
function getSystemDark(): boolean {
return window.matchMedia(MEDIA_QUERY).matches;
}
function getStored(): Theme {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw === "light" || raw === "dark" || raw === "system") return raw;
return "system";
}
function applyTheme(theme: Theme, suppressTransitions = false) {
if (suppressTransitions) {
document.documentElement.classList.add("no-transitions");
}
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
document.documentElement.classList.toggle("dark", isDark);
syncDesktopTheme(theme);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
// oxlint-disable-next-line no-unused-expressions
document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
}
}
function syncDesktopTheme(theme: Theme) {
const bridge = window.desktopBridge;
if (!bridge || lastDesktopTheme === theme) {
return;
}
lastDesktopTheme = theme;
void bridge.setTheme(theme).catch(() => {
if (lastDesktopTheme === theme) {
lastDesktopTheme = null;
}
});
}
// Apply immediately on module load to prevent flash
applyTheme(getStored());
function getSnapshot(): ThemeSnapshot {
const theme = getStored();
const systemDark = theme === "system" ? getSystemDark() : false;
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
return lastSnapshot;
}
lastSnapshot = { theme, systemDark };
return lastSnapshot;
}
function subscribe(listener: () => void): () => void {
listeners.push(listener);
// Listen for system preference changes
const mq = window.matchMedia(MEDIA_QUERY);
const handleChange = () => {
if (getStored() === "system") applyTheme("system", true);
emitChange();
};
mq.addEventListener("change", handleChange);
// Listen for storage changes from other tabs
const handleStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEY) {
applyTheme(getStored(), true);
emitChange();
}
};
window.addEventListener("storage", handleStorage);
return () => {
listeners = listeners.filter((l) => l !== listener);
mq.removeEventListener("change", handleChange);
window.removeEventListener("storage", handleStorage);
};
}
export function useTheme() {
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
const theme = snapshot.theme;
const resolvedTheme: "light" | "dark" =
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
const setTheme = useCallback((next: Theme) => {
localStorage.setItem(STORAGE_KEY, next);
applyTheme(next, true);
emitChange();
}, []);
// Keep DOM in sync on mount/change
useEffect(() => {
applyTheme(theme);
}, [theme]);
return { theme, setTheme, resolvedTheme } as const;
}
+206
View File
@@ -0,0 +1,206 @@
/**
* Theme definitions, CSS injection, and accent color derivation.
*
* V1 themes override accent/semantic colors only:
* primary, primary-foreground, ring,
* destructive, destructive-foreground,
* info, info-foreground,
* success, success-foreground,
* warning, warning-foreground
*
* Background/surface tokens stay controlled by the CSS baseline in index.css.
*/
// ── Token types ──────────────────────────────────────────────────
/**
* The set of CSS custom-property names a theme may override.
* Uses the unprefixed form (e.g. "primary", not "--color-primary").
*/
export type ThemeToken =
| "primary"
| "primary-foreground"
| "ring"
| "destructive"
| "destructive-foreground"
| "info"
| "info-foreground"
| "success"
| "success-foreground"
| "warning"
| "warning-foreground";
export type ThemeTokenMap = Partial<Record<ThemeToken, string>>;
export interface ThemeDefinition {
id: string;
name: string;
description: string;
builtIn: boolean;
light: ThemeTokenMap;
dark: ThemeTokenMap;
}
// ── Built-in themes ──────────────────────────────────────────────
const T3CODE_THEME: ThemeDefinition = {
id: "t3code",
name: "T3Code",
description: "Default color palette.",
builtIn: true,
light: {},
dark: {},
};
const HIGH_CONTRAST_THEME: ThemeDefinition = {
id: "high-contrast",
name: "High Contrast",
description: "Boosted contrast for WCAG AAA.",
builtIn: true,
light: {
primary: "oklch(0.35 0.25 264)",
"primary-foreground": "oklch(1 0 0)",
ring: "oklch(0.35 0.25 264)",
destructive: "oklch(0.45 0.28 25)",
"destructive-foreground": "oklch(0.30 0.22 25)",
info: "oklch(0.45 0.22 250)",
"info-foreground": "oklch(0.30 0.18 250)",
success: "oklch(0.42 0.20 155)",
"success-foreground": "oklch(0.28 0.16 155)",
warning: "oklch(0.55 0.22 70)",
"warning-foreground": "oklch(0.38 0.18 70)",
},
dark: {
primary: "oklch(0.75 0.22 264)",
"primary-foreground": "oklch(0.15 0 0)",
ring: "oklch(0.75 0.22 264)",
destructive: "oklch(0.72 0.26 25)",
"destructive-foreground": "oklch(0.82 0.18 25)",
info: "oklch(0.72 0.20 250)",
"info-foreground": "oklch(0.82 0.14 250)",
success: "oklch(0.72 0.20 155)",
"success-foreground": "oklch(0.82 0.14 155)",
warning: "oklch(0.78 0.20 70)",
"warning-foreground": "oklch(0.86 0.14 70)",
},
};
const COLOR_BLIND_THEME: ThemeDefinition = {
id: "color-blind",
name: "Color Blind",
description: "Deuteranopia-safe palette.",
builtIn: true,
light: {
success: "oklch(0.65 0.15 195)",
"success-foreground": "oklch(0.45 0.12 195)",
warning: "oklch(0.75 0.16 65)",
"warning-foreground": "oklch(0.50 0.14 65)",
destructive: "oklch(0.55 0.22 350)",
"destructive-foreground": "oklch(0.40 0.18 350)",
},
dark: {
success: "oklch(0.70 0.14 195)",
"success-foreground": "oklch(0.82 0.10 195)",
warning: "oklch(0.78 0.15 65)",
"warning-foreground": "oklch(0.86 0.10 65)",
destructive: "oklch(0.68 0.20 350)",
"destructive-foreground": "oklch(0.82 0.14 350)",
},
};
export const BUILT_IN_THEMES: readonly ThemeDefinition[] = [
T3CODE_THEME,
HIGH_CONTRAST_THEME,
COLOR_BLIND_THEME,
];
export const DEFAULT_THEME_ID = "t3code";
// ── Accent presets ───────────────────────────────────────────────
export interface AccentPreset {
name: string;
hue: number;
}
export const ACCENT_PRESETS: readonly AccentPreset[] = [
{ name: "Red", hue: 25 },
{ name: "Orange", hue: 55 },
{ name: "Yellow", hue: 85 },
{ name: "Green", hue: 145 },
{ name: "Teal", hue: 185 },
{ name: "Blue", hue: 240 },
{ name: "Purple", hue: 290 },
{ name: "Pink", hue: 340 },
];
// ── Lookup ───────────────────────────────────────────────────────
export function findThemeById(id: string): ThemeDefinition | undefined {
return BUILT_IN_THEMES.find((t) => t.id === id);
}
// ── Accent derivation (oklch) ────────────────────────────────────
export function deriveAccentColors(hue: number): { light: ThemeTokenMap; dark: ThemeTokenMap } {
return {
light: {
primary: `oklch(0.488 0.217 ${hue})`,
"primary-foreground": "oklch(1 0 0)",
ring: `oklch(0.488 0.217 ${hue})`,
},
dark: {
primary: `oklch(0.588 0.217 ${hue})`,
"primary-foreground": "oklch(1 0 0)",
ring: `oklch(0.588 0.217 ${hue})`,
},
};
}
// ── CSS injection ────────────────────────────────────────────────
const STYLE_ELEMENT_ID = "t3code-theme-tokens";
function buildCssBlock(selector: string, tokens: ThemeTokenMap): string {
const entries = Object.entries(tokens) as [ThemeToken, string][];
if (entries.length === 0) return "";
const declarations = entries.map(([token, value]) => ` --color-${token}: ${value};`).join("\n");
return `${selector} {\n${declarations}\n}`;
}
/**
* Inject or replace a `<style>` element with theme overrides.
* When the T3Code default is active with no accent, removes the element entirely.
*/
export function applyThemeTokens(theme: ThemeDefinition, accentHue: number | null): void {
const accent = accentHue != null ? deriveAccentColors(accentHue) : null;
const lightTokens: ThemeTokenMap = { ...theme.light, ...accent?.light };
const darkTokens: ThemeTokenMap = { ...theme.dark, ...accent?.dark };
const hasOverrides = Object.keys(lightTokens).length > 0 || Object.keys(darkTokens).length > 0;
if (!hasOverrides) {
removeThemeTokens();
return;
}
const blocks = [
buildCssBlock(":root", lightTokens),
buildCssBlock(":root:is(.dark, .dark *)", darkTokens),
]
.filter(Boolean)
.join("\n");
let style = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;
if (!style) {
style = document.createElement("style");
style.id = STYLE_ELEMENT_ID;
document.head.appendChild(style);
}
style.textContent = blocks;
}
export function removeThemeTokens(): void {
document.getElementById(STYLE_ELEMENT_ID)?.remove();
}
+21
View File
@@ -14,6 +14,7 @@ import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
const SettingsRoute = SettingsRouteImport.update({
@@ -40,6 +41,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({
id: '/appearance',
path: '/appearance',
getParentRoute: () => SettingsRoute,
} as any)
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
id: '/$threadId',
path: '/$threadId',
@@ -50,12 +56,14 @@ export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/settings': typeof SettingsRouteWithChildren
'/$threadId': typeof ChatThreadIdRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/general': typeof SettingsGeneralRoute
}
export interface FileRoutesByTo {
'/settings': typeof SettingsRouteWithChildren
'/$threadId': typeof ChatThreadIdRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/general': typeof SettingsGeneralRoute
'/': typeof ChatIndexRoute
@@ -65,6 +73,7 @@ export interface FileRoutesById {
'/_chat': typeof ChatRouteWithChildren
'/settings': typeof SettingsRouteWithChildren
'/_chat/$threadId': typeof ChatThreadIdRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/general': typeof SettingsGeneralRoute
'/_chat/': typeof ChatIndexRoute
@@ -75,12 +84,14 @@ export interface FileRouteTypes {
| '/'
| '/settings'
| '/$threadId'
| '/settings/appearance'
| '/settings/archived'
| '/settings/general'
fileRoutesByTo: FileRoutesByTo
to:
| '/settings'
| '/$threadId'
| '/settings/appearance'
| '/settings/archived'
| '/settings/general'
| '/'
@@ -89,6 +100,7 @@ export interface FileRouteTypes {
| '/_chat'
| '/settings'
| '/_chat/$threadId'
| '/settings/appearance'
| '/settings/archived'
| '/settings/general'
| '/_chat/'
@@ -136,6 +148,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/appearance': {
id: '/settings/appearance'
path: '/appearance'
fullPath: '/settings/appearance'
preLoaderRoute: typeof SettingsAppearanceRouteImport
parentRoute: typeof SettingsRoute
}
'/_chat/$threadId': {
id: '/_chat/$threadId'
path: '/$threadId'
@@ -159,11 +178,13 @@ const ChatRouteChildren: ChatRouteChildren = {
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
interface SettingsRouteChildren {
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
SettingsAppearanceRoute: SettingsAppearanceRoute,
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
}
+5
View File
@@ -22,6 +22,7 @@ import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
import { useAppearance } from "../hooks/useAppearance";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
@@ -50,6 +51,10 @@ function RootRouteView() {
);
}
// Mount appearance system — drives .dark class, theme tokens, and Electron sync.
// The import also triggers module-scope FOUC prevention.
useAppearance();
return (
<ToastProvider>
<AnchoredToastProvider>
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { AppearanceSettingsPanel } from "../components/settings/AppearanceSettingsPanel";
export const Route = createFileRoute("/settings/appearance")({
component: AppearanceSettingsPanel,
});
+8
View File
@@ -73,6 +73,12 @@ export type DesktopUpdateStatus =
export type DesktopRuntimeArch = "arm64" | "x64" | "other";
export type DesktopTheme = "light" | "dark" | "system";
export type DesktopAppearance = {
mode: DesktopTheme;
themeId: string;
accentHue: number | null;
};
export interface DesktopRuntimeInfo {
hostArch: DesktopRuntimeArch;
appArch: DesktopRuntimeArch;
@@ -110,7 +116,9 @@ export interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
/** @deprecated Use `setAppearance` instead. */
setTheme: (theme: DesktopTheme) => Promise<void>;
setAppearance: (appearance: DesktopAppearance) => Promise<void>;
showContextMenu: <T extends string>(
items: readonly ContextMenuItem<T>[],
position?: { x: number; y: number },
+18
View File
@@ -39,6 +39,14 @@ export type ClientSettings = typeof ClientSettingsSchema.Type;
export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
// ── Appearance ──────────────────────────────────────────────────
export const ColorMode = Schema.Literals(["light", "dark", "system"]);
export type ColorMode = typeof ColorMode.Type;
export const DEFAULT_COLOR_MODE: ColorMode = "system";
export const DEFAULT_ACTIVE_THEME_ID = "t3code";
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
@@ -83,6 +91,13 @@ export const ServerSettings = Schema.Struct({
})),
),
// Appearance
colorMode: ColorMode.pipe(
Schema.withDecodingDefault(() => "system" as const satisfies ColorMode),
),
activeThemeId: Schema.String.pipe(Schema.withDecodingDefault(() => DEFAULT_ACTIVE_THEME_ID)),
accentHue: Schema.NullOr(Schema.Number).pipe(Schema.withDecodingDefault(() => null)),
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
@@ -144,6 +159,9 @@ export const ServerSettingsPatch = Schema.Struct({
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
colorMode: Schema.optionalKey(ColorMode),
activeThemeId: Schema.optionalKey(Schema.String),
accentHue: Schema.optionalKey(Schema.NullOr(Schema.Number)),
providers: Schema.optionalKey(
Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),