An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Improve vertical navigation across block regions https://github.com/siyuan-note/siyuan/issues/19131
Danielc0e7050fcbe2
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scssindex 05bf7db00f..f1d207ec7e 100644--- a/app/src/assets/scss/protyle/_wysiwyg.scss+++ b/app/src/assets/scss/protyle/_wysiwyg.scss@@ -46,6 +46,12 @@[data-node-id] {position: relative;+ &.protyle-wysiwyg--navigation {+ outline: 2px solid var(--b3-theme-primary-lighter);+ outline-offset: -2px;+ border-radius: var(--b3-border-radius);+ }+&[data-type="NodeHeading"] {& > .protyle-heading-number__measure {position: absolute;diff --git a/app/src/protyle/render/av/focus.ts b/app/src/protyle/render/av/focus.tsindex e0d0b9e5da..6eeae15f8d 100644--- a/app/src/protyle/render/av/focus.ts+++ b/app/src/protyle/render/av/focus.ts@@ -3,9 +3,100 @@ import {clearSelect} from "../../util/clear";import {focusBlock, focusByRange} from "../../util/selection";import {getFirstBlock, getLastBlock, getNextBlock, getPreviousBlock} from "../../wysiwyg/getBlock";import {scrollCenter} from "../../../util/highlightById";+import {focusEditableAtGoalX, TVerticalDirection} from "../../wysiwyg/verticalCaret";+import {selectAVItemRange, setAVItemAnchor} from "./rangeSelect";const isForwardArrow = (key: string) => key === "ArrowDown" || key === "ArrowRight";+const getVisibleAVTitle = (blockElement: HTMLElement) => {+ const titleElement = Array.from(blockElement.querySelectorAll<HTMLElement>(".av__title:not(.fn__none)")).find(item =>+ item.closest(".av") === blockElement+ );+ return titleElement?.getClientRects().length > 0 ? titleElement : undefined;+};++const getOwnVisibleElements = (blockElement: HTMLElement, selector: string) =>+ Array.from(blockElement.querySelectorAll<HTMLElement>(selector)).filter(item =>+ item.closest(".av") === blockElement && item.getClientRects().length > 0+ );++const getClosestCell = (rowElement: HTMLElement, goalX: number) => {+ const cells = Array.from(rowElement.querySelectorAll<HTMLElement>(".av__cell")).filter(item =>+ item.getClientRects().length > 0+ );+ return cells.reduce((closest, item) => {+ const rect = item.getBoundingClientRect();+ const distance = goalX < rect.left ? rect.left - goalX : goalX > rect.right ? goalX - rect.right : 0;+ return !closest || distance < closest.distance ? {element: item, distance} : closest;+ }, undefined as { element: HTMLElement, distance: number } | undefined)?.element;+};++export const getAVVerticalGoalX = (blockElement: HTMLElement) => {+ const selectedElement = Array.from(blockElement.querySelectorAll<HTMLElement>(+ ".av__cell--select, .av__cell--active, .av__row--select, .av__gallery-item--select")).find(item =>+ item.closest(".av") === blockElement+ );+ if (!selectedElement) {+ return;+ }+ const rect = selectedElement.getBoundingClientRect();+ return rect.left + rect.width / 2;+};++export const focusAVTitleByVerticalArrow = (blockElement: HTMLElement, direction: TVerticalDirection,+ goalX: number) => {+ const titleElement = getVisibleAVTitle(blockElement);+ if (!titleElement) {+ return false;+ }+ clearSelect(["av"], blockElement);+ return focusEditableAtGoalX(titleElement, direction, goalX);+};++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);+ }++ if (blockElement.dataset.avType === "table") {+ const rows = getOwnVisibleElements(blockElement, ".av__row[data-id]:not(.av__row--header)");+ const rowElement = rows[direction === "down" ? 0 : rows.length - 1];+ const cellElement = rowElement && getClosestCell(rowElement, goalX);+ if (cellElement) {+ if (!focusBlock(blockElement)) {+ return false;+ }+ clearSelect(["av"], blockElement);+ cellElement.classList.add("av__cell--select");+ addDragFill(cellElement);+ cellScrollIntoView(blockElement, cellElement);+ return true;+ }+ } else {+ const items = getOwnVisibleElements(blockElement, ".av__gallery-item[data-id]");+ const itemElement = items[direction === "down" ? 0 : items.length - 1];+ if (itemElement) {+ if (!focusBlock(blockElement)) {+ return false;+ }+ clearSelect(["av"], blockElement);+ setAVItemAnchor(blockElement, itemElement);+ selectAVItemRange(blockElement, itemElement);+ cellScrollIntoView(blockElement, itemElement);+ return true;+ }+ }++ if (direction === "up" && titleElement) {+ clearSelect(["av"], blockElement);+ return focusEditableAtGoalX(titleElement, direction, goalX);+ }+ return false;+};+export const focusAVByArrow = (protyle: IProtyle, blockElement: HTMLElement, key: string, skipTitle = false) => {if (!["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(key) ||!blockElement.querySelector(".av__cursor")) {diff --git a/app/src/protyle/render/av/keydown.ts b/app/src/protyle/render/av/keydown.tsindex 7904f1a86b..7fb69067ce 100644--- a/app/src/protyle/render/av/keydown.ts+++ b/app/src/protyle/render/av/keydown.ts@@ -17,8 +17,10 @@ import {} from "./rangeSelect";import {getAVCellSelection, getAVItemSelection} from "./selectionState";import {isMobile} from "../../../util/functions";+import {getAVVerticalNavigationAction} from "./verticalNavigation";-export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyle: IProtyle) => {+export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protyle: IProtyle,+ leaveVerticalRegion: (direction: "up" | "down") => void) => {if (!nodeElement.classList.contains("av") || !window.siyuan.menus.menu.element.classList.contains("fn__none")) {return false;}@@ -203,11 +205,14 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylif (previousRowElement && !previousRowElement.classList.contains("av__row--header")) {newCellElement = previousRowElement.querySelector(`.av__cell[data-col-id="${selectCellElement.dataset.colId}"]`);}- if (newCellElement) {+ if (getAVVerticalNavigationAction(!!newCellElement) === "move") {clearSelect(["cell"], nodeElement);newCellElement.classList.add("av__cell--select");addDragFill(newCellElement);cellScrollIntoView(nodeElement, newCellElement);+ } else {+ clearSelect(["cell"], nodeElement);+ leaveVerticalRegion("up");}event.preventDefault();return true;@@ -217,11 +222,14 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylif (nextRowElement && !nextRowElement.classList.contains("av__row--footer")) {newCellElement = nextRowElement.querySelector(`.av__cell[data-col-id="${selectCellElement.dataset.colId}"]`);}- if (newCellElement) {+ if (getAVVerticalNavigationAction(!!newCellElement) === "move") {clearSelect(["cell"], nodeElement);newCellElement.classList.add("av__cell--select");addDragFill(newCellElement);cellScrollIntoView(nodeElement, newCellElement);+ } else {+ clearSelect(["cell"], nodeElement);+ leaveVerticalRegion("down");}event.preventDefault();return true;@@ -321,12 +329,13 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylconst previousRowElement = ensureAVTableAdjacentRow(currentRowElement, "previous") ||currentRowElement.previousElementSibling as HTMLElement;clearSelect(["row", "galleryItem"], nodeElement);- if (previousRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]")) {+ const hasPreviousItem = previousRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]");+ if (getAVVerticalNavigationAction(!!hasPreviousItem) === "move") {setAVItemAnchor(nodeElement, previousRowElement as HTMLElement);selectAVItemRange(nodeElement, previousRowElement);cellScrollIntoView(nodeElement, previousRowElement);} else {- nodeElement.classList.add("protyle-wysiwyg--select");+ leaveVerticalRegion("up");}event.preventDefault();return true;@@ -336,12 +345,13 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylconst nextRowElement = ensureAVTableAdjacentRow(currentRowElement, "next") ||currentRowElement.nextElementSibling as HTMLElement;clearSelect(["row", "galleryItem"], nodeElement);- if (nextRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]")) {+ const hasNextItem = nextRowElement?.matches(".av__row[data-id], .av__gallery-item[data-id]");+ if (getAVVerticalNavigationAction(!!hasNextItem) === "move") {setAVItemAnchor(nodeElement, nextRowElement as HTMLElement);selectAVItemRange(nodeElement, nextRowElement);cellScrollIntoView(nodeElement, nextRowElement);} else {- nodeElement.classList.add("protyle-wysiwyg--select");+ leaveVerticalRegion("down");}event.preventDefault();return true;diff --git a/app/src/protyle/render/av/verticalNavigation.test.ts b/app/src/protyle/render/av/verticalNavigation.test.tsnew file mode 100644index 0000000000..4739b31a8d--- /dev/null+++ b/app/src/protyle/render/av/verticalNavigation.test.ts@@ -0,0 +1,13 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getAVVerticalNavigationAction} from "./verticalNavigation";++describe("database vertical navigation", () => {+ it("moves inside the database when an adjacent item exists", () => {+ assert.equal(getAVVerticalNavigationAction(true), "move");+ });++ it("leaves the database at its logical item boundary", () => {+ assert.equal(getAVVerticalNavigationAction(false), "leave");+ });+});diff --git a/app/src/protyle/render/av/verticalNavigation.ts b/app/src/protyle/render/av/verticalNavigation.tsnew file mode 100644index 0000000000..73541de7d0--- /dev/null+++ b/app/src/protyle/render/av/verticalNavigation.ts@@ -0,0 +1,2 @@+export const getAVVerticalNavigationAction = (hasAdjacentItem: boolean) =>+ hasAdjacentItem ? "move" as const : "leave" as const;diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex c3c5ee3aff..df6db777cd 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -73,7 +73,7 @@ import {updateBatchTransaction,updateTransaction} from "./transaction";-import {isEmptyParagraph, isEmptyTextBlock} from "./emptyTextBlock";+import {isEmptyParagraph} from "./emptyTextBlock";import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";import {fontEvent} from "../toolbar/Font";import {applyTableCellStyleHotkey} from "../toolbar/tableCell";@@ -127,13 +127,20 @@ import {AIChat} from "../../ai/chat";import {tabCodeBlock} from "./codeBlock";import {getTopBarHeight} from "../../layout/getTopBarHeight";import {getAVTemplateInteractiveElement} from "../render/av/attributeValue";-import {focusAVByArrow} from "../render/av/focus";+import {focusAVByArrow, getAVVerticalGoalX} from "../render/av/focus";import {hideMessage, showMessage} from "../../dialog/message";import {isMobile} from "../../util/functions";import {confirmBlockRef} from "../../util/checkBlockRef";import {scheduleCaretScroll, scheduleOffscreenCaretScroll} from "./caretScroll";import {scrollPage} from "../scroll/page";-import {getCalloutTitleNavigationTarget} from "./calloutCaret";+import {isCaretAtVerticalBoundary} from "./verticalCaret";+import {+ bindVerticalNavigationReset,+ focusAdjacentVerticalRegion,+ isAtomicVerticalNavigationTarget,+ leaveAVVerticalRegion,+ prepareVerticalNavigation,+} from "./verticalNavigation";import {BLOCK_SELECTION_CLASS,clearBlockSelectionMode,@@ -276,6 +283,7 @@ const getRangeListItemElements = (editorElement: HTMLElement, range: Range) => {export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {let forwardBlockRemovalPending = false;+ bindVerticalNavigationReset(editorElement);editorElement.addEventListener("keydown", async (event: KeyboardEvent & { target: HTMLElement }) => {if (event.target.localName === "protyle-html" || event.target.localName === "input") {event.stopPropagation();@@ -327,11 +335,15 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}const blockSelectionModeElement = getBlockSelectionModeElement(protyle.wysiwyg.element);const calloutTitleElement = hasClosestByClassName(range.startContainer, "callout-title");+ const verticalGoalX = prepareVerticalNavigation(editorElement, event, range, nodeElement,+ nodeElement.classList.contains("av") ? getAVVerticalGoalX(nodeElement) : undefined);if (document.querySelector(".av__panel")) {return;}- if (avKeydown(event, nodeElement, protyle)) {+ if (avKeydown(event, nodeElement, protyle, direction => {+ leaveAVVerticalRegion(protyle, nodeElement, direction, verticalGoalX ?? 0);+ })) {return;}@@ -987,6 +999,15 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}}const nodeEditableElement = (tdElement || getContenteditableElement(nodeElement) || 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);+ event.stopPropagation();+ event.preventDefault();+ return;+ }if (selectText === "" && range.collapsed && (event.key === "ArrowLeft" || event.key === "ArrowRight") &&moveCaretAcrossSemanticMarker(range, event.key === "ArrowLeft" ? "left" : "right")) {focusByRange(range);@@ -1012,51 +1033,33 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {position.end -= 1;}- const selectionPosition = getSelectionPosition(nodeEditableElement, range);- const isFirstLine = (nodeEditableElement.innerText.substr(0, position.end).indexOf("\n") === -1 ||- position.start === 0) &&- selectionPosition.top - nodeEditableElement.getBoundingClientRect().top < 20;- const isLastLine = (nodeEditableElement.innerText.substr(position.end).indexOf("\n") === -1 ||- position.end >= nodeEditableElement.innerText.trimEnd().length) &&- nodeEditableElement.getBoundingClientRect().bottom - selectionPosition.top < 40;+ const isFirstLine = isCaretAtVerticalBoundary(nodeEditableElement, range, "up");+ const isLastLine = isCaretAtVerticalBoundary(nodeEditableElement, range, "down");const isStart = position.start === 0;const isEnd = position.end >= nodeEditableElement.textContent.replace(/\n$/, "").length;const toPrevious = (event.key === "ArrowUp" && isFirstLine) ||(event.key === "ArrowLeft" && isStart);const toNext = (event.key === "ArrowDown" && isLastLine) ||(event.key === "ArrowRight" && isEnd);- if (selectText === "" && range.collapsed && nodeElement.classList.contains("av") &&+ if (selectText === "" && range.collapsed && verticalDirection && (toPrevious || toNext)) {+ focusAdjacentVerticalRegion(protyle, nodeElement, verticalDirection, verticalGoalX ?? 0,+ range.startContainer);+ event.stopPropagation();+ event.preventDefault();+ return;+ }+ if (selectText === "" && range.collapsed && !verticalDirection && nodeElement.classList.contains("av") &&hasClosestByClassName(range.startContainer, "av__title") && (toPrevious || toNext) &&focusAVByArrow(protyle, nodeElement, event.key, true)) {event.stopPropagation();event.preventDefault();return;}- if (selectText === "" && range.collapsed && !nodeElement.classList.contains("av")) {+ if (selectText === "" && range.collapsed && !verticalDirection && !nodeElement.classList.contains("av")) {let adjacentElement = toPrevious ? getPreviousBlock(nodeElement) :(toNext ? getNextBlock(nodeElement) : undefined);- const calloutTitleNavigationTarget =- (event.key === "ArrowUp" && toPrevious || event.key === "ArrowDown" && toNext) ?- getCalloutTitleNavigationTarget(nodeElement, adjacentElement, event.key) : undefined;- if (calloutTitleNavigationTarget) {- range.selectNodeContents(calloutTitleNavigationTarget);- range.collapse(event.key === "ArrowDown");- focusByRange(range);- event.stopPropagation();- event.preventDefault();- return;- }if (adjacentElement) {adjacentElement = toPrevious ? getLastBlock(adjacentElement) : getFirstBlock(adjacentElement);- // 显式聚焦空文本块,避免浏览器跨越容器边界时跳过该块。- // https://github.com/siyuan-note/siyuan/issues/18862- // https://github.com/siyuan-note/siyuan/issues/19129- if ((event.key === "ArrowUp" || event.key === "ArrowDown") && isEmptyTextBlock(adjacentElement)) {- focusBlock(adjacentElement, undefined, event.key === "ArrowDown");- event.stopPropagation();- event.preventDefault();- return;- }if (adjacentElement.classList.contains("av") &&focusAVByArrow(protyle, adjacentElement as HTMLElement, event.key)) {event.stopPropagation();diff --git a/app/src/protyle/wysiwyg/verticalCaret.test.ts b/app/src/protyle/wysiwyg/verticalCaret.test.tsnew file mode 100644index 0000000000..b7ba272f72--- /dev/null+++ b/app/src/protyle/wysiwyg/verticalCaret.test.ts@@ -0,0 +1,35 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {isCaretRectAtVerticalBoundary} from "./verticalGeometry";++const rect = (top: number, height = 20) => ({+ top,+ bottom: top + height,+ left: 10,+ right: 100,+ height,+ width: 90,+});++describe("vertical caret boundary", () => {+ it("recognizes the first and last visual lines", () => {+ const rects = [rect(10), rect(30), rect(50)];++ assert.equal(isCaretRectAtVerticalBoundary(10, rects, "up"), true);+ assert.equal(isCaretRectAtVerticalBoundary(50, rects, "down"), true);+ assert.equal(isCaretRectAtVerticalBoundary(30, rects, "up"), false);+ assert.equal(isCaretRectAtVerticalBoundary(30, rects, "down"), false);+ });++ it("allows small browser differences in collapsed caret geometry", () => {+ const rects = [rect(10, 18), rect(28, 18)];++ assert.equal(isCaretRectAtVerticalBoundary(12, rects, "up"), true);+ assert.equal(isCaretRectAtVerticalBoundary(34, rects, "down"), true);+ });++ it("treats an empty editable region as both vertical boundaries", () => {+ assert.equal(isCaretRectAtVerticalBoundary(0, [], "up"), true);+ assert.equal(isCaretRectAtVerticalBoundary(0, [], "down"), true);+ });+});diff --git a/app/src/protyle/wysiwyg/verticalCaret.ts b/app/src/protyle/wysiwyg/verticalCaret.tsnew file mode 100644index 0000000000..a68c3b8a76--- /dev/null+++ b/app/src/protyle/wysiwyg/verticalCaret.ts@@ -0,0 +1,73 @@+import {focusByRange, getSelectionPosition} from "../util/selection";+import {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 getContentRects = (element: Element) => {+ const range = document.createRange();+ range.selectNodeContents(element);+ return getVisibleRects(range);+};++export const isCaretAtVerticalBoundary = (element: Element, range: Range, direction: TVerticalDirection) => {+ if (!element.contains(range.startContainer)) {+ return false;+ }+ const position = getSelectionPosition(element, range);+ return isCaretRectAtVerticalBoundary(position.top, getContentRects(element), direction);+};++export const getCaretGoalX = (range: Range, fallbackElement?: Element) => {+ const rects = Array.from(range.getClientRects());+ const rect = rects[0] || range.getBoundingClientRect();+ if (rect && Number.isFinite(rect.left) && rect.left > 0) {+ return rect.left;+ }+ if (fallbackElement) {+ const position = getSelectionPosition(fallbackElement, range);+ if (Number.isFinite(position.left) && position.left > 0) {+ return position.left;+ }+ return fallbackElement.getBoundingClientRect().left;+ }+ return 0;+};++const getBoundaryLineRects = (element: Element, direction: TVerticalDirection) => {+ const rects = getContentRects(element);+ if (rects.length === 0) {+ return [];+ }+ const boundaryTop = direction === "down" ?+ Math.min(...rects.map(rect => rect.top)) : Math.max(...rects.map(rect => rect.top));+ const lineHeight = Math.min(...rects.map(rect => rect.height));+ const tolerance = Math.max(2, lineHeight / 2);+ return rects.filter(rect => Math.abs(rect.top - boundaryTop) <= tolerance);+};++export const focusEditableAtGoalX = (element: Element, direction: TVerticalDirection, goalX: number) => {+ const elementRect = element.getBoundingClientRect();+ const lineRects = getBoundaryLineRects(element, direction);+ const range = document.createRange();+ if (lineRects.length > 0 && typeof document.caretRangeFromPoint === "function") {+ const lineLeft = Math.min(...lineRects.map(rect => rect.left));+ const lineRight = Math.max(...lineRects.map(rect => rect.right));+ const lineTop = Math.min(...lineRects.map(rect => rect.top));+ 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)) {+ pointRange.collapse(true);+ focusByRange(pointRange);+ return true;+ }+ }+ range.selectNodeContents(element);+ range.collapse(direction === "down");+ focusByRange(range);+ return elementRect.height > 0;+};diff --git a/app/src/protyle/wysiwyg/verticalGeometry.ts b/app/src/protyle/wysiwyg/verticalGeometry.tsnew file mode 100644index 0000000000..828e472b50--- /dev/null+++ b/app/src/protyle/wysiwyg/verticalGeometry.ts@@ -0,0 +1,22 @@+import type {TVerticalDirection} from "./verticalCaret";++interface IVerticalRect {+ top: number;+ bottom: number;+ left: number;+ right: number;+ height: number;+ width: number;+}++export const isCaretRectAtVerticalBoundary = (caretTop: number, rects: IVerticalRect[],+ direction: TVerticalDirection) => {+ if (rects.length === 0) {+ return true;+ }+ const lineHeight = Math.min(...rects.map(rect => rect.height));+ const tolerance = Math.max(2, lineHeight / 2);+ const boundaryTop = direction === "up" ?+ Math.min(...rects.map(rect => rect.top)) : Math.max(...rects.map(rect => rect.top));+ return Math.abs(caretTop - boundaryTop) <= tolerance;+};diff --git a/app/src/protyle/wysiwyg/verticalNavigation.ts b/app/src/protyle/wysiwyg/verticalNavigation.tsnew file mode 100644index 0000000000..6ada67d1be--- /dev/null+++ b/app/src/protyle/wysiwyg/verticalNavigation.ts@@ -0,0 +1,163 @@+import {hasClosestByClassName} from "../util/hasClosest";+import {focusBlock} from "../util/selection";+import {scrollCenter} from "../../util/highlightById";+import {+ getContenteditableElement,+ getFirstBlock,+ getLastBlock,+ getNextBlock,+ getPreviousBlock,+ isContainerBlock,+ isNotEditBlock,+} from "./getBlock";+import {getCalloutTitleNavigationTarget} from "./calloutCaret";+import {focusEditableAtGoalX, getCaretGoalX, TVerticalDirection} from "./verticalCaret";+import {focusAVTitleByVerticalArrow, focusAVVerticalRegion} from "../render/av/focus";++export const VERTICAL_NAVIGATION_ATOMIC_CLASS = "protyle-wysiwyg--navigation";++const navigationGoalX = new WeakMap<HTMLElement, number>();+const resetBoundEditors = new WeakSet<HTMLElement>();++const clearAtomicFocus = (editorElement: HTMLElement) => {+ editorElement.querySelectorAll(`.${VERTICAL_NAVIGATION_ATOMIC_CLASS}`).forEach(item => {+ item.classList.remove(VERTICAL_NAVIGATION_ATOMIC_CLASS);+ });+};++export const resetVerticalNavigation = (editorElement: HTMLElement) => {+ navigationGoalX.delete(editorElement);+ clearAtomicFocus(editorElement);+};++export const bindVerticalNavigationReset = (editorElement: HTMLElement) => {+ if (resetBoundEditors.has(editorElement)) {+ return;+ }+ resetBoundEditors.add(editorElement);+ ["pointerdown", "input", "focusout"].forEach(type => {+ editorElement.addEventListener(type, () => resetVerticalNavigation(editorElement), true);+ });+};++export const prepareVerticalNavigation = (editorElement: HTMLElement, event: KeyboardEvent, range: Range,+ fallbackElement?: Element, preferredGoalX?: number) => {+ if (!["ArrowUp", "ArrowDown"].includes(event.key) || event.altKey || event.shiftKey ||+ event.metaKey || event.ctrlKey || event.isComposing) {+ resetVerticalNavigation(editorElement);+ return;+ }+ let goalX = navigationGoalX.get(editorElement);+ if (goalX === undefined) {+ goalX = preferredGoalX ?? getCaretGoalX(range, fallbackElement);+ navigationGoalX.set(editorElement, goalX);+ }+ return goalX;+};++export const isAtomicVerticalNavigationTarget = (element: Element) =>+ element.classList.contains(VERTICAL_NAVIGATION_ATOMIC_CLASS);++const focusAtomicRegion = (editorElement: HTMLElement, element: HTMLElement, direction: TVerticalDirection) => {+ clearAtomicFocus(editorElement);+ element.classList.add(VERTICAL_NAVIGATION_ATOMIC_CLASS);+ focusBlock(element, undefined, direction === "down");+};++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]");+ }+ return boundaryElement;+};++const focusResolvedRegion = (protyle: IProtyle, element: Element, direction: TVerticalDirection, goalX: number) => {+ const targetElement = element as HTMLElement;+ clearAtomicFocus(protyle.wysiwyg.element);+ if (targetElement.classList.contains("av")) {+ if (!focusAVVerticalRegion(targetElement, direction, goalX)) {+ focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);+ }+ } else {+ const editableElement = getContenteditableElement(targetElement);+ if (editableElement) {+ focusEditableAtGoalX(editableElement, direction, goalX);+ } else {+ focusAtomicRegion(protyle.wysiwyg.element, targetElement, direction);+ }+ }+ scrollCenter(protyle, targetElement);+ return true;+};++const focusDocumentTitle = (protyle: IProtyle, direction: TVerticalDirection, goalX: number) => {+ if (direction !== "up" || !protyle.title?.editElement ||+ protyle.title.editElement.getClientRects().length === 0) {+ return false;+ }+ clearAtomicFocus(protyle.wysiwyg.element);+ return focusEditableAtGoalX(protyle.title.editElement, direction, goalX);+};++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 firstElement = getFirstBlock(contentElement);+ if (firstElement !== contentElement) {+ return focusResolvedRegion(protyle, firstElement, direction, goalX);+ }+ }+ }+ if (calloutElement) {+ sourceElement = calloutElement;+ }+ }++ if (sourceElement.classList.contains("av") && sourceNode &&+ hasClosestByClassName(sourceNode, "av__title")) {+ if (direction === "down" && focusAVVerticalRegion(sourceElement, direction, goalX, false)) {+ return true;+ }+ }++ 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;+ }+ if (!adjacentElement) {+ focusDocumentTitle(protyle, direction, goalX);+ return true;+ }+ return focusResolvedRegion(protyle, getBoundaryBlock(adjacentElement, direction), direction, goalX);+};++export const leaveAVVerticalRegion = (protyle: IProtyle, sourceElement: HTMLElement,+ direction: TVerticalDirection, goalX: number) => {+ if (direction === "up" && focusAVTitleByVerticalArrow(sourceElement, direction, goalX)) {+ return true;+ }+ return focusAdjacentVerticalRegion(protyle, sourceElement, direction, goalX);+};