diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 8444a7f82e..3a4107b194 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1168,8 +1168,7 @@ function registerIpcHandlers(): void { 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.) + // themeId is available for future Electron shell styling work. }); ipcMain.removeHandler(CONTEXT_MENU_CHANNEL); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index f26fece246..d733b5ff21 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -179,4 +179,95 @@ it.layer(NodeServices.layer)("server settings", (it) => { }); }).pipe(Effect.provide(makeServerSettingsLayer())), ); + + it.effect("persists custom themes as part of server-authoritative appearance settings", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + const serverConfig = yield* ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + + const next = yield* serverSettings.updateSettings({ + activeLightThemeId: "custom-codex-light", + activeDarkThemeId: "custom-codex-dark", + customThemes: [ + { + id: "custom-codex-light", + name: "Custom Codex Light", + version: 1, + origin: "custom", + mode: "light", + radius: "0.75rem", + fontSize: "15px", + accent: "#0169cc", + background: "#ffffff", + foreground: "#0d0d0d", + uiFontFamily: '"IBM Plex Sans", sans-serif', + codeFontFamily: '"IBM Plex Mono", monospace', + sidebarTranslucent: true, + contrast: 46, + }, + { + id: "custom-codex-dark", + name: "Custom Codex Dark", + version: 1, + origin: "custom", + mode: "dark", + radius: "0.75rem", + fontSize: "15px", + accent: "#0169cc", + background: "#111111", + foreground: "#fcfcfc", + uiFontFamily: '"IBM Plex Sans", sans-serif', + codeFontFamily: '"IBM Plex Mono", monospace', + sidebarTranslucent: true, + contrast: 41, + }, + ], + }); + + assert.equal(next.activeLightThemeId, "custom-codex-light"); + assert.equal(next.activeDarkThemeId, "custom-codex-dark"); + assert.equal(next.customThemes.length, 2); + + const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); + assert.deepEqual(JSON.parse(raw), { + activeLightThemeId: "custom-codex-light", + activeDarkThemeId: "custom-codex-dark", + customThemes: [ + { + id: "custom-codex-light", + name: "Custom Codex Light", + version: 1, + origin: "custom", + mode: "light", + radius: "0.75rem", + fontSize: "15px", + accent: "#0169cc", + background: "#ffffff", + foreground: "#0d0d0d", + uiFontFamily: '"IBM Plex Sans", sans-serif', + codeFontFamily: '"IBM Plex Mono", monospace', + sidebarTranslucent: true, + contrast: 46, + }, + { + id: "custom-codex-dark", + name: "Custom Codex Dark", + version: 1, + origin: "custom", + mode: "dark", + radius: "0.75rem", + fontSize: "15px", + accent: "#0169cc", + background: "#111111", + foreground: "#fcfcfc", + uiFontFamily: '"IBM Plex Sans", sans-serif', + codeFontFamily: '"IBM Plex Mono", monospace', + sidebarTranslucent: true, + contrast: 41, + }, + ], + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); }); diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index db2498043c..19f162abe3 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -61,8 +61,9 @@ function createBaseServerConfig(): ServerConfig { defaultThreadEnvMode: "local" as const, textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" }, colorMode: "system" as const, - activeThemeId: "t3code", - accentHue: null, + activeLightThemeId: "t3code-light", + activeDarkThemeId: "t3code-dark", + customThemes: [], providers: { codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] }, claudeAgent: { enabled: true, binaryPath: "", customModels: [] }, diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 65a295c979..25c7569973 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -1,300 +1,798 @@ -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"; + ChevronDownIcon, + CopyIcon, + MonitorIcon, + MoonIcon, + RotateCcwIcon, + SunIcon, + Trash2Icon, + UploadIcon, +} from "lucide-react"; +import { Schema, SchemaIssue } from "effect"; +import { type ChangeEvent, useCallback, useMemo, useRef, useState } from "react"; +import { + ThemeDocumentSchema, + type ColorMode, + type ThemeDerivedOverrides, + type ThemeDocument, + type ThemeMode, +} from "@t3tools/contracts"; +import { + BUILTIN_THEME_PRESETS, + canonicalizeThemeDocument, + getDefaultThemeId, + getThemeDocumentsForMode, + serializeThemeDocument, +} from "@t3tools/shared/appearance/registry"; import { cn } from "../../lib/utils"; +import { useAppearance } from "../../hooks/useAppearance"; +import { useUpdateSettings } from "../../hooks/useSettings"; +import { toastManager } from "../ui/toast"; +import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../ui/collapsible"; +import { Input } from "../ui/input"; +import { Switch } from "../ui/switch"; +import { SettingsPageContainer, SettingsSection } from "./SettingsPanels"; import { - SettingResetButton, - SettingsPageContainer, - SettingsRow, - SettingsSection, -} from "./SettingsPanels"; - -// ── Constants ──────────────────────────────────────────────────── + createDuplicateTheme, + normalizeImportedThemeDocument, + replaceCustomTheme, + updateThemeDocument, +} from "./appearance.logic"; const COLOR_MODE_OPTIONS = [ - { value: "system", label: "System" }, - { value: "light", label: "Light" }, - { value: "dark", label: "Dark" }, -] as const; + { value: "system", label: "System", icon: MonitorIcon }, + { value: "light", label: "Light", icon: SunIcon }, + { value: "dark", label: "Dark", icon: MoonIcon }, +] as const satisfies ReadonlyArray<{ + value: ColorMode; + label: string; + icon: typeof MonitorIcon; +}>; -// ── Swatch preview ────────────────────────────────────────────── - -/** Render small color dots showing what the theme overrides. */ -function ThemeSwatch({ theme }: { theme: ThemeDefinition }) { - // Show the tokens the theme actually overrides (merge light + dark for preview) - const overrideTokens = Object.keys({ ...theme.light, ...theme.dark }) as Array< - keyof ThemeTokenMap - >; - - if (overrideTokens.length === 0) { - // Default theme — show placeholder dots - return ( -
- {Array.from({ length: 4 }, (_, i) => ( - - ))} -
- ); +const MODE_COPY = { + light: { + label: "Light Theme", + modeLabel: "Light", + importTitle: "Import Light Theme", + emptyDescription: "Imported or duplicated light theme.", + }, + dark: { + label: "Dark Theme", + modeLabel: "Dark", + importTitle: "Import Dark Theme", + emptyDescription: "Imported or duplicated dark theme.", + }, +} as const satisfies Record< + ThemeMode, + { + label: string; + modeLabel: string; + importTitle: string; + emptyDescription: string; } +>; - // For display, prefer light-mode values (more vivid), fall back to dark - const displayTokens = overrideTokens.filter((t) => !t.endsWith("-foreground")).slice(0, 5); - - return ( -
- {displayTokens.map((token) => { - const color = theme.light[token] ?? theme.dark[token]; - return color ? ( - - ) : ( - - ); - })} -
- ); -} - -// ── Theme card ─────────────────────────────────────────────────── +const OVERRIDE_FIELDS: ReadonlyArray<{ + key: keyof ThemeDerivedOverrides; + label: string; + placeholder: string; +}> = [ + { key: "background", label: "Background", placeholder: "Auto" }, + { key: "foreground", label: "Foreground", placeholder: "Auto" }, + { key: "card", label: "Card", placeholder: "Auto" }, + { key: "cardForeground", label: "Card text", placeholder: "Auto" }, + { key: "popover", label: "Popover", placeholder: "Auto" }, + { key: "popoverForeground", label: "Popover text", placeholder: "Auto" }, + { key: "primary", label: "Primary", placeholder: "Auto" }, + { key: "primaryForeground", label: "Primary text", placeholder: "Auto" }, + { key: "secondary", label: "Secondary", placeholder: "Auto" }, + { key: "secondaryForeground", label: "Secondary text", placeholder: "Auto" }, + { key: "muted", label: "Muted", placeholder: "Auto" }, + { key: "mutedForeground", label: "Muted text", placeholder: "Auto" }, + { key: "accentSurface", label: "Accent surface", placeholder: "Auto" }, + { key: "accentForeground", label: "Accent text", placeholder: "Auto" }, + { key: "border", label: "Border", placeholder: "Auto" }, + { key: "input", label: "Input", placeholder: "Auto" }, + { key: "ring", label: "Ring", placeholder: "Auto" }, + { key: "destructive", label: "Destructive", placeholder: "Auto" }, + { key: "destructiveForeground", label: "Destructive text", placeholder: "Auto" }, + { key: "info", label: "Info", placeholder: "Auto" }, + { key: "infoForeground", label: "Info text", placeholder: "Auto" }, + { key: "success", label: "Success", placeholder: "Auto" }, + { key: "successForeground", label: "Success text", placeholder: "Auto" }, + { key: "warning", label: "Warning", placeholder: "Auto" }, + { key: "warningForeground", label: "Warning text", placeholder: "Auto" }, + { key: "diffAddition", label: "Diff addition", placeholder: "Auto" }, + { key: "diffDeletion", label: "Diff deletion", placeholder: "Auto" }, + { key: "sidebar", label: "Sidebar", placeholder: "Auto" }, + { key: "sidebarForeground", label: "Sidebar text", placeholder: "Auto" }, + { key: "sidebarAccent", label: "Sidebar accent", placeholder: "Auto" }, + { key: "sidebarAccentForeground", label: "Sidebar accent text", placeholder: "Auto" }, + { key: "sidebarBorder", label: "Sidebar border", placeholder: "Auto" }, +]; function ThemeCard({ theme, + description, isSelected, onSelect, }: { - theme: ThemeDefinition; + theme: ThemeDocument; + description: string; isSelected: boolean; onSelect: () => void; }) { return ( ); } -// ── Accent preset circle ───────────────────────────────────────── - -function AccentCircle({ - hue, - isSelected, +function ColorField({ label, - onClick, + value, + onChange, }: { - hue: number; - isSelected: boolean; label: string; - onClick: () => void; + value: string; + onChange: (value: string) => void; }) { return ( - + ); } -// ── Main panel ─────────────────────────────────────────────────── +function ThemeEditor({ + theme, + onChange, +}: { + theme: ThemeDocument; + onChange: (updater: (theme: ThemeDocument) => ThemeDocument) => void; +}) { + return ( +
+
+
+

{MODE_COPY[theme.mode].label}

+

+ Base colors, scale, typography, and optional advanced token overrides. +

+
+
+
+ +
+ onChange((currentTheme) => ({ ...currentTheme, accent }))} + /> + onChange((currentTheme) => ({ ...currentTheme, background }))} + /> + onChange((currentTheme) => ({ ...currentTheme, foreground }))} + /> +
+ +
+ + + + +
+ +
+
+
+
+

Translucent sidebar

+

+ Lets the sidebar pick up backdrop blur and a softer surface treatment. +

+
+ + onChange((currentTheme) => ({ ...currentTheme, sidebarTranslucent: checked })) + } + /> +
+
+ + +
+ + + +
+

Advanced token overrides

+

+ Optional explicit values for card, border, status, diff, and sidebar tokens. +

+
+ +
+ +
+ {OVERRIDE_FIELDS.map((field) => ( + + ))} +
+
+
+
+ ); +} export function AppearanceSettingsPanel() { - const { colorMode, activeTheme, accentHue, setColorMode, setThemeId, setAccentHue } = + const { colorMode, activeLightTheme, activeDarkTheme, customThemes, setColorMode, setThemeId } = useAppearance(); + const { updateSettings } = useUpdateSettings(); + const lightImportInputRef = useRef(null); + const darkImportInputRef = useRef(null); + const [importErrors, setImportErrors] = useState>({ + light: null, + dark: null, + }); - const colorInputRef = useRef(null); + const themeLibraryByMode = useMemo( + () => ({ + light: getThemeDocumentsForMode("light", customThemes).map((theme) => ({ + theme, + description: + BUILTIN_THEME_PRESETS.find((preset) => preset.theme.id === theme.id)?.description ?? + MODE_COPY.light.emptyDescription, + })), + dark: getThemeDocumentsForMode("dark", customThemes).map((theme) => ({ + theme, + description: + BUILTIN_THEME_PRESETS.find((preset) => preset.theme.id === theme.id)?.description ?? + MODE_COPY.dark.emptyDescription, + })), + }), + [customThemes], + ); - const handleCustomAccentChange = useCallback( - (e: React.ChangeEvent) => { - // Convert hex to approximate oklch hue via HSL - const hex = e.target.value; - const hue = hexToApproxHue(hex); - setAccentHue(hue); + const activeThemeByMode = useMemo( + () => + ({ + light: activeLightTheme, + dark: activeDarkTheme, + }) as const satisfies Record, + [activeLightTheme, activeDarkTheme], + ); + + const updateModeSelection = useCallback( + (mode: ThemeMode, themeId: string) => { + setThemeId(mode, themeId); }, - [setAccentHue], + [setThemeId], + ); + + const saveTheme = useCallback( + (themeDocument: ThemeDocument) => { + updateSettings({ + ...(themeDocument.mode === "dark" + ? { activeDarkThemeId: themeDocument.id } + : { activeLightThemeId: themeDocument.id }), + customThemes: replaceCustomTheme( + customThemes, + canonicalizeThemeDocument(themeDocument, "custom"), + ), + }); + }, + [customThemes, updateSettings], + ); + + const getEditableTheme = useCallback( + (mode: ThemeMode, announceDuplicate: boolean): ThemeDocument => { + const activeTheme = activeThemeByMode[mode]; + if (activeTheme.origin === "custom") { + return activeTheme; + } + + const duplicate = createDuplicateTheme(activeTheme, customThemes); + if (announceDuplicate) { + toastManager.add({ + type: "info", + title: "Created editable copy", + description: `${activeTheme.name} was duplicated into ${duplicate.name}.`, + }); + } + return duplicate; + }, + [activeThemeByMode, customThemes], + ); + + const handleThemeChange = useCallback( + (mode: ThemeMode, updater: (themeDocument: ThemeDocument) => ThemeDocument) => { + const baseTheme = getEditableTheme(mode, true); + const nextTheme = updateThemeDocument(baseTheme, updater); + saveTheme(nextTheme); + }, + [getEditableTheme, saveTheme], + ); + + const handleDuplicateTheme = useCallback( + (mode: ThemeMode) => { + const duplicate = createDuplicateTheme(activeThemeByMode[mode], customThemes); + updateSettings({ + ...(mode === "dark" + ? { activeDarkThemeId: duplicate.id } + : { activeLightThemeId: duplicate.id }), + customThemes: [...customThemes, duplicate], + }); + toastManager.add({ + type: "success", + title: "Theme duplicated", + description: `${duplicate.name} is now selected and editable.`, + }); + }, + [activeThemeByMode, customThemes, updateSettings], + ); + + const handleDeleteTheme = useCallback( + (mode: ThemeMode) => { + const activeTheme = activeThemeByMode[mode]; + if (activeTheme.origin !== "custom") return; + + updateSettings({ + ...(mode === "dark" + ? { activeDarkThemeId: getDefaultThemeId("dark") } + : { activeLightThemeId: getDefaultThemeId("light") }), + customThemes: customThemes.filter((theme) => theme.id !== activeTheme.id), + }); + toastManager.add({ + type: "success", + title: "Custom theme deleted", + description: `${activeTheme.name} was removed from your library.`, + }); + }, + [activeThemeByMode, customThemes, updateSettings], + ); + + const handleResetCurrent = useCallback( + (mode: ThemeMode) => { + const activeTheme = activeThemeByMode[mode]; + if (activeTheme.origin === "builtin") { + updateModeSelection(mode, getDefaultThemeId(mode)); + return; + } + + const builtinDefault = BUILTIN_THEME_PRESETS.find( + (preset) => preset.theme.id === getDefaultThemeId(mode), + )!.theme; + const resetTheme = canonicalizeThemeDocument( + { + ...builtinDefault, + id: activeTheme.id, + name: activeTheme.name, + origin: "custom", + }, + "custom", + ); + saveTheme(resetTheme); + toastManager.add({ + type: "success", + title: "Theme reset", + description: `${activeTheme.name} now matches the default ${MODE_COPY[mode].modeLabel.toLowerCase()} preset.`, + }); + }, + [activeThemeByMode, saveTheme, updateModeSelection], + ); + + const handleCopyTheme = useCallback( + async (mode: ThemeMode) => { + const activeTheme = activeThemeByMode[mode]; + try { + await navigator.clipboard.writeText(serializeThemeDocument(activeTheme)); + toastManager.add({ + type: "success", + title: "Theme JSON copied", + description: `${activeTheme.name} is ready to paste or share.`, + }); + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not copy theme JSON", + description: error instanceof Error ? error.message : "Clipboard access failed.", + }); + } + }, + [activeThemeByMode], + ); + + const handleImportTheme = useCallback( + (mode: ThemeMode) => async (event: ChangeEvent) => { + const file = event.target.files?.[0]; + event.target.value = ""; + if (!file) return; + + setImportErrors((current) => ({ ...current, [mode]: null })); + + let rawJson: unknown; + try { + rawJson = JSON.parse(await file.text()); + } catch (error) { + const message = error instanceof Error ? error.message : "Invalid JSON."; + setImportErrors((current) => ({ ...current, [mode]: message })); + return; + } + + let decoded: ThemeDocument; + try { + decoded = Schema.decodeUnknownSync(ThemeDocumentSchema)(rawJson); + } catch (error) { + const message = + typeof error === "object" && error !== null && "issue" in error + ? SchemaIssue.makeFormatterDefault()((error as { issue: never }).issue) + : error instanceof Error + ? error.message + : "Invalid theme document."; + setImportErrors((current) => ({ ...current, [mode]: message })); + return; + } + + if (decoded.mode !== mode) { + setImportErrors((current) => ({ + ...current, + [mode]: `Imported theme mode mismatch. Expected ${mode}, received ${decoded.mode}.`, + })); + return; + } + + const existingIds = new Set([ + ...BUILTIN_THEME_PRESETS.map((preset) => preset.theme.id), + ...customThemes.map((theme) => theme.id), + ]); + const normalized = normalizeImportedThemeDocument(decoded, existingIds); + + updateSettings({ + ...(mode === "dark" + ? { activeDarkThemeId: normalized.id } + : { activeLightThemeId: normalized.id }), + customThemes: [...customThemes, normalized], + }); + toastManager.add({ + type: "success", + title: MODE_COPY[mode].importTitle, + description: + normalized.id === decoded.id + ? `${normalized.name} is now available in your custom ${mode} theme library.` + : `${normalized.name} was imported as ${normalized.id} to avoid an id conflict.`, + }); + }, + [customThemes, updateSettings], ); return ( - {/* Section 1: Color Mode */} - setColorMode("system")} /> - ) : null - } - control={ - - } - /> - +
+ {COLOR_MODE_OPTIONS.map((option) => { + const Icon = option.icon; + const selected = colorMode === option.value; - {/* Section 2: Theme */} - -
-
- {BUILT_IN_THEMES.map((theme) => ( - setThemeId(theme.id)} - /> - ))} -
- {activeTheme.id !== DEFAULT_THEME_ID ? ( -
- setThemeId(DEFAULT_THEME_ID)} - /> -
- ) : null} + return ( + + ); + })}
- {/* Section 3: Accent Color */} - -
-

- Override the primary color across the app. -

-
- {/* Default pill */} - + {(["light", "dark"] as const satisfies ReadonlyArray).map((mode) => { + const activeTheme = activeThemeByMode[mode]; + const importInputRef = mode === "light" ? lightImportInputRef : darkImportInputRef; - {/* Preset circles */} - {ACCENT_PRESETS.map((preset) => ( - setAccentHue(preset.hue)} - /> - ))} + return ( + + + + + + {activeTheme.origin === "custom" ? ( + + ) : null} +
+ } + > +
+
+
+

{activeTheme.name}

+

+ Builtin themes stay immutable. The first edit automatically creates a custom + copy. +

+
+ + {activeTheme.origin === "builtin" ? "Builtin preset" : "Custom theme"} + +
+ +
+ {themeLibraryByMode[mode].map((entry) => ( + updateModeSelection(mode, entry.theme.id)} + /> + ))} +
- {/* Custom color picker */} - + {importErrors[mode] ? ( +
+

Import failed

+

{importErrors[mode]}

+
+ ) : null} + +
+ handleThemeChange(mode, updater)} + /> +
+
+ + ); + })} + + +
+
+

Theme document

+

+ JSON import uses the annotated `ThemeDocumentSchema`. Each file represents exactly one + mode and should mostly contain simple base colors, fonts, radius, font size, and + contrast. Advanced overrides are optional. +

+
{`{
+  "id": "custom-codex-light",
+  "name": "Custom Codex Light",
+  "version": 1,
+  "origin": "custom",
+  "mode": "light",
+  "radius": "0.625rem",
+  "fontSize": "16px",
+  "accent": "#0169cc",
+  "background": "#ffffff",
+  "foreground": "#0d0d0d",
+  "uiFontFamily": "\\"IBM Plex Sans\\", sans-serif",
+  "codeFontFamily": "\\"IBM Plex Mono\\", monospace",
+  "sidebarTranslucent": true,
+  "contrast": 46
+}`}
- {accentHue !== null ? ( -
- setAccentHue(null)} /> -
- ) : null} +
+

Current theme JSON

+

+ Use Copy JSON inside each mode section to export or share the exact active document. +

+
+              {serializeThemeDocument(activeLightTheme)}
+            
+
); } - -// ── 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; -} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index e64eb01a6b..81c110400a 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -439,8 +439,9 @@ export function useSettingsRestore(onRestored?: () => void) { const changedSettingLabels = useMemo( () => [ ...(settings.colorMode !== "system" ? ["Color mode"] : []), - ...(settings.activeThemeId !== "t3code" ? ["Appearance theme"] : []), - ...(settings.accentHue !== null ? ["Accent color"] : []), + ...(settings.activeLightThemeId !== "t3code-light" ? ["Light appearance theme"] : []), + ...(settings.activeDarkThemeId !== "t3code-dark" ? ["Dark appearance theme"] : []), + ...(settings.customThemes.length > 0 ? ["Custom themes"] : []), ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? ["Time format"] : []), @@ -465,11 +466,12 @@ export function useSettingsRestore(onRestored?: () => void) { [ areProviderSettingsDirty, isGitWritingModelDirty, - settings.accentHue, - settings.activeThemeId, + settings.activeLightThemeId, + settings.activeDarkThemeId, settings.colorMode, settings.confirmThreadArchive, settings.confirmThreadDelete, + settings.customThemes.length, settings.defaultThreadEnvMode, settings.diffWordWrap, settings.enableAssistantStreaming, @@ -487,7 +489,12 @@ export function useSettingsRestore(onRestored?: () => void) { ); if (!confirmed) return; - updateSettings({ colorMode: "system", activeThemeId: "t3code", accentHue: null }); + updateSettings({ + colorMode: "system", + activeLightThemeId: "t3code-light", + activeDarkThemeId: "t3code-dark", + customThemes: [], + }); resetSettings(); onRestored?.(); }, [changedSettingLabels, onRestored, resetSettings, updateSettings]); diff --git a/apps/web/src/components/settings/appearance.logic.test.ts b/apps/web/src/components/settings/appearance.logic.test.ts new file mode 100644 index 0000000000..8700fb395d --- /dev/null +++ b/apps/web/src/components/settings/appearance.logic.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import { BUILTIN_THEME_DOCUMENTS } from "@t3tools/shared/appearance/registry"; +import { + createDuplicateTheme, + ensureUniqueThemeId, + normalizeImportedThemeDocument, + updateThemeDocument, +} from "./appearance.logic"; + +describe("appearance.logic", () => { + it("deduplicates conflicting theme ids", () => { + expect(ensureUniqueThemeId("codex", new Set(["codex", "codex-2"]))).toBe("codex-3"); + }); + + it("normalizes imported themes into custom documents with unique ids", () => { + const imported = normalizeImportedThemeDocument( + BUILTIN_THEME_DOCUMENTS[0]!, + new Set(["t3code-light"]), + ); + expect(imported.origin).toBe("custom"); + expect(imported.id).toBe("t3code-light-2"); + }); + + it("duplicates builtin themes before editing", () => { + const duplicate = createDuplicateTheme(BUILTIN_THEME_DOCUMENTS[0]!, []); + expect(duplicate.origin).toBe("custom"); + expect(duplicate.id).toBe("t3code-light-copy"); + expect(duplicate.radius).toBe(BUILTIN_THEME_DOCUMENTS[0]!.radius); + expect(duplicate.fontSize).toBe(BUILTIN_THEME_DOCUMENTS[0]!.fontSize); + }); + + it("updates flat theme documents", () => { + const updated = updateThemeDocument(BUILTIN_THEME_DOCUMENTS[0]!, (themeDocument) => ({ + ...themeDocument, + contrast: 99, + })); + + expect(updated.contrast).toBe(99); + expect(updated.mode).toBe(BUILTIN_THEME_DOCUMENTS[0]!.mode); + }); +}); diff --git a/apps/web/src/components/settings/appearance.logic.ts b/apps/web/src/components/settings/appearance.logic.ts new file mode 100644 index 0000000000..c278e92a07 --- /dev/null +++ b/apps/web/src/components/settings/appearance.logic.ts @@ -0,0 +1,80 @@ +import type { ThemeDocument } from "@t3tools/contracts"; +import { + canonicalizeThemeDocument, + duplicateThemeDocument, + getReservedThemeIds, +} from "@t3tools/shared/appearance/registry"; + +function toKebabCase(value: string): string { + return value + .toLowerCase() + .trim() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); +} + +export function slugifyThemeId(value: string): string { + return toKebabCase(value) || "custom-theme"; +} + +export function ensureUniqueThemeId(baseId: string, existingIds: ReadonlySet): string { + if (!existingIds.has(baseId)) { + return baseId; + } + + let index = 2; + while (existingIds.has(`${baseId}-${index}`)) { + index += 1; + } + return `${baseId}-${index}`; +} + +export function normalizeImportedThemeDocument( + themeDocument: ThemeDocument, + existingThemeIds: ReadonlySet, +): ThemeDocument { + const baseId = slugifyThemeId(themeDocument.id || themeDocument.name); + const uniqueId = ensureUniqueThemeId(baseId, existingThemeIds); + + return canonicalizeThemeDocument( + { + ...themeDocument, + id: uniqueId, + origin: "custom", + }, + "custom", + ); +} + +export function createDuplicateTheme( + themeDocument: ThemeDocument, + customThemes: ReadonlyArray, +) { + const existingThemeIds = new Set([ + ...getReservedThemeIds(), + ...customThemes.map((theme) => theme.id), + ]); + const baseId = slugifyThemeId(`${themeDocument.id}-copy`); + const nextId = ensureUniqueThemeId(baseId, existingThemeIds); + const nextName = + nextId === `${themeDocument.id}-copy` + ? `${themeDocument.name} Copy` + : `${themeDocument.name} Copy ${nextId.split("-").at(-1)}`; + return duplicateThemeDocument(themeDocument, nextId, nextName); +} + +export function replaceCustomTheme( + customThemes: ReadonlyArray, + nextTheme: ThemeDocument, +): Array { + const next = customThemes.filter((theme) => theme.id !== nextTheme.id); + next.push(canonicalizeThemeDocument(nextTheme, "custom")); + return next; +} + +export function updateThemeDocument( + themeDocument: ThemeDocument, + updater: (themeDocument: ThemeDocument) => ThemeDocument, +): ThemeDocument { + return updater(themeDocument); +} diff --git a/apps/web/src/hooks/useAppearance.test.ts b/apps/web/src/hooks/useAppearance.test.ts new file mode 100644 index 0000000000..197a197353 --- /dev/null +++ b/apps/web/src/hooks/useAppearance.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import { parseAppearanceCache, resolveAppearanceMode } from "./useAppearance"; + +describe("resolveAppearanceMode", () => { + it("resolves explicit modes without consulting system preference", () => { + expect(resolveAppearanceMode("light", true)).toBe("light"); + expect(resolveAppearanceMode("dark", false)).toBe("dark"); + }); + + it("resolves system mode from the current platform preference", () => { + expect(resolveAppearanceMode("system", true)).toBe("dark"); + expect(resolveAppearanceMode("system", false)).toBe("light"); + }); +}); + +describe("parseAppearanceCache", () => { + it("decodes valid cached appearance snapshots", () => { + const parsed = parseAppearanceCache( + JSON.stringify({ + colorMode: "system", + activeLightThemeId: "custom-codex-light", + activeDarkThemeId: "custom-codex-dark", + customThemes: [ + { + id: "custom-codex-light", + name: "Custom Codex Light", + version: 1, + origin: "custom", + mode: "light", + radius: "0.75rem", + fontSize: "15px", + accent: "#0169cc", + background: "#ffffff", + foreground: "#0d0d0d", + uiFontFamily: '"IBM Plex Sans", sans-serif', + codeFontFamily: '"IBM Plex Mono", monospace', + sidebarTranslucent: true, + contrast: 46, + }, + { + id: "custom-codex-dark", + name: "Custom Codex Dark", + version: 1, + origin: "custom", + mode: "dark", + radius: "0.75rem", + fontSize: "15px", + accent: "#0169cc", + background: "#111111", + foreground: "#fcfcfc", + uiFontFamily: '"IBM Plex Sans", sans-serif', + codeFontFamily: '"IBM Plex Mono", monospace', + sidebarTranslucent: true, + contrast: 41, + }, + ], + }), + ); + + expect(parsed?.activeLightThemeId).toBe("custom-codex-light"); + expect(parsed?.activeDarkThemeId).toBe("custom-codex-dark"); + expect(parsed?.customThemes[0]?.id).toBe("custom-codex-light"); + expect(parsed?.customThemes[0]?.radius).toBe("0.75rem"); + expect(parsed?.customThemes[0]?.fontSize).toBe("15px"); + }); + + it("drops invalid cache payloads", () => { + expect( + parseAppearanceCache( + JSON.stringify({ + colorMode: "system", + activeLightThemeId: "custom-codex-light", + activeDarkThemeId: "custom-codex-dark", + customThemes: [{ id: "bad" }], + }), + ), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/hooks/useAppearance.ts b/apps/web/src/hooks/useAppearance.ts index d50a54977d..a62f9c3fc9 100644 --- a/apps/web/src/hooks/useAppearance.ts +++ b/apps/web/src/hooks/useAppearance.ts @@ -1,46 +1,100 @@ -/** - * 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 { Schema } from "effect"; import type { DesktopAppearance } from "@t3tools/contracts"; -import { applyThemeTokens, findThemeById, removeThemeTokens, BUILT_IN_THEMES } from "~/lib/themes"; +import { + ColorMode, + ThemeDocumentSchema, + type ThemeMode, + type ColorMode as AppearanceColorMode, +} from "@t3tools/contracts"; +import { + applyThemeDocumentStyles, + applyThemeVariant, + clearThemeCssVariables, +} from "@t3tools/shared/appearance/apply"; +import { + type ResolvedThemeMode, + type ThemeCssVariableMap, +} from "@t3tools/shared/appearance/derive"; +import { + DEFAULT_DARK_THEME_ID, + DEFAULT_LIGHT_THEME_ID, + resolveThemeDocument, + serializeAppearanceSnapshot, +} from "@t3tools/shared/appearance/registry"; import { useSettings, useUpdateSettings } from "./useSettings"; -// ── Constants ──────────────────────────────────────────────────── - const APPEARANCE_CACHE_KEY = "t3code:appearance-cache"; const MEDIA_QUERY = "(prefers-color-scheme: dark)"; +const AppearanceCacheSchema = Schema.Struct({ + colorMode: ColorMode, + activeLightThemeId: Schema.String, + activeDarkThemeId: Schema.String, + customThemes: Schema.Array(ThemeDocumentSchema), +}); +type AppearanceCache = typeof AppearanceCacheSchema.Type; -// ── Helpers ────────────────────────────────────────────────────── +let appliedVariableNames: ReadonlyArray = []; +let lastDesktopAppearance: string | null = null; function getSystemDark(): boolean { - return window.matchMedia(MEDIA_QUERY).matches; + return typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY).matches : false; +} + +export function resolveAppearanceMode( + colorMode: AppearanceColorMode, + systemDark: boolean, +): ResolvedThemeMode { + if (colorMode === "system") { + return systemDark ? "dark" : "light"; + } + return colorMode; +} + +export function parseAppearanceCache(raw: string | null): AppearanceCache | null { + if (!raw) return null; + + try { + const parsed = JSON.parse(raw); + return Schema.decodeUnknownSync(AppearanceCacheSchema)(parsed); + } catch { + return null; + } +} + +function resolveActiveThemeId(appearance: AppearanceCache, resolvedTheme: ThemeMode): string { + return resolvedTheme === "dark" ? appearance.activeDarkThemeId : appearance.activeLightThemeId; +} + +function applyResolvedAppearance( + appearance: AppearanceCache, + resolvedTheme: ResolvedThemeMode, +): void { + const themeDocument = resolveThemeDocument( + resolveActiveThemeId(appearance, resolvedTheme), + appearance.customThemes, + resolvedTheme, + ); + const root = document.documentElement; + + root.classList.toggle("dark", resolvedTheme === "dark"); + root.style.colorScheme = resolvedTheme; + root.dataset.sidebarTranslucent = String(themeDocument.sidebarTranslucent); + applyThemeDocumentStyles(root.style, themeDocument); + + clearThemeCssVariables(root.style, appliedVariableNames); + appliedVariableNames = applyThemeVariant(root.style, themeDocument); } 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; + void 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; @@ -61,27 +115,25 @@ function syncDesktopAppearance(appearance: DesktopAppearance): void { } } -// ── FOUC prevention (module scope — runs before React mounts) ─── +if (typeof window !== "undefined" && typeof document !== "undefined") { + const cachedAppearance = parseAppearanceCache(localStorage.getItem(APPEARANCE_CACHE_KEY)); + const initialAppearance = + cachedAppearance ?? + ({ + colorMode: "system", + activeLightThemeId: DEFAULT_LIGHT_THEME_ID, + activeDarkThemeId: DEFAULT_DARK_THEME_ID, + customThemes: [], + } satisfies AppearanceCache); + const resolvedTheme = resolveAppearanceMode(initialAppearance.colorMode, getSystemDark()); -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, isDark ? "dark" : "light"); + try { + applyResolvedAppearance(initialAppearance, resolvedTheme); + } catch { + // The cache is best-effort. React will reconcile once settings load. } -} 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; @@ -104,66 +156,86 @@ function subscribeSystemDark(listener: () => void): () => void { }; } -// ── Hook ───────────────────────────────────────────────────────── - export function useAppearance() { - const { colorMode, activeThemeId, accentHue } = useSettings((s) => ({ + const { colorMode, activeLightThemeId, activeDarkThemeId, customThemes } = useSettings((s) => ({ colorMode: s.colorMode, - activeThemeId: s.activeThemeId, - accentHue: s.accentHue, + activeLightThemeId: s.activeLightThemeId, + activeDarkThemeId: s.activeDarkThemeId, + customThemes: s.customThemes, })); 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], + const activeLightTheme = useMemo( + () => resolveThemeDocument(activeLightThemeId, customThemes, "light"), + [activeLightThemeId, customThemes], + ); + const activeDarkTheme = useMemo( + () => resolveThemeDocument(activeDarkThemeId, customThemes, "dark"), + [activeDarkThemeId, customThemes], ); - // Apply .dark class, theme tokens, cache, and relay to Electron + const systemDark = useSyncExternalStore(subscribeSystemDark, getSystemDarkSnapshot); + + const resolvedTheme = useMemo( + () => resolveAppearanceMode(colorMode, systemDark), + [colorMode, systemDark], + ); + const activeResolvedTheme = resolvedTheme === "dark" ? activeDarkTheme : activeLightTheme; + useEffect(() => { suppressTransitions(() => { - document.documentElement.classList.toggle("dark", resolvedTheme === "dark"); - applyThemeTokens(activeTheme, accentHue, resolvedTheme); + applyResolvedAppearance( + { colorMode, activeLightThemeId, activeDarkThemeId, customThemes }, + resolvedTheme, + ); }); - // Write-through cache for FOUC prevention on next load localStorage.setItem( APPEARANCE_CACHE_KEY, - JSON.stringify({ colorMode, activeThemeId, accentHue }), + serializeAppearanceSnapshot({ + colorMode, + activeLightThemeId, + activeDarkThemeId, + customThemes, + }), ); - // Sync to Electron - syncDesktopAppearance({ mode: colorMode, themeId: activeThemeId, accentHue }); - - return () => removeThemeTokens(); - }, [resolvedTheme, activeTheme, accentHue, colorMode, activeThemeId]); + syncDesktopAppearance({ mode: colorMode, themeId: activeResolvedTheme.id }); + }, [ + resolvedTheme, + activeResolvedTheme, + activeLightThemeId, + activeDarkThemeId, + colorMode, + customThemes, + ]); const setColorMode = useCallback( - (mode: ColorMode) => updateSettings({ colorMode: mode }), + (mode: AppearanceColorMode) => updateSettings({ colorMode: mode }), [updateSettings], ); const setThemeId = useCallback( - (id: string) => updateSettings({ activeThemeId: id }), + (mode: ThemeMode, id: string) => + updateSettings(mode === "dark" ? { activeDarkThemeId: id } : { activeLightThemeId: id }), [updateSettings], ); - const setAccentHue = useCallback( - (hue: number | null) => updateSettings({ accentHue: hue }), + const setCustomThemes = useCallback( + (themes: AppearanceCache["customThemes"]) => updateSettings({ customThemes: themes }), [updateSettings], ); return { colorMode, resolvedTheme, - activeTheme, - accentHue, + activeLightTheme, + activeDarkTheme, + activeResolvedTheme, + activeLightThemeId, + activeDarkThemeId, + customThemes, setColorMode, setThemeId, - setAccentHue, + setCustomThemes, } as const; } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 2fae5966f2..98d74344d8 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -4,6 +4,11 @@ @theme inline { --animate-skeleton: skeleton 2s -1s infinite linear; + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar: var(--sidebar); --color-diff-deletion: var(--diff-deletion); --color-diff-addition: var(--diff-addition); --color-warning-foreground: var(--warning-foreground); @@ -64,76 +69,19 @@ } :root { - color-scheme: light; --radius: 0.625rem; - --background: var(--color-white); - --foreground: var(--color-neutral-800); - --card: var(--color-white); - --card-foreground: var(--color-neutral-800); - --popover: var(--color-white); - --popover-foreground: var(--color-neutral-800); - --primary: oklch(0.488 0.217 264); - --primary-foreground: var(--color-white); - --secondary: --alpha(var(--color-black) / 4%); - --secondary-foreground: var(--color-neutral-800); - --muted: --alpha(var(--color-black) / 4%); - --muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black)); - --accent: --alpha(var(--color-black) / 4%); - --accent-foreground: var(--color-neutral-800); - --destructive: var(--color-red-500); - --border: --alpha(var(--color-black) / 8%); - --input: --alpha(var(--color-black) / 10%); - --ring: oklch(0.488 0.217 264); - --destructive-foreground: var(--color-red-700); - --info: var(--color-blue-500); - --info-foreground: var(--color-blue-700); - --success: var(--color-emerald-500); - --success-foreground: var(--color-emerald-700); - --warning: var(--color-amber-500); - --warning-foreground: var(--color-amber-700); - --diff-addition: var(--success); - --diff-deletion: var(--destructive); - - @variant dark { - color-scheme: dark; - --background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white)); - --foreground: var(--color-neutral-100); - --card: color-mix(in srgb, var(--background) 98%, var(--color-white)); - --card-foreground: var(--color-neutral-100); - --popover: color-mix(in srgb, var(--background) 98%, var(--color-white)); - --popover-foreground: var(--color-neutral-100); - --primary: oklch(0.588 0.217 264); - --primary-foreground: var(--color-white); - --secondary: --alpha(var(--color-white) / 4%); - --secondary-foreground: var(--color-neutral-100); - --muted: --alpha(var(--color-white) / 4%); - --muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white)); - --accent: --alpha(var(--color-white) / 4%); - --accent-foreground: var(--color-neutral-100); - --destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white)); - --border: --alpha(var(--color-white) / 6%); - --input: --alpha(var(--color-white) / 8%); - --ring: oklch(0.588 0.217 264); - --destructive-foreground: var(--color-red-400); - --info: var(--color-blue-500); - --info-foreground: var(--color-blue-400); - --success: var(--color-emerald-500); - --success-foreground: var(--color-emerald-400); - --warning: var(--color-amber-500); - --warning-foreground: var(--color-amber-400); - --diff-addition: var(--success); - --diff-deletion: var(--destructive); - } } body { - font-family: + font-family: var( + --ui-font-family, "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, - sans-serif; + sans-serif + ); margin: 0; padding: 0; min-height: 100vh; @@ -166,7 +114,19 @@ pre, code, textarea, input { - font-family: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; + font-family: var( + --code-font-family, + "SF Mono", + "SFMono-Regular", + Consolas, + "Liberation Mono", + Menlo, + monospace + ); +} + +html[data-sidebar-translucent="true"] [data-sidebar="sidebar"] { + backdrop-filter: blur(var(--sidebar-blur, 0px)); } /* Window drag region (frameless titlebar) */ diff --git a/apps/web/src/lib/themes.ts b/apps/web/src/lib/themes.ts deleted file mode 100644 index 8415b40265..0000000000 --- a/apps/web/src/lib/themes.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Theme definitions, CSS injection, and accent color derivation. - * - * V1 themes override a focused set of CSS custom properties. - * Background/surface tokens stay controlled by the CSS baseline in index.css. - * - * The override targets are the intermediate variables (--primary, --border, etc.) - * which feed into Tailwind's --color-* via @theme inline { --color-primary: var(--primary) }. - */ - -// ── 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" - | "muted-foreground" - | "border" - | "input" - | "diff-addition" - | "diff-deletion"; - -export type ThemeTokenMap = Partial>; - -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: {}, -}; - -/** - * High Contrast — strengthens borders, inputs, and muted text for readability. - * Ported from PR #1284 which overrides --muted-foreground, --border, --input. - */ -const HIGH_CONTRAST_THEME: ThemeDefinition = { - id: "high-contrast", - name: "High Contrast", - description: "Stronger borders and text for readability.", - builtIn: true, - light: { - "muted-foreground": "color-mix(in srgb, var(--color-neutral-700) 92%, var(--color-black))", - border: "--alpha(var(--color-black) / 45%)", - input: "--alpha(var(--color-black) / 50%)", - }, - dark: { - "muted-foreground": "color-mix(in srgb, var(--color-neutral-300) 92%, var(--color-white))", - border: "--alpha(var(--color-white) / 40%)", - input: "--alpha(var(--color-white) / 45%)", - }, -}; - -/** - * Color Blind — replaces red/green juxtaposition in diffs with blue/orange. - * Ported from PR #1535 which uses GitHub Primer @primer/primitives diffBlob palette. - * - * Only overrides --diff-addition / --diff-deletion (the diff-specific tokens). - * Success (green) and destructive (red) are fine in isolation — the problem - * is only when they appear side-by-side in diffs. - */ -const COLOR_BLIND_THEME: ThemeDefinition = { - id: "color-blind", - name: "Color Blind", - description: "Blue/orange diffs for color vision deficiency.", - builtIn: true, - light: { - "diff-addition": "#0969da", // blue (replaces green) - "diff-deletion": "#bc4c00", // orange (replaces red) - }, - dark: { - "diff-addition": "#388bfd", // blue (replaces green) - "diff-deletion": "#db6d28", // orange (replaces red) - }, -}; - -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 via inline styles ────────────────────────────── -// -// We set CSS custom properties directly on document.documentElement.style -// (inline styles). This is the highest specificity in the cascade and -// guarantees our overrides beat any stylesheet — including Vite HMR -// injections that can reorder