Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb538d76c5 | ||
|
|
357211864c | ||
|
|
4e4f44f286 | ||
|
|
90c0d7d95a | ||
|
|
2b7dcd0295 | ||
|
|
169e16803d | ||
|
|
0dc0cc76be |
No files matched your search
@@ -18,7 +18,8 @@
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron-updater": "^6.6.2",
|
||||
"jsonc-parser": "^3.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
|
||||
@@ -64,6 +64,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
themePreference: { mode: "system" },
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
|
||||
@@ -30,6 +30,7 @@ import type {
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
DesktopUpdateState,
|
||||
DesktopWindowThemeColors,
|
||||
} from "@t3tools/contracts";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
|
||||
@@ -84,12 +85,21 @@ import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runti
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import {
|
||||
discoverEditorColorThemes,
|
||||
getEditorThemePreferences,
|
||||
loadEditorColorTheme,
|
||||
} from "./vscodeThemeDiscovery.ts";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
|
||||
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
|
||||
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
|
||||
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
@@ -118,6 +128,7 @@ const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
|
||||
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
|
||||
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
let windowThemeColors: DesktopWindowThemeColors | null = null;
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
// Dev-only SSH launcher override. Set this to an absolute path on the SSH host
|
||||
@@ -498,6 +509,20 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function getSafeWindowThemeColors(rawInput: unknown): DesktopWindowThemeColors | null {
|
||||
if (typeof rawInput !== "object" || rawInput === null || Array.isArray(rawInput)) return null;
|
||||
const input = rawInput as Record<string, unknown>;
|
||||
if (typeof input.backgroundColor !== "string" || input.backgroundColor.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
backgroundColor: input.backgroundColor,
|
||||
titleBarColor: typeof input.titleBarColor === "string" ? input.titleBarColor : undefined,
|
||||
titleBarSymbolColor:
|
||||
typeof input.titleBarSymbolColor === "string" ? input.titleBarSymbolColor : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
@@ -1818,6 +1843,26 @@ function registerIpcHandlers(): void {
|
||||
nativeTheme.themeSource = theme;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(DISCOVER_COLOR_THEMES_CHANNEL);
|
||||
ipcMain.handle(DISCOVER_COLOR_THEMES_CHANNEL, async () => discoverEditorColorThemes());
|
||||
|
||||
ipcMain.removeHandler(LOAD_COLOR_THEME_CHANNEL);
|
||||
ipcMain.handle(LOAD_COLOR_THEME_CHANNEL, async (_event, rawThemeId: unknown) => {
|
||||
if (typeof rawThemeId !== "string") return null;
|
||||
return loadEditorColorTheme(rawThemeId);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(GET_EDITOR_THEME_PREFERENCES_CHANNEL);
|
||||
ipcMain.handle(GET_EDITOR_THEME_PREFERENCES_CHANNEL, async () => getEditorThemePreferences());
|
||||
|
||||
ipcMain.removeHandler(SET_WINDOW_THEME_COLORS_CHANNEL);
|
||||
ipcMain.handle(SET_WINDOW_THEME_COLORS_CHANNEL, async (_event, rawInput: unknown) => {
|
||||
const input = getSafeWindowThemeColors(rawInput);
|
||||
if (!input) return;
|
||||
windowThemeColors = input;
|
||||
syncAllWindowAppearance();
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
@@ -1989,7 +2034,9 @@ function getIconOption(): { icon: string } | Record<string, never> {
|
||||
}
|
||||
|
||||
function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
return (
|
||||
windowThemeColors?.backgroundColor ?? (nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff")
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
@@ -2003,11 +2050,13 @@ function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
color: windowThemeColors?.titleBarColor ?? TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
symbolColor:
|
||||
windowThemeColors?.titleBarSymbolColor ??
|
||||
(nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,6 +4,10 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
|
||||
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
|
||||
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
|
||||
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
@@ -114,7 +118,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
discoverColorThemes: () => ipcRenderer.invoke(DISCOVER_COLOR_THEMES_CHANNEL),
|
||||
loadColorTheme: (themeId) => ipcRenderer.invoke(LOAD_COLOR_THEME_CHANNEL, themeId),
|
||||
getEditorThemePreferences: () => ipcRenderer.invoke(GET_EDITOR_THEME_PREFERENCES_CHANNEL),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
setWindowThemeColors: (input) => ipcRenderer.invoke(SET_WINDOW_THEME_COLORS_CHANNEL, input),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
discoverEditorColorThemes,
|
||||
getEditorThemePreferences,
|
||||
loadEditorColorTheme,
|
||||
resolveEditorRoots,
|
||||
} from "./vscodeThemeDiscovery.ts";
|
||||
|
||||
let tempDir = "";
|
||||
|
||||
function writeJson(filePath: string, value: unknown) {
|
||||
FS.mkdirSync(Path.dirname(filePath), { recursive: true });
|
||||
FS.writeFileSync(filePath, JSON.stringify(value, null, 2));
|
||||
}
|
||||
|
||||
describe("vscodeThemeDiscovery", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-vscode-themes-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
FS.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("discovers contributed themes and ignores unsafe paths", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
publisher: "GitHub",
|
||||
displayName: "GitHub Theme",
|
||||
contributes: {
|
||||
themes: [
|
||||
{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" },
|
||||
{ label: "Escaped", uiTheme: "vs", path: "../escaped.json" },
|
||||
],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
colors: { "editor.background": "#0d1117" },
|
||||
});
|
||||
|
||||
expect(discoverEditorColorThemes(roots)).toMatchObject([
|
||||
{
|
||||
source: "vscode",
|
||||
label: "GitHub Dark Default",
|
||||
kind: "dark",
|
||||
publisher: "GitHub",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads JSONC settings overrides into the resolved app theme", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
contributes: {
|
||||
themes: [{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" }],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
semanticHighlighting: true,
|
||||
colors: {
|
||||
"editor.background": "#0d1117",
|
||||
"editor.foreground": "#e6edf3",
|
||||
},
|
||||
tokenColors: [],
|
||||
});
|
||||
FS.mkdirSync(Path.dirname(vscodeRoot.settingsPath), { recursive: true });
|
||||
FS.writeFileSync(
|
||||
vscodeRoot.settingsPath,
|
||||
`{
|
||||
"workbench.colorTheme": "GitHub Dark Default",
|
||||
"workbench.colorCustomizations": {
|
||||
"button.background": "#238636",
|
||||
"[GitHub Dark Default]": {
|
||||
"sideBar.background": "#010409"
|
||||
}
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
expect(preferences[0]?.colorTheme).toBe("GitHub Dark Default");
|
||||
|
||||
const themeId = discoverEditorColorThemes(roots)[0]?.id;
|
||||
expect(themeId).toBeTruthy();
|
||||
const resolved = themeId ? loadEditorColorTheme(themeId, roots) : null;
|
||||
|
||||
expect(resolved?.colors["button.background"]).toBe("#238636");
|
||||
expect(resolved?.colors["sideBar.background"]).toBe("#010409");
|
||||
expect(resolved?.appVariables["--primary"]).toBe("#238636");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { parse as parseJsonc } from "jsonc-parser";
|
||||
import type {
|
||||
DiscoveredColorTheme,
|
||||
EditorThemePreference,
|
||||
EditorThemeSource,
|
||||
ResolvedColorTheme,
|
||||
ThemeKind,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
mapVscodeColorsToAppVariables,
|
||||
normalizeCssColor,
|
||||
normalizeThemeColors,
|
||||
} from "@t3tools/shared/themeMapping";
|
||||
|
||||
interface EditorRoot {
|
||||
readonly source: EditorThemeSource;
|
||||
readonly extensionsPath: string;
|
||||
readonly settingsPath: string;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function kindFromUiTheme(uiTheme: unknown): ThemeKind {
|
||||
if (uiTheme === "hc-light") return "high-contrast-light";
|
||||
if (uiTheme === "hc-black") return "high-contrast-dark";
|
||||
if (uiTheme === "vs") return "light";
|
||||
return "dark";
|
||||
}
|
||||
|
||||
function readJsonOrJsoncFile(filePath: string): unknown | null {
|
||||
try {
|
||||
return parseJsonc(FS.readFileSync(filePath, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeResolveChild(root: string, relativePath: string): string | null {
|
||||
const resolved = Path.resolve(root, relativePath);
|
||||
const normalizedRoot = Path.resolve(root);
|
||||
if (resolved === normalizedRoot || resolved.startsWith(`${normalizedRoot}${Path.sep}`)) {
|
||||
return resolved;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveEditorRoots(input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly homedir: string;
|
||||
readonly appData?: string;
|
||||
}): readonly EditorRoot[] {
|
||||
const home = input.homedir;
|
||||
if (input.platform === "win32") {
|
||||
const appData = input.appData ?? Path.join(home, "AppData", "Roaming");
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(appData, "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (input.platform === "darwin") {
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code - Insiders",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Cursor",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function resolveDefaultEditorRoots() {
|
||||
const input: { platform: NodeJS.Platform; homedir: string; appData?: string } = {
|
||||
platform: process.platform,
|
||||
homedir: OS.homedir(),
|
||||
};
|
||||
if (process.env.APPDATA) input.appData = process.env.APPDATA;
|
||||
return resolveEditorRoots(input);
|
||||
}
|
||||
|
||||
function readEditorSettings(settingsPath: string): Record<string, unknown> {
|
||||
const parsed = readJsonOrJsoncFile(settingsPath);
|
||||
return isObject(parsed) ? parsed : {};
|
||||
}
|
||||
|
||||
export function getEditorThemePreferences(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly EditorThemePreference[] {
|
||||
return roots.map((root) => {
|
||||
const settings = readEditorSettings(root.settingsPath);
|
||||
const customizations = settings["workbench.colorCustomizations"];
|
||||
return {
|
||||
source: root.source,
|
||||
colorTheme:
|
||||
typeof settings["workbench.colorTheme"] === "string"
|
||||
? settings["workbench.colorTheme"]
|
||||
: null,
|
||||
preferredLightColorTheme:
|
||||
typeof settings["workbench.preferredLightColorTheme"] === "string"
|
||||
? settings["workbench.preferredLightColorTheme"]
|
||||
: null,
|
||||
preferredDarkColorTheme:
|
||||
typeof settings["workbench.preferredDarkColorTheme"] === "string"
|
||||
? settings["workbench.preferredDarkColorTheme"]
|
||||
: null,
|
||||
autoDetectColorScheme: settings["window.autoDetectColorScheme"] === true,
|
||||
workbenchColorCustomizations: isObject(customizations) ? customizations : {},
|
||||
editorTokenColorCustomizations: settings["editor.tokenColorCustomizations"],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function discoverEditorColorThemes(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly DiscoveredColorTheme[] {
|
||||
const themes: DiscoveredColorTheme[] = [];
|
||||
|
||||
for (const root of roots) {
|
||||
if (!FS.existsSync(root.extensionsPath)) continue;
|
||||
|
||||
for (const entry of FS.readdirSync(root.extensionsPath, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
const extensionDir = Path.join(root.extensionsPath, entry.name);
|
||||
const packagePath = Path.join(extensionDir, "package.json");
|
||||
const packageJson = readJsonOrJsoncFile(packagePath);
|
||||
if (!isObject(packageJson)) continue;
|
||||
|
||||
const contributes = packageJson.contributes;
|
||||
const contributedThemes = isObject(contributes) ? contributes.themes : null;
|
||||
if (!Array.isArray(contributedThemes)) continue;
|
||||
|
||||
for (const theme of contributedThemes) {
|
||||
if (!isObject(theme) || typeof theme.label !== "string" || typeof theme.path !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const themePath = safeResolveChild(extensionDir, theme.path);
|
||||
if (!themePath || !FS.existsSync(themePath)) continue;
|
||||
|
||||
themes.push({
|
||||
id: `${root.source}:${entry.name}:${theme.label}`,
|
||||
source: root.source,
|
||||
extensionId: entry.name,
|
||||
extensionDisplayName:
|
||||
typeof packageJson.displayName === "string" ? packageJson.displayName : undefined,
|
||||
label: theme.label,
|
||||
kind: kindFromUiTheme(theme.uiTheme),
|
||||
themePath,
|
||||
packagePath,
|
||||
publisher: typeof packageJson.publisher === "string" ? packageJson.publisher : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return themes.toSorted((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
function mergeWorkbenchOverrides(input: {
|
||||
readonly themeLabel: string;
|
||||
readonly themeColors: Record<string, string>;
|
||||
readonly customizations: Record<string, unknown>;
|
||||
}) {
|
||||
const next = { ...input.themeColors };
|
||||
|
||||
for (const [key, rawValue] of Object.entries(input.customizations)) {
|
||||
if (key.startsWith("[") && key.endsWith("]")) continue;
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
|
||||
const scoped = input.customizations[`[${input.themeLabel}]`];
|
||||
if (isObject(scoped)) {
|
||||
for (const [key, rawValue] of Object.entries(scoped)) {
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function loadEditorColorTheme(
|
||||
themeId: string,
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): ResolvedColorTheme | null {
|
||||
const themes = discoverEditorColorThemes(roots);
|
||||
const theme = themes.find((entry) => entry.id === themeId);
|
||||
if (!theme) return null;
|
||||
|
||||
const rawTheme = readJsonOrJsoncFile(theme.themePath);
|
||||
if (!isObject(rawTheme)) return null;
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
const preference = preferences.find((entry) => entry.source === theme.source);
|
||||
const colors = mergeWorkbenchOverrides({
|
||||
themeLabel: theme.label,
|
||||
themeColors: normalizeThemeColors(rawTheme.colors),
|
||||
customizations: preference?.workbenchColorCustomizations ?? {},
|
||||
});
|
||||
|
||||
return {
|
||||
id: theme.id,
|
||||
label: theme.label,
|
||||
source: theme.source,
|
||||
kind: theme.kind,
|
||||
colors,
|
||||
tokenColors: rawTheme.tokenColors ?? [],
|
||||
semanticHighlighting:
|
||||
typeof rawTheme.semanticHighlighting === "boolean"
|
||||
? rawTheme.semanticHighlighting
|
||||
: undefined,
|
||||
semanticTokenColors: rawTheme.semanticTokenColors,
|
||||
appVariables: mapVscodeColorsToAppVariables({ kind: theme.kind, colors }),
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import React, {
|
||||
import {
|
||||
Children,
|
||||
Suspense,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
@@ -22,8 +20,8 @@ import { VscodeEntryIcon } from "./chat/VscodeEntryIcon";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { resolveSyntaxThemeName } from "../lib/syntaxTheme";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
@@ -34,27 +32,6 @@ import {
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
{ hasError: boolean }
|
||||
> {
|
||||
constructor(props: { fallback: ReactNode; children: ReactNode }) {
|
||||
super(props);
|
||||
this.state = { hasError: false };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
override render() {
|
||||
if (this.state.hasError) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
@@ -69,12 +46,26 @@ const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
const unsupportedHighlightLanguages = new Set<string>();
|
||||
const HIGHLIGHT_LANGUAGE_ALIASES: Readonly<Record<string, string>> = {
|
||||
baml: "text",
|
||||
gitignore: "ini",
|
||||
plaintext: "text",
|
||||
txt: "text",
|
||||
};
|
||||
|
||||
function normalizeHighlightLanguage(language: string): string {
|
||||
const normalizedLanguage = language.trim().toLowerCase();
|
||||
if (!normalizedLanguage) {
|
||||
return "text";
|
||||
}
|
||||
return HIGHLIGHT_LANGUAGE_ALIASES[normalizedLanguage] ?? normalizedLanguage;
|
||||
}
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
const raw = match?.[1] ?? "text";
|
||||
// Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
|
||||
return raw === "gitignore" ? "ini" : raw;
|
||||
return normalizeHighlightLanguage(raw);
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
@@ -112,7 +103,7 @@ function extractCodeBlock(
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: string): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
@@ -120,27 +111,71 @@ function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
function getHighlighterPromise(language: string, themeName: string): Promise<DiffsHighlighter> {
|
||||
const highlighterLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
|
||||
const cacheKey = `${highlighterLanguage}:${themeName}`;
|
||||
const cached = highlighterPromiseCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
themes: [themeName],
|
||||
langs: [highlighterLanguage as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
}).catch((err) => {
|
||||
highlighterPromiseCache.delete(language);
|
||||
if (language === "text") {
|
||||
highlighterPromiseCache.delete(cacheKey);
|
||||
if (highlighterLanguage === "text") {
|
||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||
throw err;
|
||||
}
|
||||
// Language not supported by Shiki — fall back to "text"
|
||||
return getHighlighterPromise("text");
|
||||
unsupportedHighlightLanguages.add(highlighterLanguage);
|
||||
return getHighlighterPromise("text", themeName);
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
highlighterPromiseCache.set(cacheKey, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function renderHighlightedHtml(
|
||||
highlighter: DiffsHighlighter,
|
||||
code: string,
|
||||
language: string,
|
||||
themeName: string,
|
||||
): string {
|
||||
const highlightLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
|
||||
try {
|
||||
return highlighter.codeToHtml(code, {
|
||||
lang: highlightLanguage as SupportedLanguages,
|
||||
theme: themeName,
|
||||
});
|
||||
} catch (error) {
|
||||
if (highlightLanguage === "text") {
|
||||
throw error;
|
||||
}
|
||||
unsupportedHighlightLanguages.add(highlightLanguage);
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleHighlightWork(callback: () => void): () => void {
|
||||
if (typeof window === "undefined") {
|
||||
callback();
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const idleWindow = window as Window & {
|
||||
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
|
||||
cancelIdleCallback?: (handle: number) => void;
|
||||
};
|
||||
|
||||
if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {
|
||||
const idleHandle = idleWindow.requestIdleCallback(callback, { timeout: 1500 });
|
||||
return () => idleWindow.cancelIdleCallback?.(idleHandle);
|
||||
}
|
||||
|
||||
const timeoutHandle = window.setTimeout(callback, 0);
|
||||
return () => window.clearTimeout(timeoutHandle);
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
@@ -189,88 +224,97 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
|
||||
);
|
||||
}
|
||||
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
interface ShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: DiffThemeName;
|
||||
themeName: string;
|
||||
isStreaming: boolean;
|
||||
fallback: ReactNode;
|
||||
}
|
||||
|
||||
function SuspenseShikiCodeBlock({
|
||||
type HighlightedCodeState = {
|
||||
cacheKey: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
function ShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
fallback,
|
||||
}: ShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
const [highlightedCode, setHighlightedCode] = useState<HighlightedCodeState | null>(() => {
|
||||
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
|
||||
return cachedHighlightedHtml == null ? null : { cacheKey, html: cachedHighlightedHtml };
|
||||
});
|
||||
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
useEffect(() => {
|
||||
if (isStreaming) {
|
||||
setHighlightedCode(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const cachedHighlightedHtml = highlightedCodeCache.get(cacheKey);
|
||||
if (cachedHighlightedHtml != null) {
|
||||
setHighlightedCode({ cacheKey, html: cachedHighlightedHtml });
|
||||
return;
|
||||
}
|
||||
|
||||
let isCancelled = false;
|
||||
let cancelHighlightWork: (() => void) | null = null;
|
||||
setHighlightedCode(null);
|
||||
|
||||
void getHighlighterPromise(language, themeName)
|
||||
.then((highlighter) => {
|
||||
if (isCancelled) return;
|
||||
cancelHighlightWork = scheduleHighlightWork(() => {
|
||||
if (isCancelled) return;
|
||||
let highlightedHtml: string;
|
||||
try {
|
||||
highlightedHtml = renderHighlightedHtml(highlighter, code, language, themeName);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (isCancelled) return;
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
setHighlightedCode({ cacheKey, html: highlightedHtml });
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (!isCancelled) {
|
||||
setHighlightedCode(null);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
cancelHighlightWork?.();
|
||||
};
|
||||
}, [cacheKey, code, isStreaming, language, themeName]);
|
||||
|
||||
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
|
||||
const activeHighlightedHtml =
|
||||
cachedHighlightedHtml ?? (highlightedCode?.cacheKey === cacheKey ? highlightedCode.html : null);
|
||||
|
||||
if (activeHighlightedHtml == null) {
|
||||
return <>{fallback}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<UncachedShikiCodeBlock
|
||||
code={code}
|
||||
language={language}
|
||||
themeName={themeName}
|
||||
cacheKey={cacheKey}
|
||||
isStreaming={isStreaming}
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: activeHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface UncachedShikiCodeBlockProps {
|
||||
code: string;
|
||||
language: string;
|
||||
themeName: DiffThemeName;
|
||||
cacheKey: string;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function UncachedShikiCodeBlock({
|
||||
code,
|
||||
language,
|
||||
themeName,
|
||||
cacheKey,
|
||||
isStreaming,
|
||||
}: UncachedShikiCodeBlockProps) {
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
} catch (error) {
|
||||
// Log highlighting failures for debugging while falling back to plain text
|
||||
console.warn(
|
||||
`Code highlighting failed for language "${language}", falling back to plain text.`,
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
// If highlighting fails for this language, render as plain text
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}, [code, highlighter, language, themeName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
interface MarkdownFileLinkProps {
|
||||
href: string;
|
||||
targetPath: string;
|
||||
@@ -508,8 +552,11 @@ function areMarkdownFileLinkPropsEqual(
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const { resolvedTheme, resolvedColorTheme } = useTheme();
|
||||
const codeBlockThemeName = useMemo(
|
||||
() => resolveSyntaxThemeName({ resolvedTheme, resolvedColorTheme }),
|
||||
[resolvedColorTheme, resolvedTheme],
|
||||
);
|
||||
const markdownFileLinkMetaByHref = useMemo(() => {
|
||||
const metaByHref = new Map<
|
||||
string,
|
||||
@@ -572,22 +619,19 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</CodeHighlightErrorBoundary>
|
||||
<ShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={codeBlockThemeName}
|
||||
isStreaming={isStreaming}
|
||||
fallback={<pre {...props}>{children}</pre>}
|
||||
/>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[
|
||||
diffThemeName,
|
||||
codeBlockThemeName,
|
||||
fileLinkParentSuffixByPath,
|
||||
isStreaming,
|
||||
markdownFileLinkMetaByHref,
|
||||
|
||||
@@ -116,7 +116,7 @@ import {
|
||||
} from "~/projectScripts";
|
||||
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { useProjectGroupingSettings, useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
|
||||
@@ -941,10 +941,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
},
|
||||
[],
|
||||
);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useProjectGroupingSettings();
|
||||
const logicalProjectEnvironments = useMemo(() => {
|
||||
if (!activeProject) return [];
|
||||
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
|
||||
|
||||
@@ -30,7 +30,7 @@ import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { resolveSyntaxThemeName } from "../lib/syntaxTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { selectProjectByRef, useStore } from "../store";
|
||||
import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
@@ -185,8 +185,12 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { resolvedTheme, resolvedColorTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const diffThemeName = useMemo(
|
||||
() => resolveSyntaxThemeName({ resolvedTheme, resolvedColorTheme }),
|
||||
[resolvedColorTheme, resolvedTheme],
|
||||
);
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
@@ -321,8 +325,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const hasResolvedPatch = typeof selectedPatch === "string";
|
||||
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
|
||||
const renderablePatch = useMemo(
|
||||
() => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
|
||||
[resolvedTheme, selectedPatch],
|
||||
() => getRenderablePatch(selectedPatch, `diff-panel:${diffThemeName}`),
|
||||
[diffThemeName, selectedPatch],
|
||||
);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -662,7 +666,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
{renderableFiles.map((fileDiff) => {
|
||||
const filePath = resolveFileDiffPath(fileDiff);
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
const themedFileKey = `${fileKey}:${diffThemeName}`;
|
||||
const collapsed = collapsedDiffFileKeys.has(fileKey);
|
||||
return (
|
||||
<div
|
||||
@@ -709,7 +713,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
overflow: diffWordWrap ? "wrap" : "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
theme: diffThemeName,
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { DiffsThemeNames } from "@pierre/diffs";
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { resolveSyntaxThemeName } from "../lib/syntaxTheme";
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffsThemeNames }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -29,8 +30,11 @@ function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const { resolvedTheme, resolvedColorTheme } = useTheme();
|
||||
const diffThemeName = useMemo(
|
||||
() => resolveSyntaxThemeName({ resolvedTheme, resolvedColorTheme }),
|
||||
[resolvedColorTheme, resolvedTheme],
|
||||
);
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores =
|
||||
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
|
||||
@@ -141,7 +141,6 @@ import {
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from "./ui/sidebar";
|
||||
@@ -167,7 +166,7 @@ import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { CommandDialogTrigger } from "./ui/command";
|
||||
import { readEnvironmentApi } from "../environmentApi";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useProjectGroupingSettings, useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
import { useServerKeybindings } from "../rpc/serverState";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
@@ -931,10 +930,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
const defaultThreadEnvMode = useSettings<ThreadEnvMode>(
|
||||
(settings) => settings.defaultThreadEnvMode,
|
||||
);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useProjectGroupingSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const router = useRouter();
|
||||
const { isMobile, setOpenMobile } = useSidebar();
|
||||
@@ -2725,10 +2721,7 @@ export default function Sidebar() {
|
||||
const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder);
|
||||
const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
|
||||
const sidebarProjectGroupingMode = useSettings((s) => s.sidebarProjectGroupingMode);
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useProjectGroupingSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const { handleNewThread } = useNewThreadHandler();
|
||||
const { archiveThread, deleteThread } = useThreadActions();
|
||||
@@ -3386,7 +3379,6 @@ export default function Sidebar() {
|
||||
projectsLength={projects.length}
|
||||
/>
|
||||
|
||||
<SidebarSeparator />
|
||||
<SidebarChromeFooter />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -120,13 +120,30 @@ function terminalThemeFromApp(mountElement?: HTMLElement | null): ITheme {
|
||||
drawerStyles.color,
|
||||
normalizeComputedColor(bodyStyles.color, fallbackForeground),
|
||||
);
|
||||
const rootStyles = getComputedStyle(document.documentElement);
|
||||
const themedBackground = normalizeComputedColor(
|
||||
rootStyles.getPropertyValue("--terminal-background"),
|
||||
background,
|
||||
);
|
||||
const themedForeground = normalizeComputedColor(
|
||||
rootStyles.getPropertyValue("--terminal-foreground"),
|
||||
foreground,
|
||||
);
|
||||
const themedCursor = normalizeComputedColor(
|
||||
rootStyles.getPropertyValue("--terminal-cursor"),
|
||||
isDark ? "rgb(180, 203, 255)" : "rgb(38, 56, 78)",
|
||||
);
|
||||
const themedSelection = normalizeComputedColor(
|
||||
rootStyles.getPropertyValue("--terminal-selection-background"),
|
||||
isDark ? "rgba(180, 203, 255, 0.25)" : "rgba(37, 63, 99, 0.2)",
|
||||
);
|
||||
|
||||
if (isDark) {
|
||||
return {
|
||||
background,
|
||||
foreground,
|
||||
cursor: "rgb(180, 203, 255)",
|
||||
selectionBackground: "rgba(180, 203, 255, 0.25)",
|
||||
background: themedBackground,
|
||||
foreground: themedForeground,
|
||||
cursor: themedCursor,
|
||||
selectionBackground: themedSelection,
|
||||
scrollbarSliderBackground: "rgba(255, 255, 255, 0.1)",
|
||||
scrollbarSliderHoverBackground: "rgba(255, 255, 255, 0.18)",
|
||||
scrollbarSliderActiveBackground: "rgba(255, 255, 255, 0.22)",
|
||||
@@ -150,10 +167,10 @@ function terminalThemeFromApp(mountElement?: HTMLElement | null): ITheme {
|
||||
}
|
||||
|
||||
return {
|
||||
background,
|
||||
foreground,
|
||||
cursor: "rgb(38, 56, 78)",
|
||||
selectionBackground: "rgba(37, 63, 99, 0.2)",
|
||||
background: themedBackground,
|
||||
foreground: themedForeground,
|
||||
cursor: themedCursor,
|
||||
selectionBackground: themedSelection,
|
||||
scrollbarSliderBackground: "rgba(0, 0, 0, 0.15)",
|
||||
scrollbarSliderHoverBackground: "rgba(0, 0, 0, 0.25)",
|
||||
scrollbarSliderActiveBackground: "rgba(0, 0, 0, 0.3)",
|
||||
|
||||
@@ -427,7 +427,11 @@ const createDesktopBridgeStub = (overrides?: {
|
||||
getAdvertisedEndpoints: vi.fn().mockResolvedValue(overrides?.advertisedEndpoints ?? []),
|
||||
pickFolder: vi.fn().mockResolvedValue(null),
|
||||
confirm: vi.fn().mockResolvedValue(false),
|
||||
discoverColorThemes: vi.fn().mockResolvedValue([]),
|
||||
loadColorTheme: vi.fn().mockResolvedValue(null),
|
||||
getEditorThemePreferences: vi.fn().mockResolvedValue([]),
|
||||
setTheme: vi.fn().mockResolvedValue(undefined),
|
||||
setWindowThemeColors: vi.fn().mockResolvedValue(undefined),
|
||||
showContextMenu: vi.fn().mockResolvedValue(null),
|
||||
openExternal: vi.fn().mockResolvedValue(true),
|
||||
onMenuAction: () => () => {},
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceId,
|
||||
type ScopedThreadRef,
|
||||
type ThemePreference,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
@@ -95,6 +96,26 @@ const THEME_OPTIONS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
function themePreferenceToSelectValue(preference: ThemePreference) {
|
||||
if (preference.mode === "system") return "system";
|
||||
if (preference.mode === "builtin") return `builtin:${preference.theme}`;
|
||||
if (preference.mode === "external") return `external:${preference.themeId}`;
|
||||
return `follow-editor:${preference.source}`;
|
||||
}
|
||||
|
||||
function selectValueToThemePreference(value: string): ThemePreference | null {
|
||||
if (value === "system") return { mode: "system" };
|
||||
if (value === "builtin:light") return { mode: "builtin", theme: "light" };
|
||||
if (value === "builtin:dark") return { mode: "builtin", theme: "dark" };
|
||||
if (value.startsWith("external:")) return { mode: "external", themeId: value.slice(9) };
|
||||
if (value === "follow-editor:vscode") return { mode: "follow-editor", source: "vscode" };
|
||||
if (value === "follow-editor:cursor") return { mode: "follow-editor", source: "cursor" };
|
||||
if (value === "follow-editor:vscode-insiders") {
|
||||
return { mode: "follow-editor", source: "vscode-insiders" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
locale: "System default",
|
||||
"12-hour": "12-hour",
|
||||
@@ -438,7 +459,16 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const {
|
||||
theme,
|
||||
preference,
|
||||
setTheme,
|
||||
setThemePreference,
|
||||
discoveredThemes,
|
||||
refreshThemes,
|
||||
status: themeStatus,
|
||||
message: themeMessage,
|
||||
} = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const observability = useServerObservability();
|
||||
@@ -479,34 +509,67 @@ export function GeneralSettingsPanel() {
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow
|
||||
title="Theme"
|
||||
description="Choose how T3 Code looks across the app."
|
||||
description={
|
||||
themeMessage ??
|
||||
(discoveredThemes.length > 0
|
||||
? `Detected ${discoveredThemes.length} themes from VS Code and Cursor.`
|
||||
: "Choose how T3 Code looks across the app.")
|
||||
}
|
||||
resetAction={
|
||||
theme !== "system" ? (
|
||||
<SettingResetButton label="theme" onClick={() => setTheme("system")} />
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={theme}
|
||||
onValueChange={(value) => {
|
||||
if (value === "system" || value === "light" || value === "dark") {
|
||||
setTheme(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">
|
||||
<SelectValue>
|
||||
{THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{THEME_OPTIONS.map((option) => (
|
||||
<SelectItem hideIndicator key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
<div className="flex w-full items-center justify-end gap-2 sm:w-auto">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Refresh editor themes"
|
||||
disabled={themeStatus === "loading"}
|
||||
onClick={() => void refreshThemes()}
|
||||
>
|
||||
{themeStatus === "loading" ? (
|
||||
<LoaderIcon className="size-4 animate-spin" />
|
||||
) : (
|
||||
<RefreshCwIcon className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Select
|
||||
value={themePreferenceToSelectValue(preference)}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextPreference = selectValueToThemePreference(value);
|
||||
if (nextPreference) setThemePreference(nextPreference);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-64" aria-label="Theme preference">
|
||||
<SelectValue>
|
||||
{preference.mode === "external"
|
||||
? (discoveredThemes.find((entry) => entry.id === preference.themeId)?.label ??
|
||||
"External theme")
|
||||
: (THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System")}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="system">
|
||||
System
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<SelectItem hideIndicator value="builtin:light">
|
||||
Light
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="builtin:dark">
|
||||
Dark
|
||||
</SelectItem>
|
||||
{discoveredThemes.map((entry) => (
|
||||
<SelectItem hideIndicator key={entry.id} value={`external:${entry.id}`}>
|
||||
{entry.source === "cursor" ? "Cursor" : "VS Code"} · {entry.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -15,14 +15,11 @@ import { selectProjectsAcrossEnvironments, useStore } from "../store";
|
||||
import { createThreadSelectorByRef } from "../storeSelectors";
|
||||
import { resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { useSettings } from "./useSettings";
|
||||
import { useProjectGroupingSettings } from "./useSettings";
|
||||
|
||||
function useNewThreadState() {
|
||||
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useProjectGroupingSettings();
|
||||
const router = useRouter();
|
||||
const getCurrentRouteTarget = useCallback(() => {
|
||||
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
||||
|
||||
@@ -22,6 +22,7 @@ import { ensureLocalApi } from "~/localApi";
|
||||
import { Struct } from "effect";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
|
||||
import type { ProjectGroupingSettings } from "~/logicalProject";
|
||||
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
@@ -31,6 +32,11 @@ let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
let clientSettingsHydrated = false;
|
||||
let clientSettingsHydrationPromise: Promise<void> | null = null;
|
||||
|
||||
const selectSidebarProjectGroupingMode = (settings: UnifiedSettings) =>
|
||||
settings.sidebarProjectGroupingMode;
|
||||
const selectSidebarProjectGroupingOverrides = (settings: UnifiedSettings) =>
|
||||
settings.sidebarProjectGroupingOverrides;
|
||||
|
||||
function emitClientSettingsChange() {
|
||||
for (const listener of clientSettingsListeners) {
|
||||
listener();
|
||||
@@ -186,6 +192,19 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
|
||||
return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
|
||||
}
|
||||
|
||||
export function useProjectGroupingSettings(): ProjectGroupingSettings {
|
||||
const sidebarProjectGroupingMode = useSettings(selectSidebarProjectGroupingMode);
|
||||
const sidebarProjectGroupingOverrides = useSettings(selectSidebarProjectGroupingOverrides);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides,
|
||||
}),
|
||||
[sidebarProjectGroupingMode, sidebarProjectGroupingOverrides],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an updater that routes each key to the correct backing store.
|
||||
*
|
||||
|
||||
+383
-73
@@ -1,23 +1,48 @@
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import type {
|
||||
DesktopTheme,
|
||||
DiscoveredColorTheme,
|
||||
ResolvedColorTheme,
|
||||
ThemePreference,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_THEME_PREFERENCE } from "@t3tools/contracts";
|
||||
import { EXTERNAL_APP_THEME_VARIABLES, isDarkThemeKind } from "@t3tools/shared/themeMapping";
|
||||
|
||||
type Theme = "light" | "dark" | "system";
|
||||
type BuiltInTheme = "light" | "dark" | "system";
|
||||
type ThemeStatus = "idle" | "loading" | "ready" | "error";
|
||||
type ThemeSnapshot = {
|
||||
theme: Theme;
|
||||
preference: ThemePreference;
|
||||
systemDark: boolean;
|
||||
resolvedKind: "light" | "dark";
|
||||
resolvedColorTheme: ResolvedColorTheme | null;
|
||||
discoveredThemes: readonly DiscoveredColorTheme[];
|
||||
status: ThemeStatus;
|
||||
message: string | null;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const PREFERENCE_STORAGE_KEY = "t3code:theme-preference:v1";
|
||||
const BOOTSTRAP_THEME_CACHE_KEY = "t3code:resolved-theme-cache:v1";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
|
||||
theme: "system",
|
||||
systemDark: false,
|
||||
};
|
||||
const THEME_COLOR_META_NAME = "theme-color";
|
||||
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let lastSnapshot: ThemeSnapshot | null = null;
|
||||
let lastDesktopTheme: Theme | null = null;
|
||||
let lastDesktopTheme: DesktopTheme | null = null;
|
||||
let themeRuntimeRefCount = 0;
|
||||
let stopThemeRuntime: (() => void) | null = null;
|
||||
let refreshThemesPromise: Promise<void> | null = null;
|
||||
const preferenceLoadPromises = new Map<string, Promise<void>>();
|
||||
let state: ThemeSnapshot = {
|
||||
preference: DEFAULT_THEME_PREFERENCE,
|
||||
systemDark: false,
|
||||
resolvedKind: "light",
|
||||
resolvedColorTheme: null,
|
||||
discoveredThemes: [],
|
||||
status: "idle",
|
||||
message: null,
|
||||
};
|
||||
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
@@ -31,18 +56,91 @@ function getSystemDark() {
|
||||
return typeof window !== "undefined" && window.matchMedia(MEDIA_QUERY).matches;
|
||||
}
|
||||
|
||||
function getStored(): Theme {
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") return raw;
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
function builtInToPreference(theme: BuiltInTheme): ThemePreference {
|
||||
return theme === "system" ? { mode: "system" } : { mode: "builtin", theme };
|
||||
}
|
||||
|
||||
function preferenceToBuiltInTheme(preference: ThemePreference): BuiltInTheme {
|
||||
if (preference.mode === "builtin") return preference.theme;
|
||||
return "system";
|
||||
}
|
||||
|
||||
function parsePreference(value: string | null): ThemePreference | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
if (typeof parsed !== "object" || parsed === null) return null;
|
||||
if ("mode" in parsed && parsed.mode === "system") return { mode: "system" };
|
||||
if ("mode" in parsed && parsed.mode === "builtin" && "theme" in parsed) {
|
||||
if (parsed.theme === "light" || parsed.theme === "dark") {
|
||||
return { mode: "builtin", theme: parsed.theme };
|
||||
}
|
||||
}
|
||||
if ("mode" in parsed && parsed.mode === "external" && "themeId" in parsed) {
|
||||
return typeof parsed.themeId === "string"
|
||||
? { mode: "external", themeId: parsed.themeId }
|
||||
: null;
|
||||
}
|
||||
if ("mode" in parsed && parsed.mode === "follow-editor" && "source" in parsed) {
|
||||
if (
|
||||
parsed.source === "vscode" ||
|
||||
parsed.source === "cursor" ||
|
||||
parsed.source === "vscode-insiders"
|
||||
) {
|
||||
return { mode: "follow-editor", source: parsed.source };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getStoredPreference(): ThemePreference {
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_PREFERENCE;
|
||||
const savedPreference = parsePreference(localStorage.getItem(PREFERENCE_STORAGE_KEY));
|
||||
if (savedPreference) return savedPreference;
|
||||
const legacy = localStorage.getItem(STORAGE_KEY);
|
||||
if (legacy === "light" || legacy === "dark" || legacy === "system") {
|
||||
const migrated = builtInToPreference(legacy);
|
||||
localStorage.setItem(PREFERENCE_STORAGE_KEY, JSON.stringify(migrated));
|
||||
return migrated;
|
||||
}
|
||||
return DEFAULT_THEME_PREFERENCE;
|
||||
}
|
||||
|
||||
function setStoredPreference(preference: ThemePreference) {
|
||||
if (!hasThemeStorage()) return;
|
||||
localStorage.setItem(PREFERENCE_STORAGE_KEY, JSON.stringify(preference));
|
||||
localStorage.setItem(STORAGE_KEY, preferenceToBuiltInTheme(preference));
|
||||
}
|
||||
|
||||
function isSamePreference(a: ThemePreference, b: ThemePreference) {
|
||||
if (a.mode !== b.mode) return false;
|
||||
if (a.mode === "builtin") return a.theme === (b.mode === "builtin" ? b.theme : null);
|
||||
if (a.mode === "external") return a.themeId === (b.mode === "external" ? b.themeId : null);
|
||||
if (a.mode === "follow-editor") {
|
||||
return a.source === (b.mode === "follow-editor" ? b.source : null);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function themePreferenceKey(preference: ThemePreference) {
|
||||
switch (preference.mode) {
|
||||
case "builtin":
|
||||
return `builtin:${preference.theme}`;
|
||||
case "external":
|
||||
return `external:${preference.themeId}`;
|
||||
case "follow-editor":
|
||||
return `follow-editor:${preference.source}`;
|
||||
case "system":
|
||||
return "system";
|
||||
}
|
||||
}
|
||||
|
||||
function ensureThemeColorMetaTag(): HTMLMetaElement {
|
||||
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
|
||||
if (element) {
|
||||
return element;
|
||||
}
|
||||
if (element) return element;
|
||||
|
||||
element = document.createElement("meta");
|
||||
element.name = THEME_COLOR_META_NAME;
|
||||
@@ -87,108 +185,320 @@ export function syncBrowserChromeTheme() {
|
||||
ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
|
||||
}
|
||||
|
||||
function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") return;
|
||||
if (suppressTransitions) {
|
||||
document.documentElement.classList.add("no-transitions");
|
||||
}
|
||||
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
syncBrowserChromeTheme();
|
||||
syncDesktopTheme(theme);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
});
|
||||
function clearExternalThemeVariables(root: HTMLElement) {
|
||||
for (const name of EXTERNAL_APP_THEME_VARIABLES) {
|
||||
root.style.removeProperty(name);
|
||||
}
|
||||
}
|
||||
|
||||
function syncDesktopTheme(theme: Theme) {
|
||||
function syncDesktopTheme(theme: DesktopTheme) {
|
||||
if (typeof window === "undefined") return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || lastDesktopTheme === theme) {
|
||||
return;
|
||||
}
|
||||
if (!bridge?.setTheme || lastDesktopTheme === theme) return;
|
||||
|
||||
lastDesktopTheme = theme;
|
||||
void bridge.setTheme(theme).catch(() => {
|
||||
if (lastDesktopTheme === theme) {
|
||||
lastDesktopTheme = null;
|
||||
}
|
||||
if (lastDesktopTheme === theme) lastDesktopTheme = null;
|
||||
});
|
||||
}
|
||||
|
||||
// Apply immediately on module load to prevent flash
|
||||
function syncDesktopWindowColors(theme: ResolvedColorTheme | null) {
|
||||
if (typeof window === "undefined") return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge?.setWindowThemeColors || !theme) return;
|
||||
const backgroundColor =
|
||||
theme.appVariables["--app-chrome-background"] ??
|
||||
theme.appVariables["--background"] ??
|
||||
(isDarkThemeKind(theme.kind) ? "#0a0a0a" : "#ffffff");
|
||||
void bridge
|
||||
.setWindowThemeColors({
|
||||
backgroundColor,
|
||||
titleBarColor: backgroundColor,
|
||||
titleBarSymbolColor: theme.appVariables["--foreground"],
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
function applyResolvedTheme(theme: ResolvedColorTheme | null, suppressTransitions = false) {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") return;
|
||||
const root = document.documentElement;
|
||||
if (suppressTransitions) root.classList.add("no-transitions");
|
||||
|
||||
if (theme) {
|
||||
for (const [name, value] of Object.entries(theme.appVariables)) {
|
||||
root.style.setProperty(name, value);
|
||||
}
|
||||
} else {
|
||||
clearExternalThemeVariables(root);
|
||||
}
|
||||
|
||||
const preference = state.preference;
|
||||
const isDark = theme
|
||||
? isDarkThemeKind(theme.kind)
|
||||
: preference.mode === "builtin"
|
||||
? preference.theme === "dark"
|
||||
: getSystemDark();
|
||||
root.classList.toggle("dark", isDark);
|
||||
root.dataset.themeSource = theme?.source ?? "builtin";
|
||||
root.dataset.themeId = theme?.id ?? "";
|
||||
syncBrowserChromeTheme();
|
||||
syncDesktopTheme(
|
||||
theme
|
||||
? isDark
|
||||
? "dark"
|
||||
: "light"
|
||||
: preference.mode === "system"
|
||||
? "system"
|
||||
: isDark
|
||||
? "dark"
|
||||
: "light",
|
||||
);
|
||||
syncDesktopWindowColors(theme);
|
||||
|
||||
if (suppressTransitions) {
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
root.offsetHeight;
|
||||
requestAnimationFrame(() => root.classList.remove("no-transitions"));
|
||||
}
|
||||
}
|
||||
|
||||
function recomputeSnapshot(next: Partial<ThemeSnapshot> = {}) {
|
||||
const preference = next.preference ?? state.preference;
|
||||
const systemDark = getSystemDark();
|
||||
const resolvedTheme =
|
||||
next.resolvedColorTheme === undefined ? state.resolvedColorTheme : next.resolvedColorTheme;
|
||||
const resolvedKind: "light" | "dark" = resolvedTheme
|
||||
? isDarkThemeKind(resolvedTheme.kind)
|
||||
? "dark"
|
||||
: "light"
|
||||
: preference.mode === "builtin"
|
||||
? preference.theme
|
||||
: systemDark
|
||||
? "dark"
|
||||
: "light";
|
||||
|
||||
state = {
|
||||
...state,
|
||||
...next,
|
||||
preference,
|
||||
systemDark,
|
||||
resolvedKind,
|
||||
resolvedColorTheme: resolvedTheme,
|
||||
};
|
||||
lastSnapshot = null;
|
||||
emitChange();
|
||||
}
|
||||
|
||||
async function loadPreference(preference: ThemePreference, suppressTransitions = true) {
|
||||
if (preference.mode === "external") {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge?.loadColorTheme) {
|
||||
recomputeSnapshot({
|
||||
preference,
|
||||
resolvedColorTheme: null,
|
||||
status: "error",
|
||||
message: "Desktop theme discovery is unavailable in browser mode.",
|
||||
});
|
||||
applyResolvedTheme(null, suppressTransitions);
|
||||
return;
|
||||
}
|
||||
|
||||
recomputeSnapshot({ preference, status: "loading", message: null });
|
||||
let theme: ResolvedColorTheme | null;
|
||||
try {
|
||||
theme = await bridge.loadColorTheme(preference.themeId);
|
||||
} catch {
|
||||
if (!isSamePreference(state.preference, preference)) return;
|
||||
recomputeSnapshot({
|
||||
resolvedColorTheme: null,
|
||||
status: "error",
|
||||
message: "Could not load selected editor theme.",
|
||||
});
|
||||
applyResolvedTheme(null, suppressTransitions);
|
||||
return;
|
||||
}
|
||||
if (!isSamePreference(state.preference, preference)) return;
|
||||
if (!theme) {
|
||||
setStoredPreference(DEFAULT_THEME_PREFERENCE);
|
||||
recomputeSnapshot({
|
||||
preference: DEFAULT_THEME_PREFERENCE,
|
||||
resolvedColorTheme: null,
|
||||
status: "error",
|
||||
message: "Selected theme is unavailable. Falling back to System.",
|
||||
});
|
||||
applyResolvedTheme(null, suppressTransitions);
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(
|
||||
BOOTSTRAP_THEME_CACHE_KEY,
|
||||
JSON.stringify({ id: theme.id, kind: theme.kind, appVariables: theme.appVariables }),
|
||||
);
|
||||
recomputeSnapshot({ preference, resolvedColorTheme: theme, status: "ready", message: null });
|
||||
applyResolvedTheme(theme, suppressTransitions);
|
||||
return;
|
||||
}
|
||||
|
||||
recomputeSnapshot({ preference, resolvedColorTheme: null, status: "ready", message: null });
|
||||
applyResolvedTheme(null, suppressTransitions);
|
||||
}
|
||||
|
||||
function loadThemePreference(preference: ThemePreference, suppressTransitions = true) {
|
||||
const key = themePreferenceKey(preference);
|
||||
const existing = preferenceLoadPromises.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
const promise = loadPreference(preference, suppressTransitions).finally(() => {
|
||||
if (preferenceLoadPromises.get(key) === promise) {
|
||||
preferenceLoadPromises.delete(key);
|
||||
}
|
||||
});
|
||||
preferenceLoadPromises.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function loadStoredPreference(suppressTransitions = true) {
|
||||
return loadThemePreference(getStoredPreference(), suppressTransitions);
|
||||
}
|
||||
|
||||
async function refreshThemesNow() {
|
||||
const bridge = typeof window !== "undefined" ? window.desktopBridge : null;
|
||||
if (!bridge?.discoverColorThemes) {
|
||||
recomputeSnapshot({
|
||||
discoveredThemes: [],
|
||||
status: "ready",
|
||||
message: "Open the desktop app to use VS Code and Cursor themes.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
recomputeSnapshot({ status: "loading", message: null });
|
||||
try {
|
||||
const discoveredThemes = await bridge.discoverColorThemes();
|
||||
recomputeSnapshot({ discoveredThemes, status: "ready", message: null });
|
||||
} catch {
|
||||
recomputeSnapshot({ status: "error", message: "Could not refresh editor themes." });
|
||||
}
|
||||
}
|
||||
|
||||
export function refreshThemes() {
|
||||
if (refreshThemesPromise) return refreshThemesPromise;
|
||||
|
||||
refreshThemesPromise = refreshThemesNow().finally(() => {
|
||||
refreshThemesPromise = null;
|
||||
});
|
||||
return refreshThemesPromise;
|
||||
}
|
||||
|
||||
function bootstrapCachedTheme() {
|
||||
if (!hasThemeStorage()) return null;
|
||||
const raw = localStorage.getItem(BOOTSTRAP_THEME_CACHE_KEY);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<ResolvedColorTheme>;
|
||||
if (!parsed.id || !parsed.kind || !parsed.appVariables) return null;
|
||||
return parsed as ResolvedColorTheme;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof document !== "undefined" && hasThemeStorage()) {
|
||||
applyTheme(getStored());
|
||||
const preference = getStoredPreference();
|
||||
state.preference = preference;
|
||||
if (preference.mode === "external") {
|
||||
state.resolvedColorTheme = bootstrapCachedTheme();
|
||||
}
|
||||
applyResolvedTheme(state.resolvedColorTheme);
|
||||
}
|
||||
|
||||
function getSnapshot(): ThemeSnapshot {
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT;
|
||||
const theme = getStored();
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
|
||||
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
lastSnapshot = { theme, systemDark };
|
||||
if (lastSnapshot) return lastSnapshot;
|
||||
lastSnapshot = state;
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
function getServerSnapshot() {
|
||||
return DEFAULT_THEME_SNAPSHOT;
|
||||
return state;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
if (typeof window === "undefined") return () => {};
|
||||
listeners.push(listener);
|
||||
|
||||
// Listen for system preference changes
|
||||
return () => {
|
||||
listeners = listeners.filter((l) => l !== listener);
|
||||
};
|
||||
}
|
||||
|
||||
function startThemeRuntimeUnsafe() {
|
||||
const mq = window.matchMedia(MEDIA_QUERY);
|
||||
const handleChange = () => {
|
||||
if (getStored() === "system") applyTheme("system", true);
|
||||
emitChange();
|
||||
recomputeSnapshot();
|
||||
applyResolvedTheme(state.resolvedColorTheme, true);
|
||||
};
|
||||
mq.addEventListener("change", handleChange);
|
||||
|
||||
// Listen for storage changes from other tabs
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY) {
|
||||
applyTheme(getStored(), true);
|
||||
emitChange();
|
||||
if (e.key === STORAGE_KEY || e.key === PREFERENCE_STORAGE_KEY) {
|
||||
void loadStoredPreference(true);
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", handleStorage);
|
||||
|
||||
void loadStoredPreference(false).finally(() => {
|
||||
void refreshThemes();
|
||||
});
|
||||
|
||||
return () => {
|
||||
listeners = listeners.filter((l) => l !== listener);
|
||||
mq.removeEventListener("change", handleChange);
|
||||
window.removeEventListener("storage", handleStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function startThemeRuntime() {
|
||||
if (typeof window === "undefined") return () => {};
|
||||
|
||||
themeRuntimeRefCount += 1;
|
||||
if (themeRuntimeRefCount === 1) {
|
||||
stopThemeRuntime = startThemeRuntimeUnsafe();
|
||||
}
|
||||
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
themeRuntimeRefCount = Math.max(0, themeRuntimeRefCount - 1);
|
||||
if (themeRuntimeRefCount === 0) {
|
||||
stopThemeRuntime?.();
|
||||
stopThemeRuntime = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
const theme = snapshot.theme;
|
||||
|
||||
const resolvedTheme: "light" | "dark" =
|
||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
if (!hasThemeStorage()) return;
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
applyTheme(next, true);
|
||||
emitChange();
|
||||
const setThemePreference = useCallback((preference: ThemePreference) => {
|
||||
setStoredPreference(preference);
|
||||
void loadThemePreference(preference, true);
|
||||
}, []);
|
||||
|
||||
// Keep DOM in sync on mount/change
|
||||
useEffect(() => {
|
||||
applyTheme(theme);
|
||||
}, [theme]);
|
||||
const setTheme = useCallback(
|
||||
(next: BuiltInTheme) => {
|
||||
setThemePreference(builtInToPreference(next));
|
||||
},
|
||||
[setThemePreference],
|
||||
);
|
||||
|
||||
return { theme, setTheme, resolvedTheme } as const;
|
||||
return {
|
||||
theme: preferenceToBuiltInTheme(snapshot.preference),
|
||||
setTheme,
|
||||
preference: snapshot.preference,
|
||||
setThemePreference,
|
||||
resolvedTheme: snapshot.resolvedKind,
|
||||
resolvedColorTheme: snapshot.resolvedColorTheme,
|
||||
discoveredThemes: snapshot.discoveredThemes,
|
||||
refreshThemes,
|
||||
status: snapshot.status,
|
||||
message: snapshot.message,
|
||||
} as const;
|
||||
}
|
||||
@@ -31,6 +31,11 @@
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
@@ -112,6 +117,19 @@
|
||||
--success-foreground: var(--color-emerald-700);
|
||||
--warning: var(--color-amber-500);
|
||||
--warning-foreground: var(--color-amber-700);
|
||||
--sidebar: var(--background);
|
||||
--sidebar-foreground: var(--foreground);
|
||||
--sidebar-accent: var(--accent);
|
||||
--sidebar-accent-foreground: var(--accent-foreground);
|
||||
--sidebar-border: var(--border);
|
||||
--terminal-background: var(--background);
|
||||
--terminal-foreground: var(--foreground);
|
||||
--terminal-cursor: var(--ring);
|
||||
--terminal-selection-background: color-mix(in srgb, var(--ring) 24%, transparent);
|
||||
--diff-inserted: var(--success);
|
||||
--diff-removed: var(--destructive);
|
||||
--chat-request-background: var(--card);
|
||||
--chat-request-border: var(--border);
|
||||
|
||||
@variant dark {
|
||||
color-scheme: dark;
|
||||
@@ -141,6 +159,19 @@
|
||||
--success-foreground: var(--color-emerald-400);
|
||||
--warning: var(--color-amber-500);
|
||||
--warning-foreground: var(--color-amber-400);
|
||||
--sidebar: var(--background);
|
||||
--sidebar-foreground: var(--foreground);
|
||||
--sidebar-accent: var(--accent);
|
||||
--sidebar-accent-foreground: var(--accent-foreground);
|
||||
--sidebar-border: var(--border);
|
||||
--terminal-background: var(--background);
|
||||
--terminal-foreground: var(--foreground);
|
||||
--terminal-cursor: var(--ring);
|
||||
--terminal-selection-background: color-mix(in srgb, var(--ring) 24%, transparent);
|
||||
--diff-inserted: var(--success);
|
||||
--diff-removed: var(--destructive);
|
||||
--chat-request-background: var(--card);
|
||||
--chat-request-border: var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ResolvedColorTheme } from "@t3tools/contracts";
|
||||
import { resolveCodeBlockThemeName, resolveSyntaxThemeName } from "./syntaxTheme";
|
||||
|
||||
function makeTheme(overrides: Partial<ResolvedColorTheme> = {}): ResolvedColorTheme {
|
||||
return {
|
||||
id: "vscode:github.github-vscode-theme:GitHub Dark Default",
|
||||
label: "GitHub Dark Default",
|
||||
source: "vscode",
|
||||
kind: "dark",
|
||||
colors: {
|
||||
"editor.background": "#0d1117",
|
||||
"editor.foreground": "#e6edf3",
|
||||
},
|
||||
tokenColors: [
|
||||
{
|
||||
scope: "keyword",
|
||||
settings: {
|
||||
foreground: "#ff7b72",
|
||||
},
|
||||
},
|
||||
],
|
||||
appVariables: {
|
||||
"--background": "#0d1117",
|
||||
"--foreground": "#e6edf3",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("syntaxTheme", () => {
|
||||
it("falls back to built-in diff themes without an external theme", () => {
|
||||
expect(resolveSyntaxThemeName({ resolvedTheme: "dark", resolvedColorTheme: null })).toBe(
|
||||
"pierre-dark",
|
||||
);
|
||||
expect(resolveSyntaxThemeName({ resolvedTheme: "light", resolvedColorTheme: null })).toBe(
|
||||
"pierre-light",
|
||||
);
|
||||
});
|
||||
|
||||
it("creates stable content-addressed custom syntax theme names", () => {
|
||||
const theme = makeTheme();
|
||||
expect(resolveSyntaxThemeName({ resolvedTheme: "dark", resolvedColorTheme: theme })).toBe(
|
||||
resolveSyntaxThemeName({ resolvedTheme: "dark", resolvedColorTheme: theme }),
|
||||
);
|
||||
expect(
|
||||
resolveSyntaxThemeName({
|
||||
resolvedTheme: "dark",
|
||||
resolvedColorTheme: makeTheme({
|
||||
tokenColors: [{ scope: "keyword", settings: { foreground: "#79c0ff" } }],
|
||||
}),
|
||||
}),
|
||||
).not.toBe(resolveSyntaxThemeName({ resolvedTheme: "dark", resolvedColorTheme: theme }));
|
||||
});
|
||||
|
||||
it("keeps the code block resolver as an alias of the shared syntax resolver", () => {
|
||||
const theme = makeTheme();
|
||||
expect(resolveCodeBlockThemeName({ resolvedTheme: "dark", resolvedColorTheme: theme })).toBe(
|
||||
resolveSyntaxThemeName({ resolvedTheme: "dark", resolvedColorTheme: theme }),
|
||||
);
|
||||
});
|
||||
|
||||
it("handles bootstrap-cached external themes before full colors load", () => {
|
||||
const cachedTheme = {
|
||||
id: "vscode:github.github-vscode-theme:GitHub Dark Default",
|
||||
kind: "dark",
|
||||
appVariables: {
|
||||
"--background": "#0d1117",
|
||||
"--foreground": "#e6edf3",
|
||||
},
|
||||
} satisfies Partial<ResolvedColorTheme>;
|
||||
|
||||
expect(
|
||||
resolveSyntaxThemeName({ resolvedTheme: "dark", resolvedColorTheme: cachedTheme }),
|
||||
).toMatch(/^t3-syntax-/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import {
|
||||
registerCustomTheme,
|
||||
type DiffsThemeNames,
|
||||
type ThemeRegistrationResolved,
|
||||
} from "@pierre/diffs";
|
||||
import type { ResolvedColorTheme } from "@t3tools/contracts";
|
||||
import { isDarkThemeKind } from "@t3tools/shared/themeMapping";
|
||||
import { resolveDiffThemeName } from "./diffRendering";
|
||||
|
||||
type BuiltInResolvedTheme = "light" | "dark";
|
||||
type SyntaxColorTheme = Partial<ResolvedColorTheme>;
|
||||
type ThemeSetting = ThemeRegistrationResolved["settings"][number];
|
||||
type ThemeSettingOptions = ThemeSetting["settings"];
|
||||
|
||||
const registeredSyntaxThemes = new Set<string>();
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
|
||||
}
|
||||
if (isRecord(value)) {
|
||||
return `{${Object.entries(value)
|
||||
.toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
|
||||
.map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function normalizeStringRecord(value: unknown): Record<string, string> {
|
||||
if (!isRecord(value)) return {};
|
||||
|
||||
const normalized: Record<string, string> = {};
|
||||
for (const [key, entry] of Object.entries(value)) {
|
||||
if (typeof entry === "string") {
|
||||
normalized[key] = entry;
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function hashString(input: string) {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
hash = Math.imul(hash, 0x01000193) >>> 0;
|
||||
}
|
||||
return hash.toString(36);
|
||||
}
|
||||
|
||||
function normalizeScopes(value: unknown): ThemeSetting["scope"] | undefined {
|
||||
if (typeof value === "string") return value;
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeThemeSettings(value: unknown): ThemeSettingOptions | null {
|
||||
if (!isRecord(value)) return null;
|
||||
|
||||
const settings: ThemeSettingOptions = {
|
||||
...(typeof value.foreground === "string" ? { foreground: value.foreground } : {}),
|
||||
...(typeof value.background === "string" ? { background: value.background } : {}),
|
||||
...(typeof value.fontStyle === "string" ? { fontStyle: value.fontStyle } : {}),
|
||||
};
|
||||
|
||||
return Object.keys(settings).length > 0 ? settings : null;
|
||||
}
|
||||
|
||||
function normalizeTokenColors(value: unknown): ThemeRegistrationResolved["settings"] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
|
||||
const settings: ThemeRegistrationResolved["settings"] = [];
|
||||
for (const entry of value) {
|
||||
if (!isRecord(entry)) continue;
|
||||
const tokenSettings = normalizeThemeSettings(entry.settings);
|
||||
if (!tokenSettings) continue;
|
||||
|
||||
const scope = normalizeScopes(entry.scope);
|
||||
const next: ThemeSetting = {
|
||||
...(scope ? { scope } : {}),
|
||||
...(typeof entry.name === "string" ? { name: entry.name } : {}),
|
||||
settings: tokenSettings,
|
||||
};
|
||||
settings.push(next);
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
function syntaxThemeName(theme: SyntaxColorTheme, fallbackTheme: BuiltInResolvedTheme) {
|
||||
const colors = normalizeStringRecord(theme.colors);
|
||||
return `t3-syntax-${hashString(
|
||||
stableStringify({
|
||||
id: theme.id,
|
||||
kind: theme.kind ?? fallbackTheme,
|
||||
colors,
|
||||
tokenColors: theme.tokenColors,
|
||||
semanticHighlighting: theme.semanticHighlighting,
|
||||
}),
|
||||
)}`;
|
||||
}
|
||||
|
||||
function toShikiTheme(
|
||||
theme: SyntaxColorTheme,
|
||||
name: string,
|
||||
fallbackTheme: BuiltInResolvedTheme,
|
||||
): ThemeRegistrationResolved {
|
||||
const colors = normalizeStringRecord(theme.colors);
|
||||
const appVariables = normalizeStringRecord(theme.appVariables);
|
||||
const foreground = colors["editor.foreground"] ?? appVariables["--foreground"] ?? "#f5f5f5";
|
||||
const background = colors["editor.background"] ?? appVariables["--background"] ?? "#111111";
|
||||
const settings = normalizeTokenColors(theme.tokenColors);
|
||||
const isDark = theme.kind ? isDarkThemeKind(theme.kind) : fallbackTheme === "dark";
|
||||
|
||||
return {
|
||||
name,
|
||||
displayName: theme.label ?? "Custom Theme",
|
||||
type: isDark ? "dark" : "light",
|
||||
fg: foreground,
|
||||
bg: background,
|
||||
colors: {
|
||||
...colors,
|
||||
"editor.foreground": foreground,
|
||||
"editor.background": background,
|
||||
},
|
||||
settings,
|
||||
tokenColors: settings,
|
||||
...(typeof theme.semanticHighlighting === "boolean"
|
||||
? { semanticHighlighting: theme.semanticHighlighting }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function registerSyntaxTheme(theme: SyntaxColorTheme, fallbackTheme: BuiltInResolvedTheme) {
|
||||
const name = syntaxThemeName(theme, fallbackTheme);
|
||||
if (registeredSyntaxThemes.has(name)) return name;
|
||||
|
||||
const shikiTheme = toShikiTheme(theme, name, fallbackTheme);
|
||||
registerCustomTheme(name, async () => shikiTheme);
|
||||
registeredSyntaxThemes.add(name);
|
||||
return name;
|
||||
}
|
||||
|
||||
export function resolveSyntaxThemeName(input: {
|
||||
readonly resolvedTheme: BuiltInResolvedTheme;
|
||||
readonly resolvedColorTheme: SyntaxColorTheme | null;
|
||||
}): DiffsThemeNames {
|
||||
if (!input.resolvedColorTheme) {
|
||||
return resolveDiffThemeName(input.resolvedTheme);
|
||||
}
|
||||
return registerSyntaxTheme(input.resolvedColorTheme, input.resolvedTheme);
|
||||
}
|
||||
|
||||
export const resolveCodeBlockThemeName = resolveSyntaxThemeName;
|
||||
@@ -222,7 +222,11 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
|
||||
getAdvertisedEndpoints: async () => [],
|
||||
pickFolder: async () => null,
|
||||
confirm: async () => true,
|
||||
discoverColorThemes: async () => [],
|
||||
loadColorTheme: async () => null,
|
||||
getEditorThemePreferences: async () => [],
|
||||
setTheme: async () => undefined,
|
||||
setWindowThemeColors: async () => undefined,
|
||||
showContextMenu: async () => null,
|
||||
openExternal: async () => true,
|
||||
onMenuAction: () => () => undefined,
|
||||
@@ -614,6 +618,7 @@ describe("wsApi", () => {
|
||||
sidebarProjectSortOrder: "manual" as const,
|
||||
sidebarThreadSortOrder: "created_at" as const,
|
||||
timestampFormat: "24-hour" as const,
|
||||
themePreference: { mode: "system" as const },
|
||||
};
|
||||
const getClientSettings = vi.fn().mockResolvedValue({
|
||||
...clientSettings,
|
||||
@@ -676,6 +681,7 @@ describe("wsApi", () => {
|
||||
sidebarProjectSortOrder: "manual" as const,
|
||||
sidebarThreadSortOrder: "created_at" as const,
|
||||
timestampFormat: "24-hour" as const,
|
||||
themePreference: { mode: "system" as const },
|
||||
};
|
||||
|
||||
await api.persistence.setClientSettings(clientSettings);
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
} from "../components/ui/toast";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { useProjectGroupingSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
derivePhysicalProjectKeyFromPath,
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
} from "../rpc/serverState";
|
||||
import { useStore } from "../store";
|
||||
import { useUiStateStore } from "../uiStateStore";
|
||||
import { syncBrowserChromeTheme } from "../hooks/useTheme";
|
||||
import { startThemeRuntime, syncBrowserChromeTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
ensureEnvironmentConnectionBootstrapped,
|
||||
getPrimaryEnvironmentConnection,
|
||||
@@ -133,6 +133,7 @@ function RootRouteView() {
|
||||
<AnchoredToastProvider>
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ServerStateBootstrap /> : null}
|
||||
<ThemeRuntimeBootstrap />
|
||||
<EnvironmentConnectionManagerBootstrap />
|
||||
<SshPasswordPromptDialog />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
@@ -259,6 +260,12 @@ function ServerStateBootstrap() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ThemeRuntimeBootstrap() {
|
||||
useEffect(() => startThemeRuntime(), []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function AuthenticatedTracingBootstrap() {
|
||||
useEffect(() => {
|
||||
void configureClientTracing();
|
||||
@@ -281,10 +288,7 @@ function EventRouter() {
|
||||
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
const projectGroupingSettings = useSettings((settings) => ({
|
||||
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
|
||||
}));
|
||||
const projectGroupingSettings = useProjectGroupingSettings();
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
|
||||
|
||||
@@ -16,12 +16,13 @@
|
||||
},
|
||||
"apps/desktop": {
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -49,7 +50,7 @@
|
||||
},
|
||||
"apps/server": {
|
||||
"name": "t3",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"bin": {
|
||||
"t3": "./dist/bin.mjs",
|
||||
},
|
||||
@@ -82,7 +83,7 @@
|
||||
},
|
||||
"apps/web": {
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -148,7 +149,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@t3tools/contracts",
|
||||
"version": "0.0.21",
|
||||
"version": "0.0.22",
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
},
|
||||
@@ -1398,7 +1399,7 @@
|
||||
|
||||
"json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
|
||||
|
||||
"jsonc-parser": ["jsonc-parser@2.3.1", "", {}, "sha512-H8jvkz1O50L3dMZCsLqiuB2tA7muqbSg1AtGEkN0leAqGjsUzDJir3Zwr02BhqdcITPg3ei3mZ+HjMocAknhhg=="],
|
||||
"jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],
|
||||
|
||||
"jsonfile": ["[email protected]", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="],
|
||||
|
||||
@@ -2168,6 +2169,8 @@
|
||||
|
||||
"@vitest/browser/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
|
||||
|
||||
"@vscode/emmet-helper/jsonc-parser": ["[email protected]", "", {}, "sha512-H8jvkz1O50L3dMZCsLqiuB2tA7muqbSg1AtGEkN0leAqGjsUzDJir3Zwr02BhqdcITPg3ei3mZ+HjMocAknhhg=="],
|
||||
|
||||
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"ast-kit/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^8.0.0-rc.2" }, "bin": "./bin/babel-parser.js" }, "sha512-29AhEtcq4x8Dp3T72qvUMZHx0OMXCj4Jy/TEReQa+KWLln524Cj1fWb3QFi0l/xSpptQBR6y9RNEXuxpFvwiUQ=="],
|
||||
@@ -2208,8 +2211,6 @@
|
||||
|
||||
"vite/rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.115.0", "@rolldown/pluginutils": "1.0.0-rc.9" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.0.0-rc.9", "@rolldown/binding-darwin-arm64": "1.0.0-rc.9", "@rolldown/binding-darwin-x64": "1.0.0-rc.9", "@rolldown/binding-freebsd-x64": "1.0.0-rc.9", "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.9", "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.9", "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.9", "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.9", "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.9", "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.9", "@rolldown/binding-linux-x64-musl": "1.0.0-rc.9", "@rolldown/binding-openharmony-arm64": "1.0.0-rc.9", "@rolldown/binding-wasm32-wasi": "1.0.0-rc.9", "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.9", "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9" }, "bin": { "rolldown": "bin/cli.mjs" } }, "sha512-9EbgWge7ZH+yqb4d2EnELAntgPTWbfL8ajiTW+SyhJEC4qhBbkCKbqFV4Ge4zmu5ziQuVbWxb/XwLZ+RIO7E8Q=="],
|
||||
|
||||
"vscode-json-languageservice/jsonc-parser": ["[email protected]", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],
|
||||
|
||||
"yaml-language-server/request-light": ["[email protected]", "", {}, "sha512-3Zjgh+8b5fhRJBQZoy+zbVKpAQGLyka0MPgW3zruTF4dFFJ8Fqcfu9YsAvi/rvdcaTeWG3MkbZv4WKxAn/84Lg=="],
|
||||
|
||||
"yaml-language-server/yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-10ULxpnOCQXxJvBgxsn9ptjq6uviG/htZKk9veJGhlqn3w/DxQ631zFF+nlQXLwmImeS5amR2dl2U8sg6U9jsQ=="],
|
||||
|
||||
@@ -11,6 +11,7 @@ export * from "./model.ts";
|
||||
export * from "./keybindings.ts";
|
||||
export * from "./server.ts";
|
||||
export * from "./settings.ts";
|
||||
export * from "./theme.ts";
|
||||
export * from "./git.ts";
|
||||
export * from "./vcs.ts";
|
||||
export * from "./sourceControl.ts";
|
||||
|
||||
@@ -68,6 +68,13 @@ import type { AdvertisedEndpoint } from "./remoteAccess.ts";
|
||||
import { EditorId } from "./editor.ts";
|
||||
import type { ExecutionEnvironmentDescriptor } from "./environment.ts";
|
||||
import type { ClientSettings, ServerSettings, ServerSettingsPatch } from "./settings.ts";
|
||||
import type {
|
||||
DesktopWindowThemeColors,
|
||||
DiscoveredColorTheme,
|
||||
EditorThemePreference,
|
||||
ResolvedColorTheme,
|
||||
ThemeId,
|
||||
} from "./theme.ts";
|
||||
import type {
|
||||
SourceControlCloneRepositoryInput,
|
||||
SourceControlCloneRepositoryResult,
|
||||
@@ -241,7 +248,11 @@ export interface DesktopBridge {
|
||||
getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;
|
||||
pickFolder: (options?: PickFolderOptions) => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
discoverColorThemes: () => Promise<readonly DiscoveredColorTheme[]>;
|
||||
loadColorTheme: (themeId: ThemeId) => Promise<ResolvedColorTheme | null>;
|
||||
getEditorThemePreferences: () => Promise<readonly EditorThemePreference[]>;
|
||||
setTheme: (theme: DesktopTheme) => Promise<void>;
|
||||
setWindowThemeColors: (input: DesktopWindowThemeColors) => Promise<void>;
|
||||
showContextMenu: <T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
|
||||
@@ -5,6 +5,7 @@ import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
|
||||
import { ModelSelection } from "./orchestration.ts";
|
||||
import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts";
|
||||
import { DEFAULT_THEME_PREFERENCE, ThemePreference } from "./theme.ts";
|
||||
|
||||
// ── Client Settings (local-only) ───────────────────────────────
|
||||
|
||||
@@ -78,6 +79,9 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
timestampFormat: TimestampFormat.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
|
||||
),
|
||||
themePreference: ThemePreference.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_THEME_PREFERENCE)),
|
||||
),
|
||||
});
|
||||
export type ClientSettings = typeof ClientSettingsSchema.Type;
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const ThemeSource = Schema.Literals(["builtin", "vscode", "cursor", "vscode-insiders"]);
|
||||
export type ThemeSource = typeof ThemeSource.Type;
|
||||
|
||||
export const EditorThemeSource = Schema.Literals(["vscode", "cursor", "vscode-insiders"]);
|
||||
export type EditorThemeSource = typeof EditorThemeSource.Type;
|
||||
|
||||
export const ThemeKind = Schema.Literals([
|
||||
"light",
|
||||
"dark",
|
||||
"high-contrast-light",
|
||||
"high-contrast-dark",
|
||||
]);
|
||||
export type ThemeKind = typeof ThemeKind.Type;
|
||||
|
||||
export type ThemeId = string;
|
||||
|
||||
export const DiscoveredColorTheme = Schema.Struct({
|
||||
id: Schema.String,
|
||||
source: EditorThemeSource,
|
||||
extensionId: Schema.String,
|
||||
extensionDisplayName: Schema.optional(Schema.String),
|
||||
label: Schema.String,
|
||||
kind: ThemeKind,
|
||||
themePath: Schema.String,
|
||||
packagePath: Schema.String,
|
||||
publisher: Schema.optional(Schema.String),
|
||||
});
|
||||
export type DiscoveredColorTheme = typeof DiscoveredColorTheme.Type;
|
||||
|
||||
export const ResolvedColorTheme = Schema.Struct({
|
||||
id: Schema.String,
|
||||
label: Schema.String,
|
||||
source: EditorThemeSource,
|
||||
kind: ThemeKind,
|
||||
colors: Schema.Record(Schema.String, Schema.String),
|
||||
tokenColors: Schema.Unknown,
|
||||
semanticHighlighting: Schema.optional(Schema.Boolean),
|
||||
semanticTokenColors: Schema.optional(Schema.Unknown),
|
||||
appVariables: Schema.Record(Schema.String, Schema.String),
|
||||
});
|
||||
export type ResolvedColorTheme = typeof ResolvedColorTheme.Type;
|
||||
|
||||
export const ThemePreference = Schema.Union([
|
||||
Schema.Struct({ mode: Schema.Literal("system") }),
|
||||
Schema.Struct({ mode: Schema.Literal("builtin"), theme: Schema.Literals(["light", "dark"]) }),
|
||||
Schema.Struct({ mode: Schema.Literal("external"), themeId: Schema.String }),
|
||||
Schema.Struct({ mode: Schema.Literal("follow-editor"), source: EditorThemeSource }),
|
||||
]);
|
||||
export type ThemePreference = typeof ThemePreference.Type;
|
||||
|
||||
export const DEFAULT_THEME_PREFERENCE = { mode: "system" } as const satisfies ThemePreference;
|
||||
|
||||
export const EditorThemePreference = Schema.Struct({
|
||||
source: EditorThemeSource,
|
||||
colorTheme: Schema.NullOr(Schema.String),
|
||||
preferredLightColorTheme: Schema.NullOr(Schema.String),
|
||||
preferredDarkColorTheme: Schema.NullOr(Schema.String),
|
||||
autoDetectColorScheme: Schema.Boolean,
|
||||
workbenchColorCustomizations: Schema.Record(Schema.String, Schema.Unknown),
|
||||
editorTokenColorCustomizations: Schema.Unknown,
|
||||
});
|
||||
export type EditorThemePreference = typeof EditorThemePreference.Type;
|
||||
|
||||
export const DesktopWindowThemeColors = Schema.Struct({
|
||||
backgroundColor: Schema.String,
|
||||
titleBarColor: Schema.optional(Schema.String),
|
||||
titleBarSymbolColor: Schema.optional(Schema.String),
|
||||
});
|
||||
export type DesktopWindowThemeColors = typeof DesktopWindowThemeColors.Type;
|
||||
@@ -79,6 +79,10 @@
|
||||
"./keybindings": {
|
||||
"types": "./src/keybindings.ts",
|
||||
"import": "./src/keybindings.ts"
|
||||
},
|
||||
"./themeMapping": {
|
||||
"types": "./src/themeMapping.ts",
|
||||
"import": "./src/themeMapping.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mapVscodeColorsToAppVariables, normalizeThemeColors } from "./themeMapping.ts";
|
||||
|
||||
describe("themeMapping", () => {
|
||||
it("normalizes supported VS Code hex colors only", () => {
|
||||
expect(
|
||||
normalizeThemeColors({
|
||||
"editor.background": "#010203",
|
||||
"button.background": "#abc",
|
||||
ignored: "rgb(1, 2, 3)",
|
||||
missing: null,
|
||||
}),
|
||||
).toEqual({
|
||||
"editor.background": "#010203",
|
||||
"button.background": "#abc",
|
||||
});
|
||||
});
|
||||
|
||||
it("maps VS Code workbench colors to app variables", () => {
|
||||
const variables = mapVscodeColorsToAppVariables({
|
||||
kind: "dark",
|
||||
colors: {
|
||||
"editor.background": "#0d1117",
|
||||
"editor.foreground": "#e6edf3",
|
||||
"button.background": "#238636",
|
||||
"button.foreground": "#ffffff",
|
||||
"sideBar.background": "#010409",
|
||||
"terminal.ansiGreen": "#3fb950",
|
||||
},
|
||||
});
|
||||
|
||||
expect(variables["--background"]).toBe("#0d1117");
|
||||
expect(variables["--foreground"]).toBe("#e6edf3");
|
||||
expect(variables["--primary"]).toBe("#238636");
|
||||
expect(variables["--sidebar"]).toBe("#010409");
|
||||
expect(variables["--success"]).toBe("#3fb950");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import type { ThemeKind } from "@t3tools/contracts";
|
||||
|
||||
export const EXTERNAL_APP_THEME_VARIABLES = [
|
||||
"--background",
|
||||
"--app-chrome-background",
|
||||
"--foreground",
|
||||
"--card",
|
||||
"--card-foreground",
|
||||
"--popover",
|
||||
"--popover-foreground",
|
||||
"--primary",
|
||||
"--primary-foreground",
|
||||
"--secondary",
|
||||
"--secondary-foreground",
|
||||
"--muted",
|
||||
"--muted-foreground",
|
||||
"--accent",
|
||||
"--accent-foreground",
|
||||
"--destructive",
|
||||
"--destructive-foreground",
|
||||
"--border",
|
||||
"--input",
|
||||
"--ring",
|
||||
"--info",
|
||||
"--info-foreground",
|
||||
"--success",
|
||||
"--success-foreground",
|
||||
"--warning",
|
||||
"--warning-foreground",
|
||||
"--sidebar",
|
||||
"--sidebar-foreground",
|
||||
"--sidebar-accent",
|
||||
"--sidebar-accent-foreground",
|
||||
"--sidebar-border",
|
||||
"--terminal-background",
|
||||
"--terminal-foreground",
|
||||
"--terminal-cursor",
|
||||
"--terminal-selection-background",
|
||||
"--diff-inserted",
|
||||
"--diff-removed",
|
||||
"--chat-request-background",
|
||||
"--chat-request-border",
|
||||
] as const;
|
||||
|
||||
const HEX_COLOR_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
||||
|
||||
const LIGHT_FALLBACKS = {
|
||||
background: "#ffffff",
|
||||
foreground: "#262626",
|
||||
primary: "#315cec",
|
||||
border: "#00000014",
|
||||
destructive: "#ef4444",
|
||||
info: "#3b82f6",
|
||||
success: "#10b981",
|
||||
warning: "#f59e0b",
|
||||
};
|
||||
|
||||
const DARK_FALLBACKS = {
|
||||
background: "#111111",
|
||||
foreground: "#f5f5f5",
|
||||
primary: "#6384ff",
|
||||
border: "#ffffff14",
|
||||
destructive: "#f87171",
|
||||
info: "#60a5fa",
|
||||
success: "#34d399",
|
||||
warning: "#fbbf24",
|
||||
};
|
||||
|
||||
export function isDarkThemeKind(kind: ThemeKind) {
|
||||
return kind === "dark" || kind === "high-contrast-dark";
|
||||
}
|
||||
|
||||
export function normalizeCssColor(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (!HEX_COLOR_PATTERN.test(trimmed)) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function normalizeThemeColors(value: unknown): Record<string, string> {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
|
||||
|
||||
const colors: Record<string, string> = {};
|
||||
for (const [key, rawColor] of Object.entries(value)) {
|
||||
const color = normalizeCssColor(rawColor);
|
||||
if (color) colors[key] = color;
|
||||
}
|
||||
return colors;
|
||||
}
|
||||
|
||||
function firstColor(colors: Record<string, string>, keys: readonly string[]) {
|
||||
for (const key of keys) {
|
||||
const color = colors[key];
|
||||
if (color) return color;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function expandHexChannel(value: string) {
|
||||
return value.length === 1 ? `${value}${value}` : value;
|
||||
}
|
||||
|
||||
function readableForeground(background: string) {
|
||||
const normalized = normalizeCssColor(background);
|
||||
if (!normalized) return "#ffffff";
|
||||
const hex = normalized.slice(1);
|
||||
const rgb =
|
||||
hex.length === 3 || hex.length === 4
|
||||
? [hex.slice(0, 1), hex.slice(1, 2), hex.slice(2, 3)].map((channel) =>
|
||||
parseInt(expandHexChannel(channel), 16),
|
||||
)
|
||||
: [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4, 6)].map((channel) => parseInt(channel, 16));
|
||||
const [red = 0, green = 0, blue = 0] = rgb;
|
||||
const luminance = (0.2126 * red + 0.7152 * green + 0.0722 * blue) / 255;
|
||||
return luminance > 0.55 ? "#111111" : "#ffffff";
|
||||
}
|
||||
|
||||
function mix(base: string, foreground: string, percentage: number) {
|
||||
return `color-mix(in srgb, ${base} ${percentage}%, ${foreground})`;
|
||||
}
|
||||
|
||||
export function mapVscodeColorsToAppVariables(input: {
|
||||
readonly kind: ThemeKind;
|
||||
readonly colors: Record<string, string>;
|
||||
}): Record<string, string> {
|
||||
const fallback = isDarkThemeKind(input.kind) ? DARK_FALLBACKS : LIGHT_FALLBACKS;
|
||||
const colors = input.colors;
|
||||
const background =
|
||||
firstColor(colors, ["editor.background", "sideBar.background"]) ?? fallback.background;
|
||||
const foreground = firstColor(colors, ["foreground", "editor.foreground"]) ?? fallback.foreground;
|
||||
const primary =
|
||||
firstColor(colors, ["button.background", "activityBarBadge.background", "focusBorder"]) ??
|
||||
fallback.primary;
|
||||
const border =
|
||||
firstColor(colors, ["widget.border", "sideBar.border", "editorGroup.border", "panel.border"]) ??
|
||||
fallback.border;
|
||||
const accent =
|
||||
firstColor(colors, [
|
||||
"list.activeSelectionBackground",
|
||||
"list.hoverBackground",
|
||||
"toolbar.hoverBackground",
|
||||
]) ?? mix(background, foreground, 92);
|
||||
const destructive =
|
||||
firstColor(colors, [
|
||||
"errorForeground",
|
||||
"editorError.foreground",
|
||||
"notificationsErrorIcon.foreground",
|
||||
]) ?? fallback.destructive;
|
||||
|
||||
return {
|
||||
"--background": background,
|
||||
"--app-chrome-background":
|
||||
firstColor(colors, ["titleBar.activeBackground", "sideBar.background"]) ?? background,
|
||||
"--foreground": foreground,
|
||||
"--card":
|
||||
firstColor(colors, ["editorGroupHeader.tabsBackground", "sideBarSectionHeader.background"]) ??
|
||||
mix(background, foreground, 94),
|
||||
"--card-foreground": foreground,
|
||||
"--popover":
|
||||
firstColor(colors, [
|
||||
"quickInput.background",
|
||||
"editorWidget.background",
|
||||
"dropdown.background",
|
||||
]) ?? mix(background, foreground, 96),
|
||||
"--popover-foreground":
|
||||
firstColor(colors, [
|
||||
"quickInput.foreground",
|
||||
"editorWidget.foreground",
|
||||
"dropdown.foreground",
|
||||
"foreground",
|
||||
]) ?? foreground,
|
||||
"--primary": primary,
|
||||
"--primary-foreground":
|
||||
firstColor(colors, ["button.foreground"]) ?? readableForeground(primary),
|
||||
"--secondary":
|
||||
firstColor(colors, ["button.secondaryBackground", "badge.background"]) ??
|
||||
mix(background, foreground, 90),
|
||||
"--secondary-foreground":
|
||||
firstColor(colors, ["button.secondaryForeground", "foreground"]) ?? foreground,
|
||||
"--muted":
|
||||
firstColor(colors, ["editor.lineHighlightBackground", "list.hoverBackground"]) ??
|
||||
mix(background, foreground, 92),
|
||||
"--muted-foreground":
|
||||
firstColor(colors, ["descriptionForeground", "disabledForeground"]) ??
|
||||
mix(foreground, background, 66),
|
||||
"--accent": accent,
|
||||
"--accent-foreground":
|
||||
firstColor(colors, ["list.activeSelectionForeground", "list.hoverForeground"]) ?? foreground,
|
||||
"--destructive": destructive,
|
||||
"--destructive-foreground":
|
||||
firstColor(colors, ["errorForeground", "editorError.foreground"]) ??
|
||||
readableForeground(destructive),
|
||||
"--border": border,
|
||||
"--input":
|
||||
firstColor(colors, [
|
||||
"input.background",
|
||||
"dropdown.background",
|
||||
"settings.textInputBackground",
|
||||
]) ?? mix(background, foreground, 90),
|
||||
"--ring": firstColor(colors, ["focusBorder", "inputOption.activeBorder"]) ?? primary,
|
||||
"--info": firstColor(colors, ["textLink.foreground", "terminal.ansiBlue"]) ?? fallback.info,
|
||||
"--info-foreground":
|
||||
firstColor(colors, ["textLink.foreground", "terminal.ansiBrightBlue"]) ?? fallback.info,
|
||||
"--success":
|
||||
firstColor(colors, ["gitDecoration.addedResourceForeground", "terminal.ansiGreen"]) ??
|
||||
fallback.success,
|
||||
"--success-foreground":
|
||||
firstColor(colors, ["gitDecoration.addedResourceForeground", "terminal.ansiBrightGreen"]) ??
|
||||
fallback.success,
|
||||
"--warning":
|
||||
firstColor(colors, ["notificationsWarningIcon.foreground", "terminal.ansiYellow"]) ??
|
||||
fallback.warning,
|
||||
"--warning-foreground":
|
||||
firstColor(colors, ["notificationsWarningIcon.foreground", "terminal.ansiBrightYellow"]) ??
|
||||
fallback.warning,
|
||||
"--sidebar": firstColor(colors, ["sideBar.background", "activityBar.background"]) ?? background,
|
||||
"--sidebar-foreground": firstColor(colors, ["sideBar.foreground", "foreground"]) ?? foreground,
|
||||
"--sidebar-accent":
|
||||
firstColor(colors, ["list.activeSelectionBackground", "activityBar.activeBackground"]) ??
|
||||
accent,
|
||||
"--sidebar-accent-foreground":
|
||||
firstColor(colors, ["list.activeSelectionForeground", "sideBar.foreground"]) ?? foreground,
|
||||
"--sidebar-border": firstColor(colors, ["sideBar.border", "activityBar.border"]) ?? border,
|
||||
"--terminal-background":
|
||||
firstColor(colors, ["terminal.background", "panel.background"]) ?? background,
|
||||
"--terminal-foreground":
|
||||
firstColor(colors, ["terminal.foreground", "foreground"]) ?? foreground,
|
||||
"--terminal-cursor":
|
||||
firstColor(colors, ["terminalCursor.foreground", "editorCursor.foreground"]) ?? primary,
|
||||
"--terminal-selection-background":
|
||||
firstColor(colors, ["terminal.selectionBackground", "editor.selectionBackground"]) ??
|
||||
`color-mix(in srgb, ${primary} 24%, transparent)`,
|
||||
"--diff-inserted":
|
||||
firstColor(colors, [
|
||||
"diffEditor.insertedTextBackground",
|
||||
"gitDecoration.addedResourceForeground",
|
||||
]) ?? fallback.success,
|
||||
"--diff-removed":
|
||||
firstColor(colors, [
|
||||
"diffEditor.removedTextBackground",
|
||||
"gitDecoration.deletedResourceForeground",
|
||||
]) ?? fallback.destructive,
|
||||
"--chat-request-background":
|
||||
firstColor(colors, ["chat.requestBackground"]) ?? mix(background, foreground, 94),
|
||||
"--chat-request-border": firstColor(colors, ["chat.requestBorder"]) ?? border,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user