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: Harden vertical navigation boundaries https://github.com/siyuan-note/siyuan/issues/19184
Danieldc048f6b8c09
diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.tsindex b05c11c005..0f06ea30a5 100644--- a/app/src/protyle/util/selection.ts+++ b/app/src/protyle/util/selection.ts@@ -16,6 +16,7 @@ import {hasClosestByTag,isInEmbedBlock} from "./hasClosest";+import {isAtomicVerticalNavigationRange} from "../wysiwyg/verticalNavigationState";import {countBlockWord, countSelectWord} from "../../layout/status";import {hideElements} from "../ui/hideElements";import {genRenderFrame} from "../render/util";@@ -202,6 +203,10 @@ export const getEditorRange = (element: Element): Range => {if (getSelection().rangeCount > 0) {range = getSelection().getRangeAt(0);if (element === range.startContainer || element.contains(range.startContainer)) {+ // 纵向导航建立的原子 Range 已是合法位置,读取选区时不能再次聚焦其正文。+ if (isAtomicVerticalNavigationRange(range)) {+ return range;+ }if (range.toString() === "" && range.startContainer.nodeType === 1) {// 有时候点击编辑器头部需要矫正到第一个块中if (range.startOffset === 0 && (range.startContainer as HTMLElement).classList.contains("protyle-wysiwyg")) {diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 3cf84c1475..4761b4776c 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -139,10 +139,10 @@ import {isCaretAtVerticalBoundary} from "./verticalCaret";import {bindVerticalNavigationReset,focusAdjacentVerticalRegion,- isAtomicVerticalNavigationTarget,leaveAVVerticalRegion,prepareVerticalNavigation,} from "./verticalNavigation";+import {isAtomicVerticalNavigationTarget} from "./verticalNavigationState";import {BLOCK_SELECTION_CLASS,clearBlockSelectionMode,@@ -212,7 +212,10 @@ const showSelectAllTip = () => {};const preserveAVSelectionOnKeyup = (protyle: IProtyle, event: KeyboardEvent) => {- const focusedElement = hasClosestBlock(getEditorRange(protyle.wysiwyg.element).startContainer);+ const selection = getSelection();+ const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;+ const focusedElement = range && protyle.wysiwyg.element.contains(range.startContainer) &&+ hasClosestBlock(range.startContainer);if (shouldPreserveAVSelectionOnKeyup(event.key,!!focusedElement && focusedElement.classList.contains("av"))) {protyle.wysiwyg.preventKeyup = true;diff --git a/app/src/protyle/wysiwyg/verticalCaret.test.ts b/app/src/protyle/wysiwyg/verticalCaret.test.tsindex dca4ca8989..5f4242ce36 100644--- a/app/src/protyle/wysiwyg/verticalCaret.test.ts+++ b/app/src/protyle/wysiwyg/verticalCaret.test.ts@@ -1,6 +1,10 @@import {describe, it} from "node:test";import * as assert from "node:assert/strict";-import {getNavigableVerticalRects, isCaretRectAtVerticalBoundary} from "./verticalGeometry";+import {+ getNavigableVerticalRects,+ getRectsIntersectingVerticalLine,+ isCaretRectAtVerticalBoundary,+} from "./verticalGeometry";const rect = (top: number, height = 20) => ({top,@@ -48,4 +52,13 @@ describe("vertical caret boundary", () => {assert.deepEqual(navigableRects, rects.slice(0, 2));});++ it("accepts only range context rectangles that reach the target line", () => {+ const lines = [rect(30)];++ assert.deepEqual(getRectsIntersectingVerticalLine([rect(10)], lines), []);+ assert.deepEqual(getRectsIntersectingVerticalLine([rect(10, 40)], lines), [rect(10, 40)]);+ assert.deepEqual(getRectsIntersectingVerticalLine([{...rect(30), right: 10, width: 0}], lines),+ [{...rect(30), right: 10, width: 0}]);+ });});diff --git a/app/src/protyle/wysiwyg/verticalCaret.ts b/app/src/protyle/wysiwyg/verticalCaret.tsindex 0401bc6556..560a61392d 100644--- a/app/src/protyle/wysiwyg/verticalCaret.ts+++ b/app/src/protyle/wysiwyg/verticalCaret.ts@@ -1,5 +1,9 @@import {focusByRange, getSelectionPosition, setFirstNodeRange, setLastNodeRange} from "../util/selection";-import {getNavigableVerticalRects, isCaretRectAtVerticalBoundary} from "./verticalGeometry";+import {+ getNavigableVerticalRects,+ getRectsIntersectingVerticalLine,+ isCaretRectAtVerticalBoundary,+} from "./verticalGeometry";import {getFoldedNavigationOwner, getReachableVerticalRects} from "./verticalVisibility";export type TVerticalDirection = "up" | "down";@@ -16,6 +20,62 @@ 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());+ if (rangeRects.length > 0) {+ return rangeRects;+ }+ 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;+ }+ 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()));+ }+ } 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;+ }+ const probeRange = contextElement.ownerDocument.createRange();+ probeRange.selectNode(node);+ contextRects.push(...Array.from(probeRange.getClientRects()));+ });+ if (contextRects.length === 0) {+ contextRects.push(...Array.from(container.getClientRects()));+ }+ } else {+ contextRects.push(...Array.from(contextElement.getClientRects()));+ }+ return contextRects;+};++const getRangeRectsOnLine = (element: Element, range: Range, lineRects: DOMRect[]) => {+ const contextElement = getRangeContextElement(range);+ if (!contextElement || !element.contains(contextElement)) {+ return [];+ }+ return getRectsIntersectingVerticalLine(+ getReachableVerticalRects(contextElement, getRangeContextRects(range, contextElement)), lineRects);+};+const getCodeTrailingBlankLineCount = (element: Element) => {if (!element.closest(".code-block")) {return;@@ -85,10 +145,11 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirecconst 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);- if (pointRange && element.contains(pointRange.startContainer) &&- getReachableVerticalRects(element, Array.from(pointRange.getClientRects())).length > 0 &&- isCaretHitReachable(element, Array.from(pointRange.getClientRects())) &&- (!isZeroWidthLine ||+ const pointRangeRects = pointRange ? getRangeRectsOnLine(element, pointRange, lineRects) : [];+ const pointRangeHasOwnRects = !!pointRange && pointRange.getClientRects().length > 0;+ if (pointRange && element.contains(pointRange.startContainer) && pointRangeRects.length > 0 &&+ isCaretHitReachable(element, pointRangeHasOwnRects ? pointRangeRects : lineRects) &&+ (!isZeroWidthLine || !pointRangeHasOwnRects ||isCaretRectAtVerticalBoundary(getSelectionPosition(element, pointRange).top, lineRects, "up"))) {pointRange.collapse(true);focusByRange(pointRange);@@ -113,10 +174,16 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirecconst caretRects = Array.from(range.getClientRects());let reachableRects: DOMRect[];if (caretRects.length > 0) {- reachableRects = getReachableVerticalRects(element, caretRects);+ reachableRects = lineRects.length > 0 ? getRangeRectsOnLine(element, range, lineRects) :+ getReachableVerticalRects(element, caretRects);if (reachableRects.length === 0) {return false;}+ } else if (lineRects.length > 0) {+ reachableRects = getRangeRectsOnLine(element, range, lineRects);+ if (reachableRects.length === 0 || !isCaretHitReachable(element, lineRects)) {+ return false;+ }} else if (element.textContent || element.querySelector("br, img, .render-node")) {return false;} else {diff --git a/app/src/protyle/wysiwyg/verticalGeometry.ts b/app/src/protyle/wysiwyg/verticalGeometry.tsindex f470dbd5de..c4645b0bb1 100644--- a/app/src/protyle/wysiwyg/verticalGeometry.ts+++ b/app/src/protyle/wysiwyg/verticalGeometry.ts@@ -9,6 +9,11 @@ interface IVerticalRect {width: number;}+export const getRectsIntersectingVerticalLine = <T extends IVerticalRect>(rects: T[], lineRects: IVerticalRect[]) =>+ rects.filter(rect => lineRects.some(lineRect =>+ Math.min(rect.bottom, lineRect.bottom) - Math.max(rect.top, lineRect.top) > 0.5+ ));+export const getNavigableVerticalRects = <T extends IVerticalRect>(rects: T[],maxTrailingZeroWidthLines?: number) => {const navigableRects = rects.filter(rect => rect.height > 0.5);diff --git a/app/src/protyle/wysiwyg/verticalNavigation.ts b/app/src/protyle/wysiwyg/verticalNavigation.tsindex e23d238aaa..3edd08cc86 100644--- a/app/src/protyle/wysiwyg/verticalNavigation.ts+++ b/app/src/protyle/wysiwyg/verticalNavigation.ts@@ -7,8 +7,7 @@ import {focusAVTitleByVerticalArrow, focusAVVerticalRegion} from "../render/av/fimport {getAdjacentVisibleBlock, getVisibleBoundaryBlock, isVerticalNavigationElementVisible} from "./verticalTarget";import {getHostVerticalRegion, getHostVerticalTitleRegion, IHostVerticalRegion} from "./verticalRegion";import {getFoldedNavigationOwner} from "./verticalVisibility";--export const VERTICAL_NAVIGATION_ATOMIC_CLASS = "protyle-wysiwyg--navigation";+import {VERTICAL_NAVIGATION_ATOMIC_CLASS} from "./verticalNavigationState";const navigationGoalX = new WeakMap<HTMLElement, number>();const resetBoundEditors = new WeakSet<HTMLElement>();@@ -29,9 +28,23 @@ export const bindVerticalNavigationReset = (editorElement: HTMLElement) => {return;}resetBoundEditors.add(editorElement);- ["pointerdown", "input", "focusout"].forEach(type => {+ ["pointerdown", "input"].forEach(type => {editorElement.addEventListener(type, () => resetVerticalNavigation(editorElement), true);});+ editorElement.addEventListener("focusout", event => {+ clearAtomicFocus(editorElement);+ // 宿主标题与正文间的焦点切换仍属于同一次纵向导航,真正离开当前编辑器后再清除目标列。+ const relatedElement = event.relatedTarget as Element | null;+ if (relatedElement?.closest?.(".protyle-wysiwyg") === editorElement) {+ return;+ }+ queueMicrotask(() => {+ const activeElement = editorElement.ownerDocument.activeElement;+ if (!activeElement?.closest || activeElement.closest(".protyle-wysiwyg") !== editorElement) {+ navigationGoalX.delete(editorElement);+ }+ });+ }, true);};export const prepareVerticalNavigation = (editorElement: HTMLElement, event: KeyboardEvent, range: Range,@@ -49,9 +62,6 @@ export const prepareVerticalNavigation = (editorElement: HTMLElement, event: Keyreturn goalX;};-export const isAtomicVerticalNavigationTarget = (element: Element) =>- !!element.closest(`.${VERTICAL_NAVIGATION_ATOMIC_CLASS}`);-const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, direction: TVerticalDirection) => {if (element.getAttribute("fold") === "1") {const range = document.createRange();diff --git a/app/src/protyle/wysiwyg/verticalNavigationState.test.ts b/app/src/protyle/wysiwyg/verticalNavigationState.test.tsnew file mode 100644index 0000000000..06dbedb5c7--- /dev/null+++ b/app/src/protyle/wysiwyg/verticalNavigationState.test.ts@@ -0,0 +1,40 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ isAtomicVerticalNavigationRange,+ VERTICAL_NAVIGATION_ATOMIC_CLASS,+} from "./verticalNavigationState";++const element = (atomic: boolean) => ({+ nodeType: 1,+ classList: {+ contains: (className: string) => atomic && className === VERTICAL_NAVIGATION_ATOMIC_CLASS,+ },+}) as unknown as Element;++describe("vertical navigation state", () => {+ it("recognizes only the collapsed range placed on the atomic owner", () => {+ const owner = element(true);++ assert.equal(isAtomicVerticalNavigationRange({+ collapsed: true,+ startContainer: owner,+ startOffset: 0,+ } as unknown as Range), true);+ assert.equal(isAtomicVerticalNavigationRange({+ collapsed: true,+ startContainer: owner,+ startOffset: 1,+ } as unknown as Range), false);+ assert.equal(isAtomicVerticalNavigationRange({+ collapsed: true,+ startContainer: element(false),+ startOffset: 0,+ } as unknown as Range), false);+ assert.equal(isAtomicVerticalNavigationRange({+ collapsed: false,+ startContainer: owner,+ startOffset: 0,+ } as unknown as Range), false);+ });+});diff --git a/app/src/protyle/wysiwyg/verticalNavigationState.ts b/app/src/protyle/wysiwyg/verticalNavigationState.tsnew file mode 100644index 0000000000..7962229f9b--- /dev/null+++ b/app/src/protyle/wysiwyg/verticalNavigationState.ts@@ -0,0 +1,8 @@+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);diff --git a/app/src/protyle/wysiwyg/verticalTarget.test.ts b/app/src/protyle/wysiwyg/verticalTarget.test.tsindex 25a8e176ca..6bbbf4723e 100644--- a/app/src/protyle/wysiwyg/verticalTarget.test.ts+++ b/app/src/protyle/wysiwyg/verticalTarget.test.ts@@ -134,4 +134,59 @@ describe("vertical navigation targets", () => {assert.equal(getAdjacentVisibleBlock(asElement(hidden), "down"), false);});++ it("treats custom blocks as opaque regardless of their rendered descendants", () => {+ const custom = block("custom", "NodeCustomBlock").addClass("custom-block");+ const innerEditor = new TestElement().addClass("protyle-wysiwyg");+ const innerFolded = block("inner-folded", "NodeCallout").addClass("callout").setAttribute("fold", "1");+ const innerAtomic = block("inner-atomic", "NodeMathBlock");+ const superBlock = block("super", "NodeSuperBlock").addClass("sb");+ custom.append(innerEditor.append(innerFolded.append(innerAtomic)));+ superBlock.append(custom);++ assert.equal(getVisibleBoundaryBlock(asElement(custom), "down"), asElement(custom));+ assert.equal(getVisibleBoundaryBlock(asElement(custom), "up"), asElement(custom));+ assert.equal(getVisibleBoundaryBlock(asElement(superBlock), "up"), asElement(custom));+ });++ it("navigates to the last descendant within the current editable embed", () => {+ const embed = block("embed", "NodeBlockQueryEmbed");+ const result = new TestElement().addClass("protyle-wysiwyg__embed")+ .setAttribute("data-allow-child-operation", "true");+ const list = block("list", "NodeList").addClass("list");+ const firstItem = block("first-item", "NodeListItem").addClass("li");+ const lastItem = block("last-item", "NodeListItem").addClass("li");+ const first = block("first");+ const last = block("last");+ embed.append(result.append(list.append(firstItem.append(first), lastItem.append(last))));++ assert.equal(getVisibleBoundaryBlock(asElement(list), "down"), asElement(first));+ assert.equal(getVisibleBoundaryBlock(asElement(list), "up"), asElement(last));+ });++ it("keeps adjacent navigation within the current editable embed", () => {+ const embed = block("embed", "NodeBlockQueryEmbed");+ const result = new TestElement().addClass("protyle-wysiwyg__embed")+ .setAttribute("data-allow-child-operation", "true");+ const first = block("first");+ const last = block("last");+ embed.append(result.append(first, last));++ assert.equal(getAdjacentVisibleBlock(asElement(first), "down"), asElement(last));+ assert.equal(getAdjacentVisibleBlock(asElement(last), "down"), false);+ });++ it("stops at a nested embed instead of entering its rendered result", () => {+ const outerEmbed = block("outer-embed", "NodeBlockQueryEmbed");+ const outerResult = new TestElement().addClass("protyle-wysiwyg__embed")+ .setAttribute("data-allow-child-operation", "true");+ const list = block("list", "NodeList").addClass("list");+ const nestedEmbed = block("nested-embed", "NodeBlockQueryEmbed");+ const nestedResult = new TestElement().addClass("protyle-wysiwyg__embed")+ .setAttribute("data-allow-child-operation", "true");+ const nestedContent = block("nested-content");+ outerEmbed.append(outerResult.append(list.append(nestedEmbed.append(nestedResult.append(nestedContent)))));++ assert.equal(getVisibleBoundaryBlock(asElement(list), "up"), asElement(nestedEmbed));+ });});diff --git a/app/src/protyle/wysiwyg/verticalTarget.ts b/app/src/protyle/wysiwyg/verticalTarget.tsindex 530a39d20e..34c7ce67d2 100644--- a/app/src/protyle/wysiwyg/verticalTarget.ts+++ b/app/src/protyle/wysiwyg/verticalTarget.ts@@ -1,5 +1,5 @@import {isInEmbedBlock} from "../util/hasClosest";-import {getNextBlock, getPreviousBlock, isContainerBlock, isNotEditBlock} from "./getBlock";+import {getNextBlock, getPreviousBlock, isContainerBlock} from "./getBlock";import type {TVerticalDirection} from "./verticalCaret";import {getFoldedNavigationOwner, getReachableVerticalRects} from "./verticalVisibility";import {getHostVerticalRegion} from "./verticalRegion";@@ -10,16 +10,21 @@ export const isVerticalNavigationElementVisible = (element: Element) =>const getAdjacentBlock = (element: Element, direction: TVerticalDirection) =>direction === "up" ? getPreviousBlock(element) : getNextBlock(element);+const getEmbedNavigationScope = (element: Element) =>+ element.getAttribute("data-type") === "NodeBlockQueryEmbed" ?+ (element.parentElement ? isInEmbedBlock(element.parentElement, false) : false) :+ isInEmbedBlock(element, false);+export const getAdjacentVisibleBlock = (element: Element, direction: TVerticalDirection) => {if (!isVerticalNavigationElementVisible(element)) {return false;}- const embedElement = isInEmbedBlock(element);+ const embedScope = getEmbedNavigationScope(element);const visited = new Set<Element>();let adjacentElement = getAdjacentBlock(getFoldedNavigationOwner(element) || element, direction);while (adjacentElement && !visited.has(adjacentElement)) {visited.add(adjacentElement);- if (embedElement && isInEmbedBlock(adjacentElement) !== embedElement) {+ if (getEmbedNavigationScope(adjacentElement) !== embedScope) {return false;}if (isVerticalNavigationElementVisible(adjacentElement)) {@@ -30,47 +35,44 @@ export const getAdjacentVisibleBlock = (element: Element, direction: TVerticalDireturn false;};-const getAtomicOwner = (element: Element, boundaryElement: Element) => {- let currentElement: Element | null = element;- while (currentElement && boundaryElement.contains(currentElement)) {- if (currentElement.hasAttribute("data-node-id") && !isContainerBlock(currentElement) &&- isNotEditBlock(currentElement)) {- return currentElement;+const findVisibleBoundaryBlock = (element: Element, direction: TVerticalDirection,+ embedScope: Element | false, boundaryElement: Element): Element | undefined => {+ if (element !== boundaryElement && element.classList.contains("protyle-wysiwyg")) {+ return;+ }+ const isBlock = element.hasAttribute("data-node-id");+ if (isBlock) {+ if (element !== boundaryElement && getEmbedNavigationScope(element) !== embedScope) {+ return;+ }+ if (!isVerticalNavigationElementVisible(element)) {+ return;}- if (currentElement === boundaryElement) {- break;+ const region = getHostVerticalRegion(element);+ // 非容器块属于一个不透明导航区域,不能根据其内部渲染结果改变外部导航目标。+ if (element.getAttribute("fold") === "1" || !isContainerBlock(element) ||+ (direction === "down" && region?.title && isVerticalNavigationElementVisible(region.title))) {+ return element;}- currentElement = currentElement.parentElement?.closest("[data-node-id]") || null;}-};-export const getVisibleBoundaryBlock = (element: Element, direction: TVerticalDirection) => {- const candidateElements = [element, ...Array.from(element.querySelectorAll("[data-node-id]"))];+ const children = Array.from(element.children);if (direction === "up") {- candidateElements.reverse();+ children.reverse();}- const visited = new Set<Element>();- for (const candidateElement of candidateElements) {- if (!candidateElement.hasAttribute("data-node-id")) {- continue;- }- if (candidateElement !== element && isInEmbedBlock(candidateElement)) {- continue;- }- const targetElement = getFoldedNavigationOwner(candidateElement) ||- getAtomicOwner(candidateElement, element) || candidateElement;- if (visited.has(targetElement)) {- continue;- }- visited.add(targetElement);- const region = getHostVerticalRegion(targetElement);- if ((targetElement.getAttribute("fold") === "1" || !isContainerBlock(targetElement) ||- (direction === "down" && region?.title && isVerticalNavigationElementVisible(region.title))) &&- isVerticalNavigationElementVisible(targetElement)) {+ for (const child of children) {+ const targetElement = findVisibleBoundaryBlock(child, direction, embedScope, boundaryElement);+ if (targetElement) {return targetElement;}}- if (isVerticalNavigationElementVisible(element)) {- return element;+ return isBlock ? element : undefined;+};++export const getVisibleBoundaryBlock = (element: Element, direction: TVerticalDirection) => {+ const foldedOwner = getFoldedNavigationOwner(element);+ if (foldedOwner) {+ return isVerticalNavigationElementVisible(foldedOwner) ? foldedOwner : undefined;}+ return findVisibleBoundaryBlock(element, direction, getEmbedNavigationScope(element), element);};