Skip to content

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

:bug: Preserve table cell code caret positions and exclude temporary markers https://github.com/siyuan-note/siyuan/issues/19717

Daniel9ef3dfd1ab26
diff --git a/app/src/protyle/render/highlightRender.ts b/app/src/protyle/render/highlightRender.ts
index 2da40b7fe5..b4543fea08 100644
--- a/app/src/protyle/render/highlightRender.ts
+++ b/app/src/protyle/render/highlightRender.ts
@@ -1,6 +1,6 @@
import {addScript} from "../util/addScript";
import {Constants} from "../../constants";
-import {focusByOffset} from "../util/selection";
+import {focusByOffset, getSelectionOffset} from "../util/selection";
import {setCodeTheme} from "./util";
import {escapeHtml} from "../../util/escape";
@@ -44,6 +44,15 @@ export const highlightRender = (element: Element, cdn = Constants.PROTYLE_CDN, z
iconElements[1].setAttribute("aria-label", window.siyuan.languages.more);
}
const wbrElement = block.querySelector("wbr");
+ const editable = block.querySelector<HTMLElement>('[contenteditable="true"]');
+ const selection = getSelection();
+ // 高亮会重建文本节点,需保留已恢复到代码正文中的选区。
+ const codeRange = !wbrElement && editable && selection.rangeCount &&
+ editable.contains(selection.anchorNode) && editable.contains(selection.focusNode) ?
+ selection.getRangeAt(0) : undefined;
+ const codeSelection = codeRange ? getSelectionOffset(editable, undefined, codeRange) : undefined;
+ const backward = codeRange && !codeRange.collapsed && selection.anchorNode === codeRange.endContainer &&
+ selection.anchorOffset === codeRange.endOffset;
let startIndex = 0;
if (wbrElement) {
let previousSibling = wbrElement.previousSibling;
@@ -111,6 +120,11 @@ export const highlightRender = (element: Element, cdn = Constants.PROTYLE_CDN, z
}).value;
if (wbrElement && getSelection().rangeCount > 0) {
focusByOffset(block, startIndex, startIndex);
+ } else if (codeSelection) {
+ const range = focusByOffset(editable, codeSelection.start, codeSelection.end);
+ if (backward && range) {
+ selection.setBaseAndExtent(range.endContainer, range.endOffset, range.startContainer, range.startOffset);
+ }
}
});
});
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.ts
index 87279b5489..8294c186f8 100644
--- a/app/src/protyle/render/tableCellRichEditor.ts
+++ b/app/src/protyle/render/tableCellRichEditor.ts
@@ -210,7 +210,7 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
return;
}
const oldHTML = cleanTableCellRichHTML(table.outerHTML);
- const redoSelection = captureRichCellSelection(fragment.wysiwyg, getSelection()) || undoSelection;
+ const redoSelection = captureRichCellSelection(fragment.wysiwyg, getSelection(), true) || undoSelection;
const tableRange = document.createRange();
tableRange.selectNodeContents(cell);
tableRange.collapse(true);
diff --git a/app/src/protyle/util/tableCellRich.ts b/app/src/protyle/util/tableCellRich.ts
index fb097aff43..805899238d 100644
--- a/app/src/protyle/util/tableCellRich.ts
+++ b/app/src/protyle/util/tableCellRich.ts
@@ -82,6 +82,8 @@ export const getTableCellRichBlockDOM = (cell: Element) => {
export const serializeTableCellRich = (blockDOM: string) => {
const template = document.createElement("template");
template.innerHTML = sanitizeAVRichTextBlockDOM(blockDOM, true);
+ // 光标由事务选区单独记录,不能将临时定位节点序列化为正文。
+ template.content.querySelectorAll("wbr").forEach(marker => marker.remove());
let prefix = "SYTABLECELLWHITESPACE";
while (template.innerHTML.includes(prefix)) {
prefix += "X";
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index 6c30993613..aad99f53de 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -7,7 +7,8 @@ import {test} from "node:test";
import {promisify} from "node:util";
import {createSourceFile, isClassDeclaration, isMethodDeclaration, ScriptTarget, transpileModule} from "typescript";
-const browserCases = async (source: string, enterSource: string, hintSource: string, keydownSource: string, copySource: string) => {
+const browserCases = async (source: string, enterSource: string, hintSource: string, keydownSource: string,
+ copySource: string, selectionSource: string, highlightSource: string) => {
const check: typeof assert = require("node:assert/strict");
const api = new Function(source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +
"canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +
@@ -282,6 +283,65 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
copyController.abort();
wysiwyg.querySelector(".protyle-action__copy").dispatchEvent(new MouseEvent("click", {bubbles: true}));
check.equal(copied.length, 6, "closing the editor removes the copy handler");
+ const selectionDependencies = {getContenteditableElement, isNotEditBlock: () => false, revealTabsForTarget: () => {}};
+ const selectionAPI = new Function(...Object.keys(selectionDependencies), selectionSource +
+ "\nreturn {captureRichCellSelection, restoreRichCellSelection, focusByOffset, getSelectionOffset};")(
+ ...Object.values(selectionDependencies)) as typeof import("./tableCellRichSelection") & typeof import("./selection");
+ const renderDependencies = {
+ ...selectionAPI, Constants: {PROTYLE_CDN: ""}, setCodeTheme: () => {}, addScript: () => Promise.resolve(),
+ };
+ const render = new Function(...Object.keys(renderDependencies), highlightSource + "\nreturn highlightRender;")(
+ ...Object.values(renderDependencies)) as typeof import("../render/highlightRender").highlightRender;
+ Object.assign(window, {hljs: {
+ getLanguage: () => true,
+ highlight: (text: string) => {
+ const span = document.createElement("span");
+ span.textContent = text;
+ return {value: span.outerHTML};
+ },
+ }});
+ const body = "4441231234444\n\n\n123555555\n22\n\n123\n";
+ wysiwyg.innerHTML = base.Md2BlockDOM("sdf\n\n```java\n" + body + "```");
+ const codeEdit = wysiwyg.querySelector<HTMLElement>('.hljs [contenteditable="true"]');
+ selectionAPI.focusByOffset(codeEdit, 23, 23);
+ const beforeEdit = selectionAPI.captureRichCellSelection(wysiwyg, getSelection());
+ check.equal(beforeEdit.startIndex, 1, "the line number gutter is not an editable block");
+ const marker = document.createElement("wbr");
+ const markerRange = selectionAPI.focusByOffset(codeEdit, 24, 24, false);
+ check.ok(markerRange);
+ markerRange.insertNode(marker);
+ selectionAPI.focusByOffset(codeEdit, 0, 0);
+ const pending = selectionAPI.captureRichCellSelection(wysiwyg, getSelection(), true);
+ check.equal(pending.start, 24, "pending highlight uses the caret marker instead of the stale DOM selection");
+ const serialized = api.serializeTableCellRich(wysiwyg.innerHTML);
+ check.ok(!serialized.markdown.includes(Lute.Caret), "temporary caret must not enter stored cell content");
+ check.ok(wysiwyg.contains(marker), "serialization leaves the live caret intact");
+ const savedCell = document.createElement("td");
+ api.updateTableCellEditingValue(savedCell, serialized);
+ for (const lineNumbers of [false, true]) {
+ window.siyuan.config.editor.codeSyntaxHighlightLineNum = lineNumbers;
+ window.siyuan.config.editor.fontSize = 16;
+ for (const saved of [beforeEdit, pending, {...beforeEdit, end: 28, backward: true}]) {
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(savedCell);
+ render(wysiwyg);
+ check.equal(selectionAPI.restoreRichCellSelection(wysiwyg, saved), true);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ check.deepEqual(selectionAPI.captureRichCellSelection(wysiwyg, getSelection()), saved,
+ "asynchronous highlighting preserves the restored undo or redo selection");
+ check.equal(wysiwyg.querySelector('.hljs [contenteditable="true"]').textContent, body);
+ }
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(savedCell);
+ render(wysiwyg);
+ const clickedCode = wysiwyg.querySelector<HTMLElement>('.hljs [contenteditable="true"]');
+ const clickRange = document.createRange();
+ clickRange.setStart(clickedCode.firstChild, 7);
+ clickRange.collapse(true);
+ getSelection().removeAllRanges();
+ getSelection().addRange(clickRange);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ check.equal(selectionAPI.captureRichCellSelection(wysiwyg, getSelection()).start, 7,
+ "first-click caret survives the initial asynchronous code highlight");
+ }
fixture.remove();
return "Table cell code insertion cases passed";
};
@@ -309,6 +369,8 @@ test("table cells insert code through slash and Enter without losing soft breaks
const copyStart = editor.indexOf('host.addEventListener("click", event => {');
const copyEnd = editor.indexOf("}, {capture: true, signal});", copyStart) + "}, {capture: true, signal});".length;
const copySource = compile(read("normalizeText.ts") + "\n" + editor.substring(copyStart, copyEnd));
+ const selectionSource = compile(read("selection.ts")) + "\n" + compile(read("tableCellRichSelection.ts"));
+ const highlightSource = compile(read("../render/highlightRender.ts"));
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-table-cell-code-test-"));
const script = path.join(temporary, "run.cjs");
const lutePath = path.resolve(__dirname, "../../../stage/protyle/js/lute/lute.min.js");
@@ -321,7 +383,8 @@ app.whenReady().then(async () => {
await win.loadURL("data:text/html,<html><body></body></html>");
await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));
const result = await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" +
- browserCases.toString() + ")(" + [source, compile(read("../wysiwyg/enter.ts")), hintSource, keydownSource, copySource]
+ browserCases.toString() + ")(" + [source, compile(read("../wysiwyg/enter.ts")), hintSource, keydownSource, copySource,
+ selectionSource, highlightSource]
.map(value => JSON.stringify(value)).join(",") + ")")});
console.log(result);
win.destroy();
diff --git a/app/src/protyle/util/tableCellRichSelection.ts b/app/src/protyle/util/tableCellRichSelection.ts
index 609bd856cf..a2aaa25dd3 100644
--- a/app/src/protyle/util/tableCellRichSelection.ts
+++ b/app/src/protyle/util/tableCellRichSelection.ts
@@ -1,15 +1,22 @@
import {focusByOffset, focusByRange, getSelectionOffset} from "./selection";
const getCellEditables = (root: Element) => Array.from(root.querySelectorAll<HTMLElement>(
- '[data-type="NodeParagraph"] > [contenteditable], [data-type="NodeHeading"] > [contenteditable], ' +
- '[data-type="NodeCodeBlock"] .hljs > [contenteditable]'));
+ '[data-type="NodeParagraph"] > [contenteditable]:not(.protyle-attr), ' +
+ '[data-type="NodeHeading"] > [contenteditable]:not(.protyle-attr), ' +
+ '[data-type="NodeCodeBlock"] .hljs > [contenteditable]:last-child'));
-export const captureRichCellSelection = (cell: Element, selection: Selection) => {
- if (!selection.rangeCount) {
+export const captureRichCellSelection = (cell: Element, selection: Selection, useCaret = false) => {
+ const editables = getCellEditables(cell);
+ // 代码高亮异步恢复选区时,临时定位节点才是编辑完成后的光标位置。
+ const marker = useCaret ? editables.map(edit => edit.querySelector("wbr")).find(item => !!item) : undefined;
+ if (!marker && !selection.rangeCount) {
return;
}
- const range = selection.getRangeAt(0);
- const editables = getCellEditables(cell);
+ const range = marker ? document.createRange() : selection.getRangeAt(0);
+ if (marker) {
+ range.setStartBefore(marker);
+ range.collapse(true);
+ }
const startIndex = editables.findIndex(edit => edit.contains(range.startContainer));
const endIndex = editables.findIndex(edit => edit.contains(range.endContainer));
if (startIndex < 0 || endIndex < 0) {