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: Preserve tablet navigation history and reading positions https://github.com/siyuan-note/siyuan/issues/19624
Vanessa6fb8f560c73f
diff --git a/app/src/editor/navigationHistory.test.ts b/app/src/editor/navigationHistory.test.tsindex 8aa0edcde7..c374a852dd 100644--- a/app/src/editor/navigationHistory.test.ts+++ b/app/src/editor/navigationHistory.test.ts@@ -5,9 +5,11 @@ import {runInNewContext} from "node:vm";import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";const source = createSourceFile("util.ts", readFileSync("src/editor/util.ts", "utf8"), ScriptTarget.ES2021, true);-const declaration = source.statements.find(statement => isVariableStatement(statement) &&- statement.declarationList.declarations.some(item => item.name.getText(source) === "updatePanelByEditor"));-const compiled = transpileModule(declaration.getText(source).replace(/^export /, "") + "\nglobalThis.update = updatePanelByEditor;", {+const declarations = source.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item =>+ ["updatePanelByEditor", "pushBackByEditor", "switchEditor"].includes(item.name.getText(source))));+const compiled = transpileModule(declarations.map(item => item.getText(source).replace(/^export /, "")).join("\n") ++ "\nglobalThis.update = updatePanelByEditor; globalThis.openExisting = switchEditor;", {compilerOptions: {target: ScriptTarget.ES2021},}).outputText;@@ -67,54 +69,90 @@ test("history restoration and preview tab switches do not create history entriesassert.equal(records.length, 0);});-test("tablet tab switches navigate A B C backward and forward without touching the editor", async () => {- const {context} = setup();- const historySource = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);- const names = ["pushBack", "goBack", "goForward", "forwardStack", "previousIsBack"];- const declarations = historySource.statements.filter(statement => isVariableStatement(statement) &&- statement.declarationList.declarations.some(item => names.includes(item.name.getText(historySource))));- const history = declarations.map(item => item.getText(historySource).replace(/^export /, "")).join("\n");- const stacks: any[] = [];- const visited: string[] = [];- context.window.siyuan.backStack = stacks;- context.document.contains = () => true;- context.document.querySelector = (): undefined => undefined;- context.Constants = {SIZE_UNDO: 128};- context.readingPositions = new WeakMap();- context.saveBackScroll = () => {};- context.hasClosestBlock = (node: unknown) => node;- context.getSelectionOffset = () => ({start: 0, end: 0});- const switchTab = (protyle: unknown, pushBackStack: boolean) => context.update({- protyle, focus: false, pushBackStack, resize: false, reload: false,- });- context.focusStack = async (_app: unknown, stack: any) => {- visited.push(stack.protyle.block.rootID);- switchTab(stack.protyle, false);- return true;- };- runInNewContext(transpileModule(history + "\nglobalThis.back = goBack; globalThis.forward = goForward;", {- compilerOptions: {target: ScriptTarget.ES2021},- }).outputText, context);- const tabs = ["A", "B", "C"].map(id => {- const block = {getAttribute: () => id + "-block", classList: {contains: () => false}};- return {- model: {}, block: {rootID: id}, path: "/" + id + ".sy",- element: {classList: {contains: () => false}, contains: (node: unknown) => node === block},- toolbar: {}, wysiwyg: {element: {firstElementChild: block}},- preview: {element: {classList: {contains: () => true}}},+test("tablet links to an already loaded block record the destination instead of a stale caret", () => {+ const {context, records, protyle, block} = setup();+ const target = {clientHeight: 20, contains: () => false};+ protyle.toolbar.range = {startContainer: block, endContainer: block};+ Object.assign(protyle.wysiwyg.element, {querySelectorAll: () => [target]});+ context.isPhablet = () => true;+ context.isInEmbedBlock = () => false;+ context.revealTabsForTarget = () => {};+ context.preventScroll = () => {};+ context.highlightById = () => {};+ context.Constants = {CB_GET_HL: "highlight", CB_GET_FOCUS: "focus"};+ context.openExisting({editor: {protyle}, parent: {headElement: {}, parent: {+ switchTab: () => {}, showHeading: () => {},+ }}}, {id: "target", rootID: "doc", action: ["highlight"]}, {});+ assert.equal(records.length, 1);+ assert.equal(records[0].range.startContainer, target);+ assert.equal(records[0].range.endContainer, target);+});++for (const fromFileTree of [false, true]) {+ test(`tablet ${fromFileTree ? "file tree opens" : "tab switches"} navigate A B C backward and forward without touching the editor`, async () => {+ const {context} = setup();+ const historySource = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);+ const names = ["pushBack", "goBack", "goForward", "forwardStack", "previousIsBack"];+ const declarations = historySource.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item => names.includes(item.name.getText(historySource))));+ const history = declarations.map(item => item.getText(historySource).replace(/^export /, "")).join("\n");+ const stacks: any[] = [];+ const visited: string[] = [];+ context.window.siyuan.backStack = stacks;+ context.document.contains = () => true;+ context.document.querySelector = (): undefined => undefined;+ context.Constants = {SIZE_UNDO: 128};+ context.readingPositions = new WeakMap();+ context.saveBackScroll = () => {};+ context.hasClosestBlock = (node: unknown) => node;+ context.getSelectionOffset = () => ({start: 0, end: 0});+ context.isPhablet = () => true;+ context.preventScroll = () => {};+ const switchTab = (protyle: unknown, pushBackStack: boolean) => context.update({+ protyle, focus: false, pushBackStack, resize: false, reload: false,+ });+ context.focusStack = async (_app: unknown, stack: any) => {+ visited.push(stack.protyle.block.rootID);+ switchTab(stack.protyle, false);+ return true;+ };+ runInNewContext(transpileModule(history + "\nglobalThis.back = goBack; globalThis.forward = goForward;", {+ compilerOptions: {target: ScriptTarget.ES2021},+ }).outputText, context);+ const tabs = ["A", "B", "C"].map(id => {+ const block = {getAttribute: () => id + "-block", classList: {contains: () => false}};+ return {+ model: {}, block: {rootID: id}, path: "/" + id + ".sy",+ element: {classList: {contains: () => false}, contains: (node: unknown) => node === block},+ toolbar: {}, wysiwyg: {element: {firstElementChild: block, querySelectorAll: () => []}},+ preview: {element: {classList: {contains: () => true}}},+ };+ });+ const open = (protyle: typeof tabs[number]) => {+ if (fromFileTree) {+ context.openExisting({+ editor: {protyle},+ parent: {headElement: {}, parent: {+ switchTab: (_head: unknown, pushBackStack = false) => switchTab(protyle, pushBackStack),+ showHeading: () => {},+ }},+ }, {id: protyle.block.rootID, rootID: protyle.block.rootID, action: ["scroll"]}, {});+ } else {+ switchTab(protyle, true);+ }};+ tabs.forEach(open);+ open(tabs[2]);+ assert.deepEqual(stacks.map(stack => stack.protyle.block.rootID), ["A", "B", "C"]);+ await context.back({});+ await context.back({});+ await context.forward({});+ await context.forward({});+ assert.deepEqual(visited, ["B", "A", "B", "C"]);});- tabs.forEach(tab => switchTab(tab, true));- switchTab(tabs[2], true);- assert.deepEqual(stacks.map(stack => stack.protyle.block.rootID), ["A", "B", "C"]);- await context.back({});- await context.back({});- await context.forward({});- await context.forward({});- assert.deepEqual(visited, ["B", "A", "B", "C"]);-});+}-const restoreClosedHistoryEntry = async (disabled: boolean) => {+const restoreClosedHistoryEntry = async (disabled: boolean, readingPosition?: IScrollAttr, encrypted = false) => {const historySource = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);const declaration = historySource.statements.find(statement => isVariableStatement(statement) &&statement.declarationList.declarations.some(item => item.name.getText(historySource) === "focusStack"));@@ -154,8 +192,9 @@ const restoreClosedHistoryEntry = async (disabled: boolean) => {fetchSyncPost: async (path: string) => path.endsWith("checkBlockExist") ?{code: 0, data: true} : {code: 0, data: {rootID: "A", rootTitle: "A", rootIcon: ""}},getInstanceById: () => wnd,- isEncryptedBox: () => false,- isPhablet: () => false,+ isEncryptedBox: () => encrypted,+ isPhablet: () => !!readingPosition,+ readingPositions: new WeakMap(),saveScroll: (): undefined => undefined,forwardStack: [],focusByOffset: () => calls.push("focus"),@@ -177,8 +216,12 @@ const restoreClosedHistoryEntry = async (disabled: boolean) => {runInNewContext(transpileModule(declaration.getText(historySource).replace(/^export /, "") +"\nglobalThis.restore = focusStack;", {compilerOptions: {target: ScriptTarget.ES2021}}).outputText, context);const stack = {id: "A", position: {start: 2, end: 2}, protyle: {element: oldElement, block: {rootID: "A"}, notebookId: "notebook"}};+ if (readingPosition) {+ stack.id = "A-block";+ context.readingPositions.set(stack, readingPosition);+ }assert.equal(await context.restore({}, stack), true);- return {calls, protyle, editorOptions, afterInit};+ return {calls, protyle, editorOptions, afterInit, storage: context.window.siyuan.storage.positions};};test("history restores a closed document through the focused preview tab without early focus", async () => {@@ -196,6 +239,21 @@ test("history does not focus a read-only document after it loads", async () => {assert.deepEqual(calls, ["blur", "remove:current:false:false"]);});+for (const encrypted of [false, true]) {+ test(`closed tablet history restores its own reading position for encrypted=${encrypted}`, async () => {+ const readingPosition = {rootId: "A", startId: "first", endId: "last", scrollTop: 1133};+ const {calls, editorOptions, afterInit, storage} = await restoreClosedHistoryEntry(false, readingPosition, encrypted);+ assert.equal(editorOptions.scrollAttr.scrollTop, 1133);+ assert.equal(editorOptions.scrollAttr.startId, "first");+ assert.equal(editorOptions.scrollAttr.endId, "last");+ assert.equal(editorOptions.scrollAttr.focusId, "A-block");+ assert.equal("focusId" in readingPosition, false);+ assert.equal(!!storage.A, !encrypted);+ afterInit();+ assert.deepEqual(calls, ["blur", "remove:current:false:false"]);+ });+}+test("history switches to an open read-only tab without focusing its editor", async () => {const historySource = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);const declaration = historySource.statements.find(statement => isVariableStatement(statement) &&diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex 497322228e..ecd33eb9e4 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -419,6 +419,24 @@ const getUnInitTab = (options: IOpenFileOptions) => {});};+const pushBackByEditor = (protyle: IProtyle, block?: Element) => {+ // 浏览页签时记录位置,不聚焦编辑器,避免唤起软键盘。+ const range = protyle.toolbar.range;+ const container = block || protyle.element;+ if (range && container.contains(range.startContainer) && container.contains(range.endContainer)) {+ pushBack(protyle, range, block);+ } else {+ block = block || protyle.wysiwyg.element.firstElementChild;+ const editable = block && getContenteditableElement(block);+ if (editable) {+ const initialRange = document.createRange();+ initialRange.selectNodeContents(editable);+ initialRange.collapse(true);+ pushBack(protyle, initialRange, block);+ }+ }+};+const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IModels) => {if (options.keepCursor) {editor.parent.headElement.setAttribute("keep-cursor", options.id);@@ -549,7 +567,11 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IModscrollCenter(editor.editor.protyle, undefined, options.scrollPosition);}}- pushBack(editor.editor.protyle, editor.editor.protyle.toolbar.range);+ if (isPhablet()) {+ pushBackByEditor(editor.editor.protyle, nodeElement);+ } else {+ pushBack(editor.editor.protyle, editor.editor.protyle.toolbar.range);+ }}// https://github.com/siyuan-note/siyuan/issues/16445if (options.action?.includes(Constants.CB_GET_OUTLINE)) {@@ -695,21 +717,7 @@ export const updatePanelByEditor = (options: {}}if (!options.focus && options.pushBackStack && options.protyle.preview.element.classList.contains("fn__none")) {- // 浏览页签时记录位置,不聚焦编辑器,避免唤起软键盘。- const protyle = options.protyle;- const range = protyle.toolbar.range;- if (range && protyle.element.contains(range.startContainer) && protyle.element.contains(range.endContainer)) {- pushBack(protyle, range);- } else {- const block = protyle.wysiwyg.element.firstElementChild;- const editable = block && getContenteditableElement(block);- if (editable) {- const initialRange = document.createRange();- initialRange.selectNodeContents(editable);- initialRange.collapse(true);- pushBack(protyle, initialRange, block);- }- }+ pushBackByEditor(options.protyle);}if (window.siyuan.config.fileTree.alwaysSelectOpenedFile && options.protyle) {const fileModel = getDockByType("file")?.data.file;diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.tsindex b141d81f41..ba637da473 100644--- a/app/src/layout/Wnd.ts+++ b/app/src/layout/Wnd.ts@@ -987,6 +987,7 @@ export class Wnd {item.model.beforeDestroy();}if (item.model instanceof Editor) {+ saveBackScroll(item.model.editor.protyle);saveScroll(item.model.editor.protyle);// 更新文档关闭时间(批量关闭页签时由 closeTabByType 批量处理,这里不单独调用)if (!isBatchClose) {diff --git a/app/src/protyle/util/navigationHistory.test.ts b/app/src/protyle/util/navigationHistory.test.tsindex e62f3de346..7b416de3c4 100644--- a/app/src/protyle/util/navigationHistory.test.ts+++ b/app/src/protyle/util/navigationHistory.test.ts@@ -25,6 +25,7 @@ const navigate = (action: string[], tablet = true, suppressFocus = false) => {isPhablet: () => tablet,hasFocusOffsets: () => false,isInEmbedBlock: () => false,+ resolveVisibleListMindmapBlock: (): undefined => undefined,hasClosestByAttribute: () => false,getContenteditableElement: () => element,document: {createRange: () => range},@@ -43,6 +44,7 @@ const navigate = (action: string[], tablet = true, suppressFocus = false) => {};runInNewContext(compiled, context);context.navigate({+ element: {addEventListener: () => {}},block: {id: "block", rootID: "root"},wysiwyg: {element: {ownerDocument: {activeElement: null}, querySelectorAll: () => [element], firstElementChild: element}},contentElement: {addEventListener: () => {}},diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex ddc6786594..2dd837725b 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -101,6 +101,7 @@ import {blockRender} from "../render/blockRender";import {getAllModels} from "../../layout/getAll";import {pushBack, pushBackByClick} from "../../util/backForward";import {bindTouchNavigation} from "./touchNavigation";+import {openTouchReference} from "./touchReference";import {openFileById} from "../../editor/util";import {openGlobalSearch} from "../../search/util";/// #else@@ -541,6 +542,9 @@ export class WYSIWYG {/// #if !MOBILEbindTouchNavigation(this.element, (target, point) => {if (!protyle.toolbar.isMultiSelectMode() && !window.siyuan.touchDragActive) {+ if (openTouchReference(protyle, target, point)) {+ return true;+ }pushBackByClick(protyle, target, point);}});diff --git a/app/src/protyle/wysiwyg/touchNavigation.test.ts b/app/src/protyle/wysiwyg/touchNavigation.test.tsindex 9d80158ebe..52f564c86e 100644--- a/app/src/protyle/wysiwyg/touchNavigation.test.ts+++ b/app/src/protyle/wysiwyg/touchNavigation.test.ts@@ -8,11 +8,12 @@ const compiled = transpileModule(readFileSync("src/protyle/wysiwyg/touchNavigaticompilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;-const fixture = () => {+const fixture = (handled = false) => {const exports: any = {};let time = 0;const targets: unknown[] = [];const points: unknown[] = [];+ let prevented = 0;const listeners = new Map<string, (event: any) => void>();const element = {addEventListener: (type: string, listener: (event: any) => void) => listeners.set(type, listener)};runInNewContext(compiled, {@@ -23,6 +24,7 @@ const fixture = () => {exports.bindTouchNavigation(element, (target: unknown, point: unknown) => {targets.push(target);points.push(point);+ return handled;});const target = {closest: () => element};const send = (type: string, options: any = {}) => {@@ -30,12 +32,13 @@ const fixture = () => {listeners.get(type)({target,defaultPrevented: false,+ preventDefault: () => prevented++,touches: type === "touchend" ? [] : [touch],changedTouches: [touch],...options,});};- return {send, targets, points, target, advance: () => time += 500};+ return {send, targets, points, target, advance: () => time += 500, prevented: () => prevented};};test("native touch taps record each paragraph without requiring a click", () => {@@ -45,9 +48,18 @@ test("native touch taps record each paragraph without requiring a click", () =>f.send("touchstart");f.send("touchend");assert.deepEqual(f.targets, [f.target, f.target]);+ assert.equal(f.prevented(), 0);assert.equal(JSON.stringify(f.points), JSON.stringify([{x: 100, y: 100}, {x: 100, y: 100}]));});+test("handled reference taps suppress the compatibility click", () => {+ const f = fixture(true);+ f.send("touchstart");+ f.send("touchend");+ assert.equal(f.targets.length, 1);+ assert.equal(f.prevented(), 1);+});+test("scrolling away and back, cancellation and long presses do not record navigation", () => {const f = fixture();f.send("touchstart");diff --git a/app/src/protyle/wysiwyg/touchNavigation.ts b/app/src/protyle/wysiwyg/touchNavigation.tsindex 626b8a0d3b..0dc9a3bbd8 100644--- a/app/src/protyle/wysiwyg/touchNavigation.ts+++ b/app/src/protyle/wysiwyg/touchNavigation.ts@@ -1,7 +1,7 @@import {Constants} from "../../constants";export const bindTouchNavigation = (element: HTMLElement,- onTap: (target: HTMLElement, point: {x: number, y: number}) => void) => {+ onTap: (target: HTMLElement, point: {x: number, y: number}) => boolean | void) => {let start: {id: number, x: number, y: number, time: number, target: HTMLElement} | undefined;element.addEventListener("touchstart", (event: TouchEvent) => {start = undefined;@@ -32,8 +32,11 @@ export const bindTouchNavigation = (element: HTMLElement,Math.abs(touch.clientY - tap.y) >= Constants.SIZE_DRAG_THRESHOLD) {return;}- onTap(tap.target, {x: touch.clientX, y: touch.clientY});- }, {passive: true});+ if (onTap(tap.target, {x: touch.clientX, y: touch.clientY})) {+ // 已处理链接导航,阻止浏览器随后合成点击而重复打开。+ event.preventDefault();+ }+ }, {passive: false});element.addEventListener("touchcancel", () => {start = undefined;}, {passive: true});diff --git a/app/src/protyle/wysiwyg/touchReference.test.ts b/app/src/protyle/wysiwyg/touchReference.test.tsnew file mode 100644index 0000000000..fb9b91f561--- /dev/null+++ b/app/src/protyle/wysiwyg/touchReference.test.ts@@ -0,0 +1,61 @@+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/touchReference.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const fixture = (options: {reference?: string, uri?: any, selection?: string, root?: boolean} = {}) => {+ const exports: any = {};+ const calls: string[] = [];+ let opened: any;+ const dependencies = {+ Constants: {CB_GET_HL: "highlight"},+ openFileById: (value: any) => { calls.push("open"); opened = value; },+ pushBackByClick: () => calls.push("record"),+ saveBackScroll: () => calls.push("save"),+ hideElements: () => calls.push("hide"),+ processSiYuanUri: () => calls.push("uri"),+ checkFold: (_id: string, callback: any) => callback(true, ["all"], options.root),+ parseSiYuanUriInfo: () => options.uri,+ hasClosestByAttribute: (_target: any, _name: string, type: string) => type === "block-ref" ?+ options.reference && {getAttribute: () => options.reference} : {getAttribute: () => "siyuan://blocks/target"},+ };+ runInNewContext(compiled, {+ exports,+ require: () => dependencies,+ window: {getSelection: () => ({toString: () => options.selection || ""})},+ });+ const result = exports.openTouchReference({app: "app"}, {}, {x: 10, y: 20});+ return {result, calls, opened};+};++test("touch references and internal links save the source before opening a folded target", () => {+ for (const options of [{reference: "target"}, {uri: {id: "target"}}]) {+ const f = fixture(options);+ assert.equal(f.result, true);+ assert.deepEqual(f.calls, ["record", "save", "hide", "open"]);+ assert.equal(f.opened.id, "target");+ assert.equal(f.opened.zoomIn, true);+ assert.equal(f.opened.scrollPosition, "start");+ assert.deepEqual(Array.from(f.opened.action), ["all", "highlight"]);+ }+});++test("document links and attribute-view links retain their navigation behavior", () => {+ const root = fixture({uri: {id: "target"}, root: true});+ assert.deepEqual(Array.from(root.opened.action), ["all"]);+ const av = fixture({uri: {id: "target", avItemID: "row"}});+ assert.deepEqual(av.calls, ["record", "save", "hide", "uri"]);+});++test("text selection, ordinary text and external or invalid links do not navigate", () => {+ for (const options of [{selection: "selected", reference: "target"}, {}, {uri: null}]) {+ const f = fixture(options);+ assert.equal(f.result, false);+ assert.deepEqual(f.calls, []);+ }+});diff --git a/app/src/protyle/wysiwyg/touchReference.ts b/app/src/protyle/wysiwyg/touchReference.tsnew file mode 100644index 0000000000..b9ba04b1ed--- /dev/null+++ b/app/src/protyle/wysiwyg/touchReference.ts@@ -0,0 +1,37 @@+import {Constants} from "../../constants";+import {openFileById} from "../../editor/util";+import {pushBackByClick, saveBackScroll} from "../../util/backForward";+import {checkFold} from "../../util/noRelyPCFunction";+import {parseSiYuanUriInfo} from "../../util/pathName";+import {processSiYuanUri} from "../../util/uri";+import {hideElements} from "../ui/hideElements";+import {hasClosestByAttribute} from "../util/hasClosest";++export const openTouchReference = (protyle: IProtyle, target: HTMLElement, point: {x: number, y: number}) => {+ if (window.getSelection()?.toString()) {+ return false;+ }+ const reference = hasClosestByAttribute(target, "data-type", "block-ref");+ const link = hasClosestByAttribute(target, "data-type", "a");+ const href = link ? link.getAttribute("data-href") || "" : "";+ const uri = parseSiYuanUriInfo(href);+ const id = reference ? reference.getAttribute("data-id") : uri?.id;+ if (!id) {+ return false;+ }+ // 触摸跳转直接记录来源,不获取编辑光标,避免唤起软键盘。+ pushBackByClick(protyle, target, point);+ saveBackScroll(protyle);+ hideElements(["dialog", "toolbar"], protyle);+ if (!reference && uri?.avItemID) {+ processSiYuanUri(protyle.app, href);+ } else {+ checkFold(id, (zoomIn, action, isRoot) => {+ if (!isRoot) {+ action.push(Constants.CB_GET_HL);+ }+ openFileById({app: protyle.app, id, action, zoomIn, scrollPosition: "start"});+ });+ }+ return true;+};diff --git a/app/src/util/backForward.ts b/app/src/util/backForward.tsindex 91ce55ccb4..91faa36e9e 100644--- a/app/src/util/backForward.ts+++ b/app/src/util/backForward.ts@@ -46,12 +46,15 @@ export const saveBackScroll = (protyle?: IProtyle) => {}const position = saveScroll(stack.protyle, true) as IScrollAttr;if (position) {+ // 可见编辑器的零滚动位置有效,不使用隐藏页签留下的滚动缓存。+ position.scrollTop = stack.protyle.contentElement.scrollTop;readingPositions.set(stack, position);}};const focusStack = async (app: App, stack: IBackStack) => {hideElements(["gutter", "toolbar", "hint", "util", "dialog"], stack.protyle);+ const readingPosition = isPhablet() ? readingPositions.get(stack) : undefined;let blockElement: HTMLElement;if (!document.contains(stack.protyle.element)) {const response = await fetchSyncPost("/api/block/checkBlockExist", {id: stack.protyle.block.rootID});@@ -89,7 +92,7 @@ const focusStack = async (app: App, stack: IBackStack) => {title: info.data.rootTitle,docIcon: info.data.rootIcon,callback(tab) {- const scrollAttr = (saveScroll(stack.protyle, true) || {}) as IScrollAttr;+ const scrollAttr = {...(readingPosition || saveScroll(stack.protyle, true) || {})} as IScrollAttr;scrollAttr.rootId = stack.protyle.block.rootID;scrollAttr.focusId = stack.id;scrollAttr.focusStart = stack.position.start;@@ -103,6 +106,7 @@ const focusStack = async (app: App, stack: IBackStack) => {blockId: stack.zoomId || stack.id || stack.protyle.block.rootID,rootId: stack.protyle.block.rootID,notebookId: stack.protyle.notebookId,+ scrollAttr,action: stack.zoomId ? [Constants.CB_GET_SCROLL, Constants.CB_GET_ALL, Constants.CB_GET_UNUNDO] :[Constants.CB_GET_SCROLL, Constants.CB_GET_UNUNDO],afterInitProtyle(editor) {@@ -110,6 +114,9 @@ const focusStack = async (app: App, stack: IBackStack) => {if (!document.contains(protyle.element) || !tab.headElement.classList.contains("item--focus")) {return;}+ if (readingPosition) {+ return;+ }if (info.data.rootID === stack.id) {if (!protyle.disabled && !isPhablet()) {focusByOffset(protyle.title.editElement, stack.position.start, stack.position.end);@@ -168,13 +175,12 @@ const focusStack = async (app: App, stack: IBackStack) => {}const currentZoomId = stack.protyle.block.showAll ? stack.protyle.block.id : undefined;- const readingPosition = readingPositions.get(stack);- if (isPhablet() && readingPosition && currentZoomId === stack.zoomId) {+ if (readingPosition) {// 阅读位置独立于旧光标,显示页签后按离开时的加载范围和滚动值恢复。stack.protyle.model.parent.parent.switchTab(stack.protyle.model.parent.headElement);const first = stack.protyle.wysiwyg.element.firstElementChild?.getAttribute("data-node-id");const last = stack.protyle.wysiwyg.element.lastElementChild?.getAttribute("data-node-id");- if (first === readingPosition.startId && last === readingPosition.endId) {+ if (currentZoomId === stack.zoomId && first === readingPosition.startId && last === readingPosition.endId) {stack.protyle.contentElement.scrollTop = readingPosition.scrollTop;return true;}@@ -262,6 +268,7 @@ const focusStack = async (app: App, stack: IBackStack) => {onGet({data: getResponse,protyle: stack.protyle,+ action: [Constants.CB_GET_UNUNDO],afterCB() {Array.from(stack.protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${stack.id}"]`)).find((item: HTMLElement) => {if (!isInEmbedBlock(item)) {@@ -432,20 +439,20 @@ export const pushBack = (protyle: IProtyle, range?: Range, blockElement?: Elemenif (editElement) {const position = getSelectionOffset(editElement, undefined, range);const id = blockElement.getAttribute("data-node-id") || protyle.block.rootID;+ // 后退后先将当前记录归还后退栈,再去重,确保新导航能够替换前进分支。+ if (previousIsBack && forwardStack.length > 0) {+ window.siyuan.backStack.push(forwardStack.pop());+ }+ forwardStack = [];+ previousIsBack = false;+ document.querySelector("#barForward")?.classList.add("toolbar__item--disabled");const lastStack = window.siyuan.backStack[window.siyuan.backStack.length - 1];- if (lastStack && lastStack.id === id && (+ if (lastStack && lastStack.protyle === protyle && lastStack.id === id && ((protyle.block.showAll && lastStack.zoomId === protyle.block.id) || (!lastStack.zoomId && !protyle.block.showAll))) {lastStack.position = position;readingPositions.delete(lastStack);} else {- if (forwardStack.length > 0) {- if (previousIsBack) {- window.siyuan.backStack.push(forwardStack.pop());- }- forwardStack = [];- document.querySelector("#barForward")?.classList.add("toolbar__item--disabled");- }window.siyuan.backStack.push({position,id,@@ -455,7 +462,6 @@ export const pushBack = (protyle: IProtyle, range?: Range, blockElement?: Elemenif (window.siyuan.backStack.length > Constants.SIZE_UNDO) {window.siyuan.backStack.shift();}- previousIsBack = false;}if (window.siyuan.backStack.length > 1) {document.querySelector("#barBack")?.classList.remove("toolbar__item--disabled");diff --git a/app/src/util/backForwardState.test.ts b/app/src/util/backForwardState.test.tsnew file mode 100644index 0000000000..d95de38b63--- /dev/null+++ b/app/src/util/backForwardState.test.ts@@ -0,0 +1,90 @@+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("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);+const names = ["pushBack", "goBack", "goForward", "forwardStack", "previousIsBack"];+const declarations = source.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(item => names.includes(item.name.getText(source))));+const compiled = transpileModule(declarations.map(item => item.getText(source).replace(/^export /, "")).join("\n") ++ "\nglobalThis.history = {pushBack, goBack, goForward};", {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;++const setup = () => {+ const stacks: any[] = [];+ const visited: any[] = [];+ const buttons = new Map<string, Set<string>>();+ const context: any = {+ window: {siyuan: {backStack: stacks}},+ document: {+ contains: () => true,+ querySelector: (id: string) => {+ if (!buttons.has(id)) {+ buttons.set(id, new Set());+ }+ return {classList: {+ add: (value: string) => buttons.get(id).add(value),+ remove: (value: string) => buttons.get(id).delete(value),+ }};+ },+ },+ Constants: {SIZE_UNDO: 128},+ readingPositions: new WeakMap(),+ saveBackScroll: () => {},+ getContenteditableElement: (block: unknown) => block,+ getSelectionOffset: (_block: unknown, _editor: unknown, range: any) => ({start: range?.offset || 0, end: range?.offset || 0}),+ focusStack: async (_app: unknown, stack: any) => { visited.push(stack); return true; },+ };+ runInNewContext(compiled, context);+ const tabs = ["A", "B", "C"].map(id => ({model: {}, element: {}, block: {rootID: id}}));+ const push = (protyle: any, offset = 0) => context.history.pushBack(protyle, {offset}, {+ classList: {contains: () => false}, getAttribute: () => protyle.block.rootID,+ });+ return {stacks, visited, tabs, push, buttons, context, history: context.history};+};++test("opening a previous document after back creates a new branch and discards forward history", async () => {+ const {stacks, visited, tabs: [a, b, c], push, buttons, history} = setup();+ [a, b, c].forEach(tab => push(tab));+ await history.goBack({});+ push(a);+ assert.deepEqual(stacks.map(stack => stack.protyle), [a, b, a]);+ assert.equal(buttons.get("#barForward").has("toolbar__item--disabled"), true);+ await history.goForward({});+ assert.equal(visited.at(-1).protyle, a);+ await history.goBack({});+ assert.equal(visited.at(-1).protyle, b);+ await history.goForward({});+ assert.equal(visited.at(-1).protyle, a);+});++test("updating the current block after back does not insert a duplicate history entry", async () => {+ const {stacks, tabs: [a, b, c], push, history} = setup();+ [a, b, c].forEach(tab => push(tab));+ await history.goBack({});+ push(b, 7);+ assert.deepEqual(stacks.map(stack => stack.protyle), [a, b]);+ assert.equal(stacks.at(-1).position.start, 7);+});++test("the same document in different editors remains two navigation destinations", async () => {+ const {stacks, visited, tabs: [a], push, history} = setup();+ const split = {...a, element: {}};+ push(a);+ push(split);+ assert.equal(stacks.length, 2);+ await history.goBack({});+ assert.equal(visited.at(-1).protyle, a);+ await history.goForward({});+ assert.equal(visited.at(-1).protyle, split);+});++test("an invalid navigation record does not discard forward history", async () => {+ const {visited, tabs: [a, b, c], push, history} = setup();+ [a, b, c].forEach(tab => push(tab));+ await history.goBack({});+ history.pushBack(a);+ await history.goForward({});+ assert.equal(visited.at(-1).protyle, c);+});diff --git a/app/src/util/readingHistory.test.ts b/app/src/util/readingHistory.test.tsindex 63307c7345..78a7485eb5 100644--- a/app/src/util/readingHistory.test.ts+++ b/app/src/util/readingHistory.test.ts@@ -28,45 +28,73 @@ test("tab visibility changes preserve a scrolled viewport including zero", () =>});for (const changedRange of [false, true]) {- test(`tablet history restores reading position with ${changedRange ? "reloaded" : "retained"} blocks`, async () => {- let visible = true;- let switched = 0;- let reloaded = 0;- const protyle = {- element: {getBoundingClientRect: () => ({height: visible ? 700 : 0})},- contentElement: {scrollTop: 1133},- block: {rootID: "doc"},- wysiwyg: {element: {- firstElementChild: {getAttribute: () => changedRange ? "changed" : "first"},- lastElementChild: {getAttribute: () => "last"},- }},- model: {parent: {headElement: {}, parent: {switchTab: () => { switched++; visible = true; }}}},- };- const stack = {id: "old-caret", protyle};- const context: any = {- previousIsBack: false,- forwardStack: [],- window: {siyuan: {backStack: [stack]}},- isPhablet: () => true,- saveScroll: () => ({rootId: "doc", startId: "first", endId: "last", scrollTop: protyle.contentElement.scrollTop}),- document: {contains: () => true},- hideElements: () => {},- getDocByScroll: (options: any) => {- reloaded++;- assert.equal(options.focus, false);- assert.equal(options.scrollAttr.startId, "first");- protyle.contentElement.scrollTop = options.scrollAttr.scrollTop;- options.cb();- },- };- runInNewContext(compiled, context);- context.save(protyle);- visible = false;- protyle.contentElement.scrollTop = 0;- context.save(protyle);- assert.equal(await context.restore({}, stack), true);- assert.equal(protyle.contentElement.scrollTop, 1133);- assert.equal(switched, 1);- assert.equal(reloaded, changedRange ? 1 : 0);- });+ for (const changedZoom of [false, true]) {+ test(`tablet history restores reading position with changed range ${changedRange} and zoom ${changedZoom}`, async () => {+ let visible = true;+ let switched = 0;+ let reloaded = 0;+ const protyle = {+ element: {getBoundingClientRect: () => ({height: visible ? 700 : 0})},+ contentElement: {scrollTop: 1133},+ block: {rootID: "doc", showAll: false, id: "doc"},+ wysiwyg: {element: {+ firstElementChild: {getAttribute: () => changedRange ? "changed" : "first"},+ lastElementChild: {getAttribute: () => "last"},+ }},+ model: {parent: {headElement: {}, parent: {switchTab: () => { switched++; visible = true; }}}},+ };+ const stack = {id: "old-caret", protyle};+ const context: any = {+ previousIsBack: false,+ forwardStack: [],+ window: {siyuan: {backStack: [stack]}},+ isPhablet: () => true,+ saveScroll: () => ({rootId: "doc", startId: "first", endId: "last", scrollTop: protyle.contentElement.scrollTop}),+ document: {contains: () => true},+ hideElements: () => {},+ getDocByScroll: (options: any) => {+ reloaded++;+ assert.equal(options.focus, false);+ assert.equal(options.scrollAttr.startId, "first");+ protyle.contentElement.scrollTop = options.scrollAttr.scrollTop;+ options.cb();+ },+ };+ runInNewContext(compiled, context);+ context.save(protyle);+ visible = false;+ protyle.block.showAll = changedZoom;+ protyle.block.id = changedZoom ? "zoomed" : "doc";+ protyle.contentElement.scrollTop = 0;+ context.save(protyle);+ assert.equal(await context.restore({}, stack), true);+ assert.equal(protyle.contentElement.scrollTop, 1133);+ assert.equal(switched, 1);+ assert.equal(reloaded, changedRange || changedZoom ? 1 : 0);+ });+ }}++test("saving a visible document at the top does not restore a stale cached scroll offset", async () => {+ const protyle = {+ element: {getBoundingClientRect: () => ({height: 700})},+ contentElement: {scrollTop: 0},+ block: {rootID: "doc"},+ wysiwyg: {element: {+ firstElementChild: {getAttribute: () => "first"},+ lastElementChild: {getAttribute: () => "last"},+ }},+ model: {parent: {headElement: {}, parent: {switchTab: () => {}}}},+ };+ const stack = {id: "doc", protyle};+ const context: any = {+ previousIsBack: false, forwardStack: [], window: {siyuan: {backStack: [stack]}},+ isPhablet: () => true, document: {contains: () => true}, hideElements: () => {},+ saveScroll: () => ({rootId: "doc", startId: "first", endId: "last", scrollTop: 1133}),+ };+ runInNewContext(compiled, context);+ context.save(protyle);+ protyle.contentElement.scrollTop = 500;+ await context.restore({}, stack);+ assert.equal(protyle.contentElement.scrollTop, 0);+});