An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve navigation ownership and selection lifecycle https://github.com/siyuan-note/siyuan/issues/19184
Daniel2671f88f8e27
diff --git a/app/scripts/navigationLifecycle.cases.js b/app/scripts/navigationLifecycle.cases.jsnew file mode 100644index 0000000000..437d4be9c2--- /dev/null+++ b/app/scripts/navigationLifecycle.cases.js@@ -0,0 +1,245 @@+module.exports = async () => {+ const assert = require("node:assert/strict");+ const {ipcRenderer} = require("electron");+ const load = window.navigationModules;+ const navigation = load("wysiwyg/verticalNavigation");+ const state = load("wysiwyg/verticalNavigationState");+ const selection = load("util/selection");+ const targets = load("wysiwyg/verticalTarget");+ const table = load("util/tableNavigation");+ const documentRange = load("util/documentRange");+ const frame = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ const select = (element, offset = 0) => {+ const range = document.createRange();+ range.setStart(element.firstChild || element, offset);+ range.collapse(true);+ selection.focusByRange(range);+ };+ const p = (id, text = id) =>+ `<div data-node-id="${id}" data-type="NodeParagraph"><div contenteditable="true">${text}</div></div>`;+ const setup = html => {+ document.body.innerHTML = `<div class="protyle" style="height:180px;width:500px;overflow:hidden">+ <div class="protyle-content" style="height:180px;overflow:auto">+ <div class="protyle-title__input" contenteditable="true">title</div>+ <div class="protyle-wysiwyg" contenteditable="true" style="font:20px/30px monospace">${html}</div></div></div>`;+ const element = document.querySelector(".protyle");+ const editor = element.querySelector(".protyle-wysiwyg");+ const protyle = {element, contentElement: element.firstElementChild, wysiwyg: {element: editor},+ title: {editElement: element.querySelector(".protyle-title__input")},+ scroll: {lastScrollTop: 0, shouldKeepLoadedContent: () => false}};+ editor.firstElementChild?.setAttribute("data-eof", "1");+ editor.focus();+ return {protyle, editor};+ };+ window.siyuan.languages = {dragFill: "fill"};+ let cases = 0;+ // 自定义块内部形态不能改变外部所有者,连续按键必须经过外壳再离开。+ for (const content of ["plugin", '<input value="plugin">', '<div contenteditable="true">plugin editor</div>',+ `<div class="protyle-wysiwyg" contenteditable="true">${p("plugin")}</div>`]) {+ const {protyle, editor} = setup(p("before") ++ `<div class="custom-block" contenteditable="false" data-type="NodeCustomBlock" data-node-id="custom">${content}</div>` ++ p("after"));+ const [before, custom, after] = editor.children;+ assert.equal(targets.getAdjacentVerticalBlock(before, "down"), custom);+ assert.equal(targets.getAdjacentVerticalBlock(after, "up"), custom);+ navigation.bindVerticalNavigationReset(editor);+ window.navigationKeyup.bind(protyle);+ editor.addEventListener("keydown", event => {+ if (!["ArrowUp", "ArrowDown"].includes(event.key) || event.shiftKey) { return; }+ const range = selection.getEditorRange(editor);+ const owner = state.getAtomicVerticalNavigationOwner(range) ||+ load("util/hasClosest").hasClosestBlock(range.startContainer);+ assert.equal(navigation.focusAdjacentVerticalRegion(protyle, owner,+ event.key === "ArrowUp" ? "up" : "down", 20), "moved");+ protyle.wysiwyg.preventKeyup = true;+ event.preventDefault();+ });+ select(before.firstElementChild);+ for (const [key, expected] of [["Down", custom], ["Down", after], ["Up", custom], ["Up", before]]) {+ await ipcRenderer.invoke("vertical-navigation-key", key);+ await frame();+ const range = selection.getEditorRange(editor);+ assert.ok(expected === range.startContainer || expected.contains(range.startContainer), content);+ assert.equal(document.activeElement, editor);+ if (expected === custom) {+ assert.equal(state.getAtomicVerticalNavigationOwner(getSelection().getRangeAt(0)), custom);+ assert.equal(documentRange.containsCurrentSelection(custom), true);+ }+ }+ // 点击插件编辑区后不能再把其内部选区解释为外壳位置。+ custom.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));+ assert.equal(custom.classList.contains("protyle-wysiwyg--navigation"), false);+ cases++;+ }+ for (const loaded of [true, false]) {+ const {protyle, editor} = setup(p("first"));+ if (!loaded) {+ editor.firstElementChild.removeAttribute("data-eof");+ editor.firstElementChild.setAttribute("data-node-index", "200");+ }+ select(protyle.title.editElement);+ assert.equal(navigation.focusFirstVerticalRegion(protyle, 20), loaded ? "moved" : "blocked");+ select(editor.firstElementChild.firstElementChild);+ assert.equal(navigation.focusAdjacentVerticalRegion(protyle, editor.firstElementChild, "up", 20),+ loaded ? "moved" : "blocked");+ cases++;+ }+ for (const mode of [false, true]) {+ const {protyle, editor} = setup(p("before") ++ `<div class="custom-block" contenteditable="false" data-type="NodeCustomBlock" data-node-id="custom">+ <div class="protyle-wysiwyg" contenteditable="true">${p("plugin")}</div></div>` + p("after"));+ const [before, custom, after] = editor.children;+ const className = mode ? "protyle-wysiwyg--select-mode" : "protyle-wysiwyg--select";+ before.classList.add(className);+ navigation.bindVerticalNavigationReset(editor);+ load("wysiwyg/selectedNavigationKeydown").bind(protyle);+ select(before.firstElementChild);+ for (const [key, expected] of [["Down", custom], ["Down", after], ["Up", custom], ["Up", before]]) {+ await ipcRenderer.invoke("vertical-navigation-key", key);+ await frame();+ assert.equal(editor.querySelector("." + className), expected,+ mode + "/" + key + " expected " + expected.dataset.nodeId + " got " ++ editor.querySelector("." + className)?.dataset.nodeId);+ assert.equal(custom.querySelector("." + className), null);+ }+ cases++;+ }+ for (const span of [2, 3]) {+ const prefix = Array.from({length: span}, (_, i) => `<td>A${i}</td>`).join("");+ const {editor} = setup(`<div data-node-id="table"><table><tbody>+ <tr>${prefix}<td id="upper" rowspan="2">C0</td></tr>+ <tr><td colspan="${span}">AB1</td>${'<td class="fn__none" style="display:none"></td>'.repeat(span)}</tr>+ <tr>${prefix}<td id="lower">C2</td></tr></tbody></table></div>`);+ const upper = editor.querySelector("#upper");+ const lower = editor.querySelector("#lower");+ assert.equal(table.getVerticalTableCell(lower, "up"), upper);+ assert.equal(table.getVerticalTableCell(upper, "down"), lower);+ assert.equal(table.getVerticalTableCell(upper, "up"), undefined);+ assert.equal(table.getVerticalTableCell(lower, "down"), undefined);+ cases++;+ }+ // 序号始终基于整个编辑器,嵌入只校验作用域,不重新编号。+ for (const external of [true, false]) {+ for (const reverse of [true, false]) {+ const embedded = `<div data-node-id="heading">${p("same", "under heading")}</div>`;+ const separate = p("same", "separate");+ const {protyle, editor} = setup((external ? p("same", "source") : "") ++ `<div data-node-id="embed" data-type="NodeBlockQueryEmbed">${reverse ? separate + embedded : embedded + separate}</div>`);+ const copies = Array.from(editor.querySelectorAll('[data-node-id="same"]'));+ const expected = copies.find(element => element.textContent === "separate");+ const context = {undoFocusId: "same", undoFocusEndId: "same", undoFocusStart: "0", undoFocusEnd: "0",+ undoFocusIndex: String(copies.indexOf(expected)), undoFocusEndIndex: String(copies.indexOf(expected)),+ undoFocusEmbedId: "embed"};+ assert.equal(load("util/restoreNavigationFocus").restoreFocusContext(protyle, context), true);+ assert.equal(window.restoredFocusElement, expected);+ context.undoFocusIndex = "99";+ assert.equal(load("util/restoreNavigationFocus").restoreFocusContext(protyle, context), false);+ cases++;+ }+ }+ for (const before of [true, false]) {+ for (const protect of [true, false]) {+ const {protyle, editor} = setup(Array.from({length: 100}, (_, i) => p("p" + i)).join(""));+ const target = before ? editor.lastElementChild : editor.firstElementChild;+ if (protect) {+ select(target.firstElementChild);+ } else {+ select(protyle.title.editElement);+ }+ const node = getSelection().anchorNode;+ const offset = getSelection().anchorOffset;+ protyle.contentElement.scrollTop = before ? 0 : 2500;+ load("util/navigationTrim").run(protyle, p("loaded"), before);+ assert.equal(target.isConnected, protect, "trim " + before + "/" + protect);+ if (protect) {+ assert.equal(getSelection().anchorNode, node);+ assert.equal(getSelection().anchorOffset, offset);+ }+ cases++;+ }+ }+ const virtual = load("render/av/virtualScroll");+ const avState = load("render/av/selectionState");+ const constants = load("../constants").Constants;+ const createAV = (id, protyle, editor) => {+ const block = document.createElement("div");+ block.className = "av";+ block.dataset.avId = id;+ block.dataset.avType = "table";+ block.dataset.type = "NodeAttributeView";+ block.dataset.nodeId = id;+ block.setAttribute(constants.ATTRIBUTE_V_SCROLL, "true");+ block.setAttribute(constants.CUSTOM_SY_AV_VIEW, "view");+ const data = {viewType: "table", view: {id: "view", columns: [{id: "c0", type: "text"}],+ rows: Array.from({length: 100}, (_, i) => ({id: "r" + i, cells: [{id: "v" + i}]}))}};+ block.innerHTML = '<div class="av__cursor"> </div><div class="av__body">' ++ data.view.rows.map((row, rowIndex) => load("render/av/row").getRowHTML({row, rowIndex})).join("") ++ '<div class="av__row av__row--util"></div></div>';+ editor.append(block);+ virtual.initVirtualScroll({protyle, blockElement: block, data});+ return block;+ };+ // 相同持久 ID 的副本也必须独立;不同数据库交错 trim 不得污染滚动方向。+ const {protyle, editor} = setup("");+ const block = createAV("database", protyle, editor);+ const cell = block.querySelector(".av__cell");+ assert.equal(load("render/av/focus").focusAVVerticalRegion(block, "down", 20, false,+ protyle.contentElement), true);+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r0");+ load("render/av/navigationKeydown").run(block, new KeyboardEvent("keydown", {key: "ArrowDown"}));+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r1");+ load("render/av/navigationKeydown").run(block, new KeyboardEvent("keydown", {key: "ArrowUp"}));+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r0");+ const secondHost = protyle.element.cloneNode(false);+ secondHost.innerHTML = '<div style="height:180px;overflow:auto"><div class="protyle-wysiwyg"></div></div>';+ document.body.append(secondHost);+ const second = {element: secondHost, contentElement: secondHost.firstElementChild,+ wysiwyg: {element: secondHost.querySelector(".protyle-wysiwyg")}};+ const duplicate = createAV("database", second, second.wysiwyg.element);+ const other = createAV("other", second, second.wysiwyg.element);+ const trim = (target, owner) => virtual.trimAVRowsSync(target, owner.contentElement.getBoundingClientRect());+ protyle.contentElement.scrollTop = 2400;+ trim(block, protyle);+ assert.equal(cell.isConnected, false, "actual row trim");+ assert.equal(avState.getAVCellSelection(block).anchor.rowID, "r0");+ second.contentElement.scrollTop = 100;+ trim(duplicate, second);+ trim(other, second);+ protyle.contentElement.scrollTop = 0;+ trim(block, protyle);+ assert.equal(block.querySelector(".av__cell--select")?.parentElement.dataset.id, "r0");+ assert.equal(avState.getAVCellSelection(duplicate), undefined);+ assert.equal(avState.getAVCellSelection(other), undefined);+ cases++;+ const windowAfterScroll = (otherID) => {+ const {protyle: primary, editor: primaryEditor} = setup("");+ const primaryBlock = createAV("database", primary, primaryEditor);+ let otherBlock;+ let secondary;+ if (otherID) {+ const host = primary.element.cloneNode(false);+ host.style.position = "absolute";+ host.style.top = "0";+ host.style.left = "510px";+ host.innerHTML = '<div style="height:180px;overflow:auto"><div class="protyle-wysiwyg"></div></div>';+ document.body.append(host);+ secondary = {element: host, contentElement: host.firstElementChild,+ wysiwyg: {element: host.querySelector(".protyle-wysiwyg")}};+ otherBlock = createAV(otherID, secondary, secondary.wysiwyg.element);+ }+ primary.contentElement.scrollTop = 2400;+ trim(primaryBlock, primary);+ if (secondary) {+ secondary.contentElement.scrollTop = 1000;+ trim(otherBlock, secondary);+ }+ primary.contentElement.scrollTop = 2100;+ trim(primaryBlock, primary);+ return Array.from(primaryBlock.querySelectorAll(".av__row[data-id]"), row => row.dataset.id);+ };+ const standalone = windowAfterScroll();+ assert.deepEqual(windowAfterScroll("database"), standalone, "same database in two editors");+ assert.deepEqual(windowAfterScroll("other"), standalone, "interleaved independent databases");+ cases += 2;+ return cases;+};diff --git a/app/scripts/verticalNavigation.test.js b/app/scripts/verticalNavigation.test.jsindex e7a5681935..72d44c63f5 100644--- a/app/scripts/verticalNavigation.test.js+++ b/app/scripts/verticalNavigation.test.js@@ -21,11 +21,13 @@ const rendererModules = () => {};// 使用实际选区、区域解析与标题按键入口;不挂载无关的工具栏及页签控制器。modules["util/selection"] = `const revealTabsForTarget = () => {};- import {isAtomicVerticalNavigationRange} from "../wysiwyg/verticalNavigationState";+ import {getAtomicVerticalNavigationOwner} from "../wysiwyg/verticalNavigationState";import {getContenteditableElement} from "../wysiwyg/getBlock";import {hasClosestBlock} from "./hasClosest";\n` +- extract("util/selection", ["setFirstNodeRange", "setLastNodeRange", "focusByRange", "focusBlock", "getEditorRange"]);+ extract("util/selection", ["setFirstNodeRange", "setLastNodeRange", "focusByRange", "focusBlock", "getEditorRange"])+ .replace(/\/\/\/ #else[\s\S]*?\/\/\/ #endif/g, "");modules["util/hasClosest"] = readFileSync(path.join(root, "util/hasClosest.ts"), "utf8");+ modules["util/documentRange"] = readFileSync(path.join(root, "util/documentRange.ts"), "utf8");modules["wysiwyg/getBlock"] = 'import {hasClosestBlock, hasClosestByClassName} from "../util/hasClosest";\n' +extract("wysiwyg/getBlock", ["getContenteditableElement", "isContainerBlock", "getNextBlock", "getPreviousBlock"]);modules["render/tabsRender"] = "export const setTabTitleNavigationEditing = () => false;";@@ -83,6 +85,101 @@ const rendererModules = () => {protyle.wysiwyg.element.addEventListener("keyup", handler.bind(protyle.wysiwyg));}`;modules["render/av/verticalNavigation"] = readFileSync(path.join(root, "render/av/verticalNavigation.ts"), "utf8");+ modules["util/tableNavigation"] = extract("util/table", ["buildTableGrid", "getVerticalTableCell"]);+ modules["util/selectionFocus"] = readFileSync(path.join(root, "util/selectionFocus.ts"), "utf8");+ modules["util/restoreNavigationFocus"] = `import {getUndoFocusElement} from "./selectionFocus";+ import {isInEmbedBlock} from "./hasClosest";+ const focusByOffset = element => { window.restoredFocusElement = element; return true; };\n` ++ extract("util/selection", ["restoreFocusContext"]);+ for (const name of ["virtualScroll", "selectionState", "rangeSelect", "groupTableVirtual", "backlinkScroll"]) {+ modules[`render/av/${name}`] = readFileSync(path.join(root, "render/av", `${name}.ts`), "utf8");+ }+ modules["../constants"] = "const SIYUAN_VERSION = 'test', NODE_ENV = 'test';\n" ++ readFileSync(path.join(root, "../constants.ts"), "utf8");+ modules["render/av/richText"] = "export const renderAVRichTextElements = () => {};";+ modules["render/av/row"] = `export const updateAVSelectionStatus = () => {};+ export const getRowHTML = ({row, rowIndex}) =>+ '<div class="av__row" data-id="' + row.id + '" data-index="' + rowIndex ++ '" style="height:30px"><div class="av__cell" data-col-id="c0" data-dtype="text">' + row.id + '</div></div>';`;+ modules["render/av/focus"] = 'import {setAVCellAnchor} from "./rangeSelect";\n' ++ 'import {focusBlock} from "../../util/selection";\n' ++ "const addDragFill = () => {}, cellScrollIntoView = () => {};\n" + modules["render/av/focus"];+ const avKeydown = ts.createSourceFile("avKeydown.ts", readFileSync(path.join(root, "render/av/keydown.ts"), "utf8"),+ ts.ScriptTarget.Latest, true);+ let cellMoves;+ const visitCellMoves = node => {+ if (ts.isBlock(node)) {+ const index = node.statements.findIndex(statement => statement.getText(avKeydown) === "let newCellElement;");+ if (index >= 0) {+ cellMoves = Array.from(node.statements).slice(index, index + 5).map(item => item.getText(avKeydown)).join("\n");+ }+ }+ ts.forEachChild(node, visitCellMoves);+ };+ visitCellMoves(avKeydown);+ assert.ok(cellMoves);+ modules["render/av/navigationKeydown"] = `import {setAVCellAnchor} from "./rangeSelect";+ import {ensureAVTableAdjacentRow} from "./virtualScroll";+ import {getAVVerticalNavigationAction} from "./verticalNavigation";+ const matchHotKey = () => false, leaveVerticalRegion = () => false;+ const addDragFill = () => {}, cellScrollIntoView = () => {};+ export const run = (nodeElement, event) => {+ const selectCellElement = nodeElement.querySelector(".av__cell--select");+ const rowElement = selectCellElement.closest(".av__row");+ ${cellMoves}+ };`;+ const keydownSource = ts.createSourceFile("keydown.ts", readFileSync(path.join(root, "wysiwyg/keydown.ts"), "utf8"),+ ts.ScriptTarget.Latest, true);+ let selectedBranch;+ const visitSelected = node => {+ if (ts.isIfStatement(node) && node.expression.getText(keydownSource).includes('event.key === "ArrowDown" || event.key === "ArrowUp"') &&+ node.thenStatement.getText(keydownSource).startsWith(+ "{\n const selectElements = protyle.wysiwyg.element.querySelectorAll(")) {+ selectedBranch = node.getText(keydownSource);+ }+ ts.forEachChild(node, visitSelected);+ };+ visitSelected(keydownSource);+ assert.ok(selectedBranch);+ modules["wysiwyg/blockSelection"] = readFileSync(path.join(root, "wysiwyg/blockSelection.ts"), "utf8");+ modules["wysiwyg/selectedNavigationKeydown"] = `import {getEditorRange, focusByRange, setLastNodeRange} from "../util/selection";+ import {getAdjacentVerticalBlock} from "./verticalTarget";+ import {focusVerticalBlockSelection} from "./verticalNavigation";+ import {isDocumentBoundaryLoaded} from "../util/documentRange";+ import {isInEmbedBlock} from "../util/hasClosest";+ import {BLOCK_SELECTION_CLASS, getBlockSelectionModeElement, setBlockSelectionModeElement,+ clearBlockSelectionMode} from "./blockSelection";+ const countBlockWord = () => {}, countBlockSelectionMode = () => {};+ const isNotCtrl = event => !event.ctrlKey && !event.metaKey;+ const hideElements = (types, protyle) => protyle.wysiwyg.element.querySelectorAll("." + BLOCK_SELECTION_CLASS)+ .forEach(element => element.classList.remove(BLOCK_SELECTION_CLASS));+ export const bind = protyle => protyle.wysiwyg.element.addEventListener("keydown", event => {+ const range = getEditorRange(protyle.wysiwyg.element);+ const blockSelectionModeElement = getBlockSelectionModeElement(protyle.wysiwyg.element);+ ${selectedBranch}+ });`;+ // 原样抽取加载后的增删分支,隔离渲染、网络与销毁回调。+ const onGet = ts.createSourceFile("onGet.ts", readFileSync(path.join(root, "util/onGet.ts"), "utf8"),+ ts.ScriptTarget.Latest, true);+ let trimBranch;+ const visitTrim = node => {+ if (ts.isIfStatement(node) &&+ node.expression.getText(onGet) === "options.action.includes(Constants.CB_GET_APPEND)") {+ trimBranch = node;+ }+ ts.forEachChild(node, visitTrim);+ };+ visitTrim(onGet);+ assert.ok(trimBranch?.elseStatement && ts.isIfStatement(trimBranch.elseStatement));+ modules["util/navigationTrim"] = `import {containsCurrentSelection} from "./documentRange";+ import {Constants} from "../../constants";+ const invalidateTrackedRangesInElement = () => {}, disposeCustomBlocksInElement = () => {}, hideElements = () => {};+ export const run = (protyle, content, before) => {+ const options = {content, action: [before ? Constants.CB_GET_BEFORE : Constants.CB_GET_APPEND]};+ const REMOVED_OVER_HEIGHT = protyle.contentElement.clientHeight * 8;+ if (${trimBranch.expression.getText(onGet)}) ${trimBranch.thenStatement.getText(onGet)}+ else ${trimBranch.elseStatement.thenStatement.getText(onGet)}+ };`;return Object.fromEntries(Object.entries(modules).map(([name, source]) => [name,ts.transpileModule(source, {compilerOptions: {module: ts.ModuleKind.CommonJS,@@ -317,6 +414,7 @@ const runEntryCases = async () => {const protyle = {element: document.getElementById("protyle"),contentElement: document.querySelector(".protyle-content"), wysiwyg: {element: editor}, disabled: false};const title = document.getElementById("title");+ editor.firstElementChild?.setAttribute("data-eof", "1");window.titleKeydown.bind(protyle, title);bindVerticalNavigationReset(editor);title.focus();@@ -405,6 +503,8 @@ const runEntryCases = async () => {["<div data-type=\"NodeTable\" data-node-id=\"table\"><table><tr><td id=\"target\" contenteditable=\"true\">cell</td></tr></table></div>", "target", false],];window.titleEnterCalls = 0;+ variants.push([`<div id="target" class="custom-block" data-type="NodeCustomBlock" data-node-id="custom" contenteditable="false">+ <div contenteditable="true">plugin editor</div></div>`, "target", true]);for (const [markup, id, atomic] of variants) {const {protyle, editor} = setup(markup);const html = editor.innerHTML;@@ -414,7 +514,10 @@ const runEntryCases = async () => {await ipcRenderer.invoke("vertical-navigation-key", "Down");await frame();const target = document.getElementById(id);- assert.ok(target === getSelection().anchorNode || target.contains(getSelection().anchorNode), id);+ assert.ok(target === getSelection().anchorNode || target.contains(getSelection().anchorNode) ||+ window.navigationState.getAtomicVerticalNavigationOwner(getSelection().getRangeAt(0)) === target,+ id + ": " + markup + " selection: " + getSelection().anchorNode?.parentElement?.outerHTML ++ "/" + getSelection().anchorOffset + " editor: " + editor.innerHTML);assert.equal(keyups, 1);assert.equal(protyle.wysiwyg.preventKeyup, false);assert.equal(editor.querySelectorAll(".protyle-wysiwyg--navigation").length, atomic ? 1 : 0);@@ -504,13 +607,18 @@ const runElectron = async () => {window.verticalVisibility = load("wysiwyg/verticalVisibility");window.caretScroll = load("wysiwyg/caretScroll");window.verticalNavigation = load("wysiwyg/verticalNavigation");+ window.navigationState = load("wysiwyg/verticalNavigationState");window.titleKeydown = load("header/titleKeydown");window.navigationKeyup = load("wysiwyg/navigationKeyup");+ window.navigationModules = load;})()`);const cases = await win.webContents.executeJavaScript(`(${runGeometryCases.toString()})()`);console.log(`Vertical navigation: ${cases} Electron geometry cases passed`);const entryCases = await win.webContents.executeJavaScript(`(${runEntryCases.toString()})()`);console.log(`Vertical navigation: ${entryCases} Electron entry cases passed`);+ const lifecycleCases = await win.webContents.executeJavaScript(+ `(${require("./navigationLifecycle.cases.js").toString()})()`);+ console.log(`Vertical navigation: ${lifecycleCases} Electron lifecycle cases passed`);} catch (error) {console.error(error);exitCode = 1;@@ -544,6 +652,7 @@ if (process.versions.electron && process.type === "browser") {});assert.match(stdout, /Electron geometry cases passed/);assert.match(stdout, /Electron entry cases passed/);+ assert.match(stdout, /Electron lifecycle cases passed/);} finally {rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});}diff --git a/app/src/protyle/render/av/focus.ts b/app/src/protyle/render/av/focus.tsindex 0513521980..80054408f3 100644--- a/app/src/protyle/render/av/focus.ts+++ b/app/src/protyle/render/av/focus.ts@@ -4,7 +4,7 @@ import {focusBlock, focusByRange} from "../../util/selection";import {getFirstBlock, getLastBlock, getNextBlock, getPreviousBlock} from "../../wysiwyg/getBlock";import {scrollCenter} from "../../../util/highlightById";import {focusEditableAtGoalX, TVerticalDirection} from "../../wysiwyg/verticalCaret";-import {selectAVItemRange, setAVItemAnchor} from "./rangeSelect";+import {selectAVItemRange, setAVItemAnchor, setAVCellAnchor} from "./rangeSelect";const isForwardArrow = (key: string) => key === "ArrowDown" || key === "ArrowRight";@@ -71,8 +71,9 @@ export const focusAVVerticalRegion = (blockElement: HTMLElement, direction: TVerif (!focusBlock(blockElement)) {return false;}- clearSelect(["av"], blockElement);- cellElement.classList.add("av__cell--select");+ if (!setAVCellAnchor(blockElement, cellElement)) {+ return false;+ }addDragFill(cellElement);cellScrollIntoView(blockElement, cellElement);return true;@@ -127,8 +128,9 @@ export const focusAVByArrow = (protyle: IProtyle, blockElement: HTMLElement, keyif (!focusBlock(blockElement)) {return false;}- clearSelect(["av"], blockElement);- cellElement.classList.add("av__cell--select");+ if (!setAVCellAnchor(blockElement, cellElement)) {+ return false;+ }addDragFill(cellElement);cellScrollIntoView(blockElement, cellElement);return true;diff --git a/app/src/protyle/render/av/keydown.ts b/app/src/protyle/render/av/keydown.tsindex 471d180cfc..8c9052c4f5 100644--- a/app/src/protyle/render/av/keydown.ts+++ b/app/src/protyle/render/av/keydown.ts@@ -163,8 +163,10 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylnewCellElement = previousCellElements[previousCellElements.length - 1];}if (newCellElement) {- clearSelect(["cell"], nodeElement);- newCellElement.classList.add("av__cell--select");+ if (!setAVCellAnchor(nodeElement, newCellElement as HTMLElement)) {+ event.preventDefault();+ return true;+ }addDragFill(newCellElement);cellScrollIntoView(nodeElement, newCellElement, false);}@@ -182,8 +184,10 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylnewCellElement = nextRowElement.querySelector(".av__cell");}if (newCellElement) {- clearSelect(["cell"], nodeElement);- newCellElement.classList.add("av__cell--select");+ if (!setAVCellAnchor(nodeElement, newCellElement as HTMLElement)) {+ event.preventDefault();+ return true;+ }addDragFill(newCellElement);cellScrollIntoView(nodeElement, newCellElement, false);} else if (event.key !== "ArrowRight") {@@ -206,8 +210,10 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylnewCellElement = previousRowElement.querySelector(`.av__cell[data-col-id="${selectCellElement.dataset.colId}"]`);}if (getAVVerticalNavigationAction(!!newCellElement) === "move") {- clearSelect(["cell"], nodeElement);- newCellElement.classList.add("av__cell--select");+ if (!setAVCellAnchor(nodeElement, newCellElement as HTMLElement)) {+ event.preventDefault();+ return true;+ }addDragFill(newCellElement);cellScrollIntoView(nodeElement, newCellElement);} else if (leaveVerticalRegion("up")) {@@ -222,8 +228,10 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylnewCellElement = nextRowElement.querySelector(`.av__cell[data-col-id="${selectCellElement.dataset.colId}"]`);}if (getAVVerticalNavigationAction(!!newCellElement) === "move") {- clearSelect(["cell"], nodeElement);- newCellElement.classList.add("av__cell--select");+ if (!setAVCellAnchor(nodeElement, newCellElement as HTMLElement)) {+ event.preventDefault();+ return true;+ }addDragFill(newCellElement);cellScrollIntoView(nodeElement, newCellElement);} else if (leaveVerticalRegion("down")) {diff --git a/app/src/protyle/render/av/virtualScroll.ts b/app/src/protyle/render/av/virtualScroll.tsindex e611aa241c..eacf1a2f6f 100644--- a/app/src/protyle/render/av/virtualScroll.ts+++ b/app/src/protyle/render/av/virtualScroll.ts@@ -24,15 +24,14 @@ interface IBodyState {selectedRowIds?: Set<string>;}-const dataStore = new Map<string, {+const dataStore = new WeakMap<HTMLElement, {protyle: IProtyle;data: IAV;+ lastScrollTop?: number;}>();const blockDataStore = new WeakMap<HTMLElement, IAV>();const bodyStates = new WeakMap<HTMLElement, IBodyState>();const trimPending = new WeakSet<HTMLElement>();-let lastScrollTop: number;-const localScrollTops = new WeakMap<HTMLElement, number>();// 测量 DOM 变更前后容器 scrollHeight 的差值,用于精确计算 gallery 多列网格中行移除/回填的实际高度(含 gap)const measureHeightDiff = (el: HTMLElement, mutate: () => void): number => {@@ -83,19 +82,16 @@ const doTrim = (blockElement: HTMLElement, elementRect: DOMRect): void => {// AV 重渲/新增分组/局部更新未走完整 initVirtualScroll 时 dataStore 可能缺失,跳过本次 trim,// 等下次 initVirtualScroll 重新登记后再处理,避免解引用 undefined.protyle- const stored = dataStore.get(blockElement.getAttribute("data-av-id") + blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW));+ const stored = dataStore.get(blockElement);if (!stored) {return;}const protyle = stored.protyle;const scrollTop = (localScroller || protyle.contentElement).scrollTop;- const previousScrollTop = localScroller ? localScrollTops.get(localScroller) : lastScrollTop;+ const previousScrollTop = stored.lastScrollTop;const isScrollingUp = previousScrollTop !== undefined && previousScrollTop > scrollTop;- if (localScroller) {- localScrollTops.set(localScroller, scrollTop);- } else {- lastScrollTop = scrollTop;- }+ // 每个显示实例独立消费滚动位置,避免同帧中其他数据库先更新方向。+ stored.lastScrollTop = scrollTop;if ((blockRect.bottom < elementRect.top && !isScrollingUp) || (blockRect.top > elementRect.bottom && isScrollingUp)) {return;@@ -494,7 +490,7 @@ export const getBodyVirtualData = (bodyEl: HTMLElement, endSelector: string, firconst getBodyData = (bodyEl: HTMLElement) => {const avEl = bodyEl.closest(".av") as HTMLElement;if (!avEl) return null;- const stored = dataStore.get(avEl.getAttribute("data-av-id") + avEl.getAttribute(Constants.CUSTOM_SY_AV_VIEW));+ const stored = dataStore.get(avEl);const data = blockDataStore.get(avEl) || stored?.data;if (!data) return null;@@ -877,15 +873,14 @@ export const initVirtualScroll = (options: {setAVData(options.blockElement, options.data);const virtualized = options.blockElement.getAttribute(Constants.ATTRIBUTE_V_SCROLL) === "true";const needsGroupedTableState = options.data.viewType === "table" && options.data.view.groups?.length > 0;- const storeKey = options.blockElement.getAttribute("data-av-id") +- options.blockElement.getAttribute(Constants.CUSTOM_SY_AV_VIEW);if (virtualized) {- dataStore.set(storeKey, {+ dataStore.set(options.blockElement, {protyle: options.protyle,data: options.data,+ lastScrollTop: (getBacklinkScrollElement(options.blockElement) || options.protyle.contentElement).scrollTop,});} else {- dataStore.delete(storeKey);+ dataStore.delete(options.blockElement);}if (!virtualized && !needsGroupedTableState) {return;diff --git a/app/src/protyle/util/documentRange.ts b/app/src/protyle/util/documentRange.tsindex 1a3dcfe8cf..8d0dff96a3 100644--- a/app/src/protyle/util/documentRange.ts+++ b/app/src/protyle/util/documentRange.ts@@ -1,3 +1,19 @@+import {getAtomicVerticalNavigationOwner} from "../wysiwyg/verticalNavigationState";++// 动态回收按响应到达时的选区判断;连续区间在遇到用户位置时停止裁剪。+export const containsCurrentSelection = (element: Element) => {+ const selection = element.ownerDocument.getSelection();+ for (let index = 0; selection && index < selection.rangeCount; index++) {+ const range = selection.getRangeAt(index);+ const atomicOwner = getAtomicVerticalNavigationOwner(range);+ if (range.intersectsNode(element) || atomicOwner && element.contains(atomicOwner)) {+ return true;+ }+ }+ const activeElement = element.ownerDocument.activeElement;+ return activeElement && element.contains(activeElement);+};+export const updateDocumentBottomEof = (wysiwygElement: HTMLElement, preserveCurrent = false) => {if (preserveCurrent && wysiwygElement.hasAttribute("data-bottom-eof")) {return;diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex dbf9bb439b..eecc485aa4 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -27,7 +27,7 @@ import {queueHeadingNumberRefresh,renderHeadingNumbers} from "./headingNumber";-import {updateDocumentBottomEof} from "./documentRange";+import {containsCurrentSelection, updateDocumentBottomEof} from "./documentRange";import {disabledWYSIWYG} from "./disabledWYSIWYG";import {getEmbeddedDocInfoResponse} from "./docInfo";import {updateWidgetCacheVersion} from "./widgetCache";@@ -265,8 +265,11 @@ const setHTML = (options: {!protyle.scroll.shouldKeepLoadedContent() && protyle.contentElement.scrollHeight > REMOVED_OVER_HEIGHT) {let removeElement = protyle.wysiwyg.element.firstElementChild as HTMLElement;const removeElements = [];- while (protyle.wysiwyg.element.childElementCount > 2 && removeElements &&+ while (protyle.wysiwyg.element.childElementCount - removeElements.length > 2 &&protyle.wysiwyg.element.lastElementChild !== removeElement) {+ if (containsCurrentSelection(removeElement)) {+ break;+ }if (protyle.contentElement.scrollHeight - removeElement.offsetTop > REMOVED_OVER_HEIGHT) {removeElements.push(removeElement);} else {@@ -274,15 +277,17 @@ const setHTML = (options: {}removeElement = removeElement.nextElementSibling as HTMLElement;}- const lastRemoveTop = removeElement.getBoundingClientRect().top;- removeElements.forEach(item => {- invalidateTrackedRangesInElement(protyle, item);- disposeCustomBlocksInElement(item);- item.remove();- });- protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + (removeElement.getBoundingClientRect().top - lastRemoveTop) - 1;- protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop;- hideElements(["toolbar"], protyle);+ if (removeElements.length > 0) {+ const lastRemoveTop = removeElement.getBoundingClientRect().top;+ removeElements.forEach(item => {+ invalidateTrackedRangesInElement(protyle, item);+ disposeCustomBlocksInElement(item);+ item.remove();+ });+ protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + (removeElement.getBoundingClientRect().top - lastRemoveTop) - 1;+ protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop;+ hideElements(["toolbar"], protyle);+ }}protyle.wysiwyg.element.insertAdjacentHTML("beforeend", options.content);} else if (options.action.includes(Constants.CB_GET_BEFORE)) {@@ -299,6 +304,9 @@ const setHTML = (options: {let scrollHeight = protyle.contentElement.scrollHeight;let lastElement = protyle.wysiwyg.element.lastElementChild;while (childCount > 2 && scrollHeight > REMOVED_OVER_HEIGHT && lastElement.getBoundingClientRect().top > window.innerHeight) {+ if (containsCurrentSelection(lastElement)) {+ break;+ }removeElements.push(lastElement);lastElement = lastElement.previousElementSibling;childCount--;diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.tsindex 62017a5957..6b9edaf405 100644--- a/app/src/protyle/util/selection.ts+++ b/app/src/protyle/util/selection.ts@@ -16,7 +16,7 @@ import {hasClosestByTag,isInEmbedBlock} from "./hasClosest";-import {isAtomicVerticalNavigationRange} from "../wysiwyg/verticalNavigationState";+import {getAtomicVerticalNavigationOwner} from "../wysiwyg/verticalNavigationState";import {countBlockWord, countSelectWord} from "../../layout/status";import {hideElements} from "../ui/hideElements";import {genRenderFrame} from "../render/util";@@ -204,8 +204,16 @@ export const getEditorRange = (element: Element): Range => {range = getSelection().getRangeAt(0);if (element === range.startContainer || element.contains(range.startContainer)) {// 纵向导航建立的原子 Range 已是合法位置,读取选区时不能再次聚焦其正文。- if (isAtomicVerticalNavigationRange(range)) {- return range;+ const atomicOwner = getAtomicVerticalNavigationOwner(range);+ if (atomicOwner) {+ if (range.startContainer === atomicOwner) {+ return range;+ }+ // 对调用方保持块所有者坐标,不改写浏览器中稳定的外侧选区。+ const ownerRange = document.createRange();+ ownerRange.setStart(atomicOwner, 0);+ ownerRange.collapse(true);+ return ownerRange;}if (range.toString() === "" && range.startContainer.nodeType === 1) {// 有时候点击编辑器头部需要矫正到第一个块中@@ -664,7 +672,8 @@ export const restoreFocusContext = (protyle: IProtyle, context: Record<string, sif (!focusScopeElement) {return false;}- const startBlockElements = Array.from(focusScopeElement.querySelectorAll(+ // 副本序号以整个编辑器为参照保存;恢复时保留同一候选顺序,再校验嵌入作用域。+ const startBlockElements = Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${context.undoFocusId}"]`));const startBlockElement = getUndoFocusElement(@@ -673,7 +682,7 @@ export const restoreFocusContext = (protyle: IProtyle, context: Record<string, sitem => !isInEmbedBlock(item, false),);const endBlockElements = context.undoFocusEndId === context.undoFocusId ?- startBlockElements : Array.from(focusScopeElement.querySelectorAll(+ startBlockElements : Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${context.undoFocusEndId || context.undoFocusId}"]`));const endBlockElement = getUndoFocusElement(@@ -681,7 +690,8 @@ export const restoreFocusContext = (protyle: IProtyle, context: Record<string, scontext.undoFocusEndIndex,item => !isInEmbedBlock(item, false),);- if (!startBlockElement || !endBlockElement) {+ if (!startBlockElement || !endBlockElement ||+ !focusScopeElement.contains(startBlockElement) || !focusScopeElement.contains(endBlockElement)) {return false;}const startFocusElement = context.undoFocusCalloutTitle === "true" ?diff --git a/app/src/protyle/util/selectionFocus.test.ts b/app/src/protyle/util/selectionFocus.test.tsindex 78ee9c2892..154cc002df 100644--- a/app/src/protyle/util/selectionFocus.test.ts+++ b/app/src/protyle/util/selectionFocus.test.ts@@ -7,8 +7,13 @@ describe("getUndoFocusElement", () => {assert.equal(getUndoFocusElement(["source", "embed"], "1", item => item === "source"), "embed");});- it("uses the target embed element when the global duplicate index is outside its scope", () => {- assert.equal(getUndoFocusElement(["embed"], "1", item => item === "source"), "embed");+ it("does not silently reuse the first copy when the recorded index is missing", () => {+ assert.equal(getUndoFocusElement(["embed"], "1", item => item === "source"), undefined);+ });++ it("requires an unambiguous candidate for older contexts without an index", () => {+ assert.equal(getUndoFocusElement(["source", "embed"], undefined, item => item === "source"), "source");+ assert.equal(getUndoFocusElement(["embed-a", "embed-b"], undefined, () => true), undefined);});it("does not fall back to another scope while the target embed is rendering", () => {diff --git a/app/src/protyle/util/selectionFocus.ts b/app/src/protyle/util/selectionFocus.tsindex d905f97695..0d143f0272 100644--- a/app/src/protyle/util/selectionFocus.ts+++ b/app/src/protyle/util/selectionFocus.ts@@ -3,9 +3,12 @@ export const getUndoFocusElement = <T>(indexValue: string | undefined,isPreferred: (element: T) => boolean,) => {- const index = Number(indexValue);- const indexedElement = Number.isInteger(index) && index >= 0 ? elements[index] : undefined;- return indexedElement || elements.find(isPreferred) || elements[0];+ if (indexValue !== undefined) {+ const index = Number(indexValue);+ return Number.isInteger(index) && index >= 0 ? elements[index] : undefined;+ }+ const candidates = elements.filter(isPreferred);+ return candidates.length === 1 ? candidates[0] : elements.length === 1 ? elements[0] : undefined;};export const getUndoFocusTarget = <T>(elements: T[], containsSelection: (element: T) => boolean) => {diff --git a/app/src/protyle/util/table.ts b/app/src/protyle/util/table.tsindex a7a275c507..fbdc1f58f5 100644--- a/app/src/protyle/util/table.ts+++ b/app/src/protyle/util/table.ts@@ -5,12 +5,12 @@ import {focusByWbr,getEditorRange,getSelectionOffset,- getSelectionPosition,getUndoFocusContext,} from "./selection";import {hasClosestBlock, hasClosestByClassName, hasClosestByTag} from "./hasClosest";import {matchHotKey} from "./hotKey";import {isNotCtrl} from "./compatibility";+import {focusEditableAtGoalX, getCaretGoalX, isCaretAtVerticalBoundary} from "../wysiwyg/verticalCaret";import {scrollCenter} from "../../util/highlightById";import {insertEmptyBlock} from "../../block/util";import {removeBlock} from "../wysiwyg/remove";@@ -513,103 +513,17 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)return true;}- if (event.key === "ArrowUp" && isNotCtrl(event) && !event.shiftKey && !event.altKey) {- if (cellElement.firstChild) {- let firstChild = cellElement.firstChild;- while (firstChild) {- if (firstChild.textContent === "" && firstChild.nodeType === 3) {- if (!firstChild.nextSibling) {- break;- }- firstChild = firstChild.nextSibling;- } else {- break;- }- }- const rangeTemp = document.createRange();- rangeTemp.selectNodeContents(firstChild);- rangeTemp.collapse(true);- const rangeRects = range.getClientRects().length === 0 ? getSelectionPosition(cellElement, range) : range.getClientRects()[0];- const rangeTempRects = rangeTemp.getClientRects().length === 0 ? getSelectionPosition(cellElement, rangeTemp) : rangeTemp.getClientRects()[0];- if (rangeTempRects.top < rangeRects.top) {- return false;- }- }- const trElement = cellElement.parentElement as HTMLTableRowElement;- let previousElement = trElement.previousElementSibling as HTMLTableRowElement;- if (!previousElement) {- previousElement = trElement.parentElement.previousElementSibling.lastElementChild as HTMLTableRowElement;- }- if (!previousElement || previousElement?.tagName === "COL") {+ if (["ArrowUp", "ArrowDown"].includes(event.key) && isNotCtrl(event) &&+ !event.shiftKey && !event.altKey && !event.isComposing && range.collapsed) {+ const direction = event.key === "ArrowUp" ? "up" : "down";+ if (!isCaretAtVerticalBoundary(cellElement, range, direction)) {return false;}- const currentColIndex = getColIndex(cellElement);- let newCellElement = previousElement.cells[currentColIndex];- while (previousElement) {- let i = 0;- while (newCellElement && newCellElement.classList.contains("fn__none")) {- i++;- newCellElement = newCellElement.previousElementSibling as HTMLTableCellElement;- }- if (newCellElement.colSpan < 2 && i !== 0) {- previousElement = previousElement.previousElementSibling as HTMLTableRowElement;- newCellElement = previousElement.cells[currentColIndex];- } else if (newCellElement.colSpan > i) {- break;- }- }-- range.selectNodeContents(newCellElement);- range.collapse(false);- scrollCenter(protyle);- event.preventDefault();- return true;- }-- if (event.key === "ArrowDown" && isNotCtrl(event) && !event.shiftKey && !event.altKey) {- if (cellElement.lastChild) {- let lastChild = cellElement.lastChild;- while (lastChild) {- if (lastChild.textContent === "" && lastChild.nodeType === 3) {- if (!lastChild.previousSibling) {- break;- }- lastChild = lastChild.previousSibling;- } else {- break;- }- }- const rangeTemp = document.createRange();- rangeTemp.selectNodeContents(lastChild);- rangeTemp.collapse(false);- if (getSelectionPosition(cellElement, rangeTemp).top > getSelectionPosition(cellElement, range).top) {- return false;- }- }- const trElement = cellElement.parentElement as HTMLTableRowElement;- if ((!trElement.nextElementSibling && trElement.parentElement.tagName === "TBODY") ||- (trElement.parentElement.tagName === "THEAD" && !trElement.parentElement.nextElementSibling)) {- return false;- }- let nextElement = trElement.nextElementSibling as HTMLTableRowElement;- if (!nextElement) {- nextElement = trElement.parentElement.nextElementSibling.firstChild as HTMLTableRowElement;- }- if (!nextElement) {+ const target = getVerticalTableCell(cellElement, direction);+ if (!target) {return false;}- let rowSpan = cellElement.rowSpan;- while (rowSpan > 1) {- rowSpan--;- nextElement = nextElement.nextElementSibling as HTMLTableRowElement;- }- let nextCellElement = nextElement.cells[getColIndex(cellElement)];- while (nextCellElement.classList.contains("fn__none") && nextCellElement.nextElementSibling) {- nextCellElement = nextCellElement.previousElementSibling as HTMLTableCellElement;- }- range.selectNodeContents(nextCellElement);- range.collapse(true);- scrollCenter(protyle);+ focusEditableAtGoalX(target, direction, getCaretGoalX(range), protyle.contentElement);event.preventDefault();return true;}@@ -992,6 +906,21 @@ export const buildTableGrid = (tableElement: HTMLElement): ITableGrid => {};};+// 合并占位由逻辑网格确定,跨行单元格从其占据区域的外侧查找相邻行。+export const getVerticalTableCell = (cell: HTMLTableCellElement, direction: "up" | "down") => {+ const table = cell.closest("table");+ if (!table) {+ return;+ }+ const {grid, cellInfos} = buildTableGrid(table);+ const info = cellInfos.find(item => item.cell === cell);+ if (!info) {+ return;+ }+ const row = direction === "up" ? info.row - 1 : info.row + info.rowspan;+ return grid[row]?.[info.col] || undefined;+};+export const getTableCellSelectionIndexes = (tableElement: HTMLTableElement,cellElements: HTMLTableCellElement[],diff --git a/app/src/protyle/wysiwyg/caretScroll.ts b/app/src/protyle/wysiwyg/caretScroll.tsindex ffacc70e9b..4936390966 100644--- a/app/src/protyle/wysiwyg/caretScroll.ts+++ b/app/src/protyle/wysiwyg/caretScroll.ts@@ -1,5 +1,5 @@import {getVerticalCaretRect} from "./verticalCaret";-import {isAtomicVerticalNavigationTarget} from "./verticalNavigationState";+import {isAtomicVerticalNavigationTarget, isAtomicVerticalNavigationRange} from "./verticalNavigationState";import {getCaretOverflowDirection,getCaretScrollDelta,@@ -44,6 +44,9 @@ const getCaretScrollGeometry = (protyle: IProtyle): ICaretScrollGeometry | undefreturn;}range.collapse(true);+ if (isAtomicVerticalNavigationRange(range)) {+ return;+ }const caretPosition = getVerticalCaretRect(editableElement, range);if (!caretPosition) {return;diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 2adb3d80ea..67acd7c9c9 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -143,6 +143,9 @@ import {prepareVerticalNavigation,} from "./verticalNavigation";import {isAtomicVerticalNavigationTarget} from "./verticalNavigationState";+import {getAdjacentVerticalBlock} from "./verticalTarget";+import {focusVerticalBlockSelection} from "./verticalNavigation";+import {isDocumentBoundaryLoaded} from "../util/documentRange";import {BLOCK_SELECTION_CLASS,clearBlockSelectionMode,@@ -503,30 +506,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {if (event.key === "ArrowDown") {const currentSelectElement = blockSelectionModeElement ||selectElements[selectElements.length - 1] as HTMLElement;- let nextElement = getNextBlock(currentSelectElement) as HTMLElement;- if (nextElement) {- if (nextElement.getBoundingClientRect().width === 0) {- // https://github.com/siyuan-note/siyuan/issues/4294- const foldElement = hasTopClosestByAttribute(nextElement, "fold", "1");- if (foldElement) {- nextElement = getNextBlock(foldElement) as HTMLElement;- if (nextElement) {- nextElement = getFirstBlock(nextElement) as HTMLElement;- } else {- nextElement = currentSelectElement;- }- } else {- nextElement = currentSelectElement;- }- } else if (nextElement.getAttribute("fold") === "1"- && (nextElement.classList.contains("sb") || nextElement.classList.contains("bq"))) {- // https://github.com/siyuan-note/siyuan/issues/3913- } else {- nextElement = getFirstBlock(nextElement) as HTMLElement;- }- } else {- nextElement = currentSelectElement;- }+ const nextElement = getAdjacentVerticalBlock(currentSelectElement, "down") || currentSelectElement;if (blockSelectionModeElement) {setBlockSelectionModeElement(protyle.wysiwyg.element, nextElement);@@ -540,29 +520,13 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + bottom;protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop - 1;}- focusBlock(nextElement);+ focusVerticalBlockSelection(protyle.wysiwyg.element, nextElement, "down");} else if (event.key === "ArrowUp") {const currentSelectElement = blockSelectionModeElement || selectElements[0] as HTMLElement;- let previousElement: HTMLElement = getPreviousBlock(currentSelectElement) as HTMLElement;- if (previousElement) {- previousElement = getLastBlock(previousElement) as HTMLElement;- if (previousElement.getBoundingClientRect().width === 0) {- // https://github.com/siyuan-note/siyuan/issues/4294- const foldElement = hasTopClosestByAttribute(previousElement, "fold", "1");- if (foldElement) {- previousElement = getFirstBlock(foldElement) as HTMLElement;- } else {- previousElement = currentSelectElement;- }- } else if (previousElement) {- // https://github.com/siyuan-note/siyuan/issues/3913- const foldElement = hasTopClosestByAttribute(previousElement, "fold", "1");- if (foldElement && (foldElement.classList.contains("sb") || foldElement.classList.contains("bq"))) {- previousElement = foldElement;- }- }- } else if (protyle.title && protyle.title.editElement &&- (protyle.wysiwyg.element.firstElementChild.getAttribute("data-eof") === "1" || protyle.contentElement.scrollTop === 0)) {+ let previousElement = getAdjacentVerticalBlock(currentSelectElement, "up");+ if (!previousElement && protyle.title?.editElement &&+ !isInEmbedBlock(currentSelectElement) &&+ isDocumentBoundaryLoaded(protyle.wysiwyg.element, "before")) {const titleRange = setLastNodeRange(protyle.title.editElement, range, false);titleRange.collapse(false);focusByRange(titleRange);@@ -572,10 +536,10 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {clearBlockSelectionMode(protyle.wysiwyg.element, true);countBlockWord([], protyle);}- } else if (protyle.contentElement.scrollTop !== 0) {+ } else if (!previousElement && protyle.contentElement.scrollTop !== 0) {protyle.contentElement.scrollTop = 0;protyle.scroll.lastScrollTop = 8;- } else {+ } else if (!previousElement) {previousElement = currentSelectElement;}if (previousElement) {@@ -591,7 +555,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {protyle.contentElement.scrollTop = protyle.contentElement.scrollTop + top;protyle.scroll.lastScrollTop = protyle.contentElement.scrollTop + 1;}- focusBlock(previousElement);+ focusVerticalBlockSelection(protyle.wysiwyg.element, previousElement, "up");}}return;diff --git a/app/src/protyle/wysiwyg/verticalNavigation.ts b/app/src/protyle/wysiwyg/verticalNavigation.tsindex b8d41f73d8..3c5ec6dc06 100644--- a/app/src/protyle/wysiwyg/verticalNavigation.ts+++ b/app/src/protyle/wysiwyg/verticalNavigation.ts@@ -1,11 +1,12 @@import {isInEmbedBlock} from "../util/hasClosest";+import {isDocumentBoundaryLoaded} from "../util/documentRange";import {focusBlock, focusByRange} from "../util/selection";import {scrollCenter} from "../../util/highlightById";import {getContenteditableElement} from "./getBlock";import {focusEditableAtGoalX, getCaretGoalX, TVerticalDirection} from "./verticalCaret";import {focusAVTitleByVerticalArrow, focusAVVerticalRegion} from "../render/av/focus";import {- getAdjacentVisibleBlock,+ getAdjacentVerticalBlock,getVerticalNavigationScope,getVisibleBoundaryBlock,isVerticalNavigationElementVisible,@@ -91,7 +92,14 @@ export const prepareVerticalNavigation = (editorElement: HTMLElement, event: Key};const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, direction: TVerticalDirection) => {- if (element.getAttribute("fold") === "1") {+ if (element.classList.contains("custom-block")) {+ editorElement.focus({preventScroll: true});+ const range = document.createRange();+ // 非编辑外壳内的折叠 Range 会被浏览器归一化,使用外侧边界并由原子标记解释所有者。+ range.setStartBefore(element);+ range.collapse(true);+ focusByRange(range);+ } else if (element.getAttribute("fold") === "1") {const range = document.createRange();range.setStart(element, 0);range.collapse(true);@@ -104,6 +112,10 @@ const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, dirreturn true;};+export const focusVerticalBlockSelection = (editorElement: HTMLElement, element: HTMLElement,+ direction: TVerticalDirection) =>+ focusAtomicRegion(editorElement, element, direction);+type TVerticalNavigationOutcome = "moved" | "blocked" | "none";type TVerticalNavigationTarget = {@@ -196,7 +208,8 @@ const focusResolvedRegion = (protyle: IProtyle, element: Element | undefined,};export const focusFirstVerticalRegion = (protyle: IProtyle, goalX: number): TVerticalNavigationOutcome => {- if (protyle.disabled || !protyle.wysiwyg.element.isConnected) {+ if (protyle.disabled || !protyle.wysiwyg.element.isConnected ||+ !isDocumentBoundaryLoaded(protyle.wysiwyg.element, "before")) {return "blocked";}return focusResolvedRegion(protyle, getVisibleBoundaryBlock(protyle.wysiwyg.element, "down"), "down", goalX);@@ -208,6 +221,9 @@ const focusDocumentTitle = (protyle: IProtyle, direction: TVerticalDirection,protyle.title.editElement.getClientRects().length === 0) {return "none";}+ if (!isDocumentBoundaryLoaded(protyle.wysiwyg.element, "before")) {+ return "blocked";+ }const target: TVerticalNavigationTarget = {type: "text",owner: protyle.title.editElement,@@ -270,13 +286,9 @@ export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HT}}- let adjacentElement = getAdjacentVisibleBlock(sourceElement, direction);- while (adjacentElement) {- const targetElement = getVisibleBoundaryBlock(adjacentElement, direction);- if (targetElement) {- return focusResolvedRegion(protyle, targetElement, direction, goalX);- }- adjacentElement = getAdjacentVisibleBlock(adjacentElement, direction);+ const targetElement = getAdjacentVerticalBlock(sourceElement, direction);+ if (targetElement) {+ return focusResolvedRegion(protyle, targetElement, direction, goalX);}if (isInEmbedBlock(sourceElement)) {return "blocked";diff --git a/app/src/protyle/wysiwyg/verticalNavigationState.ts b/app/src/protyle/wysiwyg/verticalNavigationState.tsindex 2ce95488d6..b3aec4d3f9 100644--- a/app/src/protyle/wysiwyg/verticalNavigationState.ts+++ b/app/src/protyle/wysiwyg/verticalNavigationState.ts@@ -3,14 +3,30 @@ export const VERTICAL_NAVIGATION_ATOMIC_CLASS = "protyle-wysiwyg--navigation";export const isAtomicVerticalNavigationTarget = (element: Element) =>!!element.closest(`.${VERTICAL_NAVIGATION_ATOMIC_CLASS}`);-export const isAtomicVerticalNavigationRange = (range: Range) =>- range.collapsed && range.startOffset === 0 && range.startContainer.nodeType === 1 &&- (range.startContainer as Element).classList.contains(VERTICAL_NAVIGATION_ATOMIC_CLASS);+export const getAtomicVerticalNavigationOwner = (range: Range): Element | undefined => {+ if (!range.collapsed || range.startContainer.nodeType !== 1) {+ return;+ }+ const element = range.startContainer as Element;+ if (range.startOffset === 0 && element.classList.contains(VERTICAL_NAVIGATION_ATOMIC_CLASS)) {+ return element;+ }+ const child = element.childNodes?.[range.startOffset];+ if (child?.nodeType === 1 && (child as Element).classList.contains("custom-block") &&+ (child as Element).classList.contains(VERTICAL_NAVIGATION_ATOMIC_CLASS)) {+ return child as Element;+ }+};++export const isAtomicVerticalNavigationRange = (range: Range) => !!getAtomicVerticalNavigationOwner(range);export const shouldKeepAtomicVerticalNavigationTarget = (owner: Element, range: Range) => {if (!range.collapsed) {return false;}+ if (getAtomicVerticalNavigationOwner(range) === owner) {+ return true;+ }if (owner.getAttribute("fold") === "1") {return range.startContainer === owner && range.startOffset === 0;}diff --git a/app/src/protyle/wysiwyg/verticalTarget.ts b/app/src/protyle/wysiwyg/verticalTarget.tsindex 68fe191658..0a40d0e113 100644--- a/app/src/protyle/wysiwyg/verticalTarget.ts+++ b/app/src/protyle/wysiwyg/verticalTarget.ts@@ -79,3 +79,14 @@ export const getVisibleBoundaryBlock = (element: Element, direction: TVerticalDi}return findVisibleBoundaryBlock(element, direction, getEmbedNavigationScope(element), element);};++export const getAdjacentVerticalBlock = (element: Element, direction: TVerticalDirection) => {+ let adjacent = getAdjacentVisibleBlock(element, direction);+ while (adjacent) {+ const target = getVisibleBoundaryBlock(adjacent, direction);+ if (target) {+ return target as HTMLElement;+ }+ adjacent = getAdjacentVisibleBlock(adjacent, direction);+ }+};