Skip to content

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

:bug: Improve vertical navigation in folded blocks, databases, and tabs https://github.com/siyuan-note/siyuan/issues/19184

Danielbd6dd2c2471d
diff --git a/app/src/protyle/render/av/focus.ts b/app/src/protyle/render/av/focus.ts
index 6eeae15f8d..5ce068391e 100644
--- a/app/src/protyle/render/av/focus.ts
+++ b/app/src/protyle/render/av/focus.ts
@@ -49,16 +49,18 @@ export const focusAVTitleByVerticalArrow = (blockElement: HTMLElement, direction
if (!titleElement) {
return false;
}
+ if (!focusEditableAtGoalX(titleElement, direction, goalX)) {
+ return false;
+ }
clearSelect(["av"], blockElement);
- return focusEditableAtGoalX(titleElement, direction, goalX);
+ return true;
};
export const focusAVVerticalRegion = (blockElement: HTMLElement, direction: TVerticalDirection, goalX: number,
includeTitle = true) => {
const titleElement = includeTitle && getVisibleAVTitle(blockElement);
if (direction === "down" && titleElement) {
- clearSelect(["av"], blockElement);
- return focusEditableAtGoalX(titleElement, direction, goalX);
+ return focusAVTitleByVerticalArrow(blockElement, direction, goalX);
}
if (blockElement.dataset.avType === "table") {
@@ -91,8 +93,7 @@ export const focusAVVerticalRegion = (blockElement: HTMLElement, direction: TVer
}
if (direction === "up" && titleElement) {
- clearSelect(["av"], blockElement);
- return focusEditableAtGoalX(titleElement, direction, goalX);
+ return focusAVTitleByVerticalArrow(blockElement, direction, goalX);
}
return false;
};
diff --git a/app/src/protyle/render/av/keydown.ts b/app/src/protyle/render/av/keydown.ts
index 7fb69067ce..3249ca3b43 100644
--- a/app/src/protyle/render/av/keydown.ts
+++ b/app/src/protyle/render/av/keydown.ts
@@ -20,7 +20,7 @@ import {isMobile} from "../../../util/functions";
import {getAVVerticalNavigationAction} from "./verticalNavigation";
export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyle: IProtyle,
- leaveVerticalRegion: (direction: "up" | "down") => void) => {
+ leaveVerticalRegion: (direction: "up" | "down") => boolean) => {
if (!nodeElement.classList.contains("av") || !window.siyuan.menus.menu.element.classList.contains("fn__none")) {
return false;
}
@@ -210,9 +210,8 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
newCellElement.classList.add("av__cell--select");
addDragFill(newCellElement);
cellScrollIntoView(nodeElement, newCellElement);
- } else {
+ } else if (leaveVerticalRegion("up")) {
clearSelect(["cell"], nodeElement);
- leaveVerticalRegion("up");
}
event.preventDefault();
return true;
@@ -227,9 +226,8 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
newCellElement.classList.add("av__cell--select");
addDragFill(newCellElement);
cellScrollIntoView(nodeElement, newCellElement);
- } else {
+ } else if (leaveVerticalRegion("down")) {
clearSelect(["cell"], nodeElement);
- leaveVerticalRegion("down");
}
event.preventDefault();
return true;
@@ -328,14 +326,14 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
const currentRowElement = selectRowElements[0] as HTMLElement;
const previousRowElement = ensureAVTableAdjacentRow(currentRowElement, "previous") ||
currentRowElement.previousElementSibling as HTMLElement;
- clearSelect(["row", "galleryItem"], nodeElement);
const hasPreviousItem = previousRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]");
if (getAVVerticalNavigationAction(!!hasPreviousItem) === "move") {
+ clearSelect(["row", "galleryItem"], nodeElement);
setAVItemAnchor(nodeElement, previousRowElement as HTMLElement);
selectAVItemRange(nodeElement, previousRowElement);
cellScrollIntoView(nodeElement, previousRowElement);
- } else {
- leaveVerticalRegion("up");
+ } else if (leaveVerticalRegion("up")) {
+ clearSelect(["row", "galleryItem"], nodeElement);
}
event.preventDefault();
return true;
@@ -344,14 +342,14 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyl
const currentRowElement = selectRowElements[selectRowElements.length - 1] as HTMLElement;
const nextRowElement = ensureAVTableAdjacentRow(currentRowElement, "next") ||
currentRowElement.nextElementSibling as HTMLElement;
- clearSelect(["row", "galleryItem"], nodeElement);
const hasNextItem = nextRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]");
if (getAVVerticalNavigationAction(!!hasNextItem) === "move") {
+ clearSelect(["row", "galleryItem"], nodeElement);
setAVItemAnchor(nodeElement, nextRowElement as HTMLElement);
selectAVItemRange(nodeElement, nextRowElement);
cellScrollIntoView(nodeElement, nextRowElement);
- } else {
- leaveVerticalRegion("down");
+ } else if (leaveVerticalRegion("down")) {
+ clearSelect(["row", "galleryItem"], nodeElement);
}
event.preventDefault();
return true;
diff --git a/app/src/protyle/render/tabsRender.ts b/app/src/protyle/render/tabsRender.ts
index 20697a689d..eb068c7924 100644
--- a/app/src/protyle/render/tabsRender.ts
+++ b/app/src/protyle/render/tabsRender.ts
@@ -477,6 +477,23 @@ export const tabsRender = (element: Element, options: ITabsRenderOptions = {}) =
export const destroyTabsRender = (element: Element) => roots.get(element)?.destroy();
+export const setTabTitleNavigationEditing = (item: HTMLElement, editing: boolean) => {
+ for (let root: Element = item; root; root = root.parentElement) {
+ const controller = roots.get(root);
+ if (controller) {
+ const tabs = item.parentElement as HTMLElement;
+ if (item.getAttribute("data-tabs-hidden") !== "false" ||
+ (controller.options.readonly?.(tabs) ?? true)) {
+ return false;
+ }
+ item.dataset.tabsEditing = editing ? "true" : "false";
+ controller.render();
+ return true;
+ }
+ }
+ return false;
+};
+
export const revealTabsForTarget = (target: Element, persist = true) => {
for (let root = target; root; root = root.parentElement) {
if (roots.has(root)) {
diff --git a/app/src/protyle/wysiwyg/calloutCaret.test.ts b/app/src/protyle/wysiwyg/calloutCaret.test.ts
deleted file mode 100644
index d4dc6c55da..0000000000
--- a/app/src/protyle/wysiwyg/calloutCaret.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import {before, describe, it} from "node:test";
-import * as assert from "node:assert/strict";
-
-let getCalloutTitleNavigationTarget: typeof import("./calloutCaret").getCalloutTitleNavigationTarget;
-
-before(async () => {
- Object.assign(globalThis, {
- SIYUAN_VERSION: "test",
- NODE_ENV: "test",
- });
- ({getCalloutTitleNavigationTarget} = await import("./calloutCaret"));
-});
-
-class TestElement {
- nodeType = 1;
- tagName = "DIV";
- nodeName = "DIV";
- parentElement: TestElement | null = null;
- children: TestElement[] = [];
- attributes = new Map<string, string>();
- classes = new Set<string>();
- classList = {
- contains: (className: string) => this.classes.has(className),
- };
-
- 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);
- }
-
- querySelector(selector: string) {
- if (selector !== ":scope > .callout-info > .callout-title") {
- return null;
- }
- const infoElement = this.children.find(element => element.classes.has("callout-info"));
- return infoElement?.children.find(element => element.classes.has("callout-title")) || 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);
-
-const createCallout = () => {
- const editor = new TestElement().addClass("protyle-wysiwyg");
- const callout = block("callout", "NodeCallout").addClass("callout");
- const info = new TestElement().addClass("callout-info");
- const title = new TestElement().addClass("callout-title");
- const content = new TestElement().addClass("callout-content");
- const first = block("first");
- const second = block("second");
- editor.append(callout.append(info.append(title), content.append(first, second)));
- return {editor, callout, title, first, second};
-};
-
-describe("getCalloutTitleNavigationTarget", () => {
- it("moves upward from the first callout content block to the title", () => {
- const {title, first} = createCallout();
-
- assert.equal(getCalloutTitleNavigationTarget(asElement(first), false, "ArrowUp"), asElement(title));
- });
-
- it("keeps upward navigation between callout content blocks unchanged", () => {
- const {second} = createCallout();
-
- 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");
-
- assert.equal(getCalloutTitleNavigationTarget(asElement(previous), asElement(callout), "ArrowDown"),
- asElement(title));
- });
-
- it("finds a callout at the beginning of an adjacent container", () => {
- const {callout, title} = createCallout();
- const list = block("list", "NodeList").addClass("list");
- const item = block("item", "NodeListItem").addClass("li");
- list.append(item.append(callout));
-
- 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
deleted file mode 100644
index b74c86811b..0000000000
--- a/app/src/protyle/wysiwyg/calloutCaret.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import {hasClosestByClassName} from "../util/hasClosest";
-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") {
- const contentElement = hasClosestByClassName(nodeElement, "callout-content");
- if (!contentElement) {
- return;
- }
- const calloutElement = contentElement.parentElement;
- if (!calloutElement?.classList.contains("callout") ||
- getFirstNavigationBlock(contentElement) !== nodeElement) {
- return;
- }
- return getCalloutTitleElement(calloutElement);
- }
-
- if (key === "ArrowDown" && adjacentElement) {
- const firstElement = getFirstNavigationBlock(adjacentElement);
- const calloutElement = adjacentElement.classList.contains("callout") ? adjacentElement :
- firstElement?.classList.contains("callout") ? firstElement : undefined;
- if (calloutElement) {
- return getCalloutTitleElement(calloutElement);
- }
- }
-};
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index dca5d53458..3cf84c1475 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -360,7 +360,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
return;
}
const avHandled = avKeydown(event, nodeElement, protyle, direction => {
- leaveAVVerticalRegion(protyle, nodeElement, direction, verticalGoalX ?? 0);
+ return leaveAVVerticalRegion(protyle, nodeElement, direction, verticalGoalX ?? 0);
});
if (avHandled) {
preserveAVSelectionOnKeyup(protyle, event);
@@ -1040,6 +1040,10 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
event.preventDefault();
return;
}
+ // 原子区域位于文档边界时保持选择,避免原生移动进入其内部。
+ event.stopPropagation();
+ event.preventDefault();
+ return;
}
if (selectText === "" && range.collapsed && (event.key === "ArrowLeft" || event.key === "ArrowRight") &&
moveCaretAcrossSemanticMarker(range, event.key === "ArrowLeft" ? "left" : "right")) {
@@ -1084,6 +1088,9 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
}
if (calloutTitleElement && verticalDirection) {
+ if (range.collapsed && (toPrevious || toNext)) {
+ event.preventDefault();
+ }
return;
}
if (selectText === "" && range.collapsed && !verticalDirection && nodeElement.classList.contains("av") &&
diff --git a/app/src/protyle/wysiwyg/verticalCaret.ts b/app/src/protyle/wysiwyg/verticalCaret.ts
index 861657f254..0401bc6556 100644
--- a/app/src/protyle/wysiwyg/verticalCaret.ts
+++ b/app/src/protyle/wysiwyg/verticalCaret.ts
@@ -1,8 +1,21 @@
-import {focusByRange, getSelectionPosition, setLastNodeRange} from "../util/selection";
+import {focusByRange, getSelectionPosition, setFirstNodeRange, setLastNodeRange} from "../util/selection";
import {getNavigableVerticalRects, isCaretRectAtVerticalBoundary} from "./verticalGeometry";
+import {getFoldedNavigationOwner, getReachableVerticalRects} from "./verticalVisibility";
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 => {
+ 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);
+ return hit && (element.contains(hit) || (!element.textContent && hit === element.parentElement));
+ });
+ });
+};
+
const getCodeTrailingBlankLineCount = (element: Element) => {
if (!element.closest(".code-block")) {
return;
@@ -17,7 +30,8 @@ const getCodeTrailingBlankLineCount = (element: Element) => {
const getContentRects = (element: Element) => {
const range = document.createRange();
range.selectNodeContents(element);
- return getNavigableVerticalRects(Array.from(range.getClientRects()), getCodeTrailingBlankLineCount(element));
+ return getReachableVerticalRects(element,
+ getNavigableVerticalRects(Array.from(range.getClientRects()), getCodeTrailingBlankLineCount(element)));
};
export const isCaretAtVerticalBoundary = (element: Element, range: Range, direction: TVerticalDirection) => {
@@ -57,7 +71,8 @@ const getBoundaryLineRects = (element: Element, direction: TVerticalDirection) =
};
export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirection, goalX: number) => {
- if (getNavigableVerticalRects(Array.from(element.getClientRects())).length === 0) {
+ if (getFoldedNavigationOwner(element) ||
+ getReachableVerticalRects(element, Array.from(element.getClientRects())).length === 0) {
return false;
}
const lineRects = getBoundaryLineRects(element, direction);
@@ -71,6 +86,8 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirec
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 ||
isCaretRectAtVerticalBoundary(getSelectionPosition(element, pointRange).top, lineRects, "up"))) {
pointRange.collapse(true);
@@ -86,8 +103,28 @@ export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirec
}
range.collapse(true);
} else {
- range.selectNodeContents(element);
- range.collapse(direction === "down");
+ if (direction === "down") {
+ setFirstNodeRange(element, range);
+ } else {
+ setLastNodeRange(element, range);
+ }
+ range.collapse(true);
+ }
+ const caretRects = Array.from(range.getClientRects());
+ let reachableRects: DOMRect[];
+ if (caretRects.length > 0) {
+ reachableRects = getReachableVerticalRects(element, caretRects);
+ if (reachableRects.length === 0) {
+ return false;
+ }
+ } else if (element.textContent || element.querySelector("br, img, .render-node")) {
+ return false;
+ } else {
+ reachableRects = getReachableVerticalRects(element, Array.from(element.getClientRects()));
+ }
+ // 屏幕内的回退落点必须实际命中编辑区,屏幕外的合法落点交由滚动逻辑展示。
+ if (!isCaretHitReachable(element, reachableRects)) {
+ return false;
}
focusByRange(range);
return true;
diff --git a/app/src/protyle/wysiwyg/verticalNavigation.ts b/app/src/protyle/wysiwyg/verticalNavigation.ts
index 734a3030cc..e23d238aaa 100644
--- a/app/src/protyle/wysiwyg/verticalNavigation.ts
+++ b/app/src/protyle/wysiwyg/verticalNavigation.ts
@@ -1,11 +1,12 @@
-import {hasClosestByClassName, isInEmbedBlock} from "../util/hasClosest";
-import {focusBlock} from "../util/selection";
+import {isInEmbedBlock} from "../util/hasClosest";
+import {focusBlock, focusByRange} from "../util/selection";
import {scrollCenter} from "../../util/highlightById";
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";
+import {getAdjacentVisibleBlock, getVisibleBoundaryBlock, isVerticalNavigationElementVisible} from "./verticalTarget";
+import {getHostVerticalRegion, getHostVerticalTitleRegion, IHostVerticalRegion} from "./verticalRegion";
+import {getFoldedNavigationOwner} from "./verticalVisibility";
export const VERTICAL_NAVIGATION_ATOMIC_CLASS = "protyle-wysiwyg--navigation";
@@ -49,10 +50,15 @@ export const prepareVerticalNavigation = (editorElement: HTMLElement, event: Key
};
export const isAtomicVerticalNavigationTarget = (element: Element) =>
- element.classList.contains(VERTICAL_NAVIGATION_ATOMIC_CLASS);
+ !!element.closest(`.${VERTICAL_NAVIGATION_ATOMIC_CLASS}`);
const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, direction: TVerticalDirection) => {
- if (!focusBlock(element, undefined, direction === "down")) {
+ if (element.getAttribute("fold") === "1") {
+ const range = document.createRange();
+ range.setStart(element, 0);
+ range.collapse(true);
+ focusByRange(range);
+ } else if (!focusBlock(element, undefined, direction === "down")) {
return false;
}
clearAtomicFocus(editorElement);
@@ -67,7 +73,10 @@ const focusResolvedRegion = (protyle: IProtyle, element: Element | undefined,
}
const targetElement = element as HTMLElement;
let focused = false;
- if (targetElement.classList.contains("av")) {
+ 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 (focused) {
clearAtomicFocus(protyle.wysiwyg.element);
@@ -75,7 +84,8 @@ const focusResolvedRegion = (protyle: IProtyle, element: Element | undefined,
focused = focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);
}
} else {
- const editableElement = getContenteditableElement(targetElement);
+ const editableElement = direction === "down" && region?.title ? region.title :
+ getContenteditableElement(targetElement);
if (editableElement) {
focused = focusEditableAtGoalX(editableElement, direction, goalX);
if (focused) {
@@ -104,54 +114,64 @@ const focusDocumentTitle = (protyle: IProtyle, direction: TVerticalDirection, go
return focused;
};
+const focusHostTitle = (protyle: IProtyle, region: IHostVerticalRegion,
+ direction: TVerticalDirection, goalX: number) => {
+ if (!region.title) {
+ return false;
+ }
+ 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;
+};
+
export const focusAdjacentVerticalRegion = (protyle: IProtyle, sourceElement: HTMLElement,
direction: TVerticalDirection, goalX: number,
sourceNode?: Node) => {
- const calloutTitleElement = sourceNode && hasClosestByClassName(sourceNode, "callout-title");
- if (calloutTitleElement) {
- const calloutElement = hasClosestByClassName(calloutTitleElement, "callout");
- if (calloutElement && direction === "down") {
- const contentElement = calloutElement.querySelector(":scope > .callout-content");
- if (contentElement) {
- 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)) {
+ const foldedOwner = getFoldedNavigationOwner(sourceElement);
+ if (foldedOwner) {
+ sourceElement = foldedOwner as HTMLElement;
+ }
+ const titleRegion = !foldedOwner && sourceNode && getHostVerticalTitleRegion(sourceNode);
+ if (titleRegion) {
+ sourceElement = titleRegion.owner;
+ if (direction === "down") {
+ if (titleRegion.database) {
+ if (focusAVVerticalRegion(sourceElement, direction, goalX, false)) {
return true;
}
+ } else if (titleRegion.content && focusResolvedRegion(protyle,
+ getVisibleBoundaryBlock(titleRegion.content, direction), direction, goalX)) {
+ return true;
}
}
- if (calloutElement) {
- sourceElement = calloutElement;
- }
}
- if (sourceElement.classList.contains("av") && sourceNode &&
- hasClosestByClassName(sourceNode, "av__title")) {
- if (direction === "down" && focusAVVerticalRegion(sourceElement, direction, goalX, false)) {
- return true;
+ // 先跨越宿主正文与标题的区域边界,再查找所有者之外的相邻块。
+ if (direction === "up") {
+ let ancestor = sourceElement.parentElement;
+ 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;
+ }
+ ancestor = ancestor.parentElement;
}
}
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;
diff --git a/app/src/protyle/wysiwyg/verticalRegion.test.ts b/app/src/protyle/wysiwyg/verticalRegion.test.ts
new file mode 100644
index 0000000000..b10c83487c
--- /dev/null
+++ b/app/src/protyle/wysiwyg/verticalRegion.test.ts
@@ -0,0 +1,63 @@
+import {before, describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+
+let getHostVerticalTitleRegion: typeof import("./verticalRegion").getHostVerticalTitleRegion;
+
+before(async () => {
+ Object.assign(globalThis, {SIYUAN_VERSION: "test", NODE_ENV: "test"});
+ ({getHostVerticalTitleRegion} = await import("./verticalRegion"));
+});
+
+class RegionElement {
+ nodeType = 1;
+ parentElement: RegionElement | null = null;
+ title: RegionElement | null = null;
+ content: RegionElement | null = null;
+ constructor(private className: string) {}
+ classList = {contains: (name: string) => this.className === name};
+ querySelector(selector: string) {
+ return selector.includes("title") ? this.title : this.content;
+ }
+ contains(node: RegionElement): boolean {
+ return node === this || !!node.parentElement && this.contains(node.parentElement);
+ }
+}
+
+const region = (name: string, parent?: RegionElement) => {
+ const owner = new RegionElement(name);
+ owner.parentElement = parent || null;
+ owner.title = new RegionElement("callout-title");
+ owner.title.parentElement = owner;
+ owner.content = new RegionElement("content");
+ owner.content.parentElement = owner;
+ return owner;
+};
+
+describe("host vertical title ownership", () => {
+ it("resolves each host title independently of shared title styling", () => {
+ for (const name of ["callout", "tab-item", "av"]) {
+ const owner = region(name);
+ assert.equal(getHostVerticalTitleRegion(owner.title as unknown as Node)?.owner, owner);
+ }
+ });
+
+ it("uses the tab item instead of an enclosing callout", () => {
+ const callout = region("callout");
+ const tab = region("tab-item", callout.content);
+ assert.equal(getHostVerticalTitleRegion(tab.title as unknown as Node)?.owner, tab);
+ });
+
+ it("resolves a title through its paragraph wrapper and formatted text", () => {
+ const tab = region("tab-item");
+ const wrapper = new RegionElement("p");
+ wrapper.parentElement = tab;
+ tab.title.parentElement = wrapper;
+ const text = {nodeType: 3, parentElement: tab.title};
+ assert.equal(getHostVerticalTitleRegion(text as unknown as Node)?.owner, tab);
+ });
+
+ it("does not treat body content as a title", () => {
+ const tab = region("tab-item", region("callout").content);
+ assert.equal(getHostVerticalTitleRegion(tab.content as unknown as Node), undefined);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/verticalRegion.ts b/app/src/protyle/wysiwyg/verticalRegion.ts
new file mode 100644
index 0000000000..74ee071256
--- /dev/null
+++ b/app/src/protyle/wysiwyg/verticalRegion.ts
@@ -0,0 +1,43 @@
+import {setTabTitleNavigationEditing} from "../render/tabsRender";
+
+export interface IHostVerticalRegion {
+ owner: HTMLElement;
+ title: HTMLElement | null;
+ content: HTMLElement | null;
+ database: boolean;
+ setTitleEditing?: (editing: boolean) => boolean;
+}
+
+const hostRegions = [
+ {className: "callout", title: ":scope > .callout-info > .callout-title", content: ":scope > .callout-content"},
+ {className: "tab-item", title: ":scope > .tab-item-info > .tab-item-title, " +
+ ":scope > .tab-item-info > [tabs-title] > .tab-item-title", content: ":scope > .tab-item-content"},
+ {className: "av", title: ".av__title", content: ""},
+];
+
+export const getHostVerticalRegion = (element: Element): IHostVerticalRegion | undefined => {
+ const descriptor = hostRegions.find(item => element.classList.contains(item.className));
+ if (!descriptor) {
+ return;
+ }
+ return {
+ owner: element as HTMLElement,
+ title: element.querySelector<HTMLElement>(descriptor.title),
+ content: descriptor.content ? element.querySelector<HTMLElement>(descriptor.content) : null,
+ database: descriptor.className === "av",
+ setTitleEditing: descriptor.className === "tab-item" ?
+ editing => setTabTitleNavigationEditing(element as HTMLElement, editing) : undefined,
+ };
+};
+
+export const getHostVerticalTitleRegion = (node: Node): IHostVerticalRegion | undefined => {
+ const element = node.nodeType === 3 ? node.parentElement : node as Element;
+ let ancestor: Element | null = element;
+ while (ancestor && !ancestor.classList.contains("protyle-wysiwyg")) {
+ const region = getHostVerticalRegion(ancestor);
+ if (region) {
+ return region.title?.contains(node) ? region : undefined;
+ }
+ ancestor = ancestor.parentElement;
+ }
+};
diff --git a/app/src/protyle/wysiwyg/verticalTarget.test.ts b/app/src/protyle/wysiwyg/verticalTarget.test.ts
index 1548f664e7..25a8e176ca 100644
--- a/app/src/protyle/wysiwyg/verticalTarget.test.ts
+++ b/app/src/protyle/wysiwyg/verticalTarget.test.ts
@@ -101,7 +101,7 @@ const block = (id: string, type = "NodeParagraph") => new TestElement()
.setAttribute("data-type", type);
describe("vertical navigation targets", () => {
- it("enters a folded list through its last visible leaf", () => {
+ it("enters a folded list item as one navigation region", () => {
const list = block("list", "NodeList").addClass("list");
const item = block("item", "NodeListItem").addClass("li").setAttribute("fold", "1");
const summary = block("summary");
@@ -109,7 +109,7 @@ describe("vertical navigation targets", () => {
hidden.visible = false;
list.append(item.append(summary, hidden));
- assert.equal(getVisibleBoundaryBlock(asElement(list), "up"), asElement(summary));
+ assert.equal(getVisibleBoundaryBlock(asElement(list), "up"), asElement(item));
});
it("skips hidden folded descendants when leaving the visible summary", () => {
diff --git a/app/src/protyle/wysiwyg/verticalTarget.ts b/app/src/protyle/wysiwyg/verticalTarget.ts
index adf3b84446..530a39d20e 100644
--- a/app/src/protyle/wysiwyg/verticalTarget.ts
+++ b/app/src/protyle/wysiwyg/verticalTarget.ts
@@ -1,9 +1,11 @@
import {isInEmbedBlock} from "../util/hasClosest";
import {getNextBlock, getPreviousBlock, isContainerBlock, isNotEditBlock} from "./getBlock";
import type {TVerticalDirection} from "./verticalCaret";
+import {getFoldedNavigationOwner, getReachableVerticalRects} from "./verticalVisibility";
+import {getHostVerticalRegion} from "./verticalRegion";
export const isVerticalNavigationElementVisible = (element: Element) =>
- Array.from(element.getClientRects()).some(rect => rect.height > 0.5 || rect.width > 0.5);
+ getReachableVerticalRects(element, Array.from(element.getClientRects())).length > 0;
const getAdjacentBlock = (element: Element, direction: TVerticalDirection) =>
direction === "up" ? getPreviousBlock(element) : getNextBlock(element);
@@ -14,7 +16,7 @@ export const getAdjacentVisibleBlock = (element: Element, direction: TVerticalDi
}
const embedElement = isInEmbedBlock(element);
const visited = new Set<Element>();
- let adjacentElement = getAdjacentBlock(element, direction);
+ let adjacentElement = getAdjacentBlock(getFoldedNavigationOwner(element) || element, direction);
while (adjacentElement && !visited.has(adjacentElement)) {
visited.add(adjacentElement);
if (embedElement && isInEmbedBlock(adjacentElement) !== embedElement) {
@@ -49,15 +51,22 @@ export const getVisibleBoundaryBlock = (element: Element, direction: TVerticalDi
}
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 = getAtomicOwner(candidateElement, element) || candidateElement;
+ const targetElement = getFoldedNavigationOwner(candidateElement) ||
+ getAtomicOwner(candidateElement, element) || candidateElement;
if (visited.has(targetElement)) {
continue;
}
visited.add(targetElement);
- if (!isContainerBlock(targetElement) && isVerticalNavigationElementVisible(targetElement)) {
+ const region = getHostVerticalRegion(targetElement);
+ if ((targetElement.getAttribute("fold") === "1" || !isContainerBlock(targetElement) ||
+ (direction === "down" && region?.title && isVerticalNavigationElementVisible(region.title))) &&
+ isVerticalNavigationElementVisible(targetElement)) {
return targetElement;
}
}
diff --git a/app/src/protyle/wysiwyg/verticalVisibility.ts b/app/src/protyle/wysiwyg/verticalVisibility.ts
new file mode 100644
index 0000000000..2553faedc6
--- /dev/null
+++ b/app/src/protyle/wysiwyg/verticalVisibility.ts
@@ -0,0 +1,42 @@
+// 滚动区域外的内容仍可通过滚动到达;隐藏裁剪与折叠区域则限制合法落点。
+export const getReachableVerticalRects = (element: Element, rects: DOMRect[]) => {
+ let result = rects.filter(rect => rect.height > 0.5);
+ const view = element.ownerDocument?.defaultView;
+ if (!view) {
+ return result;
+ }
+ let ancestor: Element | null = element;
+ while (ancestor && result.length > 0) {
+ const style = view.getComputedStyle(ancestor);
+ if (style.visibility === "hidden" || style.visibility === "collapse" || style.display === "none") {
+ return [];
+ }
+ const clipX = ["hidden", "clip"].includes(style.overflowX);
+ const clipY = ["hidden", "clip"].includes(style.overflowY);
+ if (clipX || clipY) {
+ const bounds = ancestor.getBoundingClientRect();
+ result = result.flatMap(rect => {
+ const left = clipX ? Math.max(rect.left, bounds.left) : rect.left;
+ const right = clipX ? Math.min(rect.right, bounds.right) : rect.right;
+ const top = clipY ? Math.max(rect.top, bounds.top) : rect.top;
+ const bottom = clipY ? Math.min(rect.bottom, bounds.bottom) : rect.bottom;
+ return right >= left && bottom - top > 0.5 ?
+ [new DOMRect(left, top, right - left, bottom - top)] : [];
+ });
+ }
+ ancestor = ancestor.parentElement;
+ }
+ return result;
+};
+
+export const getFoldedNavigationOwner = (element: Element) => {
+ let owner: Element | undefined;
+ let ancestor: Element | null = element;
+ while (ancestor && !ancestor.classList.contains("protyle-wysiwyg")) {
+ if (ancestor.getAttribute("fold") === "1") {
+ owner = ancestor;
+ }
+ ancestor = ancestor.parentElement;
+ }
+ return owner;
+};