Add customizable appearance themes
- Replace single-theme settings with light and dark theme libraries - Persist custom theme definitions and add import, copy, duplicate, and reset flows - Update shared appearance contracts, UI, and tests
This commit is contained in:
1 parent
973ab3232f
commit
e5de3d0c8c
23 files changed
+2501
-586
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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())),
|
||||
);
|
||||
});
|
||||
@@ -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: [] },
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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]);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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>): 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<string>,
|
||||
): 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<ThemeDocument>,
|
||||
) {
|
||||
const existingThemeIds = new Set<string>([
|
||||
...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<ThemeDocument>,
|
||||
nextTheme: ThemeDocument,
|
||||
): Array<ThemeDocument> {
|
||||
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);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<keyof ThemeCssVariableMap> = [];
|
||||
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;
|
||||
}
|
||||
+22
-62
@@ -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) */
|
||||
|
||||
@@ -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<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: {},
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 <style> elements unpredictably.
|
||||
|
||||
/** Track which properties were set so we can clean them up. */
|
||||
let appliedProperties: string[] = [];
|
||||
|
||||
/**
|
||||
* Apply theme token overrides as inline CSS custom properties on <html>.
|
||||
* Resolves light/dark tokens based on `resolvedTheme` and sets them directly.
|
||||
* When the T3Code default is active with no accent, removes all overrides.
|
||||
*/
|
||||
export function applyThemeTokens(
|
||||
theme: ThemeDefinition,
|
||||
accentHue: number | null,
|
||||
resolvedTheme: "light" | "dark",
|
||||
): void {
|
||||
const accent = accentHue != null ? deriveAccentColors(accentHue) : null;
|
||||
|
||||
const tokens: ThemeTokenMap =
|
||||
resolvedTheme === "dark"
|
||||
? { ...theme.dark, ...accent?.dark }
|
||||
: { ...theme.light, ...accent?.light };
|
||||
|
||||
// Clean up previously applied properties
|
||||
removeThemeTokens();
|
||||
|
||||
const entries = Object.entries(tokens) as [ThemeToken, string][];
|
||||
if (entries.length === 0) return;
|
||||
|
||||
const el = document.documentElement;
|
||||
const props: string[] = [];
|
||||
for (const [token, value] of entries) {
|
||||
const prop = `--${token}`;
|
||||
el.style.setProperty(prop, value);
|
||||
props.push(prop);
|
||||
}
|
||||
appliedProperties = props;
|
||||
}
|
||||
|
||||
export function removeThemeTokens(): void {
|
||||
const el = document.documentElement;
|
||||
for (const prop of appliedProperties) {
|
||||
el.style.removeProperty(prop);
|
||||
}
|
||||
appliedProperties = [];
|
||||
}
|
||||
@@ -10,6 +10,11 @@
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
"./appearanceTheme": {
|
||||
"types": "./src/appearanceTheme.ts",
|
||||
"import": "./src/appearanceTheme.ts",
|
||||
"require": "./src/appearanceTheme.ts"
|
||||
},
|
||||
"./settings": {
|
||||
"types": "./src/settings.ts",
|
||||
"import": "./src/settings.ts",
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
const HEX_COLOR_PATTERN = /^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
||||
|
||||
const HexColor = TrimmedNonEmptyString.check(Schema.isPattern(HEX_COLOR_PATTERN)).annotate({
|
||||
title: "Hex color",
|
||||
description: "A 6-digit or 8-digit hex color string.",
|
||||
examples: ["#0169cc", "#f5f7fb", "#0d0d0d"],
|
||||
});
|
||||
|
||||
const CssColorValue = TrimmedNonEmptyString.annotate({
|
||||
title: "CSS color value",
|
||||
description: "Any valid CSS color string or color-mix expression.",
|
||||
examples: ["#0b6bcb", "rgb(10 20 30 / 80%)", "color-mix(in srgb, #111 92%, #fff)"],
|
||||
});
|
||||
|
||||
const FontFamilyValue = TrimmedNonEmptyString.annotate({
|
||||
title: "Font family",
|
||||
description: "A CSS font-family value.",
|
||||
examples: [
|
||||
'"Fraunces", "Iowan Old Style", serif',
|
||||
'"IBM Plex Sans", "Segoe UI", sans-serif',
|
||||
'"SF Mono", Menlo, monospace',
|
||||
],
|
||||
});
|
||||
|
||||
const CssLengthValue = TrimmedNonEmptyString.annotate({
|
||||
title: "CSS length",
|
||||
description: "A CSS length value such as px, rem, or em.",
|
||||
examples: ["16px", "0.625rem", "1em"],
|
||||
});
|
||||
|
||||
const ThemeContrast = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
|
||||
.check(Schema.isLessThanOrEqualTo(100))
|
||||
.annotate({
|
||||
title: "Contrast",
|
||||
description: "A normalized contrast modifier from 0 to 100.",
|
||||
examples: [24, 46, 72],
|
||||
});
|
||||
|
||||
export const DEFAULT_THEME_RADIUS = "0.625rem";
|
||||
export const DEFAULT_THEME_FONT_SIZE = "16px";
|
||||
|
||||
export const ThemeRadiusSchema = CssLengthValue.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_THEME_RADIUS),
|
||||
).annotate({
|
||||
title: "Theme radius",
|
||||
description: "Global corner radius used by the theme.",
|
||||
examples: ["0.625rem", "0.5rem", "0.875rem"],
|
||||
});
|
||||
export type ThemeRadius = typeof ThemeRadiusSchema.Type;
|
||||
|
||||
export const ThemeFontSizeSchema = CssLengthValue.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_THEME_FONT_SIZE),
|
||||
).annotate({
|
||||
title: "Theme font size",
|
||||
description: "Base root font size used by the theme.",
|
||||
examples: ["16px", "15px", "17px"],
|
||||
});
|
||||
export type ThemeFontSize = typeof ThemeFontSizeSchema.Type;
|
||||
|
||||
const OverrideTokenValue = CssColorValue.annotate({
|
||||
title: "Override token",
|
||||
description: "An explicit override for a derived appearance token.",
|
||||
});
|
||||
|
||||
function makeOverrideField(title: string, description: string, examples?: ReadonlyArray<string>) {
|
||||
return Schema.optionalKey(
|
||||
OverrideTokenValue.annotate({
|
||||
title,
|
||||
description,
|
||||
...(examples ? { examples } : {}),
|
||||
}),
|
||||
).annotateKey({ title, description });
|
||||
}
|
||||
|
||||
export const ThemeSeedColorsSchema = Schema.Struct({
|
||||
accent: HexColor.annotate({
|
||||
title: "Accent",
|
||||
description: "Primary brand or highlight color used for actions and focus states.",
|
||||
examples: ["#0169cc", "#d95f2b", "#00827a"],
|
||||
}).annotateKey({
|
||||
title: "Accent",
|
||||
description: "Primary brand or highlight color used for actions and focus states.",
|
||||
}),
|
||||
background: HexColor.annotate({
|
||||
title: "Background",
|
||||
description: "Primary canvas color for the app surface.",
|
||||
examples: ["#ffffff", "#111111", "#f7f0e8"],
|
||||
}).annotateKey({
|
||||
title: "Background",
|
||||
description: "Primary canvas color for the app surface.",
|
||||
}),
|
||||
foreground: HexColor.annotate({
|
||||
title: "Foreground",
|
||||
description: "Primary text color drawn over the background.",
|
||||
examples: ["#0d0d0d", "#fcfcfc", "#1a120f"],
|
||||
}).annotateKey({
|
||||
title: "Foreground",
|
||||
description: "Primary text color drawn over the background.",
|
||||
}),
|
||||
}).annotate({
|
||||
title: "Theme seed colors",
|
||||
description: "The base palette from which the rest of the appearance tokens are derived.",
|
||||
});
|
||||
export type ThemeSeedColors = typeof ThemeSeedColorsSchema.Type;
|
||||
|
||||
export const ThemeDerivedOverridesSchema = Schema.Struct({
|
||||
background: makeOverrideField("Background", "Override the primary app background."),
|
||||
foreground: makeOverrideField("Foreground", "Override the primary app foreground color."),
|
||||
card: makeOverrideField("Card", "Override the card background."),
|
||||
cardForeground: makeOverrideField("Card foreground", "Override the text color used on cards."),
|
||||
popover: makeOverrideField("Popover", "Override the popover background."),
|
||||
popoverForeground: makeOverrideField(
|
||||
"Popover foreground",
|
||||
"Override the text color used on popovers.",
|
||||
),
|
||||
primary: makeOverrideField("Primary", "Override the primary accent fill."),
|
||||
primaryForeground: makeOverrideField(
|
||||
"Primary foreground",
|
||||
"Override the text color used on the primary accent fill.",
|
||||
),
|
||||
secondary: makeOverrideField("Secondary", "Override the secondary surface."),
|
||||
secondaryForeground: makeOverrideField(
|
||||
"Secondary foreground",
|
||||
"Override the text color used on the secondary surface.",
|
||||
),
|
||||
muted: makeOverrideField("Muted", "Override the muted surface."),
|
||||
mutedForeground: makeOverrideField(
|
||||
"Muted foreground",
|
||||
"Override the text color used for muted copy.",
|
||||
),
|
||||
accentSurface: makeOverrideField("Accent surface", "Override the accent-tinted surface token."),
|
||||
accentForeground: makeOverrideField(
|
||||
"Accent foreground",
|
||||
"Override the text color used on accent-tinted surfaces.",
|
||||
),
|
||||
border: makeOverrideField("Border", "Override the default border color."),
|
||||
input: makeOverrideField("Input", "Override the default input border or fill color."),
|
||||
ring: makeOverrideField("Ring", "Override the focus ring color."),
|
||||
destructive: makeOverrideField("Destructive", "Override the destructive fill color."),
|
||||
destructiveForeground: makeOverrideField(
|
||||
"Destructive foreground",
|
||||
"Override the text color used on destructive fills.",
|
||||
),
|
||||
info: makeOverrideField("Info", "Override the informational fill color."),
|
||||
infoForeground: makeOverrideField(
|
||||
"Info foreground",
|
||||
"Override the text color used on informational fills.",
|
||||
),
|
||||
success: makeOverrideField("Success", "Override the success fill color."),
|
||||
successForeground: makeOverrideField(
|
||||
"Success foreground",
|
||||
"Override the text color used on success fills.",
|
||||
),
|
||||
warning: makeOverrideField("Warning", "Override the warning fill color."),
|
||||
warningForeground: makeOverrideField(
|
||||
"Warning foreground",
|
||||
"Override the text color used on warning fills.",
|
||||
),
|
||||
diffAddition: makeOverrideField("Diff addition", "Override the addition color used in diffs.", [
|
||||
"#0969da",
|
||||
]),
|
||||
diffDeletion: makeOverrideField("Diff deletion", "Override the deletion color used in diffs.", [
|
||||
"#bc4c00",
|
||||
]),
|
||||
sidebar: makeOverrideField("Sidebar", "Override the sidebar surface."),
|
||||
sidebarForeground: makeOverrideField(
|
||||
"Sidebar foreground",
|
||||
"Override the default sidebar text color.",
|
||||
),
|
||||
sidebarAccent: makeOverrideField("Sidebar accent", "Override hover and active sidebar surfaces."),
|
||||
sidebarAccentForeground: makeOverrideField(
|
||||
"Sidebar accent foreground",
|
||||
"Override text color on sidebar hover and active surfaces.",
|
||||
),
|
||||
sidebarBorder: makeOverrideField("Sidebar border", "Override sidebar border and divider color."),
|
||||
}).annotate({
|
||||
title: "Theme overrides",
|
||||
description: "Optional advanced overrides for exact control over derived appearance tokens.",
|
||||
});
|
||||
export type ThemeDerivedOverrides = typeof ThemeDerivedOverridesSchema.Type;
|
||||
|
||||
export const ThemeVariantSchema = Schema.Struct({
|
||||
...ThemeSeedColorsSchema.fields,
|
||||
uiFontFamily: FontFamilyValue.annotate({
|
||||
title: "UI font family",
|
||||
description: "Font family used for the application interface.",
|
||||
}).annotateKey({
|
||||
title: "UI font family",
|
||||
description: "Font family used for the application interface.",
|
||||
}),
|
||||
codeFontFamily: FontFamilyValue.annotate({
|
||||
title: "Code font family",
|
||||
description: "Font family used for code, terminal, and monospace surfaces.",
|
||||
}).annotateKey({
|
||||
title: "Code font family",
|
||||
description: "Font family used for code, terminal, and monospace surfaces.",
|
||||
}),
|
||||
sidebarTranslucent: Schema.Boolean.annotate({
|
||||
title: "Translucent sidebar",
|
||||
description: "Whether the sidebar should render with translucency.",
|
||||
examples: [true, false],
|
||||
}).annotateKey({
|
||||
title: "Translucent sidebar",
|
||||
description: "Whether the sidebar should render with translucency.",
|
||||
}),
|
||||
contrast: ThemeContrast.annotateKey({
|
||||
title: "Contrast",
|
||||
description: "A normalized contrast modifier from 0 to 100.",
|
||||
}),
|
||||
overrides: Schema.optionalKey(ThemeDerivedOverridesSchema).annotateKey({
|
||||
title: "Overrides",
|
||||
description: "Optional advanced overrides for exact control over derived appearance tokens.",
|
||||
}),
|
||||
}).annotate({
|
||||
title: "Theme variant",
|
||||
description:
|
||||
"A light or dark appearance variant with seed colors, fonts, and optional overrides.",
|
||||
});
|
||||
export type ThemeVariant = typeof ThemeVariantSchema.Type;
|
||||
|
||||
export const ThemeOriginSchema = Schema.Literals(["builtin", "custom"]).annotate({
|
||||
title: "Theme origin",
|
||||
description: "Whether a theme ships with the app or was created/imported by the user.",
|
||||
examples: ["builtin", "custom"],
|
||||
});
|
||||
export type ThemeOrigin = typeof ThemeOriginSchema.Type;
|
||||
|
||||
export const ThemeModeSchema = Schema.Literals(["light", "dark"]).annotate({
|
||||
title: "Theme mode",
|
||||
description: "Whether this theme targets light mode or dark mode.",
|
||||
examples: ["light", "dark"],
|
||||
});
|
||||
export type ThemeMode = typeof ThemeModeSchema.Type;
|
||||
|
||||
export const ThemeVersionSchema = Schema.Literal(1).annotate({
|
||||
title: "Theme document version",
|
||||
description: "Version of the theme document schema.",
|
||||
examples: [1],
|
||||
});
|
||||
export type ThemeVersion = typeof ThemeVersionSchema.Type;
|
||||
|
||||
export const ThemeMetadataSchema = Schema.Struct({
|
||||
id: TrimmedNonEmptyString.annotate({
|
||||
title: "Theme id",
|
||||
description: "Stable identifier used for selection and persistence.",
|
||||
examples: ["t3code", "warm-editorial", "custom-midnight-ledger"],
|
||||
}).annotateKey({
|
||||
title: "Theme id",
|
||||
description: "Stable identifier used for selection and persistence.",
|
||||
}),
|
||||
name: TrimmedNonEmptyString.annotate({
|
||||
title: "Theme name",
|
||||
description: "Human-readable theme label shown in the UI.",
|
||||
examples: ["T3Code", "Warm Ledger", "Cool Current"],
|
||||
}).annotateKey({
|
||||
title: "Theme name",
|
||||
description: "Human-readable theme label shown in the UI.",
|
||||
}),
|
||||
version: ThemeVersionSchema.annotateKey({
|
||||
title: "Version",
|
||||
description: "Version of the theme document schema.",
|
||||
}),
|
||||
origin: ThemeOriginSchema.annotateKey({
|
||||
title: "Origin",
|
||||
description: "Whether the theme is builtin or custom.",
|
||||
}),
|
||||
}).annotate({
|
||||
title: "Theme metadata",
|
||||
description: "Metadata shared by every appearance theme document.",
|
||||
});
|
||||
export type ThemeMetadata = typeof ThemeMetadataSchema.Type;
|
||||
|
||||
export const ThemeDocumentSchema = Schema.Struct({
|
||||
...ThemeMetadataSchema.fields,
|
||||
mode: ThemeModeSchema.annotateKey({
|
||||
title: "Mode",
|
||||
description: "Whether this theme targets light mode or dark mode.",
|
||||
}),
|
||||
radius: ThemeRadiusSchema.annotateKey({
|
||||
title: "Radius",
|
||||
description: "Global corner radius used across the interface.",
|
||||
}),
|
||||
fontSize: ThemeFontSizeSchema.annotateKey({
|
||||
title: "Font size",
|
||||
description: "Base root font size used across the interface.",
|
||||
}),
|
||||
...ThemeVariantSchema.fields,
|
||||
}).annotate({
|
||||
title: "Theme document",
|
||||
description: "A complete single-mode appearance theme document.",
|
||||
examples: [
|
||||
{
|
||||
id: "codex-light",
|
||||
name: "Codex Light",
|
||||
version: 1,
|
||||
origin: "custom",
|
||||
mode: "light",
|
||||
radius: "0.625rem",
|
||||
fontSize: "16px",
|
||||
accent: "#0169cc",
|
||||
background: "#ffffff",
|
||||
foreground: "#0d0d0d",
|
||||
uiFontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
|
||||
codeFontFamily: '"SF Mono", Menlo, monospace',
|
||||
sidebarTranslucent: true,
|
||||
contrast: 46,
|
||||
},
|
||||
],
|
||||
});
|
||||
export type ThemeDocument = typeof ThemeDocumentSchema.Type;
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./baseSchemas";
|
||||
export * from "./appearanceTheme";
|
||||
export * from "./ipc";
|
||||
export * from "./terminal";
|
||||
export * from "./provider";
|
||||
|
||||
@@ -76,7 +76,6 @@ export type DesktopTheme = "light" | "dark" | "system";
|
||||
export type DesktopAppearance = {
|
||||
mode: DesktopTheme;
|
||||
themeId: string;
|
||||
accentHue: number | null;
|
||||
};
|
||||
|
||||
export interface DesktopRuntimeInfo {
|
||||
|
||||
@@ -1,8 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "./settings";
|
||||
import { Schema } from "effect";
|
||||
import { ThemeDocumentSchema } from "./appearanceTheme";
|
||||
import { DEFAULT_CLIENT_SETTINGS, ServerSettingsPatch } from "./settings";
|
||||
|
||||
describe("DEFAULT_CLIENT_SETTINGS", () => {
|
||||
it("includes archive confirmation with a false default", () => {
|
||||
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ThemeDocumentSchema", () => {
|
||||
it("decodes a valid custom theme document", () => {
|
||||
const theme = Schema.decodeUnknownSync(ThemeDocumentSchema)({
|
||||
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: 44,
|
||||
overrides: {
|
||||
diffAddition: "#0969da",
|
||||
diffDeletion: "#bc4c00",
|
||||
},
|
||||
});
|
||||
|
||||
expect(theme.overrides?.diffAddition).toBe("#0969da");
|
||||
expect(theme.mode).toBe("light");
|
||||
expect(theme.radius).toBe("0.75rem");
|
||||
expect(theme.fontSize).toBe("15px");
|
||||
});
|
||||
|
||||
it("rejects invalid seed colors", () => {
|
||||
expect(() =>
|
||||
Schema.decodeUnknownSync(ThemeDocumentSchema)({
|
||||
id: "bad-theme",
|
||||
name: "Bad Theme",
|
||||
version: 1,
|
||||
origin: "custom",
|
||||
mode: "light",
|
||||
accent: "blue",
|
||||
background: "#ffffff",
|
||||
foreground: "#0d0d0d",
|
||||
uiFontFamily: "sans-serif",
|
||||
codeFontFamily: "monospace",
|
||||
sidebarTranslucent: false,
|
||||
contrast: 40,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerSettingsPatch", () => {
|
||||
it("accepts customThemes updates", () => {
|
||||
const patch = Schema.decodeUnknownSync(ServerSettingsPatch)({
|
||||
activeLightThemeId: "custom-codex-light",
|
||||
activeDarkThemeId: "t3code-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: false,
|
||||
contrast: 38,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(patch.activeLightThemeId).toBe("custom-codex-light");
|
||||
expect(patch.customThemes?.[0]?.id).toBe("custom-codex-light");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Effect } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
import { ThemeDocumentSchema } from "./appearanceTheme";
|
||||
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas";
|
||||
import {
|
||||
ClaudeModelOptions,
|
||||
@@ -45,7 +46,8 @@ 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";
|
||||
export const DEFAULT_ACTIVE_LIGHT_THEME_ID = "t3code-light";
|
||||
export const DEFAULT_ACTIVE_DARK_THEME_ID = "t3code-dark";
|
||||
|
||||
// ── Server Settings (server-authoritative) ────────────────────
|
||||
|
||||
@@ -95,8 +97,13 @@ export const ServerSettings = Schema.Struct({
|
||||
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)),
|
||||
activeLightThemeId: Schema.String.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_ACTIVE_LIGHT_THEME_ID),
|
||||
),
|
||||
activeDarkThemeId: Schema.String.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_ACTIVE_DARK_THEME_ID),
|
||||
),
|
||||
customThemes: Schema.Array(ThemeDocumentSchema).pipe(Schema.withDecodingDefault(() => [])),
|
||||
|
||||
// Provider specific settings
|
||||
providers: Schema.Struct({
|
||||
@@ -160,8 +167,9 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
|
||||
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
|
||||
colorMode: Schema.optionalKey(ColorMode),
|
||||
activeThemeId: Schema.optionalKey(Schema.String),
|
||||
accentHue: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
activeLightThemeId: Schema.optionalKey(Schema.String),
|
||||
activeDarkThemeId: Schema.optionalKey(Schema.String),
|
||||
customThemes: Schema.optionalKey(Schema.Array(ThemeDocumentSchema)),
|
||||
providers: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
codex: Schema.optionalKey(CodexSettingsPatch),
|
||||
|
||||
@@ -4,6 +4,18 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./appearance/registry": {
|
||||
"types": "./src/appearance/registry.ts",
|
||||
"import": "./src/appearance/registry.ts"
|
||||
},
|
||||
"./appearance/derive": {
|
||||
"types": "./src/appearance/derive.ts",
|
||||
"import": "./src/appearance/derive.ts"
|
||||
},
|
||||
"./appearance/apply": {
|
||||
"types": "./src/appearance/apply.ts",
|
||||
"import": "./src/appearance/apply.ts"
|
||||
},
|
||||
"./model": {
|
||||
"types": "./src/model.ts",
|
||||
"import": "./src/model.ts"
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ThemeDocument, ThemeVariant } from "@t3tools/contracts/appearanceTheme";
|
||||
import { deriveThemeCssVariables, type ThemeCssVariableMap } from "./derive";
|
||||
|
||||
export interface CssVariableTarget {
|
||||
setProperty(name: string, value: string): void;
|
||||
removeProperty(name: string): void;
|
||||
}
|
||||
|
||||
export function applyThemeCssVariables(
|
||||
target: CssVariableTarget,
|
||||
variables: ThemeCssVariableMap,
|
||||
): ReadonlyArray<keyof ThemeCssVariableMap> {
|
||||
const applied: Array<keyof ThemeCssVariableMap> = [];
|
||||
for (const [name, value] of Object.entries(variables) as Array<
|
||||
[keyof ThemeCssVariableMap, string]
|
||||
>) {
|
||||
target.setProperty(name, value);
|
||||
applied.push(name);
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
export function applyThemeVariant(
|
||||
target: CssVariableTarget,
|
||||
themeVariant: ThemeVariant,
|
||||
): ReadonlyArray<keyof ThemeCssVariableMap> {
|
||||
return applyThemeCssVariables(target, deriveThemeCssVariables(themeVariant));
|
||||
}
|
||||
|
||||
export function applyThemeDocumentStyles(
|
||||
target: CssVariableTarget,
|
||||
themeDocument: ThemeDocument,
|
||||
): void {
|
||||
target.setProperty("--radius", themeDocument.radius);
|
||||
target.setProperty("font-size", themeDocument.fontSize);
|
||||
}
|
||||
|
||||
export function clearThemeCssVariables(
|
||||
target: CssVariableTarget,
|
||||
variableNames: ReadonlyArray<keyof ThemeCssVariableMap>,
|
||||
): void {
|
||||
for (const variableName of variableNames) {
|
||||
target.removeProperty(variableName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveThemeCssVariables, deriveThemeTokens } from "./derive";
|
||||
import { BUILTIN_THEME_DOCUMENTS } from "./registry";
|
||||
|
||||
const t3codeLightTheme = BUILTIN_THEME_DOCUMENTS.find((theme) => theme.id === "t3code-light")!;
|
||||
const t3codeDarkTheme = BUILTIN_THEME_DOCUMENTS.find((theme) => theme.id === "t3code-dark")!;
|
||||
const warmLedgerDarkTheme = BUILTIN_THEME_DOCUMENTS.find(
|
||||
(theme) => theme.id === "warm-ledger-dark",
|
||||
)!;
|
||||
const coolCurrentLightTheme = BUILTIN_THEME_DOCUMENTS.find(
|
||||
(theme) => theme.id === "cool-current-light",
|
||||
)!;
|
||||
|
||||
describe("deriveThemeTokens", () => {
|
||||
it("derives the full semantic token set from a light theme", () => {
|
||||
const tokens = deriveThemeTokens(t3codeLightTheme);
|
||||
|
||||
expect(tokens.background).toBe("#fff");
|
||||
expect(tokens.foreground).toBe("oklch(26.9% 0 0)");
|
||||
expect(tokens.primary).toBe("oklch(0.488 0.217 264)");
|
||||
expect(tokens.accent).toBe("color-mix(in oklab, #000 4%, transparent)");
|
||||
expect(tokens.border).toBe("color-mix(in oklab, #000 8%, transparent)");
|
||||
expect(tokens["sidebar-blur"]).toBe("0px");
|
||||
});
|
||||
|
||||
it("preserves the exact main-branch dark baseline for the default theme", () => {
|
||||
const tokens = deriveThemeTokens(t3codeDarkTheme);
|
||||
|
||||
expect(tokens.background).toBe("color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff)");
|
||||
expect(tokens.foreground).toBe("oklch(97% 0 0)");
|
||||
expect(tokens.primary).toBe("oklch(0.588 0.217 264)");
|
||||
expect(tokens.accent).toBe("color-mix(in oklab, #fff 4%, transparent)");
|
||||
expect(tokens.border).toBe("color-mix(in oklab, #fff 6%, transparent)");
|
||||
expect(tokens["sidebar-blur"]).toBe("0px");
|
||||
});
|
||||
|
||||
it("strengthens borders and inputs at higher contrast", () => {
|
||||
const lowContrast = deriveThemeTokens({
|
||||
...warmLedgerDarkTheme,
|
||||
contrast: 10,
|
||||
});
|
||||
const highContrast = deriveThemeTokens({
|
||||
...warmLedgerDarkTheme,
|
||||
contrast: 90,
|
||||
});
|
||||
|
||||
expect(highContrast.border).not.toBe(lowContrast.border);
|
||||
expect(highContrast.input).not.toBe(lowContrast.input);
|
||||
});
|
||||
|
||||
it("applies overrides after derivation", () => {
|
||||
const tokens = deriveThemeTokens({
|
||||
...coolCurrentLightTheme,
|
||||
overrides: {
|
||||
border: "#222222",
|
||||
diffAddition: "#123456",
|
||||
},
|
||||
});
|
||||
|
||||
expect(tokens.border).toBe("#222222");
|
||||
expect(tokens["diff-addition"]).toBe("#123456");
|
||||
});
|
||||
|
||||
it("exports css variable names in the expected format", () => {
|
||||
const variables = deriveThemeCssVariables(t3codeDarkTheme);
|
||||
|
||||
expect(variables["--background"]).toBe("color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff)");
|
||||
expect(variables["--ui-font-family"]).toContain("DM Sans");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,324 @@
|
||||
import type { ThemeDerivedOverrides, ThemeVariant } from "@t3tools/contracts/appearanceTheme";
|
||||
|
||||
export type ResolvedThemeMode = "light" | "dark";
|
||||
|
||||
export const THEME_TOKEN_ORDER = [
|
||||
"background",
|
||||
"foreground",
|
||||
"card",
|
||||
"card-foreground",
|
||||
"popover",
|
||||
"popover-foreground",
|
||||
"primary",
|
||||
"primary-foreground",
|
||||
"secondary",
|
||||
"secondary-foreground",
|
||||
"muted",
|
||||
"muted-foreground",
|
||||
"accent",
|
||||
"accent-foreground",
|
||||
"border",
|
||||
"input",
|
||||
"ring",
|
||||
"destructive",
|
||||
"destructive-foreground",
|
||||
"info",
|
||||
"info-foreground",
|
||||
"success",
|
||||
"success-foreground",
|
||||
"warning",
|
||||
"warning-foreground",
|
||||
"diff-addition",
|
||||
"diff-deletion",
|
||||
"sidebar",
|
||||
"sidebar-foreground",
|
||||
"sidebar-accent",
|
||||
"sidebar-accent-foreground",
|
||||
"sidebar-border",
|
||||
"ui-font-family",
|
||||
"code-font-family",
|
||||
"sidebar-blur",
|
||||
] as const;
|
||||
|
||||
export type ThemeTokenName = (typeof THEME_TOKEN_ORDER)[number];
|
||||
export type ThemeTokenMap = Record<ThemeTokenName, string>;
|
||||
export type ThemeCssVariableMap = Record<`--${ThemeTokenName}`, string>;
|
||||
|
||||
type Rgb = {
|
||||
r: number;
|
||||
g: number;
|
||||
b: number;
|
||||
};
|
||||
|
||||
function transformGammaChannel(channel: number): number {
|
||||
const normalized = channel / 255;
|
||||
return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
|
||||
}
|
||||
|
||||
const STATUS_PALETTE = {
|
||||
light: {
|
||||
destructive: "#c53b2c",
|
||||
info: "#0b6bcb",
|
||||
success: "#0a7d5d",
|
||||
warning: "#a95a00",
|
||||
},
|
||||
dark: {
|
||||
destructive: "#ff7b72",
|
||||
info: "#58a6ff",
|
||||
success: "#3fb950",
|
||||
warning: "#d29922",
|
||||
},
|
||||
} as const;
|
||||
|
||||
const OVERRIDE_TOKEN_MAP: Record<keyof ThemeDerivedOverrides, ThemeTokenName> = {
|
||||
background: "background",
|
||||
foreground: "foreground",
|
||||
card: "card",
|
||||
cardForeground: "card-foreground",
|
||||
popover: "popover",
|
||||
popoverForeground: "popover-foreground",
|
||||
primary: "primary",
|
||||
primaryForeground: "primary-foreground",
|
||||
secondary: "secondary",
|
||||
secondaryForeground: "secondary-foreground",
|
||||
muted: "muted",
|
||||
mutedForeground: "muted-foreground",
|
||||
accentSurface: "accent",
|
||||
accentForeground: "accent-foreground",
|
||||
border: "border",
|
||||
input: "input",
|
||||
ring: "ring",
|
||||
destructive: "destructive",
|
||||
destructiveForeground: "destructive-foreground",
|
||||
info: "info",
|
||||
infoForeground: "info-foreground",
|
||||
success: "success",
|
||||
successForeground: "success-foreground",
|
||||
warning: "warning",
|
||||
warningForeground: "warning-foreground",
|
||||
diffAddition: "diff-addition",
|
||||
diffDeletion: "diff-deletion",
|
||||
sidebar: "sidebar",
|
||||
sidebarForeground: "sidebar-foreground",
|
||||
sidebarAccent: "sidebar-accent",
|
||||
sidebarAccentForeground: "sidebar-accent-foreground",
|
||||
sidebarBorder: "sidebar-border",
|
||||
};
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
function parseHexColor(hex: string): Rgb {
|
||||
const normalized = hex.replace("#", "");
|
||||
const expanded =
|
||||
normalized.length === 8 ? normalized.slice(0, 6) : normalized.length === 6 ? normalized : "";
|
||||
if (!expanded) {
|
||||
throw new Error(`Invalid hex color: ${hex}`);
|
||||
}
|
||||
return {
|
||||
r: Number.parseInt(expanded.slice(0, 2), 16),
|
||||
g: Number.parseInt(expanded.slice(2, 4), 16),
|
||||
b: Number.parseInt(expanded.slice(4, 6), 16),
|
||||
};
|
||||
}
|
||||
|
||||
function toHexColor({ r, g, b }: Rgb): string {
|
||||
const channel = (value: number) =>
|
||||
Math.round(clamp(value, 0, 255))
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
return `#${channel(r)}${channel(g)}${channel(b)}`;
|
||||
}
|
||||
|
||||
function mixColors(left: string, right: string, ratio: number): string {
|
||||
const from = parseHexColor(left);
|
||||
const to = parseHexColor(right);
|
||||
const amount = clamp(ratio, 0, 1);
|
||||
return toHexColor({
|
||||
r: from.r + (to.r - from.r) * amount,
|
||||
g: from.g + (to.g - from.g) * amount,
|
||||
b: from.b + (to.b - from.b) * amount,
|
||||
});
|
||||
}
|
||||
|
||||
function withAlpha(color: string, alpha: number): string {
|
||||
const { r, g, b } = parseHexColor(color);
|
||||
return `rgb(${r} ${g} ${b} / ${clamp(alpha, 0, 1).toFixed(3)})`;
|
||||
}
|
||||
|
||||
function getRelativeLuminance(color: string): number {
|
||||
const { r, g, b } = parseHexColor(color);
|
||||
return (
|
||||
0.2126 * transformGammaChannel(r) +
|
||||
0.7152 * transformGammaChannel(g) +
|
||||
0.0722 * transformGammaChannel(b)
|
||||
);
|
||||
}
|
||||
|
||||
function getContrastRatio(left: string, right: string): number {
|
||||
const leftLuminance = getRelativeLuminance(left);
|
||||
const rightLuminance = getRelativeLuminance(right);
|
||||
const lighter = Math.max(leftLuminance, rightLuminance);
|
||||
const darker = Math.min(leftLuminance, rightLuminance);
|
||||
return (lighter + 0.05) / (darker + 0.05);
|
||||
}
|
||||
|
||||
function pickReadableText(background: string, candidates: ReadonlyArray<string>): string {
|
||||
return (
|
||||
candidates
|
||||
.toSorted(
|
||||
(left, right) => getContrastRatio(background, right) - getContrastRatio(background, left),
|
||||
)
|
||||
.at(0) ?? candidates[0]!
|
||||
);
|
||||
}
|
||||
|
||||
function stripUndefinedKeys<T extends Record<string, string | undefined>>(
|
||||
value: T,
|
||||
): Record<string, string> {
|
||||
const entries = Object.entries(value).filter(
|
||||
(entry): entry is [string, string] => entry[1] !== undefined,
|
||||
);
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
export function deriveThemeTokens(themeVariant: ThemeVariant): ThemeTokenMap {
|
||||
const contrastFactor = clamp(themeVariant.contrast / 100, 0, 1);
|
||||
const isDark =
|
||||
getRelativeLuminance(themeVariant.background) < getRelativeLuminance(themeVariant.foreground);
|
||||
|
||||
const card = mixColors(
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
isDark ? 0.02 + contrastFactor * 0.04 : 0.006 + contrastFactor * 0.016,
|
||||
);
|
||||
const popover = mixColors(
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
isDark ? 0.035 + contrastFactor * 0.05 : 0.012 + contrastFactor * 0.02,
|
||||
);
|
||||
const secondary = withAlpha(themeVariant.foreground, 0.03 + contrastFactor * 0.035);
|
||||
const muted = withAlpha(themeVariant.foreground, 0.04 + contrastFactor * 0.03);
|
||||
const accentSurface = mixColors(
|
||||
themeVariant.background,
|
||||
themeVariant.accent,
|
||||
0.11 + contrastFactor * 0.09,
|
||||
);
|
||||
const border = withAlpha(themeVariant.foreground, 0.08 + contrastFactor * 0.18);
|
||||
const input = withAlpha(themeVariant.foreground, 0.1 + contrastFactor * 0.2);
|
||||
const mutedForeground = mixColors(
|
||||
themeVariant.foreground,
|
||||
themeVariant.background,
|
||||
0.38 - contrastFactor * 0.14,
|
||||
);
|
||||
const sidebarBase = mixColors(
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
isDark ? 0.055 + contrastFactor * 0.055 : 0.045 + contrastFactor * 0.05,
|
||||
);
|
||||
|
||||
const statusPalette = isDark ? STATUS_PALETTE.dark : STATUS_PALETTE.light;
|
||||
const primaryForeground = pickReadableText(themeVariant.accent, [
|
||||
themeVariant.foreground,
|
||||
themeVariant.background,
|
||||
"#0d0d0d",
|
||||
"#ffffff",
|
||||
]);
|
||||
const accentForeground = pickReadableText(accentSurface, [
|
||||
themeVariant.foreground,
|
||||
themeVariant.background,
|
||||
"#0d0d0d",
|
||||
"#ffffff",
|
||||
]);
|
||||
const destructiveForeground = pickReadableText(statusPalette.destructive, [
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
"#ffffff",
|
||||
"#0d0d0d",
|
||||
]);
|
||||
const infoForeground = pickReadableText(statusPalette.info, [
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
"#ffffff",
|
||||
"#0d0d0d",
|
||||
]);
|
||||
const successForeground = pickReadableText(statusPalette.success, [
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
"#ffffff",
|
||||
"#0d0d0d",
|
||||
]);
|
||||
const warningForeground = pickReadableText(statusPalette.warning, [
|
||||
themeVariant.background,
|
||||
themeVariant.foreground,
|
||||
"#ffffff",
|
||||
"#0d0d0d",
|
||||
]);
|
||||
|
||||
const tokens: ThemeTokenMap = {
|
||||
background: themeVariant.background,
|
||||
foreground: themeVariant.foreground,
|
||||
card,
|
||||
"card-foreground": themeVariant.foreground,
|
||||
popover,
|
||||
"popover-foreground": themeVariant.foreground,
|
||||
primary: themeVariant.accent,
|
||||
"primary-foreground": primaryForeground,
|
||||
secondary,
|
||||
"secondary-foreground": themeVariant.foreground,
|
||||
muted,
|
||||
"muted-foreground": mutedForeground,
|
||||
accent: accentSurface,
|
||||
"accent-foreground": accentForeground,
|
||||
border,
|
||||
input,
|
||||
ring: mixColors(themeVariant.accent, themeVariant.foreground, isDark ? 0.12 : 0.08),
|
||||
destructive: statusPalette.destructive,
|
||||
"destructive-foreground": destructiveForeground,
|
||||
info: statusPalette.info,
|
||||
"info-foreground": infoForeground,
|
||||
success: statusPalette.success,
|
||||
"success-foreground": successForeground,
|
||||
warning: statusPalette.warning,
|
||||
"warning-foreground": warningForeground,
|
||||
"diff-addition": statusPalette.success,
|
||||
"diff-deletion": statusPalette.destructive,
|
||||
sidebar: themeVariant.sidebarTranslucent
|
||||
? withAlpha(sidebarBase, isDark ? 0.84 : 0.94)
|
||||
: sidebarBase,
|
||||
"sidebar-foreground": themeVariant.foreground,
|
||||
"sidebar-accent": mixColors(sidebarBase, themeVariant.accent, 0.16 + contrastFactor * 0.1),
|
||||
"sidebar-accent-foreground": accentForeground,
|
||||
"sidebar-border": border,
|
||||
"ui-font-family": themeVariant.uiFontFamily,
|
||||
"code-font-family": themeVariant.codeFontFamily,
|
||||
"sidebar-blur": themeVariant.sidebarTranslucent ? "18px" : "0px",
|
||||
};
|
||||
|
||||
if (themeVariant.overrides) {
|
||||
for (const [overrideKey, overrideValue] of Object.entries(themeVariant.overrides) as Array<
|
||||
[keyof ThemeDerivedOverrides, string | undefined]
|
||||
>) {
|
||||
if (!overrideValue) continue;
|
||||
const tokenName = OVERRIDE_TOKEN_MAP[overrideKey];
|
||||
tokens[tokenName] = overrideValue;
|
||||
}
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function deriveThemeCssVariables(themeVariant: ThemeVariant): ThemeCssVariableMap {
|
||||
const tokens = deriveThemeTokens(themeVariant);
|
||||
const entries = THEME_TOKEN_ORDER.map((tokenName) => [`--${tokenName}`, tokens[tokenName]]);
|
||||
return Object.fromEntries(entries) as ThemeCssVariableMap;
|
||||
}
|
||||
|
||||
export function serializeThemeDerivedOverrides(
|
||||
overrides: ThemeDerivedOverrides | undefined,
|
||||
): ThemeDerivedOverrides | undefined {
|
||||
if (!overrides) return undefined;
|
||||
const next = stripUndefinedKeys(overrides);
|
||||
return Object.keys(next).length === 0 ? undefined : (next as ThemeDerivedOverrides);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
BUILTIN_THEME_DOCUMENTS,
|
||||
DEFAULT_DARK_THEME_ID,
|
||||
DEFAULT_LIGHT_THEME_ID,
|
||||
duplicateThemeDocument,
|
||||
resolveThemeDocument,
|
||||
serializeAppearanceSnapshot,
|
||||
serializeThemeDocument,
|
||||
} from "./registry";
|
||||
|
||||
describe("appearance registry", () => {
|
||||
it("resolves builtin themes before falling back to custom themes", () => {
|
||||
const resolved = resolveThemeDocument(
|
||||
DEFAULT_LIGHT_THEME_ID,
|
||||
[duplicateThemeDocument(BUILTIN_THEME_DOCUMENTS[0]!, DEFAULT_LIGHT_THEME_ID, "Custom Clash")],
|
||||
"light",
|
||||
);
|
||||
|
||||
expect(resolved.origin).toBe("builtin");
|
||||
expect(resolved.id).toBe(DEFAULT_LIGHT_THEME_ID);
|
||||
});
|
||||
|
||||
it("duplicates builtin themes into custom theme documents", () => {
|
||||
const duplicated = duplicateThemeDocument(
|
||||
BUILTIN_THEME_DOCUMENTS[0]!,
|
||||
"custom-copy",
|
||||
"Custom Copy",
|
||||
);
|
||||
|
||||
expect(duplicated.origin).toBe("custom");
|
||||
expect(duplicated.id).toBe("custom-copy");
|
||||
expect(duplicated.accent).toBe(BUILTIN_THEME_DOCUMENTS[0]!.accent);
|
||||
expect(duplicated.mode).toBe(BUILTIN_THEME_DOCUMENTS[0]!.mode);
|
||||
});
|
||||
|
||||
it("serializes themes and appearance snapshots deterministically", () => {
|
||||
const theme = duplicateThemeDocument(BUILTIN_THEME_DOCUMENTS[0]!, "custom-copy", "Custom Copy");
|
||||
const themeJson = serializeThemeDocument(theme);
|
||||
const snapshotJson = serializeAppearanceSnapshot({
|
||||
colorMode: "system",
|
||||
activeLightThemeId: "custom-copy",
|
||||
activeDarkThemeId: DEFAULT_DARK_THEME_ID,
|
||||
customThemes: [theme],
|
||||
});
|
||||
|
||||
expect(themeJson).toContain('"id": "custom-copy"');
|
||||
expect(themeJson).toContain('"radius": "0.625rem"');
|
||||
expect(themeJson).toContain('"fontSize": "16px"');
|
||||
expect(snapshotJson).toContain('"activeLightThemeId":"custom-copy"');
|
||||
expect(snapshotJson).toContain(`"activeDarkThemeId":"${DEFAULT_DARK_THEME_ID}"`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
import {
|
||||
DEFAULT_ACTIVE_DARK_THEME_ID,
|
||||
DEFAULT_ACTIVE_LIGHT_THEME_ID,
|
||||
DEFAULT_THEME_FONT_SIZE,
|
||||
DEFAULT_THEME_RADIUS,
|
||||
type ThemeDocument,
|
||||
type ThemeMode,
|
||||
type ThemeOrigin,
|
||||
} from "@t3tools/contracts";
|
||||
import { serializeThemeDerivedOverrides } from "./derive";
|
||||
|
||||
export interface BuiltinThemePreset {
|
||||
readonly description: string;
|
||||
readonly theme: ThemeDocument;
|
||||
}
|
||||
|
||||
const DEFAULT_UI_FONT = '"DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
const DEFAULT_CODE_FONT =
|
||||
'"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace';
|
||||
|
||||
type ThemeDocumentInput = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
mode: ThemeMode;
|
||||
radius?: string;
|
||||
fontSize?: string;
|
||||
accent: string;
|
||||
background: string;
|
||||
foreground: string;
|
||||
uiFontFamily: string;
|
||||
codeFontFamily: string;
|
||||
sidebarTranslucent: boolean;
|
||||
contrast: number;
|
||||
overrides?: ThemeDocument["overrides"];
|
||||
};
|
||||
|
||||
function makeThemeDocument(input: ThemeDocumentInput): BuiltinThemePreset {
|
||||
return {
|
||||
description: input.description,
|
||||
theme: {
|
||||
id: input.id,
|
||||
name: input.name,
|
||||
version: 1,
|
||||
origin: "builtin",
|
||||
mode: input.mode,
|
||||
radius: input.radius ?? DEFAULT_THEME_RADIUS,
|
||||
fontSize: input.fontSize ?? DEFAULT_THEME_FONT_SIZE,
|
||||
accent: input.accent,
|
||||
background: input.background,
|
||||
foreground: input.foreground,
|
||||
uiFontFamily: input.uiFontFamily,
|
||||
codeFontFamily: input.codeFontFamily,
|
||||
sidebarTranslucent: input.sidebarTranslucent,
|
||||
contrast: input.contrast,
|
||||
...(input.overrides ? { overrides: input.overrides } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const BUILTIN_THEME_PRESETS: readonly BuiltinThemePreset[] = [
|
||||
makeThemeDocument({
|
||||
id: DEFAULT_ACTIVE_LIGHT_THEME_ID,
|
||||
name: "T3Code Light",
|
||||
mode: "light",
|
||||
description: "Clean neutral foundations with a sharper blue accent.",
|
||||
accent: "#0169cc",
|
||||
background: "#ffffff",
|
||||
foreground: "#262626",
|
||||
uiFontFamily: DEFAULT_UI_FONT,
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 46,
|
||||
overrides: {
|
||||
background: "#fff",
|
||||
foreground: "oklch(26.9% 0 0)",
|
||||
card: "#fff",
|
||||
cardForeground: "oklch(26.9% 0 0)",
|
||||
popover: "#fff",
|
||||
popoverForeground: "oklch(26.9% 0 0)",
|
||||
primary: "oklch(0.488 0.217 264)",
|
||||
primaryForeground: "#fff",
|
||||
secondary: "color-mix(in oklab, #000 4%, transparent)",
|
||||
secondaryForeground: "oklch(26.9% 0 0)",
|
||||
muted: "color-mix(in oklab, #000 4%, transparent)",
|
||||
mutedForeground: "color-mix(in srgb, oklch(55.6% 0 0) 90%, #000)",
|
||||
accentSurface: "color-mix(in oklab, #000 4%, transparent)",
|
||||
accentForeground: "oklch(26.9% 0 0)",
|
||||
border: "color-mix(in oklab, #000 8%, transparent)",
|
||||
input: "color-mix(in oklab, #000 10%, transparent)",
|
||||
ring: "oklch(0.488 0.217 264)",
|
||||
destructive: "oklch(63.7% 0.237 25.331)",
|
||||
destructiveForeground: "oklch(50.5% 0.213 27.518)",
|
||||
info: "oklch(62.3% 0.214 259.815)",
|
||||
infoForeground: "oklch(48.8% 0.243 264.376)",
|
||||
success: "oklch(69.6% 0.17 162.48)",
|
||||
successForeground: "oklch(50.8% 0.118 165.612)",
|
||||
warning: "oklch(76.9% 0.188 70.08)",
|
||||
warningForeground: "oklch(55.5% 0.163 48.998)",
|
||||
sidebar: "transparent",
|
||||
sidebarForeground: "oklch(26.9% 0 0)",
|
||||
sidebarAccent: "color-mix(in oklab, #000 4%, transparent)",
|
||||
sidebarAccentForeground: "oklch(26.9% 0 0)",
|
||||
sidebarBorder: "color-mix(in oklab, #000 8%, transparent)",
|
||||
},
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: DEFAULT_ACTIVE_DARK_THEME_ID,
|
||||
name: "T3Code Dark",
|
||||
mode: "dark",
|
||||
description: "Clean neutral foundations with a sharper blue accent.",
|
||||
accent: "#0169cc",
|
||||
background: "#17171a",
|
||||
foreground: "#f5f5f5",
|
||||
uiFontFamily: DEFAULT_UI_FONT,
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 41,
|
||||
overrides: {
|
||||
background: "color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff)",
|
||||
foreground: "oklch(97% 0 0)",
|
||||
card: "color-mix(in srgb, color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff) 98%, #fff)",
|
||||
cardForeground: "oklch(97% 0 0)",
|
||||
popover: "color-mix(in srgb, color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff) 98%, #fff)",
|
||||
popoverForeground: "oklch(97% 0 0)",
|
||||
primary: "oklch(0.588 0.217 264)",
|
||||
primaryForeground: "#fff",
|
||||
secondary: "color-mix(in oklab, #fff 4%, transparent)",
|
||||
secondaryForeground: "oklch(97% 0 0)",
|
||||
muted: "color-mix(in oklab, #fff 4%, transparent)",
|
||||
mutedForeground: "color-mix(in srgb, oklch(55.6% 0 0) 90%, #fff)",
|
||||
accentSurface: "color-mix(in oklab, #fff 4%, transparent)",
|
||||
accentForeground: "oklch(97% 0 0)",
|
||||
border: "color-mix(in oklab, #fff 6%, transparent)",
|
||||
input: "color-mix(in oklab, #fff 8%, transparent)",
|
||||
ring: "oklch(0.588 0.217 264)",
|
||||
destructive: "color-mix(in srgb, oklch(63.7% 0.237 25.331) 90%, #fff)",
|
||||
destructiveForeground: "oklch(70.4% 0.191 22.216)",
|
||||
info: "oklch(62.3% 0.214 259.815)",
|
||||
infoForeground: "oklch(70.7% 0.165 254.624)",
|
||||
success: "oklch(69.6% 0.17 162.48)",
|
||||
successForeground: "oklch(76.5% 0.177 163.223)",
|
||||
warning: "oklch(76.9% 0.188 70.08)",
|
||||
warningForeground: "oklch(82.8% 0.189 84.429)",
|
||||
sidebar: "transparent",
|
||||
sidebarForeground: "oklch(97% 0 0)",
|
||||
sidebarAccent: "color-mix(in oklab, #fff 4%, transparent)",
|
||||
sidebarAccentForeground: "oklch(97% 0 0)",
|
||||
sidebarBorder: "color-mix(in oklab, #fff 6%, transparent)",
|
||||
},
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "warm-ledger-light",
|
||||
name: "Warm Ledger Light",
|
||||
mode: "light",
|
||||
description: "Editorial warmth with paper-like light mode.",
|
||||
accent: "#b35b2c",
|
||||
background: "#f7f0e8",
|
||||
foreground: "#201814",
|
||||
uiFontFamily: '"Iowan Old Style", "Palatino Linotype", "Book Antiqua", Georgia, serif',
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 56,
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "warm-ledger-dark",
|
||||
name: "Warm Ledger Dark",
|
||||
mode: "dark",
|
||||
description: "Editorial warmth with a coffee-toned dark mode.",
|
||||
accent: "#e58d54",
|
||||
background: "#1b1411",
|
||||
foreground: "#f5ede6",
|
||||
uiFontFamily: '"Iowan Old Style", "Palatino Linotype", "Book Antiqua", Georgia, serif',
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: true,
|
||||
contrast: 52,
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "cool-current-light",
|
||||
name: "Cool Current Light",
|
||||
mode: "light",
|
||||
description: "Crystalline teals with a cooler edge.",
|
||||
accent: "#00827a",
|
||||
background: "#f2fbfb",
|
||||
foreground: "#11232b",
|
||||
uiFontFamily: '"Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif',
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: true,
|
||||
contrast: 40,
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "cool-current-dark",
|
||||
name: "Cool Current Dark",
|
||||
mode: "dark",
|
||||
description: "Crystalline teals on deep slate surfaces.",
|
||||
accent: "#19b8b0",
|
||||
background: "#09161d",
|
||||
foreground: "#ebfbff",
|
||||
uiFontFamily: '"Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif',
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: true,
|
||||
contrast: 48,
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "editorial-signal-light",
|
||||
name: "Editorial Signal Light",
|
||||
mode: "light",
|
||||
description: "Minimal black-and-cream contrast with sharper serif typography.",
|
||||
accent: "#7f1933",
|
||||
background: "#fffaf2",
|
||||
foreground: "#121212",
|
||||
uiFontFamily: '"Charter", "Bitstream Charter", "Sitka Text", Cambria, serif',
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 64,
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "editorial-signal-dark",
|
||||
name: "Editorial Signal Dark",
|
||||
mode: "dark",
|
||||
description: "Minimal black-and-cream contrast with sharper serif typography.",
|
||||
accent: "#f05d7a",
|
||||
background: "#111114",
|
||||
foreground: "#f7f4ef",
|
||||
uiFontFamily: '"Charter", "Bitstream Charter", "Sitka Text", Cambria, serif',
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 58,
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "accessibility-spectrum-light",
|
||||
name: "Accessibility Spectrum Light",
|
||||
mode: "light",
|
||||
description: "High-legibility neutrals with color-blind friendly diff colors.",
|
||||
accent: "#245dce",
|
||||
background: "#ffffff",
|
||||
foreground: "#101828",
|
||||
uiFontFamily: DEFAULT_UI_FONT,
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 68,
|
||||
overrides: {
|
||||
diffAddition: "#0969da",
|
||||
diffDeletion: "#bc4c00",
|
||||
},
|
||||
}),
|
||||
makeThemeDocument({
|
||||
id: "accessibility-spectrum-dark",
|
||||
name: "Accessibility Spectrum Dark",
|
||||
mode: "dark",
|
||||
description: "High-legibility neutrals with color-blind friendly diff colors.",
|
||||
accent: "#58a6ff",
|
||||
background: "#0d1117",
|
||||
foreground: "#f0f6fc",
|
||||
uiFontFamily: DEFAULT_UI_FONT,
|
||||
codeFontFamily: DEFAULT_CODE_FONT,
|
||||
sidebarTranslucent: false,
|
||||
contrast: 64,
|
||||
overrides: {
|
||||
diffAddition: "#388bfd",
|
||||
diffDeletion: "#db6d28",
|
||||
},
|
||||
}),
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_LIGHT_THEME_ID = DEFAULT_ACTIVE_LIGHT_THEME_ID;
|
||||
export const DEFAULT_DARK_THEME_ID = DEFAULT_ACTIVE_DARK_THEME_ID;
|
||||
export const BUILTIN_THEME_DOCUMENTS: readonly ThemeDocument[] = BUILTIN_THEME_PRESETS.map(
|
||||
(preset) => preset.theme,
|
||||
);
|
||||
|
||||
const BUILTIN_THEME_ID_SET = new Set(BUILTIN_THEME_DOCUMENTS.map((theme) => theme.id));
|
||||
|
||||
export function getDefaultThemeId(mode: ThemeMode): string {
|
||||
return mode === "dark" ? DEFAULT_DARK_THEME_ID : DEFAULT_LIGHT_THEME_ID;
|
||||
}
|
||||
|
||||
export function isBuiltinThemeId(themeId: string): boolean {
|
||||
return BUILTIN_THEME_ID_SET.has(themeId);
|
||||
}
|
||||
|
||||
export function getBuiltinThemePreset(themeId: string): BuiltinThemePreset | undefined {
|
||||
return BUILTIN_THEME_PRESETS.find((preset) => preset.theme.id === themeId);
|
||||
}
|
||||
|
||||
export function getBuiltinThemeDocument(themeId: string): ThemeDocument | undefined {
|
||||
return getBuiltinThemePreset(themeId)?.theme;
|
||||
}
|
||||
|
||||
export function getThemeDocumentsForMode(
|
||||
mode: ThemeMode,
|
||||
customThemes: ReadonlyArray<ThemeDocument>,
|
||||
): ReadonlyArray<ThemeDocument> {
|
||||
return [...BUILTIN_THEME_DOCUMENTS, ...customThemes].filter((theme) => theme.mode === mode);
|
||||
}
|
||||
|
||||
export function resolveThemeDocument(
|
||||
themeId: string,
|
||||
customThemes: ReadonlyArray<ThemeDocument>,
|
||||
mode: ThemeMode,
|
||||
): ThemeDocument {
|
||||
const resolved =
|
||||
getBuiltinThemeDocument(themeId) ?? customThemes.find((theme) => theme.id === themeId);
|
||||
|
||||
if (resolved && resolved.mode === mode) {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
return (
|
||||
getBuiltinThemeDocument(getDefaultThemeId(mode)) ??
|
||||
BUILTIN_THEME_DOCUMENTS.find((theme) => theme.mode === mode)!
|
||||
);
|
||||
}
|
||||
|
||||
export function canonicalizeThemeDocument(
|
||||
themeDocument: ThemeDocument,
|
||||
origin: ThemeOrigin = themeDocument.origin,
|
||||
): ThemeDocument {
|
||||
const overrides = serializeThemeDerivedOverrides(themeDocument.overrides);
|
||||
return {
|
||||
id: themeDocument.id,
|
||||
name: themeDocument.name,
|
||||
version: 1,
|
||||
origin,
|
||||
mode: themeDocument.mode,
|
||||
radius: themeDocument.radius,
|
||||
fontSize: themeDocument.fontSize,
|
||||
accent: themeDocument.accent,
|
||||
background: themeDocument.background,
|
||||
foreground: themeDocument.foreground,
|
||||
uiFontFamily: themeDocument.uiFontFamily,
|
||||
codeFontFamily: themeDocument.codeFontFamily,
|
||||
sidebarTranslucent: themeDocument.sidebarTranslucent,
|
||||
contrast: themeDocument.contrast,
|
||||
...(overrides ? { overrides } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function serializeThemeDocument(themeDocument: ThemeDocument): string {
|
||||
return `${JSON.stringify(canonicalizeThemeDocument(themeDocument), null, 2)}\n`;
|
||||
}
|
||||
|
||||
export function serializeAppearanceSnapshot(snapshot: {
|
||||
colorMode: "light" | "dark" | "system";
|
||||
activeLightThemeId: string;
|
||||
activeDarkThemeId: string;
|
||||
customThemes: ReadonlyArray<ThemeDocument>;
|
||||
}): string {
|
||||
return JSON.stringify({
|
||||
colorMode: snapshot.colorMode,
|
||||
activeLightThemeId: snapshot.activeLightThemeId,
|
||||
activeDarkThemeId: snapshot.activeDarkThemeId,
|
||||
customThemes: snapshot.customThemes.map((theme) => canonicalizeThemeDocument(theme, "custom")),
|
||||
});
|
||||
}
|
||||
|
||||
export function duplicateThemeDocument(
|
||||
themeDocument: ThemeDocument,
|
||||
nextId: string,
|
||||
nextName: string,
|
||||
): ThemeDocument {
|
||||
return canonicalizeThemeDocument(
|
||||
{
|
||||
...themeDocument,
|
||||
id: nextId,
|
||||
name: nextName,
|
||||
origin: "custom",
|
||||
},
|
||||
"custom",
|
||||
);
|
||||
}
|
||||
|
||||
export function getReservedThemeIds(): ReadonlySet<string> {
|
||||
return BUILTIN_THEME_ID_SET;
|
||||
}
|
||||
Reference in new issue
Block a user