Skip to content

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

:bug: Honor selected embed blocks in insertion shortcuts https://github.com/siyuan-note/siyuan/issues/20026

Daniel092b767305f9
diff --git a/app/src/block/insertEmptyBlock.test.ts b/app/src/block/insertEmptyBlock.test.ts
index 72dbdc8dc9..484a171da1 100644
--- a/app/src/block/insertEmptyBlock.test.ts
+++ b/app/src/block/insertEmptyBlock.test.ts
@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {getBlockInsertionContext} from "../protyle/wysiwyg/blockInsertion";
import {
BLOCK_SELECTION_CLASS,
BLOCK_SELECTION_MODE_CLASS,
@@ -21,6 +22,8 @@ const compiled = transpileModule(
}).outputText;
class TestElement {
+ nodeType = 1;
+ tagName = "DIV";
parentElement: TestElement;
children: TestElement[] = [];
attributes = new Map<string, string>();
@@ -72,7 +75,7 @@ class TestElement {
}
for (const position of ["beforebegin", "afterend"]) {
- for (const targetKind of ["cursor", "element", "id", "multiple", "editing"]) {
+ for (const targetKind of ["cursor", "element", "id", "multiple", "editing", "embed"]) {
for (const type of ["NodeParagraph", "NodeHeading", "NodeCodeBlock"]) {
test(`${position} from ${targetKind} at ${type} clears the old input target`, async () => {
const editor = new TestElement("editor");
@@ -80,6 +83,11 @@ for (const position of ["beforebegin", "afterend"]) {
const first = new TestElement("first", type);
const last = new TestElement("last");
editor.append(first, last);
+ if (targetKind === "embed") {
+ first.attributes.set("data-type", "NodeBlockQueryEmbed");
+ first.classes.add(BLOCK_SELECTION_CLASS);
+ first.append(new TestElement("inner"));
+ }
if (targetKind !== "editing") {
first.classes.add(BLOCK_SELECTION_MODE_CLASS);
}
@@ -90,7 +98,7 @@ for (const position of ["beforebegin", "afterend"]) {
last.attributes.set("select-end", "true");
}
const inserted = new TestElement("inserted");
- const range = {startContainer: first};
+ const range = {startContainer: targetKind === "embed" ? first.children[0] : first};
const context = {undoFocusId: "first"};
const protyle = {wysiwyg: {element: editor}};
const exports: {insertEmptyBlock?: (...args: unknown[]) => Promise<void>} = {};
@@ -125,8 +133,13 @@ for (const position of ["beforebegin", "afterend"]) {
callMobileAppShowKeyboard: () => keyboardRequests++,
});
+ const insertion = targetKind === "embed" ? getBlockInsertionContext(editor as unknown as Element,
+ range.startContainer as unknown as Element, position as "beforebegin" | "afterend") : undefined;
+ if (insertion) {
+ assert.equal(insertion.allowed, true);
+ }
await exports.insertEmptyBlock(protyle, position,
- targetKind === "element" ? first : targetKind === "id" ? "first" : undefined);
+ insertion?.target || (targetKind === "element" ? first : targetKind === "id" ? "first" : undefined));
assert.equal(getBlockSelectionModeElement(editor as unknown as Element), undefined);
assert.equal(editor.querySelectorAll(`.${BLOCK_SELECTION_CLASS}`).length, 0);
@@ -144,6 +157,9 @@ for (const position of ["beforebegin", "afterend"]) {
assert.equal(inverse[0].action, "delete");
assert.equal(inverse[0].id, "inserted");
assert.equal(inverse[0].context, context);
+ if (targetKind === "embed") {
+ assert.deepEqual(first.children.map(child => child.getAttribute("data-node-id")), ["inner"]);
+ }
});
}
}
diff --git a/app/src/protyle/wysiwyg/blockInsertion.test.ts b/app/src/protyle/wysiwyg/blockInsertion.test.ts
new file mode 100644
index 0000000000..5db4e92580
--- /dev/null
+++ b/app/src/protyle/wysiwyg/blockInsertion.test.ts
@@ -0,0 +1,114 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {getBlockInsertionContext} from "./blockInsertion";
+
+class TestElement {
+ nodeType = 1;
+ tagName = "DIV";
+ selected: TestElement[] = [];
+ classList = {contains: (name: string) => name === "protyle-wysiwyg" && this.type === "editor"};
+
+ constructor(public type: string, public parentElement?: TestElement) {}
+
+ getAttribute(name: string) {
+ return name === "data-type" ? this.type : null;
+ }
+
+ querySelectorAll() {
+ return this.selected;
+ }
+
+ querySelector() {
+ return null;
+ }
+}
+
+const asElement = (element: TestElement) => element as unknown as Element;
+const keydownSource = readFileSync("src/protyle/wysiwyg/keydown.ts", "utf8");
+const shortcutSource = keydownSource.slice(
+ keydownSource.indexOf(" if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBefore, event))"),
+ keydownSource.indexOf(" if (matchHotKey(window.siyuan.config.keymap.editor.general.insertSuperBlockLeft, event)"));
+
+for (const position of ["beforebegin", "afterend"] as const) {
+ test(`${position} shortcut dispatch passes the checked target exactly once`, () => {
+ const editor = new TestElement("editor");
+ const embed = new TestElement("NodeBlockQueryEmbed", editor);
+ const inner = new TestElement("NodeParagraph", embed);
+ const key = position === "beforebegin" ? "insertBefore" : "insertAfter";
+ for (const selected of [embed, inner]) {
+ editor.selected = [selected];
+ const calls: Array<{position: string; target: TestElement}> = [];
+ let prevented = 0;
+ runInNewContext(`(function () {${shortcutSource}})()`, {
+ editorElement: editor,
+ nodeElement: inner,
+ blockSelectionModeElement: undefined,
+ protyle: {},
+ window: {siyuan: {config: {keymap: {editor: {general: {insertBefore: "insertBefore", insertAfter: "insertAfter"}}}}}},
+ event: {preventDefault: () => prevented++, stopPropagation: () => {}},
+ matchHotKey: (hotkey: string) => hotkey === key,
+ getBlockInsertionContext,
+ insertEmptyBlock: (_protyle: unknown, insertionPosition: string, target: TestElement) => {
+ calls.push({position: insertionPosition, target});
+ },
+ });
+ assert.equal(prevented, selected === embed ? 1 : 0);
+ assert.equal(calls.length, selected === embed ? 1 : 0);
+ if (selected === embed) {
+ assert.equal(calls[0].target, embed);
+ assert.equal(calls[0].position, position);
+ }
+ }
+ });
+
+ test(`${position} uses selected outer embed instead of its inner caret`, () => {
+ const editor = new TestElement("editor");
+ const embed = new TestElement("NodeBlockQueryEmbed", editor);
+ const inner = new TestElement("NodeParagraph", embed);
+ editor.selected = [embed];
+ const context = getBlockInsertionContext(asElement(editor), asElement(inner), position);
+ assert.equal(context.target, embed);
+ assert.equal(context.allowed, true);
+ });
+
+ test(`${position} preserves embedded-content protection`, () => {
+ const editor = new TestElement("editor");
+ const embed = new TestElement("NodeBlockQueryEmbed", editor);
+ const inner = new TestElement("NodeParagraph", embed);
+ const nested = new TestElement("NodeBlockQueryEmbed", embed);
+ for (const selected of [[], [inner], [nested]]) {
+ editor.selected = selected;
+ assert.equal(getBlockInsertionContext(asElement(editor), asElement(inner), position).allowed, false);
+ }
+ });
+
+ test(`${position} chooses the selection boundary before selection-mode focus`, () => {
+ const editor = new TestElement("editor");
+ const first = new TestElement("NodeParagraph", editor);
+ const last = new TestElement("NodeBlockQueryEmbed", editor);
+ const inner = new TestElement("NodeParagraph", last);
+ editor.selected = [first, last];
+ for (const active of [first, last]) {
+ const context = getBlockInsertionContext(asElement(editor), asElement(inner), position, asElement(active));
+ assert.equal(context.target, position === "beforebegin" ? first : last);
+ assert.equal(context.allowed, true);
+ }
+ });
+
+ test(`${position} supports selection mode without changing ordinary caret fallback`, () => {
+ const editor = new TestElement("editor");
+ const embed = new TestElement("NodeBlockQueryEmbed", editor);
+ const inner = new TestElement("NodeParagraph", embed);
+ const normal = new TestElement("NodeParagraph", editor);
+ const selected = getBlockInsertionContext(asElement(editor), asElement(inner), position, asElement(embed));
+ assert.equal(selected.target, embed);
+ assert.equal(selected.allowed, true);
+ const editing = getBlockInsertionContext(asElement(editor), asElement(normal), position);
+ assert.equal(editing.target, undefined);
+ assert.equal(editing.allowed, true);
+ assert.equal(getBlockInsertionContext(asElement(editor), asElement(embed), position).allowed, true);
+ assert.equal(getBlockInsertionContext(asElement(editor), asElement(normal), position, asElement(inner)).allowed, false);
+ });
+}
diff --git a/app/src/protyle/wysiwyg/blockInsertion.ts b/app/src/protyle/wysiwyg/blockInsertion.ts
new file mode 100644
index 0000000000..8a0d03e5db
--- /dev/null
+++ b/app/src/protyle/wysiwyg/blockInsertion.ts
@@ -0,0 +1,11 @@
+import {isInEmbedBlock} from "../util/hasClosest";
+import {BLOCK_SELECTION_CLASS} from "./blockSelection";
+
+export const getBlockInsertionContext = (editorElement: Element, nodeElement: Element,
+ position: "beforebegin" | "afterend", selectionModeElement?: Element) => {
+ const selectedElements = editorElement.querySelectorAll(`.${BLOCK_SELECTION_CLASS}`);
+ const target = selectedElements.length > 0 ?
+ selectedElements[position === "beforebegin" ? 0 : selectedElements.length - 1] : selectionModeElement;
+ // 以实际插入目标检查嵌入边界,未选块时保留光标位置的插入规则。
+ return {target, allowed: !isInEmbedBlock(target || nodeElement)};
+};
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 0c701e1810..bb6aa2cb1f 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -2,6 +2,7 @@ import type {BlockQueryRequestInput} from "../../types/api";
import {isProtyleListItemFragment} from "../runtimeCapabilities";
import {hideElements} from "../ui/hideElements";
import {isTabTextBoundary} from "./tabsBoundary";
+import {getBlockInsertionContext} from "./blockInsertion";
import {isNotCtrl, isOnlyMeta, updateHotkeyTip, writeText} from "../util/compatibility";
import {
focusBlock,
@@ -382,8 +383,10 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
if ((nodeElement.classList.contains(BLOCK_SELECTION_CLASS) || blockSelectionModeElement) &&
isNotCtrl(event) && !event.shiftKey && !event.altKey &&
- !isInEmbedBlock(nodeElement)) {
- if (event.key.toLowerCase() === "a") {
+ ["a", "b"].includes(event.key.toLowerCase())) {
+ const position = event.key.toLowerCase() === "a" ? "afterend" : "beforebegin";
+ const insertion = getBlockInsertionContext(editorElement, nodeElement, position, blockSelectionModeElement);
+ if (insertion.allowed) {
event.stopPropagation();
event.preventDefault();
protyle.wysiwyg.element.blur();
@@ -393,19 +396,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
// 阻止中文输入的残留
setTimeout(() => {
- insertEmptyBlock(protyle, "afterend", blockSelectionModeElement);
- }, 100);
- return false;
- } else if (event.key.toLowerCase() === "b") {
- event.stopPropagation();
- event.preventDefault();
- protyle.wysiwyg.element.blur();
- if (blockSelectionModeElement) {
- clearBlockSelectionMode(protyle.wysiwyg.element, true);
- countBlockWord([], protyle);
- }
- setTimeout(() => {
- insertEmptyBlock(protyle, "beforebegin", blockSelectionModeElement);
+ insertEmptyBlock(protyle, position, insertion.target);
}, 100);
return false;
}
@@ -2418,21 +2409,25 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
event.stopPropagation();
return;
}
- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBefore, event) &&
- !isInEmbedBlock(nodeElement)) {
- // https://github.com/siyuan-note/siyuan/issues/14290#issuecomment-2846594701
- nodeElement.querySelector(".img--select")?.classList.remove("img--select");
- insertEmptyBlock(protyle, "beforebegin");
- event.preventDefault();
- return true;
+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBefore, event)) {
+ const insertion = getBlockInsertionContext(editorElement, nodeElement, "beforebegin", blockSelectionModeElement);
+ if (insertion.allowed) {
+ // https://github.com/siyuan-note/siyuan/issues/14290#issuecomment-2846594701
+ nodeElement.querySelector(".img--select")?.classList.remove("img--select");
+ insertEmptyBlock(protyle, "beforebegin", insertion.target);
+ event.preventDefault();
+ return true;
+ }
}
- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertAfter, event) &&
- !isInEmbedBlock(nodeElement)) {
- nodeElement.querySelector(".img--select")?.classList.remove("img--select");
- insertEmptyBlock(protyle, "afterend");
- event.preventDefault();
- event.stopPropagation();
- return true;
+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertAfter, event)) {
+ const insertion = getBlockInsertionContext(editorElement, nodeElement, "afterend", blockSelectionModeElement);
+ if (insertion.allowed) {
+ nodeElement.querySelector(".img--select")?.classList.remove("img--select");
+ insertEmptyBlock(protyle, "afterend", insertion.target);
+ event.preventDefault();
+ event.stopPropagation();
+ return true;
+ }
}
if (matchHotKey(window.siyuan.config.keymap.editor.general.insertSuperBlockLeft, event) &&
!isInEmbedBlock(nodeElement)) {