Skip to content

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

:bug: Correct vertical navigation at folded and editable boundaries https://github.com/siyuan-note/siyuan/issues/19131

Daniel8e49ee0bfe85
diff --git a/app/src/protyle/wysiwyg/calloutCaret.test.ts b/app/src/protyle/wysiwyg/calloutCaret.test.ts
index 943e5d4976..d4dc6c55da 100644
--- a/app/src/protyle/wysiwyg/calloutCaret.test.ts
+++ b/app/src/protyle/wysiwyg/calloutCaret.test.ts
@@ -106,6 +106,17 @@ describe("getCalloutTitleNavigationTarget", () => {
assert.equal(getCalloutTitleNavigationTarget(asElement(second), false, "ArrowUp"), undefined);
});
+ it("moves upward from the first leaf in a callout container to the title", () => {
+ const {title, first, callout} = createCallout();
+ const content = callout.children[1];
+ const list = block("list", "NodeList").addClass("list");
+ const item = block("item", "NodeListItem").addClass("li");
+ content.children = [];
+ content.append(list.append(item.append(first)));
+
+ assert.equal(getCalloutTitleNavigationTarget(asElement(first), false, "ArrowUp"), asElement(title));
+ });
+
it("moves downward into the title of an adjacent callout", () => {
const {callout, title} = createCallout();
const previous = block("previous");
@@ -123,4 +134,15 @@ describe("getCalloutTitleNavigationTarget", () => {
assert.equal(getCalloutTitleNavigationTarget(asElement(block("previous")), asElement(list), "ArrowDown"),
asElement(title));
});
+
+ it("finds a callout nested through multiple adjacent containers", () => {
+ const {callout, title} = createCallout();
+ const list = block("list", "NodeList").addClass("list");
+ const item = block("item", "NodeListItem").addClass("li");
+ const quote = block("quote", "NodeBlockquote").addClass("bq");
+ list.append(item.append(quote.append(callout)));
+
+ assert.equal(getCalloutTitleNavigationTarget(asElement(block("previous")), asElement(list), "ArrowDown"),
+ asElement(title));
+ });
});
diff --git a/app/src/protyle/wysiwyg/calloutCaret.ts b/app/src/protyle/wysiwyg/calloutCaret.ts
index 802dbf7c75..b74c86811b 100644
--- a/app/src/protyle/wysiwyg/calloutCaret.ts
+++ b/app/src/protyle/wysiwyg/calloutCaret.ts
@@ -1,9 +1,20 @@
import {hasClosestByClassName} from "../util/hasClosest";
-import {getFirstBlock} from "./getBlock";
+import {getFirstBlock, isContainerBlock} from "./getBlock";
const getCalloutTitleElement = (calloutElement: Element) =>
calloutElement.querySelector<HTMLElement>(":scope > .callout-info > .callout-title");
+const getFirstNavigationBlock = (contentElement: Element) => {
+ let blockElement = getFirstBlock(contentElement);
+ const visited = new Set<Element>();
+ while (blockElement !== contentElement && isContainerBlock(blockElement) &&
+ !blockElement.classList.contains("callout") && !visited.has(blockElement)) {
+ visited.add(blockElement);
+ blockElement = getFirstBlock(blockElement);
+ }
+ return blockElement;
+};
+
export const getCalloutTitleNavigationTarget = (nodeElement: Element, adjacentElement: Element | false | undefined,
key: string) => {
if (key === "ArrowUp") {
@@ -13,14 +24,14 @@ export const getCalloutTitleNavigationTarget = (nodeElement: Element, adjacentEl
}
const calloutElement = contentElement.parentElement;
if (!calloutElement?.classList.contains("callout") ||
- getFirstBlock(contentElement) !== nodeElement) {
+ getFirstNavigationBlock(contentElement) !== nodeElement) {
return;
}
return getCalloutTitleElement(calloutElement);
}
if (key === "ArrowDown" && adjacentElement) {
- const firstElement = getFirstBlock(adjacentElement);
+ const firstElement = getFirstNavigationBlock(adjacentElement);
const calloutElement = adjacentElement.classList.contains("callout") ? adjacentElement :
firstElement?.classList.contains("callout") ? firstElement : undefined;
if (calloutElement) {
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index e357f15162..7f6329652e 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -455,10 +455,16 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
event.stopPropagation();
return;
}
- if (event.key.startsWith("Arrow") || event.key === "Home" || event.key === "End") {
+ const isPlainVerticalArrow = ["ArrowUp", "ArrowDown"].includes(event.key) &&
+ !event.altKey && !event.shiftKey && isNotCtrl(event);
+ if ((event.key.startsWith("Arrow") && !isPlainVerticalArrow) ||
+ event.key === "Home" || event.key === "End") {
event.stopPropagation();
return;
}
+ if (isPlainVerticalArrow) {
+ event.stopPropagation();
+ }
}
if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&
@@ -1022,16 +1028,18 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
tdStatus = "last";
}
}
- const nodeEditableElement = (tdElement || getContenteditableElement(nodeElement) || nodeElement) as HTMLElement;
+ const nodeEditableElement = (tdElement || getContenteditableElement(nodeElement, range.startContainer) ||
+ nodeElement) as HTMLElement;
const verticalDirection = event.key === "ArrowUp" ? "up" : event.key === "ArrowDown" ? "down" : undefined;
if (selectText === "" && range.collapsed && verticalDirection &&
isAtomicVerticalNavigationTarget(nodeElement)) {
- focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,
- range.startContainer);
- preserveAVSelectionOnKeyup(protyle, event);
- event.stopPropagation();
- event.preventDefault();
- return;
+ if (focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,
+ range.startContainer)) {
+ preserveAVSelectionOnKeyup(protyle, event);
+ event.stopPropagation();
+ event.preventDefault();
+ return;
+ }
}
if (selectText === "" && range.collapsed && (event.key === "ArrowLeft" || event.key === "ArrowRight") &&
moveCaretAcrossSemanticMarker(range, event.key === "ArrowLeft" ? "left" : "right")) {
@@ -1067,11 +1075,15 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
const toNext = (event.key === "ArrowDown" && isLastLine) ||
(event.key === "ArrowRight" && isEnd);
if (selectText === "" && range.collapsed && verticalDirection && (toPrevious || toNext)) {
- focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,
- range.startContainer);
- preserveAVSelectionOnKeyup(protyle, event);
- event.stopPropagation();
- event.preventDefault();
+ if (focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,
+ range.startContainer)) {
+ preserveAVSelectionOnKeyup(protyle, event);
+ event.stopPropagation();
+ event.preventDefault();
+ return;
+ }
+ }
+ if (calloutTitleElement && verticalDirection) {
return;
}
if (selectText === "" && range.collapsed && !verticalDirection && nodeElement.classList.contains("av") &&
diff --git a/app/src/protyle/wysiwyg/verticalCaret.test.ts b/app/src/protyle/wysiwyg/verticalCaret.test.ts
index b7ba272f72..dca4ca8989 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.test.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.test.ts
@@ -1,6 +1,6 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {isCaretRectAtVerticalBoundary} from "./verticalGeometry";
+import {getNavigableVerticalRects, isCaretRectAtVerticalBoundary} from "./verticalGeometry";
const rect = (top: number, height = 20) => ({
top,
@@ -32,4 +32,20 @@ describe("vertical caret boundary", () => {
assert.equal(isCaretRectAtVerticalBoundary(0, [], "up"), true);
assert.equal(isCaretRectAtVerticalBoundary(0, [], "down"), true);
});
+
+ it("keeps zero-width visual lines navigable", () => {
+ const rects = [rect(10), {...rect(30), right: 10, width: 0}];
+ const navigableRects = getNavigableVerticalRects(rects);
+
+ assert.equal(navigableRects.length, 2);
+ assert.equal(isCaretRectAtVerticalBoundary(10, navigableRects, "down"), false);
+ assert.equal(isCaretRectAtVerticalBoundary(30, navigableRects, "down"), true);
+ });
+
+ it("removes only the technical trailing line from code blocks", () => {
+ const rects = [rect(10), {...rect(30), right: 10, width: 0}, {...rect(50), right: 10, width: 0}];
+ const navigableRects = getNavigableVerticalRects(rects, 1);
+
+ assert.deepEqual(navigableRects, rects.slice(0, 2));
+ });
});
diff --git a/app/src/protyle/wysiwyg/verticalCaret.ts b/app/src/protyle/wysiwyg/verticalCaret.ts
index a68c3b8a76..861657f254 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.ts
@@ -1,16 +1,23 @@
-import {focusByRange, getSelectionPosition} from "../util/selection";
-import {isCaretRectAtVerticalBoundary} from "./verticalGeometry";
+import {focusByRange, getSelectionPosition, setLastNodeRange} from "../util/selection";
+import {getNavigableVerticalRects, isCaretRectAtVerticalBoundary} from "./verticalGeometry";
export type TVerticalDirection = "up" | "down";
-const getVisibleRects = (range: Range) => Array.from(range.getClientRects()).filter(rect =>
- rect.height > 0.5 && rect.width > 0.5
-);
+const getCodeTrailingBlankLineCount = (element: Element) => {
+ if (!element.closest(".code-block")) {
+ return;
+ }
+ const trailingNewlineCount = element.textContent.match(/\n+$/)?.[0].length || 0;
+ if (trailingNewlineCount === 0) {
+ return;
+ }
+ return Math.max(0, trailingNewlineCount - 1);
+};
const getContentRects = (element: Element) => {
const range = document.createRange();
range.selectNodeContents(element);
- return getVisibleRects(range);
+ return getNavigableVerticalRects(Array.from(range.getClientRects()), getCodeTrailingBlankLineCount(element));
};
export const isCaretAtVerticalBoundary = (element: Element, range: Range, direction: TVerticalDirection) => {
@@ -50,7 +57,9 @@ const getBoundaryLineRects = (element: Element, direction: TVerticalDirection) =
};
export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirection, goalX: number) => {
- const elementRect = element.getBoundingClientRect();
+ if (getNavigableVerticalRects(Array.from(element.getClientRects())).length === 0) {
+ return false;
+ }
const lineRects = getBoundaryLineRects(element, direction);
const range = document.createRange();
if (lineRects.length > 0 && typeof document.caretRangeFromPoint === "function") {
@@ -60,14 +69,26 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirec
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);
- if (pointRange && element.contains(pointRange.startContainer)) {
+ const isZeroWidthLine = lineRects.every(rect => rect.width <= 0.5);
+ if (pointRange && element.contains(pointRange.startContainer) &&
+ (!isZeroWidthLine ||
+ isCaretRectAtVerticalBoundary(getSelectionPosition(element, pointRange).top, lineRects, "up"))) {
pointRange.collapse(true);
focusByRange(pointRange);
return true;
}
}
- range.selectNodeContents(element);
- range.collapse(direction === "down");
+ if (direction === "up" && getCodeTrailingBlankLineCount(element) !== undefined) {
+ setLastNodeRange(element, range);
+ if (range.startContainer.nodeType === Node.TEXT_NODE && range.startOffset > 0 &&
+ range.startContainer.textContent[range.startOffset - 1] === "\n") {
+ range.setStart(range.startContainer, range.startOffset - 1);
+ }
+ range.collapse(true);
+ } else {
+ range.selectNodeContents(element);
+ range.collapse(direction === "down");
+ }
focusByRange(range);
- return elementRect.height > 0;
+ return true;
};
diff --git a/app/src/protyle/wysiwyg/verticalGeometry.ts b/app/src/protyle/wysiwyg/verticalGeometry.ts
index 828e472b50..f470dbd5de 100644
--- a/app/src/protyle/wysiwyg/verticalGeometry.ts
+++ b/app/src/protyle/wysiwyg/verticalGeometry.ts
@@ -9,6 +9,33 @@ interface IVerticalRect {
width: number;
}
+export const getNavigableVerticalRects = <T extends IVerticalRect>(rects: T[],
+ maxTrailingZeroWidthLines?: number) => {
+ const navigableRects = rects.filter(rect => rect.height > 0.5);
+ if (maxTrailingZeroWidthLines === undefined || navigableRects.length === 0) {
+ return navigableRects;
+ }
+ const lineTops: number[] = [];
+ navigableRects.forEach(rect => {
+ if (!lineTops.some(top => Math.abs(rect.top - top) < 0.5)) {
+ lineTops.push(rect.top);
+ }
+ });
+ lineTops.sort((first, second) => first - second);
+ const trailingZeroWidthLineTops: number[] = [];
+ for (let index = lineTops.length - 1; index >= 0; index--) {
+ const top = lineTops[index];
+ const lineRects = navigableRects.filter(rect => Math.abs(rect.top - top) < 0.5);
+ if (lineRects.some(rect => rect.width > 0.5)) {
+ break;
+ }
+ trailingZeroWidthLineTops.push(top);
+ }
+ const removedLineTops = trailingZeroWidthLineTops.slice(0,
+ Math.max(0, trailingZeroWidthLineTops.length - maxTrailingZeroWidthLines));
+ return navigableRects.filter(rect => !removedLineTops.some(top => Math.abs(rect.top - top) < 0.5));
+};
+
export const isCaretRectAtVerticalBoundary = (caretTop: number, rects: IVerticalRect[],
direction: TVerticalDirection) => {
if (rects.length === 0) {
diff --git a/app/src/protyle/wysiwyg/verticalNavigation.ts b/app/src/protyle/wysiwyg/verticalNavigation.ts
index 6ada67d1be..734a3030cc 100644
--- a/app/src/protyle/wysiwyg/verticalNavigation.ts
+++ b/app/src/protyle/wysiwyg/verticalNavigation.ts
@@ -1,18 +1,11 @@
-import {hasClosestByClassName} from "../util/hasClosest";
+import {hasClosestByClassName, isInEmbedBlock} from "../util/hasClosest";
import {focusBlock} from "../util/selection";
import {scrollCenter} from "../../util/highlightById";
-import {
- getContenteditableElement,
- getFirstBlock,
- getLastBlock,
- getNextBlock,
- getPreviousBlock,
- isContainerBlock,
- isNotEditBlock,
-} from "./getBlock";
+import {getContenteditableElement} from "./getBlock";
import {getCalloutTitleNavigationTarget} from "./calloutCaret";
import {focusEditableAtGoalX, getCaretGoalX, TVerticalDirection} from "./verticalCaret";
import {focusAVTitleByVerticalArrow, focusAVVerticalRegion} from "../render/av/focus";
+import {getAdjacentVisibleBlock, getVisibleBoundaryBlock} from "./verticalTarget";
export const VERTICAL_NAVIGATION_ATOMIC_CLASS = "protyle-wysiwyg--navigation";
@@ -59,45 +52,42 @@ export const isAtomicVerticalNavigationTarget = (element: Element) =>
element.classList.contains(VERTICAL_NAVIGATION_ATOMIC_CLASS);
const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, direction: TVerticalDirection) => {
+ if (!focusBlock(element, undefined, direction === "down")) {
+ return false;
+ }
clearAtomicFocus(editorElement);
element.classList.add(VERTICAL_NAVIGATION_ATOMIC_CLASS);
- focusBlock(element, undefined, direction === "down");
+ return true;
};
-const getAdjacentBlock = (element: Element, direction: TVerticalDirection) =>
- direction === "up" ? getPreviousBlock(element) : getNextBlock(element);
-
-const getBoundaryBlock = (element: Element, direction: TVerticalDirection) => {
- if (element.getAttribute("fold") === "1" || element.classList.contains("av") ||
- (!isContainerBlock(element) && isNotEditBlock(element))) {
- return element;
- }
- const boundaryElement = direction === "up" ? getLastBlock(element) : getFirstBlock(element);
- let parentElement = boundaryElement.parentElement?.closest("[data-node-id]");
- while (parentElement && element.contains(parentElement)) {
- if (!isContainerBlock(parentElement) && isNotEditBlock(parentElement)) {
- return parentElement;
- }
- parentElement = parentElement.parentElement?.closest("[data-node-id]");
+const focusResolvedRegion = (protyle: IProtyle, element: Element | undefined,
+ direction: TVerticalDirection, goalX: number) => {
+ if (!element) {
+ return false;
}
- return boundaryElement;
-};
-
-const focusResolvedRegion = (protyle: IProtyle, element: Element, direction: TVerticalDirection, goalX: number) => {
const targetElement = element as HTMLElement;
- clearAtomicFocus(protyle.wysiwyg.element);
+ let focused = false;
if (targetElement.classList.contains("av")) {
- if (!focusAVVerticalRegion(targetElement, direction, goalX)) {
- focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
+ focused = focusAVVerticalRegion(targetElement, direction, goalX);
+ if (focused) {
+ clearAtomicFocus(protyle.wysiwyg.element);
+ } else {
+ focused = focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
}
} else {
const editableElement = getContenteditableElement(targetElement);
if (editableElement) {
- focusEditableAtGoalX(editableElement, direction, goalX);
+ focused = focusEditableAtGoalX(editableElement, direction, goalX);
+ if (focused) {
+ clearAtomicFocus(protyle.wysiwyg.element);
+ }
} else {
- focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
+ focused = focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
}
}
+ if (!focused) {
+ return false;
+ }
scrollCenter(protyle, targetElement);
return true;
};
@@ -107,8 +97,11 @@ const focusDocumentTitle = (protyle: IProtyle, direction: TVerticalDirection, go
protyle.title.editElement.getClientRects().length === 0) {
return false;
}
- clearAtomicFocus(protyle.wysiwyg.element);
- return focusEditableAtGoalX(protyle.title.editElement, direction, goalX);
+ const focused = focusEditableAtGoalX(protyle.title.editElement, direction, goalX);
+ if (focused) {
+ clearAtomicFocus(protyle.wysiwyg.element);
+ }
+ return focused;
};
export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HTMLElement,
@@ -120,9 +113,18 @@ export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HT
if (calloutElement && direction === "down") {
const contentElement = calloutElement.querySelector(":scope > .callout-content");
if (contentElement) {
- const firstElement = getFirstBlock(contentElement);
- if (firstElement !== contentElement) {
- return focusResolvedRegion(protyle, firstElement, direction, goalX);
+ const nestedCalloutTarget = getCalloutTitleNavigationTarget(sourceElement, contentElement, "ArrowDown");
+ if (nestedCalloutTarget) {
+ const focused = focusEditableAtGoalX(nestedCalloutTarget, direction, goalX);
+ if (focused) {
+ clearAtomicFocus(protyle.wysiwyg.element);
+ scrollCenter(protyle, hasClosestByClassName(nestedCalloutTarget, "callout") || calloutElement);
+ return true;
+ }
+ }
+ const targetElement = getVisibleBoundaryBlock(contentElement, direction);
+ if (targetElement && focusResolvedRegion(protyle, targetElement, direction, goalX)) {
+ return true;
}
}
}
@@ -138,20 +140,28 @@ export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HT
}
}
- const adjacentElement = getAdjacentBlock(sourceElement, direction);
- const calloutTarget = getCalloutTitleNavigationTarget(sourceElement, adjacentElement,
- direction === "up" ? "ArrowUp" : "ArrowDown");
- if (calloutTarget) {
- clearAtomicFocus(protyle.wysiwyg.element);
- focusEditableAtGoalX(calloutTarget, direction, goalX);
- scrollCenter(protyle, hasClosestByClassName(calloutTarget, "callout") || sourceElement);
- return true;
+ let adjacentElement = getAdjacentVisibleBlock(sourceElement, direction);
+ while (adjacentElement) {
+ const calloutTarget = getCalloutTitleNavigationTarget(sourceElement, adjacentElement,
+ direction === "up" ? "ArrowUp" : "ArrowDown");
+ if (calloutTarget) {
+ const focused = focusEditableAtGoalX(calloutTarget, direction, goalX);
+ if (focused) {
+ clearAtomicFocus(protyle.wysiwyg.element);
+ scrollCenter(protyle, hasClosestByClassName(calloutTarget, "callout") || sourceElement);
+ return true;
+ }
+ }
+ const targetElement = getVisibleBoundaryBlock(adjacentElement, direction);
+ if (targetElement && focusResolvedRegion(protyle, targetElement, direction, goalX)) {
+ return true;
+ }
+ adjacentElement = getAdjacentVisibleBlock(adjacentElement, direction);
}
- if (!adjacentElement) {
- focusDocumentTitle(protyle, direction, goalX);
- return true;
+ if (isInEmbedBlock(sourceElement)) {
+ return false;
}
- return focusResolvedRegion(protyle, getBoundaryBlock(adjacentElement, direction), direction, goalX);
+ return focusDocumentTitle(protyle, direction, goalX);
};
export const leaveAVVerticalRegion = (protyle: IProtyle, sourceElement: HTMLElement,
diff --git a/app/src/protyle/wysiwyg/verticalTarget.test.ts b/app/src/protyle/wysiwyg/verticalTarget.test.ts
new file mode 100644
index 0000000000..1548f664e7
--- /dev/null
+++ b/app/src/protyle/wysiwyg/verticalTarget.test.ts
@@ -0,0 +1,137 @@
+import {before, describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+
+let getAdjacentVisibleBlock: typeof import("./verticalTarget").getAdjacentVisibleBlock;
+let getVisibleBoundaryBlock: typeof import("./verticalTarget").getVisibleBoundaryBlock;
+
+before(async () => {
+ Object.assign(globalThis, {
+ SIYUAN_VERSION: "test",
+ NODE_ENV: "test",
+ });
+ ({getAdjacentVisibleBlock, getVisibleBoundaryBlock} = await import("./verticalTarget"));
+});
+
+class TestElement {
+ nodeType = 1;
+ tagName = "DIV";
+ nodeName = "DIV";
+ parentElement: TestElement | null = null;
+ children: TestElement[] = [];
+ attributes = new Map<string, string>();
+ classes = new Set<string>();
+ visible = true;
+ classList = {
+ contains: (className: string) => this.classes.has(className),
+ };
+
+ get previousElementSibling() {
+ const index = this.parentElement?.children.indexOf(this) ?? -1;
+ return index > 0 ? this.parentElement.children[index - 1] : null;
+ }
+
+ get nextElementSibling() {
+ const index = this.parentElement?.children.indexOf(this) ?? -1;
+ return index >= 0 ? this.parentElement.children[index + 1] || null : null;
+ }
+
+ append(...elements: TestElement[]) {
+ elements.forEach(element => {
+ element.parentElement = this;
+ this.children.push(element);
+ });
+ return this;
+ }
+
+ addClass(className: string) {
+ this.classes.add(className);
+ return this;
+ }
+
+ setAttribute(name: string, value: string) {
+ this.attributes.set(name, value);
+ return this;
+ }
+
+ getAttribute(name: string) {
+ return this.attributes.get(name) || null;
+ }
+
+ hasAttribute(name: string) {
+ return this.attributes.has(name);
+ }
+
+ getClientRects() {
+ return this.visible ? [{top: 0, bottom: 20, left: 0, right: 100, height: 20, width: 100}] : [];
+ }
+
+ contains(element: TestElement): boolean {
+ return element === this || this.children.some(child => child.contains(element));
+ }
+
+ closest(selector: string): TestElement | null {
+ if (selector !== "[data-node-id]") {
+ return null;
+ }
+ return this.hasAttribute("data-node-id") ? this : this.parentElement?.closest(selector) || null;
+ }
+
+ querySelectorAll(selector: string) {
+ if (selector !== "[data-node-id]") {
+ return [];
+ }
+ const matches: TestElement[] = [];
+ const visit = (element: TestElement) => {
+ element.children.forEach(child => {
+ if (child.hasAttribute("data-node-id")) {
+ matches.push(child);
+ }
+ visit(child);
+ });
+ };
+ visit(this);
+ return matches;
+ }
+}
+
+const asElement = (element: TestElement) => element as unknown as Element;
+
+const block = (id: string, type = "NodeParagraph") => new TestElement()
+ .setAttribute("data-node-id", id)
+ .setAttribute("data-type", type);
+
+describe("vertical navigation targets", () => {
+ it("enters a folded list through its last visible leaf", () => {
+ const list = block("list", "NodeList").addClass("list");
+ const item = block("item", "NodeListItem").addClass("li").setAttribute("fold", "1");
+ const summary = block("summary");
+ const hidden = block("hidden");
+ hidden.visible = false;
+ list.append(item.append(summary, hidden));
+
+ assert.equal(getVisibleBoundaryBlock(asElement(list), "up"), asElement(summary));
+ });
+
+ it("skips hidden folded descendants when leaving the visible summary", () => {
+ const editor = new TestElement().addClass("protyle-wysiwyg");
+ const list = block("list", "NodeList").addClass("list");
+ const item = block("item", "NodeListItem").addClass("li").setAttribute("fold", "1");
+ const summary = block("summary");
+ const hidden = block("hidden");
+ const after = block("after");
+ hidden.visible = false;
+ editor.append(list.append(item.append(summary, hidden)), after);
+
+ assert.equal(getAdjacentVisibleBlock(asElement(summary), "down"), asElement(after));
+ });
+
+ it("does not navigate from a hidden source", () => {
+ const editor = new TestElement().addClass("protyle-wysiwyg");
+ const hidden = block("hidden");
+ const after = block("after");
+ hidden.visible = false;
+ editor.append(hidden, after);
+
+ assert.equal(getAdjacentVisibleBlock(asElement(hidden), "down"), false);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/verticalTarget.ts b/app/src/protyle/wysiwyg/verticalTarget.ts
new file mode 100644
index 0000000000..adf3b84446
--- /dev/null
+++ b/app/src/protyle/wysiwyg/verticalTarget.ts
@@ -0,0 +1,67 @@
+import {isInEmbedBlock} from "../util/hasClosest";
+import {getNextBlock, getPreviousBlock, isContainerBlock, isNotEditBlock} from "./getBlock";
+import type {TVerticalDirection} from "./verticalCaret";
+
+export const isVerticalNavigationElementVisible = (element: Element) =>
+ Array.from(element.getClientRects()).some(rect => rect.height > 0.5 || rect.width > 0.5);
+
+const getAdjacentBlock = (element: Element, direction: TVerticalDirection) =>
+ direction === "up" ? getPreviousBlock(element) : getNextBlock(element);
+
+export const getAdjacentVisibleBlock = (element: Element, direction: TVerticalDirection) => {
+ if (!isVerticalNavigationElementVisible(element)) {
+ return false;
+ }
+ const embedElement = isInEmbedBlock(element);
+ const visited = new Set<Element>();
+ let adjacentElement = getAdjacentBlock(element, direction);
+ while (adjacentElement && !visited.has(adjacentElement)) {
+ visited.add(adjacentElement);
+ if (embedElement && isInEmbedBlock(adjacentElement) !== embedElement) {
+ return false;
+ }
+ if (isVerticalNavigationElementVisible(adjacentElement)) {
+ return adjacentElement;
+ }
+ adjacentElement = getAdjacentBlock(adjacentElement, direction);
+ }
+ return 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;
+ }
+ if (currentElement === boundaryElement) {
+ break;
+ }
+ 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]"))];
+ if (direction === "up") {
+ candidateElements.reverse();
+ }
+ const visited = new Set<Element>();
+ for (const candidateElement of candidateElements) {
+ if (candidateElement !== element && isInEmbedBlock(candidateElement)) {
+ continue;
+ }
+ const targetElement = getAtomicOwner(candidateElement, element) || candidateElement;
+ if (visited.has(targetElement)) {
+ continue;
+ }
+ visited.add(targetElement);
+ if (!isContainerBlock(targetElement) && isVerticalNavigationElementVisible(targetElement)) {
+ return targetElement;
+ }
+ }
+ if (isVerticalNavigationElementVisible(element)) {
+ return element;
+ }
+};