Skip to content

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

:bug: Preserve vertical caret lines and scroll reachability https://github.com/siyuan-note/siyuan/issues/19184

Daniel7248c3061184
diff --git a/app/scripts/verticalNavigation.test.js b/app/scripts/verticalNavigation.test.js
new file mode 100644
index 0000000000..e4a79a7fa6
--- /dev/null
+++ b/app/scripts/verticalNavigation.test.js
@@ -0,0 +1,302 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const rendererModules = () => {
+ const ts = require("typescript");
+ const root = path.join(__dirname, "../src/protyle");
+ const modules = {};
+ for (const name of ["verticalGeometry", "verticalVisibility", "verticalCaret"]) {
+ modules[`./${name}`] = readFileSync(path.join(root, "wysiwyg", `${name}.ts`), "utf8");
+ }
+ // 使用实际选区函数;这些几何用例不挂载页签控制器。
+ const selection = ts.createSourceFile("selection.ts",
+ readFileSync(path.join(root, "util/selection.ts"), "utf8"), ts.ScriptTarget.Latest, true);
+ const names = ["setFirstNodeRange", "setLastNodeRange", "focusByRange"];
+ modules["../util/selection"] = "const revealTabsForTarget = () => {};\n" + selection.statements.filter(statement =>
+ ts.isVariableStatement(statement) && statement.declarationList.declarations.some(declaration =>
+ names.includes(declaration.name.getText(selection)))).map(statement => statement.getText(selection)).join("\n");
+ return Object.fromEntries(Object.entries(modules).map(([name, source]) => [name,
+ ts.transpileModule(source, {compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2020,
+ }}).outputText]));
+};
+
+const runGeometryCases = async () => {
+ const assert = require("node:assert/strict");
+ const {ipcRenderer} = require("electron");
+ const {focusEditableAtGoalX, isCaretAtVerticalBoundary, getCaretGoalX} = window.verticalCaret;
+ const {getReachableVerticalRects} = window.verticalVisibility;
+ const select = (node, offset) => {
+ const range = document.createRange();
+ range.setStart(node, offset);
+ range.collapse(true);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ return range;
+ };
+ const setup = (text, whiteSpace = "pre", height = 320) => {
+ document.body.innerHTML = `<div class="layout" style="height:${height}px;width:500px;overflow:hidden">
+ <div class="protyle-content" style="height:100%;overflow:auto">
+ <div class="protyle-wysiwyg" contenteditable="true" style="font:20px/30px monospace">
+ <div data-node-id="before"><div id="before">before</div></div>
+ <div data-node-id="code" class="code-block"><div class="hljs" style="overflow:auto;max-height:140px">
+ <div id="code" contenteditable="true" style="white-space:${whiteSpace};min-height:30px"></div>
+ </div></div>
+ <div data-node-id="after"><div id="after">after</div></div>
+ </div>
+ </div>
+ </div>`;
+ const code = document.getElementById("code");
+ code.textContent = text;
+ const content = document.querySelector(".protyle-content");
+ const editor = document.querySelector(".protyle-wysiwyg");
+ const before = document.getElementById("before");
+ const after = document.getElementById("after");
+ editor.addEventListener("keydown", event => {
+ if (!["ArrowUp", "ArrowDown"].includes(event.key)) {
+ return;
+ }
+ const range = getSelection().getRangeAt(0);
+ const source = [before, code, after].find(element => element.contains(range.startContainer));
+ const direction = event.key === "ArrowUp" ? "up" : "down";
+ if (!source || !isCaretAtVerticalBoundary(source, range, direction)) {
+ return;
+ }
+ const index = [before, code, after].indexOf(source) + (direction === "up" ? -1 : 1);
+ const target = [before, code, after][index];
+ if (target) {
+ focusEditableAtGoalX(target, direction, getCaretGoalX(range), content);
+ event.preventDefault();
+ }
+ });
+ editor.focus();
+ select(after.firstChild, 0);
+ return {code, content, before, after, scroller: code.parentElement};
+ };
+ const press = key => ipcRenderer.invoke("vertical-navigation-key", key);
+ let cases = 0;
+ for (const whiteSpace of ["pre", "pre-wrap"]) {
+ for (const text of ["\na\n", "a\nb\n\nc\n", "x\n\n", "\n", "\n\n\n"]) {
+ const {code, content} = setup(text, whiteSpace);
+ const starts = [0];
+ for (let offset = 0; offset < text.length - 1; offset++) {
+ if (text[offset] === "\n") {
+ starts.push(offset + 1);
+ }
+ }
+ for (const [index, offset] of starts.entries()) {
+ const range = select(code.firstChild, offset);
+ assert.equal(isCaretAtVerticalBoundary(code, range, "up"), index === 0,
+ `${whiteSpace} ${JSON.stringify(text)} offset ${offset} up`);
+ assert.equal(isCaretAtVerticalBoundary(code, range, "down"), index === starts.length - 1,
+ `${whiteSpace} ${JSON.stringify(text)} offset ${offset} down`);
+ }
+ for (const direction of ["up", "down"]) {
+ assert.equal(focusEditableAtGoalX(code, direction, 40, content), true, `enter ${JSON.stringify(text)}`);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0),
+ direction === "up" ? "down" : "up"), true);
+ assert.ok(getSelection().anchorOffset < text.length);
+ }
+ cases++;
+ }
+ const {code, before, after} = setup("x\n\n", whiteSpace);
+ await press("Up");
+ assert.equal(getSelection().anchorNode, code.firstChild, `first up ${whiteSpace}`);
+ assert.equal(getSelection().anchorOffset, 2);
+ await press("Up");
+ assert.equal(getSelection().anchorNode, code.firstChild,
+ `second up ${whiteSpace}: ${getSelection().anchorNode.parentElement.outerHTML}, ${getSelection().anchorOffset}`);
+ assert.ok(getSelection().anchorOffset <= 1);
+ await press("Up");
+ assert.equal(getSelection().anchorNode, before.firstChild, `third up ${whiteSpace}`);
+ await press("Down");
+ await press("Down");
+ assert.equal(getSelection().anchorNode, code.firstChild);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0), "down"), true);
+ await press("Down");
+ assert.equal(getSelection().anchorNode, after.firstChild);
+ cases++;
+ }
+ for (const whiteSpace of ["pre", "pre-wrap"]) {
+ for (const markup of ["<span>a\nb\n</span><span>\nc\n</span>", "<span>a\nb\n\nc</span>\n"]) {
+ const {code, content} = setup("", whiteSpace);
+ code.innerHTML = markup;
+ const walker = document.createTreeWalker(code, NodeFilter.SHOW_TEXT);
+ let offset = 4;
+ let node = walker.nextNode();
+ while (node && offset > node.textContent.length) {
+ offset -= node.textContent.length;
+ node = walker.nextNode();
+ }
+ const range = select(node, offset);
+ assert.equal(isCaretAtVerticalBoundary(code, range, "up"), false, markup);
+ assert.equal(isCaretAtVerticalBoundary(code, range, "down"), false, markup);
+ assert.equal(focusEditableAtGoalX(code, "up", 40, content), true);
+ cases++;
+ }
+ const {code, content} = setup("", whiteSpace);
+ code.innerHTML = "<span>x\n</span><span>\n</span>";
+ const range = select(code.firstChild.firstChild, 2);
+ assert.equal(isCaretAtVerticalBoundary(code, range, "up"), false);
+ assert.equal(isCaretAtVerticalBoundary(code, range, "down"), true);
+ assert.equal(focusEditableAtGoalX(code, "up", 40, content), true);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0), "up"), false);
+ cases++;
+ }
+ for (const height of [180, 320]) {
+ for (const direction of ["up", "down"]) {
+ const {code, content, scroller} = setup(Array.from({length: 30}, (_, i) => `line ${i}`).join("\n") + "\n",
+ "pre", height);
+ scroller.scrollTop = direction === "down" ? scroller.scrollHeight : 0;
+ content.scrollTop = direction === "down" ? content.scrollHeight : 0;
+ assert.equal(focusEditableAtGoalX(code, direction, 40, content), true, `nested scroll ${height} ${direction}`);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0),
+ direction === "up" ? "down" : "up"), true);
+ assert.ok(direction === "up" ? scroller.scrollTop > 0 : scroller.scrollTop < 30);
+ cases++;
+ }
+ }
+ for (const font of ["14px/23px monospace", "28px/46px monospace"]) {
+ const {code, content, scroller} = setup(`${"wrapped ".repeat(30)}\n\n`, "pre-wrap");
+ code.style.font = font;
+ const goalX = scroller.getBoundingClientRect().right - 25;
+ assert.equal(focusEditableAtGoalX(code, "down", goalX, content), true);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0), "up"), true);
+ const contentRange = document.createRange();
+ contentRange.selectNodeContents(code);
+ const firstLine = contentRange.getClientRects()[0];
+ const expectedX = Math.max(firstLine.left, Math.min(goalX, firstLine.right));
+ assert.ok(Math.abs(getSelection().getRangeAt(0).getBoundingClientRect().left - expectedX) < parseFloat(font),
+ `${font}: goal ${goalX}, caret ${getSelection().getRangeAt(0).getBoundingClientRect().left}, offset ${getSelection().anchorOffset}`);
+ assert.equal(focusEditableAtGoalX(code, "up", goalX, content), true);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0), "up"), false);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0), "down"), true);
+ cases++;
+ }
+ {
+ const {code, content} = setup("");
+ for (const direction of ["up", "down"]) {
+ assert.equal(focusEditableAtGoalX(code, direction, 40, content), true);
+ assert.equal(isCaretAtVerticalBoundary(code, getSelection().getRangeAt(0), direction), true);
+ }
+ assert.equal(code.innerHTML, "");
+ cases++;
+ }
+ for (const direction of ["up", "down"]) {
+ const text = direction === "down" ? `x\n${"long".repeat(200)}\n` : `${"long".repeat(200)}\nx\n`;
+ const {code, content, scroller} = setup(text);
+ scroller.scrollLeft = 1000;
+ assert.equal(focusEditableAtGoalX(code, direction, 40, content), true, `horizontal scroll ${direction}`);
+ assert.equal(scroller.scrollLeft, 0);
+ cases++;
+ }
+ {
+ const {code, content, scroller} = setup(`${"long".repeat(200)}\nlast\n`);
+ scroller.scrollLeft = 1000;
+ assert.equal(focusEditableAtGoalX(code, "down", 100, content), true);
+ assert.equal(scroller.scrollLeft, 1000);
+ assert.ok(Math.abs(getSelection().getRangeAt(0).getBoundingClientRect().left - 100) < 10);
+ cases++;
+ }
+ for (const style of ["display:none", "visibility:hidden", "height:0;overflow:hidden", "height:0;overflow:clip"]) {
+ const {code, content, after} = setup("hidden\n");
+ code.parentElement.setAttribute("style", style);
+ assert.equal(focusEditableAtGoalX(code, "up", 40, content), false, style);
+ assert.equal(getSelection().anchorNode, after.firstChild);
+ cases++;
+ }
+ const {code, content, after} = setup("folded\n");
+ code.closest(".code-block").setAttribute("fold", "1");
+ assert.equal(focusEditableAtGoalX(code, "down", 40, content), false);
+ assert.equal(getSelection().anchorNode, after.firstChild);
+ const range = document.createRange();
+ range.selectNodeContents(code);
+ code.closest(".code-block").removeAttribute("fold");
+ code.parentElement.style.marginTop = "600px";
+ content.style.overflow = "hidden";
+ assert.deepEqual(getReachableVerticalRects(code, Array.from(range.getClientRects())), []);
+ assert.equal(focusEditableAtGoalX(code, "down", 40, content), false);
+ cases++;
+ return cases;
+};
+
+const runElectron = async () => {
+ const {app, BrowserWindow, ipcMain} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, width: 1000, height: 800, webPreferences: {
+ nodeIntegration: true,
+ contextIsolation: false,
+ backgroundThrottling: false,
+ }});
+ ipcMain.handle("vertical-navigation-key", async (event, keyCode) => {
+ const key = `Arrow${keyCode}`;
+ const code = keyCode === "Up" ? 38 : 40;
+ await win.webContents.debugger.sendCommand("Input.dispatchKeyEvent", {
+ type: "keyDown", key, code: key, windowsVirtualKeyCode: code,
+ });
+ await win.webContents.debugger.sendCommand("Input.dispatchKeyEvent", {
+ type: "keyUp", key, code: key, windowsVirtualKeyCode: code,
+ });
+ });
+ let exitCode = 0;
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ win.webContents.debugger.attach("1.3");
+ await win.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {enabled: true});
+ await win.webContents.executeJavaScript(`(() => {
+ const sources = ${JSON.stringify(rendererModules())};
+ const cache = {};
+ const load = name => {
+ if (!cache[name]) {
+ cache[name] = {};
+ new Function("require", "exports", sources[name])(load, cache[name]);
+ }
+ return cache[name];
+ };
+ window.verticalCaret = load("./verticalCaret");
+ window.verticalVisibility = load("./verticalVisibility");
+ })()`);
+ const cases = await win.webContents.executeJavaScript(`(${runGeometryCases.toString()})()`);
+ console.log(`Vertical navigation: ${cases} Electron geometry cases passed`);
+ } catch (error) {
+ console.error(error);
+ exitCode = 1;
+ } finally {
+ win.destroy();
+ app.exit(exitCode);
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ runElectron().catch(error => {
+ console.error(error);
+ require("electron").app.exit(1);
+ });
+} else {
+ const {it} = require("node:test");
+ const {execFile} = require("node:child_process");
+ const {promisify} = require("node:util");
+ it("keeps vertical caret lines and scroll reachability consistent in Electron", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+ }, async () => {
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-navigation-"));
+ try {
+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {
+ env,
+ windowsHide: true,
+ timeout: 40000,
+ });
+ assert.match(stdout, /Electron geometry cases passed/);
+ } finally {
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 2f8b73733c..76e1422091 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -1125,10 +1125,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
nodeElement.contains(firstEditElement)
) ||
(!firstEditElement && nodeElement === protyle.wysiwyg.element.firstElementChild)) {
- // 不能用\n判断,否则文字过长折行将错误 https://github.com/siyuan-note/siyuan/issues/6156
- // 空行 getSelectionPosition 计算有问题导致 https://github.com/siyuan-note/siyuan/issues/17602
- const diff = getSelectionPosition(nodeEditableElement, range).top - nodeEditableElement.getBoundingClientRect().top;
- if ((diff < 20 && diff !== 0) || nodeElement.classList.contains("av")) {
+ if (isFirstLine || nodeElement.classList.contains("av")) {
if (protyle.title && protyle.title.editElement &&
(protyle.wysiwyg.element.firstElementChild.getAttribute("data-eof") === "1" ||
protyle.contentElement.scrollTop === 0)) {
@@ -1143,8 +1140,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
}
} else {
- if (((nodeEditableElement?.innerText.substr(0, position.end).indexOf("\n") === -1 || position.start === 0) &&
- getSelectionPosition(nodeEditableElement, range).top - nodeEditableElement.getBoundingClientRect().top < 20)) {
+ if (isFirstLine) {
let previousElement: HTMLElement = getPreviousBlock(nodeElement) as HTMLElement;
if (previousElement) {
previousElement = getLastBlock(previousElement) as HTMLElement;
diff --git a/app/src/protyle/wysiwyg/verticalCaret.test.ts b/app/src/protyle/wysiwyg/verticalCaret.test.ts
index 891a442077..3322fd2ed7 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.test.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.test.ts
@@ -64,7 +64,7 @@ describe("vertical caret boundary", () => {
[emptyLine]);
assert.equal(getCodeTrailingZeroWidthLineLimit("x\n"), 0);
assert.equal(getCodeTrailingZeroWidthLineLimit("x\n\n"), 1);
- assert.equal(getCodeTrailingZeroWidthLineLimit("\n\n\n"), 2);
+ assert.equal(getCodeTrailingZeroWidthLineLimit("\n\n\n"), 3);
});
it("accepts only range context rectangles that reach the target line", () => {
diff --git a/app/src/protyle/wysiwyg/verticalCaret.ts b/app/src/protyle/wysiwyg/verticalCaret.ts
index 7550d5cc24..245e0f5e82 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.ts
@@ -1,4 +1,4 @@
-import {focusByRange, getSelectionPosition, setFirstNodeRange, setLastNodeRange} from "../util/selection";
+import {focusByRange, setFirstNodeRange, setLastNodeRange} from "../util/selection";
import {
getCodeTrailingZeroWidthLineLimit,
getNavigableVerticalRects,
@@ -25,57 +25,66 @@ const isCaretHitReachable = (element: Element, rects: DOMRect[]) => {
const getRangeContextElement = (range: Range) => range.startContainer.nodeType === Node.ELEMENT_NODE ?
range.startContainer as Element : range.startContainer.parentElement;
-// 折叠 Range 可能没有自身矩形,用相邻内容验证其所在行,不向正文插入占位字符。
+// 缺少光标矩形时,优先测量偏移之后的字符,避免把换行后的空行解释成前一行。
const getRangeContextRects = (range: Range, contextElement: Element) => {
- const rangeRects = Array.from(range.getClientRects());
+ const rangeRects = Array.from(range.getClientRects()).filter(rect => rect.height > 0.5);
if (rangeRects.length > 0) {
- return rangeRects;
+ return [rangeRects[range.collapsed ? rangeRects.length - 1 : 0]];
}
- const contextRects: DOMRect[] = [];
- if (range.startContainer.nodeType === Node.TEXT_NODE) {
- const textNode = range.startContainer as Text;
- const offsets = [
- [Math.max(0, range.startOffset - 1), range.startOffset],
- [range.startOffset, Math.min(textNode.length, range.startOffset + 1)],
- ];
- offsets.forEach(([start, end]) => {
- if (start === end) {
- return;
+ for (const forward of [true, false]) {
+ const adjacent = (node: Node): Node | null => {
+ while (node && node !== contextElement) {
+ const sibling = forward ? node.nextSibling : node.previousSibling;
+ if (sibling) {
+ return sibling;
+ }
+ node = node.parentNode;
}
- const probeRange = contextElement.ownerDocument.createRange();
- probeRange.setStart(textNode, start);
- probeRange.setEnd(textNode, end);
- contextRects.push(...Array.from(probeRange.getClientRects()));
- });
- if (contextRects.length === 0) {
- contextRects.push(...Array.from(contextElement.getClientRects()));
+ return null;
+ };
+ let node: Node = range.startContainer;
+ if (node.nodeType !== Node.TEXT_NODE) {
+ node = node.childNodes[range.startOffset - (forward ? 0 : 1)] || adjacent(node);
}
- } else if (range.startContainer.nodeType === Node.ELEMENT_NODE) {
- const container = range.startContainer as Element;
- [container.childNodes[range.startOffset - 1], container.childNodes[range.startOffset]].forEach(node => {
- if (!node) {
- return;
- }
+ while (node && contextElement.contains(node)) {
const probeRange = contextElement.ownerDocument.createRange();
- probeRange.selectNode(node);
- contextRects.push(...Array.from(probeRange.getClientRects()));
- });
- if (contextRects.length === 0) {
- contextRects.push(...Array.from(container.getClientRects()));
+ if (node.nodeType === Node.TEXT_NODE) {
+ const offset = node === range.startContainer ? range.startOffset :
+ forward ? 0 : node.textContent.length;
+ const start = forward ? offset : Math.max(0, offset - 1);
+ const end = forward ? Math.min(node.textContent.length, offset + 1) : offset;
+ if (start === end) {
+ node = adjacent(node);
+ continue;
+ }
+ probeRange.setStart(node, start);
+ probeRange.setEnd(node, end);
+ } else if (node.nodeType === Node.ELEMENT_NODE && node.hasChildNodes() &&
+ !(node as Element).matches(".render-node, [contenteditable=\"false\"]")) {
+ node = forward ? node.firstChild : node.lastChild;
+ continue;
+ } else {
+ probeRange.selectNode(node);
+ }
+ const rects = Array.from(probeRange.getClientRects()).filter(rect => rect.height > 0.5);
+ const rect = rects[forward ? 0 : rects.length - 1];
+ if (rect) {
+ return [new DOMRect(forward ? rect.left : rect.right, rect.top, 0, rect.height)];
+ }
+ node = adjacent(node);
}
- } else {
- contextRects.push(...Array.from(contextElement.getClientRects()));
}
- return contextRects;
+ return contextElement.textContent || contextElement.querySelector("img, .render-node") ? [] :
+ Array.from(contextElement.getClientRects());
};
-const getRangeRectsOnLine = (element: Element, range: Range, lineRects: DOMRect[]) => {
+const getRangeRectsOnLine = (element: Element, range: Range, lineRects: DOMRect[], requireVisible = false) => {
const contextElement = getRangeContextElement(range);
if (!contextElement || !element.contains(contextElement)) {
return [];
}
return getRectsIntersectingVerticalLine(
- getReachableVerticalRects(contextElement, getRangeContextRects(range, contextElement)), lineRects);
+ getReachableVerticalRects(contextElement, getRangeContextRects(range, element), requireVisible), lineRects);
};
const getCodeTrailingBlankLineCount = (element: Element) => {
@@ -96,21 +105,18 @@ export const isCaretAtVerticalBoundary = (element: Element, range: Range, direct
if (!element.contains(range.startContainer)) {
return false;
}
- const position = getSelectionPosition(element, range);
- return isCaretRectAtVerticalBoundary(position.top, getContentRects(element), direction);
+ const rects = getRangeContextRects(range, element);
+ return rects.length > 0 && isCaretRectAtVerticalBoundary(rects[0].top, getContentRects(element), direction);
};
export const getCaretGoalX = (range: Range, fallbackElement?: Element) => {
- const rects = Array.from(range.getClientRects());
- const rect = rects[0] || range.getBoundingClientRect();
- if (rect && Number.isFinite(rect.left) && rect.left > 0) {
+ const contextElement = getRangeContextElement(range);
+ const editable = contextElement?.closest("[contenteditable=\"true\"]");
+ const rect = contextElement && getRangeContextRects(range, editable || contextElement)[0];
+ if (rect && Number.isFinite(rect.left)) {
return rect.left;
}
if (fallbackElement) {
- const position = getSelectionPosition(fallbackElement, range);
- if (Number.isFinite(position.left) && position.left > 0) {
- return position.left;
- }
return fallbackElement.getBoundingClientRect().left;
}
return 0;
@@ -137,7 +143,7 @@ interface IEditableVerticalNavigationTarget {
// 目标解析只计算合法 Range,Selection 统一在滚动和复核完成后提交。
const resolveEditableVerticalNavigationTarget = (element: Element, direction: TVerticalDirection, goalX: number,
requireHit: boolean): IEditableVerticalNavigationTarget | undefined => {
- if (getFoldedNavigationOwner(element) ||
+ if (!element.isConnected || getFoldedNavigationOwner(element) ||
getReachableVerticalRects(element, Array.from(element.getClientRects())).length === 0) {
return;
}
@@ -149,16 +155,29 @@ const resolveEditableVerticalNavigationTarget = (element: Element, direction: TV
const lineTop = Math.min(...lineRects.map(rect => rect.top));
const lineBottom = Math.max(...lineRects.map(rect => rect.bottom));
const x = Math.max(lineLeft + 1, Math.min(goalX, lineRight - 1));
- const pointRange = document.caretRangeFromPoint(x, (lineTop + lineBottom) / 2);
- const isZeroWidthLine = lineRects.every(rect => rect.width <= 0.5);
- const pointRangeRects = pointRange ? getRangeRectsOnLine(element, pointRange, lineRects) : [];
- const pointRangeHasOwnRects = !!pointRange && pointRange.getClientRects().length > 0;
- if (pointRange && element.contains(pointRange.startContainer) && pointRangeRects.length > 0 &&
- (!requireHit || isCaretHitReachable(element, pointRangeHasOwnRects ? pointRangeRects : lineRects)) &&
- (!isZeroWidthLine || !pointRangeHasOwnRects ||
- isCaretRectAtVerticalBoundary(getSelectionPosition(element, pointRange).top, lineRects, "up"))) {
- pointRange.collapse(true);
- return {element, direction, range: pointRange};
+ let pointRange = document.caretRangeFromPoint(x, (lineTop + lineBottom) / 2);
+ for (let attempt = 0; pointRange && attempt < 2; attempt++) {
+ const pointRangeRects = getRangeRectsOnLine(element, pointRange, lineRects, requireHit);
+ if (element.contains(pointRange.startContainer) && pointRangeRects.length > 0 &&
+ (!requireHit || isCaretHitReachable(element, pointRangeRects))) {
+ pointRange.collapse(true);
+ return {element, direction, range: pointRange};
+ }
+ // 自动折行处可能同时带有前后两行矩形,改用前一字形的另一侧建立明确的行内位置。
+ if (attempt > 0 || pointRangeRects.length > 0 || pointRange.getClientRects().length < 2 ||
+ !element.contains(pointRange.startContainer) ||
+ pointRange.startContainer.nodeType !== Node.TEXT_NODE || pointRange.startOffset === 0) {
+ break;
+ }
+ const probeRange = pointRange.cloneRange();
+ probeRange.setStart(pointRange.startContainer, pointRange.startOffset - 1);
+ const rect = getRectsIntersectingVerticalLine(Array.from(probeRange.getClientRects()), lineRects)
+ .find(item => item.width > 0.5);
+ if (!rect) {
+ break;
+ }
+ const probeX = Math.abs(rect.left - x) > Math.abs(rect.right - x) ? rect.left + 0.25 : rect.right - 0.25;
+ pointRange = document.caretRangeFromPoint(probeX, (rect.top + rect.bottom) / 2);
}
}
if (direction === "up" && getCodeTrailingBlankLineCount(element) !== undefined) {
@@ -179,20 +198,20 @@ const resolveEditableVerticalNavigationTarget = (element: Element, direction: TV
const caretRects = Array.from(range.getClientRects());
let reachableRects: DOMRect[];
if (caretRects.length > 0) {
- reachableRects = lineRects.length > 0 ? getRangeRectsOnLine(element, range, lineRects) :
- getReachableVerticalRects(element, caretRects);
+ reachableRects = lineRects.length > 0 ? getRangeRectsOnLine(element, range, lineRects, requireHit) :
+ getReachableVerticalRects(element, caretRects, requireHit);
if (reachableRects.length === 0) {
return;
}
} else if (lineRects.length > 0) {
- reachableRects = getRangeRectsOnLine(element, range, lineRects);
+ reachableRects = getRangeRectsOnLine(element, range, lineRects, requireHit);
if (reachableRects.length === 0) {
return;
}
} else if (element.textContent || element.querySelector("img, .render-node")) {
return;
} else {
- reachableRects = getReachableVerticalRects(element, Array.from(element.getClientRects()));
+ reachableRects = getReachableVerticalRects(element, Array.from(element.getClientRects()), requireHit);
}
if (requireHit && !isCaretHitReachable(element, reachableRects)) {
return;
@@ -208,7 +227,7 @@ const getEditableTargetRects = (target: IEditableVerticalNavigationTarget) => {
const contextElement = getRangeContextElement(target.range);
if (contextElement && target.element.contains(contextElement)) {
const contextRects = getReachableVerticalRects(contextElement,
- getRangeContextRects(target.range, contextElement));
+ getRangeContextRects(target.range, target.element));
if (contextRects.length > 0) {
return contextRects;
}
@@ -217,7 +236,7 @@ const getEditableTargetRects = (target: IEditableVerticalNavigationTarget) => {
};
const revealEditableVerticalNavigationTarget = (target: IEditableVerticalNavigationTarget,
- boundaryElement?: Element) => {
+ goalX: number, boundaryElement?: Element) => {
const closestBlock = target.element.closest("[data-node-id]");
const scrollBoundary = boundaryElement?.contains(target.element) ? boundaryElement : closestBlock || target.element;
let ancestor: Element | null = target.element;
@@ -225,17 +244,27 @@ const revealEditableVerticalNavigationTarget = (target: IEditableVerticalNavigat
const scrollElement = ancestor as HTMLElement;
const view = ancestor.ownerDocument.defaultView;
const style = view?.getComputedStyle(ancestor);
+ const canScrollX = scrollElement.scrollWidth > scrollElement.clientWidth + 1 &&
+ ["auto", "scroll", "overlay"].includes(style?.overflowX);
const canScrollY = scrollElement.scrollHeight > scrollElement.clientHeight + 1 &&
(ancestor === scrollBoundary || ["auto", "scroll", "overlay"].includes(style?.overflowY));
- if (canScrollY) {
+ if (canScrollX || canScrollY) {
const rects = getEditableTargetRects(target);
if (rects.length > 0) {
const bounds = ancestor.getBoundingClientRect();
- const viewportTop = bounds.top + scrollElement.clientTop;
- const delta = getRevealDelta(Math.min(...rects.map(rect => rect.top)),
- Math.max(...rects.map(rect => rect.bottom)), viewportTop, viewportTop + scrollElement.clientHeight);
- if (delta !== 0) {
- scrollElement.scrollTop += delta;
+ if (canScrollX) {
+ const viewportLeft = bounds.left + scrollElement.clientLeft;
+ const lineLeft = Math.min(...rects.map(rect => rect.left));
+ const lineRight = Math.max(...rects.map(rect => rect.right));
+ const x = Math.max(lineLeft, Math.min(goalX, lineRight));
+ const fitsLine = lineRight - lineLeft + 2 <= scrollElement.clientWidth;
+ scrollElement.scrollLeft += getRevealDelta(fitsLine ? lineLeft - 1 : x - 1,
+ fitsLine ? lineRight + 1 : x + 1, viewportLeft, viewportLeft + scrollElement.clientWidth);
+ }
+ if (canScrollY) {
+ const viewportTop = bounds.top + scrollElement.clientTop;
+ scrollElement.scrollTop += getRevealDelta(Math.min(...rects.map(rect => rect.top)),
+ Math.max(...rects.map(rect => rect.bottom)), viewportTop, viewportTop + scrollElement.clientHeight);
}
}
}
@@ -252,7 +281,11 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirec
if (!target) {
return false;
}
- revealEditableVerticalNavigationTarget(target, scrollBoundary);
+ const parentElement = element.parentElement;
+ revealEditableVerticalNavigationTarget(target, goalX, scrollBoundary);
+ if (!element.isConnected || element.parentElement !== parentElement || !element.contains(target.range.startContainer)) {
+ return false;
+ }
const verifiedTarget = resolveEditableVerticalNavigationTarget(element, direction, goalX, true);
if (!verifiedTarget) {
return false;
diff --git a/app/src/protyle/wysiwyg/verticalGeometry.ts b/app/src/protyle/wysiwyg/verticalGeometry.ts
index 9b1e99d38a..7e22901527 100644
--- a/app/src/protyle/wysiwyg/verticalGeometry.ts
+++ b/app/src/protyle/wysiwyg/verticalGeometry.ts
@@ -41,7 +41,7 @@ export const getCodeTrailingZeroWidthLineLimit = (text: string) => {
return;
}
const hasVisiblePrefix = text.substring(0, text.length - trailingNewlineCount).length > 0;
- return Math.max(hasVisiblePrefix ? 0 : 1, trailingNewlineCount - 1);
+ return hasVisiblePrefix ? trailingNewlineCount - 1 : trailingNewlineCount;
};
export const getNavigableVerticalRects = <T extends IVerticalRect>(rects: T[],
diff --git a/app/src/protyle/wysiwyg/verticalVisibility.ts b/app/src/protyle/wysiwyg/verticalVisibility.ts
index 2553faedc6..1c87c27e24 100644
--- a/app/src/protyle/wysiwyg/verticalVisibility.ts
+++ b/app/src/protyle/wysiwyg/verticalVisibility.ts
@@ -1,9 +1,11 @@
-// 滚动区域外的内容仍可通过滚动到达;隐藏裁剪与折叠区域则限制合法落点。
-export const getReachableVerticalRects = (element: Element, rects: DOMRect[]) => {
- let result = rects.filter(rect => rect.height > 0.5);
+import {getRevealDelta} from "./verticalGeometry";
+
+// 逻辑解析保留原始矩形,并用可滚动到达的投影检查外层裁剪;展示后只接受当前可见的矩形。
+export const getReachableVerticalRects = (element: Element, rects: DOMRect[], requireVisible = false) => {
+ let result = rects.filter(rect => rect.height > 0.5).map(rect => ({original: rect, rect}));
const view = element.ownerDocument?.defaultView;
if (!view) {
- return result;
+ return result.map(item => item.rect);
}
let ancestor: Element | null = element;
while (ancestor && result.length > 0) {
@@ -11,22 +13,40 @@ export const getReachableVerticalRects = (element: Element, rects: DOMRect[]) =>
if (style.visibility === "hidden" || style.visibility === "collapse" || style.display === "none") {
return [];
}
- const clipX = ["hidden", "clip"].includes(style.overflowX);
- const clipY = ["hidden", "clip"].includes(style.overflowY);
+ const scrollX = ["auto", "scroll", "overlay"].includes(style.overflowX);
+ const scrollY = ["auto", "scroll", "overlay"].includes(style.overflowY);
+ const clipX = scrollX || ["hidden", "clip"].includes(style.overflowX);
+ const clipY = scrollY || ["hidden", "clip"].includes(style.overflowY);
if (clipX || clipY) {
const bounds = ancestor.getBoundingClientRect();
- result = result.flatMap(rect => {
- const left = clipX ? Math.max(rect.left, bounds.left) : rect.left;
- const right = clipX ? Math.min(rect.right, bounds.right) : rect.right;
- const top = clipY ? Math.max(rect.top, bounds.top) : rect.top;
- const bottom = clipY ? Math.min(rect.bottom, bounds.bottom) : rect.bottom;
+ const viewportLeft = bounds.left + ancestor.clientLeft;
+ const viewportTop = bounds.top + ancestor.clientTop;
+ const viewportRight = viewportLeft + ancestor.clientWidth;
+ const viewportBottom = viewportTop + ancestor.clientHeight;
+ result = result.flatMap(({original, rect}) => {
+ let deltaX = 0;
+ let deltaY = 0;
+ if (!requireVisible && scrollX) {
+ const maxScroll = ancestor.scrollWidth - ancestor.clientWidth;
+ const minScroll = style.direction === "rtl" ? -maxScroll : 0;
+ deltaX = Math.max(minScroll, Math.min(minScroll + maxScroll, ancestor.scrollLeft +
+ getRevealDelta(rect.left, rect.right, viewportLeft, viewportRight))) - ancestor.scrollLeft;
+ }
+ if (!requireVisible && scrollY) {
+ deltaY = Math.max(0, Math.min(ancestor.scrollHeight - ancestor.clientHeight, ancestor.scrollTop +
+ getRevealDelta(rect.top, rect.bottom, viewportTop, viewportBottom))) - ancestor.scrollTop;
+ }
+ const left = clipX ? Math.max(rect.left - deltaX, viewportLeft) : rect.left;
+ const right = clipX ? Math.min(rect.right - deltaX, viewportRight) : rect.right;
+ const top = clipY ? Math.max(rect.top - deltaY, viewportTop) : rect.top;
+ const bottom = clipY ? Math.min(rect.bottom - deltaY, viewportBottom) : rect.bottom;
return right >= left && bottom - top > 0.5 ?
- [new DOMRect(left, top, right - left, bottom - top)] : [];
+ [{original, rect: new DOMRect(left, top, right - left, bottom - top)}] : [];
});
}
ancestor = ancestor.parentElement;
}
- return result;
+ return result.map(item => requireVisible ? item.rect : item.original);
};
export const getFoldedNavigationOwner = (element: Element) => {