Skip to content

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

:bug: Restore the caret when undoing slash block commands https://github.com/siyuan-note/siyuan/issues/19955

Daniel9edf3aa12f9b
diff --git a/app/src/protyle/hint/blockHintRange.test.ts b/app/src/protyle/hint/blockHintRange.test.ts
index 1645f38a14..b62781ca1c 100644
--- a/app/src/protyle/hint/blockHintRange.test.ts
+++ b/app/src/protyle/hint/blockHintRange.test.ts
@@ -109,22 +109,21 @@ describe("shouldCaptureHintUndoFocus", () => {
const blockHintKeys = ["((", "[[", "((", "【【"];
it("captures block hint focus in all editors", () => {
- assert.equal(shouldCaptureHintUndoFocus("[[", blockHintKeys, false), true);
+ assert.equal(shouldCaptureHintUndoFocus("[[", blockHintKeys), true);
});
- it("captures slash hint focus in lite editors", () => {
- assert.equal(shouldCaptureHintUndoFocus("/", blockHintKeys, true), true);
- assert.equal(shouldCaptureHintUndoFocus("、", blockHintKeys, true), true);
+ it("captures slash hint focus in all editors", () => {
+ assert.equal(shouldCaptureHintUndoFocus("/", blockHintKeys), true);
+ assert.equal(shouldCaptureHintUndoFocus("、", blockHintKeys), true);
});
it("captures slash emoji focus in regular editors", () => {
- assert.equal(shouldCaptureHintUndoFocus("/", blockHintKeys, false, "emoji"), true);
- assert.equal(shouldCaptureHintUndoFocus("、", blockHintKeys, false, "emoji"), true);
+ assert.equal(shouldCaptureHintUndoFocus("/", blockHintKeys, "emoji"), true);
+ assert.equal(shouldCaptureHintUndoFocus("、", blockHintKeys, "emoji"), true);
});
- it("does not change regular editor slash hint focus handling", () => {
- assert.equal(shouldCaptureHintUndoFocus("/", blockHintKeys, false), false);
- assert.equal(shouldCaptureHintUndoFocus("#", blockHintKeys, true), false);
+ it("does not change unrelated hint focus handling", () => {
+ assert.equal(shouldCaptureHintUndoFocus("#", blockHintKeys), false);
});
});
diff --git a/app/src/protyle/hint/blockHintRange.ts b/app/src/protyle/hint/blockHintRange.ts
index f041c6f062..8e29d715ba 100644
--- a/app/src/protyle/hint/blockHintRange.ts
+++ b/app/src/protyle/hint/blockHintRange.ts
@@ -29,9 +29,8 @@ export const shouldIgnoreHintTrigger = (activeHint: string, candidateHint: strin
return activeHint === "#" && ["/", "、"].includes(candidateHint);
};
-export const shouldCaptureHintUndoFocus = (splitChar: string, blockHintKeys: string[], lite: boolean,
- value = "") => {
- return value === "emoji" || blockHintKeys.includes(splitChar) || (lite && ["/", "、"].includes(splitChar));
+export const shouldCaptureHintUndoFocus = (splitChar: string, blockHintKeys: string[], value = "") => {
+ return value === "emoji" || blockHintKeys.includes(splitChar) || ["/", "、"].includes(splitChar);
};
export const endsWithMultiCharHintPrefix = (key: string, hintKeys: string[]) => {
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 324c3ad62d..3742655605 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -931,7 +931,7 @@ ${genHintItemHTML(item)}
id = nodeElement.getAttribute("data-node-id");
}
const html = nodeElement.outerHTML;
- const undoContext = shouldCaptureHintUndoFocus(this.splitChar, Constants.BLOCK_HINT_KEYS, protyle.lite, value) ?
+ const undoContext = shouldCaptureHintUndoFocus(this.splitChar, Constants.BLOCK_HINT_KEYS, value) ?
getUndoFocusContext(protyle.wysiwyg.element, range, true) : undefined;
// 自顶向下法新建文档后光标定位问题 https://github.com/siyuan-note/siyuan/issues/299
if (this.lastIndex > -1) {
@@ -1058,13 +1058,13 @@ ${genHintItemHTML(item)}
range.deleteContents();
this.fixImageCursor(range);
protyle.toolbar.showTpl(protyle, nodeElement, range);
- updateTransaction(protyle, nodeElement, html);
+ updateTransaction(protyle, nodeElement, html, undoContext);
return;
} else if (value === Constants.ZWSP + 1) {
range.deleteContents();
this.fixImageCursor(range);
protyle.toolbar.showWidget(protyle, nodeElement, range);
- updateTransaction(protyle, nodeElement, html);
+ updateTransaction(protyle, nodeElement, html, undoContext);
return;
} else if (value === Constants.ZWSP + 2) {
range.deleteContents();
@@ -1072,7 +1072,7 @@ ${genHintItemHTML(item)}
protyle.toolbar.range = range;
const rangePosition = getSelectionPosition(nodeElement, range);
assetMenu(protyle, {x: rangePosition.left, y: rangePosition.top + 26, w: 0, h: 26});
- updateTransaction(protyle, nodeElement, html);
+ updateTransaction(protyle, nodeElement, html, undoContext);
return;
} else if (value === Constants.ZWSP + 3) {
range.deleteContents();
@@ -1128,7 +1128,7 @@ ${genHintItemHTML(item)}
range.deleteContents();
this.fixImageCursor(range);
nodeElement.setAttribute("style", value.split(Constants.ZWSP)[1] || "");
- updateTransaction(protyle, nodeElement, html);
+ updateTransaction(protyle, nodeElement, html, undoContext);
return;
} else if (value.startsWith("plugin") && areProtylePluginExtensionsEnabled(protyle)) {
protyle.app.plugins.find((plugin) => {
@@ -1163,7 +1163,7 @@ ${genHintItemHTML(item)}
nodeElement = nodeElement.nextElementSibling as HTMLElement;
nodeElement.previousElementSibling.remove();
focusByWbr(nodeElement, range);
- updateTransaction(protyle, nodeElement, html);
+ updateTransaction(protyle, nodeElement, html, undoContext);
let imgElement: HTMLElement = range.startContainer.childNodes[range.startOffset - 1] as HTMLElement || range.startContainer as HTMLElement;
if (imgElement && imgElement.nodeType !== 3 && imgElement.classList.contains("img")) {
// 已经找到图片
@@ -1218,7 +1218,7 @@ ${genHintItemHTML(item)}
item.style.minWidth = "60px";
});
}
- updateTransaction(protyle, nodeElement, html);
+ updateTransaction(protyle, nodeElement, html, undoContext);
} else {
// 保留空段落:原段落清空内容,新列表用 insert 操作
editableElement.textContent = "";
@@ -1234,7 +1234,8 @@ ${genHintItemHTML(item)}
}], [{
action: "update",
id: id,
- data: html
+ data: html,
+ context: undoContext,
}, {
action: "delete",
id: nodeElement.getAttribute("data-node-id")
@@ -1274,7 +1275,8 @@ ${genHintItemHTML(item)}
}], [{
action: "update",
id: id,
- data: html
+ data: html,
+ context: undoContext,
}, {
action: "delete",
id: newListId
@@ -1313,6 +1315,7 @@ ${genHintItemHTML(item)}
action: "delete"
}, {
data: html,
+ context: undoContext,
id,
action: "update"
}];
diff --git a/app/src/protyle/hint/slashUndo.test.ts b/app/src/protyle/hint/slashUndo.test.ts
new file mode 100644
index 0000000000..6cf4796fd3
--- /dev/null
+++ b/app/src/protyle/hint/slashUndo.test.ts
@@ -0,0 +1,69 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";
+import {shouldCaptureHintUndoFocus} from "./blockHintRange";
+
+const source = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest);
+const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");
+assert.ok(declaration && isClassDeclaration(declaration));
+const fill = declaration.members.find(member => member.name?.getText(source) === "fill").getText(source);
+
+for (const scenario of ["replace", "insert", "empty-list-item", "list-item"]) {
+ test(`slash undo retains the original caret for ${scenario}`, () => {
+ const inList = scenario.includes("list-item");
+ const empty = scenario === "replace" || scenario === "empty-list-item";
+ const originalHTML = "original command text";
+ const context = {undoFocusId: "original", undoFocusStart: "7", undoFocusEnd: "7"};
+ let mutated = false;
+ let saved: IOperation["context"];
+ const editable = {textContent: empty ? "" : "prefix"};
+ const old = {
+ outerHTML: originalHTML,
+ getAttribute: (name: string) => name === "data-type" ? "NodeParagraph" : "original",
+ setAttribute() {}, remove() {}, insertAdjacentHTML() {}, nextElementSibling: undefined as unknown,
+ };
+ const inserted = {
+ outerHTML: "inserted block",
+ getAttribute: (name: string) => name === "data-type" ? (inList ? "NodeList" : "NodeHeading") : "new-block",
+ classList: {contains: () => false}, previousElementSibling: old,
+ };
+ old.nextElementSibling = inserted;
+ const range = {startContainer: old, setStart() { mutated = true; }, deleteContents() { mutated = true; }};
+ const code = transpileModule(`class Hint { ${fill} } new Hint();`, {
+ compilerOptions: {target: ScriptTarget.ES2020},
+ }).outputText;
+ const hint = runInNewContext(code, {
+ Constants: {BLOCK_HINT_KEYS: ["(("], INLINE_TYPE: [], ZWSP: "\u200b"},
+ Lute: {Caret: "caret", NewNodeID: () => "new-block"},
+ Element: class {}, getSelection: (): null => null,
+ document: {createElement: () => ({innerHTML: "", firstElementChild: {
+ getAttribute: () => inList ? "NodeList" : "NodeHeading", setAttribute() {},
+ }})},
+ hideElements() {}, isProtyleListItemFragment: () => false,
+ hasClosestBlock: () => old, hasClosestByClassName: () => inList,
+ shouldCaptureHintUndoFocus,
+ getUndoFocusContext: () => { assert.equal(mutated, false); return context; },
+ getContenteditableElement: () => editable, getSuperBlockCommandLayout: (): undefined => undefined,
+ focusByRange() {}, focusByWbr() {},
+ updateTransaction: (_protyle: unknown, _element: unknown, html: string, undo: Record<string, string>) => {
+ assert.equal(html, originalHTML);
+ saved = undo;
+ },
+ transaction: (_protyle: unknown, _do: IOperation[], undo: IOperation[]) => {
+ const restore = undo.find(operation => operation.action === "update" && operation.id === "original");
+ assert.equal(restore.data, originalHTML);
+ saved = restore.context;
+ },
+ });
+ Object.assign(hint, {source: "hint", splitChar: "/", lastIndex: 6, fixImageCursor() {}});
+ hint.fill("# caret", {
+ toolbar: {range}, wysiwyg: {element: {querySelector: () => inserted}},
+ lute: {SpinBlockDOM: () => '<div data-node-id="20260929120000-abcdefg"></div>'},
+ }, false);
+ assert.equal(saved, context);
+ assert.equal(mutated, true);
+ });
+}