diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index 3043a7ad3..b0844ca1e 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -17,7 +17,7 @@ import { registerMenuGroup, registerMenuSlotItem, registerOverlay, - registerSettingsPage, + registerSettingsPages, registerStatusItem, registerToolWindow, toolWindowService, @@ -55,8 +55,8 @@ import { replyActions } from "./replyActions"; /** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */ export function activateSettingsPages(): () => void { - const disposers = [ - registerSettingsPage({ + return registerSettingsPages([ + { id: REGISTRY_PAGE, title: "Coding Agents", group: AGENTS_GROUP, @@ -64,8 +64,8 @@ export function activateSettingsPages(): () => void { order: 450, keywords: ["agent", "acp", "registry", "install", "update", "coding agent"], component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)), - }), - registerSettingsPage({ + }, + { id: WORKING_STATUS_PAGE, title: "Working Status", group: AGENTS_GROUP, @@ -73,25 +73,24 @@ export function activateSettingsPages(): () => void { order: 465, keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"], component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)), - }), - registerSettingsPage({ + }, + { id: MCP_PAGE, title: "External MCP Servers", group: AGENTS_GROUP, order: 475, keywords: ["mcp", "model context protocol", "servers", "tools", "agent"], component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)), - }), - registerSettingsPage({ + }, + { id: POLICY_PAGE, title: "Command Permissions", group: AGENTS_GROUP, order: 490, keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"], component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)), - }), - ]; - return () => disposers.reverse().forEach((d) => d()); + }, + ]); } export function activate(): () => void { diff --git a/src/features/plugins/settings.tsx b/src/features/plugins/settings.tsx index ea78b0ba6..f593d63a2 100644 --- a/src/features/plugins/settings.tsx +++ b/src/features/plugins/settings.tsx @@ -2,7 +2,7 @@ import { useMemo, useRef, useState } from "react"; import { tx } from "@/platform/i18n"; import { Button, Checkbox, IconButton, Input, Select, T } from "@/ui"; -import { registerSettingsPage, useSettingsForm } from "@/workbench/contributions"; +import { registerSettingsPages, useSettingsForm } from "@/workbench/contributions"; import { pluginsBackend } from "./backend"; import { localizeContributions, usePluginCatalogs } from "./pluginText"; import { itemsOf } from "./projection"; @@ -372,24 +372,20 @@ function PluginSecrets({ pluginId }: { pluginId: string }) { export function projectSettings(pluginId: string, decl: SettingsDecl): () => void { const id = pluginSettingsPageId(pluginId); const pages = decl.pages ?? []; - const dispose = [ - registerSettingsPage({ + return registerSettingsPages([ + { id, title: decl.title, projectScope: true, keywords: ["plugin", pluginId, ...keywords(decl)], component: pages.length ? undefined : settingsPage(pluginId, decl), - }), - ]; - for (const p of pages) - dispose.push( - registerSettingsPage({ - id: `${id}.settings:${p.id}`, - title: p.title, - projectScope: true, - keywords: [pluginId, decl.title, ...keywords(p)], - component: settingsPage(pluginId, p), - }), - ); - return () => dispose.forEach((d) => d()); + }, + ...pages.map((p) => ({ + id: `${id}.settings:${p.id}`, + title: p.title, + projectScope: true, + keywords: [pluginId, decl.title, ...keywords(p)], + component: settingsPage(pluginId, p), + })), + ]); } diff --git a/src/features/settings/__tests__/batchRegistration.test.ts b/src/features/settings/__tests__/batchRegistration.test.ts new file mode 100644 index 000000000..b9b5c69e7 --- /dev/null +++ b/src/features/settings/__tests__/batchRegistration.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it, vi } from "vitest"; + +const listeners = new Map void>(); +const emitTo = vi.fn(() => Promise.resolve()); + +vi.mock("@tauri-apps/api/event", () => ({ + emitTo: (...args: unknown[]) => (emitTo as (...a: unknown[]) => Promise)(...args), +})); +vi.mock("@tauri-apps/api/webviewWindow", () => ({ + getCurrentWebviewWindow: () => ({ + label: "settings-main", + listen: (event: string, cb: (e: { payload: unknown }) => void) => { + listeners.set(event, cb); + return Promise.resolve(() => listeners.delete(event)); + }, + }), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, isTauri: () => true }; +}); + +import { executeAction, getAction, registerAction, useActions } from "@/platform/actions"; +import { registerSettingsPage, registerSettingsPages, useSettingsPages } from "@/workbench/contributions"; +import { installActionProxies, type ActionInfo } from "../window/bridge"; + +describe("registerSettingsPages", () => { + it("registers and disposes a page batch in one store update each while keeping later overrides", () => { + let updates = 0; + const off = useSettingsPages.subscribe(() => { + updates += 1; + }); + const disposeBatch = registerSettingsPages([ + { id: "batch.a", title: "A" }, + { id: "batch.b", title: "B" }, + { id: "batch.c", title: "C" }, + ]); + const disposeOverride = registerSettingsPage({ id: "batch.b", title: "B2" }); + try { + expect(updates).toBe(2); + expect(useSettingsPages.getState().pages.get("batch.a")?.title).toBe("A"); + expect(useSettingsPages.getState().pages.get("batch.b")?.title).toBe("B2"); + disposeBatch(); + expect(updates).toBe(3); + expect(useSettingsPages.getState().pages.has("batch.a")).toBe(false); + expect(useSettingsPages.getState().pages.get("batch.b")?.title).toBe("B2"); + expect(useSettingsPages.getState().pages.has("batch.c")).toBe(false); + } finally { + disposeOverride(); + off(); + } + }); +}); + +describe("installActionProxies", () => { + it("batches parent action syncs and keeps local actions authoritative", async () => { + const localRun = vi.fn(); + const disposeLocal = registerAction({ id: "local.win", title: "Local", run: localRun }); + const dispose = installActionProxies("main"); + await vi.waitFor(() => expect(listeners.has("openidea://settings/actions")).toBe(true)); + + let updates = 0; + const off = useActions.subscribe(() => { + updates += 1; + }); + const batch: ActionInfo[] = [ + { id: "local.win", title: "Remote Should Lose" }, + ...Array.from({ length: 50 }, (_, i) => ({ id: `remote.act.${i}`, title: `Remote ${i}` })), + ]; + try { + listeners.get("openidea://settings/actions")!({ payload: batch }); + // 50 remote actions register in a single store update instead of 50. + expect(updates).toBe(1); + expect(getAction("local.win")?.title).toBe("Local"); + expect(getAction("remote.act.49")?.title).toBe("Remote 49"); + + await executeAction("remote.act.3", "arg3"); + expect(emitTo).toHaveBeenCalledWith("main", "openidea://settings/exec", { id: "remote.act.3", arg: "arg3" }); + + // Re-syncing disposes previous proxies in 1 update and registers the new list in 1 update. + listeners.get("openidea://settings/actions")!({ payload: [{ id: "remote.act.0", title: "Updated 0" }] }); + expect(updates).toBe(3); + expect(getAction("remote.act.49")).toBeUndefined(); + expect(getAction("remote.act.0")?.title).toBe("Updated 0"); + } finally { + off(); + dispose(); + disposeLocal(); + } + }); +}); diff --git a/src/features/settings/appearanceRuntime.ts b/src/features/settings/appearanceRuntime.ts index 927ebd4f7..2f395ef93 100644 --- a/src/features/settings/appearanceRuntime.ts +++ b/src/features/settings/appearanceRuntime.ts @@ -293,6 +293,7 @@ export function installIdleSave(config: () => { enabled: boolean; seconds: numbe */ export function installIconFont(root: HTMLElement = document.documentElement): () => void { let cancelled = false; + let idleId: number | undefined; const resolve = () => void loadSystemFonts().then(() => { if (cancelled) return; @@ -301,16 +302,16 @@ export function installIconFont(root: HTMLElement = document.documentElement): ( const faces = uiIconFaces(installed); if (faces.length) root.style.setProperty("--font-icons", faces.join(", ")); }); - if (typeof requestIdleCallback === "function") { - const id = requestIdleCallback(resolve, { timeout: 5000 }); - return () => { - cancelled = true; - cancelIdleCallback(id); - }; - } - const timer = setTimeout(resolve, 200); + // Wait past initial startup IPC gaps before scheduling idle font enumeration; + // in Chromium/WebView2 `requestIdleCallback` otherwise fires at ~5 ms between startup IPCs. + const timer = setTimeout(() => { + if (cancelled) return; + if (typeof requestIdleCallback === "function") idleId = requestIdleCallback(resolve, { timeout: 5000 }); + else resolve(); + }, 500); return () => { cancelled = true; clearTimeout(timer); + if (idleId !== undefined && typeof cancelIdleCallback === "function") cancelIdleCallback(idleId); }; } diff --git a/src/features/settings/components/FontPicker.test.tsx b/src/features/settings/components/FontPicker.test.tsx index eaf386ad0..836d8ffa0 100644 --- a/src/features/settings/components/FontPicker.test.tsx +++ b/src/features/settings/components/FontPicker.test.tsx @@ -2,6 +2,7 @@ import { beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen } from "@testing-library/react"; import { useState } from "react"; import { FontPicker } from "./FontPicker"; +import * as systemFonts from "@/platform/systemFonts"; import { bundledFonts, useSystemFontStore } from "@/platform/systemFonts"; beforeEach(() => @@ -85,3 +86,25 @@ it("quietly keeps selections and manual input through fallback and native retry" fireEvent.focus(input); expect(screen.getByRole("option", { name: /New Native Family/ })).toBeInTheDocument(); }); + +it("skips font enumeration while disabled, defers on mount when enabled, and loads immediately on focus", () => { + vi.useFakeTimers(); + const spy = vi.spyOn(systemFonts, "loadSystemFonts").mockResolvedValue(); + useSystemFontStore.setState({ status: "idle", source: "bundled", fonts: bundledFonts }); + try { + const view = render( {}} disabled />); + vi.advanceTimersByTime(2000); + expect(spy).not.toHaveBeenCalled(); + + view.rerender( {}} />); + // Not called synchronously during initial render/mount commit. + expect(spy).not.toHaveBeenCalled(); + + // Focusing before the idle timer fires triggers enumeration immediately. + fireEvent.focus(screen.getByRole("combobox")); + expect(spy).toHaveBeenCalledTimes(1); + } finally { + spy.mockRestore(); + vi.useRealTimers(); + } +}); diff --git a/src/features/settings/components/FontPicker.tsx b/src/features/settings/components/FontPicker.tsx index 55812964d..d18ec07e2 100644 --- a/src/features/settings/components/FontPicker.tsx +++ b/src/features/settings/components/FontPicker.tsx @@ -1,4 +1,4 @@ -import { useId, useRef, useState } from "react"; +import { useId, useMemo, useRef, useState } from "react"; import { IconButton, Input, Popup, T } from "@/ui"; import { useTx } from "@/platform/i18n"; import { loadSystemFonts, useSystemFonts } from "@/platform/systemFonts"; @@ -23,7 +23,7 @@ export function FontPicker({ allowEmpty?: boolean; }) { const tx = useTx(); - const { fonts, status } = useSystemFonts(); + const { fonts, status } = useSystemFonts(!disabled); const listId = useId(); const input = useRef(null); const [open, setOpen] = useState(false); @@ -31,8 +31,24 @@ export function FontPicker({ const [active, setActive] = useState(-1); const text = draft?.source === value ? draft.text : value; const query = draft?.source === value ? text.trim().toLocaleLowerCase() : ""; - const suggestions = fonts.filter((f) => (!monoOnly || f.monospaced) && f.name.toLocaleLowerCase().includes(query)); - const known = fonts.some((f) => f.name.toLocaleLowerCase() === value.trim().toLocaleLowerCase()); + const suggestions = useMemo( + () => + open && !disabled + ? fonts.filter((f) => (!monoOnly || f.monospaced) && f.name.toLocaleLowerCase().includes(query)) + : [], + [open, disabled, fonts, monoOnly, query], + ); + const trimmed = value.trim(); + const known = useMemo( + () => + status === "ready" && trimmed + ? fonts.some((f) => f.name.toLocaleLowerCase() === trimmed.toLocaleLowerCase()) + : true, + [status, trimmed, fonts], + ); + const ensureLoaded = () => { + if (status === "idle") void loadSystemFonts(); + }; const message = status === "loading" ? "Loading system fonts…" @@ -64,15 +80,20 @@ export function FontPicker({ disabled={disabled} placeholder={allowEmpty ? "None" : undefined} onFocus={() => { + ensureLoaded(); setOpen(true); setActive(-1); }} - onClick={() => setOpen(true)} + onClick={() => { + ensureLoaded(); + setOpen(true); + }} onBlur={() => { setOpen(false); setDraft(null); }} onChange={(e) => { + ensureLoaded(); const next = e.target.value; const valid = allowEmpty || !!next.trim(); setDraft({ source: valid ? next : value, text: next }); @@ -84,6 +105,7 @@ export function FontPicker({ if (e.nativeEvent.isComposing) return; if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); + ensureLoaded(); setOpen(true); const next = Math.max(0, Math.min(suggestions.length - 1, active + (e.key === "ArrowDown" ? 1 : -1))); setActive(next); diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts index 42f5a1901..c565c5153 100644 --- a/src/features/settings/index.ts +++ b/src/features/settings/index.ts @@ -133,22 +133,7 @@ export function activate(): () => void { unloadBuiltinPages, registerOverlay({ id: "settings.dialog", component: LazySettingsDialog }), registerOverlay({ id: "settings.projectStructure", component: LazyProjectStructureDialog }), - registerActions(zoomActions()), - registerActions(appearanceToggleActions()), - registerActions([presentationAssistantAction()]), registerOverlay({ id: "settings.presentationAssistant", component: PresentationAssistant }), - registerActions(navigationBarActions()), - registerActions(settingsActions((page, newProjects) => void showSettings(page, newProjects))), - registerActions([ - { - id: "file.projectStructure", - title: "Project Structure…", - category: "File", - icon: "folder", - keywords: ["project structure", "sdk", "jdk", "modules", "libraries", "facets", "artifacts", "sources"], - run: ({ arg }) => openProjectStructure(typeof arg === "string" ? arg : undefined), - }, - ]), activateFileTypes(), registerOverlay({ id: "settings.assignShortcut", @@ -157,6 +142,19 @@ export function activate(): () => void { ), }), registerActions([ + ...zoomActions(), + ...appearanceToggleActions(), + presentationAssistantAction(), + ...navigationBarActions(), + ...settingsActions((page, newProjects) => void showSettings(page, newProjects)), + { + id: "file.projectStructure", + title: "Project Structure…", + category: "File", + icon: "folder", + keywords: ["project structure", "sdk", "jdk", "modules", "libraries", "facets", "artifacts", "sources"], + run: ({ arg }) => openProjectStructure(typeof arg === "string" ? arg : undefined), + }, { // Search Everywhere's ⌥↵ on an action (arg: the action id). id: "settings.assignShortcut", diff --git a/src/features/settings/pages/registry.tsx b/src/features/settings/pages/registry.tsx index 622a55371..2b398df90 100644 --- a/src/features/settings/pages/registry.tsx +++ b/src/features/settings/pages/registry.tsx @@ -2,7 +2,7 @@ import { commands } from "@/platform/ipc"; import { UPDATES_PAGE } from "./updates"; import { onLanguageListChanged } from "@/platform/languageList"; -import { registerSettingsPage, type SettingsPageContribution } from "@/workbench/contributions"; +import { registerSettingsPage, registerSettingsPages, type SettingsPageContribution } from "@/workbench/contributions"; import { BEHAVIOR_PAGES } from "./behavior"; import { BUILTIN_PAGES as CORE_PAGES } from "./builtins"; import { DEPLOYMENT_PAGES } from "./deployment"; @@ -60,29 +60,28 @@ function toContribution(spec: PageSpec): SettingsPageContribution { } export function registerBuiltinPages(): () => void { - const disposers = BUILTIN_PAGES.filter((spec) => spec !== UPDATES_PAGE).map((spec) => - registerSettingsPage(toContribution(spec)), + const disposeBuiltins = registerSettingsPages( + BUILTIN_PAGES.filter((spec) => spec !== UPDATES_PAGE).map(toContribution), ); // Code Style › pages come from the backend's language list, which plugins change. let live = true; + let disposeUpdates = () => {}; void commands .appBuildInfo() .then((info) => { - if (live && info.updates) disposers.push(registerSettingsPage(toContribution(UPDATES_PAGE))); + if (live && info.updates) disposeUpdates = registerSettingsPage(toContribution(UPDATES_PAGE)); }) .catch(() => {}); - let languagePages: (() => void)[] = []; + let disposeLanguagePages = () => {}; let generation = 0; const loadLanguagePages = () => { const mine = ++generation; void codeStyleLanguagePages() .then((pages) => { if (!live || mine !== generation) return; - languagePages.forEach((d) => d()); - languagePages = pages.map((spec) => { - specs.set(spec.id, spec); - return registerSettingsPage(toContribution(spec)); - }); + disposeLanguagePages(); + for (const spec of pages) specs.set(spec.id, spec); + disposeLanguagePages = registerSettingsPages(pages.map(toContribution)); }) .catch(() => {}); }; @@ -91,7 +90,8 @@ export function registerBuiltinPages(): () => void { return () => { live = false; unsubscribe(); - languagePages.forEach((d) => d()); - disposers.forEach((d) => d()); + disposeLanguagePages(); + disposeUpdates(); + disposeBuiltins(); }; } diff --git a/src/features/settings/window/bridge.ts b/src/features/settings/window/bridge.ts index 44077c095..2ee0ad630 100644 --- a/src/features/settings/window/bridge.ts +++ b/src/features/settings/window/bridge.ts @@ -11,7 +11,7 @@ */ import { emitTo } from "@tauri-apps/api/event"; import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; -import { allActions, executeAction, getAction, registerAction, useActions, type Action } from "@/platform/actions"; +import { allActions, executeAction, getAction, registerActions, useActions, type Action } from "@/platform/actions"; import { isTauri } from "@/platform/ipc"; const SETTINGS_PREFIX = "settings-"; @@ -99,19 +99,19 @@ export function installSettingsHost(): () => void { * the parent. Actions registered locally (e.g. `file.settings`) win. */ export function installActionProxies(parent: string): () => void { - const proxies = new Map void>(); + let disposeProxies = () => {}; const sync = (infos: ActionInfo[]) => { - proxies.forEach((dispose) => dispose()); - proxies.clear(); + disposeProxies(); + const proxies: Action[] = []; for (const info of infos) { if (getAction(info.id)) continue; - const proxy: Action = { ...info, run: ({ arg }) => void emitTo(parent, EXEC, { id: info.id, arg }) }; - proxies.set(info.id, registerAction(proxy)); + proxies.push({ ...info, run: ({ arg }) => void emitTo(parent, EXEC, { id: info.id, arg }) }); } + disposeProxies = registerActions(proxies); }; const off = listen(ACTIONS, sync, () => void emitTo(parent, REQUEST_ACTIONS, null).catch(() => {})); return () => { off(); - proxies.forEach((dispose) => dispose()); + disposeProxies(); }; } diff --git a/src/features/templates/index.ts b/src/features/templates/index.ts index 4761a6dbc..ea38e44bf 100644 --- a/src/features/templates/index.ts +++ b/src/features/templates/index.ts @@ -4,13 +4,13 @@ * templates ("New ▸ …"). */ import { lazyComponent } from "@/ui"; -import { registerAction, registerActions, type Action } from "@/platform/actions"; +import { registerActions, type Action } from "@/platform/actions"; import { activeEditor, registerEditorContribution } from "@/editor/api"; import { notifications, registerMenuGroup, registerOverlay, - registerSettingsPage, + registerSettingsPages, hasRunConfiguration, type MenuGroupContext, } from "@/workbench/contributions"; @@ -149,10 +149,10 @@ function registerNewMenuGroups(): () => void { } function registerFileTemplateActions(): () => void { - let disposers: Array<() => void> = []; + let dispose = () => {}; const sync = (templates: FileTemplate[]) => { - disposers.forEach((d) => d()); - disposers = templates.filter((t) => t.enabled !== false).map((t) => registerAction(newFileAction(t))); + dispose(); + dispose = registerActions(templates.filter((t) => t.enabled !== false).map(newFileAction)); }; sync(useFileTemplates.getState().templates); const unsub = useFileTemplates.subscribe((s, prev) => { @@ -160,22 +160,22 @@ function registerFileTemplateActions(): () => void { }); return () => { unsub(); - disposers.forEach((d) => d()); + dispose(); }; } /** Live / postfix / file template pages (also used by the Settings window). */ export function activateSettingsPages(): () => void { - const disposers = [ - registerSettingsPage({ + return registerSettingsPages([ + { id: "editor.liveTemplates", title: "Live Templates", group: "Editor", order: 28, keywords: ["snippet", "abbreviation", "surround", "template"], component: lazyComponent(() => import("./settings/LiveTemplatesPage").then((m) => m.LiveTemplatesPage)), - }), - registerSettingsPage({ + }, + { // IDEA: Editor › General › Postfix Completion. id: "editor.general.postfixCompletion", title: "Postfix Completion", @@ -183,17 +183,16 @@ export function activateSettingsPages(): () => void { order: 7, keywords: ["postfix", "template", ".if", ".var", ".for"], component: lazyComponent(() => import("./settings/PostfixPage").then((m) => m.PostfixPage)), - }), - registerSettingsPage({ + }, + { id: "editor.fileTemplates", title: "File and Code Templates", group: "Editor", order: 26, keywords: ["new file", "class", "template", "package", "includes", "file header", "code", "scheme", "reformat"], component: lazyComponent(() => import("./settings/FileTemplatesPage").then((m) => m.FileTemplatesPage)), - }), - ]; - return () => disposers.reverse().forEach((d) => d()); + }, + ]); } export function activate(): () => void { diff --git a/src/platform/actions.test.ts b/src/platform/actions.test.ts index a2fbdead3..587bba0a6 100644 --- a/src/platform/actions.test.ts +++ b/src/platform/actions.test.ts @@ -100,21 +100,28 @@ it("checks argument-specific enablement before dispatch", async () => { } }); -it("registers a batch with one store update and disposes every action", () => { +it("registers and disposes a batch with one store update each while keeping later overrides", () => { const updates: number[] = []; const off = useActions.subscribe((s) => updates.push(s.actions.size)); const dispose = registerActions([ { id: "test.batch.one", title: "One", run: () => {} }, { id: "test.batch.two", title: "Two", run: () => {} }, + { id: "test.batch.three", title: "Three", run: () => {} }, ]); + const disposeOverride = registerAction({ id: "test.batch.two", title: "Overridden", run: () => {} }); try { - expect(updates).toHaveLength(1); + expect(updates).toHaveLength(2); expect(getAction("test.batch.one")?.title).toBe("One"); - expect(getAction("test.batch.two")?.title).toBe("Two"); - } finally { + expect(getAction("test.batch.two")?.title).toBe("Overridden"); + expect(getAction("test.batch.three")?.title).toBe("Three"); dispose(); + // Disposing the 3-action batch fires only 1 store update and leaves the overridden id intact. + expect(updates).toHaveLength(3); + expect(getAction("test.batch.one")).toBeUndefined(); + expect(getAction("test.batch.two")?.title).toBe("Overridden"); + expect(getAction("test.batch.three")).toBeUndefined(); + } finally { + disposeOverride(); off(); } - expect(getAction("test.batch.one")).toBeUndefined(); - expect(getAction("test.batch.two")).toBeUndefined(); }); diff --git a/src/platform/actions.ts b/src/platform/actions.ts index f3701944e..58e424fed 100644 --- a/src/platform/actions.ts +++ b/src/platform/actions.ts @@ -140,17 +140,34 @@ export function registerAction(action: Action): () => void { } export function registerActions(actions: Action[]): () => void { - const disposers = actions.map(addSource); + const owned = new Map(); + for (const action of actions) { + sources.set(action.id, action); + owned.set(action.id, action); + } // One state update for the batch: features register dozens of actions at start-up, // and cloning the whole map per action made that O(n²). - if (actions.length) { + if (owned.size) { useActions.setState((s) => { const next = new Map(s.actions); - for (const action of actions) next.set(action.id, localize(action)); + for (const [id, action] of owned) next.set(id, localize(action)); return { actions: next }; }); } - return () => disposers.forEach((d) => d()); + return () => { + const removed: string[] = []; + for (const [id, action] of owned) { + if (sources.get(id) !== action) continue; + sources.delete(id); + removed.push(id); + } + if (!removed.length) return; + useActions.setState((s) => { + const next = new Map(s.actions); + for (const id of removed) next.delete(id); + return { actions: next }; + }); + }; } export function getAction(id: string): Action | undefined { diff --git a/src/platform/systemFonts.ts b/src/platform/systemFonts.ts index 71a3aa0d6..83fc1621c 100644 --- a/src/platform/systemFonts.ts +++ b/src/platform/systemFonts.ts @@ -62,10 +62,22 @@ export function loadSystemFonts(refresh = false): Promise { }); return pending; } -export function useSystemFonts() { +export function useSystemFonts(enabled = true) { const state = useSystemFontStore(); useEffect(() => { - void loadSystemFonts(); - }, []); + if (!enabled || useSystemFontStore.getState().status !== "idle") return; + let idleId: number | undefined; + const timer = setTimeout(() => { + if (typeof requestIdleCallback === "function") { + idleId = requestIdleCallback(() => void loadSystemFonts(), { timeout: 1000 }); + } else { + void loadSystemFonts(); + } + }, 250); + return () => { + clearTimeout(timer); + if (idleId !== undefined && typeof cancelIdleCallback === "function") cancelIdleCallback(idleId); + }; + }, [enabled]); return state; } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index ab9f9076c..1583895d7 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -1212,6 +1212,28 @@ export function registerSettingsPage(page: SettingsPageContribution): () => void }); } +/** Registers a batch of settings pages in one store update; returns a batched disposer. */ +export function registerSettingsPages(list: SettingsPageContribution[]): () => void { + if (!list.length) return () => {}; + const owned = new Map(); + for (const page of list) owned.set(page.id, page); + useSettingsPages.setState((s) => { + const pages = new Map(s.pages); + for (const [id, page] of owned) pages.set(id, page); + return { pages }; + }); + return () => + useSettingsPages.setState((s) => { + let next: Map | null = null; + for (const [id, page] of owned) { + if (s.pages.get(id) !== page) continue; + next ??= new Map(s.pages); + next.delete(id); + } + return next ? { pages: next } : s; + }); +} + /** A searchable settings entry: a page, or an option label on it (Search Everywhere's "Settings: …" items). */ export interface SettingsSearchEntry { pageId: string;