Skip to content

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

:bug: Refine vertical navigation target handling https://github.com/siyuan-note/siyuan/issues/19184

Daniel02719934aaad
diff --git a/app/src/protyle/render/av/focus.ts b/app/src/protyle/render/av/focus.ts
index 5ce068391e..0513521980 100644
--- a/app/src/protyle/render/av/focus.ts
+++ b/app/src/protyle/render/av/focus.ts
@@ -44,12 +44,12 @@ export const getAVVerticalGoalX = (blockElement: HTMLElement) => {
};
export const focusAVTitleByVerticalArrow = (blockElement: HTMLElement, direction: TVerticalDirection,
- goalX: number) => {
+ goalX: number, scrollBoundary?: Element) => {
const titleElement = getVisibleAVTitle(blockElement);
if (!titleElement) {
return false;
}
- if (!focusEditableAtGoalX(titleElement, direction, goalX)) {
+ if (!focusEditableAtGoalX(titleElement, direction, goalX, scrollBoundary)) {
return false;
}
clearSelect(["av"], blockElement);
@@ -57,10 +57,10 @@ export const focusAVTitleByVerticalArrow = (blockElement: HTMLElement, direction
};
export const focusAVVerticalRegion = (blockElement: HTMLElement, direction: TVerticalDirection, goalX: number,
- includeTitle = true) => {
+ includeTitle = true, scrollBoundary?: Element) => {
const titleElement = includeTitle && getVisibleAVTitle(blockElement);
if (direction === "down" && titleElement) {
- return focusAVTitleByVerticalArrow(blockElement, direction, goalX);
+ return focusAVTitleByVerticalArrow(blockElement, direction, goalX, scrollBoundary);
}
if (blockElement.dataset.avType === "table") {
@@ -93,7 +93,7 @@ export const focusAVVerticalRegion = (blockElement: HTMLElement, direction: TVer
}
if (direction === "up" && titleElement) {
- return focusAVTitleByVerticalArrow(blockElement, direction, goalX);
+ return focusAVTitleByVerticalArrow(blockElement, direction, goalX, scrollBoundary);
}
return false;
};
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index cf5ed0871a..2f8b73733c 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -1035,12 +1035,10 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
const verticalDirection = event.key === "ArrowUp" ? "up" : event.key === "ArrowDown" ? "down" : undefined;
if (selectText === "" && range.collapsed && verticalDirection &&
isAtomicVerticalNavigationTarget(nodeElement)) {
- if (focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,
- range.startContainer)) {
+ const outcome = focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection,
+ verticalGoalX ?? 0, range.startContainer);
+ if (outcome === "moved") {
preserveAVSelectionOnKeyup(protyle, event);
- event.stopPropagation();
- event.preventDefault();
- return;
}
// 原子区域位于文档边界时保持选择,避免原生移动进入其内部。
event.stopPropagation();
@@ -1081,9 +1079,12 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
const toNext = (event.key === "ArrowDown" && isLastLine) ||
(event.key === "ArrowRight" && isEnd);
if (selectText === "" && range.collapsed && verticalDirection && (toPrevious || toNext)) {
- if (focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,
- range.startContainer)) {
- preserveAVSelectionOnKeyup(protyle, event);
+ const outcome = focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection,
+ verticalGoalX ?? 0, range.startContainer);
+ if (outcome !== "none") {
+ if (outcome === "moved") {
+ preserveAVSelectionOnKeyup(protyle, event);
+ }
event.stopPropagation();
event.preventDefault();
return;
diff --git a/app/src/protyle/wysiwyg/verticalCaret.test.ts b/app/src/protyle/wysiwyg/verticalCaret.test.ts
index 5f4242ce36..891a442077 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.test.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.test.ts
@@ -1,8 +1,11 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
+ getCodeTrailingZeroWidthLineLimit,
+ getHorizontalDistanceToRect,
getNavigableVerticalRects,
getRectsIntersectingVerticalLine,
+ getRevealDelta,
isCaretRectAtVerticalBoundary,
} from "./verticalGeometry";
@@ -53,6 +56,17 @@ describe("vertical caret boundary", () => {
assert.deepEqual(navigableRects, rects.slice(0, 2));
});
+ it("keeps the only caret line of an empty code block", () => {
+ const emptyLine = {...rect(10), right: 10, width: 0};
+
+ assert.equal(getCodeTrailingZeroWidthLineLimit("\n"), 1);
+ assert.deepEqual(getNavigableVerticalRects([emptyLine], getCodeTrailingZeroWidthLineLimit("\n")),
+ [emptyLine]);
+ assert.equal(getCodeTrailingZeroWidthLineLimit("x\n"), 0);
+ assert.equal(getCodeTrailingZeroWidthLineLimit("x\n\n"), 1);
+ assert.equal(getCodeTrailingZeroWidthLineLimit("\n\n\n"), 2);
+ });
+
it("accepts only range context rectangles that reach the target line", () => {
const lines = [rect(30)];
@@ -61,4 +75,13 @@ describe("vertical caret boundary", () => {
assert.deepEqual(getRectsIntersectingVerticalLine([{...rect(30), right: 10, width: 0}], lines),
[{...rect(30), right: 10, width: 0}]);
});
+
+ it("calculates the nearest horizontal region and the required reveal distance", () => {
+ assert.equal(getHorizontalDistanceToRect(30, rect(10)), 0);
+ assert.equal(getHorizontalDistanceToRect(5, rect(10)), 5);
+ assert.equal(getHorizontalDistanceToRect(120, rect(10)), 20);
+ assert.equal(getRevealDelta(80, 100, 20, 120), 0);
+ assert.equal(getRevealDelta(10, 30, 20, 120), -10);
+ assert.equal(getRevealDelta(130, 150, 20, 120), 30);
+ });
});
diff --git a/app/src/protyle/wysiwyg/verticalCaret.ts b/app/src/protyle/wysiwyg/verticalCaret.ts
index 560a61392d..7550d5cc24 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.ts
@@ -1,7 +1,9 @@
import {focusByRange, getSelectionPosition, setFirstNodeRange, setLastNodeRange} from "../util/selection";
import {
+ getCodeTrailingZeroWidthLineLimit,
getNavigableVerticalRects,
getRectsIntersectingVerticalLine,
+ getRevealDelta,
isCaretRectAtVerticalBoundary,
} from "./verticalGeometry";
import {getFoldedNavigationOwner, getReachableVerticalRects} from "./verticalVisibility";
@@ -11,7 +13,7 @@ export type TVerticalDirection = "up" | "down";
const isCaretHitReachable = (element: Element, rects: DOMRect[]) => {
const onScreenRects = rects.filter(rect => rect.bottom > 0 && rect.top < window.innerHeight &&
rect.right >= 0 && rect.left < window.innerWidth);
- return onScreenRects.length === 0 || onScreenRects.some(rect => {
+ return onScreenRects.some(rect => {
const y = Math.max(0, Math.min(window.innerHeight - 1, (rect.top + rect.bottom) / 2));
return [rect.left + 0.25, rect.left - 0.25].some(x => {
const hit = document.elementFromPoint(x, y);
@@ -80,11 +82,7 @@ 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);
+ return getCodeTrailingZeroWidthLineLimit(element.textContent);
};
const getContentRects = (element: Element) => {
@@ -130,10 +128,18 @@ const getBoundaryLineRects = (element: Element, direction: TVerticalDirection) =
return rects.filter(rect => Math.abs(rect.top - boundaryTop) <= tolerance);
};
-export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirection, goalX: number) => {
+interface IEditableVerticalNavigationTarget {
+ element: Element;
+ direction: TVerticalDirection;
+ range: Range;
+}
+
+// 目标解析只计算合法 Range,Selection 统一在滚动和复核完成后提交。
+const resolveEditableVerticalNavigationTarget = (element: Element, direction: TVerticalDirection, goalX: number,
+ requireHit: boolean): IEditableVerticalNavigationTarget | undefined => {
if (getFoldedNavigationOwner(element) ||
getReachableVerticalRects(element, Array.from(element.getClientRects())).length === 0) {
- return false;
+ return;
}
const lineRects = getBoundaryLineRects(element, direction);
const range = document.createRange();
@@ -148,12 +154,11 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirec
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) &&
+ (!requireHit || isCaretHitReachable(element, pointRangeHasOwnRects ? pointRangeRects : lineRects)) &&
(!isZeroWidthLine || !pointRangeHasOwnRects ||
isCaretRectAtVerticalBoundary(getSelectionPosition(element, pointRange).top, lineRects, "up"))) {
pointRange.collapse(true);
- focusByRange(pointRange);
- return true;
+ return {element, direction, range: pointRange};
}
}
if (direction === "up" && getCodeTrailingBlankLineCount(element) !== undefined) {
@@ -177,22 +182,81 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirec
reachableRects = lineRects.length > 0 ? getRangeRectsOnLine(element, range, lineRects) :
getReachableVerticalRects(element, caretRects);
if (reachableRects.length === 0) {
- return false;
+ return;
}
} else if (lineRects.length > 0) {
reachableRects = getRangeRectsOnLine(element, range, lineRects);
- if (reachableRects.length === 0 || !isCaretHitReachable(element, lineRects)) {
- return false;
+ if (reachableRects.length === 0) {
+ return;
}
- } else if (element.textContent || element.querySelector("br, img, .render-node")) {
- return false;
+ } else if (element.textContent || element.querySelector("img, .render-node")) {
+ return;
} else {
reachableRects = getReachableVerticalRects(element, Array.from(element.getClientRects()));
}
- // 屏幕内的回退落点必须实际命中编辑区,屏幕外的合法落点交由滚动逻辑展示。
- if (!isCaretHitReachable(element, reachableRects)) {
+ if (requireHit && !isCaretHitReachable(element, reachableRects)) {
+ return;
+ }
+ return {element, direction, range};
+};
+
+const getEditableTargetRects = (target: IEditableVerticalNavigationTarget) => {
+ const lineRects = getBoundaryLineRects(target.element, target.direction);
+ if (lineRects.length > 0) {
+ return lineRects;
+ }
+ const contextElement = getRangeContextElement(target.range);
+ if (contextElement && target.element.contains(contextElement)) {
+ const contextRects = getReachableVerticalRects(contextElement,
+ getRangeContextRects(target.range, contextElement));
+ if (contextRects.length > 0) {
+ return contextRects;
+ }
+ }
+ return getReachableVerticalRects(target.element, Array.from(target.element.getClientRects()));
+};
+
+const revealEditableVerticalNavigationTarget = (target: IEditableVerticalNavigationTarget,
+ boundaryElement?: Element) => {
+ const closestBlock = target.element.closest("[data-node-id]");
+ const scrollBoundary = boundaryElement?.contains(target.element) ? boundaryElement : closestBlock || target.element;
+ let ancestor: Element | null = target.element;
+ while (ancestor) {
+ const scrollElement = ancestor as HTMLElement;
+ const view = ancestor.ownerDocument.defaultView;
+ const style = view?.getComputedStyle(ancestor);
+ const canScrollY = scrollElement.scrollHeight > scrollElement.clientHeight + 1 &&
+ (ancestor === scrollBoundary || ["auto", "scroll", "overlay"].includes(style?.overflowY));
+ if (canScrollY) {
+ const rects = getEditableTargetRects(target);
+ if (rects.length > 0) {
+ const bounds = ancestor.getBoundingClientRect();
+ const viewportTop = bounds.top + scrollElement.clientTop;
+ const delta = getRevealDelta(Math.min(...rects.map(rect => rect.top)),
+ Math.max(...rects.map(rect => rect.bottom)), viewportTop, viewportTop + scrollElement.clientHeight);
+ if (delta !== 0) {
+ scrollElement.scrollTop += delta;
+ }
+ }
+ }
+ if (ancestor === scrollBoundary) {
+ break;
+ }
+ ancestor = ancestor.parentElement;
+ }
+};
+
+export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirection, goalX: number,
+ scrollBoundary?: Element) => {
+ const target = resolveEditableVerticalNavigationTarget(element, direction, goalX, false);
+ if (!target) {
+ return false;
+ }
+ revealEditableVerticalNavigationTarget(target, scrollBoundary);
+ const verifiedTarget = resolveEditableVerticalNavigationTarget(element, direction, goalX, true);
+ if (!verifiedTarget) {
return false;
}
- focusByRange(range);
+ focusByRange(verifiedTarget.range);
return true;
};
diff --git a/app/src/protyle/wysiwyg/verticalGeometry.ts b/app/src/protyle/wysiwyg/verticalGeometry.ts
index c4645b0bb1..9b1e99d38a 100644
--- a/app/src/protyle/wysiwyg/verticalGeometry.ts
+++ b/app/src/protyle/wysiwyg/verticalGeometry.ts
@@ -14,6 +14,36 @@ export const getRectsIntersectingVerticalLine = <T extends IVerticalRect>(rects:
Math.min(rect.bottom, lineRect.bottom) - Math.max(rect.top, lineRect.top) > 0.5
));
+export const getHorizontalDistanceToRect = (x: number, rect: IVerticalRect) => {
+ if (x < rect.left) {
+ return rect.left - x;
+ }
+ if (x > rect.right) {
+ return x - rect.right;
+ }
+ return 0;
+};
+
+export const getRevealDelta = (targetStart: number, targetEnd: number, viewportStart: number,
+ viewportEnd: number) => {
+ if (targetStart < viewportStart) {
+ return targetStart - viewportStart;
+ }
+ if (targetEnd > viewportEnd) {
+ return targetEnd - viewportEnd;
+ }
+ return 0;
+};
+
+export const getCodeTrailingZeroWidthLineLimit = (text: string) => {
+ const trailingNewlineCount = text.match(/\n+$/)?.[0].length || 0;
+ if (trailingNewlineCount === 0) {
+ return;
+ }
+ const hasVisiblePrefix = text.substring(0, text.length - trailingNewlineCount).length > 0;
+ return Math.max(hasVisiblePrefix ? 0 : 1, trailingNewlineCount - 1);
+};
+
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.ts
index 3edd08cc86..ea9b981e19 100644
--- a/app/src/protyle/wysiwyg/verticalNavigation.ts
+++ b/app/src/protyle/wysiwyg/verticalNavigation.ts
@@ -4,10 +4,23 @@ import {scrollCenter} from "../../util/highlightById";
import {getContenteditableElement} from "./getBlock";
import {focusEditableAtGoalX, getCaretGoalX, TVerticalDirection} from "./verticalCaret";
import {focusAVTitleByVerticalArrow, focusAVVerticalRegion} from "../render/av/focus";
-import {getAdjacentVisibleBlock, getVisibleBoundaryBlock, isVerticalNavigationElementVisible} from "./verticalTarget";
-import {getHostVerticalRegion, getHostVerticalTitleRegion, IHostVerticalRegion} from "./verticalRegion";
+import {
+ getAdjacentVisibleBlock,
+ getVerticalNavigationScope,
+ getVisibleBoundaryBlock,
+ isVerticalNavigationElementVisible,
+} from "./verticalTarget";
+import {
+ getHostVerticalRegion,
+ getHostVerticalTitleRegion,
+ getTableBoundaryCell,
+ IHostVerticalRegion,
+} from "./verticalRegion";
import {getFoldedNavigationOwner} from "./verticalVisibility";
-import {VERTICAL_NAVIGATION_ATOMIC_CLASS} from "./verticalNavigationState";
+import {
+ shouldKeepAtomicVerticalNavigationTarget,
+ VERTICAL_NAVIGATION_ATOMIC_CLASS,
+} from "./verticalNavigationState";
const navigationGoalX = new WeakMap<HTMLElement, number>();
const resetBoundEditors = new WeakSet<HTMLElement>();
@@ -18,19 +31,34 @@ const clearAtomicFocus = (editorElement: HTMLElement) => {
});
};
-export const resetVerticalNavigation = (editorElement: HTMLElement) => {
+const resetVerticalNavigationGoal = (editorElement: HTMLElement) => {
navigationGoalX.delete(editorElement);
+};
+
+const clearVerticalNavigation = (editorElement: HTMLElement) => {
+ resetVerticalNavigationGoal(editorElement);
clearAtomicFocus(editorElement);
};
+const clearStaleAtomicFocus = (editorElement: HTMLElement) => {
+ const selection = editorElement.ownerDocument.getSelection();
+ const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
+ editorElement.querySelectorAll(`.${VERTICAL_NAVIGATION_ATOMIC_CLASS}`).forEach(item => {
+ if (!range || !shouldKeepAtomicVerticalNavigationTarget(item, range)) {
+ item.classList.remove(VERTICAL_NAVIGATION_ATOMIC_CLASS);
+ }
+ });
+};
+
export const bindVerticalNavigationReset = (editorElement: HTMLElement) => {
if (resetBoundEditors.has(editorElement)) {
return;
}
resetBoundEditors.add(editorElement);
["pointerdown", "input"].forEach(type => {
- editorElement.addEventListener(type, () => resetVerticalNavigation(editorElement), true);
+ editorElement.addEventListener(type, () => clearVerticalNavigation(editorElement), true);
});
+ editorElement.addEventListener("keyup", () => clearStaleAtomicFocus(editorElement), true);
editorElement.addEventListener("focusout", event => {
clearAtomicFocus(editorElement);
// 宿主标题与正文间的焦点切换仍属于同一次纵向导航,真正离开当前编辑器后再清除目标列。
@@ -51,7 +79,7 @@ export const prepareVerticalNavigation = (editorElement: HTMLElement, event: Key
fallbackElement?: Element, preferredGoalX?: number) => {
if (!["ArrowUp", "ArrowDown"].includes(event.key) || event.altKey || event.shiftKey ||
event.metaKey || event.ctrlKey || event.isComposing) {
- resetVerticalNavigation(editorElement);
+ resetVerticalNavigationGoal(editorElement);
return;
}
let goalX = navigationGoalX.get(editorElement);
@@ -76,77 +104,131 @@ const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, dir
return true;
};
-const focusResolvedRegion = (protyle: IProtyle, element: Element | undefined,
- direction: TVerticalDirection, goalX: number) => {
- if (!element) {
+type TVerticalNavigationOutcome = "moved" | "blocked" | "none";
+
+type TVerticalNavigationTarget = {
+ type: "atomic";
+ owner: HTMLElement;
+ scope?: Element;
+} | {
+ type: "database";
+ owner: HTMLElement;
+ scope?: Element;
+} | {
+ type: "text";
+ owner: HTMLElement;
+ editable: Element;
+ scope?: Element;
+ reveal?: () => boolean;
+ rollbackReveal?: () => void;
+};
+
+const resolveBlockVerticalNavigationTarget = (editorElement: HTMLElement, element: HTMLElement,
+ direction: TVerticalDirection, goalX: number): TVerticalNavigationTarget => {
+ const scope = getVerticalNavigationScope(element, editorElement);
+ if (element.getAttribute("fold") === "1") {
+ return {type: "atomic", owner: element, scope};
+ }
+ const region = getHostVerticalRegion(element);
+ if (region?.database) {
+ return {type: "database", owner: element, scope};
+ }
+ let editable = direction === "down" && region?.title ? region.title : getContenteditableElement(element);
+ if (editable?.tagName === "TABLE") {
+ editable = getTableBoundaryCell(editable as HTMLTableElement, direction, goalX);
+ }
+ return editable ? {type: "text", owner: element, editable, scope} :
+ {type: "atomic", owner: element, scope};
+};
+
+const isVerticalNavigationTargetCurrent = (protyle: IProtyle, target: TVerticalNavigationTarget) =>
+ target.owner.isConnected && (!target.scope || target.scope.isConnected &&
+ (target.scope === protyle.wysiwyg.element || protyle.wysiwyg.element.contains(target.scope)) &&
+ target.scope.contains(target.owner)) &&
+ (target.type !== "text" || target.editable.isConnected &&
+ (target.owner === target.editable || target.owner.contains(target.editable)));
+
+// 显现、滚动和 Selection 修改集中在提交阶段,解析阶段不改变编辑器状态。
+const commitVerticalNavigationTarget = (protyle: IProtyle, target: TVerticalNavigationTarget,
+ direction: TVerticalDirection, goalX: number) => {
+ if (!isVerticalNavigationTargetCurrent(protyle, target)) {
return false;
}
- const targetElement = element as HTMLElement;
let focused = false;
- const region = getHostVerticalRegion(targetElement);
- if (targetElement.getAttribute("fold") === "1") {
- focused = focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
- } else if (region?.database) {
- focused = focusAVVerticalRegion(targetElement, direction, goalX);
+ if (target.type === "atomic") {
+ focused = focusAtomicRegion(protyle.wysiwyg.element, target.owner, direction);
+ } else if (target.type === "database") {
+ focused = focusAVVerticalRegion(target.owner, direction, goalX, true, protyle.contentElement);
if (focused) {
clearAtomicFocus(protyle.wysiwyg.element);
} else {
- focused = focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
+ focused = focusAtomicRegion(protyle.wysiwyg.element, target.owner, direction);
}
} else {
- const editableElement = direction === "down" && region?.title ? region.title :
- getContenteditableElement(targetElement);
- if (editableElement) {
- focused = focusEditableAtGoalX(editableElement, direction, goalX);
- if (focused) {
- clearAtomicFocus(protyle.wysiwyg.element);
+ const revealed = !!target.reveal;
+ if (revealed && !target.reveal()) {
+ return false;
+ }
+ if (!isVerticalNavigationTargetCurrent(protyle, target) ||
+ !focusEditableAtGoalX(target.editable, direction, goalX, protyle.contentElement)) {
+ if (revealed) {
+ target.rollbackReveal?.();
}
- } else {
- focused = focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
+ return false;
}
+ clearAtomicFocus(protyle.wysiwyg.element);
+ focused = true;
}
- if (!focused) {
- return false;
+ if (focused && target.scope) {
+ scrollCenter(protyle, target.owner);
}
- scrollCenter(protyle, targetElement);
- return true;
+ return focused;
};
-const focusDocumentTitle = (protyle: IProtyle, direction: TVerticalDirection, goalX: number) => {
+const focusResolvedRegion = (protyle: IProtyle, element: Element | undefined,
+ direction: TVerticalDirection, goalX: number): TVerticalNavigationOutcome => {
+ if (!element) {
+ return "none";
+ }
+ const target = resolveBlockVerticalNavigationTarget(protyle.wysiwyg.element, element as HTMLElement,
+ direction, goalX);
+ return commitVerticalNavigationTarget(protyle, target, direction, goalX) ? "moved" : "blocked";
+};
+
+const focusDocumentTitle = (protyle: IProtyle, direction: TVerticalDirection,
+ goalX: number): TVerticalNavigationOutcome => {
if (direction !== "up" || !protyle.title?.editElement ||
protyle.title.editElement.getClientRects().length === 0) {
- return false;
- }
- const focused = focusEditableAtGoalX(protyle.title.editElement, direction, goalX);
- if (focused) {
- clearAtomicFocus(protyle.wysiwyg.element);
+ return "none";
}
- return focused;
+ const target: TVerticalNavigationTarget = {
+ type: "text",
+ owner: protyle.title.editElement,
+ editable: protyle.title.editElement,
+ };
+ return commitVerticalNavigationTarget(protyle, target, direction, goalX) ? "moved" : "blocked";
};
const focusHostTitle = (protyle: IProtyle, region: IHostVerticalRegion,
- direction: TVerticalDirection, goalX: number) => {
+ direction: TVerticalDirection, goalX: number): TVerticalNavigationOutcome => {
if (!region.title) {
- return false;
+ return "none";
}
const revealTitle = !isVerticalNavigationElementVisible(region.title);
- if (revealTitle && !region.setTitleEditing?.(true)) {
- return false;
- }
- if (!focusEditableAtGoalX(region.title, direction, goalX)) {
- if (revealTitle) {
- region.setTitleEditing?.(false);
- }
- return false;
- }
- clearAtomicFocus(protyle.wysiwyg.element);
- scrollCenter(protyle, region.owner);
- return true;
+ const target: TVerticalNavigationTarget = {
+ type: "text",
+ owner: region.owner,
+ editable: region.title,
+ scope: getVerticalNavigationScope(region.owner, protyle.wysiwyg.element),
+ reveal: revealTitle ? () => !!region.setTitleEditing?.(true) : undefined,
+ rollbackReveal: revealTitle ? () => region.setTitleEditing?.(false) : undefined,
+ };
+ return commitVerticalNavigationTarget(protyle, target, direction, goalX) ? "moved" : "blocked";
};
export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HTMLElement,
direction: TVerticalDirection, goalX: number,
- sourceNode?: Node) => {
+ sourceNode?: Node): TVerticalNavigationOutcome => {
const foldedOwner = getFoldedNavigationOwner(sourceElement);
if (foldedOwner) {
sourceElement = foldedOwner as HTMLElement;
@@ -156,12 +238,14 @@ export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HT
sourceElement = titleRegion.owner;
if (direction === "down") {
if (titleRegion.database) {
- if (focusAVVerticalRegion(sourceElement, direction, goalX, false)) {
- return true;
+ if (focusAVVerticalRegion(sourceElement, direction, goalX, false, protyle.contentElement)) {
+ return "moved";
+ }
+ } else if (titleRegion.content) {
+ const targetElement = getVisibleBoundaryBlock(titleRegion.content, direction);
+ if (targetElement) {
+ return focusResolvedRegion(protyle, targetElement, direction, goalX);
}
- } else if (titleRegion.content && focusResolvedRegion(protyle,
- getVisibleBoundaryBlock(titleRegion.content, direction), direction, goalX)) {
- return true;
}
}
}
@@ -172,9 +256,8 @@ export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HT
while (ancestor && ancestor !== protyle.wysiwyg.element) {
const region = getHostVerticalRegion(ancestor);
if (region?.content?.contains(sourceElement) && region.title &&
- getVisibleBoundaryBlock(region.content, "down") === sourceElement &&
- focusHostTitle(protyle, region, direction, goalX)) {
- return true;
+ getVisibleBoundaryBlock(region.content, "down") === sourceElement) {
+ return focusHostTitle(protyle, region, direction, goalX);
}
ancestor = ancestor.parentElement;
}
@@ -183,21 +266,22 @@ export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HT
let adjacentElement = getAdjacentVisibleBlock(sourceElement, direction);
while (adjacentElement) {
const targetElement = getVisibleBoundaryBlock(adjacentElement, direction);
- if (targetElement && focusResolvedRegion(protyle, targetElement, direction, goalX)) {
- return true;
+ if (targetElement) {
+ return focusResolvedRegion(protyle, targetElement, direction, goalX);
}
adjacentElement = getAdjacentVisibleBlock(adjacentElement, direction);
}
if (isInEmbedBlock(sourceElement)) {
- return false;
+ return "blocked";
}
return focusDocumentTitle(protyle, direction, goalX);
};
export const leaveAVVerticalRegion = (protyle: IProtyle, sourceElement: HTMLElement,
direction: TVerticalDirection, goalX: number) => {
- if (direction === "up" && focusAVTitleByVerticalArrow(sourceElement, direction, goalX)) {
+ if (direction === "up" && focusAVTitleByVerticalArrow(sourceElement, direction, goalX,
+ protyle.contentElement)) {
return true;
}
- return focusAdjacentVerticalRegion(protyle, sourceElement, direction, goalX);
+ return focusAdjacentVerticalRegion(protyle, sourceElement, direction, goalX) === "moved";
};
diff --git a/app/src/protyle/wysiwyg/verticalNavigationState.test.ts b/app/src/protyle/wysiwyg/verticalNavigationState.test.ts
index 06dbedb5c7..878545cc5e 100644
--- a/app/src/protyle/wysiwyg/verticalNavigationState.test.ts
+++ b/app/src/protyle/wysiwyg/verticalNavigationState.test.ts
@@ -2,15 +2,26 @@ import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
isAtomicVerticalNavigationRange,
+ shouldKeepAtomicVerticalNavigationTarget,
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;
+class AtomicElement {
+ nodeType = 1;
+ children = new Set<Node>();
+ constructor(private atomic: boolean, private folded = false) {}
+ classList = {
+ contains: (className: string) => this.atomic && className === VERTICAL_NAVIGATION_ATOMIC_CLASS,
+ };
+ getAttribute(name: string) {
+ return name === "fold" && this.folded ? "1" : null;
+ }
+ contains(node: Node) {
+ return node === this as unknown as Node || this.children.has(node);
+ }
+}
+
+const element = (atomic: boolean, folded = false) => new AtomicElement(atomic, folded) as unknown as Element;
describe("vertical navigation state", () => {
it("recognizes only the collapsed range placed on the atomic owner", () => {
@@ -37,4 +48,40 @@ describe("vertical navigation state", () => {
startOffset: 0,
} as unknown as Range), false);
});
+
+ it("keeps a folded atomic position until the selection actually moves", () => {
+ const owner = element(true, true);
+ const range = {
+ collapsed: true,
+ startContainer: owner,
+ startOffset: 0,
+ } as unknown as Range;
+
+ assert.equal(shouldKeepAtomicVerticalNavigationTarget(owner, range), true);
+ assert.equal(shouldKeepAtomicVerticalNavigationTarget(owner, {
+ ...range,
+ startOffset: 1,
+ } as unknown as Range), false);
+ assert.equal(shouldKeepAtomicVerticalNavigationTarget(owner, {
+ ...range,
+ startContainer: element(false),
+ } as unknown as Range), false);
+ });
+
+ it("keeps a non-folded atomic target while the selection remains inside it", () => {
+ const owner = element(true) as unknown as AtomicElement;
+ const child = element(false) as unknown as Node;
+ owner.children.add(child);
+
+ assert.equal(shouldKeepAtomicVerticalNavigationTarget(owner as unknown as Element, {
+ collapsed: true,
+ startContainer: child,
+ startOffset: 0,
+ } as unknown as Range), true);
+ assert.equal(shouldKeepAtomicVerticalNavigationTarget(owner as unknown as Element, {
+ collapsed: false,
+ startContainer: child,
+ startOffset: 0,
+ } as unknown as Range), false);
+ });
});
diff --git a/app/src/protyle/wysiwyg/verticalNavigationState.ts b/app/src/protyle/wysiwyg/verticalNavigationState.ts
index 7962229f9b..2ce95488d6 100644
--- a/app/src/protyle/wysiwyg/verticalNavigationState.ts
+++ b/app/src/protyle/wysiwyg/verticalNavigationState.ts
@@ -6,3 +6,13 @@ export const isAtomicVerticalNavigationTarget = (element: Element) =>
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 shouldKeepAtomicVerticalNavigationTarget = (owner: Element, range: Range) => {
+ if (!range.collapsed) {
+ return false;
+ }
+ if (owner.getAttribute("fold") === "1") {
+ return range.startContainer === owner && range.startOffset === 0;
+ }
+ return range.startContainer === owner || owner.contains(range.startContainer);
+};
diff --git a/app/src/protyle/wysiwyg/verticalRegion.test.ts b/app/src/protyle/wysiwyg/verticalRegion.test.ts
index b10c83487c..5c5054300f 100644
--- a/app/src/protyle/wysiwyg/verticalRegion.test.ts
+++ b/app/src/protyle/wysiwyg/verticalRegion.test.ts
@@ -2,10 +2,11 @@ import {before, describe, it} from "node:test";
import * as assert from "node:assert/strict";
let getHostVerticalTitleRegion: typeof import("./verticalRegion").getHostVerticalTitleRegion;
+let getTableBoundaryCell: typeof import("./verticalRegion").getTableBoundaryCell;
before(async () => {
Object.assign(globalThis, {SIYUAN_VERSION: "test", NODE_ENV: "test"});
- ({getHostVerticalTitleRegion} = await import("./verticalRegion"));
+ ({getHostVerticalTitleRegion, getTableBoundaryCell} = await import("./verticalRegion"));
});
class RegionElement {
@@ -61,3 +62,73 @@ describe("host vertical title ownership", () => {
assert.equal(getHostVerticalTitleRegion(tab.content as unknown as Node), undefined);
});
});
+
+const layoutRect = (left: number, right: number, top: number, bottom: number) => ({
+ left,
+ right,
+ top,
+ bottom,
+ width: right - left,
+ height: bottom - top,
+});
+
+describe("table vertical regions", () => {
+ it("selects a cell from the boundary row at the horizontal goal", () => {
+ const table = {rows: [], cells: []} as unknown as HTMLTableElement & {
+ rows: HTMLTableRowElement[];
+ cells: HTMLTableCellElement[];
+ };
+ const cell = (left: number, right: number, top: number, bottom: number) => ({
+ classList: {contains: () => false},
+ closest: () => table,
+ getClientRects: () => [layoutRect(left, right, top, bottom)],
+ }) as unknown as HTMLTableCellElement;
+ const row = (top: number, bottom: number, cells: HTMLTableCellElement[]) => ({
+ cells,
+ closest: () => table,
+ getClientRects: () => [layoutRect(0, 200, top, bottom)],
+ }) as unknown as HTMLTableRowElement;
+ const firstLeft = cell(0, 100, 0, 20);
+ const firstRight = cell(100, 200, 0, 20);
+ const lastLeft = cell(0, 100, 20, 40);
+ const lastRight = cell(100, 200, 20, 40);
+ table.rows.push(row(0, 20, [firstLeft, firstRight]), row(20, 40, [lastLeft, lastRight]));
+ table.cells.push(firstLeft, firstRight, lastLeft, lastRight);
+ table.querySelectorAll = (() => table.cells) as unknown as typeof table.querySelectorAll;
+
+ assert.equal(getTableBoundaryCell(table, "down", 160), firstRight);
+ assert.equal(getTableBoundaryCell(table, "up", 160), lastRight);
+ });
+
+ it("includes a row-spanning cell in the last logical row", () => {
+ const table = {rows: [], cells: []} as unknown as HTMLTableElement & {
+ rows: HTMLTableRowElement[];
+ cells: HTMLTableCellElement[];
+ };
+ const spanningCell = {
+ classList: {contains: () => false},
+ closest: () => table,
+ getClientRects: () => [layoutRect(0, 100, 0, 40)],
+ } as unknown as HTMLTableCellElement;
+ const lastCell = {
+ classList: {contains: () => false},
+ closest: () => table,
+ getClientRects: () => [layoutRect(100, 200, 20, 40)],
+ } as unknown as HTMLTableCellElement;
+ const firstRow = {
+ cells: [spanningCell],
+ closest: () => table,
+ getClientRects: () => [layoutRect(0, 200, 0, 20)],
+ } as unknown as HTMLTableRowElement;
+ const lastRow = {
+ cells: [lastCell],
+ closest: () => table,
+ getClientRects: () => [layoutRect(0, 200, 20, 40)],
+ } as unknown as HTMLTableRowElement;
+ table.rows.push(firstRow, lastRow);
+ table.cells.push(spanningCell, lastCell);
+ table.querySelectorAll = (() => table.cells) as unknown as typeof table.querySelectorAll;
+
+ assert.equal(getTableBoundaryCell(table, "up", 50), spanningCell);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/verticalRegion.ts b/app/src/protyle/wysiwyg/verticalRegion.ts
index 74ee071256..2d32ce5f82 100644
--- a/app/src/protyle/wysiwyg/verticalRegion.ts
+++ b/app/src/protyle/wysiwyg/verticalRegion.ts
@@ -1,4 +1,6 @@
import {setTabTitleNavigationEditing} from "../render/tabsRender";
+import type {TVerticalDirection} from "./verticalCaret";
+import {getHorizontalDistanceToRect} from "./verticalGeometry";
export interface IHostVerticalRegion {
owner: HTMLElement;
@@ -41,3 +43,43 @@ export const getHostVerticalTitleRegion = (node: Node): IHostVerticalRegion | un
ancestor = ancestor.parentElement;
}
};
+
+const getLayoutRect = (element: Element) => Array.from(element.getClientRects())
+ .find(rect => rect.width > 0.5 && rect.height > 0.5);
+
+export const getTableBoundaryCell = (table: HTMLTableElement, direction: TVerticalDirection,
+ goalX: number): HTMLTableCellElement | undefined => {
+ const rows = Array.from(table.rows).filter(row => row.closest("table") === table && getLayoutRect(row));
+ const boundaryRow = rows[direction === "down" ? 0 : rows.length - 1];
+ const rowRect = boundaryRow && getLayoutRect(boundaryRow);
+ if (!rowRect) {
+ return;
+ }
+ let cells = Array.from(table.querySelectorAll<HTMLTableCellElement>("th, td")).filter(cell => {
+ if (cell.closest("table") !== table || cell.classList.contains("fn__none")) {
+ return false;
+ }
+ const rect = getLayoutRect(cell);
+ return rect && Math.min(rect.bottom, rowRect.bottom) - Math.max(rect.top, rowRect.top) > 0.5;
+ });
+ if (cells.length === 0) {
+ cells = Array.from(boundaryRow.cells).filter(cell => !cell.classList.contains("fn__none") && getLayoutRect(cell));
+ }
+ let closestCell: HTMLTableCellElement | undefined;
+ let closestDistance = Number.POSITIVE_INFINITY;
+ let closestCenterDistance = Number.POSITIVE_INFINITY;
+ cells.forEach(cell => {
+ const rect = getLayoutRect(cell);
+ if (!rect) {
+ return;
+ }
+ const distance = getHorizontalDistanceToRect(goalX, rect);
+ const centerDistance = Math.abs(goalX - (rect.left + rect.right) / 2);
+ if (distance < closestDistance || (distance === closestDistance && centerDistance < closestCenterDistance)) {
+ closestCell = cell;
+ closestDistance = distance;
+ closestCenterDistance = centerDistance;
+ }
+ });
+ return closestCell;
+};
diff --git a/app/src/protyle/wysiwyg/verticalTarget.test.ts b/app/src/protyle/wysiwyg/verticalTarget.test.ts
index 6bbbf4723e..4052ba9169 100644
--- a/app/src/protyle/wysiwyg/verticalTarget.test.ts
+++ b/app/src/protyle/wysiwyg/verticalTarget.test.ts
@@ -2,6 +2,7 @@ import {before, describe, it} from "node:test";
import * as assert from "node:assert/strict";
let getAdjacentVisibleBlock: typeof import("./verticalTarget").getAdjacentVisibleBlock;
+let getVerticalNavigationScope: typeof import("./verticalTarget").getVerticalNavigationScope;
let getVisibleBoundaryBlock: typeof import("./verticalTarget").getVisibleBoundaryBlock;
before(async () => {
@@ -9,7 +10,7 @@ before(async () => {
SIYUAN_VERSION: "test",
NODE_ENV: "test",
});
- ({getAdjacentVisibleBlock, getVisibleBoundaryBlock} = await import("./verticalTarget"));
+ ({getAdjacentVisibleBlock, getVerticalNavigationScope, getVisibleBoundaryBlock} = await import("./verticalTarget"));
});
class TestElement {
@@ -165,18 +166,21 @@ describe("vertical navigation targets", () => {
});
it("keeps adjacent navigation within the current editable embed", () => {
+ const editor = new TestElement().addClass("protyle-wysiwyg");
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));
+ editor.append(embed.append(result.append(first, last)));
+ assert.equal(getVerticalNavigationScope(asElement(first), asElement(editor) as HTMLElement), asElement(embed));
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 editor = new TestElement().addClass("protyle-wysiwyg");
const outerEmbed = block("outer-embed", "NodeBlockQueryEmbed");
const outerResult = new TestElement().addClass("protyle-wysiwyg__embed")
.setAttribute("data-allow-child-operation", "true");
@@ -185,8 +189,13 @@ describe("vertical navigation targets", () => {
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)))));
+ editor.append(outerEmbed.append(
+ outerResult.append(list.append(nestedEmbed.append(nestedResult.append(nestedContent))))));
assert.equal(getVisibleBoundaryBlock(asElement(list), "up"), asElement(nestedEmbed));
+ assert.equal(getVerticalNavigationScope(asElement(nestedEmbed), asElement(editor) as HTMLElement),
+ asElement(outerEmbed));
+ assert.equal(getVerticalNavigationScope(asElement(nestedContent), asElement(editor) as HTMLElement),
+ asElement(nestedEmbed));
});
});
diff --git a/app/src/protyle/wysiwyg/verticalTarget.ts b/app/src/protyle/wysiwyg/verticalTarget.ts
index 34c7ce67d2..68fe191658 100644
--- a/app/src/protyle/wysiwyg/verticalTarget.ts
+++ b/app/src/protyle/wysiwyg/verticalTarget.ts
@@ -15,6 +15,9 @@ const getEmbedNavigationScope = (element: Element) =>
(element.parentElement ? isInEmbedBlock(element.parentElement, false) : false) :
isInEmbedBlock(element, false);
+export const getVerticalNavigationScope = (element: Element, editorElement: HTMLElement) =>
+ getEmbedNavigationScope(element) || editorElement;
+
export const getAdjacentVisibleBlock = (element: Element, direction: TVerticalDirection) => {
if (!isVerticalNavigationElementVisible(element)) {
return false;