Skip to content

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

:bug: Preserve shortcut menu focus and editor Escape behavior https://github.com/siyuan-note/siyuan/issues/20030

Daniel8edcf3d76a4c
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 0c7806f1c4..08431838d5 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": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-wub2unw",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -71,7 +71,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002010621-zd9bn2e",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -85,7 +85,34 @@
},
{
"Type": "NodeText",
- "Data": " to close it; if an editor popup is visible, Esc closes that popup first."
+ "Data": " to close it; if an editor popup is visible, Esc closes that popup first. In flashcard content, "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " selects blocks. Hold "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to focus the review buttons, then press "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to close the dialog."
}
]
},
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 8f04bb4aaa..d0aee26a61 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": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-w9nonqj",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -71,7 +71,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002010621-3c1s74q",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -85,7 +85,34 @@
},
{
"Type": "NodeText",
- "Data": " 关闭;编辑器中已有浮层时,先关闭浮层。"
+ "Data": " 关闭;编辑器中已有浮层时,先关闭浮层。在闪卡正文中,按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 选中块,长按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 将焦点移回复习按钮,再按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 关闭弹窗。"
}
]
},
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 05450f365b..52e07b65c9 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": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-a3qlogr",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -71,7 +71,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002010621-im1xicd",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -85,7 +85,34 @@
},
{
"Type": "NodeText",
- "Data": " 關閉;編輯器中已有浮層時,先關閉浮層。"
+ "Data": " 關閉;編輯器中已有浮層時,先關閉浮層。在閃卡正文中,按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 選取區塊,長按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 將焦點移回複習按鈕,再按 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 關閉彈窗。"
}
]
},
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 0826f08ec6..c60a19e3b8 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": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -18,7 +18,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260928091747-t67pljp",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -69,7 +69,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261002010621-mogxh00",
- "updated": "20261002010621"
+ "updated": "20261002013053"
},
"Children": [
{
@@ -83,7 +83,34 @@
},
{
"Type": "NodeText",
- "Data": " を押すと閉じます。エディターのポップアップが表示されている場合は、先にそのポップアップを閉じます。"
+ "Data": " を押すと閉じます。エディターのポップアップが表示されている場合は、先にそのポップアップを閉じます。フラッシュカードの本文では、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を押すとブロックを選択します。"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を長押しすると復習ボタンにフォーカスが移り、もう一度 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Esc"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を押すとダイアログが閉じます。"
}
]
},
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 01f007919f..191e1fca21 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1466,7 +1466,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
}
if (matchHotKey(window.siyuan.config.keymap.general.recentDocs, event)) {
- openRecentDocs();
+ openRecentDocs(true);
event.preventDefault();
return;
}
@@ -1603,8 +1603,9 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
return;
}
if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.riffCard, event)) {
- openCard(app);
- if (document.activeElement) {
+ openCard(app, true);
+ if (document.activeElement && !window.siyuan.dialogs.some(item =>
+ item.element.getAttribute("data-key") === Constants.DIALOG_OPENCARD)) {
(document.activeElement as HTMLElement).blur();
}
event.preventDefault();
diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.ts
index 14e380c3aa..4d3db70c3b 100644
--- a/app/src/card/openCard.ts
+++ b/app/src/card/openCard.ts
@@ -868,22 +868,6 @@ 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/menus/workspace.ts b/app/src/menus/workspace.ts
index 098f2feb2b..5a67c0ec67 100644
--- a/app/src/menus/workspace.ts
+++ b/app/src/menus/workspace.ts
@@ -514,6 +514,24 @@ export const workspaceMenu = async (app: App, rect: DOMRect, openOnly = false) =
}).element);
}
window.siyuan.menus.menu.popup({x: rect.left, y: rect.bottom, h: rect.height});
+ if (openOnly) {
+ const menu = window.siyuan.menus.menu;
+ const activeElement = document.activeElement;
+ const currentElement = Array.from(menu.element.lastElementChild.children).find(item =>
+ item.classList.contains("b3-menu__item") &&
+ !item.classList.contains("b3-menu__item--readonly") &&
+ !item.hasAttribute("disabled") && item.getBoundingClientRect().height > 0) as HTMLElement;
+ currentElement?.classList.add("b3-menu__item--current");
+ currentElement?.focus({preventScroll: true});
+ currentElement?.scrollIntoView({block: "nearest"});
+ // 仅在焦点仍位于菜单内时恢复,避免菜单动作打开新界面后抢回原焦点。
+ menu.removeCB = () => {
+ if (activeElement instanceof HTMLElement && activeElement.isConnected &&
+ menu.element.contains(document.activeElement)) {
+ activeElement.focus({preventScroll: true});
+ }
+ };
+ }
};
if (getHostCapabilities().workspaces) {
fetchPost("/api/system/getWorkspaces", {}, (response) => renderMenu(response.data));
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index c285a31f02..d32730c276 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -84,6 +84,7 @@ import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";
import {fontEvent} from "../toolbar/Font";
import {applyTableCellStyleHotkey} from "../toolbar/tableCell";
import {formatPainter} from "../toolbar/FormatPainter";
+import {closeSubElement, SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE} from "../toolbar/subElementLifecycle";
import {
addSubList,
appendListItem,
@@ -1892,6 +1893,14 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
// esc
if (event.key === "Escape") {
+ if (!protyle.toolbar.subElement.classList.contains("fn__none") &&
+ protyle.toolbar.subElement.dataset.subElementSource === SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE) {
+ protyle.toolbar.subElement.classList.add("fn__none");
+ closeSubElement(protyle.toolbar);
+ event.stopPropagation();
+ event.preventDefault();
+ return;
+ }
if (formatPainter.deactivate()) {
event.stopPropagation();
event.preventDefault();
diff --git a/app/tests/shortcutEscape.test.js b/app/tests/shortcutEscape.test.js
new file mode 100644
index 0000000000..38e6071109
--- /dev/null
+++ b/app/tests/shortcutEscape.test.js
@@ -0,0 +1,253 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+const ts = require("typescript");
+
+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 sources = () => {
+ const keyboard = sourceFile("protyle/wysiwyg/keydown.ts");
+ const escape = find(keyboard, node => ts.isIfStatement(node) &&
+ node.expression.getText(keyboard) === 'event.key === "Escape"');
+ const card = sourceFile("card/openCard.ts");
+ const openCard = find(card, node => ts.isVariableDeclaration(node) &&
+ node.name.getText(card) === "openCardByData").initializer;
+ const compile = text => ts.transpileModule(text, {compilerOptions: {
+ module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022,
+ }}).outputText;
+ const workspace = sourceFile("menus/workspace.ts");
+ const renderMenu = find(workspace, node => ts.isVariableDeclaration(node) &&
+ node.name.getText(workspace) === "renderMenu").initializer;
+ const popupIndex = renderMenu.body.statements.findIndex(node =>
+ node.getText(workspace).startsWith("window.siyuan.menus.menu.popup("));
+ assert.ok(popupIndex >= 0);
+ const menu = sourceFile("menus/Menu.ts");
+ const declaration = name => find(menu, node => ts.isVariableDeclaration(node) &&
+ node.name.getText(menu) === name).getText(menu);
+ return {
+ escape: compile(`function editorEscape(protyle, event, range, isCrossBlock, nodeElement) {
+ const blockSelectionModeElement = undefined;
+ ${escape.getText(keyboard)}
+ }` + sourceFile("protyle/toolbar/subElementLifecycle.ts").text.replaceAll("export ", "")),
+ card: compile(`const openCardByData = ${openCard.getText(card)};`),
+ menu: compile(`function openWorkspaceMenu(openOnly) {
+ const rect = {left: 0, bottom: 0, height: 0};
+ ${renderMenu.body.statements.slice(popupIndex).map(node => node.getText(workspace)).join("\n")}
+ }
+ const ${declaration("getActionMenu")};
+ const ${declaration("bindMenuKeydown")};`),
+ };
+};
+
+const cases = async compiled => {
+ const check = require("node:assert/strict");
+ const Constants = {DIALOG_OPENCARD: "card"};
+ const menu = document.createElement("div");
+ menu.className = "fn__none";
+ window.siyuan = {dialogs: [], menus: {menu: {element: menu}}, languages: {}};
+ let blockSelections = 0;
+ const hideElements = (panels, protyle) => {
+ for (const name of ["toolbar", "hint", "util"]) {
+ if (panels.includes(name)) {
+ (name === "util" ? protyle.toolbar.subElement : protyle[name].element).classList.add("fn__none");
+ }
+ }
+ if (panels.includes("select")) {
+ protyle.wysiwyg.element.querySelectorAll(".selected-block").forEach(item => item.classList.remove("selected-block"));
+ }
+ };
+ const editorEscape = new Function("hideElements", "formatPainter", "hasClosestByClassName",
+ "setBlockSelectionModeElement", "selectBlocksByRange", "clearBlockSelectionMode", "countBlockWord",
+ "BLOCK_SELECTION_CLASS", compiled.escape + "\nreturn editorEscape;")(hideElements, {deactivate: () => false},
+ (node, name) => (node.nodeType === 1 ? node : node.parentElement).closest(`.${name}`),
+ (root, block) => {block.classList.add("selected-block"); root.focus(); blockSelections++;},
+ () => blockSelections++, () => {}, () => {}, "selected-block");
+ const setup = () => {
+ document.body.innerHTML = '<div class="protyle-wysiwyg" tabindex="0"><div data-node-id="first"><div contenteditable="true">First text</div></div><div data-node-id="last"><div contenteditable="true">Last text</div></div></div>';
+ const root = document.body.firstElementChild;
+ const element = document.createElement("div");
+ const subElement = document.createElement("div");
+ const hint = document.createElement("div");
+ return {wysiwyg: {element: root}, toolbar: {element, subElement}, hint: {element: hint}};
+ };
+ // 行内外观先独立关闭,跨块文本选区和工具栏保持不变。
+ for (const crossBlock of [false, true]) {
+ const protyle = setup();
+ const root = protyle.wysiwyg.element;
+ const first = root.firstElementChild;
+ const range = document.createRange();
+ range.setStart(first.firstElementChild.firstChild, 0);
+ range.setEnd((crossBlock ? root.lastElementChild : first).firstElementChild.firstChild, 4);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ const selected = getSelection().toString();
+ let cleaned = 0;
+ protyle.toolbar.subElement.dataset.subElementSource = "selection-toolbar";
+ protyle.toolbar.subElementCloseCB = () => cleaned++;
+ protyle.hint.element.classList.add("fn__none");
+ root.addEventListener("keydown", event => editorEscape(protyle, event, range, crossBlock, first));
+ const before = blockSelections;
+ const event = new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true});
+ first.firstElementChild.dispatchEvent(event);
+ check.equal(event.defaultPrevented, true);
+ check.equal(protyle.toolbar.subElement.classList.contains("fn__none"), true);
+ check.equal(protyle.toolbar.element.classList.contains("fn__none"), false);
+ check.equal(getSelection().toString(), selected);
+ check.equal(blockSelections, before);
+ check.equal(cleaned, 1);
+ check.equal(protyle.toolbar.subElement.dataset.subElementSource, undefined);
+ }
+ // 使用复习弹窗的实际打开函数,验证捕获阶段不会抢走正文的 Esc。
+ for (const mobile of [false, true]) {
+ const protyle = setup();
+ for (const element of [protyle.toolbar.element, protyle.toolbar.subElement, protyle.hint.element]) {
+ element.classList.add("fn__none");
+ }
+ const root = protyle.wysiwyg.element;
+ const first = root.firstElementChild;
+ const editor = {protyle, resize() {}, destroy() {}};
+ class Dialog {
+ constructor() {
+ this.element = document.createElement("div");
+ this.element.dataset.key = "card";
+ this.element.innerHTML = '<div class="b3-dialog__scrim"></div><div class="b3-dialog__container"><div class="card__main"><div class="block__icons card__action"><button class="block__icon">Review</button></div></div></div>';
+ this.element.querySelector(".card__main").append(root);
+ document.body.append(this.element);
+ window.siyuan.dialogs.push(this);
+ this.destroyed = false;
+ }
+ destroy() {this.destroyed = true;}
+ }
+ const focusByRange = range => {getSelection().removeAllRanges(); getSelection().addRange(range);};
+ const openCard = new Function("window", "Dialog", "Constants", "genCardHTML", "isMobile", "bindCardEvent",
+ "focusByRange", "updateCardHV", compiled.card + "\nreturn openCardByData;")(
+ window, Dialog, Constants, () => "", () => mobile, async () => editor, focusByRange, () => {});
+ window.siyuan.dialogs = [];
+ await openCard({plugins: []}, {}, "all");
+ const dialog = window.siyuan.dialogs[0];
+ const range = document.createRange();
+ range.selectNodeContents(first.firstElementChild);
+ range.collapse();
+ focusByRange(range);
+ first.firstElementChild.focus();
+ root.addEventListener("keydown", event => editorEscape(protyle, event, range, false, first));
+ const before = blockSelections;
+ first.firstElementChild.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true, cancelable: true}));
+ check.equal(dialog.destroyed, false);
+ check.equal(blockSelections, before + 1);
+ check.equal(first.classList.contains("selected-block"), true);
+ root.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", repeat: true, bubbles: true, cancelable: true}));
+ check.equal(dialog.destroyed, false);
+ check.equal(document.activeElement, dialog.element.querySelector(".card__action button"));
+ check.equal(first.classList.contains("selected-block"), false);
+ }
+ // 快捷键将焦点移到可操作菜单项,方向键不再被编辑器截获。
+ const menuBindings = new Function("window", "Constants", compiled.menu +
+ "\nreturn {openWorkspaceMenu, bindMenuKeydown};")(window, {KEYCODELIST: {38: "↑", 40: "↓"}});
+ for (const openOnly of [true, false]) {
+ const protyle = setup();
+ const editor = protyle.wysiwyg.element.firstElementChild.firstElementChild;
+ editor.focus();
+ const menuElement = document.createElement("div");
+ menuElement.className = "b3-menu fn__none";
+ menuElement.innerHTML = '<div></div><div class="b3-menu__items"><button class="b3-menu__item" style="display: none">Hidden</button><button class="b3-menu__item b3-menu__item--readonly">Readonly</button><button class="b3-menu__item" disabled>Disabled</button><button class="b3-menu__item" id="firstAction">First</button><button class="b3-menu__item" id="nextAction">Next</button></div>';
+ document.body.append(menuElement);
+ const menu = {element: menuElement, popup: () => menuElement.classList.remove("fn__none"),
+ remove() {this.removeCB?.(); this.removeCB = undefined; menuElement.classList.add("fn__none");}};
+ window.siyuan.menus.menu = menu;
+ let editorArrows = 0;
+ editor.addEventListener("keydown", event => {
+ if (event.key.startsWith("Arrow")) {
+ editorArrows++;
+ event.stopPropagation();
+ }
+ });
+ const listener = event => {
+ if (menuBindings.bindMenuKeydown(event)) {
+ event.preventDefault();
+ } else if (event.key === "Escape") {
+ menu.remove();
+ event.preventDefault();
+ }
+ };
+ document.body.addEventListener("keydown", listener);
+ try {
+ menuBindings.openWorkspaceMenu(openOnly);
+ check.equal(document.activeElement, openOnly ? menuElement.querySelector("#firstAction") : editor);
+ document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "ArrowDown", keyCode: 40, bubbles: true, cancelable: true,
+ }));
+ check.equal(editorArrows, openOnly ? 0 : 1);
+ if (openOnly) {
+ check.equal(menuElement.querySelector(".b3-menu__item--current").id, "nextAction");
+ document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "Escape", bubbles: true, cancelable: true,
+ }));
+ check.equal(menuElement.classList.contains("fn__none"), true);
+ check.equal(document.activeElement, editor);
+ menuBindings.openWorkspaceMenu(true);
+ const newFocus = document.createElement("button");
+ document.body.append(newFocus);
+ newFocus.focus();
+ menu.remove();
+ check.equal(document.activeElement, newFocus);
+ }
+ } finally {
+ document.body.removeEventListener("keydown", listener);
+ }
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ (async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, webPreferences: {
+ nodeIntegration: true, contextIsolation: false, backgroundThrottling: false,
+ }});
+ let result = 0;
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.executeJavaScript(`(${cases.toString()})(${JSON.stringify(sources())})`);
+ console.log("Shortcut Escape and menu focus cases passed");
+ } catch (error) {
+ console.error(error);
+ result = 1;
+ } finally {
+ win.destroy();
+ app.exit(result);
+ }
+ })();
+} else {
+ require("node:test").test("shortcut menu focus and Escape preserve editor behavior", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 35000,
+ }, async () => {
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-shortcut-escape-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 30000});
+ assert.match(stdout, /Shortcut Escape and menu focus cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(profile).startsWith("siyuan-shortcut-escape-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}
diff --git a/app/tests/shortcutOpenPanels.test.js b/app/tests/shortcutOpenPanels.test.js
index ac9252a558..08685024ba 100644
--- a/app/tests/shortcutOpenPanels.test.js
+++ b/app/tests/shortcutOpenPanels.test.js
@@ -111,37 +111,52 @@ test("native shortcut sources open panels without toggling while menu commands r
}
});
-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);
+test("Ctrl+E and Alt+0 keep their dialogs open through the actual global keydown branches", async () => {
+ const keymap = evaluate(sourceFile("util/keymapBindings.ts").text, {});
+ const Constants = {DIALOG_RECENTDOCS: "recent", DIALOG_OPENCARD: "card", KEYCODELIST: {69: "E", 48: "0"}};
+ const {matchHotKey} = evaluate(sourceFile("protyle/util/hotKey.ts").text, {
+ require: name => name.endsWith("keymapBindings") ? keymap : name.endsWith("constants") ? {Constants} : {
+ isMac: () => false, isNotCtrl: event => !event.ctrlKey && !event.metaKey,
+ isOnlyMeta: event => event.ctrlKey && !event.metaKey,
+ },
+ });
+ const source = sourceFile("boot/globalEvent/keydown.ts");
+ for (const [command, key, eventFlags] of [
+ ["recentDocs", "⌘E", {key: "e", keyCode: 69, ctrlKey: true}],
+ ["riffCard", "⌥0", {key: "0", keyCode: 48, altKey: true}],
+ ]) {
+ const branch = find(source, node => ts.isIfStatement(node) &&
+ node.expression.getText(source).includes(`keymap.general.${command}, event`));
+ let closes = 0;
+ let blurs = 0;
+ const pending = [];
+ const window = {siyuan: {config: {keymap: {general: {[command]: {custom: key}}}},
+ dialogs: [{element: {getAttribute: () => command === "recentDocs" ? "recent" : "card"},
+ destroy: () => closes++}]}};
+ const recentSource = sourceFile("business/openRecentDocs.ts");
+ const recent = prefix(recentSource, arrow(recentSource, "openRecentDocs"), "const sortBy", {
+ window, Constants, hideElements: () => closes++,
+ });
+ const cardSource = sourceFile("card/openCard.ts");
+ const card = prefix(cardSource, arrow(cardSource, "openCardByData"), "let lastRange", {window, Constants});
+ const openCard = evaluate(`exports.openCard = ${arrow(cardSource, "openCard").getText(cardSource)};`, {
+ window, fetchPost: (_url, _data, callback) => callback({data: {}}),
+ openCardByData: (...args) => pending.push(card(...args)),
+ }).openCard;
+ const handler = evaluate(`exports.subject = function(event) {${branch.getText(source)}};`, {
+ app: {}, window, Constants, isTabWindow: false, matchHotKey,
+ document: {activeElement: {blur: () => blurs++}}, openCard,
+ openRecentDocs: (...args) => pending.push(recent(...args)),
+ }).subject;
+ for (const repeat of [false, true]) {
+ const event = {ctrlKey: false, metaKey: false, altKey: false, shiftKey: false,
+ repeat, ...eventFlags, preventDefault() {this.defaultPrevented = true;}};
+ handler(event);
+ await Promise.all(pending);
+ assert.equal(event.defaultPrevented, true);
+ assert.equal(closes, 0);
+ assert.equal(blurs, 0);
+ assert.equal(window.siyuan.dialogs.length, 1);
+ }
}
- 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);
});