Skip to content

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

:bug: Restore iPad navigation history and precise caret positions

Vanessa66b235d7fcc8
diff --git a/app/src/protyle/util/navigationHistory.test.ts b/app/src/protyle/util/navigationHistory.test.ts
new file mode 100644
index 0000000000..9dab80478a
--- /dev/null
+++ b/app/src/protyle/util/navigationHistory.test.ts
@@ -0,0 +1,72 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("onGet.ts", readFileSync("src/protyle/util/onGet.ts", "utf8"), ScriptTarget.ES2021, true);
+const declaration = source.statements.find(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(source) === "focusElementById"));
+const compiled = transpileModule(declaration.getText(source) + "\nglobalThis.navigate = focusElementById;", {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+
+const navigate = (action: string[], tablet = true, suppressFocus = false) => {
+ const records: unknown[] = [];
+ let focused = 0;
+ const element = {
+ classList: {contains: () => false},
+ getAttribute: () => "NodeParagraph",
+ };
+ const range = {selectNodeContents: (target: unknown) => assert.equal(target, element), collapse: () => {}};
+ const context: any = {
+ Constants: Object.fromEntries(["FOCUS", "FOCUSFIRST", "SCROLL", "HL", "UNUNDO", "UNCHANGEID", "OUTLINE"]
+ .map(key => ["CB_GET_" + key, key])),
+ isPhablet: () => tablet,
+ hasFocusOffsets: () => false,
+ isInEmbedBlock: () => false,
+ hasClosestByAttribute: () => false,
+ getContenteditableElement: () => element,
+ document: {createRange: () => range},
+ pushBack: (_protyle: unknown, savedRange: unknown, target: unknown) => {
+ assert.equal(target, element);
+ records.push(savedRange);
+ },
+ focusBlock: () => { focused++; return range; },
+ preventScroll: () => {},
+ bgFade: () => {},
+ scrollCenter: () => {},
+ setTimeout: (callback: () => void, delay: number) => { if (!delay) { callback(); } },
+ AbortController,
+ ResizeObserver: class { observe() {} disconnect() {} },
+ };
+ runInNewContext(compiled, context);
+ context.navigate({
+ block: {id: "block", rootID: "root"},
+ wysiwyg: {element: {querySelectorAll: () => [element], firstElementChild: element}},
+ contentElement: {addEventListener: () => {}},
+ observer: {unobserve: () => {}},
+ }, action, undefined, undefined, false, suppressFocus);
+ return {records, focused};
+};
+
+test("tablet browsing records navigation without focusing the editor", () => {
+ for (const action of ["SCROLL", "HL", "FOCUS"]) {
+ const result = navigate([action], true, true);
+ assert.equal(result.records.length, 1);
+ assert.equal(result.focused, 0);
+ }
+});
+
+test("history restoration and dynamic scrolling do not add tablet navigation records", () => {
+ assert.equal(navigate(["SCROLL", "UNUNDO"]).records.length, 0);
+ assert.equal(navigate(["FOCUSFIRST", "UNCHANGEID"], true, true).records.length, 0);
+ assert.equal(navigate([]).records.length, 0);
+});
+
+test("desktop browsing and explicit focus retain their history behavior", () => {
+ assert.equal(navigate(["SCROLL"], false).records.length, 0);
+ const result = navigate(["FOCUS"], false);
+ assert.equal(result.records.length, 1);
+ assert.equal(result.focused, 1);
+});
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index eecc485aa4..e0d260e4c2 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -33,7 +33,7 @@ import {getEmbeddedDocInfoResponse} from "./docInfo";
import {updateWidgetCacheVersion} from "./widgetCache";
import {normalizeHTMLAssetIFrameSources} from "../../asset/html";
import {getSavedTabFocusTarget, hasFocusOffsets} from "./focusRestore";
-import {isIPhone} from "./compatibility";
+import {isIPhone, isPhablet} from "./compatibility";
import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {disposeCustomBlocksInElement, setCustomBlockRootReady} from "../../plugin/customBlockRender";
import {invalidateTrackedRanges, invalidateTrackedRangesInElement} from "./trackedRange";
@@ -631,6 +631,22 @@ const focusElementById = (protyle: IProtyle, action: string[], scrollAttr?: IScr
/// #endif
}, focusElement.getAttribute("data-type") === "NodeCodeBlock" ? Constants.TIMEOUT_TRANSITION : 0);
}
+ /// #if !MOBILE
+ else if (isPhablet() && !action.includes(Constants.CB_GET_UNUNDO) &&
+ !action.includes(Constants.CB_GET_UNCHANGEID) &&
+ (action.includes(Constants.CB_GET_FOCUS) || action.includes(Constants.CB_GET_FOCUSFIRST) ||
+ action.includes(Constants.CB_GET_SCROLL) || action.includes(Constants.CB_GET_HL))) {
+ // 平板浏览时不聚焦编辑器,仍需记录导航位置,并避免读取其他文档的选区。
+ const editElement = focusElement.classList.contains("protyle-title__input") ?
+ focusElement : getContenteditableElement(focusElement);
+ if (editElement) {
+ const range = document.createRange();
+ range.selectNodeContents(editElement);
+ range.collapse(true);
+ pushBack(protyle, range, focusElement);
+ }
+ }
+ /// #endif
if (hasScrollTop) {
protyle.contentElement.scrollTop = scrollAttr.scrollTop;
}
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index ae778ca7d9..d13616bb09 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -90,7 +90,8 @@ import {openAttr} from "../../menus/commonMenuItem";
import {blockRender} from "../render/blockRender";
/// #if !MOBILE
import {getAllModels} from "../../layout/getAll";
-import {pushBack} from "../../util/backForward";
+import {pushBack, pushBackByClick} from "../../util/backForward";
+import {bindTouchNavigation} from "./touchNavigation";
import {openFileById} from "../../editor/util";
import {openGlobalSearch} from "../../search/util";
/// #else
@@ -105,6 +106,7 @@ import {
isIPhone,
isMac,
isOnlyMeta,
+ isPhablet,
readClipboard,
writeClipboardData
} from "../util/compatibility";
@@ -499,6 +501,13 @@ export class WYSIWYG {
if (!isMobile()) {
bindTouchBlockDragSelect(this.element, () => !protyle.toolbar.isMultiSelectMode());
}
+ /// #if !MOBILE
+ bindTouchNavigation(this.element, (target, point) => {
+ if (!protyle.toolbar.isMultiSelectMode() && !window.siyuan.touchDragActive) {
+ pushBackByClick(protyle, target, point);
+ }
+ });
+ /// #endif
if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {
return;
}
@@ -5090,6 +5099,12 @@ export class WYSIWYG {
const pointerElement = document.elementFromPoint(event.clientX, event.clientY);
const isDirectCalloutClick = isDirectCalloutStructureClick(this.mouseDownTarget, event.target,
pointerElement);
+ /// #if !MOBILE
+ const recordClickHistory = isPhablet();
+ if (recordClickHistory) {
+ pushBackByClick(protyle, event.target, {x: event.clientX, y: event.clientY});
+ }
+ /// #endif
setTimeout(() => {
// 选中后,在选中的文字上点击需等待 range 更新
let newRange = getEditorRange(this.element);
@@ -5181,7 +5196,9 @@ export class WYSIWYG {
focusByRange(newRange);
}
/// #if !MOBILE
- pushBack(protyle, newRange);
+ if (!recordClickHistory) {
+ pushBack(protyle, newRange);
+ }
/// #endif
mobileBlur = false;
}, (isMobile() || isInIOS()) ? 520 : 0); // Android/iPad 双击慢了出不来
diff --git a/app/src/protyle/wysiwyg/touchNavigation.test.ts b/app/src/protyle/wysiwyg/touchNavigation.test.ts
new file mode 100644
index 0000000000..9d80158ebe
--- /dev/null
+++ b/app/src/protyle/wysiwyg/touchNavigation.test.ts
@@ -0,0 +1,75 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/protyle/wysiwyg/touchNavigation.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = () => {
+ const exports: any = {};
+ let time = 0;
+ const targets: unknown[] = [];
+ const points: unknown[] = [];
+ const listeners = new Map<string, (event: any) => void>();
+ const element = {addEventListener: (type: string, listener: (event: any) => void) => listeners.set(type, listener)};
+ runInNewContext(compiled, {
+ exports,
+ require: () => ({Constants: {SIZE_DRAG_THRESHOLD: 5, TIMEOUT_LONGPRESS: 460}}),
+ Date: {now: () => time},
+ });
+ exports.bindTouchNavigation(element, (target: unknown, point: unknown) => {
+ targets.push(target);
+ points.push(point);
+ });
+ const target = {closest: () => element};
+ const send = (type: string, options: any = {}) => {
+ const touch = {identifier: 1, clientX: 100, clientY: 100, ...options.point};
+ listeners.get(type)({
+ target,
+ defaultPrevented: false,
+ touches: type === "touchend" ? [] : [touch],
+ changedTouches: [touch],
+ ...options,
+ });
+ };
+ return {send, targets, points, target, advance: () => time += 500};
+};
+
+test("native touch taps record each paragraph without requiring a click", () => {
+ const f = fixture();
+ f.send("touchstart");
+ f.send("touchend");
+ f.send("touchstart");
+ f.send("touchend");
+ assert.deepEqual(f.targets, [f.target, f.target]);
+ assert.equal(JSON.stringify(f.points), JSON.stringify([{x: 100, y: 100}, {x: 100, y: 100}]));
+});
+
+test("scrolling away and back, cancellation and long presses do not record navigation", () => {
+ const f = fixture();
+ f.send("touchstart");
+ f.send("touchmove", {point: {clientY: 110}});
+ f.send("touchend");
+ f.send("touchstart");
+ f.send("touchcancel");
+ f.send("touchend");
+ f.send("touchstart");
+ f.advance();
+ f.send("touchend");
+ assert.deepEqual(f.targets, []);
+});
+
+test("multi-touch and gestures handled by other controls do not record navigation", () => {
+ const f = fixture();
+ f.send("touchstart");
+ f.send("touchstart", {touches: [{identifier: 1}, {identifier: 2}]});
+ f.send("touchend");
+ f.send("touchstart", {defaultPrevented: true});
+ f.send("touchend");
+ f.send("touchstart");
+ f.send("touchend", {defaultPrevented: true});
+ assert.deepEqual(f.targets, []);
+});
diff --git a/app/src/protyle/wysiwyg/touchNavigation.ts b/app/src/protyle/wysiwyg/touchNavigation.ts
new file mode 100644
index 0000000000..626b8a0d3b
--- /dev/null
+++ b/app/src/protyle/wysiwyg/touchNavigation.ts
@@ -0,0 +1,40 @@
+import {Constants} from "../../constants";
+
+export const bindTouchNavigation = (element: HTMLElement,
+ onTap: (target: HTMLElement, point: {x: number, y: number}) => void) => {
+ let start: {id: number, x: number, y: number, time: number, target: HTMLElement} | undefined;
+ element.addEventListener("touchstart", (event: TouchEvent) => {
+ start = undefined;
+ const target = event.target as HTMLElement;
+ if (event.defaultPrevented || event.touches.length !== 1 ||
+ !target.closest('[contenteditable="true"]')) {
+ return;
+ }
+ const touch = event.touches[0];
+ start = {id: touch.identifier, x: touch.clientX, y: touch.clientY, time: Date.now(), target};
+ }, {passive: true});
+ element.addEventListener("touchmove", (event: TouchEvent) => {
+ const touch = start && Array.from(event.touches).find(item => item.identifier === start.id);
+ if (!touch || event.touches.length !== 1 ||
+ Math.abs(touch.clientX - start.x) >= Constants.SIZE_DRAG_THRESHOLD ||
+ Math.abs(touch.clientY - start.y) >= Constants.SIZE_DRAG_THRESHOLD) {
+ start = undefined;
+ }
+ }, {passive: true});
+ element.addEventListener("touchend", (event: TouchEvent) => {
+ const tap = start;
+ start = undefined;
+ const touch = tap && Array.from(event.changedTouches).find(item => item.identifier === tap.id);
+ // 原生触摸不一定合成点击事件,短按结束时直接记录;滚动、长按和多指手势不进入导航历史。
+ if (!touch || event.defaultPrevented || event.touches.length > 0 ||
+ Date.now() - tap.time >= Constants.TIMEOUT_LONGPRESS ||
+ Math.abs(touch.clientX - tap.x) >= Constants.SIZE_DRAG_THRESHOLD ||
+ Math.abs(touch.clientY - tap.y) >= Constants.SIZE_DRAG_THRESHOLD) {
+ return;
+ }
+ onTap(tap.target, {x: touch.clientX, y: touch.clientY});
+ }, {passive: true});
+ element.addEventListener("touchcancel", () => {
+ start = undefined;
+ }, {passive: true});
+};
diff --git a/app/src/util/backForward.ts b/app/src/util/backForward.ts
index 4484d55f0a..87719aa7d7 100644
--- a/app/src/util/backForward.ts
+++ b/app/src/util/backForward.ts
@@ -297,6 +297,32 @@ export const goForward = async (app: App) => {
}
};
+export const pushBackByClick = (protyle: IProtyle, target: HTMLElement, point?: {x: number, y: number}) => {
+ const blockElement = hasClosestBlock(target);
+ if (!blockElement || !protyle.wysiwyg.element.contains(blockElement) || isInEmbedBlock(blockElement)) {
+ return;
+ }
+ const editElement = getContenteditableElement(blockElement);
+ if (!editElement) {
+ return;
+ }
+ const selection = editElement.ownerDocument.getSelection();
+ let range = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
+ // 触摸结束时选区可能仍在旧位置,按触摸坐标记录文字偏移,且不改变浏览器选区。
+ if (point) {
+ const pointRange = editElement.ownerDocument.caretRangeFromPoint?.(point.x, point.y);
+ if (pointRange && editElement.contains(pointRange.startContainer) && editElement.contains(pointRange.endContainer)) {
+ range = pointRange;
+ }
+ }
+ if (!range || !editElement.contains(range.startContainer) || !editElement.contains(range.endContainer)) {
+ range = editElement.ownerDocument.createRange();
+ range.selectNodeContents(editElement);
+ range.collapse(true);
+ }
+ pushBack(protyle, range, blockElement);
+};
+
export const pushBack = (protyle: IProtyle, range?: Range, blockElement?: Element) => {
if (!protyle.model) {
return;
diff --git a/app/src/util/backForwardClick.test.ts b/app/src/util/backForwardClick.test.ts
new file mode 100644
index 0000000000..db5c6a8e3c
--- /dev/null
+++ b/app/src/util/backForwardClick.test.ts
@@ -0,0 +1,74 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);
+const declarations = source.statements.filter(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item =>
+ ["pushBackByClick", "pushBack", "goBack", "goForward", "forwardStack", "previousIsBack"].includes(item.name.getText(source))));
+const compiled = transpileModule(declarations.map(item => item.getText(source)).join("\n"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+test("tablet paragraph clicks navigate back and forward despite a stale title selection", async () => {
+ const exports: any = {};
+ const focused: string[] = [];
+ const stacks: any[] = [];
+ let selectionRange: any = {startContainer: "title", endContainer: "title", offset: 0};
+ let pointRange: any;
+ const documentSelf = {
+ contains: () => true,
+ querySelector: (): undefined => undefined,
+ getSelection: () => ({rangeCount: 1, getRangeAt: () => selectionRange}),
+ caretRangeFromPoint: () => pointRange,
+ createRange: () => ({
+ startContainer: "", endContainer: "", offset: 0,
+ selectNodeContents(element: any) { this.startContainer = element.id; this.endContainer = element.id; },
+ collapse() {},
+ }),
+ };
+ const block = (id: string) => ({
+ id,
+ ownerDocument: documentSelf,
+ contains: (node: string) => node === id,
+ getAttribute: () => id,
+ classList: {contains: () => false},
+ });
+ runInNewContext(compiled, {
+ exports,
+ window: {siyuan: {backStack: stacks}},
+ document: documentSelf,
+ Constants: {SIZE_UNDO: 128},
+ hasClosestBlock: (target: unknown) => target,
+ isInEmbedBlock: () => false,
+ getContenteditableElement: (element: unknown) => element,
+ getSelectionOffset: (_element: unknown, _editor: unknown, range: any) => ({start: range.offset, end: range.offset}),
+ focusStack: async (_app: unknown, stack: any) => { focused.push(stack.id); return true; },
+ });
+ const protyle = {model: {}, block: {rootID: "title"}, wysiwyg: {element: {contains: () => true}}};
+ exports.pushBack(protyle, selectionRange, block("title"));
+ pointRange = {startContainer: "first", endContainer: "first", offset: 8};
+ exports.pushBackByClick(protyle, block("first"), {x: 100, y: 100});
+ assert.equal(stacks.at(-1).position.start, 8);
+ selectionRange = {startContainer: "first", endContainer: "first", offset: 4};
+ pointRange = {startContainer: "second", endContainer: "second", offset: 12};
+ exports.pushBackByClick(protyle, block("second"), {x: 100, y: 140});
+ assert.equal(stacks.at(-1).position.start, 12);
+ assert.deepEqual(stacks.map(stack => stack.id), ["title", "first", "second"]);
+ await exports.goBack({});
+ assert.equal(focused.at(-1), "first");
+ await exports.goForward({});
+ assert.equal(focused.at(-1), "second");
+ selectionRange = {startContainer: "second", endContainer: "second", offset: 7};
+ exports.pushBackByClick(protyle, block("second"));
+ assert.equal(stacks.at(-1).position.start, 7);
+ pointRange = {startContainer: "second", endContainer: "second", offset: 15};
+ exports.pushBackByClick(protyle, block("second"), {x: 150, y: 140});
+ assert.equal(stacks.at(-1).position.start, 15);
+ assert.equal(selectionRange.offset, 7);
+ pointRange = {startContainer: "first", endContainer: "first", offset: 3};
+ exports.pushBackByClick(protyle, block("second"), {x: 10, y: 10});
+ assert.equal(stacks.at(-1).position.start, 7);
+});