Skip to content

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

:zap: Improve concurrent loading when restoring the document tree expanded state https://github.com/siyuan-note/siyuan/issues/19390

Daniel4262ad724d99
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 07a28e180f..40c48fac06 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -16,6 +16,7 @@ import {
openPublishAccessDialog
} from "../../protyle/util/publishAccess";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
+import {restoreFileTreePaths} from "../../util/fileTreeRestore";
import {openEmojiPanel} from "../../emoji";
import {
getFileTreeDefaultIconAttr,
@@ -1484,11 +1485,30 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
} else {
this.closeElement.classList.add("fn__none");
}
- window.siyuan.storage[Constants.LOCAL_FILESPATHS].forEach(async (item: IFilesPath) => {
- for (const openPath of item.openPaths) {
- await this.selectItem(item.notebookId, openPath, undefined, false, false);
+ const firstNotebook = this.element.firstElementChild;
+ void restoreFileTreePaths(window.siyuan.storage[Constants.LOCAL_FILESPATHS], async (notebookId, path) => {
+ if (this.element.firstElementChild !== firstNotebook) {
+ return;
+ }
+ const liElement = this.element.querySelector(`ul[data-url="${notebookId}"] li[data-path="${path}"]`);
+ if (!liElement || liElement.querySelector(".b3-list-item__arrow--open")) {
+ return;
+ }
+ const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: notebookId,
+ path,
+ app: Constants.SIYUAN_APPID,
+ });
+ if (response.code !== 0 || !response.data || !this.element.contains(liElement) ||
+ liElement.querySelector(".b3-list-item__arrow--open")) {
+ return;
+ }
+ await this.onLsSelect(response.data, path, false, false);
+ }).then(() => {
+ if (this.element.firstElementChild === firstNotebook) {
+ this.refreshPublishAccessSwitch();
+ this.element.scrollTop = scrollTop;
}
- this.element.scrollTop = scrollTop;
});
this.refreshPublishAccessSwitch();
if (!init) {
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index a6e8703a31..c13c2a4bd8 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -11,6 +11,7 @@ import {
openPublishAccessDialog
} from "../../protyle/util/publishAccess";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
+import {restoreFileTreePaths} from "../../util/fileTreeRestore";
import {reorderSortedFileTree} from "../../util/fileTreeReorder";
import {genUUID} from "../../util/genID";
import {openMobileFileById} from "../editor";
@@ -927,11 +928,30 @@ export class MobileFiles extends Model {
} else {
this.closeElement.classList.add("fn__none");
}
- window.siyuan.storage[Constants.LOCAL_FILESPATHS].forEach(async (item: IFilesPath) => {
- for (const openPath of item.openPaths) {
- await this.selectItem(item.notebookId, openPath, undefined, false, false);
+ const firstNotebook = this.element.firstElementChild;
+ void restoreFileTreePaths(window.siyuan.storage[Constants.LOCAL_FILESPATHS], async (notebookId, path) => {
+ if (this.element.firstElementChild !== firstNotebook) {
+ return;
+ }
+ const liElement = this.element.querySelector(`ul[data-url="${notebookId}"] li[data-path="${path}"]`);
+ if (!liElement || liElement.querySelector(".b3-list-item__arrow--open")) {
+ return;
+ }
+ const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: notebookId,
+ path,
+ app: Constants.SIYUAN_APPID,
+ });
+ if (response.code !== 0 || !response.data || !this.element.contains(liElement) ||
+ liElement.querySelector(".b3-list-item__arrow--open")) {
+ return;
+ }
+ await this.onLsSelect(response.data, path, false, false);
+ }).then(() => {
+ if (this.element.firstElementChild === firstNotebook) {
+ this.refreshPublishAccessSwitch();
+ this.element.scrollTop = scrollTop;
}
- this.element.scrollTop = scrollTop;
});
this.refreshPublishAccessSwitch();
if (!init) {
diff --git a/app/src/util/fileTreeRestore.test.ts b/app/src/util/fileTreeRestore.test.ts
new file mode 100644
index 0000000000..e8fe59ba89
--- /dev/null
+++ b/app/src/util/fileTreeRestore.test.ts
@@ -0,0 +1,68 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {restoreFileTreePaths} from "./fileTreeRestore";
+
+test("loads independent branches concurrently after their shared ancestors finish", async () => {
+ const calls: string[] = [];
+ const pending = new Map<string, () => void>();
+ const restore = restoreFileTreePaths([
+ {notebookId: "one", openPaths: ["/a/b/leaf.sy", "/a/c/leaf.sy", "/a/b/other.sy"]},
+ {notebookId: "two", openPaths: ["/x/leaf.sy"]},
+ {notebookId: "one", openPaths: ["//a/b/leaf.sy"]},
+ ], async (notebookId, path) => {
+ const key = `${notebookId}:${path}`;
+ calls.push(key);
+ await new Promise<void>(resolve => pending.set(key, resolve));
+ });
+ const flush = () => new Promise(resolve => setImmediate(resolve));
+ assert.deepEqual(calls, ["one:/", "two:/"]);
+ pending.get("one:/")();
+ await flush();
+ assert.equal(calls.length, 2);
+ pending.get("two:/")();
+ await flush();
+ assert.deepEqual(calls.slice(2), ["one:/a.sy", "two:/x.sy"]);
+ pending.get("one:/a.sy")();
+ pending.get("two:/x.sy")();
+ await flush();
+ assert.deepEqual(calls.slice(4), ["one:/a/b.sy", "one:/a/c.sy"]);
+ pending.get("one:/a/c.sy")();
+ pending.get("one:/a/b.sy")();
+ await restore;
+ assert.equal(calls.length, 6);
+});
+
+test("restores only ancestors and leaves root-only and empty saved paths collapsed", async () => {
+ const calls: string[] = [];
+ await restoreFileTreePaths([
+ {notebookId: "one", openPaths: ["/", ""]},
+ {notebookId: "two", openPaths: []},
+ {notebookId: "three", openPaths: ["/leaf.sy"]},
+ ], async (notebookId, path) => {
+ calls.push(`${notebookId}:${path}`);
+ });
+ assert.deepEqual(calls, ["three:/"]);
+});
+
+test("a rejected branch does not interrupt restoration of other branches", async () => {
+ const calls: string[] = [];
+ const errors: unknown[] = [];
+ const originalError = console.error;
+ const failure = new Error("request failed");
+ console.error = error => errors.push(error);
+ try {
+ await restoreFileTreePaths([
+ {notebookId: "one", openPaths: ["/leaf.sy"]},
+ {notebookId: "two", openPaths: ["/a/leaf.sy"]},
+ ], async (notebookId, path) => {
+ if (notebookId === "one") {
+ throw failure;
+ }
+ calls.push(path);
+ });
+ assert.deepEqual(calls, ["/", "/a.sy"]);
+ assert.deepEqual(errors, [failure]);
+ } finally {
+ console.error = originalError;
+ }
+});
diff --git a/app/src/util/fileTreeRestore.ts b/app/src/util/fileTreeRestore.ts
new file mode 100644
index 0000000000..b7292f586a
--- /dev/null
+++ b/app/src/util/fileTreeRestore.ts
@@ -0,0 +1,27 @@
+export const restoreFileTreePaths = async (
+ filesPaths: {notebookId: string, openPaths: string[]}[],
+ load: (notebookId: string, path: string) => Promise<void>,
+) => {
+ const levels: Map<string, {notebookId: string, path: string}>[] = [];
+ filesPaths.forEach(({notebookId, openPaths}) => {
+ openPaths.forEach(openPath => {
+ const parts = openPath.split("/").filter(Boolean);
+ // 保存的路径指向展开节点的子文档,只加载其祖先,保留目标文档的折叠状态。
+ for (let depth = 0; depth < parts.length; depth++) {
+ const path = depth === 0 ? "/" : `/${parts.slice(0, depth).join("/")}.sy`;
+ levels[depth] = levels[depth] || new Map();
+ levels[depth].set(JSON.stringify([notebookId, path]), {notebookId, path});
+ }
+ });
+ });
+ for (const level of levels) {
+ // 每层完成 DOM 插入后再加载下一层,避免祖先刷新覆盖已展开的子树。
+ await Promise.all(Array.from(level.values(), async ({notebookId, path}) => {
+ try {
+ await load(notebookId, path);
+ } catch (error) {
+ console.error(error);
+ }
+ }));
+ }
+};