Skip to content

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

:bug: Respect manual scrolling in mobile editors https://github.com/siyuan-note/siyuan/issues/20133

Danielb7cbb602179f
diff --git a/app/src/mobile/util/keyboardSelectionScroll.test.ts b/app/src/mobile/util/keyboardSelectionScroll.test.ts
new file mode 100644
index 0000000000..81e267b0b2
--- /dev/null
+++ b/app/src/mobile/util/keyboardSelectionScroll.test.ts
@@ -0,0 +1,188 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {createKeyboardSelectionScroll, type IKeyboardSelectionScrollState} from "./keyboardSelectionScroll";
+
+class ScrollContainer extends EventTarget {
+ public scrollTop = 180;
+ public scrollLeft = 12;
+ public stops: ScrollToOptions[] = [];
+
+ scroll(options: ScrollToOptions) {
+ this.stops.push(options);
+ }
+}
+
+const setup = (smooth = false) => {
+ const container = new ScrollContainer();
+ const node = {} as Node;
+ const state: IKeyboardSelectionScrollState = {
+ container: container as unknown as HTMLElement,
+ anchorNode: node, anchorOffset: 0, focusNode: node, focusOffset: 0,
+ viewportTop: 200, viewportBottom: 320,
+ };
+ const timers = new Map<number, {callback: () => void, delay: number}>();
+ let nextTimer = 0;
+ const calls: HTMLElement[] = [];
+ const controller = createKeyboardSelectionScroll({
+ delay: 300,
+ scroll: element => { calls.push(element); return smooth; },
+ onCancel() {},
+ setTimer: (callback, delay) => { timers.set(++nextTimer, {callback, delay}); return nextTimer; },
+ clearTimer: timer => { timers.delete(timer); },
+ });
+ const flush = () => {
+ const tasks = [...timers.entries()].filter(([, task]) => task.delay === 300);
+ tasks.forEach(([id, task]) => { timers.delete(id); task.callback(); });
+ };
+ return {container, state, controller, timers, calls, flush};
+};
+
+test("toolbar refreshes do not restart or repeat selection positioning", () => {
+ const s = setup();
+ s.controller.request(s.state);
+ const original = [...s.timers.keys()];
+ s.controller.request({...s.state});
+ assert.deepEqual([...s.timers.keys()], original);
+ s.flush();
+ s.controller.request({...s.state});
+ assert.equal(s.calls.length, 1);
+ assert.equal(s.timers.size, 0);
+});
+
+test("a swipe cancels pending positioning and repeated selection events cannot pull the viewport back", () => {
+ const s = setup();
+ s.controller.request(s.state);
+ s.container.dispatchEvent(new Event("touchstart"));
+ s.controller.request({...s.state});
+ s.container.dispatchEvent(new Event("touchmove"));
+ s.container.scrollTop = 350;
+ s.container.dispatchEvent(new Event("scroll"));
+ s.container.dispatchEvent(new Event("touchend"));
+ s.controller.request({...s.state});
+ s.flush();
+ assert.equal(s.calls.length, 0);
+ assert.equal(s.container.scrollTop, 350);
+ assert.equal(s.timers.size, 0);
+ s.controller.request({...s.state, focusOffset: 1});
+ s.flush();
+ assert.equal(s.calls.length, 1, "a later caret move still positions the selection");
+});
+
+test("tapping a new caret defers positioning until the touch ends", () => {
+ const s = setup();
+ s.controller.request(s.state);
+ s.container.dispatchEvent(new Event("touchstart"));
+ s.controller.request({...s.state, focusOffset: 1});
+ s.flush();
+ assert.equal(s.calls.length, 0);
+ s.container.dispatchEvent(new Event("touchend"));
+ s.flush();
+ assert.equal(s.calls.length, 1);
+});
+
+test("viewport refreshes during a swipe do not schedule positioning after release", () => {
+ for (const end of ["touchend", "touchcancel"]) {
+ const s = setup();
+ s.controller.request(s.state);
+ s.container.dispatchEvent(new Event("touchstart"));
+ const next = {...s.state, viewportBottom: 300};
+ s.controller.request(next);
+ s.container.dispatchEvent(new Event("touchmove"));
+ s.controller.request(next, true);
+ s.container.dispatchEvent(new Event(end));
+ s.controller.request(next);
+ s.flush();
+ assert.equal(s.calls.length, 0);
+ assert.equal(s.timers.size, 0);
+ }
+});
+
+test("wheel and scrollbar interaction cancel pending positioning", () => {
+ for (const type of ["wheel", "pointerdown"]) {
+ const s = setup();
+ s.controller.request(s.state);
+ const event = new Event(type);
+ Object.assign(event, {pointerType: "mouse"});
+ s.container.dispatchEvent(event);
+ s.controller.request({...s.state});
+ s.flush();
+ assert.equal(s.calls.length, 0, type);
+ }
+});
+
+test("dragging a selection endpoint still positions the changed selection after release", () => {
+ const s = setup();
+ s.controller.request(s.state);
+ s.container.dispatchEvent(new Event("touchstart"));
+ s.container.dispatchEvent(new Event("touchmove"));
+ s.controller.request({...s.state, focusOffset: 1});
+ s.flush();
+ assert.equal(s.calls.length, 0);
+ s.container.dispatchEvent(new Event("touchend"));
+ s.flush();
+ assert.equal(s.calls.length, 1);
+});
+
+test("layout adjustments and other programmatic scrolls preserve pending caret positioning", () => {
+ const s = setup();
+ s.controller.request(s.state);
+ s.container.dispatchEvent(new Event("scroll"));
+ s.flush();
+ assert.equal(s.calls.length, 1);
+});
+
+test("committed input and keyboard viewport changes can position an unchanged caret", () => {
+ const s = setup();
+ s.controller.request(s.state);
+ s.flush();
+ s.controller.request({...s.state}, true);
+ s.flush();
+ s.controller.request({...s.state, viewportBottom: 260});
+ s.flush();
+ assert.equal(s.calls.length, 3);
+});
+
+test("manual interaction stops an ongoing smooth scroll while preserving horizontal position", () => {
+ for (const type of ["touchstart", "wheel", "pointerdown"]) {
+ const s = setup(true);
+ s.controller.request(s.state);
+ s.flush();
+ const event = new Event(type);
+ Object.assign(event, {pointerType: "mouse"});
+ s.container.dispatchEvent(event);
+ assert.deepEqual(s.container.stops, [{top: 180, left: 12, behavior: "auto"}]);
+ assert.equal(s.timers.size, 0);
+ }
+});
+
+test("automatic scroll events do not cancel a newer caret request", () => {
+ const s = setup(true);
+ s.controller.request(s.state);
+ s.flush();
+ s.controller.request({...s.state, focusOffset: 1});
+ s.container.dispatchEvent(new Event("scroll"));
+ s.flush();
+ assert.equal(s.calls.length, 2);
+ s.container.dispatchEvent(new Event("scrollend"));
+ assert.equal(s.timers.size, 0);
+});
+
+test("switching or hiding editors cancels tasks and releases listeners on the previous editor", () => {
+ const s = setup(true);
+ s.controller.request(s.state);
+ s.flush();
+ const other = new ScrollContainer();
+ const next = {...s.state, container: other as unknown as HTMLElement};
+ s.controller.request(next);
+ assert.equal(s.container.stops.length, 1);
+ s.container.dispatchEvent(new Event("touchstart"));
+ s.flush();
+ assert.equal(s.calls[1], other);
+ s.controller.reset();
+ assert.equal(s.timers.size, 0);
+ s.controller.request(s.state);
+ other.dispatchEvent(new Event("touchstart"));
+ s.flush();
+ assert.equal(s.calls[2], s.container);
+ s.controller.reset();
+});
diff --git a/app/src/mobile/util/keyboardSelectionScroll.ts b/app/src/mobile/util/keyboardSelectionScroll.ts
new file mode 100644
index 0000000000..86381916af
--- /dev/null
+++ b/app/src/mobile/util/keyboardSelectionScroll.ts
@@ -0,0 +1,135 @@
+export interface IKeyboardSelectionScrollState {
+ container: HTMLElement;
+ anchorNode: Node;
+ anchorOffset: number;
+ focusNode: Node;
+ focusOffset: number;
+ viewportTop: number;
+ viewportBottom: number;
+}
+
+interface IKeyboardSelectionScrollOptions {
+ delay: number;
+ scroll: (container: HTMLElement) => boolean;
+ onCancel: () => void;
+ setTimer?: (callback: () => void, delay: number) => number;
+ clearTimer?: (timer: number) => void;
+}
+
+const sameSelection = (a: IKeyboardSelectionScrollState, b: IKeyboardSelectionScrollState) =>
+ a?.container === b.container && a.anchorNode === b.anchorNode && a.anchorOffset === b.anchorOffset &&
+ a.focusNode === b.focusNode && a.focusOffset === b.focusOffset;
+
+const sameState = (a: IKeyboardSelectionScrollState, b: IKeyboardSelectionScrollState) =>
+ sameSelection(a, b) && a.viewportTop === b.viewportTop && a.viewportBottom === b.viewportBottom;
+
+export const createKeyboardSelectionScroll = (options: IKeyboardSelectionScrollOptions) => {
+ const setTimer = options.setTimer || ((callback, delay) => window.setTimeout(callback, delay));
+ const clearTimer = options.clearTimer || (timer => window.clearTimeout(timer));
+ let state: IKeyboardSelectionScrollState;
+ let touchState: IKeyboardSelectionScrollState;
+ let timer: number | undefined;
+ let stopTimer: number | undefined;
+ let container: HTMLElement;
+ let touching = false;
+ let moved = false;
+ let deferred = false;
+ let scrolling = false;
+
+ const cancelPending = () => {
+ if (timer !== undefined) {
+ clearTimer(timer);
+ timer = undefined;
+ }
+ deferred = false;
+ };
+ const finishScroll = () => {
+ scrolling = false;
+ if (stopTimer !== undefined) {
+ clearTimer(stopTimer);
+ stopTimer = undefined;
+ }
+ };
+ const cancel = () => {
+ cancelPending();
+ if (scrolling) {
+ container.scroll({top: container.scrollTop, left: container.scrollLeft, behavior: "auto"});
+ }
+ finishScroll();
+ options.onCancel();
+ };
+ const schedule = () => {
+ timer = setTimer(() => {
+ timer = undefined;
+ finishScroll();
+ scrolling = options.scroll(container);
+ if (scrolling) {
+ stopTimer = setTimer(finishScroll, 1000);
+ }
+ }, options.delay);
+ };
+ const touchStart = () => {
+ cancel();
+ touching = true;
+ moved = false;
+ touchState = state;
+ };
+ const touchMove = () => {
+ moved = true;
+ cancel();
+ };
+ const touchEnd = () => {
+ touching = false;
+ // 滑动仅浏览内容时保留视口;拖动选区端点后仍定位到新的选区。
+ if ((deferred && !moved) || (state && touchState && !sameSelection(touchState, state))) {
+ schedule();
+ }
+ deferred = false;
+ touchState = undefined;
+ };
+ const touchCancel = () => {
+ touching = false;
+ touchState = undefined;
+ cancel();
+ };
+ const pointerDown = (event: PointerEvent) => {
+ if (event.pointerType === "mouse") {
+ cancel();
+ }
+ };
+ const listeners: Array<[string, EventListener]> = [
+ ["touchstart", touchStart], ["touchmove", touchMove], ["touchend", touchEnd],
+ ["touchcancel", touchCancel], ["wheel", cancel], ["pointerdown", pointerDown],
+ ["scrollend", finishScroll],
+ ];
+ const reset = () => {
+ cancel();
+ listeners.forEach(([type, listener]) => container?.removeEventListener(type, listener));
+ container = undefined;
+ state = undefined;
+ touching = false;
+ moved = false;
+ touchState = undefined;
+ };
+ return {
+ request: (nextState: IKeyboardSelectionScrollState, force = false) => {
+ if (container !== nextState.container) {
+ reset();
+ container = nextState.container;
+ listeners.forEach(([type, listener]) => container.addEventListener(type, listener, {passive: true}));
+ }
+ // 记录已处理的选区与视口,手动滚动后重复刷新工具栏不会再次定位。
+ if (!force && sameState(state, nextState)) {
+ return;
+ }
+ state = {...nextState};
+ cancelPending();
+ if (touching) {
+ deferred = !moved;
+ return;
+ }
+ schedule();
+ },
+ reset,
+ };
+};
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 0fd4aa7f6d..b6b1f74039 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -8,7 +8,7 @@ import {
import {moveToDown, moveToUp} from "../../protyle/wysiwyg/move";
import {Constants} from "../../constants";
import {getSuperBlockCommand} from "../../block/superBlock";
-import {focusBlock, focusByRange, getSelectionPosition} from "../../protyle/util/selection";
+import {focusByRange, getSelectionPosition} from "../../protyle/util/selection";
import {getCurrentEditor as getDocumentEditor} from "../editor";
import {getMobileToolbarPaddingElement, getMobileToolbarProtyle, getMobileToolbarUndo} from "../../protyle/lite/mobileToolbar";
import {LocalUndo} from "../../protyle/undo";
@@ -25,7 +25,6 @@ import {
} from "../../protyle/util/compatibility";
import {tabCodeBlock} from "../../protyle/wysiwyg/codeBlock";
import {armKeyboardLock, callMobileAppShowKeyboard, canInput, keyboardLockUntil} from "./mobileAppUtil";
-import {isNotEditBlock} from "../../protyle/wysiwyg/getBlock";
import {getMirror, getUndoRootID, hasUndoStateMirror, initMirror} from "../../protyle/undo/globalUndo";
import {getMobilePluginToolbarItems} from "./pluginToolbar";
import {escapeHtml} from "../../util/escape";
@@ -94,6 +93,8 @@ import {pauseMobileBarsScroll} from "./mobileBars";
import {getBlockTypeSelection, openBlockTypeMenu, updateBlockTypeButton} from "../../protyle/toolbar/BlockType";
import {TTextBlockSelection} from "../../protyle/toolbar/blockTypeCore";
import {getMobileToolbarContextPath} from "../../config/entryVisibility/mobileToolbarContext";
+import {createKeyboardSelectionScroll} from "./keyboardSelectionScroll";
+import {getCaretOverflowDirection, getCaretScrollDelta} from "../../protyle/wysiwyg/caretScrollCore";
const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();
let toolbarProtyle: IProtyle;
@@ -154,8 +155,12 @@ const ANDROID_TABLE_CELL_SELECT_ALL_TIMEOUT = 2000;
const inlineMathSelection = createInlineMathSelection();
let renderKeyboardToolbarFrame: number | undefined;
-let scrollSelectionIntoViewTimeout: number;
let clearRenderGutterAfterScroll: () => void;
+const keyboardSelectionScroll = createKeyboardSelectionScroll({
+ delay: Constants.TIMEOUT_TRANSITION,
+ scroll: container => scrollKeyboardSelection(container),
+ onCancel: () => clearRenderGutterAfterScroll?.(),
+});
let showUtil = false;
let keyboardPanelTop: number | undefined;
let keyboardPanelClosing = false;
@@ -1161,80 +1166,103 @@ export const showKeyboardToolbar = () => {
}
};
-const scrollKeyboardSelectionIntoView = () => {
+const scrollKeyboardSelectionIntoView = (force = false) => {
const toolbarElement = document.getElementById("keyboardToolbar");
if (!toolbarElement || toolbarElement.classList.contains("fn__none") || showUtil) {
return;
}
- clearTimeout(scrollSelectionIntoViewTimeout);
+ const editor = getCurrentEditor();
+ const selection = getSelection();
+ if (!editor || selection.rangeCount === 0 ||
+ !editor.protyle.wysiwyg.element.contains(selection.anchorNode) ||
+ !editor.protyle.wysiwyg.element.contains(selection.focusNode)) {
+ return;
+ }
+ const container = hasClosestByClassName(selection.focusNode, "protyle-content", true);
+ if (!container) {
+ return;
+ }
+ const viewport = getVisibleViewportBounds();
+ const contentRect = container.getBoundingClientRect();
+ keyboardSelectionScroll.request({
+ container,
+ anchorNode: selection.anchorNode,
+ anchorOffset: selection.anchorOffset,
+ focusNode: selection.focusNode,
+ focusOffset: selection.focusOffset,
+ viewportTop: Math.max(viewport.top, contentRect.top),
+ viewportBottom: Math.min(viewport.bottom, contentRect.bottom, toolbarElement.getBoundingClientRect().top),
+ }, force);
+};
+
+const scrollKeyboardSelection = (container: HTMLElement) => {
clearRenderGutterAfterScroll?.();
- scrollSelectionIntoViewTimeout = window.setTimeout(() => {
- const editor = getCurrentEditor();
- const selection = getSelection();
- if (!editor || editor.protyle.toolbar.isMultiSelectMode() || selection.rangeCount === 0 ||
- !editor.protyle.wysiwyg.element.contains(document.activeElement) ||
- toolbarElement.classList.contains("fn__none") || showUtil) {
- return;
- }
- // 视口稳定后读取当前选区,避免键盘动画期间使用已经移动的光标位置。
- const range = selection.getRangeAt(0);
- if (!editor.protyle.wysiwyg.element.contains(range.startContainer)) {
- return;
- }
- const contentElement = hasClosestByClassName(range.startContainer, "protyle-content", true);
- if (contentElement) {
- const renderGutter = () => {
- restoreGutterBySelection(editor.protyle);
- };
- let cursorTop = getSelectionPosition(contentElement, range.cloneRange()).top;
- if (cursorTop < 0 && window.siyuan.mobile.touchRange) {
- const rangeBlockElement = hasClosestBlock(window.siyuan.mobile.touchRange.startContainer);
- if (rangeBlockElement) {
- if (isNotEditBlock(rangeBlockElement)) {
- focusBlock(rangeBlockElement);
- } else {
- focusByRange(window.siyuan.mobile.touchRange);
- }
- cursorTop = getSelectionPosition(contentElement, window.siyuan.mobile.touchRange).top;
- }
- }
- const viewportBounds = getVisibleViewportBounds();
- const cursorElement = range.startContainer.nodeType === Node.ELEMENT_NODE ?
- range.startContainer as Element : range.startContainer.parentElement;
- // 自动滚动时额外预留一行,避免输入文字被键盘工具栏遮挡。
- const extraLineHeight = parseFloat(getComputedStyle(cursorElement).lineHeight) ||
- window.siyuan.config.editor.fontSize * 1.625;
- const visibleBottom = Math.min(viewportBounds.bottom, contentElement.getBoundingClientRect().bottom,
- toolbarElement.getBoundingClientRect().top);
- if (cursorTop + extraLineHeight < visibleBottom &&
- cursorTop > Math.max(contentElement.getBoundingClientRect().top, viewportBounds.top)) {
- renderGutter();
- return;
- }
- const clearRenderGutter = () => {
- contentElement.removeEventListener("scrollend", renderGutterAfterScroll);
- contentElement.removeEventListener("touchstart", clearRenderGutter);
- clearTimeout(renderGutterTimeout);
- clearRenderGutterAfterScroll = undefined;
- };
- const renderGutterAfterScroll = () => {
- clearRenderGutter();
- renderGutter();
- };
- const renderGutterTimeout = window.setTimeout(renderGutterAfterScroll, Constants.TIMEOUT_COUNT);
- clearRenderGutterAfterScroll = clearRenderGutter;
- contentElement.addEventListener("scrollend", renderGutterAfterScroll, {once: true});
- contentElement.addEventListener("touchstart", clearRenderGutter, {once: true, passive: true});
- pauseMobileBarsScroll(Constants.TIMEOUT_COUNT);
- contentElement.scroll({
- top: cursorTop < 0 ?
- contentElement.scrollTop + visibleBottom - viewportBounds.top + extraLineHeight :
- contentElement.scrollTop + cursorTop - visibleBottom + extraLineHeight * 2,
- left: contentElement.scrollLeft,
- behavior: "smooth"
- });
- }
- }, Constants.TIMEOUT_TRANSITION);
+ const toolbarElement = document.getElementById("keyboardToolbar");
+ const editor = getCurrentEditor();
+ const selection = getSelection();
+ if (!editor || !container.isConnected || !toolbarElement ||
+ editor.protyle.toolbar.isMultiSelectMode() || selection.rangeCount === 0 ||
+ !editor.protyle.wysiwyg.element.contains(document.activeElement) ||
+ toolbarElement.classList.contains("fn__none") || showUtil) {
+ return false;
+ }
+ // 视口稳定后读取当前选区,避免键盘动画期间使用已经移动的光标位置。
+ const range = selection.getRangeAt(0);
+ if (!editor.protyle.wysiwyg.element.contains(range.startContainer) ||
+ !editor.protyle.wysiwyg.element.contains(range.endContainer)) {
+ return false;
+ }
+ const contentElement = hasClosestByClassName(range.startContainer, "protyle-content", true);
+ if (contentElement !== container) {
+ return false;
+ }
+ const renderGutter = () => {
+ restoreGutterBySelection(editor.protyle);
+ };
+ const cursorTop = getSelectionPosition(contentElement, range.cloneRange()).top;
+ const viewportBounds = getVisibleViewportBounds();
+ const cursorElement = range.startContainer.nodeType === Node.ELEMENT_NODE ?
+ range.startContainer as Element : range.startContainer.parentElement;
+ // 自动滚动时额外预留一行,避免输入文字被键盘工具栏遮挡。
+ const extraLineHeight = parseFloat(getComputedStyle(cursorElement).lineHeight) ||
+ window.siyuan.config.editor.fontSize * 1.625;
+ const visibleBottom = Math.min(viewportBounds.bottom, contentElement.getBoundingClientRect().bottom,
+ toolbarElement.getBoundingClientRect().top);
+ const visibleTop = Math.max(contentElement.getBoundingClientRect().top, viewportBounds.top);
+ const geometry = {
+ caretTop: cursorTop,
+ caretHeight: extraLineHeight,
+ viewportTop: visibleTop,
+ viewportHeight: visibleBottom - visibleTop,
+ lineHeight: extraLineHeight,
+ surroundingLines: 1,
+ };
+ const direction = getCaretOverflowDirection(geometry);
+ if (!direction) {
+ renderGutter();
+ return false;
+ }
+ const clearRenderGutter = () => {
+ contentElement.removeEventListener("scrollend", renderGutterAfterScroll);
+ contentElement.removeEventListener("touchstart", clearRenderGutter);
+ clearTimeout(renderGutterTimeout);
+ clearRenderGutterAfterScroll = undefined;
+ };
+ const renderGutterAfterScroll = () => {
+ clearRenderGutter();
+ renderGutter();
+ };
+ const renderGutterTimeout = window.setTimeout(renderGutterAfterScroll, Constants.TIMEOUT_COUNT);
+ clearRenderGutterAfterScroll = clearRenderGutter;
+ contentElement.addEventListener("scrollend", renderGutterAfterScroll, {once: true});
+ contentElement.addEventListener("touchstart", clearRenderGutter, {once: true, passive: true});
+ pauseMobileBarsScroll(Constants.TIMEOUT_COUNT);
+ contentElement.scroll({
+ top: contentElement.scrollTop + getCaretScrollDelta(geometry, direction),
+ left: contentElement.scrollLeft,
+ behavior: "smooth"
+ });
+ return true;
};
export const hideKeyboardToolbar = (keyboardClosed = true) => {
@@ -1242,7 +1270,7 @@ export const hideKeyboardToolbar = (keyboardClosed = true) => {
window.cancelAnimationFrame(renderKeyboardToolbarFrame);
renderKeyboardToolbarFrame = undefined;
}
- clearTimeout(scrollSelectionIntoViewTimeout);
+ keyboardSelectionScroll.reset();
clearRenderGutterAfterScroll?.();
// 键盘退场时保留已展开的移动端菜单,菜单由用户操作或编辑器切换关闭。
if (showUtil || keyboardPanelTop !== undefined) {
@@ -1398,6 +1426,9 @@ export const initKeyboardToolbar = () => {
if (isCommittedTextInput(event)) {
composing = false;
}
+ if (getCurrentEditor()?.protyle.wysiwyg.element.contains(event.target as Node)) {
+ scrollKeyboardSelectionIntoView(true);
+ }
}, true);
document.addEventListener("selectionchange", () => {
inlineMathSelection.update(getMathEditor(), getSelection(), composing);
diff --git a/app/src/mobile/util/keyboardToolbarScroll.test.ts b/app/src/mobile/util/keyboardToolbarScroll.test.ts
new file mode 100644
index 0000000000..0b4a673810
--- /dev/null
+++ b/app/src/mobile/util/keyboardToolbarScroll.test.ts
@@ -0,0 +1,160 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+import {createKeyboardSelectionScroll} from "./keyboardSelectionScroll";
+import {getCaretOverflowDirection, getCaretScrollDelta} from "../../protyle/wysiwyg/caretScrollCore";
+
+const source = createSourceFile("keyboardToolbar.ts", readFileSync(join(__dirname, "keyboardToolbar.ts"), "utf8"),
+ ScriptTarget.Latest, true);
+const declarations = source.statements.filter(node => isVariableStatement(node) &&
+ node.declarationList.declarations.some(item =>
+ ["scrollKeyboardSelectionIntoView", "scrollKeyboardSelection"].includes(item.name.getText(source))));
+assert.equal(declarations.length, 2);
+const code = transpileModule(declarations.map(node => node.getText(source)).join("\n") +
+ "\n({scrollKeyboardSelectionIntoView, scrollKeyboardSelection});", {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+
+class Content extends EventTarget {
+ public isConnected = true;
+ public scrollTop = 180;
+ public scrollLeft = 12;
+ public calls: ScrollToOptions[] = [];
+
+ getBoundingClientRect() {
+ return {top: 200, bottom: 320};
+ }
+
+ scroll(options: ScrollToOptions) {
+ this.calls.push(options);
+ this.scrollTop = options.top;
+ }
+}
+
+const setup = () => {
+ const content = new Content();
+ const cursor = {nodeType: 1};
+ const range = {startContainer: cursor, endContainer: cursor, cloneRange: () => range};
+ const selection = {rangeCount: 1, anchorNode: cursor, anchorOffset: 0, focusNode: cursor, focusOffset: 0,
+ getRangeAt: () => range};
+ const state = {cursorTop: 350, viewportBottom: 600, hidden: false, showUtil: false, focused: true, multi: false};
+ const toolbar = {classList: {contains: () => state.hidden}, getBoundingClientRect: () => ({top: 400})};
+ const protyle = {toolbar: {isMultiSelectMode: () => state.multi}, wysiwyg: {element: {
+ contains: (node: unknown) => node === cursor && state.focused,
+ }}};
+ let current: {protyle: typeof protyle} | undefined = {protyle};
+ const timers = new Map<number, {callback: () => void, delay: number}>();
+ let nextTimer = 0;
+ const setTimer = (callback: () => void, delay: number) => {
+ timers.set(++nextTimer, {callback, delay});
+ return nextTimer;
+ };
+ const clearTimer = (id: number) => { timers.delete(id); };
+ const context = {
+ document: {getElementById: () => toolbar, activeElement: cursor},
+ window: {setTimeout: setTimer, siyuan: {mobile: {touchRange: {startContainer: {}}},
+ config: {editor: {fontSize: 14}}}},
+ clearTimeout: clearTimer, Constants: {TIMEOUT_COUNT: 1000},
+ getCurrentEditor: () => current, getSelection: () => selection,
+ hasClosestByClassName: (node: unknown) => node === cursor ? content : undefined,
+ getVisibleViewportBounds: () => ({top: 0, bottom: state.viewportBottom}),
+ getSelectionPosition: () => ({top: state.cursorTop}), getComputedStyle: () => ({lineHeight: "22px"}),
+ getCaretOverflowDirection, getCaretScrollDelta,
+ Node: {ELEMENT_NODE: 1}, showUtil: false, clearRenderGutterAfterScroll: undefined as (() => void) | undefined,
+ restoreGutterBySelection() {}, pauseMobileBarsScroll() {},
+ keyboardSelectionScroll: undefined as ReturnType<typeof createKeyboardSelectionScroll> | undefined,
+ };
+ context.keyboardSelectionScroll = createKeyboardSelectionScroll({
+ delay: 300, setTimer, clearTimer,
+ scroll: container => api.scrollKeyboardSelection(container),
+ onCancel: () => context.clearRenderGutterAfterScroll?.(),
+ });
+ const api: {scrollKeyboardSelectionIntoView: (force?: boolean) => void,
+ scrollKeyboardSelection: (container: HTMLElement) => boolean} = runInNewContext(code, context);
+ const flush = () => {
+ [...timers.entries()].filter(([, task]) => task.delay === 300).forEach(([id, task]) => {
+ timers.delete(id);
+ task.callback();
+ });
+ };
+ return {api, content, state, selection, context, flush, leaveEditor: () => { current = undefined; }};
+};
+
+test("mobile toolbar positioning yields to a swipe even after repeated selection refreshes", () => {
+ const s = setup();
+ s.state.cursorTop = 250;
+ s.api.scrollKeyboardSelectionIntoView();
+ s.content.dispatchEvent(new Event("touchstart"));
+ s.content.dispatchEvent(new Event("touchmove"));
+ s.content.scrollTop = 350;
+ s.state.cursorTop = 80;
+ s.api.scrollKeyboardSelectionIntoView();
+ s.content.dispatchEvent(new Event("touchend"));
+ s.api.scrollKeyboardSelectionIntoView();
+ s.flush();
+ assert.equal(s.content.calls.length, 0);
+ assert.equal(s.content.scrollTop, 350);
+ s.selection.focusOffset++;
+ s.api.scrollKeyboardSelectionIntoView();
+ s.flush();
+ assert.ok(s.content.calls[0].top < 350, "a later caret move can scroll upwards");
+});
+
+test("positioning uses the crossed viewport edge and preserves the current selection", () => {
+ for (const [cursorTop, expectedTop] of [[180, 138], [-20, -62], [350, 254], [250, undefined]]) {
+ const s = setup();
+ s.state.cursorTop = cursorTop;
+ s.api.scrollKeyboardSelectionIntoView();
+ s.flush();
+ assert.equal(s.content.calls[0]?.top, expectedTop);
+ if (expectedTop !== undefined) {
+ assert.equal(s.content.calls[0].left, 12);
+ assert.equal(s.content.calls[0].behavior, "smooth");
+ }
+ }
+});
+
+test("input and keyboard viewport changes still position the caret after manual browsing", () => {
+ for (const reason of ["input", "viewport"]) {
+ const s = setup();
+ s.state.cursorTop = 250;
+ s.api.scrollKeyboardSelectionIntoView();
+ s.flush();
+ s.content.dispatchEvent(new Event("wheel"));
+ if (reason === "input") {
+ s.state.cursorTop = 350;
+ } else {
+ s.state.viewportBottom = 260;
+ }
+ s.api.scrollKeyboardSelectionIntoView(reason === "input");
+ s.flush();
+ assert.equal(s.content.calls.length, 1, reason);
+ }
+});
+
+test("delayed positioning checks editor, focus, toolbar, selection and detached-container state", () => {
+ for (const change of ["editor", "focus", "hidden", "panel", "multi", "range", "detached"]) {
+ const s = setup();
+ s.api.scrollKeyboardSelectionIntoView();
+ if (change === "editor") {
+ s.leaveEditor();
+ } else if (change === "focus") {
+ s.state.focused = false;
+ } else if (change === "hidden") {
+ s.state.hidden = true;
+ } else if (change === "panel") {
+ s.context.showUtil = true;
+ } else if (change === "multi") {
+ s.state.multi = true;
+ } else if (change === "range") {
+ s.selection.rangeCount = 0;
+ } else {
+ s.content.isConnected = false;
+ }
+ s.flush();
+ assert.equal(s.content.calls.length, 0, change);
+ }
+});
diff --git a/app/src/mobile/util/keyboardVideo.test.ts b/app/src/mobile/util/keyboardVideo.test.ts
index 733b14bfda..e68549d2f2 100644
--- a/app/src/mobile/util/keyboardVideo.test.ts
+++ b/app/src/mobile/util/keyboardVideo.test.ts
@@ -31,7 +31,7 @@ test("a non-editable video focus hides editing controls without reporting a syst
window: {requestAnimationFrame: (callback: () => void) => { frame = callback; return 1; }, cancelAnimationFrame() {}},
document: {activeElement: {tagName: "VIDEO"}, getElementById: (id: string) => id === "keyboardToolbar" ? toolbar :
{style: {transform: ""}}},
- renderKeyboardToolbarFrame: undefined as number | undefined, scrollSelectionIntoViewTimeout: undefined as number | undefined,
+ renderKeyboardToolbarFrame: undefined as number | undefined, keyboardSelectionScroll: {reset() {}},
clearRenderGutterAfterScroll: undefined as (() => void) | undefined, showUtil: false,
keyboardPanelTop: undefined as number | undefined,
pendingKeyboardFocus: undefined as {protyle: unknown, range: unknown} | undefined,