Skip to content

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

:bug: Unify read-only editor shortcut handling https://github.com/siyuan-note/siyuan/issues/19374

Daniel4015499392b0
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 9f21725ddf..db5dfe3409 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -206,21 +206,26 @@ const dialogArrow = (app: App, element: HTMLElement, event: KeyboardEvent) => {
const editKeydown = (app: App, event: KeyboardEvent) => {
const eventTarget = event.target as HTMLElement;
+ // 页签标题的未处理按键进入全局快捷键,不使用正文中可能残留的选区执行编辑命令。
+ if (eventTarget.closest(".tabs-header")) {
+ return false;
+ }
if (hasClosestByClassName(eventTarget, "sy__backlink--bottom", true) &&
!hasClosestByClassName(eventTarget, "protyle", true)) {
return false;
}
- let protyle: IProtyle;
+ // 优先使用事件所属编辑器,避免只读正文获得焦点后仍命中其它编辑器的选区。
+ let protyle = getAllEditor().find(item => item.protyle.element.contains(eventTarget))?.protyle;
let range: Range;
if (getSelection().rangeCount > 0) {
range = getSelection().getRangeAt(0);
}
const activePanelElement = document.querySelector(".layout__tab--active");
let isFileFocus = false;
- if (activePanelElement && activePanelElement.classList.contains("sy__file")) {
+ if (!protyle && activePanelElement && activePanelElement.classList.contains("sy__file")) {
isFileFocus = true;
}
- if (range) {
+ if (!protyle && range) {
window.siyuan.dialogs.find(item => {
if (item.editors) {
Object.keys(item.editors).find(key => {
@@ -305,6 +310,23 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
return false;
}
}
+ if (protyle.disabled && [
+ window.siyuan.config.keymap.general.move,
+ window.siyuan.config.keymap.general.addToDatabase,
+ window.siyuan.config.keymap.editor.general.quickMakeCard,
+ window.siyuan.config.keymap.editor.general.duplicate,
+ window.siyuan.config.keymap.editor.general.duplicateCompletely,
+ window.siyuan.config.keymap.editor.general.undo,
+ window.siyuan.config.keymap.editor.general.redo,
+ ].some(keymap => matchHotKey(keymap, event))) {
+ // 内容修改在编辑快捷键入口拦截,不阻断搜索、导航和其它全局操作。
+ event.preventDefault();
+ return true;
+ }
+ // 焦点移动到不可编辑容器后,浏览器可能没有正文选区,或仍保留其它编辑器的选区。
+ if (!range || !protyle.element.contains(range.commonAncestorContainer)) {
+ range = undefined;
+ }
if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.replace, event)) {
execByCommand({
command: "replace",
@@ -325,7 +347,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
event.preventDefault();
return true;
}
- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard, event) && !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {
+ if (!isFileFocus && range && matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard, event) && !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {
if (protyle.title?.editElement.contains(range.startContainer)) {
quickMakeCard(protyle, [protyle.title.element]);
} else {
@@ -373,7 +395,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
return true;
}
- if (!isFileFocus && !event.repeat && !protyle.disabled &&
+ if (!isFileFocus && range && !event.repeat && !protyle.disabled &&
matchHotKey(window.siyuan.config.keymap.editor.general.duplicate, event)) {
event.preventDefault();
event.stopPropagation();
@@ -414,7 +436,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
zoomOut({protyle, id: protyle.block.rootID, focusId: protyle.block.id});
return true;
}
- if (matchHotKey(window.siyuan.config.keymap.editor.general.focusBreadcrumb, event)) {
+ if (range && matchHotKey(window.siyuan.config.keymap.editor.general.focusBreadcrumb, event)) {
if (protyle.breadcrumb?.focus(range)) {
event.preventDefault();
return true;
@@ -498,7 +520,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
}
/// #if !MOBILE
if (matchHotKey(window.siyuan.config.keymap.editor.general.copyRichText, event)) {
- if (!hasClosestBlock(range.startContainer)) {
+ if (!range || !hasClosestBlock(range.startContainer)) {
return false;
}
protyle.wysiwyg.copyRichText();
@@ -507,6 +529,9 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
}
/// #endif
if (matchHotKey(window.siyuan.config.keymap.editor.general.copyPlainText, event)) {
+ if (!range) {
+ return false;
+ }
const nodeElement = hasClosestBlock(range.startContainer);
if (!nodeElement) {
return false;
@@ -528,6 +553,9 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
return true;
}
if (matchHotKey(window.siyuan.config.keymap.editor.general.duplicateCompletely, event)) {
+ if (!range) {
+ return false;
+ }
const nodeElement = hasClosestBlock(range.startContainer);
if (!nodeElement || !nodeElement.classList.contains("av")) {
return false;
diff --git a/app/src/boot/globalEvent/readonlyKeydown.test.ts b/app/src/boot/globalEvent/readonlyKeydown.test.ts
new file mode 100644
index 0000000000..5b866dc2ed
--- /dev/null
+++ b/app/src/boot/globalEvent/readonlyKeydown.test.ts
@@ -0,0 +1,122 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const loadFunction = (path: string, name: string, globals: Record<string, unknown>) => {
+ const source = createSourceFile(path, readFileSync(path, "utf8"), ScriptTarget.ES2021, true);
+ const declaration = source.statements.find(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(source) === name));
+ assert.ok(declaration);
+ const compiled = transpileModule(`${declaration.getText(source)}\nexports.subject = ${name};`, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const exports: any = {};
+ runInNewContext(compiled, {exports, ...globals});
+ return exports.subject;
+};
+
+const keyboardEvent = (key: string, header = false) => ({
+ key,
+ target: {localName: "div", closest: () => header ? {} : null},
+ defaultPrevented: false,
+ propagationStopped: false,
+ preventDefault() { this.defaultPrevented = true; },
+ stopPropagation() { this.propagationStopped = true; },
+});
+
+test("readonly body and tab header preserve keyboard defaults and bubbling", async () => {
+ const bind = loadFunction("src/protyle/wysiwyg/keydown.ts", "keydown", {
+ bindVerticalNavigationReset: (): void => undefined,
+ getAVTemplateInteractiveElement: () => false,
+ hasClosestByAttribute: () => false,
+ });
+ for (const [disabled, header] of [[true, false], [true, true], [false, true]]) {
+ let listener: (event: any) => Promise<void>;
+ bind({disabled}, {addEventListener: (_type: string, callback: typeof listener) => listener = callback});
+ for (const key of ["copy", "commandPanel", "editReadonly", "search", "customShortcut", "Tab", "ArrowDown", "Escape"]) {
+ const event = keyboardEvent(key, header);
+ await listener(event);
+ assert.equal(event.defaultPrevented, false, key);
+ assert.equal(event.propagationStopped, false, key);
+ }
+ }
+});
+
+const globalFixture = (disabled: boolean, hasRange = true, foreignRange = false) => {
+ const calls: string[] = [];
+ const body = {};
+ const range = {commonAncestorContainer: foreignRange ? {} : body};
+ const protyle = {
+ disabled,
+ options: {},
+ element: {contains: (node: unknown) => node === body || (node as any)?.localName === "div"},
+ undo: {undo: () => calls.push("undo"), redo: () => calls.push("redo")},
+ };
+ const bindings = new Proxy({}, {get: (_target, key) => key});
+ const edit = loadFunction("src/boot/globalEvent/keydown.ts", "editKeydown", {
+ getAllEditor: () => [{protyle}],
+ getSelection: () => ({rangeCount: hasRange ? 1 : 0, getRangeAt: () => range}),
+ getActiveTab: (): null => null,
+ document: {querySelector: (): null => null},
+ window: {siyuan: {config: {keymap: {general: bindings, editor: {general: bindings}}}}},
+ hasClosestByClassName: () => false,
+ isOnlyMeta: () => false,
+ matchHotKey: (binding: string, event: {key: string}) => binding === event.key,
+ execByCommand: ({command}: {command: string}) => calls.push(command),
+ });
+ return {edit: (event: any) => edit({}, event), calls};
+};
+
+test("readonly content mutations are consumed before command execution, even without a valid selection", () => {
+ for (const [hasRange, foreignRange] of [[true, false], [false, false], [true, true]]) {
+ const fixture = globalFixture(true, hasRange, foreignRange);
+ for (const command of ["move", "addToDatabase", "quickMakeCard", "duplicate", "duplicateCompletely", "undo", "redo"]) {
+ const event = keyboardEvent(command);
+ assert.equal(fixture.edit(event), true, command);
+ assert.equal(event.defaultPrevented, true, command);
+ }
+ assert.deepEqual(fixture.calls, []);
+ }
+});
+
+test("readonly search remains contextual while unmatched shortcuts reach global dispatch", () => {
+ const fixture = globalFixture(true);
+ assert.equal(fixture.edit(keyboardEvent("search")), true);
+ assert.deepEqual(fixture.calls, ["search"]);
+ for (const command of ["commandPanel", "editReadonly", "customShortcut"]) {
+ const event = keyboardEvent(command);
+ assert.equal(fixture.edit(event), false);
+ assert.equal(event.defaultPrevented, false);
+ }
+});
+
+test("tab headers and stale selections do not execute commands on the old text selection", () => {
+ const header = globalFixture(false);
+ assert.equal(header.edit(keyboardEvent("undo", true)), false);
+ assert.deepEqual(header.calls, []);
+ const stale = globalFixture(false, true, true);
+ assert.equal(stale.edit(keyboardEvent("copyPlainText")), false);
+ assert.deepEqual(stale.calls, []);
+});
+
+test("editable undo still executes", () => {
+ for (const [hasRange, foreignRange] of [[true, false], [false, false], [true, true]]) {
+ const fixture = globalFixture(false, hasRange, foreignRange);
+ assert.equal(fixture.edit(keyboardEvent("undo")), true);
+ assert.deepEqual(fixture.calls, ["undo"]);
+ }
+});
+
+test("native command availability protects readonly content across command panel and shortcuts", () => {
+ const matches = loadFunction("src/command/nativeCommands.ts", "matchesContext", {});
+ for (const legacyId of ["move", "addToDatabase"]) {
+ const item = {legacyId, requirement: "editorOrFileTree"};
+ assert.equal(matches(item, {focus: "editor", protyle: {disabled: true}}), false);
+ assert.equal(matches(item, {focus: "editor", protyle: {disabled: false}}), true);
+ assert.equal(matches(item, {focus: "fileTree", fileTree: {elements: [{}]}}), true);
+ }
+ assert.equal(matches({legacyId: "search", requirement: "none"}, {protyle: {disabled: true}}), true);
+ assert.equal(matches({legacyId: "switchReadonly", requirement: "editor"}, {protyle: {disabled: true}}), true);
+});
diff --git a/app/src/command/nativeCommands.ts b/app/src/command/nativeCommands.ts
index ceeaedebaa..9e265fed12 100644
--- a/app/src/command/nativeCommands.ts
+++ b/app/src/command/nativeCommands.ts
@@ -23,6 +23,11 @@ const getHotkey = (item: INativeCommandCatalogItem) => {
};
const matchesContext = (item: INativeCommandCatalogItem, context: ICommandContextSnapshot) => {
+ // 命令面板和快捷键共用只读限制,文档树操作仍按文档树上下文处理。
+ if (context.focus !== "fileTree" && context.protyle?.disabled &&
+ ["move", "addToDatabase"].includes(item.legacyId)) {
+ return false;
+ }
if (item.requirement === "editor") {
return Boolean(context.protyle);
}
diff --git a/app/src/protyle/render/tabsKeyboard.test.ts b/app/src/protyle/render/tabsKeyboard.test.ts
new file mode 100644
index 0000000000..3f3205c118
--- /dev/null
+++ b/app/src/protyle/render/tabsKeyboard.test.ts
@@ -0,0 +1,101 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isArrowFunction, isCallExpression, ModuleKind, Node, ScriptTarget, transpileModule} from "typescript";
+import {tabKeyboardTarget} from "./tabsState";
+
+const source = createSourceFile("tabsRender.ts", readFileSync("src/protyle/render/tabsRender.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+
+const loadHandler = (element: "button" | "task", globals: Record<string, unknown>) => {
+ let handler: Node;
+ const visit = (node: Node) => {
+ if (isCallExpression(node) && node.expression.getText(source) === `${element}.addEventListener` &&
+ node.arguments[0].getText(source) === (element === "button" ? '"keydown"' : "type") &&
+ isArrowFunction(node.arguments[1])) {
+ handler = node.arguments[1];
+ }
+ node.forEachChild(visit);
+ };
+ visit(source);
+ assert.ok(handler);
+ const compiled = transpileModule(`exports.handler = ${handler.getText(source)};`, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const exports: any = {};
+ runInNewContext(compiled, {exports, ...globals});
+ return exports.handler;
+};
+
+const fixture = (readonly: boolean, vertical = false) => {
+ const calls: string[] = [];
+ const globals = {
+ ids: ["a", "b"], item: {}, itemID: () => "a", type: "keydown", readonly,
+ tabs: {getAttribute: () => vertical ? "vertical" : "horizontal"},
+ tabKeyboardTarget,
+ list: {children: [{
+ dataset: {tabId: "b"},
+ scrollIntoView: () => calls.push("scroll"),
+ focus: () => calls.push("focus"),
+ }]},
+ controller: {select: () => calls.push("select"), options: {task: () => calls.push("task")}},
+ };
+ const button = loadHandler("button", globals);
+ const task = loadHandler("task", globals);
+ const dispatch = (key: string, onTask = false, modifiers: Record<string, boolean> = {}) => {
+ const event = {
+ key, defaultPrevented: false, propagationStopped: false, ...modifiers,
+ preventDefault() { this.defaultPrevented = true; },
+ stopPropagation() { this.propagationStopped = true; },
+ };
+ if (onTask) {
+ task(event);
+ }
+ if (!event.propagationStopped) {
+ button(event);
+ }
+ return event;
+ };
+ return {dispatch, calls};
+};
+
+test("tab controls leave modified shortcuts and composition events for their owners", () => {
+ for (const readonly of [false, true]) {
+ const f = fixture(readonly);
+ for (const modifier of ["ctrlKey", "metaKey", "altKey", "shiftKey", "isComposing"]) {
+ for (const key of ["Enter", " ", "ArrowRight", "Home"]) {
+ for (const onTask of [false, true]) {
+ const event = f.dispatch(key, onTask, {[modifier]: true});
+ assert.equal(event.defaultPrevented, false);
+ assert.equal(event.propagationStopped, false);
+ }
+ }
+ }
+ assert.deepEqual(f.calls, []);
+ }
+});
+
+test("plain tab navigation keeps focus and consumes only matching orientation keys", () => {
+ for (const vertical of [false, true]) {
+ const f = fixture(true, vertical);
+ const event = f.dispatch(vertical ? "ArrowDown" : "ArrowRight");
+ assert.equal(event.defaultPrevented, true);
+ assert.equal(event.propagationStopped, true);
+ assert.deepEqual(f.calls, ["scroll", "focus"]);
+ assert.equal(f.dispatch(vertical ? "ArrowRight" : "ArrowDown").propagationStopped, false);
+ assert.equal(f.dispatch("Tab").defaultPrevented, false);
+ }
+});
+
+test("readonly task activation cannot toggle the task or select the parent tab", () => {
+ const locked = fixture(true);
+ assert.equal(locked.dispatch("Enter", true).propagationStopped, true);
+ assert.deepEqual(locked.calls, []);
+ const editable = fixture(false);
+ assert.equal(editable.dispatch(" ", true).propagationStopped, true);
+ assert.deepEqual(editable.calls, ["task"]);
+ const tab = fixture(true);
+ assert.equal(tab.dispatch("Enter").propagationStopped, true);
+ assert.deepEqual(tab.calls, ["select"]);
+});
diff --git a/app/src/protyle/render/tabsRender.ts b/app/src/protyle/render/tabsRender.ts
index eb068c7924..582c828269 100644
--- a/app/src/protyle/render/tabsRender.ts
+++ b/app/src/protyle/render/tabsRender.ts
@@ -185,7 +185,7 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
header.setAttribute("contenteditable", "false");
if (!boundHeaders.has(header)) {
boundHeaders.add(header);
- ["pointerdown", "mousedown", "mouseup", "click", "keydown"].forEach(type => {
+ ["pointerdown", "mousedown", "mouseup", "click"].forEach(type => {
header.addEventListener(type, event => event.stopPropagation());
});
header.addEventListener("selectstart", event => event.preventDefault());
@@ -264,10 +264,14 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
task.classList.add("tabs-task--custom");
}
["click", "dblclick", "contextmenu", "keydown"].forEach(type => task.addEventListener(type, event => {
- event.stopPropagation();
- if (type === "keydown" && !["Enter", " "].includes((event as KeyboardEvent).key)) {
- return;
+ if (type === "keydown") {
+ const keyEvent = event as KeyboardEvent;
+ if (keyEvent.isComposing || keyEvent.ctrlKey || keyEvent.metaKey || keyEvent.altKey ||
+ keyEvent.shiftKey || !["Enter", " "].includes(keyEvent.key)) {
+ return;
+ }
}
+ event.stopPropagation();
event.preventDefault();
if (!readonly) {
if (type === "contextmenu") {
@@ -298,6 +302,9 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
controller.options.menu?.(tabs, item, button);
});
button.addEventListener("keydown", event => {
+ if (event.isComposing || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) {
+ return;
+ }
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
event.stopPropagation();
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 278081a90d..4e20387709 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -317,21 +317,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
event.stopPropagation();
return;
}
- if (protyle.disabled) {
- if (event.key === "Escape" && !event.isComposing && !event.repeat) {
- return;
- }
- // 放行锁定编辑和命令面板快捷键,由全局快捷键处理器执行。
- if (matchHotKey(window.siyuan.config.keymap.general.editReadonly, event) ||
- matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {
- return;
- }
- event.stopPropagation();
- // 只读页签正文获得焦点后,保留复制快捷键的默认行为。
- if (matchHotKey("⌘C", event)) {
- return;
- }
- event.preventDefault();
+ // 只读正文和页签标题不执行正文编辑逻辑,保留默认行为并交给全局快捷键处理器。
+ if (protyle.disabled || event.target.closest(".tabs-header")) {
return;
}
if (!protyle.selectElement.classList.contains("fn__none") &&