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: Keep editor scroll stable while typing https://github.com/siyuan-note/siyuan/issues/19837
Daniel0a3f9999179c
diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex 9bb21d0a17..497322228e 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -526,6 +526,11 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IModpassive: true,signal: userScrollAbort.signal});+ // 开始编辑后停止定位补偿,避免输入改变布局时把光标滚回原位置+ editor.editor.protyle.element.addEventListener("beforeinput", stopObserve, {+ capture: true,+ signal: userScrollAbort.signal+ });editor.editor.protyle.contentElement.addEventListener("keydown", (event: KeyboardEvent) => {if (["PageUp", "PageDown", "Home", "End", "ArrowUp", "ArrowDown", " "].includes(event.key)) {stopObserve();diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsindex 15d4b43706..dd2765be2a 100644--- a/app/src/layout/dock/BacklinkContent.ts+++ b/app/src/layout/dock/BacklinkContent.ts@@ -939,6 +939,7 @@ export class BacklinkContent extends Model {app: this.app,host: this.tree.element,scroll: this.getScrollElement(this.tree),+ sharedScroll: this.type === "bottom",state: () => this.viewState,foldedTypes: () => normalizeBacklinkFoldTypes(this.viewState?.get("foldedBlockTypes")),open: id => this.openDocument({app: this.app, id, action: [Constants.CB_GET_CONTEXT]}),diff --git a/app/src/layout/dock/GlobalBacklinkList.test.ts b/app/src/layout/dock/GlobalBacklinkList.test.tsnew file mode 100644index 0000000000..b67ab543f8--- /dev/null+++ b/app/src/layout/dock/GlobalBacklinkList.test.ts@@ -0,0 +1,115 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {ScriptTarget, transpileModule} from "typescript";++const browserCases = async (source: string) => {+ const check: typeof assert = require("node:assert/strict");+ const response = (url: string) => url.endsWith("getGlobalBacklinks") ? {+ code: 0,+ data: {snapshot: "snapshot", total: 1, offset: 0, items: [{id: "link", hPath: "Source", anchor: "Text"}]}+ } : {code: 0, data: {items: [] as unknown[]}};+ const GlobalBacklinkList = new Function("fetchSyncPost", "GLOBAL_BACKLINK_PAGE_SIZE",+ "globalBacklinkPageWindow", "hasAVEditorSession", "waitForPendingTransactions",+ source + "\nreturn GlobalBacklinkList;")(+ async (url: string) => response(url), 50, () => ({start: 0, end: 50}),+ () => false, async (): Promise<undefined> => undefined) as typeof import("./GlobalBacklinkList").GlobalBacklinkList;+ window.siyuan = {languages: {loading: "Loading", emptyContent: "Empty", retry: "Retry"}} as unknown as typeof window.siyuan;+ const noop = (): void => undefined;+ const writes: unknown[] = [];+ const state = {get: () => ({id: "link", offset: -100}), set: (_field: string, value: unknown) => {+ writes.push(value);+ }};+ const common = {app: {} as never, state: () => state as never, foldedTypes: (): string[] => [], open: noop,+ editorAdded: noop, editorRemoved: noop, count: noop};++ const owner = document.createElement("div");+ owner.className = "protyle";+ const content = document.createElement("div");+ content.style.cssText = "height: 200px; width: 300px; overflow-y: auto";+ const spacer = document.createElement("div");+ spacer.style.height = "195px";+ const host = document.createElement("div");+ content.append(spacer, host);+ owner.append(content);+ document.body.append(owner);+ const bottomList = new GlobalBacklinkList({...common, host, scroll: content, sharedScroll: true});+ bottomList.search({id: "doc", sort: 1, containChildren: false}, false);+ await new Promise(resolve => setTimeout(resolve, 200));+ check.ok(host.querySelector(".backlinkList__item"));+ check.equal(content.scrollTop, 0, "a saved bottom backlink anchor does not move the document");+ check.equal(writes.length, 0, "shared scrolling does not overwrite a dock anchor");+ const editable = document.createElement("div");+ editable.contentEditable = "true";+ owner.prepend(editable);+ editable.focus({preventScroll: true});+ check.equal(document.activeElement, editable);+ const bottomAnchor = bottomList as unknown as {restoreAnchor: (anchor: {id: string, offset: number}) => void};+ bottomAnchor.restoreAnchor({id: "link", offset: -100});+ check.equal(content.scrollTop, 0, "backlink rendering does not scroll a focused editor");+ editable.remove();++ const dock = document.createElement("div");+ dock.style.cssText = "height: 200px; width: 300px; overflow-y: auto";+ document.body.append(dock);+ const dockList = new GlobalBacklinkList({...common, host: dock, scroll: dock, sharedScroll: false});+ const dockFooter = document.createElement("div");+ dockFooter.style.height = "500px";+ dock.append(dockFooter);+ dockList.search({id: "doc", sort: 1, containChildren: false}, false);+ await new Promise(resolve => setTimeout(resolve, 200));+ check.equal(dock.scrollTop, 100, "the dock keeps its own saved reading anchor");+ bottomList.destroy();+ dockList.destroy();+ check.ok(writes.length > 0, "the dock still persists its reading anchor");+ owner.remove();+ dock.remove();+ return "Global backlink anchor cases passed";+};++test("bottom backlinks leave the editor scroll position alone", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const source = readFileSync(path.join(__dirname, "GlobalBacklinkList.ts"), "utf8");+ const start = source.indexOf("const MIN_SHARED_ANCHOR_VISIBLE_HEIGHT");+ assert.ok(start >= 0);+ const compiled = transpileModule(source.slice(start).replace("export class", "class"), {+ compilerOptions: {target: ScriptTarget.ES2021}+ }).outputText;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-global-backlink-test-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(compiled) + ")")}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Global backlink anchor cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-global-backlink-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/layout/dock/GlobalBacklinkList.ts b/app/src/layout/dock/GlobalBacklinkList.tsindex e38fad58c7..6e00a1bf53 100644--- a/app/src/layout/dock/GlobalBacklinkList.ts+++ b/app/src/layout/dock/GlobalBacklinkList.ts@@ -29,6 +29,9 @@ interface IGlobalBacklinkAnchor {offset: number;}+// 底部反链与正文共用滚动容器,条目只露出边缘时不作为正文滚动锚点+const MIN_SHARED_ANCHOR_VISIBLE_HEIGHT = 32;+// 固定数量的页容器与编辑器留在视口附近,其余位置由高度占位维持。export class GlobalBacklinkList {public readonly element = document.createElement("div");@@ -62,7 +65,9 @@ export class GlobalBacklinkList {this.frame = window.requestAnimationFrame(() => {this.frame = 0;this.lastAnchor = this.captureAnchor() || this.lastAnchor;- this.options.state()?.set(this.anchorField(), this.lastAnchor);+ if (!this.options.sharedScroll && this.lastAnchor) {+ this.options.state()?.set(this.anchorField(), this.lastAnchor);+ }void this.updateViewport();});}@@ -84,6 +89,7 @@ export class GlobalBacklinkList {app: App;host: HTMLElement;scroll: HTMLElement;+ sharedScroll: boolean;state: () => ViewStateService | undefined;foldedTypes: () => string[];open: (id: string) => void;@@ -118,7 +124,8 @@ export class GlobalBacklinkList {this.controller.abort();this.key = key;this.query = query;- this.lastAnchor = this.options.state()?.get<IGlobalBacklinkAnchor>(this.anchorField());+ this.lastAnchor = this.options.sharedScroll ? undefined :+ this.options.state()?.get<IGlobalBacklinkAnchor>(this.anchorField());this.heights.clear();void this.refresh(false);} else if (refresh) {@@ -161,7 +168,9 @@ export class GlobalBacklinkList {for (const page of Array.from(this.pages.entries()).sort((a, b) => a[0] - b[0])) {for (const element of Array.from(page[1].children)) {const rect = element.getBoundingClientRect();- if (rect.bottom > viewport.top && rect.top < viewport.bottom) {+ const visibleHeight = Math.min(rect.bottom, viewport.bottom) - Math.max(rect.top, viewport.top);+ if (visibleHeight >= (this.options.sharedScroll ?+ Math.min(MIN_SHARED_ANCHOR_VISIBLE_HEIGHT, rect.height) : 0) && visibleHeight > 0) {return {id: element.getAttribute("data-global-backlink-id"), offset: rect.top - viewport.top};}}@@ -169,6 +178,16 @@ export class GlobalBacklinkList {}private restoreAnchor(anchor?: IGlobalBacklinkAnchor) {+ if (this.options.sharedScroll) {+ // 正文有光标或焦点时,反链异步渲染不得改变正文滚动位置+ const owner = this.options.scroll.closest(".protyle");+ const active = document.activeElement;+ const selection = window.getSelection()?.focusNode;+ if (owner && ((active && owner.contains(active) && !this.element.contains(active)) ||+ (selection && owner.contains(selection) && !this.element.contains(selection)))) {+ return;+ }+ }const record = anchor && this.records.get(anchor.id);if (record) {this.options.scroll.scrollTop += record.element.getBoundingClientRect().top -@@ -181,7 +200,9 @@ export class GlobalBacklinkList {const generation = ++this.generation;this.controller.abort();this.controller = new AbortController();- const anchor = preserve ? this.captureAnchor() || this.lastAnchor : this.lastAnchor;+ // 共用正文滚动容器时只保持当前可见的锚点,不读取上次停留在反链列表时保存的锚点+ const anchor = this.options.sharedScroll ? this.captureAnchor() :+ (preserve ? this.captureAnchor() || this.lastAnchor : this.lastAnchor);this.pendingAnchor = anchor;this.dirty = false;await Promise.all(Array.from(this.records.values()).map(record =>@@ -218,7 +239,7 @@ export class GlobalBacklinkList {this.addPage(data.offset, data.items);this.updateSpacers();this.restoreAnchor(this.pendingAnchor || anchor);- this.lastAnchor = this.pendingAnchor || anchor || this.lastAnchor;+ this.lastAnchor = this.pendingAnchor || anchor || (this.options.sharedScroll ? undefined : this.lastAnchor);this.pendingAnchor = undefined;this.message.textContent = this.total === 0 ? window.siyuan.languages.emptyContent : "";this.message.classList.toggle("fn__none", this.total > 0);@@ -470,7 +491,9 @@ export class GlobalBacklinkList {public destroy() {this.lastAnchor = this.captureAnchor() || this.lastAnchor;- if (this.lastAnchor) { this.options.state()?.set(this.anchorField(), this.lastAnchor); }+ if (!this.options.sharedScroll && this.lastAnchor) {+ this.options.state()?.set(this.anchorField(), this.lastAnchor);+ }this.destroyed = true;this.controller.abort();this.generation++;diff --git a/app/src/protyle/render/tableCellInput.test.ts b/app/src/protyle/render/tableCellInput.test.tsindex 3254369bdd..369a0ff9b1 100644--- a/app/src/protyle/render/tableCellInput.test.ts+++ b/app/src/protyle/render/tableCellInput.test.ts@@ -78,7 +78,8 @@ const browserCases = async (source: string, queueSource: string, editorSource: sdocument.body.appendChild(element);const table = wysiwyg.firstElementChild as HTMLElement;const queue = Object.assign(new Queue(), {element: wysiwyg, lastHTMLs: {[table.dataset.nodeId]: table.outerHTML}});- const owner = {element, wysiwyg: queue, lute, contentElement: wysiwyg, hint: {render: noop},+ const owner = {element, wysiwyg: queue, lute, contentElement: wysiwyg, options: {typewriterMode: false},+ hint: {render: noop},block: {rootID: "root"}, disabled: false} as unknown as IProtyle;const range = document.createRange();range.selectNodeContents(table.querySelector("th"));diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 51bcdcda75..c85987581d 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -718,32 +718,37 @@ const focusElementById = (protyle: IProtyle, action: string[], scrollAttr?: IScrreturn;}// 加强定位- // 使用 AbortController 监听用户手势(滚轮/触摸/方向键),一旦用户主动滚动即停止强制定位,否则顶部为数据库等异步渲染块撑高内容时会反复重置滚动位置- const userScrollAbort = new AbortController();- const onUserScroll = () => userScrollAbort.abort();- protyle.contentElement.addEventListener("wheel", onUserScroll, {+ // 使用 AbortController 监听用户滚动或编辑,停止后续布局变化引起的重复定位+ const positioningAbort = new AbortController();+ const cancelPositioning = () => positioningAbort.abort();+ protyle.contentElement.addEventListener("wheel", cancelPositioning, {capture: true,passive: true,- signal: userScrollAbort.signal+ signal: positioningAbort.signal});- protyle.contentElement.addEventListener("touchstart", onUserScroll, {+ protyle.contentElement.addEventListener("touchstart", cancelPositioning, {capture: true,passive: true,- signal: userScrollAbort.signal+ signal: positioningAbort.signal});- protyle.contentElement.addEventListener("touchmove", onUserScroll, {+ protyle.contentElement.addEventListener("touchmove", cancelPositioning, {capture: true,passive: true,- signal: userScrollAbort.signal+ signal: positioningAbort.signal+ });+ // 开始编辑后停止自动定位,避免输入引起的布局变化把可见光标重新滚到视口顶部+ protyle.element.addEventListener("beforeinput", cancelPositioning, {+ capture: true,+ signal: positioningAbort.signal});protyle.contentElement.addEventListener("keydown", (event: KeyboardEvent) => {// 仅拦截会触发滚动的按键,避免影响正常编辑输入if (["PageUp", "PageDown", "Home", "End", "ArrowUp", "ArrowDown", " "].includes(event.key)) {- userScrollAbort.abort();+ positioningAbort.abort();}- }, {capture: true, signal: userScrollAbort.signal});+ }, {capture: true, signal: positioningAbort.signal});protyle.observerLoad = new ResizeObserver(() => {- if (userScrollAbort.signal.aborted) {+ if (positioningAbort.signal.aborted) {// 用户已主动滚动,停止强制定位并将滚动权交还给用户protyle.observerLoad.disconnect();protyle.observer.observe(protyle.wysiwyg.element);@@ -762,13 +767,13 @@ const focusElementById = (protyle: IProtyle, action: string[], scrollAttr?: IScrprotyle.observer.unobserve(protyle.wysiwyg.element);setTimeout(() => {protyle.observerLoad.disconnect();- userScrollAbort.abort();+ positioningAbort.abort();protyle.observer.observe(protyle.wysiwyg.element);}, 1000 * 3);if (focusElement === protyle.wysiwyg.element.firstElementChild && !hasScrollTop) {protyle.observerLoad.disconnect();- userScrollAbort.abort();+ positioningAbort.abort();}};diff --git a/app/src/protyle/util/onGetPositioning.test.ts b/app/src/protyle/util/onGetPositioning.test.tsnew file mode 100644index 0000000000..1158e1c269--- /dev/null+++ b/app/src/protyle/util/onGetPositioning.test.ts@@ -0,0 +1,119 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {ScriptTarget, transpileModule} from "typescript";++const browserCases = async (source: string, desktopSource: string) => {+ const check: typeof assert = require("node:assert/strict");+ const Constants = {CB_GET_SCROLL: "scroll", CB_GET_HL: "highlight", CB_GET_FOCUS: "focus",+ CB_GET_FOCUSFIRST: "focusFirst"};+ const focusElementById = new Function("Constants", "resolveVisibleListMindmapBlock", "isPhablet",+ "hasClosestByAttribute", source + "\nreturn focusElementById;")(+ Constants, (): undefined => undefined, () => false, (): null => null) as (+ protyle: IProtyle, action: string[], scrollAttr: IScrollAttr) => void;++ const host = document.createElement("div");+ const content = document.createElement("div");+ const wysiwyg = document.createElement("div");+ content.style.cssText = "height: 200px; width: 300px; overflow-y: auto";+ wysiwyg.innerHTML = '<div data-node-id="block"><div contenteditable="true">Text</div></div>' ++ '<div id="spacer" style="height: 800px"></div>';+ content.append(wysiwyg);+ host.append(content);+ document.body.append(host);+ const spacer = wysiwyg.querySelector<HTMLElement>("#spacer");+ const editable = wysiwyg.querySelector<HTMLElement>('[contenteditable="true"]');+ const noop = (): void => undefined;+ const protyle = {element: host, contentElement: content, wysiwyg: {element: wysiwyg},+ block: {id: "block", rootID: "root"}, observer: {observe: noop, unobserve: noop}} as unknown as IProtyle;++ focusElementById(protyle, [Constants.CB_GET_SCROLL], {scrollTop: 221} as IScrollAttr);+ content.scrollTop = 0;+ spacer.style.height = "801px";+ await new Promise(resolve => setTimeout(resolve, 150));+ check.equal(content.scrollTop, 221, "layout changes keep the requested position before editing");++ focusElementById(protyle, [Constants.CB_GET_SCROLL], {scrollTop: 221} as IScrollAttr);+ content.scrollTop = 0;+ editable.dispatchEvent(new InputEvent("beforeinput", {bubbles: true, inputType: "insertText", data: "x"}));+ spacer.style.height = "802px";+ await new Promise(resolve => setTimeout(resolve, 150));+ check.equal(content.scrollTop, 0, "typing releases the old position before layout changes");++ const editor = {editor: {protyle}};+ const observeDesktopPosition = new Function("editor", "nodeElement", "scrollTop", "options",+ "isHiddenTabContent", "scrollCenter", desktopSource + "\nreturn observerLoad;");+ const target = wysiwyg.querySelector('[data-node-id="block"]');+ const observe = () => observeDesktopPosition(editor, target, 221, {}, () => false, noop) as ResizeObserver;+ const firstObserver = observe();+ content.scrollTop = 0;+ spacer.style.height = "803px";+ await new Promise(resolve => setTimeout(resolve, 150));+ check.equal(content.scrollTop, 221, "desktop focus compensation follows layout changes before editing");+ firstObserver.disconnect();++ observe();+ content.scrollTop = 0;+ editable.dispatchEvent(new InputEvent("beforeinput", {bubbles: true, inputType: "insertText", data: "x"}));+ spacer.style.height = "804px";+ await new Promise(resolve => setTimeout(resolve, 150));+ check.equal(content.scrollTop, 0, "typing cancels desktop focus compensation");+ host.remove();+ return "Positioning cancellation cases passed";+};++test("typing stops delayed document positioning", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const source = readFileSync(path.join(__dirname, "onGet.ts"), "utf8");+ const start = source.indexOf("const focusElementById = ");+ const end = source.indexOf("export const setReadonlyByConfig", start);+ assert.ok(start >= 0 && end > start);+ const compiled = transpileModule(source.slice(start, end), {+ compilerOptions: {target: ScriptTarget.ES2021}+ }).outputText;+ const desktopSource = readFileSync(path.join(__dirname, "../../editor/util.ts"), "utf8");+ const desktopStart = desktopSource.indexOf("const userScrollAbort = new AbortController();");+ const desktopEndMarker = "observerLoad.observe(editor.editor.protyle.wysiwyg.element);";+ const desktopEnd = desktopSource.indexOf(desktopEndMarker, desktopStart) + desktopEndMarker.length;+ assert.ok(desktopStart >= 0 && desktopEnd > desktopStart);+ const desktopCompiled = transpileModule(desktopSource.slice(desktopStart, desktopEnd), {+ compilerOptions: {target: ScriptTarget.ES2021}+ }).outputText;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-onget-positioning-test-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(compiled) + "," + JSON.stringify(desktopCompiled) + ")")}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Positioning cancellation cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-onget-positioning-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});