Skip to content

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

:bug: Preserve clicked caret positions when opening table cell editors https://github.com/siyuan-note/siyuan/issues/19717

Danielf00b5963115d
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.ts
index 8294c186f8..6eec3bb228 100644
--- a/app/src/protyle/render/tableCellRichEditor.ts
+++ b/app/src/protyle/render/tableCellRichEditor.ts
@@ -19,7 +19,7 @@ import {focusEditableAtGoalX, getCaretGoalX} from "../wysiwyg/verticalCaret";
import {fixTable} from "../util/table";
import {updateTableCellContentLayout} from "../util/tableCellRich";
import {TABLE_CELL_SLASH_IDS} from "../util/tableCellRichMenu";
-import {captureRichCellSelection, restoreRichCellSelection} from "../util/tableCellRichSelection";
+import {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection} from "../util/tableCellRichSelection";
import {matchHotKey} from "../util/hotKey";
import {bindTableCellRichDrag} from "../util/tableCellRichDrag";
import {getTableCellEditorLute} from "../util/tableCellRichLute";
@@ -116,6 +116,8 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
const richSelection = cell.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE) ? captureRichCellSelection(cell, selection) : undefined;
const preserveSelection = initialRange && !initialRange.collapsed &&
cell.contains(initialRange.startContainer) && cell.contains(initialRange.endContainer);
+ // 在预览布局中记录点击位置,避免编辑器重建及行号留白变化影响坐标定位。
+ const clickedSelection = point && !preserveSelection ? captureRichCellSelectionAtPoint(cell, point) : undefined;
const initialOffset = !cell.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE) && initialRange &&
cell.contains(initialRange.startContainer) && cell.contains(initialRange.endContainer) ?
getSelectionOffset(cell, owner.wysiwyg.element, initialRange) : undefined;
@@ -508,6 +510,9 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
}
return;
}
+ if (clickedSelection && restoreRichCellSelection(fragment.wysiwyg, clickedSelection)) {
+ return;
+ }
if (richSelection && (preserveSelection || !point) && restoreRichCellSelection(fragment.wysiwyg, richSelection)) {
if (preserveSelection) {
fragment.protyle.toolbar.render(fragment.protyle, getSelection().getRangeAt(0));
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index aad99f53de..8644003c62 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -285,7 +285,7 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
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};")(
+ "\nreturn {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection, focusByOffset, getSelectionOffset};")(
...Object.values(selectionDependencies)) as typeof import("./tableCellRichSelection") & typeof import("./selection");
const renderDependencies = {
...selectionAPI, Constants: {PROTYLE_CDN: ""}, setCodeTheme: () => {}, addScript: () => Promise.resolve(),
@@ -342,6 +342,30 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
check.equal(selectionAPI.captureRichCellSelection(wysiwyg, getSelection()).start, 7,
"first-click caret survives the initial asynchronous code highlight");
}
+ for (const offset of [2, 6, body.indexOf("123555555") + 4]) {
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(savedCell);
+ render(wysiwyg);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ const previewCode = wysiwyg.querySelector<HTMLElement>('.hljs > [contenteditable="true"]');
+ previewCode.style.cssText = "white-space: pre; font: 16px monospace; padding-left: 40px;";
+ wysiwyg.querySelectorAll<HTMLElement>("[contenteditable]").forEach(element => element.contentEditable = "false");
+ const previewRange = selectionAPI.focusByOffset(previewCode, offset, offset, false);
+ check.ok(previewRange);
+ const rect = previewRange.getBoundingClientRect();
+ const point = {x: rect.left + 0.1, y: rect.top + rect.height / 2};
+ const clicked = selectionAPI.captureRichCellSelectionAtPoint(wysiwyg, point);
+ check.equal(clicked?.start, offset, "hit-test uses the visible preview text");
+ check.equal(clicked.startIndex, 1);
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(savedCell);
+ const editingCode = wysiwyg.querySelector<HTMLElement>('.hljs > [contenteditable="true"]');
+ editingCode.style.cssText = "white-space: pre; font: 16px monospace; padding-left: 0;";
+ check.notEqual(selectionAPI.captureRichCellSelectionAtPoint(wysiwyg, point)?.start, offset,
+ "the same screen coordinate points elsewhere before the line number gutter is rendered");
+ render(wysiwyg);
+ check.equal(selectionAPI.restoreRichCellSelection(wysiwyg, clicked), true);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ check.deepEqual(selectionAPI.captureRichCellSelection(wysiwyg, getSelection()), clicked);
+ }
fixture.remove();
return "Table cell code insertion cases passed";
};
diff --git a/app/src/protyle/util/tableCellRichSelection.ts b/app/src/protyle/util/tableCellRichSelection.ts
index a2aaa25dd3..1d4c7b0efd 100644
--- a/app/src/protyle/util/tableCellRichSelection.ts
+++ b/app/src/protyle/util/tableCellRichSelection.ts
@@ -5,18 +5,7 @@ const getCellEditables = (root: Element) => Array.from(root.querySelectorAll<HTM
'[data-type="NodeHeading"] > [contenteditable]:not(.protyle-attr), ' +
'[data-type="NodeCodeBlock"] .hljs > [contenteditable]:last-child'));
-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 = marker ? document.createRange() : selection.getRangeAt(0);
- if (marker) {
- range.setStartBefore(marker);
- range.collapse(true);
- }
+const captureRichCellRange = (editables: HTMLElement[], range: Range, backward = false) => {
const startIndex = editables.findIndex(edit => edit.contains(range.startContainer));
const endIndex = editables.findIndex(edit => edit.contains(range.endContainer));
if (startIndex < 0 || endIndex < 0) {
@@ -30,10 +19,31 @@ export const captureRichCellSelection = (cell: Element, selection: Selection, us
startIndex, endIndex,
start: getSelectionOffset(editables[startIndex], undefined, startRange).start,
end: getSelectionOffset(editables[endIndex], undefined, endRange).start,
- backward: !range.collapsed && selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset,
+ backward,
};
};
+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 = marker ? document.createRange() : selection.getRangeAt(0);
+ if (marker) {
+ range.setStartBefore(marker);
+ range.collapse(true);
+ }
+ return captureRichCellRange(editables, range, !range.collapsed &&
+ selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset);
+};
+
+export const captureRichCellSelectionAtPoint = (cell: Element, point: {x: number, y: number}) => {
+ const range = document.caretRangeFromPoint(point.x, point.y);
+ return range ? captureRichCellRange(getCellEditables(cell), range) : undefined;
+};
+
export const restoreRichCellSelection = (root: Element, saved: ReturnType<typeof captureRichCellSelection>) => {
if (!saved) {
return false;