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
Vanessad9575b97c111
diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.tsindex c6c5c3dd6d..f4fcf837eb 100644--- a/app/src/boot/globalEvent/command/panel.ts+++ b/app/src/boot/globalEvent/command/panel.ts@@ -2,29 +2,41 @@ import {Dialog} from "../../../dialog";import type {App} from "../../../index";import {upDownHint} from "../../../util/upDownHint";import {updateHotkeyTip} from "../../../protyle/util/compatibility";-import {isMobile, isWindow} from "../../../util/functions";+import {isMobile} from "../../../util/functions";import {Constants} from "../../../constants";-/// #if MOBILE-import {getCurrentEditor} from "../../../mobile/editor";-import {popSearch} from "../../../mobile/menu/search";-/// #else-import {Editor} from "../../../editor";-import {getActiveTab, getDockByType} from "../../../layout/tabUtil";-import {Custom} from "../../../layout/dock/Custom";-import {getAllModels} from "../../../layout/getAll";-import {Files} from "../../../layout/dock/Files";-import {Search} from "../../../search";-import {openSearch} from "../../../search/spread";-/// #endif-import {addEditorToDatabase, addFilesToDatabase} from "../../../protyle/render/av/addToDatabase";-import {hasClosestBlock, hasClosestByClassName, hasTopClosestByTag} from "../../../protyle/util/hasClosest";-import {onlyProtyleCommand} from "./protyle";-import {globalCommand} from "./global";-import {getDisplayName, getNotebookName, getTopPaths, movePathTo, moveToPath, pathPosix} from "../../../util/pathName";-import {hintMoveBlock} from "../../../protyle/hint/extend";-import {fetchSyncPost} from "../../../util/fetch";+import {hasClosestByClassName} from "../../../protyle/util/hasClosest";import {focusByRange} from "../../../protyle/util/selection";import {matchHotKey} from "../../../protyle/util/hotKey";+import {captureCommandContext} from "../../../command/context";+import {ensureCommandSystem, executeCommandById} from "../../../command/executor";+import {initializeEnglishCommandTranslations} from "../../../command/english";+import {createPaletteFocusLifecycle, queryCommandPalette} from "../../../command/paletteCore";+import type {ICommandContextSnapshot, ICommandDefinition} from "../../../command/types";++const renderCommands = (listElement: HTMLElement, commands: ICommandDefinition[]) => {+ const fragment = document.createDocumentFragment();+ commands.forEach(command => {+ const itemElement = document.createElement("li");+ itemElement.className = "b3-list-item";+ itemElement.dataset.commandId = command.id;+ const textElement = document.createElement("span");+ textElement.className = "b3-list-item__text";+ textElement.textContent = command.label();+ const hotkeyElement = document.createElement("span");+ hotkeyElement.className = `b3-list-item__meta${isMobile() ? " fn__none" : ""}`;+ hotkeyElement.textContent = updateHotkeyTip(command.hotkey?.() || "");+ itemElement.append(textElement, hotkeyElement);+ fragment.append(itemElement);+ });+ listElement.replaceChildren(fragment);+ listElement.firstElementChild?.classList.add("b3-list-item--focus");+};++const executePaletteCommand = (app: App, commandId: string, context: ICommandContextSnapshot) => {+ void executeCommandById(app, commandId, context).catch(error => {+ console.error(`Unable to execute command "${commandId}":`, error);+ });+};export const commandPanel = (app: App) => {const openCommandPanelDialog = window.siyuan.dialogs.find(item =>@@ -33,7 +45,13 @@ export const commandPanel = (app: App) => {openCommandPanelDialog.destroy();return;}- const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : undefined;+ const context = captureCommandContext({app, source: "commandPanel"});+ const registry = ensureCommandSystem(app);+ const focusLifecycle = createPaletteFocusLifecycle(() => {+ if (context.range?.startContainer.isConnected) {+ focusByRange(context.range);+ }+ });const dialog = new Dialog({width: isMobile() ? "92vw" : "80vw",height: isMobile() ? "80vh" : "70vh",@@ -50,86 +68,32 @@ export const commandPanel = (app: App) => {<kbd>Esc</kbd> ${window.siyuan.languages.close}</div></div>`,+ disableAnimation: true,destroyCallback() {- if (range) {- focusByRange(range);- }+ focusLifecycle.restoreAfterCancel();},});dialog.element.setAttribute("data-key", Constants.DIALOG_COMMANDPANEL);- const listElement = dialog.element.querySelector("#commands");- let html = "";- Object.keys(window.siyuan.config.keymap.general).forEach((key) => {- let keys;- /// #if MOBILE- 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"];- /// #else- 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"];- /// #if !BROWSER- keys.push("toggleWin");- /// #endif- /// #endif- if (keys.includes(key)) {- html += `<li class="b3-list-item" data-command="${key}">- <span class="b3-list-item__text">${window.siyuan.languages[key]}</span>- <span class="b3-list-item__meta${isMobile() ? " fn__none" : ""}">${updateHotkeyTip(window.siyuan.config.keymap.general[key].custom)}</span>-</li>`;- }- });- Object.keys(window.siyuan.config.keymap.editor.general).forEach((key) => {- if (["switchReadonly", "switchAdjust"].includes(key)) {- html += `<li class="b3-list-item" data-command="${key}">- <span class="b3-list-item__text">${window.siyuan.languages[key]}</span>- <span class="b3-list-item__meta${isMobile() ? " fn__none" : ""}">${updateHotkeyTip(window.siyuan.config.keymap.editor.general[key].custom)}</span>-</li>`;- }- });- listElement.insertAdjacentHTML("beforeend", html);- app.plugins.forEach(plugin => {- plugin.commands.forEach(command => {- const liElement = document.createElement("li");- liElement.classList.add("b3-list-item");- liElement.innerHTML = `<span class="b3-list-item__text">${plugin.displayName}: ${command.langText || plugin.i18n[command.langKey]}</span>-<span class="b3-list-item__meta${isMobile() ? " fn__none" : ""}">${updateHotkeyTip(command.customHotkey)}</span>`;- liElement.addEventListener("click", (event) => {- if (command.callback) {- command.callback();- } else if (command.globalCallback && !isWindow()) {- command.globalCallback();- }- dialog.destroy();- event.preventDefault();- event.stopPropagation();- });- listElement.insertAdjacentElement("beforeend", liElement);- });- });-- listElement.firstElementChild.classList.add("b3-list-item--focus");+ const listElement = dialog.element.querySelector("#commands") as HTMLElement;const inputElement = dialog.element.querySelector(".b3-text-field") as HTMLInputElement;+ const refresh = () => {+ renderCommands(listElement, queryCommandPalette(registry, context, inputElement.value));+ };+ refresh();inputElement.focus();- listElement.addEventListener("click", (event: KeyboardEvent) => {- const liElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item");- if (liElement) {- const command = liElement.getAttribute("data-command");- if (command) {- execByCommand({command, app, previousRange: range});- dialog.destroy();- event.preventDefault();- event.stopPropagation();- }++ const run = (commandId: string, event?: Event) => {+ focusLifecycle.prepareCommand(() => event?.preventDefault());+ executePaletteCommand(app, commandId, context);+ dialog.destroy();+ };++ listElement.addEventListener("click", (event: MouseEvent) => {+ const itemElement = hasClosestByClassName(event.target as HTMLElement, "b3-list-item");+ const commandId = itemElement && itemElement.dataset.commandId;+ if (commandId) {+ run(commandId, event);+ event.stopPropagation();}});inputElement.addEventListener("keydown", (event: KeyboardEvent) => {@@ -144,362 +108,31 @@ export const commandPanel = (app: App) => {}upDownHint(listElement, event);if (event.key === "Enter") {- const currentElement = listElement.querySelector(".b3-list-item--focus");- if (currentElement) {- const command = currentElement.getAttribute("data-command");- if (command) {- execByCommand({command, app, previousRange: range});- } else {- currentElement.dispatchEvent(new CustomEvent("click"));- }+ const commandId = listElement.querySelector<HTMLElement>(".b3-list-item--focus")?.dataset.commandId;+ if (commandId) {+ run(commandId, event);+ } else {+ event.preventDefault();+ dialog.destroy();}- dialog.destroy();} else if (event.key === "Escape") {dialog.destroy();}});- inputElement.addEventListener("compositionend", () => {- filterList(inputElement, listElement);- });+ inputElement.addEventListener("compositionend", refresh);inputElement.addEventListener("input", (event: InputEvent) => {- if (event.isComposing) {- return;+ if (!event.isComposing) {+ event.stopPropagation();+ refresh();}- event.stopPropagation();- filterList(inputElement, listElement);});-};--const filterList = (inputElement: HTMLInputElement, listElement: Element) => {- const inputValue = inputElement.value.toLowerCase();- listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");- let hasFocus = false;- Array.from(listElement.children).forEach((element: HTMLElement) => {- const elementValue = element.querySelector(".b3-list-item__text").textContent.toLowerCase();- const command = element.dataset.command;- if (inputValue.indexOf(elementValue) > -1 || elementValue.indexOf(inputValue) > -1 ||- inputValue.indexOf(command) > -1 || command?.indexOf(inputValue) > -1) {- if (!hasFocus) {- element.classList.add("b3-list-item--focus");- }- hasFocus = true;- element.classList.remove("fn__none");- } else {- element.classList.add("fn__none");+ void initializeEnglishCommandTranslations(+ window.siyuan.config.appearance.lang,+ window.siyuan.languages as Record<string, string>,+ Constants.SIYUAN_VERSION,+ ).then(() => {+ if (dialog.element.isConnected) {+ refresh();}});};--export const execByCommand = async (options: {- command: string,- app?: App,- previousRange?: Range,- protyle?: IProtyle,- fileLiElements?: Element[]-}) => {- if (globalCommand(options.command, options.app)) {- return;- }-- const isFileFocus = document.querySelector(".layout__tab--active")?.classList.contains("sy__file");-- let protyle = options.protyle;- /// #if MOBILE- if (!protyle) {- protyle = getCurrentEditor()?.protyle;- options.previousRange = protyle?.toolbar.range;- }- /// #endif- const range: Range = options.previousRange || (getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : document.createRange());- let fileLiElements = options.fileLiElements;- if (!isFileFocus && !protyle) {- if (range) {- window.siyuan.dialogs.find(item => {- if (item.editors) {- Object.keys(item.editors).find(key => {- if (item.editors[key].protyle.element.contains(range.startContainer)) {- protyle = item.editors[key].protyle;- return true;- }- });- if (protyle) {- return true;- }- }- });- }- /// #if !MOBILE- const activeTab = getActiveTab();- if (!protyle && activeTab) {- if (activeTab.model instanceof Editor) {- protyle = activeTab.model.getCurrentProtyle(range);- } else if (activeTab.model instanceof Search) {- if (activeTab.model.element.querySelector("#searchUnRefPanel").classList.contains("fn__none")) {- protyle = activeTab.model.editors.edit.protyle;- } else {- protyle = activeTab.model.editors.unRefEdit.protyle;- }- } else if (activeTab.model instanceof Custom && activeTab.model.editors?.length > 0) {- if (range) {- activeTab.model.editors.find(item => {- if (item.protyle.element.contains(range.startContainer)) {- protyle = item.protyle;- return true;- }- });- }- }- }- /// #endif- if (!protyle) {- if (!protyle && range) {- window.siyuan.blockPanels.find(item => {- item.editors.find(editorItem => {- if (editorItem.protyle.element.contains(range.startContainer)) {- protyle = editorItem.protyle;- return true;- }- });- if (protyle) {- return true;- }- });- }- /// #if !MOBILE- const models = getAllModels();- if (!protyle) {- models.backlink.find(item => {- if (item.element.classList.contains("layout__tab--active")) {- if (range) {- item.editors.find(editor => {- if (editor.protyle.element.contains(range.startContainer)) {- protyle = editor.protyle;- return true;- }- });- }- if (!protyle && item.editors.length > 0) {- protyle = item.editors[0].protyle;- }- return true;- }- });- }- if (!protyle) {- models.editor.find(item => {- if (item.parent.headElement.classList.contains("item--focus")) {- protyle = item.editor.protyle;- return true;- }- });- }- /// #endif- }- }-- // only protyle- if (!isFileFocus && protyle && onlyProtyleCommand({- command: options.command,- previousRange: range,- protyle- })) {- return;- }-- if (isFileFocus && !fileLiElements) {- const dockFile = getDockByType("file");- if (!dockFile) {- return false;- }- const files = dockFile.data.file as Files;- fileLiElements = Array.from(files.element.querySelectorAll(".b3-list-item--focus"));- }-- // 全局命令,在没有 protyle 和文件树没聚焦的情况下执行- if ((!protyle && !isFileFocus) ||- (isFileFocus && (!fileLiElements || fileLiElements.length === 0)) ||- (isMobile() && !document.getElementById("empty").classList.contains("fn__none"))) {- if (options.command === "replace") {- /// #if MOBILE- popSearch(options.app, {hasReplace: true, page: 1});- /// #else- openSearch({- app: options.app,- hotkey: Constants.DIALOG_REPLACE,- key: range.toString()- });- /// #endif- } else if (options.command === "search") {- /// #if MOBILE- popSearch(options.app, {hasReplace: false, page: 1});- /// #else- openSearch({- app: options.app,- hotkey: Constants.DIALOG_SEARCH,- key: range.toString()- });- /// #endif- }- return;- }-- // protyle and file tree- switch (options.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(options.app, {- page: 1,- hasReplace: true,- hPath: pathPosix().join(getNotebookName(protyle.notebookId), response.data),- idPath: [pathPosix().join(protyle.notebookId, protyle.path)]- });- /// #else- openSearch({- app: options.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: options.app,- hotkey: Constants.DIALOG_REPLACE,- notebookId: notebookId,- searchPath: getDisplayName(pathString, false, true)- });- } else {- openSearch({- app: options.app,- hotkey: Constants.DIALOG_REPLACE,- notebookId: 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(options.app, {- page: 1,- hasReplace: false,- hPath: pathPosix().join(getNotebookName(protyle.notebookId), response.data),- idPath: [pathPosix().join(protyle.notebookId, protyle.path)]- });- /// #else- openSearch({- app: options.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: options.app,- hotkey: Constants.DIALOG_SEARCH,- notebookId: notebookId,- searchPath: getDisplayName(pathString, false, true)- });- } else {- openSearch({- app: options.app,- hotkey: Constants.DIALOG_SEARCH,- notebookId: notebookId,- });- }- /// #endif- }- break;- case "addToDatabase":- if (!isFileFocus) {- addEditorToDatabase(protyle, range);- } else {- addFilesToDatabase(fileLiElements);- }- break;- case "move":- if (!isFileFocus) {- 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 (nodeElement && range && 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 {- const paths = getTopPaths(fileLiElements);- const sourceNotebookIds = fileLiElements.map((item) =>- item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");- const rootIDs: string[] = [];- fileLiElements.forEach(item => {- rootIDs.push(item.getAttribute("data-node-id"));- });- movePathTo({- cb: (toPath, toNotebook) => {- moveToPath(paths, toNotebook[0], toPath[0]);- },- paths,- rootIDs,- flashcard: false,- sourceNotebookIds- });- }- break;- }-};