Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Keep shortcut-opened panels visible on repeated presses https://github.com/siyuan-note/siyuan/issues/20030

Danielf7b2b51d1c3f
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
index 753d0ad149..0c7806f1c4 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
@@ -7,7 +7,7 @@
"id": "20200924100950-9op5xi1",
"title": "Shortcuts",
"type": "doc",
- "updated": "20261001015635"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-wub2unw",
- "updated": "20260928175046"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -66,6 +66,29 @@
}
]
},
+ {
+ "ID": "20261002010621-zd9bn2e",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002010621-zd9bn2e",
+ "updated": "20261002010621"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "The shortcuts for the command palette, recent documents, data history, flashcard review, inline appearance, main menu, and tab list open their panels. Pressing the shortcut again keeps the panel open. Press "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to close it; if an editor popup is visible, Esc closes that popup first."
+ }
+ ]
+ },
{
"ID": "20201227133532-44ubczo",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
index 7fe03dbfb4..8f04bb4aaa 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
@@ -7,7 +7,7 @@
"id": "20200813004551-gm0pbn1",
"title": "快捷键",
"type": "doc",
- "updated": "20261001015635"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-w9nonqj",
- "updated": "20260928175046"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -66,6 +66,29 @@
}
]
},
+ {
+ "ID": "20261002010621-3c1s74q",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002010621-3c1s74q",
+ "updated": "20261002010621"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "命令面板、最近打开的文档、数据历史、闪卡复习、行内外观、主菜单和页签列表的快捷键只负责打开面板,再次按下会保持打开。按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 关闭;编辑器中已有浮层时,先关闭浮层。"
+ }
+ ]
+ },
{
"ID": "20240112150737-e41yt1y",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
index f1651bc500..05450f365b 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
@@ -7,7 +7,7 @@
"id": "20211226122549-jktxego",
"title": "快捷鍵",
"type": "doc",
- "updated": "20261001015635"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-a3qlogr",
- "updated": "20260928175046"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -66,6 +66,29 @@
}
]
},
+ {
+ "ID": "20261002010621-im1xicd",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002010621-im1xicd",
+ "updated": "20261002010621"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "命令面板、最近開啟的文件、資料歷史、閃卡複習、行內外觀、主選單和頁籤列表的快捷鍵只負責開啟面板,再次按下會保持開啟。按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 關閉;編輯器中已有浮層時,先關閉浮層。"
+ }
+ ]
+ },
{
"ID": "20211226122652-0t4c1qf",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
index 5a1bb892a5..0826f08ec6 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
@@ -9,7 +9,7 @@
"id": "20240530101000-xsbxokr",
"title": "ショートカット",
"type": "doc",
- "updated": "20261001015635"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -18,7 +18,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-t67pljp",
- "updated": "20260928175046"
+ "updated": "20261002010621"
},
"Children": [
{
@@ -64,6 +64,29 @@
}
]
},
+ {
+ "ID": "20261002010621-mogxh00",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002010621-mogxh00",
+ "updated": "20261002010621"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "コマンドパレット、最近開いたドキュメント、データ履歴、フラッシュカードの復習、インラインの外観、メインメニュー、タブ一覧のショートカットは、パネルを開きます。もう一度押してもパネルは開いたままです。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を押すと閉じます。エディターのポップアップが表示されている場合は、先にそのポップアップを閉じます。"
+ }
+ ]
+ },
{
"ID": "20240530101000-9imgmgf",
"Type": "NodeHeading",
diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.ts
index bca3fa8190..544436ffdf 100644
--- a/app/src/boot/globalEvent/command/global.ts
+++ b/app/src/boot/globalEvent/command/global.ts
@@ -55,7 +55,7 @@ const getSelectionText = (range?: Range) => {
return selection?.rangeCount ? selection.getRangeAt(0).toString() : "";
};
-export const globalCommand = (command: string, app: App, range?: Range) => {
+export const globalCommand = (command: string, app: App, range?: Range, openOnly = false) => {
/// #if MOBILE
switch (command) {
case "fileTree":
@@ -159,11 +159,11 @@ export const globalCommand = (command: string, app: App, range?: Range) => {
return true;
case "mainMenu":
if (!isWindow()) {
- workspaceMenu(app, document.querySelector("#barWorkspace").getBoundingClientRect());
+ workspaceMenu(app, document.querySelector("#barWorkspace").getBoundingClientRect(), openOnly);
}
return true;
case "recentDocs":
- openRecentDocs();
+ openRecentDocs(openOnly);
return true;
case "recentClosed": {
const closedTabsLength = window.siyuan.storage[Constants.LOCAL_CLOSED_TABS].length;
@@ -469,7 +469,7 @@ export const globalCommand = (command: string, app: App, range?: Range) => {
newDailyNote(app);
return true;
case "dataHistory":
- openHistory(app);
+ openHistory(app, "doc", openOnly);
return true;
case "editReadonly":
editorConfigApi.patch("editor.readOnly", !window.siyuan.config.editor.readOnly);
@@ -481,7 +481,7 @@ export const globalCommand = (command: string, app: App, range?: Range) => {
newFile(app);
return true;
case "riffCard":
- openCard(app);
+ openCard(app, openOnly);
return true;
case "selectOpen1":
selectOpenTab();
diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.ts
index 76b9be148e..4c44fb46ea 100644
--- a/app/src/boot/globalEvent/command/panel.ts
+++ b/app/src/boot/globalEvent/command/panel.ts
@@ -61,16 +61,21 @@ export const commandPanel = (app: App, options: {
protyle?: IProtyle;
range?: Range;
restoreKeyboard?: () => void;
+ openOnly?: boolean;
} = {}) => {
const menu = window.siyuan.menus.menu;
if (isMobile() && menu.element.getAttribute("data-name") === Constants.DIALOG_COMMANDPANEL) {
- menu.closeSheet();
+ if (!options.openOnly) {
+ menu.closeSheet();
+ }
return;
}
const openCommandPanelDialog = window.siyuan.dialogs.find(item =>
item.element.getAttribute("data-key") === Constants.DIALOG_COMMANDPANEL);
if (openCommandPanelDialog) {
- openCommandPanelDialog.destroy();
+ if (!options.openOnly) {
+ openCommandPanelDialog.destroy();
+ }
return;
}
const context = captureCommandContext({app, source: "commandPanel", protyle: options.protyle, range: options.range});
@@ -175,8 +180,7 @@ export const commandPanel = (app: App, options: {
if (event.isComposing) {
return;
}
- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {
- close();
+ if (matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {
event.preventDefault();
return;
}
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 5b35508463..01f007919f 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -241,7 +241,7 @@ const documentKeydown = (app: App, event: KeyboardEvent, protyle: IProtyle, rang
if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition, event) &&
!window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {
fetchPost("/api/riff/getTreeRiffDueCards", {rootID: protyle.block.rootID}, (response) => {
- openCardByData(app, response.data, "doc", protyle.block.rootID, protyle.title?.editElement.textContent || window.siyuan.languages.untitled);
+ openCardByData(app, response.data, "doc", protyle.block.rootID, protyle.title?.editElement.textContent || window.siyuan.languages.untitled, true);
});
event.preventDefault();
return true;
@@ -716,11 +716,11 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {
if (isFile) {
const id = liElements[0].getAttribute("data-node-id");
fetchPost("/api/riff/getTreeRiffDueCards", {rootID: id}, (response) => {
- openCardByData(app, response.data, "doc", id, getDisplayName(liElements[0].getAttribute("data-name"), false, true));
+ openCardByData(app, response.data, "doc", id, getDisplayName(liElements[0].getAttribute("data-name"), false, true), true);
});
} else {
fetchPost("/api/riff/getNotebookRiffDueCards", {notebook: notebookId}, (response) => {
- openCardByData(app, response.data, "notebook", notebookId, getNotebookName(notebookId));
+ openCardByData(app, response.data, "notebook", notebookId, getNotebookName(notebookId), true);
});
}
event.preventDefault();
@@ -1523,7 +1523,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
}
if (matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {
event.preventDefault();
- commandPanel(app);
+ commandPanel(app, {openOnly: true});
return;
}
const editorFontSizeCommand = EDITOR_FONT_SIZE_COMMANDS.find((item) =>
@@ -1544,7 +1544,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
return;
}
if (matchHotKey(window.siyuan.config.keymap.general.dataHistory, event)) {
- openHistory(app);
+ openHistory(app, "doc", true);
event.preventDefault();
return;
}
diff --git a/app/src/business/openRecentDocs.ts b/app/src/business/openRecentDocs.ts
index cf0f7ca312..94cf0c723c 100644
--- a/app/src/business/openRecentDocs.ts
+++ b/app/src/business/openRecentDocs.ts
@@ -77,14 +77,16 @@ const renderRecentDocsContent = async (data: {
</div>`;
};
-export const openRecentDocs = () => {
+export const openRecentDocs = (openOnly = false) => {
const openRecentDocsDialog = window.siyuan.dialogs.find(item => {
if (item.element.getAttribute("data-key") === Constants.DIALOG_RECENTDOCS) {
return true;
}
});
if (openRecentDocsDialog) {
- hideElements(["dialog"]);
+ if (!openOnly) {
+ hideElements(["dialog"]);
+ }
return;
}
const sortBy = window.siyuan.storage[Constants.LOCAL_RECENT_DOCS].type as TRecentDocsSort;
diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.ts
index a4cf69a33f..14e380c3aa 100644
--- a/app/src/card/openCard.ts
+++ b/app/src/card/openCard.ts
@@ -801,19 +801,22 @@ const emitEvent = (card: ICard, type: string) => {
});
};
-export const openCard = (app: App) => {
+export const openCard = (app: App, openOnly = false) => {
if (window.siyuan.config.readonly) {
return;
}
fetchPost("/api/riff/getRiffDueCards", {deckID: ""}, (cardsResponse) => {
- openCardByData(app, cardsResponse.data, "all");
+ openCardByData(app, cardsResponse.data, "all", undefined, undefined, openOnly);
});
};
-export const openCardByData = async (app: App, cardsData: ICardData, cardType: TCardType, id?: string, title?: string) => {
+export const openCardByData = async (app: App, cardsData: ICardData, cardType: TCardType, id?: string, title?: string,
+ openOnly = false) => {
const exit = window.siyuan.dialogs.find(item => {
if (item.element.getAttribute("data-key") === Constants.DIALOG_OPENCARD) {
- item.destroy();
+ if (!openOnly) {
+ item.destroy();
+ }
return true;
}
});
@@ -865,6 +868,22 @@ export const openCardByData = async (app: App, cardsData: ICardData, cardType: T
dialog.editors = {
card: editor
};
+ dialog.element.addEventListener("keydown", (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.isComposing || event.repeat) {
+ return;
+ }
+ const protyle = editor.protyle;
+ // 编辑器浮层优先处理 Esc,正文获得焦点时仍可关闭复习弹窗。
+ if (!window.siyuan.menus.menu.element.classList.contains("fn__none") ||
+ !protyle.toolbar.element.classList.contains("fn__none") ||
+ !protyle.toolbar.subElement.classList.contains("fn__none") ||
+ !protyle.hint.element.classList.contains("fn__none")) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ dialog.destroy();
+ }, true);
/// #if !MOBILE
const focusElement = dialog.element.querySelector(".block__icons button.block__icon") as HTMLElement;
focusElement.focus();
diff --git a/app/src/command/nativeRuntime.ts b/app/src/command/nativeRuntime.ts
index 0233da2f8f..de1bd4743a 100644
--- a/app/src/command/nativeRuntime.ts
+++ b/app/src/command/nativeRuntime.ts
@@ -17,7 +17,9 @@ import {openSearch} from "../search/spread";
export const executeLegacyNativeCommand = async (command: string, context: ICommandContextSnapshot) => {
const app = context.app as App;
- if (globalCommand(command, app, context.range)) {
+ const openOnly = ["shortcut", "editorShortcut", "fileTreeShortcut", "dockShortcut", "globalShortcut", "keymap"]
+ .includes(context.source);
+ if (globalCommand(command, app, context.range, openOnly)) {
return;
}
diff --git a/app/src/history/history.ts b/app/src/history/history.ts
index 27a3a67ea0..24752040e5 100644
--- a/app/src/history/history.ts
+++ b/app/src/history/history.ts
@@ -512,13 +512,15 @@ const renderRmNotebook = (element: HTMLElement) => {
});
};
-export const openHistory = (app: App, tab: "doc" | "notebook" | "repo" = "doc") => {
+export const openHistory = (app: App, tab: "doc" | "notebook" | "repo" = "doc", openOnly = false) => {
if (window.siyuan.config.readonly) {
return;
}
const exitDialog = window.siyuan.dialogs.find((item) => {
if (item.element.querySelector("#historyContainer")) {
- item.destroy();
+ if (!openOnly) {
+ item.destroy();
+ }
return true;
}
});
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.ts
index 224a490acd..31c87657a6 100644
--- a/app/src/layout/Wnd.ts
+++ b/app/src/layout/Wnd.ts
@@ -867,7 +867,9 @@ export class Wnd {
}
if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&
window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_TAB_LIST) {
- window.siyuan.menus.menu.remove();
+ if (!focus) {
+ window.siyuan.menus.menu.remove();
+ }
return;
}
window.siyuan.menus.menu.remove();
diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.ts
index 8ff3dccf43..098f2feb2b 100644
--- a/app/src/menus/workspace.ts
+++ b/app/src/menus/workspace.ts
@@ -135,10 +135,12 @@ const getZoomSubMenu = () => {
return submenu;
};
-export const workspaceMenu = async (app: App, rect: DOMRect) => {
+export const workspaceMenu = async (app: App, rect: DOMRect, openOnly = false) => {
if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&
window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BAR_WORKSPACE) {
- window.siyuan.menus.menu.remove();
+ if (!openOnly) {
+ window.siyuan.menus.menu.remove();
+ }
return;
}
let remoteConnections: string[] = [];
diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.ts
index edb1d4662c..b0f42d0403 100644
--- a/app/src/protyle/toolbar/Font.ts
+++ b/app/src/protyle/toolbar/Font.ts
@@ -83,9 +83,12 @@ export class Font extends ToolbarItem {
constructor(protyle: IProtyle, menuItem: IMenuItem) {
super(protyle, menuItem);
- this.element.addEventListener("click", () => {
+ this.element.addEventListener("click", (event) => {
if (protyle.toolbar.subElement.dataset.subElementSource === SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE &&
!protyle.toolbar.subElement.classList.contains("fn__none")) {
+ if (event instanceof CustomEvent && event.detail?.openOnly) {
+ return;
+ }
protyle.toolbar.subElement.classList.add("fn__none");
closeSubElement(protyle.toolbar);
focusByRange(protyle.toolbar.range);
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index bb6aa2cb1f..c285a31f02 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -2121,7 +2121,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
findToolbar = true;
if (["a", "block-ref", "inline-math", "inline-memo", "text"].includes(menuItem.name)) {
- protyle.toolbar.element.querySelector(`[data-type="${menuItem.name}"]`).dispatchEvent(new CustomEvent("click"));
+ protyle.toolbar.element.querySelector(`[data-type="${menuItem.name}"]`).dispatchEvent(
+ new CustomEvent("click", {detail: {openOnly: menuItem.name === "text"}}));
} else if (Constants.INLINE_TYPE.includes(menuItem.name)) {
protyle.toolbar.setInlineMark(protyle, menuItem.name, "range");
} else if (menuItem.click) {
diff --git a/app/tests/commandPaletteClose.test.js b/app/tests/commandPaletteClose.test.js
index 26ef9c1f72..59d55fcf0f 100644
--- a/app/tests/commandPaletteClose.test.js
+++ b/app/tests/commandPaletteClose.test.js
@@ -4,7 +4,7 @@ const path = require("node:path");
const { test } = require("node:test");
const { runInNewContext } = require("node:vm");
const ts = require("typescript");
-function fixture(delay) {
+function fixture(delay, mobile = false) {
const log = [];
let now = 0;
let counter = 0;
@@ -74,6 +74,7 @@ function fixture(delay) {
addEventListener() { }, removeEventListener() { }, getElementById() { return null; } };
document.activeElement = document.body;
const menu = { element: new Element(), visible: false,
+ closeSheet() { log.push({at: now, action: "sheet closed"}); },
remove() {
if (this.visible)
log.push({ at: now, action: "resources removed" });
@@ -109,12 +110,12 @@ function fixture(delay) {
const command = { id: "core.insert.assets", label: () => "Assets" };
const context = {};
const { commandPanel } = load("boot/globalEvent/command/panel.ts", {
- "../../../dialog": { Dialog }, "../../../util/functions": { isMobile: () => false },
+ "../../../dialog": { Dialog }, "../../../util/functions": { isMobile: () => mobile },
"../../../constants": { Constants }, "../../../util/upDownHint": { upDownHint() { } },
"../../../util/keymapBindings": {},
"../../../protyle/util/compatibility": { updateHotkeyTip: x => x, setStorageVal() { } },
"../../../protyle/util/hasClosest": { hasClosestByClassName: x => x },
- "../../../protyle/util/hotKey": { matchHotKey: () => false },
+ "../../../protyle/util/hotKey": { matchHotKey: (_keymap, event) => event.key === "Palette" },
"../../../command/context": { captureCommandContext: () => context },
"../../../command/insertCommands": { ensureInsertCommands() { } },
"../../../command/executor": { ensureCommandSystem: () => ({}), executeCommandById: () => {
@@ -125,8 +126,43 @@ function fixture(delay) {
"../../../command/english": { initializeEnglishCommandTranslations: () => Promise.resolve() },
"../../../command/paletteCore": { ...lifecycle, queryCommandPalette: () => [command] },
});
- return { commandPanel, menu, window, advance, log, Dialog, timeout: Constants.TIMEOUT_DBLCLICK };
+ return { commandPanel, menu, window, advance, log, Dialog, Constants, timeout: Constants.TIMEOUT_DBLCLICK };
}
+
+test("palette shortcuts retain the existing query and Escape still cancels", () => {
+ const f = fixture(0);
+ f.commandPanel({}, {openOnly: true});
+ const dialog = f.window.siyuan.dialogs[0];
+ const input = dialog.element.querySelector(".b3-text-field");
+ input.value = "query";
+ f.commandPanel({}, {openOnly: true});
+ assert.equal(f.window.siyuan.dialogs[0], dialog);
+ let prevented = 0;
+ for (const repeat of [false, true]) {
+ input.listeners.keydown({key: "Palette", repeat, stopPropagation() {}, preventDefault() {prevented++;}});
+ assert.equal(f.window.siyuan.dialogs[0], dialog);
+ assert.equal(input.value, "query");
+ }
+ assert.equal(prevented, 2);
+ input.listeners.keydown({key: "Escape", stopPropagation() {}, preventDefault() {}});
+ f.advance(300);
+ assert.equal(f.window.siyuan.dialogs.length, 0);
+ assert.equal(f.log.some(item => item.action === "assets command executed"), false);
+});
+
+test("palette mouse entry still toggles and mobile shortcut keeps its sheet open", () => {
+ const desktop = fixture(0);
+ desktop.commandPanel({});
+ desktop.commandPanel({});
+ desktop.advance(300);
+ assert.equal(desktop.window.siyuan.dialogs.length, 0);
+ const mobile = fixture(0, true);
+ mobile.menu.element.setAttribute("data-name", mobile.Constants.DIALOG_COMMANDPANEL);
+ mobile.commandPanel({}, {openOnly: true});
+ assert.equal(mobile.log.some(item => item.action === "sheet closed"), false);
+ mobile.commandPanel({});
+ assert.equal(mobile.log.filter(item => item.action === "sheet closed").length, 1);
+});
for (const action of ["Enter", "click"]) {
for (const responseDelay of [0, 10, 189, 190, 250]) {
test(`palette ${action} preserves resources opened after ${responseDelay}ms`, () => {
diff --git a/app/tests/shortcutOpenPanels.test.js b/app/tests/shortcutOpenPanels.test.js
new file mode 100644
index 0000000000..ac9252a558
--- /dev/null
+++ b/app/tests/shortcutOpenPanels.test.js
@@ -0,0 +1,147 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const path = require("node:path");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const ts = require("typescript");
+const {parse} = require("ifdef-loader/preprocessor");
+
+const sourceFile = file => ts.createSourceFile(file, readFileSync(path.join(__dirname, "../src", file), "utf8"),
+ ts.ScriptTarget.Latest, true);
+const find = (source, predicate) => {
+ let result;
+ const visit = node => {
+ if (!result && predicate(node)) {
+ result = node;
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ assert.ok(result);
+ return result;
+};
+const arrow = (source, name) => find(source, node => ts.isVariableDeclaration(node) &&
+ node.name.getText(source) === name).initializer;
+const evaluate = (text, scope) => {
+ const exports = {};
+ runInNewContext(ts.transpileModule(text, {compilerOptions: {module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022}}).outputText, {exports, ...scope});
+ return exports;
+};
+// 运行入口的实际重复打开分支,在首次打开的渲染和请求之前终止。
+const prefix = (source, fn, marker, scope) => {
+ const end = fn.body.statements.findIndex(node => node.getText(source).startsWith(marker));
+ assert.ok(end >= 0);
+ return evaluate(`exports.subject = async function(${fn.parameters.map(node => node.getText(source)).join(",")}) {
+ ${fn.body.statements.slice(0, end).map(node => node.getText(source)).join("\n")}
+ throw new Error("An existing panel must not be rendered again");
+ };`, scope).subject;
+};
+const hiddenElement = (hidden = true) => ({classList: {contains: () => hidden}});
+
+for (const [file, name, marker, args] of [
+ ["business/openRecentDocs.ts", "openRecentDocs", "const sortBy", openOnly => [openOnly]],
+ ["history/history.ts", "openHistory", "const localHistory", openOnly => [{}, "doc", openOnly]],
+ ["card/openCard.ts", "openCardByData", "let lastRange", openOnly => [{}, {}, "doc", "id", "title", openOnly]],
+ ["menus/workspace.ts", "workspaceMenu", "let remoteConnections", openOnly => [{}, {}, openOnly]],
+]) {
+ test(`${name} retains the open panel for shortcuts and toggles for mouse entry`, async () => {
+ let closes = 0;
+ const element = {...hiddenElement(false), getAttribute: () => "panel", querySelector: () => ({})};
+ const item = {element, destroy: () => closes++};
+ const window = {siyuan: {config: {}, dialogs: [item], menus: {menu: {element, remove: () => closes++}}}};
+ const source = sourceFile(file);
+ const subject = prefix(source, arrow(source, name), marker, {window,
+ Constants: {DIALOG_RECENTDOCS: "panel", DIALOG_OPENCARD: "panel", MENU_BAR_WORKSPACE: "panel"},
+ hideElements: () => closes++});
+ await subject(...args(true));
+ assert.equal(closes, 0);
+ await subject(...args(false));
+ assert.equal(closes, 1);
+ });
+}
+
+test("tab list and inline appearance retain their existing shortcut panel", async () => {
+ let closes = 0;
+ const source = sourceFile("layout/Wnd.ts");
+ const method = find(source, node => ts.isMethodDeclaration(node) && node.name.getText(source) === "renderTabList");
+ const subject = prefix(source, method, "window.siyuan.menus.menu.remove();", {
+ window: {siyuan: {menus: {menu: {element: {...hiddenElement(false), getAttribute: () => "tabs"},
+ remove: () => closes++}}}}, Constants: {MENU_TAB_LIST: "tabs"},
+ });
+ const wnd = {headersElement: {children: [{}]}};
+ await subject.call(wnd, {}, true);
+ assert.equal(closes, 0);
+ await subject.call(wnd, {}, false);
+ assert.equal(closes, 1);
+ const font = sourceFile("protyle/toolbar/Font.ts");
+ const binding = find(font, node => ts.isCallExpression(node) &&
+ node.expression.getText(font) === "this.element.addEventListener" && node.arguments[0]?.text === "click");
+ const subElement = {dataset: {subElementSource: "selection"}, classList: {contains: () => false, add() {}}};
+ const click = prefix(font, binding.arguments[1], "closeSubElement(protyle.toolbar);", {
+ protyle: {toolbar: {subElement}}, SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE: "selection", CustomEvent,
+ closeSubElement: () => closes++, focusByRange() {},
+ });
+ await click(new CustomEvent("click", {detail: {openOnly: true}}));
+ assert.equal(closes, 1);
+ await click(new Event("click"));
+ assert.equal(closes, 2);
+});
+
+test("native shortcut sources open panels without toggling while menu commands retain their behavior", async () => {
+ const source = sourceFile("command/nativeRuntime.ts");
+ const calls = [];
+ const subject = prefix(source, arrow(source, "executeLegacyNativeCommand"), "const isFileFocus", {
+ globalCommand: (...args) => {calls.push(args); return true;},
+ });
+ for (const commandSource of ["shortcut", "editorShortcut", "fileTreeShortcut", "dockShortcut", "globalShortcut", "keymap", "menu", "api", "commandPanel"]) {
+ await subject("recentDocs", {app: {}, source: commandSource});
+ assert.equal(calls.at(-1)[3], !["menu", "api", "commandPanel"].includes(commandSource));
+ }
+ const dispatches = [];
+ const handlers = Object.fromEntries(["workspaceMenu", "openRecentDocs", "openHistory", "openCard"]
+ .map(name => [name, (...args) => dispatches.push({name, args})]));
+ const compiled = parse(sourceFile("boot/globalEvent/command/global.ts").text,
+ {MOBILE: false, BROWSER: true}, false, true);
+ const {globalCommand} = evaluate(compiled, {require: () => new Proxy(handlers, {get: (target, key) =>
+ target[key] || (() => false)}), document: {querySelector: () => ({getBoundingClientRect: () => ({})})}});
+ for (const command of ["mainMenu", "recentDocs", "dataHistory", "riffCard"]) {
+ assert.equal(globalCommand(command, {}, undefined, true), true);
+ assert.equal(dispatches.at(-1).args.at(-1), true);
+ }
+});
+
+test("Escape from flashcard content closes its dialog after editor overlays are dismissed", () => {
+ const source = sourceFile("card/openCard.ts");
+ const binding = find(source, node => ts.isCallExpression(node) &&
+ node.expression.getText(source) === "dialog.element.addEventListener" && node.arguments[0]?.text === "keydown");
+ let handler;
+ let destroyed = 0;
+ const elements = [hiddenElement(), hiddenElement(), hiddenElement(), hiddenElement()];
+ const dialog = {element: {addEventListener: (name, fn, capture) => {
+ assert.equal(name, "keydown");
+ assert.equal(capture, true);
+ handler = fn;
+ }}, destroy: () => destroyed++};
+ evaluate(binding.getText(source), {dialog, window: {siyuan: {menus: {menu: {element: elements[0]}}}},
+ editor: {protyle: {toolbar: {element: elements[1], subElement: elements[2]}, hint: {element: elements[3]}}}});
+ for (const overlay of elements) {
+ overlay.classList.contains = () => false;
+ const event = new Event("keydown", {cancelable: true});
+ event.key = "Escape";
+ handler(event);
+ assert.equal(destroyed, 0);
+ assert.equal(event.defaultPrevented, false);
+ overlay.classList.contains = () => true;
+ }
+ for (const flags of [{isComposing: true}, {repeat: true}, {key: "Enter"}]) {
+ handler({key: "Escape", ...flags});
+ assert.equal(destroyed, 0);
+ }
+ const event = new Event("keydown", {cancelable: true});
+ event.key = "Escape";
+ handler(event);
+ assert.equal(destroyed, 1);
+ assert.equal(event.defaultPrevented, true);
+ assert.equal(event.cancelBubble, true);
+});