An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: https://github.com/siyuan-note/siyuan/issues/19046
Vanessa7af3c50c58a5
diff --git a/app/src/boot/globalEvent/globalShortcut.ts b/app/src/boot/globalEvent/globalShortcut.tsnew file mode 100644index 0000000000..50124f7c21--- /dev/null+++ b/app/src/boot/globalEvent/globalShortcut.ts@@ -0,0 +1,52 @@+import type {App} from "../../index";+import {Constants} from "../../constants";+import {isWindow} from "../../util/functions";+import {clearDisallowedTextInputHotkey} from "../../util/hotKeyPolicy";+/// #if !BROWSER+import {ipcRenderer} from "electron";+/// #endif++export const sendGlobalShortcut = (app: App) => {+ /// #if !BROWSER+ if (isWindow()) {+ return;+ }+ const hotkeys = [clearDisallowedTextInputHotkey(window.siyuan.config.keymap.general.toggleWin.custom)];+ app.plugins.forEach(plugin => {+ plugin.commands.forEach(command => {+ if (command.globalCallback && command.customHotkey) {+ const hotkey = clearDisallowedTextInputHotkey(command.customHotkey);+ if (hotkey) {+ hotkeys.push(hotkey);+ }+ }+ });+ });+ ipcRenderer.send(Constants.SIYUAN_HOTKEY, {+ languages: window.siyuan.languages["_trayMenu"],+ hotkeys+ });+ /// #endif+};++export const sendUnregisterGlobalShortcut = (app: App) => {+ /// #if !BROWSER+ if (isWindow()) {+ return;+ }+ ipcRenderer.send(Constants.SIYUAN_CMD, {+ cmd: "unregisterGlobalShortcut",+ accelerator: window.siyuan.config.keymap.general.toggleWin.custom+ });+ app.plugins.forEach(plugin => {+ plugin.commands.forEach(command => {+ if (command.globalCallback) {+ ipcRenderer.send(Constants.SIYUAN_CMD, {+ cmd: "unregisterGlobalShortcut",+ accelerator: command.customHotkey+ });+ }+ });+ });+ /// #endif+};diff --git a/app/src/command/context.ts b/app/src/command/context.tsnew file mode 100644index 0000000000..95ef16d001--- /dev/null+++ b/app/src/command/context.ts@@ -0,0 +1,252 @@+import type {App} from "../index";+import {getFrontend} from "../util/functions";+import {hasClosestBlock, hasClosestByClassName, hasClosestByTag} from "../protyle/util/hasClosest";+import {+ cloneCommandRange,+ collectCommandFileTreeMetadata,+ createCommandContextSnapshot,+ isBottomBacklinkEditorContext,+ resolveCommandFocus,+} from "./contextCore";+import type {+ ICommandBlockContext,+ ICommandContextSnapshot,+ ICommandDockContext,+ ICommandFileTreeContext,+ ICommandTabContext,+ TCommandSource,+} from "./types";+/// #if MOBILE+import {getCurrentEditor} from "../mobile/editor";+/// #else+import {Editor} from "../editor";+import {Custom} from "../layout/dock/Custom";+import {Files} from "../layout/dock/Files";+import {getAllModels} from "../layout/getAll";+import {getActiveTab, getDockByType} from "../layout/tabUtil";+import {Search} from "../search";+/// #endif++interface ICaptureCommandContextOptions {+ app: App;+ source: TCommandSource;+ range?: Range;+ protyle?: IProtyle;+ fileLiElements?: Element[];+}++const findDialogProtyle = (range?: Range) => {+ if (!range) {+ return undefined;+ }+ let protyle: IProtyle | undefined;+ window.siyuan.dialogs.find(item => {+ if (!item.editors) {+ return false;+ }+ return Object.keys(item.editors).some(key => {+ if (item.editors[key].protyle.element.contains(range.startContainer)) {+ protyle = item.editors[key].protyle;+ return true;+ }+ return false;+ });+ });+ return protyle;+};++/// #if !MOBILE+const findActiveTabProtyle = (activeTab: ReturnType<typeof getActiveTab>, range?: Range) => {+ if (!activeTab) {+ return undefined;+ }+ if (activeTab.model instanceof Editor) {+ return activeTab.model.getCurrentProtyle(range);+ }+ if (activeTab.model instanceof Search) {+ const unRefPanel = activeTab.model.element.querySelector("#searchUnRefPanel");+ return !unRefPanel || unRefPanel.classList.contains("fn__none") ?+ activeTab.model.editors.edit.protyle : activeTab.model.editors.unRefEdit.protyle;+ }+ if (activeTab.model instanceof Custom && activeTab.model.editors?.length > 0 && range) {+ return activeTab.model.editors.find(item => item.protyle.element.contains(range.startContainer))?.protyle;+ }+ return undefined;+};++const findFallbackProtyle = (range?: Range) => {+ let protyle: IProtyle | undefined;+ if (range) {+ window.siyuan.blockPanels.find(item => item.editors.some(editorItem => {+ if (editorItem.protyle.element.contains(range.startContainer)) {+ protyle = editorItem.protyle;+ return true;+ }+ return false;+ }));+ }+ if (protyle) {+ return protyle;+ }+ const models = getAllModels();+ models.backlink.find(item => {+ if (!item.element.classList.contains("layout__tab--active")) {+ return false;+ }+ if (range) {+ protyle = item.editors.find(editor => editor.protyle.element.contains(range.startContainer))?.protyle;+ }+ protyle ||= item.editors[0]?.protyle;+ return true;+ });+ if (protyle) {+ return protyle;+ }+ models.editor.find(item => {+ if (item.parent.headElement.classList.contains("item--focus")) {+ protyle = item.editor.protyle;+ return true;+ }+ return false;+ });+ return protyle;+};+/// #endif++const getDockElement = (activeElement?: Element) => {+ const bottomBacklink = activeElement && hasClosestByClassName(activeElement, "sy__backlink--bottom", true);+ if (bottomBacklink) {+ const closestProtyle = hasClosestByClassName(activeElement, "protyle", true);+ if (isBottomBacklinkEditorContext(bottomBacklink, closestProtyle)) {+ return undefined;+ }+ return {element: bottomBacklink, type: "backlink-bottom"} as ICommandDockContext;+ }+ let element = activeElement?.closest<HTMLElement>(".layout__tab--active");+ if (!element && (!activeElement || activeElement === document.body)) {+ element = document.querySelector<HTMLElement>(".layout__tab--active");+ }+ if (!element && (!activeElement || activeElement === document.body)) {+ element = Array.from(document.querySelectorAll<HTMLElement>(+ ".layout__wnd--active .layout-tab-container > div",+ )).find(item => !item.classList.contains("fn__none") && item.className.includes("sy__"));+ }+ if (!element || !element.className.includes("sy__") || element.classList.contains("sy__file")) {+ return undefined;+ }+ const type = Array.from(element.classList).find(item => item.startsWith("sy__"))?.substring(4);+ return {element, type} as ICommandDockContext;+};++/// #if !MOBILE+const getFileTree = (elements?: Element[]) => {+ const dockFile = getDockByType("file");+ const model = dockFile?.data.file;+ if (!(model instanceof Files)) {+ return undefined;+ }+ const selectedElements = elements ? [...elements] :+ Array.from(model.element.querySelectorAll(".b3-list-item--focus"));+ const metadata = collectCommandFileTreeMetadata(selectedElements);+ return {+ model,+ elements: selectedElements,+ ...metadata,+ } as ICommandFileTreeContext;+};+/// #endif++const getBlockContext = (element: HTMLElement | false): ICommandBlockContext | undefined => {+ if (!element) {+ return undefined;+ }+ const id = element.getAttribute("data-node-id");+ return id ? {id, element} : undefined;+};++export const captureCommandContext = (options: ICaptureCommandContextOptions): ICommandContextSnapshot => {+ const explicitProtyle = Boolean(options.protyle);+ const explicitFileTree = Boolean(options.fileLiElements);+ const activeElement = document.activeElement || undefined;+ const selection = document.getSelection();+ let range = cloneCommandRange(options.range || (selection?.rangeCount ? selection.getRangeAt(0) : undefined));+ let protyle = options.protyle;+ /// #if MOBILE+ if (!protyle) {+ protyle = getCurrentEditor()?.protyle;+ }+ if (!options.range) {+ range = cloneCommandRange(protyle?.toolbar?.range) || range;+ }+ /// #endif+ const dialogProtyle = protyle || explicitFileTree ? undefined : findDialogProtyle(range);+ protyle ||= dialogProtyle;+ let fileTreeFocused = false;+ const dock = getDockElement(activeElement);+ /// #if !MOBILE+ const activePanelElement = document.querySelector<HTMLElement>(".layout__tab--active");+ fileTreeFocused = !protyle && (explicitFileTree || activePanelElement?.classList.contains("sy__file"));+ const activeTab = getActiveTab(false);+ if (!protyle && !fileTreeFocused) {+ protyle = findActiveTabProtyle(activeTab, range) || findFallbackProtyle(range);+ }+ /// #endif+ const fileTree: ICommandFileTreeContext | undefined =+ /// #if !MOBILE+ fileTreeFocused ? getFileTree(options.fileLiElements) :+ /// #endif+ undefined;+ if (!range) {+ range = cloneCommandRange(protyle?.toolbar?.range);+ }+ const blockElement = range ? hasClosestBlock(range.startContainer) : false;+ const block = getBlockContext(blockElement);+ const selectedBlocks = protyle?.wysiwyg?.element ?+ Array.from(protyle.wysiwyg.element.querySelectorAll<HTMLElement>(".protyle-wysiwyg--select"))+ .map(element => getBlockContext(element)).filter((item): item is ICommandBlockContext => Boolean(item)) : [];+ const tableCellElement = range && (hasClosestByTag(range.startContainer, "TD") ||+ hasClosestByTag(range.startContainer, "TH"));+ const focus = resolveCommandFocus({+ explicitEditor: explicitProtyle,+ explicitFileTree,+ dialogEditor: Boolean(dialogProtyle),+ fileTree: fileTreeFocused,+ dock: Boolean(dock),+ editor: Boolean(protyle),+ });+ let tab: ICommandTabContext | undefined;+ /// #if !MOBILE+ if (activeTab) {+ tab = {+ id: activeTab.id,+ model: activeTab.model,+ element: activeTab.panelElement,+ };+ }+ /// #endif+ return createCommandContextSnapshot({+ app: options.app,+ source: options.source,+ environment: getFrontend(),+ focus,+ range,+ activeElement,+ protyle,+ document: protyle ? {+ id: protyle.block?.id,+ rootId: protyle.block?.rootID,+ notebookId: protyle.notebookId,+ path: protyle.path,+ } : undefined,+ block,+ selectedBlocks,+ tableCell: tableCellElement ? {+ element: tableCellElement as HTMLTableCellElement,+ row: (tableCellElement.parentElement as HTMLTableRowElement)?.rowIndex ?? -1,+ column: (tableCellElement as HTMLTableCellElement).cellIndex,+ } : undefined,+ fileTree,+ activeTab: tab,+ dock,+ });+};diff --git a/app/src/command/contextCore.test.ts b/app/src/command/contextCore.test.tsnew file mode 100644index 0000000000..c044ba7312--- /dev/null+++ b/app/src/command/contextCore.test.ts@@ -0,0 +1,102 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ cloneCommandRange,+ collectCommandFileTreeMetadata,+ createCommandContextSnapshot,+ isBottomBacklinkEditorContext,+ resolveCommandFocus,+} from "./contextCore";+import type {ICommandContextSnapshot} from "./types";++describe("command context core", () => {+ it("clones a range exactly once", () => {+ let clones = 0;+ const snapshot = {value: "snapshot", cloneRange: () => snapshot};+ const source = {cloneRange: () => {+ clones++;+ return snapshot;+ }};++ assert.equal(cloneCommandRange(source), snapshot);+ assert.equal(clones, 1);+ assert.equal(cloneCommandRange(undefined), undefined);+ });++ it("uses the stable focus precedence", () => {+ const base = {+ explicitEditor: false,+ explicitFileTree: false,+ dialogEditor: false,+ fileTree: false,+ dock: false,+ editor: false,+ };++ assert.equal(resolveCommandFocus({...base, explicitEditor: true, fileTree: true}), "editor");+ assert.equal(resolveCommandFocus({...base, explicitFileTree: true, dialogEditor: true}), "fileTree");+ assert.equal(resolveCommandFocus({...base, dialogEditor: true, fileTree: true}), "editor");+ assert.equal(resolveCommandFocus({...base, fileTree: true, dock: true}), "fileTree");+ assert.equal(resolveCommandFocus({...base, dock: true, editor: true}), "dock");+ assert.equal(resolveCommandFocus({...base, editor: true}), "editor");+ assert.equal(resolveCommandFocus(base), "global");+ });++ it("collects stable file tree identifiers", () => {+ const elements = [+ {getAttribute: (name: string) => name === "data-node-id" ? "first" : "/first.sy"},+ {getAttribute: (name: string) => name === "data-node-id" ? null : "/second.sy"},+ ];++ assert.deepEqual(collectCommandFileTreeMetadata(elements), {+ ids: ["first"],+ paths: ["/first.sy", "/second.sy"],+ });+ });++ it("distinguishes a bottom backlink editor from its owner editor", () => {+ const ownerProtyle = {} as Element;+ const nestedProtyle = {} as Element;+ const bottomBacklink = {+ contains: (element: Node | null) => element === nestedProtyle,+ } as Pick<Element, "contains">;++ assert.equal(isBottomBacklinkEditorContext(bottomBacklink, ownerProtyle), false);+ assert.equal(isBottomBacklinkEditorContext(bottomBacklink, nestedProtyle), true);+ assert.equal(isBottomBacklinkEditorContext(bottomBacklink, false), false);+ });++ it("copies the resolved context collections into a snapshot", () => {+ const blockElement = {} as HTMLElement;+ const tableCellElement = {} as HTMLTableCellElement;+ const fileElement = {} as Element;+ const dockElement = {} as HTMLElement;+ const source: ICommandContextSnapshot = {+ app: {},+ source: "commandPanel",+ environment: "desktop",+ focus: "editor",+ range: {} as Range,+ protyle: {} as IProtyle,+ document: {id: "document", rootId: "root", notebookId: "notebook", path: "/document.sy"},+ block: {id: "block", element: blockElement},+ selectedBlocks: [{id: "selected", element: blockElement}],+ tableCell: {element: tableCellElement, row: 2, column: 3},+ fileTree: {model: {}, elements: [fileElement], ids: ["file"], paths: ["/file.sy"]},+ activeTab: {id: "tab", model: {}, element: dockElement},+ dock: {type: "outline", element: dockElement},+ };+ const snapshot = createCommandContextSnapshot(source);++ source.document.id = "changed";+ source.selectedBlocks.length = 0;+ source.fileTree.ids.length = 0;+ assert.equal(snapshot.document?.id, "document");+ assert.deepEqual(snapshot.selectedBlocks.map(item => item.id), ["selected"]);+ assert.deepEqual(snapshot.fileTree?.ids, ["file"]);+ assert.equal(snapshot.tableCell?.row, 2);+ assert.equal(snapshot.activeTab?.id, "tab");+ assert.equal(snapshot.dock?.type, "outline");+ assert.equal(snapshot.range, source.range);+ });+});diff --git a/app/src/command/contextCore.ts b/app/src/command/contextCore.tsnew file mode 100644index 0000000000..69fe2dd766--- /dev/null+++ b/app/src/command/contextCore.ts@@ -0,0 +1,57 @@+import type {ICommandContextSnapshot, TCommandFocus} from "./types";++export const cloneCommandRange = <T extends {cloneRange: () => T}>(range?: T) => range?.cloneRange();++export const collectCommandFileTreeMetadata = <T extends {getAttribute: (name: string) => string | null}>(+ elements: T[],+) => ({+ ids: elements.map(item => item.getAttribute("data-node-id") || "").filter(Boolean),+ paths: elements.map(item => item.getAttribute("data-path") || "").filter(Boolean),+});++export const isBottomBacklinkEditorContext = (+ bottomBacklink: Pick<Element, "contains">,+ closestProtyle?: Element | false,+) => Boolean(closestProtyle && bottomBacklink.contains(closestProtyle));++export const createCommandContextSnapshot = (context: ICommandContextSnapshot): ICommandContextSnapshot => ({+ ...context,+ document: context.document ? {...context.document} : undefined,+ block: context.block ? {...context.block} : undefined,+ selectedBlocks: context.selectedBlocks.map(block => ({...block})),+ tableCell: context.tableCell ? {...context.tableCell} : undefined,+ fileTree: context.fileTree ? {+ ...context.fileTree,+ elements: [...context.fileTree.elements],+ ids: [...context.fileTree.ids],+ paths: [...context.fileTree.paths],+ } : undefined,+ activeTab: context.activeTab ? {...context.activeTab} : undefined,+ dock: context.dock ? {...context.dock} : undefined,+});++export const resolveCommandFocus = (options: {+ explicitEditor: boolean,+ explicitFileTree: boolean,+ dialogEditor: boolean,+ fileTree: boolean,+ dock: boolean,+ editor: boolean,+}): TCommandFocus => {+ if (options.explicitEditor) {+ return "editor";+ }+ if (options.explicitFileTree) {+ return "fileTree";+ }+ if (options.dialogEditor) {+ return "editor";+ }+ if (options.fileTree) {+ return "fileTree";+ }+ if (options.dock) {+ return "dock";+ }+ return options.editor ? "editor" : "global";+};diff --git a/app/src/command/english.test.ts b/app/src/command/english.test.tsnew file mode 100644index 0000000000..7d1e5bd94a--- /dev/null+++ b/app/src/command/english.test.ts@@ -0,0 +1,28 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {requestEnglishCommandTranslations} from "./english";++describe("English command translations", () => {+ it("loads the versioned English language file without caching", async () => {+ const requests: Array<{url: string; cache?: RequestCache}> = [];+ const fetcher = (async (url: string, init?: RequestInit) => {+ requests.push({url, cache: init?.cache});+ return {+ ok: true,+ json: async () => ({search: "Search"}),+ } as Response;+ }) as typeof fetch;++ assert.deepEqual(await requestEnglishCommandTranslations("1.2.3", fetcher), {search: "Search"});+ assert.deepEqual(requests, [{+ url: "/appearance/langs/en.json?v=1.2.3",+ cache: "no-store",+ }]);+ });++ it("rejects a failed language response", async () => {+ const fetcher = (async () => ({ok: false, status: 404}) as Response) as typeof fetch;++ await assert.rejects(requestEnglishCommandTranslations("1.2.3", fetcher), /404/);+ });+});diff --git a/app/src/command/english.ts b/app/src/command/english.tsnew file mode 100644index 0000000000..40d9790e71--- /dev/null+++ b/app/src/command/english.ts@@ -0,0 +1,38 @@+let englishLanguages: Record<string, string> | undefined;+let englishLanguagesPromise: Promise<Record<string, string> | undefined> | undefined;++export const getEnglishCommandLabel = (key: string) => englishLanguages?.[key];++export const requestEnglishCommandTranslations = async (+ version: string,+ fetcher: typeof fetch = fetch,+) => {+ const response = await fetcher(`/appearance/langs/en.json?v=${version}`, {cache: "no-store"});+ if (!response.ok) {+ throw new Error(`Unable to load English commands: ${response.status}`);+ }+ return response.json() as Promise<Record<string, string>>;+};++export const initializeEnglishCommandTranslations = (+ currentLanguage: string,+ currentLanguages: Record<string, string>,+ version: string,+) => {+ if (currentLanguage === "en") {+ englishLanguages = currentLanguages;+ return Promise.resolve(englishLanguages);+ }+ if (!englishLanguagesPromise) {+ englishLanguagesPromise = requestEnglishCommandTranslations(version)+ .then(languages => {+ englishLanguages = languages;+ return languages;+ })+ .catch(error => {+ console.warn("Unable to load English command translations:", error);+ return undefined;+ });+ }+ return englishLanguagesPromise;+};diff --git a/app/src/command/executor.ts b/app/src/command/executor.tsnew file mode 100644index 0000000000..cb4f965605--- /dev/null+++ b/app/src/command/executor.ts@@ -0,0 +1,45 @@+import type {App} from "../index";+import {captureCommandContext} from "./context";+import {ensureNativeCommands, getNativeCommandId} from "./nativeCommands";+import {executeLegacyNativeCommand} from "./nativeRuntime";+import {getCommandRegistry} from "./service";+import type {ICommandContextSnapshot, TCommandSource} from "./types";++interface IExecByCommandOptions {+ command: string;+ app?: App;+ previousRange?: Range;+ protyle?: IProtyle;+ fileLiElements?: Element[];+ context?: ICommandContextSnapshot;+ source?: TCommandSource;+}++export const ensureCommandSystem = (app: App) => {+ ensureNativeCommands(app, executeLegacyNativeCommand);+ return getCommandRegistry(app);+};++export const executeCommandById = (+ app: App,+ commandId: string,+ context: ICommandContextSnapshot,+ args?: unknown,+) => ensureCommandSystem(app).execute(commandId, context, args);++export const execByCommand = async (options: IExecByCommandOptions) => {+ const app = options.app || window.siyuan.ws.app;+ const context = options.context || captureCommandContext({+ app,+ source: options.source || "shortcut",+ range: options.previousRange,+ protyle: options.protyle,+ fileLiElements: options.fileLiElements,+ });+ const commandId = getNativeCommandId(options.command);+ if (commandId) {+ return ensureCommandSystem(app).execute(commandId, context);+ }+ await executeLegacyNativeCommand(options.command, context);+ return {status: "executed" as const};+};diff --git a/app/src/command/nativeCatalog.test.ts b/app/src/command/nativeCatalog.test.tsnew file mode 100644index 0000000000..8c7ca97be8--- /dev/null+++ b/app/src/command/nativeCatalog.test.ts@@ -0,0 +1,87 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ COMMAND_PANEL_EDITOR_KEYS,+ DESKTOP_COMMAND_PANEL_GENERAL_KEYS,+ getNativeCommandByLegacyId,+ isNativeCommandSupported,+ MOBILE_COMMAND_PANEL_GENERAL_KEYS,+ NATIVE_COMMAND_CATALOG,+ orderNativeCommands,+ type TNativeCommandEnvironment,+} from "./nativeCatalog";++const expectedDesktopGeneralKeys = [+ "addToDatabase", "fileTree", "outline", "bookmark", "tag", "dailyNote", "inbox", "backlinks",+ "graphView", "globalGraph", "closeAll", "closeLeft", "closeOthers", "closeRight", "closeTab",+ "closeUnmodified", "config", "dataHistory", "editReadonly", "enter", "enterBack", "globalSearch", "goBack",+ "goForward", "goToEditTabNext", "goToEditTabPrev", "goToTab1", "goToTab2", "goToTab3", "goToTab4",+ "goToTab5", "goToTab6", "goToTab7", "goToTab8", "goToTab9", "goToTabNext", "goToTabPrev", "lockScreen",+ "mainMenu", "move", "newFile", "recentDocs", "replace", "riffCard", "search", "selectOpen1", "syncNow",+ "splitLR", "splitMoveB", "splitMoveR", "splitTB", "switchLeftDock", "switchRightDock", "switchBottomDock",+ "tabToWindow", "stickSearch", "toggleDock", "toggleLeftDockPanel", "toggleRightDockPanel",+ "toggleBottomDockPanel", "unsplitAll", "unsplit", "recentClosed", "increaseEditorFontSize",+ "decreaseEditorFontSize", "resetEditorFontSize", "toggleWin",+];++const expectedMobileGeneralKeys = [+ "addToDatabase", "fileTree", "outline", "bookmark", "tag", "dailyNote", "inbox", "backlinks",+ "dataHistory", "editReadonly", "enter", "enterBack", "globalSearch", "lockScreen", "mainMenu", "move",+ "newFile", "recentDocs", "replace", "riffCard", "search", "selectOpen1", "syncNow", "increaseEditorFontSize",+ "decreaseEditorFontSize", "resetEditorFontSize",+];++const getSupportedIds = (environment: TNativeCommandEnvironment) => NATIVE_COMMAND_CATALOG+ .filter(item => isNativeCommandSupported(item, environment))+ .map(item => item.id);++describe("native command catalog", () => {+ it("preserves the existing command panel baseline", () => {+ assert.deepEqual([...DESKTOP_COMMAND_PANEL_GENERAL_KEYS], expectedDesktopGeneralKeys);+ assert.deepEqual([...MOBILE_COMMAND_PANEL_GENERAL_KEYS], expectedMobileGeneralKeys);+ assert.deepEqual([...COMMAND_PANEL_EDITOR_KEYS], ["switchReadonly", "switchAdjust"]);+ assert.equal(DESKTOP_COMMAND_PANEL_GENERAL_KEYS.length, 67);+ assert.equal(MOBILE_COMMAND_PANEL_GENERAL_KEYS.length, 26);+ assert.equal(COMMAND_PANEL_EDITOR_KEYS.length, 2);+ assert.equal(NATIVE_COMMAND_CATALOG.length, 69);+ assert.equal(new Set(NATIVE_COMMAND_CATALOG.map(item => item.id)).size, NATIVE_COMMAND_CATALOG.length);+ });++ it("filters all five frontends without exposing desktop-only commands", () => {+ assert.equal(getSupportedIds("desktop").length, 69);+ assert.equal(getSupportedIds("desktop-window").length, 69);+ assert.equal(getSupportedIds("browser-desktop").length, 68);+ assert.equal(getSupportedIds("mobile").length, 28);+ assert.equal(getSupportedIds("browser-mobile").length, 28);+ assert.equal(getSupportedIds("browser-desktop").includes("core.general.toggleWin"), false);+ assert.equal(getSupportedIds("mobile").includes("core.general.graphView"), false);+ });++ it("maps legacy keys to stable IDs and keymap paths", () => {+ assert.deepEqual(getNativeCommandByLegacyId("fileTree"), {+ id: "core.general.fileTree",+ legacyId: "fileTree",+ keymapPath: ["general", "fileTree"],+ desktop: true,+ mobile: true,+ browser: true,+ requirement: "none",+ order: 1,+ });+ assert.deepEqual(getNativeCommandByLegacyId("switchReadonly")?.keymapPath, [+ "editor",+ "general",+ "switchReadonly",+ ]);+ });++ it("preserves configured native order and keeps editor commands last", () => {+ assert.deepEqual(+ orderNativeCommands(+ ["unknown", "search", "fileTree"],+ ["switchAdjust", "unknown", "switchReadonly"],+ ).map(item => item.legacyId),+ ["search", "fileTree", "switchAdjust", "switchReadonly"],+ );+ });+});diff --git a/app/src/command/nativeCatalog.ts b/app/src/command/nativeCatalog.tsnew file mode 100644index 0000000000..0998bf9e51--- /dev/null+++ b/app/src/command/nativeCatalog.ts@@ -0,0 +1,92 @@+export const DESKTOP_COMMAND_PANEL_GENERAL_KEYS = [+ "addToDatabase", "fileTree", "outline", "bookmark", "tag", "dailyNote", "inbox", "backlinks",+ "graphView", "globalGraph", "closeAll", "closeLeft", "closeOthers", "closeRight", "closeTab",+ "closeUnmodified", "config", "dataHistory", "editReadonly", "enter", "enterBack", "globalSearch", "goBack",+ "goForward", "goToEditTabNext", "goToEditTabPrev", "goToTab1", "goToTab2", "goToTab3", "goToTab4",+ "goToTab5", "goToTab6", "goToTab7", "goToTab8", "goToTab9", "goToTabNext", "goToTabPrev", "lockScreen",+ "mainMenu", "move", "newFile", "recentDocs", "replace", "riffCard", "search", "selectOpen1", "syncNow",+ "splitLR", "splitMoveB", "splitMoveR", "splitTB", "switchLeftDock", "switchRightDock", "switchBottomDock",+ "tabToWindow", "stickSearch", "toggleDock", "toggleLeftDockPanel", "toggleRightDockPanel",+ "toggleBottomDockPanel", "unsplitAll", "unsplit", "recentClosed", "increaseEditorFontSize",+ "decreaseEditorFontSize", "resetEditorFontSize", "toggleWin",+] as const;++export const MOBILE_COMMAND_PANEL_GENERAL_KEYS = [+ "addToDatabase", "fileTree", "outline", "bookmark", "tag", "dailyNote", "inbox", "backlinks",+ "dataHistory", "editReadonly", "enter", "enterBack", "globalSearch", "lockScreen", "mainMenu", "move",+ "newFile", "recentDocs", "replace", "riffCard", "search", "selectOpen1", "syncNow", "increaseEditorFontSize",+ "decreaseEditorFontSize", "resetEditorFontSize",+] as const;++export const COMMAND_PANEL_EDITOR_KEYS = ["switchReadonly", "switchAdjust"] as const;++export type TNativeCommandRequirement = "none" | "editor" | "editorOrFileTree";++export interface INativeCommandCatalogItem {+ id: string;+ legacyId: string;+ keymapPath: readonly ["general", string] | readonly ["editor", "general", string];+ desktop: boolean;+ mobile: boolean;+ browser: boolean;+ requirement: TNativeCommandRequirement;+ order: number;+}++export type TNativeCommandEnvironment =+ "desktop" |+ "desktop-window" |+ "mobile" |+ "browser-desktop" |+ "browser-mobile";++const mobileKeys = new Set<string>(MOBILE_COMMAND_PANEL_GENERAL_KEYS);+const editorRequiredKeys = new Set<string>(["enter", "enterBack"]);+const editorOrFileTreeRequiredKeys = new Set<string>(["addToDatabase", "move"]);++export const NATIVE_COMMAND_CATALOG: INativeCommandCatalogItem[] = [+ ...DESKTOP_COMMAND_PANEL_GENERAL_KEYS.map((legacyId, order) => ({+ id: `core.general.${legacyId}`,+ legacyId,+ keymapPath: ["general", legacyId] as const,+ desktop: true,+ mobile: mobileKeys.has(legacyId),+ browser: legacyId !== "toggleWin",+ requirement: editorRequiredKeys.has(legacyId) ? "editor" as const :+ editorOrFileTreeRequiredKeys.has(legacyId) ? "editorOrFileTree" as const : "none" as const,+ order,+ })),+ ...COMMAND_PANEL_EDITOR_KEYS.map((legacyId, index) => ({+ id: `core.editor.general.${legacyId}`,+ legacyId,+ keymapPath: ["editor", "general", legacyId] as const,+ desktop: true,+ mobile: true,+ browser: true,+ requirement: "editor" as const,+ order: DESKTOP_COMMAND_PANEL_GENERAL_KEYS.length + index,+ })),+];++const commandsByLegacyId = new Map(NATIVE_COMMAND_CATALOG.map(item => [item.legacyId, item]));++export const getNativeCommandByLegacyId = (legacyId: string) => commandsByLegacyId.get(legacyId);++export const orderNativeCommands = (generalKeys: string[], editorKeys: string[]) => [+ ...generalKeys+ .map(key => getNativeCommandByLegacyId(key))+ .filter((item): item is INativeCommandCatalogItem => Boolean(item?.keymapPath[0] === "general")),+ ...editorKeys+ .map(key => getNativeCommandByLegacyId(key))+ .filter((item): item is INativeCommandCatalogItem => Boolean(item?.keymapPath[0] === "editor")),+];++export const isNativeCommandSupported = (+ item: INativeCommandCatalogItem,+ environment: TNativeCommandEnvironment,+) => {+ if (environment.startsWith("browser-") && !item.browser) {+ return false;+ }+ return ["mobile", "browser-mobile"].includes(environment) ? item.mobile : item.desktop;+};diff --git a/app/src/command/nativeCommands.ts b/app/src/command/nativeCommands.tsnew file mode 100644index 0000000000..ceeaedebaa--- /dev/null+++ b/app/src/command/nativeCommands.ts@@ -0,0 +1,74 @@+import {getEnglishCommandLabel} from "./english";+import {+ getNativeCommandByLegacyId,+ isNativeCommandSupported,+ orderNativeCommands,+ type INativeCommandCatalogItem,+} from "./nativeCatalog";+import {getCommandRegistry} from "./service";+import type {ICommandContextSnapshot, ICommandDefinition} from "./types";++export type TNativeCommandExecutor = (+ command: string,+ context: ICommandContextSnapshot,+) => unknown | Promise<unknown>;++const initializedApps = new WeakSet<object>();++const getHotkey = (item: INativeCommandCatalogItem) => {+ if (item.keymapPath[0] === "general") {+ return window.siyuan.config.keymap.general[item.keymapPath[1]]?.custom || "";+ }+ return window.siyuan.config.keymap.editor[item.keymapPath[1]][item.keymapPath[2]]?.custom || "";+};++const matchesContext = (item: INativeCommandCatalogItem, context: ICommandContextSnapshot) => {+ if (item.requirement === "editor") {+ return Boolean(context.protyle);+ }+ if (item.requirement === "editorOrFileTree") {+ return Boolean(context.protyle || context.fileTree?.elements.length);+ }+ return true;+};++const createNativeCommand = (+ item: INativeCommandCatalogItem,+ order: number,+ execute: TNativeCommandExecutor,+): ICommandDefinition => ({+ id: item.id,+ category: "core",+ label: () => window.siyuan.languages[item.legacyId] || item.legacyId,+ englishLabel: () => getEnglishCommandLabel(item.legacyId),+ keywords: () => [item.legacyId, ...item.keymapPath],+ keymapPath: item.keymapPath,+ hotkey: () => getHotkey(item),+ order,+ platform: environment => isNativeCommandSupported(item, environment),+ enabled: context => matchesContext(item, context),+ execute: context => execute(item.legacyId, context),+});++export const ensureNativeCommands = (app: object, execute: TNativeCommandExecutor) => {+ if (initializedApps.has(app)) {+ return;+ }+ const registry = getCommandRegistry(app);+ const items = orderNativeCommands(+ Object.keys(window.siyuan.config.keymap.general),+ Object.keys(window.siyuan.config.keymap.editor.general),+ );+ const owner = {};+ const disposers: Array<() => boolean> = [];+ try {+ items.forEach((item, order) =>+ disposers.push(registry.register(createNativeCommand(item, order, execute), owner)));+ initializedApps.add(app);+ } catch (error) {+ disposers.reverse().forEach(dispose => dispose());+ throw error;+ }+};++export const getNativeCommandId = (legacyId: string) => getNativeCommandByLegacyId(legacyId)?.id;diff --git a/app/src/command/nativeRuntime.ts b/app/src/command/nativeRuntime.tsnew file mode 100644index 0000000000..0233da2f8f--- /dev/null+++ b/app/src/command/nativeRuntime.ts@@ -0,0 +1,224 @@+import type {App} from "../index";+import {Constants} from "../constants";+import {isMobile} from "../util/functions";+import {addEditorToDatabase, addFilesToDatabase} from "../protyle/render/av/addToDatabase";+import {hasClosestBlock, hasTopClosestByTag} from "../protyle/util/hasClosest";+import {getDisplayName, getNotebookName, getTopPaths, movePathTo, moveToPath, pathPosix} from "../util/pathName";+import {hintMoveBlock} from "../protyle/hint/extend";+import {fetchSyncPost} from "../util/fetch";+import {globalCommand} from "../boot/globalEvent/command/global";+import {onlyProtyleCommand} from "../boot/globalEvent/command/protyle";+import type {ICommandContextSnapshot} from "./types";+/// #if MOBILE+import {popSearch} from "../mobile/menu/search";+/// #else+import {openSearch} from "../search/spread";+/// #endif++export const executeLegacyNativeCommand = async (command: string, context: ICommandContextSnapshot) => {+ const app = context.app as App;+ if (globalCommand(command, app, context.range)) {+ return;+ }++ const isFileFocus = context.focus === "fileTree";+ const protyle = context.protyle;+ const range = context.range;+ const fileLiElements = context.fileTree?.elements;++ if (!isFileFocus && protyle && onlyProtyleCommand({+ command,+ previousRange: range,+ protyle,+ })) {+ return;+ }++ // 全局命令,在没有编辑器上下文或文档树没有选中项时执行。+ if ((!protyle && !isFileFocus) ||+ (isFileFocus && (!fileLiElements || fileLiElements.length === 0)) ||+ (isMobile() && !document.getElementById("empty")?.classList.contains("fn__none"))) {+ if (command === "replace") {+ /// #if MOBILE+ popSearch(app, {hasReplace: true, page: 1});+ /// #else+ openSearch({+ app,+ hotkey: Constants.DIALOG_REPLACE,+ key: range?.toString() || "",+ });+ /// #endif+ } else if (command === "search") {+ /// #if MOBILE+ popSearch(app, {hasReplace: false, page: 1});+ /// #else+ openSearch({+ app,+ hotkey: Constants.DIALOG_SEARCH,+ key: range?.toString() || "",+ });+ /// #endif+ }+ return;+ }++ switch (command) {+ case "replace":+ if (!isFileFocus) {+ /// #if MOBILE+ const response = await fetchSyncPost("/api/filetree/getHPathByPath", {+ notebook: protyle.notebookId,+ path: protyle.path.endsWith(".sy") ? protyle.path : protyle.path + ".sy",+ });+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }+ popSearch(app, {+ page: 1,+ hasReplace: true,+ hPath: pathPosix().join(getNotebookName(protyle.notebookId), response.data),+ idPath: [pathPosix().join(protyle.notebookId, protyle.path)],+ });+ /// #else+ openSearch({+ app,+ hotkey: Constants.DIALOG_REPLACE,+ key: range?.toString() || "",+ notebookId: protyle.notebookId,+ searchPath: protyle.path,+ });+ /// #endif+ } else {+ /// #if !MOBILE+ const topULElement = hasTopClosestByTag(fileLiElements[0], "UL");+ if (!topULElement) {+ return false;+ }+ const notebookId = topULElement.getAttribute("data-url");+ const pathString = fileLiElements[0].getAttribute("data-path");+ const isFile = fileLiElements[0].getAttribute("data-type") === "navigation-file";+ if (isFile) {+ openSearch({+ app,+ hotkey: Constants.DIALOG_REPLACE,+ notebookId,+ searchPath: getDisplayName(pathString, false, true),+ });+ } else {+ openSearch({+ app,+ hotkey: Constants.DIALOG_REPLACE,+ notebookId,+ });+ }+ /// #endif+ }+ break;+ case "search":+ if (!isFileFocus) {+ /// #if MOBILE+ const response = await fetchSyncPost("/api/filetree/getHPathByPath", {+ notebook: protyle.notebookId,+ path: protyle.path.endsWith(".sy") ? protyle.path : protyle.path + ".sy",+ });+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }+ popSearch(app, {+ page: 1,+ hasReplace: false,+ hPath: pathPosix().join(getNotebookName(protyle.notebookId), response.data),+ idPath: [pathPosix().join(protyle.notebookId, protyle.path)],+ });+ /// #else+ openSearch({+ app,+ hotkey: Constants.DIALOG_SEARCH,+ key: range?.toString() || "",+ notebookId: protyle.notebookId,+ searchPath: protyle.path,+ });+ /// #endif+ } else {+ /// #if !MOBILE+ const topULElement = hasTopClosestByTag(fileLiElements[0], "UL");+ if (!topULElement) {+ return false;+ }+ const notebookId = topULElement.getAttribute("data-url");+ const pathString = fileLiElements[0].getAttribute("data-path");+ const isFile = fileLiElements[0].getAttribute("data-type") === "navigation-file";+ if (isFile) {+ openSearch({+ app,+ hotkey: Constants.DIALOG_SEARCH,+ notebookId,+ searchPath: getDisplayName(pathString, false, true),+ });+ } else {+ openSearch({+ app,+ hotkey: Constants.DIALOG_SEARCH,+ notebookId,+ });+ }+ /// #endif+ }+ break;+ case "addToDatabase":+ if (!isFileFocus && range) {+ addEditorToDatabase(protyle, range);+ } else if (fileLiElements) {+ addFilesToDatabase(fileLiElements);+ }+ break;+ case "move":+ if (!isFileFocus && range) {+ const nodeElement = hasClosestBlock(range.startContainer);+ if (protyle.title?.editElement.contains(range.startContainer) || !nodeElement ||+ window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TITLE) {+ movePathTo({+ cb: (toPath, toNotebook) => {+ moveToPath([protyle.path], toNotebook[0], toPath[0]);+ },+ paths: [protyle.path],+ range,+ flashcard: false,+ rootIDs: [protyle.block.rootID],+ sourceNotebookIds: [protyle.notebookId],+ });+ } else if (protyle.element.contains(range.startContainer)) {+ let selectElements = Array.from(+ protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"),+ );+ if (selectElements.length === 0) {+ selectElements = [nodeElement];+ }+ movePathTo({+ cb: (toPath) => {+ void hintMoveBlock(toPath[0], selectElements, protyle);+ },+ flashcard: false,+ rootIDs: [protyle.block.rootID],+ sourceNotebookIds: [protyle.notebookId],+ });+ }+ } else if (fileLiElements) {+ const paths = getTopPaths(fileLiElements);+ const sourceNotebookIds = fileLiElements.map(item =>+ item.getAttribute("data-notebook-id") ||+ item.closest("ul[data-url]")?.getAttribute("data-url") || "");+ const rootIDs = fileLiElements.map(item => item.getAttribute("data-node-id"));+ movePathTo({+ cb: (toPath, toNotebook) => {+ moveToPath(paths, toNotebook[0], toPath[0]);+ },+ paths,+ rootIDs,+ flashcard: false,+ sourceNotebookIds,+ });+ }+ break;+ }+};diff --git a/app/src/command/paletteCore.test.ts b/app/src/command/paletteCore.test.tsnew file mode 100644index 0000000000..d0240ae6d4--- /dev/null+++ b/app/src/command/paletteCore.test.ts@@ -0,0 +1,59 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {createPaletteFocusLifecycle, queryCommandPalette} from "./paletteCore";+import {CommandRegistry} from "./registry";+import type {ICommandContextSnapshot, ICommandDefinition} from "./types";++const context: ICommandContextSnapshot = {+ app: {},+ source: "commandPanel",+ environment: "desktop",+ focus: "global",+ selectedBlocks: [],+};++const command = (id: string, label: string, order: number): ICommandDefinition => ({+ id,+ category: id.startsWith("plugin/") ? "plugin" : "core",+ label: () => label,+ order,+ execute: () => undefined,+});++describe("command palette core", () => {+ it("keeps core commands before plugins regardless of registration time", () => {+ const registry = new CommandRegistry();+ registry.register(command("plugin/sample/open", "Plugin open", 10_000), {});+ registry.register(command("core.general.open", "Open", 0), {});++ assert.deepEqual(queryCommandPalette(registry, context, "").map(item => item.id), [+ "core.general.open",+ "plugin/sample/open",+ ]);+ });++ it("returns an empty result without throwing", () => {+ assert.deepEqual(queryCommandPalette(new CommandRegistry(), context, "anything"), []);+ });++ it("restores focus before a command without stealing it again on close", () => {+ const events: string[] = [];+ const lifecycle = createPaletteFocusLifecycle(() => events.push("restore"));++ lifecycle.prepareCommand(() => events.push("prevent default"));+ events.push("execute");+ lifecycle.restoreAfterCancel();++ assert.deepEqual(events, ["prevent default", "restore", "execute"]);+ });++ it("restores focus once when the palette is canceled", () => {+ const events: string[] = [];+ const lifecycle = createPaletteFocusLifecycle(() => events.push("restore"));++ lifecycle.restoreAfterCancel();+ lifecycle.restoreAfterCancel();++ assert.deepEqual(events, ["restore"]);+ });+});diff --git a/app/src/command/paletteCore.ts b/app/src/command/paletteCore.tsnew file mode 100644index 0000000000..21fb903a24--- /dev/null+++ b/app/src/command/paletteCore.ts@@ -0,0 +1,29 @@+import type {CommandRegistry} from "./registry";+import {searchCommands} from "./search";+import type {ICommandContextSnapshot} from "./types";++export const queryCommandPalette = (registry: CommandRegistry, context: ICommandContextSnapshot, query: string) =>+ searchCommands(registry.list(context), query);++export const createPaletteFocusLifecycle = (restore: () => void) => {+ let restored = false;+ const restoreOnce = () => {+ if (!restored) {+ restored = true;+ restore();+ }+ };+ let commandSelected = false;+ return {+ prepareCommand(beforeRestore?: () => void) {+ beforeRestore?.();+ commandSelected = true;+ restoreOnce();+ },+ restoreAfterCancel() {+ if (!commandSelected) {+ restoreOnce();+ }+ },+ };+};diff --git a/app/src/command/registry.test.ts b/app/src/command/registry.test.tsnew file mode 100644index 0000000000..506bb80f3e--- /dev/null+++ b/app/src/command/registry.test.ts@@ -0,0 +1,123 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {CommandRegistry} from "./registry";+import {getCommandRegistry} from "./service";+import type {ICommandContextSnapshot, ICommandDefinition} from "./types";++const createContext = (+ overrides: Partial<ICommandContextSnapshot> = {},+): ICommandContextSnapshot => ({+ app: {},+ source: "commandPanel",+ environment: "desktop",+ focus: "global",+ selectedBlocks: [],+ ...overrides,+});++const createCommand = (+ id: string,+ overrides: Partial<ICommandDefinition> = {},+): ICommandDefinition => ({+ id,+ category: "core",+ label: () => id,+ execute: () => undefined,+ ...overrides,+});++describe("command registry", () => {+ it("rejects duplicate IDs and unregisters commands by owner", () => {+ const registry = new CommandRegistry();+ const firstOwner = {};+ const secondOwner = {};+ registry.register(createCommand("core.first"), firstOwner);++ assert.throws(+ () => registry.register(createCommand("core.first"), secondOwner),+ /already registered/,+ );+ assert.equal(registry.unregisterOwner(firstOwner), 1);+ assert.equal(registry.get("core.first"), undefined);+ assert.equal(registry.unregisterOwner(firstOwner), 0);+ });++ it("keeps a newer generation when an old disposer runs", () => {+ const registry = new CommandRegistry();+ const oldOwner = {};+ const oldDispose = registry.register(createCommand("core.reload"), oldOwner);+ registry.unregisterOwner(oldOwner);+ const current = createCommand("core.reload", {label: () => "current"});+ registry.register(current, {});++ assert.equal(oldDispose(), false);+ assert.equal(registry.get("core.reload")?.label(), "current");+ });++ it("uses order and then registration sequence", () => {+ const registry = new CommandRegistry();+ registry.register(createCommand("plugin.first", {order: 10_000}), {});+ registry.register(createCommand("core.second", {order: 2}), {});+ registry.register(createCommand("core.first", {order: 1}), {});+ registry.register(createCommand("core.also-first", {order: 1}), {});++ assert.deepEqual(+ registry.list(createContext()).map(command => command.id),+ ["core.first", "core.also-first", "core.second", "plugin.first"],+ );+ });++ it("filters by source, platform, and context", () => {+ const registry = new CommandRegistry();+ registry.register(createCommand("core.editor", {+ surfaces: ["commandPanel"],+ platform: environment => environment === "desktop",+ when: context => context.focus === "editor",+ }), {});++ assert.deepEqual(registry.list(createContext()).map(command => command.id), []);+ assert.deepEqual(registry.list(createContext({focus: "editor"})).map(command => command.id), ["core.editor"]);+ assert.deepEqual(registry.list(createContext({focus: "editor", environment: "mobile"})), []);+ assert.deepEqual(registry.list(createContext({focus: "editor", source: "shortcut"})), []);+ });++ it("reports execution status and awaits asynchronous handlers", async () => {+ const registry = new CommandRegistry();+ registry.register(createCommand("core.disabled", {enabled: () => false}), {});+ registry.register(createCommand("core.hidden", {when: () => false}), {});+ registry.register(createCommand("core.async", {execute: async () => "done"}), {});++ assert.deepEqual(registry.list(createContext()).map(command => command.id), ["core.disabled", "core.async"]);+ assert.equal((await registry.execute("missing", createContext())).status, "notFound");+ assert.equal((await registry.execute("core.hidden", createContext())).status, "unavailable");+ assert.equal((await registry.execute("core.disabled", createContext())).status, "disabled");+ assert.deepEqual(await registry.execute("core.async", createContext()), {+ status: "executed",+ command: registry.get("core.async"),+ value: "done",+ });+ });++ it("keeps dynamic command metadata live", () => {+ const registry = new CommandRegistry();+ let hotkey = "Ctrl+A";+ const definition = createCommand("core.dynamic", {hotkey: () => hotkey});+ registry.register(definition, {});++ assert.equal(registry.get("core.dynamic")?.hotkey?.(), "Ctrl+A");+ hotkey = "Ctrl+B";+ definition.id = "core.changed";+ assert.equal(registry.get("core.dynamic")?.hotkey?.(), "Ctrl+B");+ assert.equal(registry.get("core.dynamic")?.id, "core.dynamic");+ assert.equal(registry.get("core.changed"), undefined);+ });++ it("isolates registries by app", () => {+ const firstApp = {};+ const secondApp = {};+ getCommandRegistry(firstApp).register(createCommand("core.first"), firstApp);++ assert.notEqual(getCommandRegistry(firstApp), getCommandRegistry(secondApp));+ assert.equal(getCommandRegistry(secondApp).get("core.first"), undefined);+ });+});diff --git a/app/src/command/registry.ts b/app/src/command/registry.tsnew file mode 100644index 0000000000..b4d33b31a6--- /dev/null+++ b/app/src/command/registry.ts@@ -0,0 +1,97 @@+import type {+ ICommandContextSnapshot,+ ICommandDefinition,+ ICommandExecutionResult,+} from "./types";++interface ICommandEntry {+ command: ICommandDefinition;+ owner: object | string | symbol;+ sequence: number;+}++const isAvailable = (command: ICommandDefinition, context: ICommandContextSnapshot) => {+ if (command.surfaces && !command.surfaces.includes(context.source)) {+ return false;+ }+ if (command.platform && !command.platform(context.environment)) {+ return false;+ }+ return !command.when || command.when(context);+};++export class CommandRegistry {+ private readonly entries = new Map<string, ICommandEntry>();+ private sequence = 0;++ public register(command: ICommandDefinition, owner: object | string | symbol) {+ if (!command.id || command.id !== command.id.trim()) {+ throw new Error("Command ID must be a non-empty trimmed string");+ }+ if (this.entries.has(command.id)) {+ throw new Error(`Command ID "${command.id}" is already registered`);+ }+ const id = command.id;+ const entry: ICommandEntry = {+ command: Object.freeze({...command}),+ owner,+ sequence: this.sequence++,+ };+ this.entries.set(id, entry);+ let disposed = false;+ return () => {+ if (disposed) {+ return false;+ }+ disposed = true;+ if (this.entries.get(id) !== entry) {+ return false;+ }+ this.entries.delete(id);+ return true;+ };+ }++ public unregisterOwner(owner: object | string | symbol) {+ let count = 0;+ this.entries.forEach((entry, id) => {+ if (entry.owner === owner) {+ this.entries.delete(id);+ count++;+ }+ });+ return count;+ }++ public get(id: string) {+ return this.entries.get(id)?.command;+ }++ public list(context: ICommandContextSnapshot) {+ return Array.from(this.entries.values())+ .filter(entry => isAvailable(entry.command, context))+ .sort((first, second) => {+ const order = (first.command.order ?? 0) - (second.command.order ?? 0);+ return order || first.sequence - second.sequence;+ })+ .map(entry => entry.command);+ }++ public async execute(id: string, context: ICommandContextSnapshot, args?: unknown): Promise<ICommandExecutionResult> {+ const command = this.get(id);+ if (!command) {+ return {status: "notFound"};+ }+ if (!isAvailable(command, context)) {+ return {status: "unavailable", command};+ }+ if (command.enabled && !command.enabled(context)) {+ return {status: "disabled", command};+ }+ return {+ status: "executed",+ command,+ value: await command.execute(context, args),+ };+ }+}diff --git a/app/src/command/search.test.ts b/app/src/command/search.test.tsnew file mode 100644index 0000000000..7397b4b0b8--- /dev/null+++ b/app/src/command/search.test.ts@@ -0,0 +1,77 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {normalizeCommandSearchText, searchCommands} from "./search";+import type {ICommandDefinition} from "./types";++const createCommand = (options: {+ id: string,+ label: string,+ english?: string,+ keywords?: string[],+}): ICommandDefinition => ({+ id: options.id,+ category: "core",+ label: () => options.label,+ englishLabel: () => options.english,+ keywords: () => options.keywords || [],+ execute: () => undefined,+});++const commands = [+ createCommand({+ id: "core.general.globalSearch",+ label: "全局搜索",+ english: "Global Search",+ keywords: ["find workspace"],+ }),+ createCommand({+ id: "core.editor.general.switchReadonly",+ label: "切换只读模式",+ english: "Switch read-only mode",+ }),+];++describe("command search", () => {+ it("normalizes width, case, camelCase, and separators", () => {+ assert.equal(normalizeCommandSearchText("GlobalSearch/core-command"), "global search core command");+ assert.equal(normalizeCommandSearchText("COMMAND_ID"), "command id");+ });++ it("searches the current label and English label", () => {+ assert.deepEqual(searchCommands(commands, "全局").map(item => item.id), ["core.general.globalSearch"]);+ assert.deepEqual(searchCommands(commands, "global search").map(item => item.id), ["core.general.globalSearch"]);+ assert.deepEqual(searchCommands(commands, "read only").map(item => item.id), [+ "core.editor.general.switchReadonly",+ ]);+ });++ it("searches stable IDs and keywords with multiple tokens", () => {+ assert.deepEqual(searchCommands(commands, "general global").map(item => item.id), [+ "core.general.globalSearch",+ ]);+ assert.deepEqual(searchCommands(commands, "workspace find").map(item => item.id), [+ "core.general.globalSearch",+ ]);+ assert.deepEqual(searchCommands(commands, "globalsearch").map(item => item.id), [+ "core.general.globalSearch",+ ]);+ assert.deepEqual(searchCommands(commands, "GLOBALSEARCH").map(item => item.id), [+ "core.general.globalSearch",+ ]);+ });++ it("ranks exact and prefix matches without disturbing ties", () => {+ const ranked = [+ createCommand({id: "sample.contains", label: "Open global search"}),+ createCommand({id: "sample.exact", label: "Search"}),+ createCommand({id: "sample.prefix", label: "Search documents"}),+ ];++ assert.deepEqual(searchCommands(ranked, "search").map(item => item.id), [+ "sample.exact",+ "sample.prefix",+ "sample.contains",+ ]);+ assert.deepEqual(searchCommands(ranked, "").map(item => item.id), ranked.map(item => item.id));+ });+});diff --git a/app/src/command/search.ts b/app/src/command/search.tsnew file mode 100644index 0000000000..ca53f8db8a--- /dev/null+++ b/app/src/command/search.ts@@ -0,0 +1,45 @@+import type {ICommandDefinition} from "./types";++export const normalizeCommandSearchText = (value: string) => value+ .normalize("NFKC")+ .replace(/([a-z\d])([A-Z])/g, "$1 $2")+ .replace(/[._:/\\-]+/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ .toLowerCase();++const getSearchFields = (command: ICommandDefinition) => {+ const normalizedFields = [+ command.label(),+ command.englishLabel?.() || "",+ command.id,+ ...(command.keywords?.() || []),+ ].map(normalizeCommandSearchText).filter(Boolean);+ return [...new Set(normalizedFields.flatMap(field => [field, field.replace(/ /g, "")]))];+};++const getScore = (fields: string[], query: string, tokens: string[]) => {+ if (!query) {+ return 0;+ }+ if (!tokens.every(token => fields.some(field => field.includes(token)))) {+ return -1;+ }+ if (fields.some(field => field === query)) {+ return 300;+ }+ if (fields.some(field => field.startsWith(query))) {+ return 200;+ }+ return 100;+};++export const searchCommands = (commands: ICommandDefinition[], value: string) => {+ const query = normalizeCommandSearchText(value);+ const tokens = query.split(" ").filter(Boolean);+ return commands+ .map((command, index) => ({command, index, score: getScore(getSearchFields(command), query, tokens)}))+ .filter(item => item.score >= 0)+ .sort((first, second) => second.score - first.score || first.index - second.index)+ .map(item => item.command);+};diff --git a/app/src/command/service.ts b/app/src/command/service.tsnew file mode 100644index 0000000000..51fef574dd--- /dev/null+++ b/app/src/command/service.ts@@ -0,0 +1,12 @@+import {CommandRegistry} from "./registry";++const registries = new WeakMap<object, CommandRegistry>();++export const getCommandRegistry = (app: object) => {+ let registry = registries.get(app);+ if (!registry) {+ registry = new CommandRegistry();+ registries.set(app, registry);+ }+ return registry;+};diff --git a/app/src/command/types.ts b/app/src/command/types.tsnew file mode 100644index 0000000000..41ce835b28--- /dev/null+++ b/app/src/command/types.ts@@ -0,0 +1,102 @@+export type TCommandSource =+ "commandPanel" |+ "shortcut" |+ "editorShortcut" |+ "fileTreeShortcut" |+ "dockShortcut" |+ "globalShortcut" |+ "keymap" |+ "menu" |+ "api";++export type TCommandFocus = "global" | "editor" | "fileTree" | "dock";++export type TCommandEnvironment =+ "desktop" |+ "desktop-window" |+ "mobile" |+ "browser-desktop" |+ "browser-mobile";++export interface ICommandDocumentContext {+ id?: string;+ rootId?: string;+ notebookId?: string;+ path?: string;+}++export interface ICommandBlockContext {+ id: string;+ element: HTMLElement;+}++export interface ICommandTableCellContext {+ element: HTMLTableCellElement;+ row: number;+ column: number;+}++export interface ICommandFileTreeContext {+ model?: unknown;+ elements: Element[];+ ids: string[];+ paths: string[];+}++export interface ICommandTabContext {+ id?: string;+ model?: unknown;+ element?: HTMLElement;+}++export interface ICommandDockContext {+ type?: string;+ element: HTMLElement;+}++export interface ICommandContextSnapshot {+ app: object;+ source: TCommandSource;+ environment: TCommandEnvironment;+ focus: TCommandFocus;+ range?: Range;+ activeElement?: Element;+ protyle?: IProtyle;+ document?: ICommandDocumentContext;+ block?: ICommandBlockContext;+ selectedBlocks: ICommandBlockContext[];+ tableCell?: ICommandTableCellContext;+ fileTree?: ICommandFileTreeContext;+ activeTab?: ICommandTabContext;+ dock?: ICommandDockContext;+}++export type TCommandKeymapPath =+ readonly ["general", string] |+ readonly ["editor", string, string] |+ readonly ["plugin", string, string];++export interface ICommandDefinition {+ id: string;+ category: "core" | "plugin";+ label: () => string;+ englishLabel?: () => string | undefined;+ keywords?: () => readonly string[];+ icon?: string;+ keymapPath?: TCommandKeymapPath;+ hotkey?: () => string;+ surfaces?: readonly TCommandSource[];+ order?: number;+ platform?: (environment: TCommandEnvironment) => boolean;+ when?: (context: ICommandContextSnapshot) => boolean;+ enabled?: (context: ICommandContextSnapshot) => boolean;+ execute: (context: ICommandContextSnapshot, args?: unknown) => unknown | Promise<unknown>;+}++export type TCommandExecutionStatus = "executed" | "notFound" | "unavailable" | "disabled";++export interface ICommandExecutionResult {+ status: TCommandExecutionStatus;+ command?: ICommandDefinition;+ value?: unknown;+}diff --git a/app/src/plugin/commandAdapter.test.ts b/app/src/plugin/commandAdapter.test.tsnew file mode 100644index 0000000000..fcbbaf8cd8--- /dev/null+++ b/app/src/plugin/commandAdapter.test.ts@@ -0,0 +1,254 @@+import {afterEach, describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getCommandRegistry} from "../command/service";+import type {ICommandContextSnapshot} from "../command/types";+import {+ createPluginCommandDefinition,+ getPluginCommandId,+ registerPluginCommand,+ resolvePluginCommandCallback,+ unregisterPluginCommands,+} from "./commandAdapter";++const owners: object[] = [];++afterEach(() => {+ owners.forEach(owner => unregisterPluginCommands(owner));+ owners.length = 0;+});++const createContext = (+ overrides: Partial<ICommandContextSnapshot> = {},+): ICommandContextSnapshot => ({+ app: {},+ source: "commandPanel",+ environment: "desktop",+ focus: "global",+ selectedBlocks: [],+ ...overrides,+});++describe("plugin command adapter", () => {+ it("creates collision-safe IDs and live metadata", () => {+ const plugin = {name: "sample/plugin", displayName: "Sample", i18n: {open: "Open"}};+ const command = {langKey: "open:item", customHotkey: "Ctrl+A"} as ICommand;+ const definition = createPluginCommandDefinition(plugin, command);++ assert.equal(definition.id, "plugin/sample%2Fplugin/open%3Aitem");+ assert.equal(getPluginCommandId("first", "open"), "plugin/first/open");+ assert.notEqual(getPluginCommandId("first", "open"), getPluginCommandId("second", "open"));+ assert.equal(definition.label(), "Sample: open:item");+ assert.equal(definition.hotkey?.(), "Ctrl+A");+ command.customHotkey = "Ctrl+B";+ command.langText = "Open item";+ assert.equal(definition.hotkey?.(), "Ctrl+B");+ assert.equal(definition.label(), "Sample: Open item");+ });++ it("keeps the command panel callback precedence", () => {+ const calls: string[] = [];+ const command = {+ langKey: "sample",+ callback: () => calls.push("callback"),+ editorCallback: () => calls.push("editor"),+ globalCallback: () => calls.push("global"),+ } as ICommand;+ const callback = resolvePluginCommandCallback(command, createContext({+ focus: "editor",+ protyle: {} as IProtyle,+ }));++ callback?.();+ assert.deepEqual(calls, ["callback"]);+ });++ it("preserves the plugin command as the callback receiver", () => {+ const receivers: unknown[] = [];+ const command = {+ langKey: "sample",+ callback() {+ receivers.push(this);+ },+ globalCallback() {+ receivers.push(this);+ },+ } as ICommand;++ resolvePluginCommandCallback(command, createContext())?.();+ resolvePluginCommandCallback(command, createContext({source: "globalShortcut"}))?.();++ assert.deepEqual(receivers, [command, command]);+ });++ it("dispatches editor, file tree, and dock callbacks from the captured context", () => {+ const calls: unknown[] = [];+ const protyle = {} as IProtyle;+ const files = {} as import("../layout/dock/Files").Files;+ const dockElement = {} as HTMLElement;+ const command = {+ langKey: "sample",+ editorCallback: value => calls.push(value),+ fileTreeCallback: value => calls.push(value),+ dockCallback: value => calls.push(value),+ } as ICommand;++ resolvePluginCommandCallback(command, createContext({focus: "editor", protyle}))?.();+ resolvePluginCommandCallback(command, createContext({+ focus: "fileTree",+ fileTree: {model: files, elements: [], ids: [], paths: []},+ }))?.();+ resolvePluginCommandCallback(command, createContext({+ focus: "dock",+ dock: {element: dockElement},+ }))?.();++ assert.deepEqual(calls, [protyle, files, dockElement]);+ });++ it("does not enable specialized callbacks on mobile", () => {+ const command = {langKey: "sample", editorCallback: () => undefined} as ICommand;+ const context = createContext({+ environment: "mobile",+ focus: "editor",+ protyle: {} as IProtyle,+ });++ assert.equal(resolvePluginCommandCallback(command, context), undefined);+ });++ it("does not treat the bottom backlink panel as a plugin dock", () => {+ const command = {langKey: "sample", dockCallback: () => undefined} as ICommand;+ const context = createContext({+ focus: "dock",+ dock: {type: "backlink-bottom", element: {} as HTMLElement},+ });++ assert.equal(resolvePluginCommandCallback(command, context), undefined);+ assert.equal(resolvePluginCommandCallback(command, {...context, source: "dockShortcut"}), undefined);+ });++ it("keeps unavailable scoped commands visible as disabled entries", async () => {+ const app = {};+ const plugin = {name: "scoped", displayName: "Scoped", i18n: {editor: "Editor"}};+ const command = {langKey: "editor", editorCallback: () => undefined} as ICommand;+ owners.push(plugin);+ registerPluginCommand(app, plugin, command);+ const registry = getCommandRegistry(app);+ const context = createContext({app});+ const commandId = getPluginCommandId(plugin.name, command.langKey);++ assert.deepEqual(registry.list(context).map(item => item.id), [commandId]);+ assert.equal((await registry.execute(commandId, context)).status, "disabled");+ });++ it("uses global callbacks only for global shortcuts or a main command panel", () => {+ let calls = 0;+ const command = {langKey: "sample", globalCallback: () => calls++} as ICommand;++ resolvePluginCommandCallback(command, createContext())?.();+ assert.equal(calls, 1);+ assert.equal(resolvePluginCommandCallback(command, createContext({environment: "desktop-window"})), undefined);+ assert.equal(resolvePluginCommandCallback(command, createContext({environment: "mobile"})), undefined);+ assert.equal(resolvePluginCommandCallback(command, createContext({environment: "browser-mobile"})), undefined);+ resolvePluginCommandCallback(command, createContext({+ source: "globalShortcut",+ environment: "desktop-window",+ }))?.();+ assert.equal(calls, 2);+ });++ it("preserves generic shortcut restrictions", () => {+ let calls = 0;+ const generic = {langKey: "generic", callback: () => calls++} as ICommand;+ const specialized = {+ langKey: "specialized",+ callback: () => calls++,+ editorCallback: () => calls++,+ } as ICommand;++ ["global", "editor", "fileTree", "dock"].forEach(focus => {+ resolvePluginCommandCallback(generic, createContext({+ source: "shortcut",+ focus: focus as ICommandContextSnapshot["focus"],+ }))?.();+ });+ resolvePluginCommandCallback(generic, createContext({+ source: "shortcut",+ environment: "mobile",+ focus: "editor",+ }))?.();+ assert.equal(resolvePluginCommandCallback(specialized, createContext({source: "shortcut"})), undefined);+ assert.equal(calls, 5);+ });++ it("keeps scoped shortcut callbacks separate", () => {+ const calls: string[] = [];+ const command = {+ langKey: "scoped",+ callback: () => calls.push("generic"),+ editorCallback: () => calls.push("editor"),+ fileTreeCallback: () => calls.push("fileTree"),+ dockCallback: () => calls.push("dock"),+ } as ICommand;+ const protyle = {} as IProtyle;+ const files = {} as import("../layout/dock/Files").Files;+ const element = {} as HTMLElement;++ resolvePluginCommandCallback(command, createContext({source: "editorShortcut", protyle}))?.();+ resolvePluginCommandCallback(command, createContext({+ source: "fileTreeShortcut",+ fileTree: {model: files, elements: [], ids: [], paths: []},+ }))?.();+ resolvePluginCommandCallback(command, createContext({+ source: "dockShortcut",+ dock: {element},+ }))?.();+ assert.equal(resolvePluginCommandCallback(command, createContext({source: "shortcut"})), undefined);+ assert.deepEqual(calls, ["editor", "fileTree", "dock"]);+ });++ it("registers the first duplicate command and removes it with its owner", async () => {+ const app = {};+ const plugin = {name: "sample", displayName: "Sample", i18n: {first: "First"}};+ const calls: string[] = [];+ owners.push(plugin);+ const originalError = console.error;+ console.error = () => undefined;+ try {+ registerPluginCommand(app, plugin, {langKey: "first", callback: () => calls.push("first")} as ICommand);+ registerPluginCommand(app, plugin, {langKey: "first", callback: () => calls.push("second")} as ICommand);+ } finally {+ console.error = originalError;+ }+ const registry = getCommandRegistry(app);+ const context = createContext({app});+ const commandId = getPluginCommandId("sample", "first");++ assert.equal((await registry.execute(commandId, context)).status, "executed");+ assert.deepEqual(calls, ["first"]);+ assert.equal(unregisterPluginCommands(plugin), 1);+ assert.equal(registry.get(commandId), undefined);+ registerPluginCommand(app, plugin, {langKey: "late", callback: () => undefined} as ICommand);+ assert.equal(registry.get(getPluginCommandId("sample", "late")), undefined);+ });++ it("keeps a reloaded instance when the old owner is cleaned again", async () => {+ const app = {};+ const oldPlugin = {name: "sample", displayName: "Old", i18n: {open: "Open"}};+ const newPlugin = {name: "sample", displayName: "New", i18n: {open: "Open"}};+ const calls: string[] = [];+ owners.push(oldPlugin, newPlugin);+ registerPluginCommand(app, oldPlugin, {langKey: "open", callback: () => calls.push("old")} as ICommand);+ assert.equal(unregisterPluginCommands(oldPlugin), 1);+ assert.equal(unregisterPluginCommands(oldPlugin), 0);+ registerPluginCommand(app, newPlugin, {langKey: "open", callback: () => calls.push("new")} as ICommand);+ unregisterPluginCommands(oldPlugin);++ const result = await getCommandRegistry(app).execute(+ getPluginCommandId("sample", "open"),+ createContext({app}),+ );+ assert.equal(result.status, "executed");+ assert.deepEqual(calls, ["new"]);+ });+});diff --git a/app/src/plugin/commandAdapter.ts b/app/src/plugin/commandAdapter.tsnew file mode 100644index 0000000000..68208647b6--- /dev/null+++ b/app/src/plugin/commandAdapter.ts@@ -0,0 +1,128 @@+import {getCommandRegistry} from "../command/service";+import type {ICommandContextSnapshot, ICommandDefinition} from "../command/types";++interface IPluginCommandOwner {+ name: string;+ displayName: string;+ i18n: Record<string, string>;+}++interface IPluginCommandRegistration {+ registry: ReturnType<typeof getCommandRegistry>;+ disposers: Set<() => boolean>;+}++const registrations = new WeakMap<object, IPluginCommandRegistration>();+const inactiveOwners = new WeakSet<object>();++export const getPluginCommandId = (pluginName: string, langKey: string) =>+ `plugin/${encodeURIComponent(pluginName)}/${encodeURIComponent(langKey)}`;++const isMobileContext = (context: ICommandContextSnapshot) =>+ context.environment === "mobile" || context.environment === "browser-mobile";++const hasPluginDockContext = (context: ICommandContextSnapshot) =>+ Boolean(context.dock?.element && context.dock.type !== "backlink-bottom");++export const resolvePluginCommandCallback = (command: ICommand, context: ICommandContextSnapshot) => {+ if (context.source === "globalShortcut") {+ return command.globalCallback ? () => command.globalCallback() : undefined;+ }+ if (context.source === "commandPanel") {+ if (command.callback) {+ return () => command.callback();+ }+ if (!isMobileContext(context)) {+ if (context.focus === "editor" && context.protyle && command.editorCallback) {+ return () => command.editorCallback(context.protyle);+ }+ if (context.focus === "fileTree" && context.fileTree?.model && command.fileTreeCallback) {+ return () => command.fileTreeCallback(+ context.fileTree.model as import("../layout/dock/Files").Files,+ );+ }+ if (context.focus === "dock" && hasPluginDockContext(context) && command.dockCallback) {+ return () => command.dockCallback(context.dock.element);+ }+ }+ if (command.globalCallback && ["desktop", "browser-desktop"].includes(context.environment)) {+ return () => command.globalCallback();+ }+ return undefined;+ }+ if (context.source === "editorShortcut" && context.protyle && command.editorCallback) {+ return () => command.editorCallback(context.protyle);+ }+ if (context.source === "fileTreeShortcut" && context.fileTree?.model && command.fileTreeCallback) {+ return () => command.fileTreeCallback(+ context.fileTree.model as import("../layout/dock/Files").Files,+ );+ }+ if (context.source === "dockShortcut" && hasPluginDockContext(context) && command.dockCallback) {+ return () => command.dockCallback(context.dock.element);+ }+ if (context.source === "shortcut") {+ if (command.callback &&+ !command.fileTreeCallback && !command.editorCallback && !command.dockCallback && !command.globalCallback) {+ return () => command.callback();+ }+ }+ return undefined;+};++export const createPluginCommandDefinition = (+ plugin: IPluginCommandOwner,+ command: ICommand,+): ICommandDefinition => {+ const id = getPluginCommandId(plugin.name, command.langKey);+ return {+ id,+ category: "plugin",+ label: () => `${plugin.displayName}: ${command.langText || plugin.i18n[command.langKey] || command.langKey}`,+ keywords: () => [plugin.displayName, plugin.name, command.langKey, id],+ keymapPath: ["plugin", plugin.name, command.langKey],+ hotkey: () => command.customHotkey || "",+ order: 10_000,+ enabled: context => Boolean(resolvePluginCommandCallback(command, context)),+ execute: context => resolvePluginCommandCallback(command, context)?.(),+ };+};++export const registerPluginCommand = (+ app: object,+ plugin: IPluginCommandOwner & object,+ command: ICommand,+) => {+ if (inactiveOwners.has(plugin)) {+ return;+ }+ const registry = getCommandRegistry(app);+ let registration = registrations.get(plugin);+ if (!registration) {+ registration = {registry, disposers: new Set()};+ registrations.set(plugin, registration);+ }+ try {+ registration.disposers.add(registry.register(createPluginCommandDefinition(plugin, command), plugin));+ } catch (error) {+ console.error(`Plugin ${plugin.name} command "${command.langKey}" was not registered:`, error);+ }+};++export const unregisterPluginCommands = (plugin: object) => {+ inactiveOwners.add(plugin);+ const registration = registrations.get(plugin);+ if (!registration) {+ return 0;+ }+ let count = 0;+ registration.disposers.forEach(dispose => {+ if (dispose()) {+ count++;+ }+ });+ registration.disposers.clear();+ registration.registry.unregisterOwner(plugin);+ registrations.delete(plugin);+ return count;+};diff --git a/app/src/search/config.test.ts b/app/src/search/config.test.tsnew file mode 100644index 0000000000..562a528d42--- /dev/null+++ b/app/src/search/config.test.ts@@ -0,0 +1,340 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ cloneSearchConfig,+ getSearchPathID,+ getGlobalSearchPath,+ hasExplicitSearchScope,+ hasSearchConfigTemporaryPath,+ isSameSearchPath,+ isCurrentSearchPath,+ isSearchPathRequestVersionCurrent,+ isSearchPathAffectedByNotebookRename,+ isSearchPathAffectedByRename,+ nextSearchPathRequestVersion,+ refreshSearchConfigHPath,+ replaceSearchConfigPath,+ resolvePersistedSearchConfig,+ resolveSearchHPath,+ resolveSearchNotebookHPath,+ resolveSearchConfig,+ setSearchConfigTemporaryPath,+ syncSearchConfig,+ syncSearchConfigHPath,+} from "./config";++describe("search configuration scope", () => {+ const criterionA: Config.IUILayoutTabSearchConfig = {+ removed: false,+ name: "criterion A",+ hPath: "Notebook/Document A",+ idPath: ["notebook/document-a"],+ k: "keyword",+ method: 0,+ };+ const documentB: Config.IUILayoutTabSearchConfig = {+ removed: false,+ hPath: "Notebook/Document B",+ idPath: ["notebook/document-b"],+ k: "keyword",+ method: 0,+ };++ it("keeps the current document effective without changing the saved criterion", () => {+ const result = resolveSearchConfig(criterionA, documentB, true);++ assert.equal(result.effectiveConfig.hPath, documentB.hPath);+ assert.deepEqual(result.effectiveConfig.idPath, documentB.idPath);+ assert.equal(result.persistedConfig.hPath, criterionA.hPath);+ assert.deepEqual(result.persistedConfig.idPath, criterionA.idPath);+ assert.equal(criterionA.hPath, "Notebook/Document A");+ assert.deepEqual(criterionA.idPath, ["notebook/document-a"]);++ result.effectiveConfig.idPath.push("notebook/document-b-child");+ assert.deepEqual(documentB.idPath, ["notebook/document-b"]);+ assert.deepEqual(result.persistedConfig.idPath, ["notebook/document-a"]);+ });++ it("restores the saved criterion path for global search", () => {+ const {persistedConfig} = resolveSearchConfig(criterionA, documentB, true);+ const globalPath = getGlobalSearchPath(persistedConfig);++ assert.equal(globalPath.hPath, criterionA.hPath);+ assert.deepEqual(globalPath.idPath, criterionA.idPath);+ assert.notEqual(globalPath.idPath, persistedConfig.idPath);+ });++ it("clears the global path after the criterion is removed", () => {+ const globalPath = getGlobalSearchPath({+ removed: true,+ hPath: documentB.hPath,+ idPath: [...documentB.idPath],+ });++ assert.deepEqual(globalPath, {+ hPath: "",+ idPath: [],+ });+ });++ it("keeps the persisted path when a shortcut changes the effective scope", () => {+ const effectiveDocumentSearch = replaceSearchConfigPath(criterionA, documentB);+ const persistedDocumentSearch = replaceSearchConfigPath(effectiveDocumentSearch, criterionA);+ const globalPath = getGlobalSearchPath(persistedDocumentSearch);++ assert.equal(effectiveDocumentSearch.hPath, documentB.hPath);+ assert.deepEqual(effectiveDocumentSearch.idPath, documentB.idPath);+ assert.equal(persistedDocumentSearch.hPath, criterionA.hPath);+ assert.deepEqual(globalPath.idPath, criterionA.idPath);+ });++ it("does not persist temporary document paths after changing other options", () => {+ const activeCriterionConfig = resolvePersistedSearchConfig(documentB, criterionA, true);+ const removedCriterionConfig = resolvePersistedSearchConfig({+ ...documentB,+ removed: true,+ }, criterionA, true);++ assert.equal(activeCriterionConfig.hPath, criterionA.hPath);+ assert.deepEqual(activeCriterionConfig.idPath, criterionA.idPath);+ assert.equal(removedCriterionConfig.hPath, "");+ assert.deepEqual(removedCriterionConfig.idPath, []);+ });++ it("treats explicitly scoped replace paths as temporary", () => {+ assert.equal(hasExplicitSearchScope({}), false);+ assert.equal(hasExplicitSearchScope({notebookIds: []}), false);+ assert.equal(hasExplicitSearchScope({notebookId: "notebook"}), true);+ assert.equal(hasExplicitSearchScope({notebookIds: ["notebook-a", "notebook-b"]}), true);++ const scopedReplace = {+ ...documentB,+ hasReplace: true,+ };+ const replaceCriterion = {+ ...criterionA,+ hasReplace: true,+ replaceTypes: {text: true},+ };+ setSearchConfigTemporaryPath(scopedReplace, hasExplicitSearchScope({notebookId: "notebook"}));++ const appliedCriterion = resolveSearchConfig(+ replaceCriterion,+ scopedReplace,+ hasSearchConfigTemporaryPath(scopedReplace),+ );+ syncSearchConfig(scopedReplace, appliedCriterion.effectiveConfig);+ scopedReplace.method = 3;+ scopedReplace.replaceTypes = {text: false};+ const pinnedSearchConfig = cloneSearchConfig(scopedReplace);+ const persistedConfig = resolvePersistedSearchConfig(+ scopedReplace,+ appliedCriterion.persistedConfig,+ hasSearchConfigTemporaryPath(scopedReplace),+ );++ assert.equal(scopedReplace.hPath, documentB.hPath);+ assert.deepEqual(scopedReplace.idPath, documentB.idPath);+ assert.equal(persistedConfig.hPath, criterionA.hPath);+ assert.deepEqual(persistedConfig.idPath, criterionA.idPath);+ assert.equal(persistedConfig.method, 3);+ assert.deepEqual(persistedConfig.replaceTypes, {text: false});+ assert.equal(hasSearchConfigTemporaryPath(pinnedSearchConfig), false);+ });++ it("detects renamed documents that affect the current search path", () => {+ assert.equal(isSearchPathAffectedByRename(+ ["notebook/parent/document"], "notebook", "/parent/document.sy", "document"), true);+ assert.equal(isSearchPathAffectedByRename(+ ["notebook/parent/document.sy"], "notebook", "/parent.sy", "parent"), true);+ assert.equal(isSearchPathAffectedByRename(+ ["document"], "notebook", "/parent/document.sy", "document"), true);+ assert.equal(isSearchPathAffectedByRename(+ ["notebook/other"], "notebook", "/parent/document.sy", "document"), false);+ assert.equal(isSearchPathAffectedByRename(+ ["notebook/parent"], "notebook", "/parent/child.sy", "child"), false);+ assert.equal(isSearchPathAffectedByRename(+ ["notebook/parent2"], "notebook", "/parent.sy", "parent"), false);+ assert.equal(isSearchPathAffectedByRename(+ ["notebook/parent/document"], "notebook", "/parent/document.sy", undefined), true);+ assert.equal(isSearchPathAffectedByRename(+ ["document"], "notebook", "/parent/document.sy", undefined), true);+ });++ it("detects notebook renames for notebook and document scopes", () => {+ assert.equal(isSearchPathAffectedByNotebookRename(["notebook"], "notebook"), true);+ assert.equal(isSearchPathAffectedByNotebookRename(["notebook/parent/document"], "notebook"), true);+ assert.equal(isSearchPathAffectedByNotebookRename(["notebook2/document"], "notebook"), false);+ });++ it("resolves notebook scopes without requiring a document block", () => {+ const notebooks = [{id: "notebook", name: "Old Notebook"}];++ assert.equal(resolveSearchNotebookHPath("notebook", notebooks), "Old Notebook");+ assert.equal(resolveSearchNotebookHPath("notebook", notebooks, {notebook: "Renamed Notebook"}),+ "Renamed Notebook");+ assert.equal(resolveSearchNotebookHPath("document", notebooks), undefined);+ });++ it("validates that a stored search path has not moved", () => {+ assert.equal(getSearchPathID("notebook/parent/document.sy"), "document");+ assert.equal(isCurrentSearchPath(+ "notebook/parent/document", "notebook", "/parent/document.sy"), true);+ assert.equal(isCurrentSearchPath(+ "notebook/parent/document.sy", "notebook", "/parent/document.sy"), true);+ assert.equal(isCurrentSearchPath(+ "notebook/parent/document", "notebook", "/moved/document.sy"), false);+ assert.equal(isCurrentSearchPath(+ "notebook/parent/document", "other-notebook", "/parent/document.sy"), false);+ assert.equal(isCurrentSearchPath("notebook", "notebook", "/notebook.sy"), true);+ assert.equal(isCurrentSearchPath("document", "notebook", "/parent/document.sy"), true);+ });++ it("updates only a persisted human-readable path for the same stable scope", () => {+ const persistedCriterion = cloneSearchConfig(criterionA);+ const renamedCriterion = {+ ...cloneSearchConfig(criterionA),+ hPath: "Notebook/Renamed Document A",+ };+ assert.equal(syncSearchConfigHPath(persistedCriterion, renamedCriterion), true);+ assert.equal(persistedCriterion.hPath, renamedCriterion.hPath);++ const persistedOtherScope = cloneSearchConfig(criterionA);+ assert.equal(syncSearchConfigHPath(persistedOtherScope, documentB), false);+ assert.equal(persistedOtherScope.hPath, criterionA.hPath);+ });++ it("invalidates older asynchronous search path requests", () => {+ const searchElement = {};+ const firstVersion = nextSearchPathRequestVersion(searchElement);+ assert.equal(isSearchPathRequestVersionCurrent(searchElement, firstVersion), true);++ const secondVersion = nextSearchPathRequestVersion(searchElement);+ assert.equal(isSearchPathRequestVersionCurrent(searchElement, firstVersion), false);+ assert.equal(isSearchPathRequestVersionCurrent(searchElement, secondVersion), true);+ });++ it("resolves current human-readable paths without changing their stable paths", async () => {+ const idPath = ["notebook/parent/document", "notebook/second"];+ const requestedPaths: string[] = [];+ const hPath = await resolveSearchHPath(idPath, async (path) => {+ requestedPaths.push(path);+ return path.endsWith("document") ? "Notebook/New <Title>" : "Notebook/Second";+ });++ assert.equal(hPath, "Notebook/New <Title> Notebook/Second");+ assert.deepEqual(requestedPaths, idPath);+ assert.deepEqual(idPath, ["notebook/parent/document", "notebook/second"]);+ assert.equal(await resolveSearchHPath([], async () => "unused"), undefined);+ assert.equal(await resolveSearchHPath(idPath, async () => undefined), undefined);+ assert.equal(await resolveSearchHPath(idPath, async () => {+ throw new Error("unavailable");+ }), undefined);+ });++ it("keeps the configured order when path requests finish out of order", async () => {+ const idPath = ["notebook/first", "notebook/second"];+ const resolvers = new Map<string, (value: string) => void>();+ const hPathPromise = resolveSearchHPath(idPath, (path) => new Promise((resolve) => {+ resolvers.set(path, resolve);+ }));++ resolvers.get(idPath[1])("Notebook/Second");+ resolvers.get(idPath[0])("Notebook/First");++ assert.equal(await hPathPromise, "Notebook/First Notebook/Second");+ });++ it("refreshes the original search configuration after resolving its current path", async () => {+ const config: Config.IUILayoutTabSearchConfig = {+ ...documentB,+ hPath: "Notebook/Old Document B",+ idPath: [...documentB.idPath],+ };+ const reference = config;+ let resolvedPath: string[];+ let renderedPath = "";++ const refreshed = await refreshSearchConfigHPath({+ config,+ resolveHPath: async (idPath) => {+ resolvedPath = idPath;+ return "Notebook/Renamed Document B";+ },+ render: (hPath) => {+ renderedPath = hPath;+ },+ });++ assert.equal(refreshed, true);+ assert.equal(config, reference);+ assert.equal(config.hPath, "Notebook/Renamed Document B");+ assert.deepEqual(config.idPath, documentB.idPath);+ assert.deepEqual(resolvedPath, documentB.idPath);+ assert.notEqual(resolvedPath, config.idPath);+ assert.equal(renderedPath, config.hPath);+ });++ it("discards a resolved path after the stable scope changes", async () => {+ const config: Config.IUILayoutTabSearchConfig = {+ ...documentB,+ hPath: "Notebook/Old Document B",+ idPath: [...documentB.idPath],+ };+ let resolveHPath: (value: string) => void;+ let rendered = false;+ const refreshed = refreshSearchConfigHPath({+ config,+ resolveHPath: () => new Promise((resolve) => {+ resolveHPath = resolve;+ }),+ render: () => {+ rendered = true;+ },+ });++ config.idPath = ["notebook/other"];+ resolveHPath("Notebook/Renamed Document B");++ assert.equal(await refreshed, false);+ assert.equal(config.hPath, "Notebook/Old Document B");+ assert.equal(rendered, false);+ });++ it("does not refresh when the request is stale or fails", async () => {+ const staleConfig = cloneSearchConfig(documentB);+ assert.equal(await refreshSearchConfigHPath({+ config: staleConfig,+ resolveHPath: async () => "Notebook/Renamed Document B",+ isCurrent: () => false,+ }), false);+ assert.equal(staleConfig.hPath, documentB.hPath);++ const failedConfig = cloneSearchConfig(documentB);+ assert.equal(await refreshSearchConfigHPath({+ config: failedConfig,+ resolveHPath: async () => {+ throw new Error("unavailable");+ },+ }), false);+ assert.equal(failedConfig.hPath, documentB.hPath);+ assert.equal(isSameSearchPath(documentB.idPath, failedConfig.idPath), true);+ });++ it("updates shared configuration references in place", () => {+ const target: Config.IUILayoutTabSearchConfig = {+ hPath: documentB.hPath,+ idPath: [...documentB.idPath],+ query: "stale query",+ };+ const reference = target;++ const result = syncSearchConfig(target, criterionA);++ assert.equal(result, reference);+ assert.equal(reference.hPath, criterionA.hPath);+ assert.deepEqual(reference.idPath, criterionA.idPath);+ assert.equal(reference.query, undefined);+ assert.notEqual(reference.idPath, criterionA.idPath);+ });+});diff --git a/app/src/search/config.ts b/app/src/search/config.tsnew file mode 100644index 0000000000..dd98a7d818--- /dev/null+++ b/app/src/search/config.ts@@ -0,0 +1,193 @@+const temporaryPathConfigs = new WeakSet<Config.IUILayoutTabSearchConfig>();+const searchPathRequestVersions = new WeakMap<object, number>();++export const nextSearchPathRequestVersion = (target: object) => {+ const version = (searchPathRequestVersions.get(target) || 0) + 1;+ searchPathRequestVersions.set(target, version);+ return version;+};++export const isSearchPathRequestVersionCurrent = (target: object, version: number) => {+ return searchPathRequestVersions.get(target) === version;+};++export const hasExplicitSearchScope = (options: {+ notebookId?: string,+ notebookIds?: string[],+}) => {+ return Boolean(options.notebookId || options.notebookIds?.length);+};++export const setSearchConfigTemporaryPath = (config: Config.IUILayoutTabSearchConfig, temporary: boolean) => {+ if (temporary) {+ temporaryPathConfigs.add(config);+ } else {+ temporaryPathConfigs.delete(config);+ }+};++export const hasSearchConfigTemporaryPath = (config: Config.IUILayoutTabSearchConfig) => {+ return temporaryPathConfigs.has(config);+};++const normalizeSearchPath = (value: string) => {+ return value.replace(/\\/g, "/").replace(/\.sy$/, "").replace(/^\/+|\/+$/g, "");+};++export const getSearchPathID = (path: string) => {+ return normalizeSearchPath(path).split("/").pop() || "";+};++export const resolveSearchNotebookHPath = (path: string, notebooks: {id: string, name: string}[],+ notebookNames: Record<string, string> = {}) => {+ const id = getSearchPathID(path);+ const notebook = notebooks.find((item) => item.id === id);+ if (notebook) {+ return notebookNames[id] || notebook.name;+ }+};++export const isCurrentSearchPath = (searchPath: string, notebookId: string, path: string) => {+ const normalizedSearchPath = normalizeSearchPath(searchPath);+ const normalizedNotebookId = normalizeSearchPath(notebookId);+ if (normalizedSearchPath.includes("/")) {+ return normalizedSearchPath === `${normalizedNotebookId}/${normalizeSearchPath(path)}`;+ }+ return normalizedSearchPath === normalizedNotebookId || normalizedSearchPath === getSearchPathID(path);+};++export const isSearchPathAffectedByRename = (idPath: string[], notebookId: string, path: string, id?: string) => {+ const renamedPath = `${normalizeSearchPath(notebookId)}/${normalizeSearchPath(path)}`;+ const renamedId = typeof id === "string" ? normalizeSearchPath(id) : getSearchPathID(path);+ return idPath.some((item) => {+ const normalizedPath = normalizeSearchPath(item);+ return (renamedId !== "" && normalizedPath === renamedId) || normalizedPath === renamedPath ||+ normalizedPath.startsWith(`${renamedPath}/`);+ });+};++export const isSearchPathAffectedByNotebookRename = (idPath: string[], notebookId: string) => {+ const normalizedNotebookId = normalizeSearchPath(notebookId);+ return idPath.some((item) => {+ const normalizedPath = normalizeSearchPath(item);+ return normalizedPath === normalizedNotebookId || normalizedPath.startsWith(`${normalizedNotebookId}/`);+ });+};++export const isSameSearchPath = (path: string[], targetPath: string[]) => {+ return path.length === targetPath.length && path.every((item, index) => item === targetPath[index]);+};++export const syncSearchConfigHPath = (target: Config.IUILayoutTabSearchConfig,+ source: Config.IUILayoutTabSearchConfig) => {+ if (!isSameSearchPath(target.idPath || [], source.idPath || [])) {+ return false;+ }+ target.hPath = source.hPath;+ return true;+};++export const resolveSearchHPath = async (idPath: string[],+ resolvePath: (path: string) => Promise<string | undefined>) => {+ if (idPath.length === 0) {+ return;+ }+ let hPaths: (string | undefined)[];+ try {+ hPaths = await Promise.all(idPath.map((item) => resolvePath(item)));+ } catch {+ return;+ }+ if (hPaths.some((item) => typeof item !== "string" || item === "")) {+ return;+ }+ return hPaths.join(" ");+};++export const refreshSearchConfigHPath = async (options: {+ config: Config.IUILayoutTabSearchConfig,+ resolveHPath: (idPath: string[]) => Promise<string | undefined>,+ isCurrent?: () => boolean,+ render?: (hPath: string) => void,+}) => {+ const idPath = [...(options.config.idPath || [])];+ if (idPath.length === 0) {+ return false;+ }+ let hPath: string | undefined;+ try {+ hPath = await options.resolveHPath(idPath);+ } catch {+ return false;+ }+ if (!hPath || !isSameSearchPath(idPath, options.config.idPath || []) || options.isCurrent && !options.isCurrent()) {+ return false;+ }+ options.config.hPath = hPath;+ options.render?.(hPath);+ return true;+};++export const cloneSearchConfig = (config: Config.IUILayoutTabSearchConfig) => {+ return JSON.parse(JSON.stringify(config)) as Config.IUILayoutTabSearchConfig;+};++export const syncSearchConfig = (target: Config.IUILayoutTabSearchConfig,+ source: Config.IUILayoutTabSearchConfig) => {+ Object.keys(target).forEach((key) => {+ Reflect.deleteProperty(target, key);+ });+ Object.assign(target, cloneSearchConfig(source));+ return target;+};++export const resolveSearchConfig = (nextConfig: Config.IUILayoutTabSearchConfig,+ currentConfig: Config.IUILayoutTabSearchConfig,+ preserveCurrentPath: boolean) => {+ const persistedConfig = cloneSearchConfig(nextConfig);+ const effectiveConfig = cloneSearchConfig(nextConfig);+ if (preserveCurrentPath) {+ effectiveConfig.hPath = currentConfig.hPath || "";+ effectiveConfig.idPath = [...(currentConfig.idPath || [])];+ }+ return {+ effectiveConfig,+ persistedConfig,+ };+};++export const replaceSearchConfigPath = (config: Config.IUILayoutTabSearchConfig,+ pathConfig: Config.IUILayoutTabSearchConfig) => {+ const result = cloneSearchConfig(config);+ result.hPath = pathConfig.hPath || "";+ result.idPath = [...(pathConfig.idPath || [])];+ return result;+};++export const resolvePersistedSearchConfig = (effectiveConfig: Config.IUILayoutTabSearchConfig,+ previousConfig: Config.IUILayoutTabSearchConfig,+ hasTemporaryPath: boolean) => {+ if (!hasTemporaryPath) {+ return cloneSearchConfig(effectiveConfig);+ }+ if (effectiveConfig.removed) {+ return replaceSearchConfigPath(effectiveConfig, {+ hPath: "",+ idPath: [],+ });+ }+ return replaceSearchConfigPath(effectiveConfig, previousConfig);+};++export const getGlobalSearchPath = (config: Config.IUILayoutTabSearchConfig) => {+ if (config.removed) {+ return {+ hPath: "",+ idPath: [] as string[],+ };+ }+ return {+ hPath: config.hPath || "",+ idPath: [...(config.idPath || [])],+ };+};diff --git a/app/src/search/path.ts b/app/src/search/path.tsnew file mode 100644index 0000000000..2f64285096--- /dev/null+++ b/app/src/search/path.ts@@ -0,0 +1,108 @@+import {fetchSyncPost} from "../util/fetch";+import {escapeHtml} from "../util/escape";+import {+ getSearchPathID,+ isCurrentSearchPath,+ isSearchPathRequestVersionCurrent,+ isSearchPathAffectedByNotebookRename,+ isSearchPathAffectedByRename,+ nextSearchPathRequestVersion,+ refreshSearchConfigHPath,+ resolveSearchNotebookHPath,+ resolveSearchHPath,+} from "./config";++const refreshVersions = new WeakMap<Element, number>();+const notebookNameOverrides = new WeakMap<Element, Record<string, string>>();++const nextRefreshVersion = (element: Element) => {+ const version = (refreshVersions.get(element) || 0) + 1;+ refreshVersions.set(element, version);+ return version;+};++export const beginSearchPathRequest = (element: Element) => {+ const version = nextSearchPathRequestVersion(element);+ nextRefreshVersion(element);+ return () => isSearchPathRequestVersionCurrent(element, version) && element.isConnected;+};++const resolveCurrentSearchHPath = (idPath: string[], notebookNames: Record<string, string> = {}) => {+ return resolveSearchHPath(idPath, async (path) => {+ const id = getSearchPathID(path);+ const notebookHPath = resolveSearchNotebookHPath(path, window.siyuan.notebooks, notebookNames);+ if (notebookHPath) {+ return notebookHPath;+ }+ const hPathResponse = await fetchSyncPost("/api/filetree/getFullHPathByID", {id});+ if (hPathResponse.code !== 0 || typeof hPathResponse.data !== "string") {+ return;+ }+ const pathResponse = await fetchSyncPost("/api/filetree/getPathByID", {id});+ if (pathResponse.code !== 0 || typeof pathResponse.data?.notebook !== "string" ||+ typeof pathResponse.data?.path !== "string" ||+ !isCurrentSearchPath(path, pathResponse.data.notebook, pathResponse.data.path)) {+ return;+ }+ return hPathResponse.data;+ });+};++const renderSearchPath = (element: Element, hPath: string) => {+ const pathElement = element.querySelector("#searchPathInput");+ if (pathElement) {+ pathElement.innerHTML = `${escapeHtml(hPath)}<svg class="search__rmpath"><use xlink:href="#iconCloseRound"></use></svg>`;+ pathElement.setAttribute("aria-label", hPath);+ }+};++export const refreshCurrentSearchPath = async (options: {+ config: Config.IUILayoutTabSearchConfig,+ element: Element,+ resolveHPath?: (idPath: string[]) => Promise<string | undefined>,+}) => {+ const version = nextRefreshVersion(options.element);+ return refreshSearchConfigHPath({+ config: options.config,+ resolveHPath: options.resolveHPath || ((idPath) => resolveCurrentSearchHPath(+ idPath, notebookNameOverrides.get(options.element))),+ isCurrent: () => refreshVersions.get(options.element) === version && options.element.isConnected,+ render: (hPath) => renderSearchPath(options.element, hPath),+ });+};++export const invalidateSearchPathRequests = (element: Element) => {+ nextSearchPathRequestVersion(element);+ nextRefreshVersion(element);+};++export const refreshSearchPathAfterRename = async (options: {+ config: Config.IUILayoutTabSearchConfig,+ element: Element,+ rename: {+ box: string,+ id?: string,+ path: string,+ },+}) => {+ if (!isSearchPathAffectedByRename(options.config.idPath || [], options.rename.box, options.rename.path,+ options.rename.id)) {+ return;+ }+ return refreshCurrentSearchPath(options);+};++export const refreshSearchPathAfterNotebookRename = async (options: {+ config: Config.IUILayoutTabSearchConfig,+ element: Element,+ notebookId: string,+ notebookName: string,+}) => {+ if (!isSearchPathAffectedByNotebookRename(options.config.idPath || [], options.notebookId)) {+ return;+ }+ const notebookNames = notebookNameOverrides.get(options.element) || {};+ notebookNames[options.notebookId] = options.notebookName;+ notebookNameOverrides.set(options.element, notebookNames);+ return refreshCurrentSearchPath(options);+};