diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index 035a78a82..cea01c06a 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -214,6 +214,54 @@ pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState windows.take_launch(window.label()) } +#[derive(Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SettingsWindowInit { + pub launch: Option, + pub remote: Option, + pub project: Option, + pub global_settings: ide_core::settings::Settings, + pub updates: bool, +} + +/// Local bootstrap snapshot for a `settings-` window, avoiding a sequential +/// startup IPC waterfall and any blocking SSH `project_current` round-trip before first paint. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub fn window_take_settings_init( + app: AppHandle, + window: WebviewWindow, + windows: State<'_, WindowsState>, + state: State<'_, AppState>, +) -> SettingsWindowInit { + let owner = AppState::owner_window(window.label()); + let launch = windows.take_launch(window.label()); + let (remote, project) = if let Some(c) = state.remote_dev.get(owner) { + let session = crate::remote_dev::RemoteSession { + target: c.target.clone(), + root: c.root.clone(), + host: c.host.clone(), + os: c.os.clone(), + commands: c.commands.clone(), + }; + // Leave `project` empty on remote sessions: the Settings page tree renders immediately + // from local client settings, and `projectCurrent()` fills in project-scoped settings + // right after first paint without keeping a shadow cache in sync. + (Some(session), None) + } else { + let project = state.project(owner).ok().filter(|p| !p.light).map(|p| ide_host::ops::project::info(&p)); + (None, project) + }; + SettingsWindowInit { + launch, + remote, + project, + global_settings: state.host.with_proxy_password(state.global_settings.effective()), + updates: updates_configured(&app), + } +} + /// Release the opening window's reservation after navigation or cancellation. #[desktop_command(trust = always)] #[tauri::command] @@ -889,6 +937,7 @@ ide_command::desktop_domain!( window_set_smooth_scrolling, window_set_titlebar_height, window_take_launch, + window_take_settings_init, window_toggle_fullscreen, window_toggle_zoom, ); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 6f113640d..7e7749243 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -730,6 +730,7 @@ window_set_smooth_scrolling always desktop bin window_set_titlebar_height always desktop bindings sync window_start_drag always desktop bindings sync window_take_launch always desktop bindings sync +window_take_settings_init always desktop bindings sync window_toggle_fullscreen always desktop bindings sync window_toggle_zoom always desktop bindings sync workspace_attach always desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index b4671dec4..d5cfbe26c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1963,6 +1963,11 @@ export const commands = { /** Deployment windows: the server and local selection to compare. */ deployment: DeploymentLaunch | null, } | null>("window_take_launch"), + /** + * Local bootstrap snapshot for a `settings-` window, avoiding a sequential + * startup IPC waterfall and any blocking SSH `project_current` round-trip before first paint. + */ + windowTakeSettingsInit: () => __TAURI_INVOKE("window_take_settings_init"), windowToggleFullscreen: () => typedError(__TAURI_INVOKE("window_toggle_fullscreen")), /** Fills the work area without the platform zoom animation. Returns whether it is filled now. */ windowToggleZoom: () => typedError(__TAURI_INVOKE("window_toggle_zoom")), @@ -10702,6 +10707,24 @@ export type SettingsImport_Serialize = { export type SettingsScope = "global" | "project"; +export type SettingsWindowInit = SettingsWindowInit_Serialize | SettingsWindowInit_Deserialize; + +export type SettingsWindowInit_Deserialize = { + launch: Launch_Deserialize | null, + remote: RemoteSession | null, + project: ProjectInfo_Deserialize | null, + globalSettings: Settings_Deserialize, + updates: boolean, +}; + +export type SettingsWindowInit_Serialize = { + launch: Launch_Serialize | null, + remote: RemoteSession | null, + project: ProjectInfo_Serialize | null, + globalSettings: Settings_Serialize, + updates: boolean, +}; + export type Settings_Deserialize = { general?: GeneralSettings, appearance?: AppearanceSettings_Deserialize, diff --git a/src/features/settings/__tests__/colorScheme.test.tsx b/src/features/settings/__tests__/colorScheme.test.tsx index c82272e5a..77101cc11 100644 --- a/src/features/settings/__tests__/colorScheme.test.tsx +++ b/src/features/settings/__tests__/colorScheme.test.tsx @@ -1,6 +1,6 @@ import { readFileSync } from "node:fs"; import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { executeAction } from "@/platform/actions"; import { CLEAR_COLOR, _setSchemeSource } from "@/platform/colorScheme"; import { setLocale } from "@/platform/i18n"; @@ -9,6 +9,7 @@ import { DEFAULT_SETTINGS } from "../model/schema"; import { openSettings, stage, stagedValue, useSettingsDialog } from "../model/staging"; import { PageContext } from "../components/context"; import { COLOR_SCHEME_PAGES } from "../pages/editor/colorScheme"; +import { preloadBuiltinPage } from "../pages/lazyPage"; const mocks = vi.hoisted(() => ({ open: vi.fn(), @@ -40,6 +41,7 @@ const schemePage = (id: string) => { ); }; +beforeAll(() => preloadBuiltinPage("editor.colorScheme")); beforeEach(() => { vi.resetAllMocks(); mocks.open.mockResolvedValue("/schemes/forest.icls"); diff --git a/src/features/settings/__tests__/deploymentFtpPassword.test.tsx b/src/features/settings/__tests__/deploymentFtpPassword.test.tsx index 6b99f623e..36088e239 100644 --- a/src/features/settings/__tests__/deploymentFtpPassword.test.tsx +++ b/src/features/settings/__tests__/deploymentFtpPassword.test.tsx @@ -1,11 +1,12 @@ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings"; import { useProject } from "@/platform/project"; import { PageContext } from "../components/context"; import { validateSettings } from "../model/schema"; import { applySettings, openSettings, useSettingsDialog } from "../model/staging"; import { DEPLOYMENT_PAGES } from "../pages/deployment"; +import { preloadBuiltinPage } from "../pages/lazyPage"; const mocks = vi.hoisted(() => ({ store: vi.fn(), saved: vi.fn(), test: vi.fn() })); vi.mock("@/platform/ipc", async (original) => { @@ -29,6 +30,7 @@ const savedDialog = useSettingsDialog.getState(); const savedProject = useProject.getState(); const PAGE = DEPLOYMENT_PAGES[0]!.id; +beforeAll(() => preloadBuiltinPage(PAGE)); beforeEach(() => { vi.resetAllMocks(); mocks.store.mockResolvedValue(undefined); diff --git a/src/features/settings/__tests__/deploymentListMenu.test.tsx b/src/features/settings/__tests__/deploymentListMenu.test.tsx index 24e59dfb6..c116a6a03 100644 --- a/src/features/settings/__tests__/deploymentListMenu.test.tsx +++ b/src/features/settings/__tests__/deploymentListMenu.test.tsx @@ -1,15 +1,18 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; import type { ComponentType } from "react"; -import { afterEach, beforeEach, expect, it } from "vitest"; +import { afterEach, beforeAll, beforeEach, expect, it } from "vitest"; import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings"; import { useContextMenuStore } from "@/ui"; import { PageContext } from "../components/context"; import { DEFAULT_SETTINGS } from "../model/schema"; import { stagedValue, useSettingsDialog } from "../model/staging"; import { DEPLOYMENT_PAGES } from "../pages/deployment"; +import { preloadBuiltinPage } from "../pages/lazyPage"; const server = (id: string, name: string) => ({ ...DEFAULT_DEPLOYMENT_SERVER, id, name }); +beforeAll(() => preloadBuiltinPage("build.deployment")); + beforeEach(() => { const base = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & { deployment: Record }; base.deployment = { ...base.deployment, servers: [server("a", "Alpha"), server("b", "Beta")], defaultServer: "a" }; diff --git a/src/features/settings/__tests__/settingsWindowOpen.test.ts b/src/features/settings/__tests__/settingsWindowOpen.test.ts index 64b5ced29..9f2c1ce13 100644 --- a/src/features/settings/__tests__/settingsWindowOpen.test.ts +++ b/src/features/settings/__tests__/settingsWindowOpen.test.ts @@ -1,6 +1,17 @@ import { describe, expect, it, vi } from "vitest"; const logFrontend = vi.hoisted(() => vi.fn(() => Promise.resolve())); +const defaultInit = () => ({ + launch: null, + remote: null, + project: null, + globalSettings: {}, + updates: false, +}); +const windowTakeSettingsInit = vi.hoisted(() => vi.fn<() => Promise>(() => Promise.resolve(defaultInit()))); +const windowTakeLaunch = vi.hoisted(() => vi.fn<() => Promise>(() => Promise.resolve(null))); +const projectCurrent = vi.hoisted(() => vi.fn<() => Promise>(() => Promise.resolve(null))); +const settingsGetGlobal = vi.hoisted(() => vi.fn(() => Promise.resolve({}))); vi.mock("@tauri-apps/api/webviewWindow", () => ({ getCurrentWebviewWindow: () => ({ label: "settings-main", @@ -11,32 +22,42 @@ vi.mock("@tauri-apps/api/webviewWindow", () => ({ })); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); - const ok = (data: unknown) => Promise.resolve({ status: "ok", data }); return { ...real, isTauri: () => true, commands: { ...real.commands, logFrontend, - remoteCurrent: () => ok(null), - projectCurrent: () => ok(null), - settingsGetGlobal: () => ok({}), - windowTakeLaunch: () => Promise.resolve(null), + remoteCurrent: () => Promise.resolve(null), + projectCurrent, + settingsGet: () => Promise.resolve({}), + settingsGetGlobal, + windowTakeLaunch, + windowTakeSettingsInit, }, }; }); +const loadBuiltinPages = vi.hoisted(() => + vi.fn<() => Promise<() => void>>(() => Promise.reject(new Error("page failed"))), +); +const preloadBuiltinRegistry = vi.hoisted(() => vi.fn(() => Promise.resolve())); vi.mock("../dialog/LazySettingsDialog", () => ({ LazySettingsDialog: () => null, - loadBuiltinPages: () => Promise.reject(new Error("page failed")), + LazyProjectStructureDialog: () => null, + loadBuiltinPages, + preloadBuiltinRegistry, unloadBuiltinPages: () => {}, })); const { activateSettingsWindow } = await import(".."); -const { useSettingsDialog } = await import("../model/staging"); +const { disableRemote } = await import("@/platform/remote"); +const { useProject } = await import("@/platform/project"); +const { stage, useSettingsDialog } = await import("../model/staging"); describe("the native Settings window", () => { it("opens even when a page fails to register, and logs why", async () => { vi.spyOn(console, "error").mockImplementation(() => {}); + windowTakeSettingsInit.mockResolvedValueOnce(defaultInit()); const dispose = activateSettingsWindow("main"); expect(useSettingsDialog.getState().open).toBe(true); expect(useSettingsDialog.getState().pagesLoading).toBe(true); @@ -48,4 +69,74 @@ describe("the native Settings window", () => { ); dispose(); }); + + it("hydrates from windowTakeSettingsInit without blocking on SSH and rebases base while keeping staged edits", async () => { + loadBuiltinPages.mockClear().mockResolvedValue(() => {}); + settingsGetGlobal.mockClear(); + windowTakeLaunch.mockClear().mockResolvedValueOnce(null); + let resolveRemoteRefresh!: (v: unknown) => void; + projectCurrent.mockReturnValueOnce(new Promise((r) => (resolveRemoteRefresh = r))); + windowTakeSettingsInit.mockResolvedValueOnce({ + launch: { settingsPage: "keymap", newProjects: false }, + remote: { + target: { type: "ssh", config: "devbox" }, + root: "/home/dev/repo", + host: "devbox", + os: "linux", + commands: ["project_current"], + }, + project: null, + globalSettings: { appearance: { theme: "dark" }, editor: { tabSize: 4 } }, + updates: true, + }); + + const dispose = activateSettingsWindow("main"); + // Unblocks pagesLoading immediately from local client settings while SSH projectCurrent is still pending. + await vi.waitFor(() => expect(useSettingsDialog.getState().pagesLoading).toBe(false)); + await vi.waitFor(() => expect(windowTakeLaunch).toHaveBeenCalledTimes(1)); + expect(loadBuiltinPages).toHaveBeenCalledTimes(1); + expect(loadBuiltinPages).toHaveBeenCalledWith({ pageId: "keymap", updates: true }); + expect(useSettingsDialog.getState().pageId).toBe("keymap"); + expect(useSettingsDialog.getState().base.appearance.theme).toBe("dark"); + expect(useSettingsDialog.getState().globalBase.editor.tabSize).toBe(4); + expect(settingsGetGlobal).not.toHaveBeenCalled(); + + // Even if the user stages an edit before SSH returns, remote `base` updates while `staged` stays intact. + stage("editor.codeStyle.other", "project", "editor.tabSize", 8); + resolveRemoteRefresh({ + root: "/home/dev/repo", + name: "repo", + displayName: "repo", + trusted: true, + isGit: true, + settings: { editor: { tabSize: 6 }, appearance: { theme: "dark" } }, + }); + await vi.waitFor(() => expect(useSettingsDialog.getState().base.editor.tabSize).toBe(6)); + expect(useProject.getState().project?.root).toBe("/home/dev/repo"); + expect(useSettingsDialog.getState().staged["project|editor.tabSize"]?.value).toBe(8); + + disableRemote(); + useProject.setState({ project: null, settings: null }); + dispose(); + }); + + it("picks up a launch queued between windowTakeSettingsInit and listen()", async () => { + loadBuiltinPages.mockResolvedValue(() => {}); + windowTakeLaunch.mockResolvedValueOnce({ settingsPage: "appearance", newProjects: true }); + windowTakeSettingsInit.mockResolvedValueOnce({ + launch: { settingsPage: "keymap", newProjects: false }, + remote: null, + project: null, + globalSettings: {}, + updates: false, + }); + + const dispose = activateSettingsWindow("main"); + await vi.waitFor(() => expect(useSettingsDialog.getState().pagesLoading).toBe(false)); + await vi.waitFor(() => expect(useSettingsDialog.getState().newProjects).toBe(true)); + expect(useSettingsDialog.getState().pageId).toBe("appearance"); + + useProject.setState({ project: null, settings: null }); + dispose(); + }); }); diff --git a/src/features/settings/__tests__/ssh.test.tsx b/src/features/settings/__tests__/ssh.test.tsx index 1f24fa0b8..030790a11 100644 --- a/src/features/settings/__tests__/ssh.test.tsx +++ b/src/features/settings/__tests__/ssh.test.tsx @@ -1,12 +1,13 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { DEFAULT_SSH_CONFIG, type SshAuthValid } from "@/platform/remoteSettings"; import { useProject } from "@/platform/project"; import { PageContext } from "../components/context"; import { validateSettings } from "../model/schema"; import { applySettings, closeSettings, openSettings, resetPage, useSettingsDialog } from "../model/staging"; import { SettingsFooter } from "../dialog/SettingsDialog"; +import { preloadBuiltinPage } from "../pages/lazyPage"; import { SSH_PAGES } from "../pages/ssh"; const mocks = vi.hoisted(() => ({ store: vi.fn(), test: vi.fn(), needsSecret: vi.fn(), trust: vi.fn() })); @@ -32,6 +33,7 @@ const savedDialog = useSettingsDialog.getState(); const savedProject = useProject.getState(); let typed: string; +beforeAll(() => preloadBuiltinPage("tools.sshConfigurations")); beforeEach(() => { vi.resetAllMocks(); typed = crypto.randomUUID(); diff --git a/src/features/settings/actions.ts b/src/features/settings/actions.ts index 7e0a4b5d1..7b16a02a4 100644 --- a/src/features/settings/actions.ts +++ b/src/features/settings/actions.ts @@ -4,7 +4,7 @@ import { nativeToAsciiAction } from "./nativeToAscii"; /** Java's page first: JDK, Maven and the language server are what new projects most often need. */ export const NEW_PROJECTS_PAGE = "languages.java"; -export function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] { +export function settingsActions(open: (page?: string, newProjects?: boolean) => void | Promise): Action[] { return [ nativeToAsciiAction(), { diff --git a/src/features/settings/dialog/LazySettingsDialog.tsx b/src/features/settings/dialog/LazySettingsDialog.tsx index aab3228c4..44e03ba5c 100644 --- a/src/features/settings/dialog/LazySettingsDialog.tsx +++ b/src/features/settings/dialog/LazySettingsDialog.tsx @@ -4,13 +4,24 @@ * window rarely needs them. */ import { lazyComponent } from "@/ui"; -import { useSettingsDialog } from "../model/staging"; +import { DEFAULT_PAGE, splitPageTarget, useSettingsDialog } from "../model/staging"; +let registry: Promise | null = null; let pages: Promise<() => void> | null = null; -/** Registers the built-in pages once; resolves with their disposer. */ -export function loadBuiltinPages(): Promise<() => void> { - return (pages ??= import("../pages/registry").then((m) => m.registerBuiltinPages())); +/** Pre-fetches the built-in page registry chunk without registering pages yet. */ +export function preloadBuiltinRegistry(): Promise { + return (registry ??= import("../pages/registry")); +} + +/** Registers the built-in pages once and preloads `pageId`'s body; resolves with their disposer. */ +export async function loadBuiltinPages(opts: { pageId?: string; updates?: boolean } = {}): Promise<() => void> { + const mod = await (registry ??= import("../pages/registry")); + const dispose = await (pages ??= Promise.resolve(mod.registerBuiltinPages({ updates: opts.updates }))); + const target = opts.pageId ? splitPageTarget(opts.pageId).pageId : DEFAULT_PAGE; + const preload = mod.preloadBuiltinPage(target); + if (preload) await preload; + return dispose; } /** Drops the pages registered by `loadBuiltinPages` (feature deactivation). */ diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts index 210b98db5..9d307e759 100644 --- a/src/features/settings/index.ts +++ b/src/features/settings/index.ts @@ -18,7 +18,7 @@ import { lazyWhen } from "@/ui"; import { useProject } from "@/platform/project"; import { provideSettingsSearchIndex, registerOverlay } from "@/workbench/contributions"; import { windowBackgroundHex } from "@/workbench/theme"; -import { settingsActions } from "./actions"; +import { NEW_PROJECTS_PAGE, settingsActions } from "./actions"; import { LazyProjectStructureDialog, LazySettingsDialog, @@ -57,7 +57,8 @@ async function showSettings(page?: string, newProjects = false) { console.warn("settings window unavailable, using the dialog", e); } } - await loadBuiltinPages(); + const targetPage = page ?? (newProjects ? NEW_PROJECTS_PAGE : useSettingsDialog.getState().pageId); + await loadBuiltinPages({ pageId: targetPage }); // Like a launch into the open window: go to the page, keep the edits not applied yet. if (useSettingsDialog.getState().open) relaunchSettings({ page, newProjects }); else openSettings(page, { newProjects }); @@ -87,7 +88,7 @@ export function activate(): () => void { ...appearanceToggleActions(), presentationAssistantAction(), ...navigationBarActions(), - ...settingsActions((page, newProjects) => void showSettings(page, newProjects)), + ...settingsActions((page, newProjects) => showSettings(page, newProjects)), { id: "file.projectStructure", title: "Project Structure…", diff --git a/src/features/settings/keymap/KeymapPage.tsx b/src/features/settings/keymap/KeymapPage.tsx index cadd59f99..18ffce972 100644 --- a/src/features/settings/keymap/KeymapPage.tsx +++ b/src/features/settings/keymap/KeymapPage.tsx @@ -8,8 +8,8 @@ */ import { useMemo, useRef, useState, type MouseEvent } from "react"; import clsx from "clsx"; -import { useActions, allActions, type Action } from "@/platform/actions"; -import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS, useKeymap } from "@/platform/keymap"; +import { allActions, useActions, type Action } from "@/platform/actions"; +import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS } from "@/platform/keymap"; import { call, commands } from "@/platform/ipc"; import { notifications } from "@/workbench/contributions"; import { ask, confirm, showError } from "@/workbench/messages"; @@ -40,6 +40,7 @@ import { isModified, isKeymapAction, keymapName, + keymapSearchLabels, removeBinding, removeConflicts, renameKeymap, @@ -65,12 +66,7 @@ type KNode = type GroupNode = Extract; -export function keymapSearchLabels(): string[] { - const draft = useKeymap.getState(); - return allActions() - .filter((a) => isKeymapAction(a, draft)) - .map((a) => a.title); -} +export { keymapSearchLabels }; const groupKey = (path: readonly string[]) => `grp:${path.join("/")}`; diff --git a/src/features/settings/keymap/model.ts b/src/features/settings/keymap/model.ts index b777bcd59..bc3d4d27b 100644 --- a/src/features/settings/keymap/model.ts +++ b/src/features/settings/keymap/model.ts @@ -3,7 +3,7 @@ * (plugins' default shortcuts count as the preset's), add / remove / reset, * conflict detection with `when` overlap, and shortcut search. */ -import type { Action } from "@/platform/actions"; +import { allActions, type Action } from "@/platform/actions"; import { evaluateWhen, type ContextKeys } from "@/platform/context"; import { customKeymapId, @@ -12,6 +12,7 @@ import { presetBindings, PRESET_TITLES, PRESETS, + useKeymap, withBindings, type Keymap, type KeymapDraft, @@ -19,6 +20,13 @@ import { export { presetBindings, withBindings, type KeymapDraft }; +export function keymapSearchLabels(): string[] { + const draft = useKeymap.getState(); + return allActions() + .filter((a) => isKeymapAction(a, draft)) + .map((a) => a.title); +} + export function resolveBindings(draft: KeymapDraft, id: string): string[] { return draft.overrides[id]?.map(normalizeBinding) ?? presetBindings(draft.preset, id); } diff --git a/src/features/settings/model/staging.ts b/src/features/settings/model/staging.ts index 33e7f95f1..3ff041535 100644 --- a/src/features/settings/model/staging.ts +++ b/src/features/settings/model/staging.ts @@ -109,7 +109,7 @@ export function splitPageTarget(target: string): { pageId: string; focus: string return i < 0 ? { pageId: target, focus: null } : { pageId: target.slice(0, i), focus: target.slice(i + 1) || null }; } -export function openSettings(pageId?: string, opts: { newProjects?: boolean } = {}) { +export function openSettings(pageId?: string, opts: { newProjects?: boolean; globalBase?: ValidSettings } = {}) { const s = useSettingsDialog.getState(); const base = validateSettings(useProject.getState().settings); const target = pageId ? splitPageTarget(pageId) : { pageId: s.pageId, focus: null }; @@ -120,7 +120,7 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean } = focus: target.focus, query: "", base, - globalBase: base, + globalBase: opts.globalBase ?? base, newProjects: opts.newProjects ?? false, staged: {}, stagedSecrets: {}, @@ -129,7 +129,7 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean } = saving: false, error: null, }); - void loadGlobalBase(); + if (!opts.globalBase) void loadGlobalBase(); } export function openProjectStructure(section?: string) { @@ -182,10 +182,10 @@ async function loadGlobalBase() { } } -export function rebaseSettings() { +export function rebaseSettings(globalBase?: ValidSettings) { const base = validateSettings(useProject.getState().settings); - useSettingsDialog.setState((s) => (s.open || s.projectStructureOpen ? { base, globalBase: base } : {})); - void loadGlobalBase(); + useSettingsDialog.setState((s) => (s.open || s.projectStructureOpen ? { base, globalBase: globalBase ?? base } : {})); + if (!globalBase) void loadGlobalBase(); } /** IDEA's File › New Projects Setup › Settings for New Projects. */ diff --git a/src/features/settings/pages/deployment.tsx b/src/features/settings/pages/DeploymentBody.tsx similarity index 93% rename from src/features/settings/pages/deployment.tsx rename to src/features/settings/pages/DeploymentBody.tsx index 3b58deaeb..9cc190c3d 100644 --- a/src/features/settings/pages/deployment.tsx +++ b/src/features/settings/pages/DeploymentBody.tsx @@ -50,8 +50,6 @@ import { updateMapping, } from "./deploymentModel"; import { choosePath } from "@/platform/choosePath"; -import { BUILD_GROUP } from "./execution"; -import type { PageSpec } from "./spec"; import { parseSshPort, sshTestRemedy } from "./sshConnection"; import { PageLink } from "./workflowControls"; import workflow from "./Workflow.module.css"; @@ -733,7 +731,7 @@ function GroupPanel({ type Selection = { kind: "server" | "group"; id: string } | null; -function DeploymentServersEditor() { +export function DeploymentServersEditor() { const tx = useTx(); const [servers, setServers] = useSetting("deployment.servers"); const [groups, setGroups] = useSetting("deployment.groups"); @@ -955,7 +953,7 @@ function DeploymentServersEditor() { // --------------------------------------------------------------------------- // Options -function ExcludeNamesRow() { +export function ExcludeNamesRow() { const [names, setNames] = useSetting("deployment.exclude"); const [draft, setDraft] = useState(null); const id = useId(); @@ -979,89 +977,3 @@ function ExcludeNamesRow() { ); } - -export const DEPLOYMENT_PAGES: PageSpec[] = [ - { - id: "build.deployment", - title: "Deployment", - group: BUILD_GROUP, - order: 365, - projectScope: true, - defaultScope: "project", - keywords: [ - "local", - "mounted", - "sftp", - "ftp", - "ftps", - "ssh", - "server", - "upload", - "remote host", - "mappings", - "web server", - "deploy", - ], - sections: [ - { - options: [ - { - kind: "custom", - label: "Deployment servers", - keywords: [ - "Connection", - "Mappings", - "Excluded Paths", - "Root path", - "Web server URL", - "SSH configuration", - "FTP", - "Passive mode", - "Password", - "Save password", - "Test Connection", - "Use as Default", - "Server Group", - "Local path", - "Deployment path", - "Web path", - ], - component: DeploymentServersEditor, - }, - ], - }, - ], - }, - { - id: "build.deployment.options", - title: "Options", - order: 0, - projectScope: true, - defaultScope: "project", - keywords: ["deployment", "upload", "exclude", "timestamps", "automatic upload", "sftp"], - sections: [ - { - options: [ - { - kind: "custom", - label: "Exclude items by name", - keywords: ["exclude"], - component: ExcludeNamesRow, - }, - { - kind: "select", - key: "deployment.autoUpload", - label: "Upload changed files automatically to the default server", - options: [ - { value: "never", label: "Never" }, - { value: "onExplicitSave", label: "On explicit save action" }, - { value: "always", label: "Always" }, - ], - }, - { kind: "toggle", key: "deployment.deleteRemote", label: "Delete remote files when local are deleted" }, - { kind: "toggle", key: "deployment.preserveTimestamps", label: "Preserve files timestamps" }, - ], - }, - ], - }, -]; diff --git a/src/features/settings/pages/runTargets.tsx b/src/features/settings/pages/RunTargetsBody.tsx similarity index 92% rename from src/features/settings/pages/runTargets.tsx rename to src/features/settings/pages/RunTargetsBody.tsx index b81efefa5..3a1033c86 100644 --- a/src/features/settings/pages/runTargets.tsx +++ b/src/features/settings/pages/RunTargetsBody.tsx @@ -19,20 +19,10 @@ import { Button, Checkbox, Dialog, Icon, IconButton, Input, T, type SelectOption import { Row, Section, Select } from "../components/Form"; import { useSetting } from "../components/context"; import { SshConfigSelect, useSshConfigs } from "../components/SshConfigSelect"; -import { BUILD_GROUP } from "./execution"; -import type { PageSpec } from "./spec"; +import { parentPath, splitList } from "./runTargetsPaths"; import styles from "./Workflow.module.css"; import own from "./RunTargets.module.css"; -/** Parent of a remote path (`~/a` → `~`, `/a` → `/`); null at the top. */ -export function parentPath(path: string): string | null { - const p = path.length > 1 ? path.replace(/\/+$/, "") : path; - if (p === "/" || p === "~" || p === "") return null; - const i = p.lastIndexOf("/"); - if (i < 0) return null; - return i === 0 ? "/" : p.slice(0, i); -} - const UNKNOWN_HOST = /^Unknown SSH host key/; const NEEDS_SECRET = /^SSH (password|key passphrase) required|passphrase required|^cannot decrypt SSH key/; @@ -259,13 +249,6 @@ function ProjectFolderField({ target, onChange }: { target: RunTargetValid; onCh ); } -/** Settings typed as lists of words (`8000:8000 5678:5678`, `a.yaml; b.yaml`). */ -export const splitList = (text: string): string[] => - text - .split(/[\s,;]+/) - .map((s) => s.trim()) - .filter(Boolean); - function ListField({ label, value, @@ -414,7 +397,7 @@ function ContainerFields({ target, update }: { target: RunTargetValid; update: ( ); } -function RunTargetsEditor() { +export function RunTargetsEditor() { const plugins = usePluginRunTargets((s) => s.targets); const [defaultTarget, setDefaultTarget] = useSetting("run.defaultTarget"); const [raw, setTargets] = useSetting("runTargets"); @@ -593,40 +576,3 @@ function RunTargetsEditor() { ); } - -export const RUN_TARGET_PAGES: PageSpec[] = [ - { - id: "build.runTargets", - title: "Run Targets", - group: BUILD_GROUP, - order: 364, - projectScope: true, - keywords: ["ssh", "remote", "target", "run on", "interpreter", "upload", "sync", "docker", "compose", "container"], - sections: [ - { - options: [ - { - kind: "custom", - label: "Run Targets", - keywords: [ - "SSH configuration", - "Project folder on target", - "Upload changed project files before each run", - "Python interpreter", - "Node.js interpreter", - "Java executable", - "Docker connection", - "Image", - "Compose files", - "Service", - "Container folder", - "Published ports", - "Run options", - ], - component: RunTargetsEditor, - }, - ], - }, - ], - }, -]; diff --git a/src/features/settings/pages/scopes.tsx b/src/features/settings/pages/ScopesBody.tsx similarity index 87% rename from src/features/settings/pages/scopes.tsx rename to src/features/settings/pages/ScopesBody.tsx index ecaedfb94..9fe0f8556 100644 --- a/src/features/settings/pages/scopes.tsx +++ b/src/features/settings/pages/ScopesBody.tsx @@ -10,8 +10,6 @@ import { BUILTIN_SCOPES, scopeError, validateScopes, type NamedScope } from "@/p import { IconButton, Input, T, type SelectOption } from "@/ui"; import { ColorSwatches, Row, Section, Select } from "../components/Form"; import { useSetting } from "../components/context"; -import { APPEARANCE_GROUP } from "./behavior"; -import type { PageSpec } from "./spec"; import styles from "./Workflow.module.css"; import own from "./Scopes.module.css"; @@ -73,7 +71,7 @@ function errorText(error: { message: string; at: number }): string { return tx`${message} at column ${column}`; } -function ScopesEditor() { +export function ScopesEditor() { const [raw, setRaw] = useSetting("scopes"); const scopes = validateScopes(raw); const [selected, setSelected] = useState(0); @@ -182,7 +180,7 @@ const COLOR_LABELS: Record = { const colorLabel = (color: string) => COLOR_LABELS[color.toLowerCase()] ?? color; -function FileColorsEditor() { +export function FileColorsEditor() { const [raw, setRaw] = useSetting("fileColors"); const [rawScopes] = useSetting("scopes"); const settings = validateFileColors(raw); @@ -266,48 +264,3 @@ function FileColorsEditor() { ); } - -export const SCOPE_PAGES: PageSpec[] = [ - { - id: "fileColors", - title: "File Colors", - group: APPEARANCE_GROUP, - order: 1.5, - projectScope: true, - defaultScope: "project", - keywords: ["colour", "color", "tab", "background", "tests", "non-project"], - sections: [ - { - options: [ - { kind: "toggle", key: "fileColors.enabled", label: "Enable file colors" }, - { kind: "toggle", key: "fileColors.editorTabs", label: "Use in editor tabs" }, - { kind: "toggle", key: "fileColors.projectView", label: "Use in project view" }, - ], - }, - { - options: [ - { - kind: "custom", - label: "File Colors", - keywords: ["Scope", "Color", "Custom", "Hex value"], - component: FileColorsEditor, - }, - ], - }, - ], - }, - { - id: "scopes", - title: "Scopes", - group: APPEARANCE_GROUP, - order: 1.6, - projectScope: true, - defaultScope: "project", - keywords: ["scope", "file set", "pattern"], - sections: [ - { - options: [{ kind: "custom", label: "Scopes", keywords: ["Name", "Pattern"], component: ScopesEditor }], - }, - ], - }, -]; diff --git a/src/features/settings/pages/ssh.tsx b/src/features/settings/pages/SshBody.tsx similarity index 92% rename from src/features/settings/pages/ssh.tsx rename to src/features/settings/pages/SshBody.tsx index 4d27d2bda..a334984e0 100644 --- a/src/features/settings/pages/ssh.tsx +++ b/src/features/settings/pages/SshBody.tsx @@ -17,9 +17,7 @@ import { Button, Checkbox, IconButton, Input, type SelectOption, T } from "@/ui" import { Row, Section, Select } from "../components/Form"; import { useSetting } from "../components/context"; import { stageSshSecret, useSettingsDialog } from "../model/staging"; -import type { PageSpec } from "./spec"; import { parseSshPort, sshTestRemedy, type SshTestRemedy } from "./sshConnection"; -import { TOOLS_GROUP } from "./tools"; import styles from "./Workflow.module.css"; const AUTH: Array> = [ @@ -284,7 +282,7 @@ function SshConfigForm({ ); } -function SshConfigsEditor() { +export function SshConfigsEditor() { const [stored, setConfigs] = useSetting("ssh.configs", "global"); const configs = stored ?? []; const [selected, setSelected] = useState(configs[0]?.id ?? null); @@ -360,37 +358,3 @@ function SshConfigsEditor() { ); } - -export const SSH_PAGES: PageSpec[] = [ - { - id: "tools.sshConfigurations", - title: "SSH Configurations", - group: TOOLS_GROUP, - order: 603, - keywords: ["ssh", "remote", "host", "server", "key pair", "private key", "password", "known_hosts", "agent"], - sections: [ - { - options: [ - { - kind: "custom", - label: "SSH Configurations", - keywords: [ - "Host", - "Port", - "User name", - "Authentication type", - "Private key file", - "Password", - "Passphrase", - "Save password", - "Save passphrase", - "Test Connection", - "OpenSSH config and authentication agent", - ], - component: SshConfigsEditor, - }, - ], - }, - ], - }, -]; diff --git a/src/features/settings/pages/updates.tsx b/src/features/settings/pages/UpdatesBody.tsx similarity index 55% rename from src/features/settings/pages/updates.tsx rename to src/features/settings/pages/UpdatesBody.tsx index 3e3eaa1b6..cc836c32e 100644 --- a/src/features/settings/pages/updates.tsx +++ b/src/features/settings/pages/UpdatesBody.tsx @@ -5,9 +5,8 @@ import { call, commands, onIdeEvent, type UpdateStatus } from "@/platform/ipc"; import { useTx } from "@/platform/i18n"; import { Button, T } from "@/ui"; import { Row } from "../components/Form"; -import type { PageSpec } from "./spec"; -function UpdateStatusRows() { +export function UpdateStatusRows() { const tx = useTx(); const [version, setVersion] = useState(null); const [status, setStatus] = useState(null); @@ -49,45 +48,3 @@ function UpdateStatusRows() { ); } - -export const UPDATES_PAGE: PageSpec = { - id: "general.updates", - title: "Updates", - order: 3, - keywords: ["update", "upgrade", "version", "automatic", "GitHub", "CNB"], - sections: [ - { - options: [ - { - kind: "custom", - label: "Current version", - keywords: ["Last checked", "Check Now"], - component: UpdateStatusRows, - }, - { - kind: "toggle", - key: "general.autoCheckUpdates", - label: "Check for updates automatically", - hint: "At startup and every 4 hours while OpenIDEA runs. Each new version is announced once per session.", - }, - { - kind: "toggle", - key: "general.showWhatsNewAfterUpdate", - label: "Show What's New after an update", - hint: "Opens a page with the release notes when a new version starts. Help › What's New opens it any time.", - }, - { - kind: "select", - key: "general.updateSource", - label: "Update source", - hint: "Where updates are downloaded from. If it can't be reached, the other source is tried.", - options: [ - { value: "auto", label: "Automatic" }, - { value: "github", label: "GitHub" }, - { value: "cnb", label: "CNB (China mirror)" }, - ], - }, - ], - }, - ], -}; diff --git a/src/features/settings/pages/builtins.tsx b/src/features/settings/pages/builtins.tsx index bd72561bf..0beb7ae23 100644 --- a/src/features/settings/pages/builtins.tsx +++ b/src/features/settings/pages/builtins.tsx @@ -1,11 +1,17 @@ /** Built-in settings pages (IDEA layout: Appearance & Behavior, Keymap, Editor). */ import { GlobListEditor, Row } from "../components/Form"; import { useSetting } from "../components/context"; -import { KeymapPage, keymapSearchLabels } from "../keymap/KeymapPage"; -import { AssociatedApplicationsRow, RecognizedFileTypes } from "./FileTypes"; +import { keymapSearchLabels } from "../keymap/model"; +import { lazyPage } from "./lazyPage"; import type { PageSpec } from "./spec"; export const EDITOR_GROUP = "Editor"; +const KeymapPage = lazyPage("keymap", () => import("../keymap/KeymapPage").then((m) => m.KeymapPage)); +const RecognizedFileTypes = lazyPage("editor.files", () => import("./FileTypes").then((m) => m.RecognizedFileTypes)); +const AssociatedApplicationsRow = lazyPage("editor.files", () => + import("./FileTypes").then((m) => m.AssociatedApplicationsRow), +); + function ExcludeRow() { const [exclude, setExclude] = useSetting("files.exclude"); return ( diff --git a/src/features/settings/pages/deployment.ts b/src/features/settings/pages/deployment.ts new file mode 100644 index 000000000..f91c19606 --- /dev/null +++ b/src/features/settings/pages/deployment.ts @@ -0,0 +1,96 @@ +import { BUILD_GROUP } from "./execution"; +import { lazyPage } from "./lazyPage"; +import type { PageSpec } from "./spec"; + +const DeploymentServersEditor = lazyPage("build.deployment", () => + import("./DeploymentBody").then((m) => m.DeploymentServersEditor), +); +const ExcludeNamesRow = lazyPage("build.deployment.options", () => + import("./DeploymentBody").then((m) => m.ExcludeNamesRow), +); + +export const DEPLOYMENT_PAGES: PageSpec[] = [ + { + id: "build.deployment", + title: "Deployment", + group: BUILD_GROUP, + order: 365, + projectScope: true, + defaultScope: "project", + keywords: [ + "local", + "mounted", + "sftp", + "ftp", + "ftps", + "ssh", + "server", + "upload", + "remote host", + "mappings", + "web server", + "deploy", + ], + sections: [ + { + options: [ + { + kind: "custom", + label: "Deployment servers", + keywords: [ + "Connection", + "Mappings", + "Excluded Paths", + "Root path", + "Web server URL", + "SSH configuration", + "FTP", + "Passive mode", + "Password", + "Save password", + "Test Connection", + "Use as Default", + "Server Group", + "Local path", + "Deployment path", + "Web path", + ], + component: DeploymentServersEditor, + }, + ], + }, + ], + }, + { + id: "build.deployment.options", + title: "Options", + order: 0, + projectScope: true, + defaultScope: "project", + keywords: ["deployment", "upload", "exclude", "timestamps", "automatic upload", "sftp"], + sections: [ + { + options: [ + { + kind: "custom", + label: "Exclude items by name", + keywords: ["exclude"], + component: ExcludeNamesRow, + }, + { + kind: "select", + key: "deployment.autoUpload", + label: "Upload changed files automatically to the default server", + options: [ + { value: "never", label: "Never" }, + { value: "onExplicitSave", label: "On explicit save action" }, + { value: "always", label: "Always" }, + ], + }, + { kind: "toggle", key: "deployment.deleteRemote", label: "Delete remote files when local are deleted" }, + { kind: "toggle", key: "deployment.preserveTimestamps", label: "Preserve files timestamps" }, + ], + }, + ], + }, +]; diff --git a/src/features/settings/pages/editor/ColorSchemeBody.tsx b/src/features/settings/pages/editor/ColorSchemeBody.tsx new file mode 100644 index 000000000..46ed4b7fc --- /dev/null +++ b/src/features/settings/pages/editor/ColorSchemeBody.tsx @@ -0,0 +1,1715 @@ +import { SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta"; +/** + * Editor › Color Scheme: scheme chooser, the IDEA attribute tree (General, + * Language Defaults, languages) with a foreground / background / bold / + * italic / effects editor, and a live preview. Edits are staged in + * `editor.colorOverrides[scheme][attribute]`; `editor/core` injects them. + */ +import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react"; +import { Button, Checkbox, Icon, Input, Tree, type SelectOption, type TreeHandle, T } from "@/ui"; +import { fontWeightVars, type CustomColorSchemes, type TextAttributesOverride } from "@/platform/editorSettings"; +import { + ATTRIBUTES, + EFFECT_CSS, + overrideDeclarations, + effectiveScheme, + resolvedSchemeTokens, + resolvedAttribute, + CLEAR_COLOR, + listSchemes, + customSchemes, + type AttributeDef, +} from "@/platform/colorScheme"; +import { HEX_COLOR } from "../../model/schema"; +import { Row, Select } from "../../components/Form"; +import { useSetting } from "../../components/context"; +import styles from "./Editor.module.css"; +import { executeAction, registerActions } from "@/platform/actions"; +import { call, commands } from "@/platform/ipc"; +import { ask, confirm, showError } from "@/workbench/messages"; +import { parseIcls, SchemeParseError, importScheme, deleteScheme, exportIcls } from "@/platform/icls"; +import { tx, useTx } from "@/platform/i18n"; +import { selectPage } from "../../model/staging"; + +type Overrides = Record>; + +interface Node { + key: string; + label: string; + attr?: AttributeDef; + children?: Node[]; +} + +/** Tree segments of an attribute: its scope path plus any "›" groups in its display name. */ +function attrSegs(attr: AttributeDef): string[] { + const parts = attr.name.split(" › "); + return [...attr.path, ...parts.slice(0, -1)]; +} + +/** Tree keys of every ancestor group of an attribute, from the scope root down. */ +function ancestorKeys(attr: AttributeDef): string[] { + const keys: string[] = []; + let key = ""; + for (const seg of attrSegs(attr)) { + key += `/${seg}`; + keys.push(key); + } + return keys; +} + +function buildTree(): Node[] { + const roots: Node[] = []; + for (const attr of ATTRIBUTES) { + const parts = attr.name.split(" › "); + let level = roots; + let key = ""; + for (const seg of attrSegs(attr)) { + key += `/${seg}`; + let n = level.find((x) => x.key === key); + if (!n) level.push((n = { key, label: seg, children: [] })); + level = n.children!; + } + level.push({ key: attr.id, label: parts.at(-1)!, attr }); + } + return roots; +} + +const TREE = buildTree(); + +/** Roots of one page's attribute tree, in JetBrains fashion: scopes are pages, not tree panes. */ +function pageTree(scopes: readonly string[]): Node[] { + return TREE.filter((n) => scopes.includes(n.label)); +} + +function firstLeafId(nodes: readonly Node[]): string { + const n = nodes[0]!; + return n.attr ? n.attr.id : firstLeafId(n.children!); +} + +function treeIds(nodes: readonly Node[], out = new Set()): Set { + for (const n of nodes) { + if (n.attr) out.add(n.attr.id); + if (n.children) treeIds(n.children, out); + } + return out; +} + +/** Settings sub-page that owns an attribute, for preview clicks that cross pages. */ +function attrPageId(attr: AttributeDef): string { + return languagePageId(attr.path[0]!); +} + +/** Preview click on another sub-page: the target page selects and reveals the attribute. */ +let crossPageReveal: string | null = null; + +/** + * CSS custom properties of a scheme plus pending overrides (for the preview); with + * `language`, that language's own colours on top, as its editors show them. + */ +function previewVars( + id: string, + o: Record | undefined, + customs: CustomColorSchemes, + language?: string, + redGreen = false, +): CSSProperties { + const vars: Record = {}; + const tokens = resolvedSchemeTokens(id, customs, redGreen); + for (const [k, v] of tokens) + if ( + k.startsWith("--syn-") || + k.startsWith("--fg-") || + k.startsWith("--bg-") || + k.startsWith("--border-") || + k.startsWith("--ansi-") || + k.startsWith("--git-") || + k.startsWith("--wave-") || + k.startsWith("--editor-") || + k === "--caret" + ) + vars[k] = v; + vars["--bg-editor"] = tokens.get("--bg-editor") ?? tokens.get("--bg-island") ?? ""; + for (const [key, value] of overrideDeclarations(o)) vars[key] = value; + if (language) { + for (const [key, value] of overrideDeclarations(customs[id]?.attributes, language)) vars[key] = value; + for (const [key, value] of overrideDeclarations(o, language)) vars[key] = value; + } + return vars as CSSProperties; +} + +/** Text styled like an attribute in the preview. */ +function tokenStyle(attr: AttributeDef | undefined): CSSProperties { + const base = attr?.fg ?? attr?.effect; + if (!attr?.token) { + const colour: CSSProperties = { + ...(attr?.fg ? { color: `var(${attr.fg})` } : null), + ...(attr?.bg ? { backgroundColor: `var(${attr.bg})` } : null), + }; + // Token-less attributes with a font-style renderer carry it on `---*`, the same + // declarations `overrideDeclarations` emits for their overrides. + if (!attr?.fontStyle || !base) return colour; + const effectColor = `var(${attr.effect ?? attr.fg ?? "--fg-muted"})`; + const effect: TextAttributesOverride["effect"] = attr.defaultEffect ?? (attr.effect ? "wave" : undefined); + const decoration = + effect && effect !== "none" + ? `var(${attr.effect ?? base}-effect, ${EFFECT_CSS[effect]?.(effectColor) ?? "none"})` + : undefined; + return { + ...colour, + fontWeight: `var(${base}-bold, ${ + attr.defaultBold ? "var(--fw-code-bold, 700)" : "inherit" + })` as CSSProperties["fontWeight"], + fontStyle: `var(${base}-italic, ${attr.defaultItalic ? "italic" : "inherit"})`, + ...(decoration + ? { textDecoration: decoration, ...({ WebkitTextDecoration: decoration } as CSSProperties) } + : null), + }; + } + if (attr.italicOnly) + return { fontStyle: `var(--syn-${attr.token}-italic, ${attr.defaultItalic === false ? "normal" : "italic"})` }; + const t = attr.token; + const italic = t === "comment" ? "var(--syn-comment-style)" : attr.defaultItalic ? "italic" : "inherit"; + const bold = attr.defaultBold ? "var(--fw-code-bold, 700)" : "inherit"; + const effect = attr.defaultEffect === "underline" ? "underline" : "none"; + return { + color: `var(--syn-${t})`, + fontWeight: `var(--syn-${t}-bold, ${bold})` as CSSProperties["fontWeight"], + fontStyle: `var(--syn-${t}-italic, ${italic})`, + backgroundColor: `var(--syn-${t}-bg, transparent)`, + textDecoration: `var(--syn-${t}-effect, ${effect})`, + // WebKit takes a decoration with a style or colour only through the prefixed property. + ...({ WebkitTextDecoration: `var(--syn-${t}-effect, ${effect})` } as CSSProperties), + }; +} + +const A = (id: string) => ATTRIBUTES.find((a) => a.id === id); + +/** Preview click: reveal in this page, or switch to the attribute's own page. */ +function revealPreviewAttr(attrId: string, ids: Set, reveal: (id: string) => void): void { + const attr = A(attrId); + if (!attr) return; + if (ids.has(attrId)) reveal(attrId); + else { + crossPageReveal = attrId; + selectPage(attrPageId(attr)); + } +} + +type Seg = [string, string?]; +interface CodeSample { + code: Seg[][]; + /** Line shown with the caret-row background. */ + caret?: number; +} + +/** One sample per page, each covering as much of that scope's token set as possible. */ +const SAMPLES: Record = { + General: { + code: [ + [["# General: text, gutter, hints and matches", "lineComment"]], + [ + ["TODO", "todo"], + [" check the wave decorations below", "text"], + ], + [ + ["erroneous", "error"], + [" ", "text"], + ["suspicious", "warning"], + [" ", "text"], + ["could be const", "weakWarning"], + [" ", "text"], + ["legacyCall", "unused"], + ], + [ + ["typo", "typo"], + [" ", "text"], + ["deprecatedCall", "deprecated"], + ], + [ + ["bad\u203dchar", "invalid"], + [" \u00b7 ", "whitespaces"], + ["\u2192 indent guides \u2192", "indentGuide"], + ], + [ + ["const", "inlay"], + [" name", "text"], + [" = ", "operator"], + ["value", "text"], + [" ", "text"], + ["\u2026", "folded"], + [" folded region ", "folded"], + ["\u2026", "folded"], + ], + [ + ["search hit ", "text"], + ["token", "searchResult"], + [" and current ", "text"], + ["token", "searchResultCurrent"], + ], + [ + ["matched ", "text"], + ["()", "matchedBrace"], + [" identifier under caret ", "text"], + ["name", "identifierUnderCaret"], + [" / ", "text"], + ["name", "identifierUnderCaretWrite"], + ], + ], + }, + Debugger: { + code: [ + [["# Debugger: inline values and breakpoint rows", "lineComment"]], + [ + ["len", "inlineValue"], + [" = ", "text"], + ["3", "text"], + [" ", "text"], + ["name", "inlineValue"], + [" = ", "text"], + ['"world"', "string"], + ], + [ + ["return", "keyword"], + [" len(text)", "text"], + ], + ], + caret: 2, + }, + "Console Colors": { + code: [ + [ + ["black ", "ansiBlack"], + ["red ", "ansiRed"], + ["green ", "ansiGreen"], + ["yellow", "ansiYellow"], + ], + [ + ["blue ", "ansiBlue"], + ["magenta ", "ansiMagenta"], + ["cyan ", "ansiCyan"], + ["white", "ansiWhite"], + ], + [ + ["dark ", "ansiBrightBlack"], + ["bright-red ", "ansiBrightRed"], + ["bright-green ", "ansiBrightGreen"], + ["bright-yellow", "ansiBrightYellow"], + ], + [ + ["bright-blue ", "ansiBrightBlue"], + ["bright-magenta ", "ansiBrightMagenta"], + ["bright-cyan ", "ansiBrightCyan"], + ["bright-white", "ansiBrightWhite"], + ], + ], + }, + "Language Defaults": { + code: [ + [["# Language Defaults", "lineComment"]], + [["@Entity", "metadata"]], + [ + ["class ", "keyword"], + ["Session", "className"], + [" implements ", "keyword"], + ["Runnable", "className"], + [" {", "operator"], + ], + [ + [" /**", "docComment"], + [" ", "docCommentMarkup"], + ["doc comment", "docComment"], + [" ", "docCommentMarkup"], + ["@param", "docCommentTag"], + [" ", "docComment"], + ["id", "docCommentTagValue"], + [" */", "docComment"], + ], + [ + [" static", "staticSymbol"], + [" MAX", "constant"], + [" = ", "operator"], + ["0xff", "number"], + [";", "operator"], + ], + [ + [" field", "field"], + [" = ", "operator"], + ['"a', "string"], + ["\\n", "escape"], + ["\\t", "escape"], + ["z", "string"], + ['\\"', "escape"], + ['"', "string"], + [";", "operator"], + ], + [ + [" def ", "keyword"], + ["greet", "functionDeclaration"], + ["(", "operator"], + ["name", "parameter"], + [", ", "operator"], + ["GLOBAL", "globalVariable"], + [", ", "operator"], + ["com.example", "packageReference"], + ["):", "operator"], + ], + [ + [" ", "text"], + ["greet", "functionCall"], + ["(", "operator"], + ["predefined", "predefined"], + [", ", "operator"], + ["local", "identifier"], + [")", "operator"], + ], + [ + [" x", "identifier"], + [" = ", "operator"], + ["[", "bracket1"], + ["(", "bracket2"], + ["{", "bracket3"], + ["1", "number"], + ["}", "bracket3"], + [")", "bracket2"], + ["]", "bracket1"], + [";", "operator"], + ], + [ + [" s1", "semantic1"], + [" s2", "semantic2"], + [" s3", "semantic3"], + [" s4", "semantic4"], + [" s5", "semantic5"], + ], + [ + [" <", "operator"], + ["div", "markupTag"], + [" ", "text"], + ["class", "markupAttribute"], + ["=", "operator"], + ['"row"', "string"], + [">", "operator"], + ["\u2026", "text"], + ["", "operator"], + ], + [["}", "operator"]], + ], + }, + Python: { + caret: 4, + code: [ + [ + ["import ", "pyKeyword"], + ["os", "pyStaticSymbol"], + ], + [ + ["MAX_RETRIES", "pyConstant"], + [" = ", "pyOperationSign"], + ["3", "pyNumber"], + ], + [], + [ + ["@decorator", "pyDecorator"], + ["(", "pyParentheses"], + ["param", "pyKeywordArg"], + ["=", "pyOperationSign"], + ["1", "pyNumber"], + [")", "pyParentheses"], + ], + [ + ["def ", "pyKeyword"], + ["f", "pyFunctionDeclaration"], + ["(", "pyParentheses"], + ["x", "pyParameter"], + [")", "pyParentheses"], + [":", "pyOperationSign"], + ], + [[' """', "pyDocstring"]], + [[" Syntax Highlighting Demo", "pyDocstring"]], + [ + [" :", "pyDocstring"], + ["param", "pyDocstringTag"], + [" ", "pyDocstring"], + ["x", "pyDocstringKeyword"], + [": Parameter", "pyDocstring"], + ], + [], + [[" Semantic highlighting:", "pyDocstring"]], + [[" Generated spectrum to pick colors for local variables and parameters:", "pyDocstring"]], + [ + [" ", "pyDocstring"], + ["Color#1 ", "semantic1"], + ["SC1.1 SC1.2 SC1.3 SC1.4 ", "semantic1"], + ["Color#2 ", "semantic2"], + ["SC2.1 SC2.2 SC2.3 SC2.4 ", "semantic2"], + ["Color#3", "semantic3"], + ], + [ + [" ", "pyDocstring"], + ["Color#3 ", "semantic3"], + ["SC3.1 SC3.2 SC3.3 SC3.4 ", "semantic3"], + ["Color#4 ", "semantic4"], + ["SC4.1 SC4.2 SC4.3 SC4.4 ", "semantic4"], + ["Color#5", "semantic5"], + ], + [[' """', "pyDocstring"]], + [], + [ + [" def ", "pyKeyword"], + ["nested_func", "pyNestedFunction"], + ["(", "pyParentheses"], + ["y", "pyParameter"], + [")", "pyParentheses"], + [":", "pyOperationSign"], + ], + [ + [" ", "text"], + ["print", "pyBuiltin"], + ["(", "pyParentheses"], + ["y", "pyLocalVariable"], + [" + ", "pyOperationSign"], + ["1", "pyNumber"], + [")", "pyParentheses"], + ], + [], + [ + [" s", "pyLocalVariable"], + [" = ", "pyOperationSign"], + ["(", "pyParentheses"], + ['"Test"', "pyString"], + [", ", "pyOperationSign"], + ["2", "pyNumber"], + ["+", "pyOperationSign"], + ["3", "pyNumber"], + [", ", "pyOperationSign"], + ["{", "pyBraces"], + ["'a'", "pyString"], + [": ", "pyOperationSign"], + ["'b'", "pyString"], + ["}", "pyBraces"], + [",", "pyOperationSign"], + ], + [ + [" ", "text"], + ["f", "pyFString"], + ["'{", "pyFString"], + ["x", "pyParameter"], + ["!s:", "pyFormat"], + ["{", "pyFormat"], + ['"^10"', "pyString"], + ["}", "pyFormat"], + ["}'", "pyFString"], + [", ", "pyOperationSign"], + ["f", "pyFString"], + ['"{', "pyFString"], + ["1", "pyNumber"], + [":", "pyFString"], + ["01d", "pyFormat"], + ['}"', "pyFString"], + [")", "pyParentheses"], + [" ", "text"], + ["# Comment", "pyLineComment"], + ], + [ + [" ", "text"], + ["f", "pyFunctionCall"], + ["(", "pyParentheses"], + ["s", "pyLocalVariable"], + ["[", "pyBrackets"], + ["0", "pyNumber"], + ["]", "pyBrackets"], + [".", "pyOperationSign"], + ["lower", "pyMethodCall"], + ["(", "pyParentheses"], + [")", "pyParentheses"], + [")", "pyParentheses"], + ], + [ + [" ", "text"], + ["nested_func", "pyFunctionCall"], + ["(", "pyParentheses"], + ["42", "pyNumber"], + [")", "pyParentheses"], + ], + [], + [ + ["class ", "pyKeyword"], + ["Foo", "pyClassDefinition"], + [":", "pyOperationSign"], + ], + [ + [" tags", "pyClassAttribute"], + [": ", "text"], + ["List", "pyAnnotation"], + ["[", "pyBrackets"], + ["str", "pyBuiltin"], + ["]", "pyBrackets"], + ], + [], + [ + [" def ", "pyKeyword"], + ["__init__", "pyPredefinedDefinition"], + ["(", "pyParentheses"], + ["self", "pySelf"], + [": ", "text"], + ["Foo", "pyAnnotation"], + [")", "pyParentheses"], + [":", "pyOperationSign"], + ], + [ + [" byte_string", "pyLocalVariable"], + [": ", "text"], + ["bytes", "pyBuiltin"], + [" = ", "pyOperationSign"], + ["b'newline:", "pyBytes"], + ["\\n", "pyValidEscape"], + [" also newline:", "pyBytes"], + ["\\x0a", "pyValidEscape"], + ["'", "pyBytes"], + ], + [ + [" text_string", "pyLocalVariable"], + [" = ", "pyOperationSign"], + ['u"Cyrillic Я is ', "pyString"], + ["\\u042f", "pyValidEscape"], + [". Oops: ", "pyString"], + ["\\u042g", "pyInvalidEscape"], + ['"', "pyString"], + ], + [ + [" ", "text"], + ["self", "pySelf"], + [".", "pyOperationSign"], + ["make_sense", "pyMethodCall"], + ["(", "pyParentheses"], + ["whatever", "pyKeywordArg"], + ["=", "pyOperationSign"], + ["1", "pyNumber"], + [")", "pyParentheses"], + ], + [], + [["@property", "pyDecorator"]], + [ + [" def ", "pyKeyword"], + ["alias", "pyProperty"], + ["(", "pyParentheses"], + ["self", "pySelf"], + [")", "pyParentheses"], + [":", "pyOperationSign"], + ], + [ + [" return ", "pyKeyword"], + ["self", "pySelf"], + [".", "pyOperationSign"], + ["sense", "pyInstanceAttribute"], + ], + [], + [ + [" def ", "pyKeyword"], + ["make_sense", "pyFunctionDeclaration"], + ["[", "pyBrackets"], + ["T", "pyTypeParameter"], + ["]", "pyBrackets"], + ["(", "pyParentheses"], + ["self", "pySelf"], + [", ", "pyOperationSign"], + ["whatever", "pyParameter"], + [": ", "text"], + ["T", "pyAnnotation"], + [")", "pyParentheses"], + [":", "pyOperationSign"], + ], + [ + [" ", "text"], + ["self", "pySelf"], + [".", "pyOperationSign"], + ["sense", "pyInstanceAttribute"], + [" = ", "pyOperationSign"], + ["whatever", "pyParameter"], + ], + [], + [ + ["x", "pyGlobalVariable"], + [" = ", "pyOperationSign"], + ["len", "pyBuiltin"], + ["(", "pyParentheses"], + ['"abc"', "pyString"], + [")", "pyParentheses"], + ], + [ + ["type ", "pyKeyword"], + ["my_int", "pyGlobalVariable"], + [" = ", "pyOperationSign"], + ["int", "pyBuiltin"], + ], + [ + ["print", "pyBuiltin"], + ["(", "pyParentheses"], + ["f", "pyFunctionCall"], + [".", "pyOperationSign"], + ["__doc__", "pyPredefinedUsage"], + [")", "pyParentheses"], + ], + ], + }, + Markdown: { + code: [ + [["# Heading level one", "mdHeading"]], + [["## Heading level two", "mdHeading"]], + [ + ["Inline ", "text"], + ["`code`", "mdCode"], + [" and ", "text"], + ["[link](https://example.com)", "mdLink"], + [" text", "text"], + ], + [ + ["<", "operator"], + ["em", "markupTag"], + [">", "operator"], + ["emphasis", "text"], + ["", "operator"], + ], + [ + ["- ", "operator"], + ["list item ", "text"], + ["`x`", "mdCode"], + ], + ], + }, + RegExp: { + code: [ + [["# Regular expressions", "lineComment"]], + [ + ["^[a-z]", "regexp"], + ["+", "operator"], + ["(\\d{2,3})", "regexp"], + ["?", "operator"], + ["$", "regexp"], + ], + [ + ["(?P", "regexp"], + ["\\d{4}", "regexp"], + [")", "regexp"], + ["-", "operator"], + ["(\\d{2})", "regexp"], + ], + [ + ["\\bword\\b", "regexp"], + [" | ", "operator"], + ["[[:alpha:]]", "regexp"], + ], + ], + }, + Java: { + code: [ + [["// Java", "java.lineComment"]], + [["@Override", "java.metadata"]], + [ + ["public class ", "java.keyword"], + ["Greeter", "java.className"], + [" {", "java.operator"], + ], + [ + [" private static final ", "java.keyword"], + ["int", "java.keyword"], + [" MAX", "java.constant"], + [" = ", "java.operator"], + ["3", "java.number"], + [";", "java.operator"], + ], + [ + [" private ", "java.keyword"], + ["String", "java.className"], + [" name", "java.field"], + [" = ", "java.operator"], + ['"a', "java.string"], + ["\\n", "java.escape"], + ['"', "java.string"], + [";", "java.operator"], + ], + [[" /** doc comment */", "java.docComment"]], + [ + [" public ", "java.keyword"], + ["void", "java.keyword"], + ["greet", "java.functionDeclaration"], + ["(", "java.operator"], + ["String", "java.className"], + [" name", "java.parameter"], + [")", "java.operator"], + [" {", "java.operator"], + ], + [ + [" ", "text"], + ["System", "java.predefined"], + [".", "java.operator"], + ["out", "java.field"], + [".", "java.operator"], + ["println", "java.functionCall"], + ["(", "java.operator"], + ["name", "java.identifier"], + [")", "java.operator"], + [";", "java.operator"], + ], + [ + [" ", "text"], + ["Greeter", "java.className"], + [".", "java.operator"], + ["MAX", "java.staticSymbol"], + ], + [[" }", "java.operator"]], + [["}", "java.operator"]], + ], + }, + Julia: { + code: [ + [["# Julia", "julia.lineComment"]], + [ + ["struct ", "julia.keyword"], + ["Point", "julia.className"], + ["{", "julia.operator"], + ], + [[" x::Float64", "julia.identifier"]], + [["end", "julia.keyword"]], + [], + [ + ["function ", "julia.keyword"], + ["distance", "julia.functionDeclaration"], + ["(p::", "julia.operator"], + ["Point", "julia.className"], + [")", "julia.operator"], + ], + [[" norm((p.x, p.y))", "text"]], + [["end", "julia.keyword"]], + [], + [ + ["@show ", "julia.metadata"], + ["distance", "julia.functionCall"], + ["(", "julia.operator"], + ["Point", "julia.functionCall"], + ["(", "julia.operator"], + ["1.0", "julia.number"], + [", ", "julia.operator"], + ["2.0", "julia.number"], + ["))", "julia.operator"], + ], + ], + }, + Go: { + code: [ + [["package ", "go.keyword"], ["palette"]], + [ + ["import ", "go.keyword"], + ['"fmt"', "go.string"], + ], + [["// Retry a greeting", "go.lineComment"]], + [ + ["const ", "go.keyword"], + ["MaxRetries", "go.constant"], + [" = ", "go.operator"], + ["3", "go.number"], + ], + [ + ["var ", "go.keyword"], + ["DefaultName", "go.globalVariable"], + [" = ", "go.operator"], + ['"Go"', "go.string"], + ], + [ + ["type ", "go.keyword"], + ["Greeter", "go.className"], + [" struct ", "go.keyword"], + ["{", "go.operator"], + ], + [ + [" Name", "go.field"], + [" string", "go.predefined"], + ], + [["}", "go.operator"]], + [ + ["func ", "go.keyword"], + ["(", "go.operator"], + ["g", "go.parameter"], + [" Greeter", "go.className"], + [") ", "go.operator"], + ["Greet", "go.functionDeclaration"], + ["(", "go.operator"], + ["count", "go.parameter"], + [" int", "go.predefined"], + [") ", "go.operator"], + ["string", "go.predefined"], + [" {", "go.operator"], + ], + [ + [" message", "go.identifier"], + [" := ", "go.operator"], + ["fmt", "go.packageReference"], + [".", "go.operator"], + ["Sprintf", "go.functionCall"], + ["(", "go.operator"], + ['"Hello, %s', "go.string"], + ["\\n", "go.escape"], + ['"', "go.string"], + [", ", "go.operator"], + ["g", "go.parameter"], + [".", "go.operator"], + ["Name", "go.field"], + [")", "go.operator"], + ], + [ + [" return ", "go.keyword"], + ["message", "go.identifier"], + ], + [["}", "go.operator"]], + ], + }, + Kotlin: { + code: [ + [["// Kotlin", "kotlin.lineComment"]], + [["@JvmStatic", "kotlin.metadata"]], + [ + ["class ", "kotlin.keyword"], + ["Greeter", "kotlin.className"], + ["(", "kotlin.operator"], + ["val", "kotlin.keyword"], + [" name", "kotlin.parameter"], + [": ", "text"], + ["String", "kotlin.className"], + [")", "kotlin.operator"], + [" {", "kotlin.operator"], + ], + [ + [" companion ", "kotlin.keyword"], + ["object", "kotlin.keyword"], + [" {", "kotlin.operator"], + [" const ", "kotlin.keyword"], + ["val", "kotlin.keyword"], + [" MAX", "kotlin.constant"], + [" = ", "kotlin.operator"], + ["3", "kotlin.number"], + [" }", "kotlin.operator"], + ], + [ + [" fun ", "kotlin.keyword"], + ["greet", "kotlin.functionDeclaration"], + ["(", "kotlin.operator"], + ["name", "kotlin.parameter"], + [": ", "text"], + ["String", "kotlin.className"], + ["): ", "text"], + ["String", "kotlin.className"], + [" = ", "kotlin.operator"], + ['"a', "kotlin.string"], + ["\\n", "kotlin.escape"], + ['"', "kotlin.string"], + ], + [ + [" ", "text"], + ["println", "kotlin.predefined"], + ["(", "kotlin.operator"], + ["name", "kotlin.identifier"], + [")", "kotlin.operator"], + ], + [["}", "kotlin.operator"]], + ], + }, + "C#": { + code: [ + [["// Greets the user", "csharp.lineComment"]], + [ + ["using ", "csharp.keyword"], + ["System", "csharp.packageReference"], + [";", "csharp.operator"], + ], + [["/// Says hello.", "csharp.docComment"]], + [ + ["[", "csharp.operator"], + ["Serializable", "csharp.metadata"], + ["]", "csharp.operator"], + ], + [ + ["public class ", "csharp.keyword"], + ["Greeter", "csharp.className"], + ], + [["{", "csharp.operator"]], + [ + [" private const int ", "csharp.keyword"], + ["MaxRetries", "csharp.constant"], + [" = ", "csharp.operator"], + ["3", "csharp.number"], + [";", "csharp.operator"], + ], + [ + [" public string ", "csharp.keyword"], + ["Name", "csharp.field"], + [" { ", "csharp.operator"], + ["get", "csharp.keyword"], + ["; }", "csharp.operator"], + ], + [ + [" public string ", "csharp.keyword"], + ["Greet", "csharp.functionDeclaration"], + ["(", "csharp.operator"], + ["int ", "csharp.keyword"], + ["count", "csharp.parameter"], + [")", "csharp.operator"], + ], + [[" {", "csharp.operator"]], + [ + [" var ", "csharp.keyword"], + ["message", "csharp.identifier"], + [" = ", "csharp.operator"], + ['$"Hello, {Name}', "csharp.string"], + ["\\n", "csharp.escape"], + ['"', "csharp.string"], + [";", "csharp.operator"], + ], + [ + [" return ", "csharp.keyword"], + ["string", "csharp.keyword"], + [".", "csharp.operator"], + ["Format", "csharp.functionCall"], + ["(", "csharp.operator"], + ["message", "csharp.identifier"], + [", ", "csharp.operator"], + ["count", "csharp.parameter"], + [");", "csharp.operator"], + ], + [[" }", "csharp.operator"]], + [["}", "csharp.operator"]], + ], + }, + PHP: { + code: [ + [[" void; +}) { + const v = value ?? {}; + const set = (patch: Partial) => { + const next: TextAttributesOverride = { ...v, ...patch }; + for (const k of Object.keys(next) as Array) + if (next[k] === undefined || next[k] === inherited[k]) delete next[k]; + onChange(Object.keys(next).length ? next : undefined); + }; + // IDEA's panel is fixed: every channel renders for every attribute, disabled when the + // attribute cannot carry it (ColorAndFontDescriptionPanel.kt). Capability is declared, + // not inferred: `fontStyle` marks attributes whose renderer applies font style/effects. + return ( +
+ {!attr.italicOnly && ( +
+ set({ bold: b === (inherited.bold ?? false) ? undefined : b })} + label="Bold" + /> + set({ italic: b === (inherited.italic ?? false) ? undefined : b })} + label="Italic" + /> +
+ )} + {attr.italicOnly && ( +
+ set({ italic: b === (inherited.italic ?? attr.defaultItalic ?? true) ? undefined : b })} + label="Italic" + /> +
+ )} + set({ foreground: c }) : undefined} + /> + set({ background: c }) : undefined} + /> + {!attr.italicOnly && ( + <> + set({ effectColor: c }) : undefined} + /> +
+ + set({ + effect: b + ? inherited.effect && inherited.effect !== "none" + ? inherited.effect + : "underline" + : inherited.effect && inherited.effect !== "none" + ? "none" + : undefined, + effectColor: b ? v.effectColor : undefined, + }) + } + label="Effect style" + /> + {!!(v.effect ?? inherited.effect) && (v.effect ?? inherited.effect) !== "none" && ( + onChange(e.target.value)} + /> + + { + setDraft(e.target.value); + if (HEX_COLOR.test(e.target.value)) onChange(e.target.value.toLowerCase()); + }} + onBlur={() => setDraft(null)} + /> + + ); +} + +function ColorRow({ + label, + value, + inherited, + onChange, +}: { + label: string; + value: string | undefined; + inherited: string | undefined; + /** Undefined disables the row for attributes that cannot carry this channel. */ + onChange: ((c: string | undefined) => void) | undefined; +}) { + const cleared = value === CLEAR_COLOR; + const shown = cleared ? undefined : (value ?? inherited); + return ( +
+ + onChange?.( + on + ? cleared + ? (inherited ?? "#808080") + : (shown ?? "#808080") + : inherited !== undefined + ? CLEAR_COLOR + : undefined, + ) + } + label={label} + /> + {shown !== undefined && undefined)} label={label} />} +
+ ); +} + +/** Git preview sample: an editor caret line carrying the inline blame widget. */ +const GIT_EDITOR_LINES: { segs: Seg[]; blame?: boolean }[] = [ + { segs: [["function", "keyword"], [" "], ["syncRoot", "functionCall"], ["("], ["info", "parameter"], [") {"]] }, + { + segs: [ + [" "], + ["const", "keyword"], + [" "], + ["branch", "identifier"], + [" = "], + ["info", "parameter"], + ["."], + ["head", "identifier"], + [";"], + ], + blame: true, + }, + { segs: [["}"]] }, +]; + +/** A project tree root in the Git preview; its suffix mirrors rootSyncSuffix. */ +interface GitPreviewRoot { + name: string; + branch: string; + branchAttr: string; + upstream?: string; + ahead?: number; + behind?: number; +} +const GIT_PREVIEW_ROOTS: GitPreviewRoot[] = [ + { name: "openidea", branch: "main", branchAttr: "gitMasterWithRemote", upstream: "origin/main", ahead: 2, behind: 1 }, + { name: "legacy-app", branch: "master", branchAttr: "gitMasterWithoutRemote" }, + { name: "web-client", branch: "feature/login", branchAttr: "gitLocalBranch" }, + { name: "api-server", branch: "release/2.0", branchAttr: "gitTrackingBranch", upstream: "origin/release/2.0" }, +]; +interface GitPreviewSuffixSeg { + text: string; + attr: string; + icon?: "vcs-outgoing" | "vcs-incoming"; + label?: string; + strike?: boolean; +} + +/** The Git page shows the two real surfaces instead of a code sample: the editor + * inline blame widget and the project tree root branch suffix. Each coloured + * segment selects its attribute, as the shared preview does. */ +function GitPreview({ + vars, + ids, + reveal, +}: { + vars: CSSProperties; + ids: Set; + reveal: (attrId: string) => void; +}) { + const click = (attrId: string) => revealPreviewAttr(attrId, ids, reveal); + const blameSeg = (text: string, attrId: string, key: string) => ( + click(attrId)}> + {text} + + ); + // Mirrors rootSyncSuffix: branch, "/" separator, then ahead/behind counts or a struck zero. + const suffixOf = (root: GitPreviewRoot): GitPreviewSuffixSeg[] => { + const { branch, branchAttr, upstream, ahead, behind } = root; + const head: GitPreviewSuffixSeg = { text: branch, attr: branchAttr }; + if (!upstream) return [head]; + const counts: GitPreviewSuffixSeg[] = []; + if (ahead) + counts.push({ + text: String(ahead), + attr: "gitBranchChanged", + icon: "vcs-outgoing", + label: tx`${ahead} outgoing commits`, + }); + if (behind) + counts.push({ + text: String(behind), + attr: "gitBranchChanged", + icon: "vcs-incoming", + label: tx`${behind} incoming commits`, + }); + if (!counts.length) + counts.push({ text: "0", attr: "gitHeadTags", strike: true, label: tx`Up to date with ${upstream}` }); + return [head, { text: "/", attr: "gitHeadTags" }, ...counts]; + }; + return ( +
+
+
{tx("Editor inline blame")}
+
+ {GIT_EDITOR_LINES.map((line, i) => ( +
+ {i + 1} + + {line.segs.map(([text, attrId], j) => ( + click(attrId) : undefined} + > + {text} + + ))} + {line.blame && ( + + {blameSeg("Kitov, ", "gitBlameAuthor", "author")} + {blameSeg("3 days ago · ", "gitBlameDate", "date")} + {blameSeg("Add branch colours", "gitBlameSubject", "subject")} + {blameSeg(" (#123)", "gitBlameIssue", "issue")} + + )} + +
+ ))} +
+
+
+
{tx("Project View")}
+
+ {GIT_PREVIEW_ROOTS.map((root) => ( +
+ + + + + + + + {root.name} + + {suffixOf(root).map((s, j) => ( + click(s.attr)} + > + {s.strike ? {s.text} : s.text} + {s.icon && } + + ))} + + +
+ ))} +
+
+
+ ); +} + +export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landing?: boolean }) { + const translate = useTx(); + const [scheme, setScheme] = useSetting("editor.colorScheme", "global"); + const [overrides, setOverrides] = useSetting("editor.colorOverrides", "global"); + const [weight] = useSetting("editor.fontWeight"); + const [boldFontWeight] = useSetting("editor.boldFontWeight"); + const [redGreen = false] = useSetting("appearance.redGreenVision", "global"); + const [rawCustoms, setCustoms] = useSetting("editor.customSchemes", "global"); + const customs = useMemo(() => customSchemes(rawCustoms), [rawCustoms]); + const [report, setReport] = useState(""); + const [busy, setBusy] = useState(false); + // One scope per page: the scope's own name is the page, not a tree level. + const roots = useMemo(() => pageTree(scopes)[0]?.children ?? [], [scopes]); + const ids = useMemo(() => treeIds(roots), [roots]); + // A preview click on another sub-page starts this page on that attribute. + const crossReveal = + crossPageReveal && ids.has(crossPageReveal) ? ATTRIBUTES.find((x) => x.id === crossPageReveal) : undefined; + const [selected, setSelected] = useState(() => crossReveal?.id ?? "keyword"); + const [expanded, setExpanded] = useState>(() => + crossReveal ? new Set(ancestorKeys(crossReveal)) : new Set(), + ); + const [expandedFor, setExpandedFor] = useState(scopes); + if (expandedFor !== scopes) { + // Scope pages share this component; restart expansion on page switch. + setExpandedFor(scopes); + setExpanded(new Set(roots.filter((n) => n.children?.length).map((n) => n.key))); + } + // Language pages have their own attributes; keep the editor on a row of this page. + if (roots.length && !ids.has(selected)) setSelected(firstLeafId(roots)); + // Preview clicks reveal the attribute once the ancestors expanded (after the next render). + const treeRef = useRef(null); + const pendingReveal = useRef(null); + const reveal = (attrId: string) => { + const a = ATTRIBUTES.find((x) => x.id === attrId); + if (!a) return; + setSelected(attrId); + setExpanded((prev) => { + const next = new Set(prev); + for (const key of ancestorKeys(a)) next.add(key); + return next; + }); + pendingReveal.current = attrId; + }; + useEffect(() => { + if (pendingReveal.current) { + treeRef.current?.reveal(pendingReveal.current); + pendingReveal.current = null; + } else if (crossReveal) { + treeRef.current?.reveal(crossReveal.id); + } + crossPageReveal = null; + }); + const id = effectiveScheme(scheme, undefined, customs); + const mine = overrides?.[id]; + /** Keys of every group containing an overridden attribute, so the blue marks the path to the root. */ + const modifiedKeys = useMemo(() => { + const keys = new Set(); + for (const attrId of Object.keys(mine ?? {})) { + const a = ATTRIBUTES.find((x) => x.id === attrId); + if (!a) continue; + let key = ""; + for (const seg of attrSegs(a)) { + key += `/${seg}`; + keys.add(key); + } + } + return keys; + }, [mine]); + const attr = ATTRIBUTES.find((a) => a.id === selected); + const language = attr?.language; + const inherited = useMemo( + () => (attr ? resolvedAttribute(id, attr.id, customs, redGreen) : {}), + [id, attr, customs, redGreen], + ); + const vars = useMemo(() => { + const next = { + ...previewVars(id, mine, customs, language, redGreen), + ...fontWeightVars(weight, boldFontWeight), + } as CSSProperties & Record; + // Console preview sits on the console background, not the editor surface. + if (scopes[0] === "Console Colors" && next["--bg-console"]) next["--bg-editor"] = next["--bg-console"]; + return next; + }, [id, mine, customs, language, weight, boldFontWeight, scopes, redGreen]); + const baseVars = useMemo( + () => + ({ + ...previewVars(id, mine, customs, undefined, redGreen), + ...fontWeightVars(weight, boldFontWeight), + }) as CSSProperties, + [id, mine, customs, weight, boldFontWeight, redGreen], + ); + const update = (attrId: string, v: TextAttributesOverride | undefined) => { + const next: Overrides = { ...(overrides ?? {}) }; + const forScheme = { ...(next[id] ?? {}) }; + if (v) forScheme[attrId] = v; + else delete forScheme[attrId]; + if (Object.keys(forScheme).length) next[id] = forScheme; + else delete next[id]; + setOverrides(next); + }; + const schemes = listSchemes(customs); + const sample = SAMPLES[scopes[0] ?? ""] ?? SAMPLES["Language Defaults"]!; + const schemeName = schemes.find((s) => s.id === id)?.name ?? id; + const options: SelectOption[] = [ + { value: "theme-default", label: "Theme default" }, + ...schemes.map((s) => ({ value: s.id, label: s.name })), + ]; + const handlers = useRef Promise>>({}); + useEffect(() => { + handlers.current = { + import: async (file) => { + const { open } = await import("@/platform/dialog"); + const path = + file ?? + (await open({ + multiple: false, + // IDEA schemes ship as .icls, but the ones people download are frequently .xml. + filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls", "xml"] }], + })); + if (!path) return; + // A scheme element without a name is named after its file, as IntelliJ does. + const fallbackName = + path + .split(/[\\/]/) + .at(-1) + ?.replace(/\.[^.]+$/, "") || "Imported scheme"; + const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName); + let overwrite = false; + if (schemes.some((s) => s.name === parsed.scheme.name)) { + const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name); + const { button } = await ask({ + title: tx("Import Scheme"), + body: tx`A scheme named '${parsed.scheme.name}' already exists.`, + buttons: [ + ...(canOverwrite ? [{ id: "overwrite", label: tx("Overwrite") }] : []), + { id: "both", label: tx("Keep Both"), primary: true }, + ], + }); + if (button !== "overwrite" && button !== "both") return; + overwrite = button === "overwrite"; + } + const next = importScheme(customs, parsed.scheme, overwrite); + setCustoms(next.customs); + if (overwrite) + setOverrides(Object.fromEntries(Object.entries(overrides ?? {}).filter(([key]) => key !== next.id))); + setScheme(next.id); + setReport(tx`Applied ${parsed.applied} values; skipped ${parsed.skipped} unsupported or invalid values.`); + }, + export: async (file) => { + const { save } = await import("@/platform/dialog"); + const path = + file ?? + (await save({ + defaultPath: `${schemeName.replace(/[/\\:*?"<>|]/g, "_")}.icls`, + filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }], + })); + if (!path) return; + const bytes = Array.from(new TextEncoder().encode(exportIcls(id, customs, mine))); + // The save dialog already confirmed replacing an existing file. + await call(commands.fsDelete(path)).catch(() => {}); + await call(commands.fsCreateFileBytes(path, bytes)); + setReport(tx("Scheme exported.")); + }, + delete: async () => { + if ( + !customs[id] || + !(await confirm({ + title: tx("Delete Scheme"), + message: tx`Delete color scheme '${schemeName}'?`, + ok: tx("Delete"), + })) + ) + return; + const next = deleteScheme(customs, overrides ?? {}, scheme, id); + setCustoms(next.customs); + setOverrides(next.overrides); + setScheme(next.selected); + setReport(""); + }, + }; + }); + const pending = useRef(false); + useEffect( + () => + registerActions( + (["import", "export", "delete"] as const).map((name) => ({ + id: `editor.colorScheme.${name}`, + title: name === "import" ? "Import Scheme" : name === "export" ? "Export Scheme" : "Delete Scheme", + category: "Editor", + run: async ({ arg }) => { + if (pending.current) return; + pending.current = true; + setBusy(true); + try { + await handlers.current[name]!(typeof arg === "string" ? arg : undefined); + } catch (error) { + await showError( + tx("Import Scheme"), + error instanceof SchemeParseError + ? `${tx("Invalid .icls color scheme")}: ${error.message}` + : String(error), + ); + } finally { + pending.current = false; + setBusy(false); + } + }, + })), + ), + [], + ); + return ( +
+
+ + set({ effect: e as TextAttributesOverride["effect"] })} - className={styles.effectSelect} - aria-label="Effect" - /> - )} -
- - )} -
- The controls show the scheme's actual appearance; changes override it. -
-
- ); -} - -function ColorInput({ - value, - onChange, - label, -}: { - value: string; - onChange: (c: string | undefined) => void; - label: string; -}) { - const [draft, setDraft] = useState(null); - return ( - <> - - onChange(e.target.value)} - /> - - { - setDraft(e.target.value); - if (HEX_COLOR.test(e.target.value)) onChange(e.target.value.toLowerCase()); - }} - onBlur={() => setDraft(null)} - /> - - ); -} - -function ColorRow({ - label, - value, - inherited, - onChange, -}: { - label: string; - value: string | undefined; - inherited: string | undefined; - /** Undefined disables the row for attributes that cannot carry this channel. */ - onChange: ((c: string | undefined) => void) | undefined; -}) { - const cleared = value === CLEAR_COLOR; - const shown = cleared ? undefined : (value ?? inherited); - return ( -
- - onChange?.( - on - ? cleared - ? (inherited ?? "#808080") - : (shown ?? "#808080") - : inherited !== undefined - ? CLEAR_COLOR - : undefined, - ) - } - label={label} - /> - {shown !== undefined && undefined)} label={label} />} -
- ); -} - -/** Git preview sample: an editor caret line carrying the inline blame widget. */ -const GIT_EDITOR_LINES: { segs: Seg[]; blame?: boolean }[] = [ - { segs: [["function", "keyword"], [" "], ["syncRoot", "functionCall"], ["("], ["info", "parameter"], [") {"]] }, - { - segs: [ - [" "], - ["const", "keyword"], - [" "], - ["branch", "identifier"], - [" = "], - ["info", "parameter"], - ["."], - ["head", "identifier"], - [";"], - ], - blame: true, - }, - { segs: [["}"]] }, -]; - -/** A project tree root in the Git preview; its suffix mirrors rootSyncSuffix. */ -interface GitPreviewRoot { - name: string; - branch: string; - branchAttr: string; - upstream?: string; - ahead?: number; - behind?: number; -} -const GIT_PREVIEW_ROOTS: GitPreviewRoot[] = [ - { name: "openidea", branch: "main", branchAttr: "gitMasterWithRemote", upstream: "origin/main", ahead: 2, behind: 1 }, - { name: "legacy-app", branch: "master", branchAttr: "gitMasterWithoutRemote" }, - { name: "web-client", branch: "feature/login", branchAttr: "gitLocalBranch" }, - { name: "api-server", branch: "release/2.0", branchAttr: "gitTrackingBranch", upstream: "origin/release/2.0" }, -]; -interface GitPreviewSuffixSeg { - text: string; - attr: string; - icon?: "vcs-outgoing" | "vcs-incoming"; - label?: string; - strike?: boolean; -} - -/** The Git page shows the two real surfaces instead of a code sample: the editor - * inline blame widget and the project tree root branch suffix. Each coloured - * segment selects its attribute, as the shared preview does. */ -function GitPreview({ - vars, - ids, - reveal, -}: { - vars: CSSProperties; - ids: Set; - reveal: (attrId: string) => void; -}) { - const click = (attrId: string) => revealPreviewAttr(attrId, ids, reveal); - const blameSeg = (text: string, attrId: string, key: string) => ( - click(attrId)}> - {text} - - ); - // Mirrors rootSyncSuffix: branch, "/" separator, then ahead/behind counts or a struck zero. - const suffixOf = (root: GitPreviewRoot): GitPreviewSuffixSeg[] => { - const { branch, branchAttr, upstream, ahead, behind } = root; - const head: GitPreviewSuffixSeg = { text: branch, attr: branchAttr }; - if (!upstream) return [head]; - const counts: GitPreviewSuffixSeg[] = []; - if (ahead) - counts.push({ - text: String(ahead), - attr: "gitBranchChanged", - icon: "vcs-outgoing", - label: tx`${ahead} outgoing commits`, - }); - if (behind) - counts.push({ - text: String(behind), - attr: "gitBranchChanged", - icon: "vcs-incoming", - label: tx`${behind} incoming commits`, - }); - if (!counts.length) - counts.push({ text: "0", attr: "gitHeadTags", strike: true, label: tx`Up to date with ${upstream}` }); - return [head, { text: "/", attr: "gitHeadTags" }, ...counts]; - }; - return ( -
-
-
{tx("Editor inline blame")}
-
- {GIT_EDITOR_LINES.map((line, i) => ( -
- {i + 1} - - {line.segs.map(([text, attrId], j) => ( - click(attrId) : undefined} - > - {text} - - ))} - {line.blame && ( - - {blameSeg("Kitov, ", "gitBlameAuthor", "author")} - {blameSeg("3 days ago · ", "gitBlameDate", "date")} - {blameSeg("Add branch colours", "gitBlameSubject", "subject")} - {blameSeg(" (#123)", "gitBlameIssue", "issue")} - - )} - -
- ))} -
-
-
-
{tx("Project View")}
-
- {GIT_PREVIEW_ROOTS.map((root) => ( -
- - - - - - - - {root.name} - - {suffixOf(root).map((s, j) => ( - click(s.attr)} - > - {s.strike ? {s.text} : s.text} - {s.icon && } - - ))} - - -
- ))} -
-
-
- ); -} - -function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landing?: boolean }) { - const translate = useTx(); - const [scheme, setScheme] = useSetting("editor.colorScheme", "global"); - const [overrides, setOverrides] = useSetting("editor.colorOverrides", "global"); - const [weight] = useSetting("editor.fontWeight"); - const [boldFontWeight] = useSetting("editor.boldFontWeight"); - const [redGreen = false] = useSetting("appearance.redGreenVision", "global"); - const [rawCustoms, setCustoms] = useSetting("editor.customSchemes", "global"); - const customs = useMemo(() => customSchemes(rawCustoms), [rawCustoms]); - const [report, setReport] = useState(""); - const [busy, setBusy] = useState(false); - // One scope per page: the scope's own name is the page, not a tree level. - const roots = useMemo(() => pageTree(scopes)[0]?.children ?? [], [scopes]); - const ids = useMemo(() => treeIds(roots), [roots]); - // A preview click on another sub-page starts this page on that attribute. - const crossReveal = - crossPageReveal && ids.has(crossPageReveal) ? ATTRIBUTES.find((x) => x.id === crossPageReveal) : undefined; - const [selected, setSelected] = useState(() => crossReveal?.id ?? "keyword"); - const [expanded, setExpanded] = useState>(() => - crossReveal ? new Set(ancestorKeys(crossReveal)) : new Set(), - ); - const [expandedFor, setExpandedFor] = useState(scopes); - if (expandedFor !== scopes) { - // Scope pages share this component; restart expansion on page switch. - setExpandedFor(scopes); - setExpanded(new Set(roots.filter((n) => n.children?.length).map((n) => n.key))); - } - // Language pages have their own attributes; keep the editor on a row of this page. - if (roots.length && !ids.has(selected)) setSelected(firstLeafId(roots)); - // Preview clicks reveal the attribute once the ancestors expanded (after the next render). - const treeRef = useRef(null); - const pendingReveal = useRef(null); - const reveal = (attrId: string) => { - const a = ATTRIBUTES.find((x) => x.id === attrId); - if (!a) return; - setSelected(attrId); - setExpanded((prev) => { - const next = new Set(prev); - for (const key of ancestorKeys(a)) next.add(key); - return next; - }); - pendingReveal.current = attrId; - }; - useEffect(() => { - if (pendingReveal.current) { - treeRef.current?.reveal(pendingReveal.current); - pendingReveal.current = null; - } else if (crossReveal) { - treeRef.current?.reveal(crossReveal.id); - } - crossPageReveal = null; - }); - const id = effectiveScheme(scheme, undefined, customs); - const mine = overrides?.[id]; - /** Keys of every group containing an overridden attribute, so the blue marks the path to the root. */ - const modifiedKeys = useMemo(() => { - const keys = new Set(); - for (const attrId of Object.keys(mine ?? {})) { - const a = ATTRIBUTES.find((x) => x.id === attrId); - if (!a) continue; - let key = ""; - for (const seg of attrSegs(a)) { - key += `/${seg}`; - keys.add(key); - } - } - return keys; - }, [mine]); - const attr = ATTRIBUTES.find((a) => a.id === selected); - const language = attr?.language; - const inherited = useMemo( - () => (attr ? resolvedAttribute(id, attr.id, customs, redGreen) : {}), - [id, attr, customs, redGreen], - ); - const vars = useMemo(() => { - const next = { - ...previewVars(id, mine, customs, language, redGreen), - ...fontWeightVars(weight, boldFontWeight), - } as CSSProperties & Record; - // Console preview sits on the console background, not the editor surface. - if (scopes[0] === "Console Colors" && next["--bg-console"]) next["--bg-editor"] = next["--bg-console"]; - return next; - }, [id, mine, customs, language, weight, boldFontWeight, scopes, redGreen]); - const baseVars = useMemo( - () => - ({ - ...previewVars(id, mine, customs, undefined, redGreen), - ...fontWeightVars(weight, boldFontWeight), - }) as CSSProperties, - [id, mine, customs, weight, boldFontWeight, redGreen], - ); - const update = (attrId: string, v: TextAttributesOverride | undefined) => { - const next: Overrides = { ...(overrides ?? {}) }; - const forScheme = { ...(next[id] ?? {}) }; - if (v) forScheme[attrId] = v; - else delete forScheme[attrId]; - if (Object.keys(forScheme).length) next[id] = forScheme; - else delete next[id]; - setOverrides(next); - }; - const schemes = listSchemes(customs); - const sample = SAMPLES[scopes[0] ?? ""] ?? SAMPLES["Language Defaults"]!; - const schemeName = schemes.find((s) => s.id === id)?.name ?? id; - const options: SelectOption[] = [ - { value: "theme-default", label: "Theme default" }, - ...schemes.map((s) => ({ value: s.id, label: s.name })), - ]; - const handlers = useRef Promise>>({}); - useEffect(() => { - handlers.current = { - import: async (file) => { - const { open } = await import("@/platform/dialog"); - const path = - file ?? - (await open({ - multiple: false, - // IDEA schemes ship as .icls, but the ones people download are frequently .xml. - filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls", "xml"] }], - })); - if (!path) return; - // A scheme element without a name is named after its file, as IntelliJ does. - const fallbackName = - path - .split(/[\\/]/) - .at(-1) - ?.replace(/\.[^.]+$/, "") || "Imported scheme"; - const parsed = parseIcls(await call(commands.fsReadText(path)), fallbackName); - let overwrite = false; - if (schemes.some((s) => s.name === parsed.scheme.name)) { - const canOverwrite = Object.values(customs).some((s) => s.name === parsed.scheme.name); - const { button } = await ask({ - title: tx("Import Scheme"), - body: tx`A scheme named '${parsed.scheme.name}' already exists.`, - buttons: [ - ...(canOverwrite ? [{ id: "overwrite", label: tx("Overwrite") }] : []), - { id: "both", label: tx("Keep Both"), primary: true }, - ], - }); - if (button !== "overwrite" && button !== "both") return; - overwrite = button === "overwrite"; - } - const next = importScheme(customs, parsed.scheme, overwrite); - setCustoms(next.customs); - if (overwrite) - setOverrides(Object.fromEntries(Object.entries(overrides ?? {}).filter(([key]) => key !== next.id))); - setScheme(next.id); - setReport(tx`Applied ${parsed.applied} values; skipped ${parsed.skipped} unsupported or invalid values.`); - }, - export: async (file) => { - const { save } = await import("@/platform/dialog"); - const path = - file ?? - (await save({ - defaultPath: `${schemeName.replace(/[/\\:*?"<>|]/g, "_")}.icls`, - filters: [{ name: tx("IntelliJ Color Scheme"), extensions: ["icls"] }], - })); - if (!path) return; - const bytes = Array.from(new TextEncoder().encode(exportIcls(id, customs, mine))); - // The save dialog already confirmed replacing an existing file. - await call(commands.fsDelete(path)).catch(() => {}); - await call(commands.fsCreateFileBytes(path, bytes)); - setReport(tx("Scheme exported.")); - }, - delete: async () => { - if ( - !customs[id] || - !(await confirm({ - title: tx("Delete Scheme"), - message: tx`Delete color scheme '${schemeName}'?`, - ok: tx("Delete"), - })) - ) - return; - const next = deleteScheme(customs, overrides ?? {}, scheme, id); - setCustoms(next.customs); - setOverrides(next.overrides); - setScheme(next.selected); - setReport(""); - }, - }; - }); - const pending = useRef(false); - useEffect( - () => - registerActions( - (["import", "export", "delete"] as const).map((name) => ({ - id: `editor.colorScheme.${name}`, - title: name === "import" ? "Import Scheme" : name === "export" ? "Export Scheme" : "Delete Scheme", - category: "Editor", - run: async ({ arg }) => { - if (pending.current) return; - pending.current = true; - setBusy(true); - try { - await handlers.current[name]!(typeof arg === "string" ? arg : undefined); - } catch (error) { - await showError( - tx("Import Scheme"), - error instanceof SchemeParseError - ? `${tx("Invalid .icls color scheme")}: ${error.message}` - : String(error), - ); - } finally { - pending.current = false; - setBusy(false); - } - }, - })), - ), - [], - ); - return ( -
-
- -