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 reading positions across tab and history navigation https://github.com/siyuan-note/siyuan/issues/19624
Vanessaa9a86eeb13a2
diff --git a/app/src/editor/navigationHistory.test.ts b/app/src/editor/navigationHistory.test.tsindex 1aa677e3fe..ebf206e3c6 100644--- a/app/src/editor/navigationHistory.test.ts+++ b/app/src/editor/navigationHistory.test.ts@@ -80,6 +80,8 @@ test("tablet tab switches navigate A B C backward and forward without touching tcontext.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({diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.tsindex 8c3ec51159..44f21cf35c 100644--- a/app/src/layout/Wnd.ts+++ b/app/src/layout/Wnd.ts@@ -33,6 +33,8 @@ import {fetchPost, fetchSyncPost} from "../util/fetch";import {getAllModels} from "./getAll";import {clearCounter} from "./status";import {saveScroll} from "../protyle/scroll/saveScroll";+import {restoreTabPosition, saveTabPosition} from "../protyle/scroll/tabPosition";+import {saveBackScroll} from "../util/backForward";import {Asset} from "../asset";import {newFile} from "../util/newFile";import {MenuItem} from "../menus/Menu";@@ -686,11 +688,18 @@ export class Wnd {}}item.panelElement.classList.remove("fn__none");+ if (isPhablet() && item.model instanceof Editor) {+ restoreTabPosition(item.model.editor.protyle);+ }}currentTab = item;} else {item.headElement?.classList.remove("item--focus");if (!item.panelElement.classList.contains("fn__none")) {+ if (isPhablet() && item.model instanceof Editor) {+ saveTabPosition(item.model.editor.protyle);+ saveBackScroll(item.model.editor.protyle);+ }// 必须现判断,否则会触发 observer.observe(this.element, {attributeFilter: ["class"]}); 导致 https://ld246.com/article/1641198819303item.panelElement.classList.add("fn__none");}@@ -786,6 +795,10 @@ export class Wnd {}}if (!keepCursor) {+ if (isPhablet() && item.model instanceof Editor && !item.panelElement.classList.contains("fn__none")) {+ saveTabPosition(item.model.editor.protyle);+ saveBackScroll(item.model.editor.protyle);+ }item.headElement?.classList.remove("item--focus");item.panelElement.classList.add("fn__none");}diff --git a/app/src/protyle/scroll/tabPosition.ts b/app/src/protyle/scroll/tabPosition.tsnew file mode 100644index 0000000000..a23a940ef5--- /dev/null+++ b/app/src/protyle/scroll/tabPosition.ts@@ -0,0 +1,13 @@+const positions = new WeakMap<IProtyle, number>();++export const saveTabPosition = (protyle: IProtyle) => {+ positions.set(protyle, protyle.contentElement.scrollTop);+};++export const restoreTabPosition = (protyle: IProtyle) => {+ const top = positions.get(protyle);+ if (typeof top === "number") {+ protyle.contentElement.scrollTop = top;+ positions.delete(protyle);+ }+};diff --git a/app/src/util/backForward.ts b/app/src/util/backForward.tsindex 29a953fa92..2f6b97e696 100644--- a/app/src/util/backForward.ts+++ b/app/src/util/backForward.ts@@ -12,7 +12,8 @@ import {Editor} from "../editor";import {scrollCenter} from "./highlightById";import {zoomOut} from "../menus/protyle";import {showMessage} from "../dialog/message";-import {saveScroll} from "../protyle/scroll/saveScroll";+import {getDocByScroll, saveScroll} from "../protyle/scroll/saveScroll";+import {isPhablet} from "../protyle/util/compatibility";import {getAllModels} from "../layout/getAll";import type {App} from "../index";import {onGet} from "../protyle/util/onGet";@@ -20,6 +21,23 @@ import {isEncryptedBox} from "./pathName";let forwardStack: IBackStack[] = [];let previousIsBack = false;+const readingPositions = new WeakMap<IBackStack, IScrollAttr>();++export const saveBackScroll = (protyle?: IProtyle) => {+ if (!isPhablet()) {+ return;+ }+ const stack = previousIsBack ? forwardStack[forwardStack.length - 1] :+ window.siyuan.backStack[window.siyuan.backStack.length - 1];+ if (!stack || (protyle && stack.protyle !== protyle) ||+ stack.protyle.element.getBoundingClientRect().height === 0) {+ return;+ }+ const position = saveScroll(stack.protyle, true) as IScrollAttr;+ if (position) {+ readingPositions.set(stack, position);+ }+};const focusStack = async (app: App, stack: IBackStack) => {hideElements(["gutter", "toolbar", "hint", "util", "dialog"], stack.protyle);@@ -124,6 +142,26 @@ 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) {+ // 阅读位置独立于旧光标,显示页签后按离开时的加载范围和滚动值恢复。+ 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) {+ stack.protyle.contentElement.scrollTop = readingPosition.scrollTop;+ return true;+ }+ return new Promise<boolean>(resolve => {+ getDocByScroll({+ protyle: stack.protyle,+ scrollAttr: readingPosition,+ focus: false,+ cb: () => resolve(true),+ fail: () => resolve(false),+ });+ });+ }const focusTitle = () => {if (stack.protyle.title.editElement.getBoundingClientRect().height === 0) {// 切换 tab@@ -245,6 +283,12 @@ const focusStack = async (app: App, stack: IBackStack) => {};export const goBack = async (app: App) => {+ const current = previousIsBack ? forwardStack[forwardStack.length - 1] :+ window.siyuan.backStack[window.siyuan.backStack.length - 1];+ const target = window.siyuan.backStack[window.siyuan.backStack.length - (previousIsBack ? 1 : 2)];+ if (target && current?.protyle !== target.protyle) {+ saveBackScroll();+ }if (window.siyuan.backStack.length === 0) {if (forwardStack.length > 0) {await focusStack(app, forwardStack[forwardStack.length - 1]);@@ -274,6 +318,12 @@ export const goBack = async (app: App) => {};export const goForward = async (app: App) => {+ const current = previousIsBack ? forwardStack[forwardStack.length - 1] :+ window.siyuan.backStack[window.siyuan.backStack.length - 1];+ const target = forwardStack[forwardStack.length - (previousIsBack ? 2 : 1)];+ if (target && current?.protyle !== target.protyle) {+ saveBackScroll();+ }if (forwardStack.length === 0) {if (window.siyuan.backStack.length > 0) {await focusStack(app, window.siyuan.backStack[window.siyuan.backStack.length - 1]);@@ -351,6 +401,7 @@ export const pushBack = (protyle: IProtyle, range?: Range, blockElement?: Elemen(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) {diff --git a/app/src/util/backForwardClick.test.ts b/app/src/util/backForwardClick.test.tsindex db5c6a8e3c..4acb8989c6 100644--- a/app/src/util/backForwardClick.test.ts+++ b/app/src/util/backForwardClick.test.ts@@ -41,6 +41,8 @@ test("tablet paragraph clicks navigate back and forward despite a stale title sewindow: {siyuan: {backStack: stacks}},document: documentSelf,Constants: {SIZE_UNDO: 128},+ readingPositions: new WeakMap(),+ saveBackScroll: () => {},hasClosestBlock: (target: unknown) => target,isInEmbedBlock: () => false,getContenteditableElement: (element: unknown) => element,diff --git a/app/src/util/readingHistory.test.ts b/app/src/util/readingHistory.test.tsnew file mode 100644index 0000000000..63307c7345--- /dev/null+++ b/app/src/util/readingHistory.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";+import {restoreTabPosition, saveTabPosition} from "../protyle/scroll/tabPosition";++const source = createSourceFile("backForward.ts", readFileSync("src/util/backForward.ts", "utf8"), ScriptTarget.ES2021, true);+const names = ["readingPositions", "saveBackScroll", "focusStack"];+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.save = saveBackScroll; globalThis.restore = focusStack;", {+ compilerOptions: {target: ScriptTarget.ES2021},+}).outputText;++test("tab visibility changes preserve a scrolled viewport including zero", () => {+ const protyle = {contentElement: {scrollTop: 1133}} as IProtyle;+ saveTabPosition(protyle);+ protyle.contentElement.scrollTop = 0;+ restoreTabPosition(protyle);+ assert.equal(protyle.contentElement.scrollTop, 1133);+ protyle.contentElement.scrollTop = 0;+ saveTabPosition(protyle);+ protyle.contentElement.scrollTop = 200;+ restoreTabPosition(protyle);+ assert.equal(protyle.contentElement.scrollTop, 0);+});++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);+ });+}