An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve cursor position restoration when undoing edits https://github.com/siyuan-note/siyuan/issues/19690
Daniel631ea64955a7
diff --git a/app/src/protyle/undo/index.ts b/app/src/protyle/undo/index.tsindex 4cbf1cc181..af68d0bfc9 100644--- a/app/src/protyle/undo/index.ts+++ b/app/src/protyle/undo/index.ts@@ -78,14 +78,13 @@ export class Undo implements IUndo {}}onTransaction(protyle, operations, true);- if (restoreUndoFocus(protyle, operations)) {- scrollCenter(protyle);- }+ restoreUndoFocus(protyle, operations);document.querySelector(".av__panel")?.remove();preventScroll(protyle);// 同步 toolbar range,避免 undo/redo 替换 DOM 后 range 变为 detached,// 导致后续异步操作(如 F3 创建子文档)读到无效 range 而报错 https://github.com/siyuan-note/siyuan/issues/17896syncToolbarRange(protyle);+ scrollCenter(protyle);}// add 降级为:不压栈(kernel 已在 commit 后 Record),仅置位本地镜像 + 刷新按钮态。diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.tsindex 09b3d359e0..264a3b2300 100644--- a/app/src/protyle/util/selection.ts+++ b/app/src/protyle/util/selection.ts@@ -654,6 +654,15 @@ Record<string, string> | undefined => {undoFocusEnd: end.toString(),undoFocusIgnoreZWSP: ignoreZWSP.toString(),};+ if (startBlockElement === endBlockElement && startBlockElement.getAttribute("data-type") === "NodeTable") {+ const cell = hasClosestByTag(range.startContainer, "TH") || hasClosestByTag(range.startContainer, "TD");+ if (cell && cell.contains(range.endContainer)) {+ context.undoFocusTableCell = Array.from(startBlockElement.querySelectorAll("th, td")).indexOf(cell).toString();+ const offset = getSelectionOffset(cell, undefined, range, ignoreZWSP);+ context.undoFocusStart = offset.start.toString();+ context.undoFocusEnd = offset.end.toString();+ }+ }if (startEditableElement.classList.contains("callout-title") &&endEditableElement.classList.contains("callout-title")) {context.undoFocusCalloutTitle = "true";@@ -709,16 +718,27 @@ export const restoreFocusContext = (protyle: IProtyle, context: Pick<IOperation[if (!cell || cell.classList.contains("fn__none")) {return false;}+ const cellRange = context.undoFocusTableSelection === undefined ?+ focusByOffset(cell, context.undoFocusCollapseToEnd === "true" ? end : start, end, false,+ context.undoFocusIgnoreZWSP === "true") : undefined;+ if (cellRange && cell.getAttribute("contenteditable") !== "false") {+ // 按单元格定位,避免空单元格与前一单元格末尾的文本偏移相同。+ focusByRange(cellRange);+ return true;+ }try {- const saved = JSON.parse(context.undoFocusTableSelection);- if (![saved.startIndex, saved.endIndex, saved.start, saved.end].every(value =>- Number.isInteger(value) && value >= 0) || typeof saved.backward !== "boolean") {+ const saved = context.undoFocusTableSelection === undefined ? undefined : JSON.parse(context.undoFocusTableSelection);+ if (context.undoFocusTableSelection !== undefined && (!saved ||+ ![saved.startIndex, saved.endIndex, saved.start, saved.end].every(value =>+ Number.isInteger(value) && value >= 0) || typeof saved.backward !== "boolean")) {return false;}// 单元格内部块没有持久 ID,使用单元格序号和片段内选区恢复编辑位置。- const range = document.createRange();- range.selectNodeContents(cell);- range.collapse(true);+ const range = cellRange || document.createRange();+ if (!cellRange) {+ range.selectNodeContents(cell);+ range.collapse(true);+ }cell.tabIndex = -1;cell.focus({preventScroll: true});focusByRange(range);diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.tsindex a9cf2cca5e..998cfb51d7 100644--- a/app/src/protyle/util/tableControl.ts+++ b/app/src/protyle/util/tableControl.ts@@ -5,7 +5,7 @@ import {updateTransaction} from "../wysiwyg/transaction";import {copyPlainText, encodeBase64, isMac, readClipboard} from "./compatibility";import {removeZWJ} from "./normalizeText";import {paste} from "./paste";-import {focusByRange, getEditorRange} from "./selection";+import {focusByRange, getEditorRange, getUndoFocusContext} from "./selection";import {matchHotKey} from "./hotKey";import {buildTableGrid,@@ -1983,8 +1983,23 @@ export class TableControl {return;}const oldHTML = this.selection.node.outerHTML;+ // 框选没有浏览器文本选区,使用活动单元格记录撤销和重做的光标位置。+ const getFocusContext = () => {+ const range = document.createRange();+ range.selectNodeContents(this.selection.activeCell);+ range.collapse(false);+ return getUndoFocusContext(this.wysiwygElement, range, true);+ };+ const undoContext = getFocusContext();this.getSelectedCells().forEach(clearTableCellContent);- updateTransaction(this.protyle, this.selection.node, oldHTML);+ if (oldHTML === this.selection.node.outerHTML) {+ return;+ }+ updateTransaction(this.protyle, this.selection.node, oldHTML, undoContext, {+ doOperations: [],+ undoOperations: [],+ context: getFocusContext(),+ });this.scheduleRender();}diff --git a/app/src/protyle/util/undoReplayFocus.test.ts b/app/src/protyle/util/undoReplayFocus.test.tsnew file mode 100644index 0000000000..7fc0112680--- /dev/null+++ b/app/src/protyle/util/undoReplayFocus.test.ts@@ -0,0 +1,264 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import test from "node:test";+import {promisify} from "node:util";+import {createSourceFile, isClassDeclaration, isVariableStatement, ScriptTarget, transpileModule} from "typescript";++const compile = (source: string) => transpileModule(source+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {+ compilerOptions: {target: ScriptTarget.ES2021},+}).outputText;++const extract = (file: string, names: string[]) => {+ const source = createSourceFile(file, readFileSync(path.join(__dirname, file), "utf8"), ScriptTarget.Latest, true);+ const declarations = source.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => names.includes(declaration.name.getText(source))));+ assert.equal(declarations.length, names.length);+ return compile(declarations.map(statement => statement.getText(source)).join("\n"));+};++const moduleSource = (file: string, names: string[]) => `const {${names.join(",")}} = (() => {+${compile(readFileSync(path.join(__dirname, file), "utf8"))}+return {${names.join(",")}};+})();`;++const browserCases = async (source: string) => {+ const check = require("node:assert/strict");+ const noop = (): void => undefined;+ const openedCells: {cell: HTMLTableCellElement, saved: unknown}[] = [];+ const highlightedCarets: Element[] = [];+ const transactions: {before: string, after: string, undoContext: Record<string, string>,+ context: Record<string, string>}[] = [];+ const dependencies = {+ Constants: {ZWSP: "\u200b"},+ revealTabsForTarget: (): void => undefined,+ captureBlockSelectionModeState: noop,+ disposeCustomBlocksInElement: noop,+ getVisibleFoldHeadingHTML: (html: string) => html,+ restoreBlockSelectionModeState: noop,+ focusRestoredBlockSelectionMode: noop,+ processRender: noop,+ avRender: noop,+ blockRender: noop,+ highlightRender: (element: Element) => {+ if (element.getAttribute("data-type") === "NodeCodeBlock" && element.querySelector("wbr")) {+ highlightedCarets.push(element);+ api.focusByWbr(element, document.createRange());+ }+ },+ loadRichCellEditor: async () => ({openTableCellRichEditor: (_owner: unknown, cell: HTMLTableCellElement,+ _navigation: unknown, _point: unknown, saved: unknown) => openedCells.push({cell, saved})}),+ updateTransaction: (_protyle: unknown, node: Element, before: string, undoContext: Record<string, string>,+ operations?: {context: Record<string, string>}) => {+ if (node.outerHTML === before && !operations) {+ return;+ }+ transactions.push({before, after: node.outerHTML, undoContext, context: operations?.context});+ },+ };+ const api = new Function(...Object.keys(dependencies), source.replace('import("../render/tableCellRichEditor")',+ "loadRichCellEditor()") ++ "return {TableCutControl, getUndoFocusContext, restoreUndoFocus, focusByRange, focusByWbr, updateBlock};")(...Object.values(dependencies));+ const editor = document.createElement("div");+ editor.className = "protyle-wysiwyg";+ editor.contentEditable = "true";+ document.body.append(editor);+ const protyle = {wysiwyg: {element: editor}, element: editor, contentElement: editor,+ scroll: {lastScrollTop: 0}, toolbar: {}};+ const focus = (element: Element) => {+ const range = document.createRange();+ range.selectNodeContents(element);+ range.collapse(false);+ api.focusByRange(range);+ return range;+ };+ const assertCaret = (cell: Element, offset: number) => {+ const selection = getSelection();+ check.ok(cell.contains(selection.focusNode), "caret must return to the operation's recorded location");+ const prefix = document.createRange();+ prefix.selectNodeContents(cell);+ prefix.setEnd(selection.focusNode, selection.focusOffset);+ check.equal(prefix.toString().length, offset);+ check.equal(selection.isCollapsed, true);+ };+ for (const activeHTML of ["two", "", "<strong>two</strong>"]) {+ editor.innerHTML = '<div data-node-id="table" data-type="NodeTable" class="table">' ++ '<div contenteditable="true"><table><thead><tr><th>head</th><th></th></tr></thead>' ++ "<tbody><tr><td>one</td><td>" + activeHTML + "</td></tr></tbody></table></div></div>" ++ '<div data-node-id="other" data-type="NodeParagraph"><div contenteditable="true">destination</div></div>';+ const node = editor.firstElementChild;+ const cells = Array.from(node.querySelectorAll("td"));+ const control = new api.TableCutControl();+ Object.assign(control, {+ protyle, wysiwygElement: editor, element: document.createElement("div"),+ abortController: new AbortController(), selectedCells: cells,+ selection: {node, mode: "cell", activeCell: cells[1]},+ scheduleRender: () => undefined, isRectangle: () => true,+ writeClipboard: () => true,+ });+ control.bindEvents();+ getSelection().removeAllRanges();+ const oldCount = transactions.length;+ const cut = new ClipboardEvent("cut", {bubbles: true, cancelable: true});+ editor.dispatchEvent(cut);+ check.equal(cut.defaultPrevented, true);+ check.equal(transactions.length, oldCount + 1);+ check.deepEqual(cells.map(cell => cell.textContent), ["", ""]);+ editor.dispatchEvent(new ClipboardEvent("cut", {bubbles: true, cancelable: true}));+ check.equal(transactions.length, oldCount + 1, "clearing empty cells must not add undo entries");+ control.abortController.abort();++ // 模拟粘贴及其撤销后,光标留在目标段落,再回放源表格的剪切事务。+ const pasted = node.cloneNode(true) as Element;+ pasted.setAttribute("data-node-id", "pasted");+ editor.append(pasted);+ focus(pasted.querySelector("td"));+ pasted.remove();+ focus(editor.querySelector('[data-node-id="other"] > div'));+ const operation = transactions[transactions.length - 1];+ node.outerHTML = operation.before;+ check.equal(api.restoreUndoFocus(protyle, [{context: operation.undoContext}]), true);+ assertCaret(editor.querySelectorAll("td")[1], activeHTML ? 3 : 0);++ // 重做清空后仍应定位到同一个空单元格,而非相邻单元格的末尾。+ focus(editor.querySelector('[data-node-id="other"] > div'));+ editor.firstElementChild.outerHTML = operation.after;+ check.equal(api.restoreUndoFocus(protyle, [{context: operation.context}]), true);+ assertCaret(editor.querySelectorAll("td")[1], 0);+ }+ editor.innerHTML = '<div data-node-id="paragraph" data-type="NodeParagraph"><div contenteditable="true">text</div></div>';+ const context = api.getUndoFocusContext(editor, focus(editor.firstElementChild.firstElementChild), true);+ check.equal(context.undoFocusTableCell, undefined);+ check.equal(api.restoreUndoFocus(protyle, [{context}]), true);+ assertCaret(editor.firstElementChild.firstElementChild, 4);++ editor.innerHTML = '<div data-node-id="rich" data-type="NodeTable" class="table">' ++ '<div contenteditable="true"><table><tbody><tr><td>before</td><td contenteditable="false">' ++ '<div data-type="NodeParagraph"><div contenteditable="false">first</div></div>' ++ '<div data-type="NodeParagraph"><div contenteditable="false">second</div></div>' ++ "</td></tr></tbody></table></div></div>";+ const richCell = editor.querySelectorAll("td")[1];+ const richContext = api.getUndoFocusContext(editor, focus(richCell), true);+ getSelection().removeAllRanges();+ check.equal(api.restoreUndoFocus(protyle, [{context: richContext}]), true);+ await Promise.resolve();+ check.equal(openedCells[0].cell, richCell, "rich cells must reopen the cell editor");+ check.equal(openedCells[0].saved, undefined);+ assertCaret(richCell, 11);+ const saved = {startIndex: 1, endIndex: 1, start: 2, end: 4, backward: true};+ check.equal(api.restoreUndoFocus(protyle, [{context: {...richContext,+ undoFocusTableSelection: JSON.stringify(saved)}}]), true);+ await Promise.resolve();+ check.deepEqual(openedCells[1].saved, saved, "existing rich text selections must be preserved");+ check.equal(api.restoreUndoFocus(protyle, [{context: {...richContext,+ undoFocusTableSelection: "null"}}]), false);++ const paragraph = (id: string, html: string) => `<div data-node-id="${id}" data-type="NodeParagraph">` ++ `<div contenteditable="true">${html}</div></div>`;+ const replay = (id: string, html: string, isUndo = true) => {+ api.updateBlock(Array.from(editor.querySelectorAll(`[data-node-id="${id}"]`)), protyle,+ {action: "update", id, data: html}, isUndo);+ check.equal(editor.querySelectorAll("wbr").length, 0);+ };+ editor.innerHTML = paragraph("a", "first12") + paragraph("b", "second34") + paragraph("c", "destination");+ focus(editor.lastElementChild.firstElementChild);+ for (const [id, html, offset] of [+ ["b", "second3<wbr>", 7], ["b", "second<wbr>", 6],+ ["a", "first1<wbr>", 6], ["a", "first<wbr>", 5],+ ["a", "first12<wbr>", 7], ["b", "second34<wbr>", 8],+ ] as const) {+ replay(id, paragraph(id, html));+ assertCaret(editor.querySelector(`[data-node-id="${id}"] > div`), offset);+ }+ getSelection().removeAllRanges();+ replay("a", paragraph("a", "fi<wbr>rst"));+ assertCaret(editor.firstElementChild.firstElementChild, 2);+ focus(editor.lastElementChild.firstElementChild);+ replay("a", paragraph("a", "sync<wbr>update"), false);+ assertCaret(editor.lastElementChild.firstElementChild, 11);+ replay("a", paragraph("a", "no caret"));+ assertCaret(editor.lastElementChild.firstElementChild, 11);++ // 嵌入副本按当前选区定位,光标在其他块时优先恢复源块,且只聚焦一次。+ editor.innerHTML = '<div data-node-id="embed" data-type="NodeBlockQueryEmbed">' + paragraph("a", "copy") ++ "</div>" + paragraph("a", "source") + paragraph("c", "destination");+ focus(editor.lastElementChild.firstElementChild);+ replay("a", paragraph("a", "ab<wbr>cd"));+ assertCaret(editor.children[1].firstElementChild, 2);+ focus(editor.firstElementChild.firstElementChild.firstElementChild);+ replay("a", paragraph("a", "abc<wbr>d"));+ assertCaret(editor.firstElementChild.firstElementChild.firstElementChild, 3);++ // 代码块重建高亮前必须保留目标副本的标记,其他副本不能抢走光标。+ const code = (html: string) => '<div data-node-id="code" data-type="NodeCodeBlock" class="code-block">' ++ '<div class="hljs"><div contenteditable="true">' + html + "</div></div></div>";+ editor.innerHTML = '<div data-node-id="embed" data-type="NodeBlockQueryEmbed">' + code("copy") ++ "</div>" + code("source") + paragraph("c", "destination");+ focus(editor.lastElementChild.firstElementChild);+ replay("code", code("ab<wbr>cd"));+ check.equal(highlightedCarets.length, 1);+ check.equal(highlightedCarets[0], editor.children[1]);+ assertCaret(editor.children[1].querySelector("[contenteditable]"), 2);+ editor.remove();+ return "Undo replay focus cases passed";+};++test("undo replay restores recorded carets across paragraphs, table cells and embedded copies", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const tableSource = createSourceFile("tableControl.ts", readFileSync(path.join(__dirname,+ "tableControl.ts"), "utf8"), ScriptTarget.Latest, true);+ const tableClass = tableSource.statements.find(isClassDeclaration);+ const methodNames = ["bindEvents", "deleteSelection", "clearCells", "canMutateSelection", "getSelectedCells"];+ const methods = tableClass.members.filter(member => methodNames.includes(member.name?.getText(tableSource)));+ assert.equal(methods.length, methodNames.length);+ const source = compile(`class TableCutControl {${methods.map(method => method.getText(tableSource)).join("\n")}}`) ++ extract("tableCellRich.ts", ["clearTableCellContent"]) ++ compile(readFileSync(path.join(__dirname, "hasClosest.ts"), "utf8")) ++ moduleSource("inlineElementBoundary.ts", ["getInlineElementBoundaryOffset", "getTextWithLegacyInlineBoundary",+ "hasInlineElementBoundary", "normalizeInlineElementBoundary", "restoreInlineElementBoundary",+ "restoreInlineElementBoundaries", "SEMANTIC_INLINE_HTML_REGEXP"]) ++ moduleSource("inlineElementMarker.ts", ["stripSemanticMarkersFromRangeText", "getMarkerAwareTextLength",+ "getSemanticMarkerPrefixLengthForNode"]) ++ extract("tableCellRichValue.ts", ["TABLE_CELL_RICH_ATTRIBUTE"]) ++ extract("selectionFocus.ts", ["getUndoFocusElement"]) ++ extract("../wysiwyg/getBlock.ts", ["getContenteditableElement", "isEndOfBlock", "hasNextSibling",+ "isNotEditBlock", "isContainerBlock", "hasPreviousSibling"]) ++ extract("../wysiwyg/transaction.ts", ["updateBlock"]) ++ extract("../wysiwyg/transactionUpdate.ts", ["shouldDeferCodeBlockCaretRestore"]) ++ extract("selection.ts", ["getSelectionOffset", "getUndoFocusContext", "restoreFocusContext", "restoreUndoFocus",+ "focusByOffset", "focusByRange", "focusByWbr", "searchNode", "getDOMOffset", "setLastNodeRange"]);+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-cut-undo-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("about:blank");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(+ `const __name = value => value; (async () => {try {return await (${browserCases.toString()})(${JSON.stringify(source)});}+catch (error) {return error.stack;}})()`)}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Undo replay focus cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 4a8dae602e..cfb3450f11 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -746,6 +746,9 @@ const deleteBlock = (updateElements: Element[], id: string, protyle: IProtyle, iconst updateBlock = (updateElements: Element[], protyle: IProtyle, operation: Extract<IOperation, {action: "update"}>, isUndo: boolean) => {const range = getSelection().rangeCount > 0 ? getSelection().getRangeAt(0) : null;+ // 撤销按快照中的光标返回操作块;同 ID 副本优先使用当前选区所在的实例,其次使用源块。+ const focusElement = isUndo ? updateElements.find(item => range && item.contains(range.startContainer)) ||+ updateElements.find(item => !isInEmbedBlock(item, false)) || updateElements[0] : undefined;updateElements.forEach(item => {// 前序局部回放可能已替换包含该块的祖先,跳过失效引用。if (!item.parentElement) {@@ -755,6 +758,7 @@ const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: Exif (range && item.contains(range.startContainer)) {isRangeBlock = true;}+ const isFocusBlock = item === focusElement;// 表格的横向、纵向滚动均发生在首个子节点(contenteditable 容器,overflow:auto)上,// 更新块后需一并还原,否则固定表头长表格撤销/重做会跳回开头// https://github.com/siyuan-note/siyuan/issues/3650 https://github.com/siyuan-note/siyuan/issues/18035@@ -782,17 +786,18 @@ const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: Exconst wbrElement = item.querySelector("wbr");const codeElement = item.getAttribute("data-type") === "NodeCodeBlock" ? item.querySelector(".hljs") : undefined;+ const restoreCaret = isFocusBlock && !!wbrElement;// 未高亮的代码块由 highlightRender 使用 wbr 记录偏移,并在重建 DOM 后恢复光标。const deferCodeBlockCaretRestore = shouldDeferCodeBlockCaretRestore({- isRangeBlock,+ isRangeBlock: restoreCaret,isReplay: isUndo,hasCaret: !!wbrElement,isCodeBlock: !!codeElement,isRendered: codeElement?.getAttribute("data-render") === "true",});- if (isRangeBlock && isUndo) {+ if (isUndo && (restoreCaret || isRangeBlock)) {if (wbrElement) {- focusByWbr(item, range, deferCodeBlockCaretRestore);+ focusByWbr(item, range || document.createRange(), deferCodeBlockCaretRestore);} else {focusBlock(item);}