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 document tree state when changing sort rules https://github.com/siyuan-note/siyuan/issues/18787
Danielfd9a72a5d74c
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 88dec574e8..47f559992e 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -53,8 +53,10 @@ import {import {FILE_TREE_CHILDREN_SORT_MODE,FILE_TREE_EFFECTIVE_SORT_MODE,+ getFileTreeSortRefreshTargets,getResponseEffectiveSortMode,isCustomFileTreeList,+ reorderFileTreeNotebooks,type IDocSortModeChanged,updateFileTreeSortMode} from "../../util/fileTreeSort";@@ -67,6 +69,8 @@ export class Files extends Model {private actionsElement: HTMLElement;private reloadNotebookInfoTimeout: number;private docSortModeRefreshTimeout: number;+ private docSortModeChanges = new Map<string, IDocSortModeChanged>();+ private docSortModeFullRefresh = false;private movedExpandedDocIDs = new Set<string>();constructor(options: { tab: Tab, app: App }) {@@ -1523,10 +1527,56 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"}public onDocSortModeChanged(data?: IDocSortModeChanged) {- updateFileTreeSortMode(data);+ updateFileTreeSortMode(data, this.element);+ if (data) {+ this.docSortModeChanges.set(`${data.scope}:${data.box}:${data.id}:${data.path}`, data);+ } else {+ this.docSortModeFullRefresh = true;+ }window.clearTimeout(this.docSortModeRefreshTimeout);this.docSortModeRefreshTimeout = window.setTimeout(() => {- this.init(false);+ const fullRefresh = this.docSortModeFullRefresh;+ const changes = Array.from(this.docSortModeChanges.values());+ this.docSortModeFullRefresh = false;+ this.docSortModeChanges.clear();+ if (fullRefresh) {+ if (changes.some((item) => item.scope === "global")) {+ setNoteBook(() => this.init(false));+ } else {+ this.init(false);+ }+ return;+ }+ const refreshLists = () => {+ getFileTreeSortRefreshTargets(this.element, changes).forEach((target) => {+ const notebookElement = Array.from(this.element.children).find((item) =>+ item.getAttribute("data-url") === target.notebookId+ );+ const liElement = Array.from(notebookElement?.querySelectorAll("li[data-path]") || []).find((item) =>+ item.getAttribute("data-path") === target.path+ );+ if (liElement) {+ this.getLeaf(liElement, target.notebookId, true);+ }+ });+ };+ if (changes.some((item) => item.scope === "global")) {+ setNoteBook((notebooks) => {+ reorderFileTreeNotebooks(this.element, this.closeElement.lastElementChild, notebooks);+ this.element.querySelectorAll<HTMLElement>(+ ":scope > ul[data-url] > li[data-type=\"navigation-root\"]"+ ).forEach((item) => {+ if (window.siyuan.config.fileTree.sort === 6) {+ item.setAttribute("draggable", "true");+ } else {+ item.removeAttribute("draggable");+ }+ });+ refreshLists();+ });+ } else {+ refreshLists();+ }}, 100);}@@ -1671,6 +1721,16 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"// 文件展开时,刷新const tempElement = document.createElement("template");tempElement.innerHTML = fileHTML;+ const focusedIDs = Array.from(nextElement.querySelectorAll(":scope > .b3-list-item--focus")).map((item) =>+ item.getAttribute("data-node-id")+ );+ const lastSelectedID = nextElement.contains(this.lastSelectedElement) ?+ this.lastSelectedElement.getAttribute("data-node-id") : "";+ focusedIDs.forEach((id) => {+ Array.from(tempElement.content.children).find((item) =>+ item.getAttribute("data-node-id") === id+ )?.classList.add("b3-list-item--focus");+ });// 保持文件夹展开状态nextElement.querySelectorAll(":scope > .b3-list-item > .b3-list-item__toggle> .b3-list-item__arrow--open").forEach(item => {const openLiElement = hasClosestByClassName(item, "b3-list-item");@@ -1683,6 +1743,11 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"}});nextElement.innerHTML = tempElement.innerHTML;+ if (lastSelectedID) {+ this.lastSelectedElement = Array.from(nextElement.querySelectorAll("[data-node-id]")).find((item) =>+ item.getAttribute("data-node-id") === lastSelectedID+ ) || null;+ }nextElement.setAttribute(FILE_TREE_EFFECTIVE_SORT_MODE, effectiveSortMode.toString());this.restoreMovedExpandedItems(nextElement, data.box);if (typeof scrollTop === "number") {@@ -1986,9 +2051,16 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}...window.siyuan.config.fileTree,sort,}, (response) => {+ if (response.code !== 0) {+ return;+ }window.siyuan.config.fileTree = response.data;- setNoteBook(() => {- this.init(false);+ this.onDocSortModeChanged({+ scope: "global",+ box: "",+ id: "",+ path: "/",+ sortMode: sort,});});});diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex 7eb933e6b8..1f77520b1b 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -76,7 +76,6 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>/// #elsefiles = (getDockByType("file").data["file"] as Files);/// #endif- let sortModeChanged = false;for (const item of selectedItems) {const notebookId = item.parentElement?.getAttribute("data-url");if (!notebookId) {@@ -94,10 +93,13 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>if (notebook) {notebook.sortMode = sort;}- sortModeChanged = true;- }- if (sortModeChanged) {- files?.onDocSortModeChanged();+ files?.onDocSortModeChanged({+ scope: "notebook",+ box: notebookId,+ id: "",+ path: "/",+ sortMode: sort,+ });}});window.siyuan.menus.menu.append(new MenuItem({@@ -487,7 +489,13 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {if (notebook) {notebook.sortMode = sort;}- files?.onDocSortModeChanged();+ files?.onDocSortModeChanged({+ scope: "notebook",+ box: notebookId,+ id: "",+ path: "/",+ sortMode: sort,+ });});return true;});@@ -822,7 +830,13 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l/// #elsefiles = (getDockByType("file").data["file"] as Files);/// #endif- files?.onDocSortModeChanged();+ files?.onDocSortModeChanged({+ scope: "document",+ box: notebookId,+ id,+ path: pathString,+ sortMode,+ });});});window.siyuan.menus.menu.append(new MenuItem({diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex 7afc668119..3c69e80c9f 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -40,8 +40,10 @@ import {import {FILE_TREE_CHILDREN_SORT_MODE,FILE_TREE_EFFECTIVE_SORT_MODE,+ getFileTreeSortRefreshTargets,getResponseEffectiveSortMode,isCustomFileTreeList,+ reorderFileTreeNotebooks,type IDocSortModeChanged,updateFileTreeSortMode} from "../../util/fileTreeSort";@@ -52,6 +54,8 @@ export class MobileFiles extends Model {private closeElement: HTMLElement;private reloadNotebookInfoTimeout: number;private docSortModeRefreshTimeout: number;+ private docSortModeChanges = new Map<string, IDocSortModeChanged>();+ private docSortModeFullRefresh = false;private movedExpandedDocIDs = new Set<string>();private touchDragState: {selectedElement: HTMLElement;@@ -712,9 +716,16 @@ export class MobileFiles extends Model {...window.siyuan.config.fileTree,sort,}, (response) => {+ if (response.code !== 0) {+ return;+ }window.siyuan.config.fileTree = response.data;- setNoteBook(() => {- this.init(false);+ this.onDocSortModeChanged({+ scope: "global",+ box: "",+ id: "",+ path: "/",+ sortMode: sort,});});});@@ -1113,10 +1124,47 @@ export class MobileFiles extends Model {}public onDocSortModeChanged(data?: IDocSortModeChanged) {- updateFileTreeSortMode(data);+ updateFileTreeSortMode(data, this.element);+ if (data) {+ this.docSortModeChanges.set(`${data.scope}:${data.box}:${data.id}:${data.path}`, data);+ } else {+ this.docSortModeFullRefresh = true;+ }window.clearTimeout(this.docSortModeRefreshTimeout);this.docSortModeRefreshTimeout = window.setTimeout(() => {- this.init(false);+ const fullRefresh = this.docSortModeFullRefresh;+ const changes = Array.from(this.docSortModeChanges.values());+ this.docSortModeFullRefresh = false;+ this.docSortModeChanges.clear();+ if (fullRefresh) {+ if (changes.some((item) => item.scope === "global")) {+ setNoteBook(() => this.init(false));+ } else {+ this.init(false);+ }+ return;+ }+ const refreshLists = () => {+ getFileTreeSortRefreshTargets(this.element, changes).forEach((target) => {+ const notebookElement = Array.from(this.element.children).find((item) =>+ item.getAttribute("data-url") === target.notebookId+ );+ const liElement = Array.from(notebookElement?.querySelectorAll("li[data-path]") || []).find((item) =>+ item.getAttribute("data-path") === target.path+ );+ if (liElement) {+ this.getLeaf(liElement, target.notebookId, true);+ }+ });+ };+ if (changes.some((item) => item.scope === "global")) {+ setNoteBook((notebooks) => {+ reorderFileTreeNotebooks(this.element, this.closeElement.lastElementChild, notebooks);+ refreshLists();+ });+ } else {+ refreshLists();+ }}, 100);}@@ -1190,6 +1238,14 @@ export class MobileFiles extends Model {// 文件展开时,刷新const tempElement = document.createElement("template");tempElement.innerHTML = fileHTML;+ const focusedIDs = Array.from(nextElement.querySelectorAll(":scope > .b3-list-item--focus")).map((item) =>+ item.getAttribute("data-node-id")+ );+ focusedIDs.forEach((id) => {+ Array.from(tempElement.content.children).find((item) =>+ item.getAttribute("data-node-id") === id+ )?.classList.add("b3-list-item--focus");+ });// 保持文件夹展开状态nextElement.querySelectorAll(":scope > .b3-list-item > .b3-list-item__toggle> .b3-list-item__arrow--open").forEach(item => {const openLiElement = hasClosestByClassName(item, "b3-list-item");diff --git a/app/src/util/fileTreeSort.test.ts b/app/src/util/fileTreeSort.test.tsindex 52a362abc6..d9d5e496fe 100644--- a/app/src/util/fileTreeSort.test.ts+++ b/app/src/util/fileTreeSort.test.ts@@ -4,8 +4,10 @@ import {FILE_TREE_CHILDREN_SORT_MODE,FILE_TREE_EFFECTIVE_SORT_MODE,getConfiguredChildrenSortMode,+ getFileTreeSortRefreshTargets,getFileTreeListSortMode,isCustomFileTreeList,+ reorderFileTreeNotebooks,updateFileTreeSortMode} from "./fileTreeSort";@@ -38,6 +40,94 @@ const elementWithAttrs = (attrs: Record<string, string>, notebookSortMode = "15"}),}) as unknown as Element;+interface ITreeElement {+ tagName: string;+ attrs: Record<string, string>;+ children: ITreeElement[];+ parent?: ITreeElement;+ getAttribute: (name: string) => string | null;+ setAttribute: (name: string, value: string) => void;+ append: (child: ITreeElement) => void;+}++const treeElement = (tagName: string, attrs: Record<string, string> = {}, children: Element[] = []) => {+ const element: ITreeElement = {+ tagName,+ attrs,+ children: children as unknown as ITreeElement[],+ getAttribute(name: string) {+ return this.attrs[name] ?? null;+ },+ setAttribute(name: string, value: string) {+ this.attrs[name] = value;+ },+ append(child: ITreeElement) {+ if (child.parent) {+ const index = child.parent.children.indexOf(child);+ child.parent.children.splice(index, 1);+ }+ child.parent = this;+ this.children.push(child);+ },+ };+ Object.defineProperties(element, {+ firstElementChild: {+ get: () => element.children[0] || null,+ },+ nextElementSibling: {+ get: () => {+ if (!element.parent) {+ return null;+ }+ const index = element.parent.children.indexOf(element);+ return element.parent.children[index + 1] || null;+ },+ },+ });+ children.forEach((child) => {+ (child as unknown as ITreeElement).parent = element;+ });+ return element as unknown as Element;+};++const fileTreeFixture = () => {+ const inheritedList = treeElement("UL");+ const inherited = treeElement("LI", {+ "data-type": "navigation-file",+ "data-node-id": "inherited",+ "data-path": "/parent/inherited.sy",+ [FILE_TREE_CHILDREN_SORT_MODE]: "",+ });+ const overriddenList = treeElement("UL");+ const overridden = treeElement("LI", {+ "data-type": "navigation-file",+ "data-node-id": "overridden",+ "data-path": "/parent/overridden.sy",+ [FILE_TREE_CHILDREN_SORT_MODE]: "3",+ });+ const parentList = treeElement("UL", {}, [inherited, inheritedList, overridden, overriddenList]);+ const parent = treeElement("LI", {+ "data-type": "navigation-file",+ "data-node-id": "parent",+ "data-path": "/parent.sy",+ [FILE_TREE_CHILDREN_SORT_MODE]: "",+ });+ const rootList = treeElement("UL", {}, [parent, parentList]);+ const root = treeElement("LI", {"data-type": "navigation-root", "data-path": "/"});+ const notebook = treeElement("UL", {"data-url": "notebook", "data-sortmode": "15"}, [root, rootList]);+ const explicitRootList = treeElement("UL");+ const explicitRoot = treeElement("LI", {"data-type": "navigation-root", "data-path": "/"});+ const explicitNotebook = treeElement("UL", {"data-url": "explicit", "data-sortmode": "6"}, [+ explicitRoot,+ explicitRootList,+ ]);+ return {+ element: treeElement("DIV", {}, [notebook, explicitNotebook]),+ notebook,+ parent,+ };+};+test("effective list sort mode takes precedence over notebook sorting", () => withWindow(() => {const listElement = elementWithAttrs({[FILE_TREE_EFFECTIVE_SORT_MODE]: "3"});assert.equal(getFileTreeListSortMode(listElement), 3);@@ -65,3 +155,69 @@ test("sort mode events update global and notebook fallback state", () => withWinupdateFileTreeSortMode({scope: "notebook", box: "notebook", id: "", path: "/", sortMode: 6});assert.equal(window.siyuan.notebooks[0].sortMode, 6);}));++test("document sorting refreshes expanded inherited lists up to an override", () => {+ const fixture = fileTreeFixture();+ assert.deepEqual(getFileTreeSortRefreshTargets(fixture.element, [{+ scope: "document",+ box: "notebook",+ id: "parent",+ path: "/parent.sy",+ sortMode: 2,+ }]), [+ {notebookId: "notebook", path: "/parent.sy"},+ {notebookId: "notebook", path: "/parent/inherited.sy"},+ ]);+});++test("global sorting refreshes only notebooks that inherit the panel rule", () => {+ const fixture = fileTreeFixture();+ assert.deepEqual(getFileTreeSortRefreshTargets(fixture.element, [{+ scope: "global",+ box: "",+ id: "",+ path: "/",+ sortMode: 2,+ }]), [+ {notebookId: "notebook", path: "/"},+ {notebookId: "notebook", path: "/parent.sy"},+ {notebookId: "notebook", path: "/parent/inherited.sy"},+ ]);+});++test("sort mode events update rendered notebook and document declarations", () => withWindow(() => {+ const fixture = fileTreeFixture();+ updateFileTreeSortMode({+ scope: "notebook",+ box: "notebook",+ id: "",+ path: "/",+ sortMode: 6,+ }, fixture.element);+ assert.equal(fixture.notebook.getAttribute("data-sortmode"), "6");+ updateFileTreeSortMode({+ scope: "document",+ box: "notebook",+ id: "parent",+ path: "/parent.sy",+ sortMode: null,+ }, fixture.element);+ assert.equal(fixture.parent.getAttribute(FILE_TREE_CHILDREN_SORT_MODE), "");+}));++test("notebook reordering moves existing opened and closed elements", () => {+ const openedA = treeElement("UL", {"data-url": "a"});+ const openedB = treeElement("UL", {"data-url": "b"});+ const closedA = treeElement("LI", {"data-url": "c"});+ const closedB = treeElement("LI", {"data-url": "d"});+ const opened = treeElement("DIV", {}, [openedA, openedB]);+ const closed = treeElement("UL", {}, [closedA, closedB]);+ reorderFileTreeNotebooks(opened, closed, [+ {id: "b", closed: false},+ {id: "a", closed: false},+ {id: "d", closed: true},+ {id: "c", closed: true},+ ]);+ assert.deepEqual(Array.from(opened.children).map((item) => item.getAttribute("data-url")), ["b", "a"]);+ assert.deepEqual(Array.from(closed.children).map((item) => item.getAttribute("data-url")), ["d", "c"]);+});diff --git a/app/src/util/fileTreeSort.ts b/app/src/util/fileTreeSort.tsindex afc7825d87..216952301b 100644--- a/app/src/util/fileTreeSort.ts+++ b/app/src/util/fileTreeSort.ts@@ -9,6 +9,11 @@ export interface IDocSortModeChanged {sortMode: number | null;}+export interface IFileTreeSortRefreshTarget {+ notebookId: string;+ path: string;+}+const parseSortMode = (value: string | null) => {if (value === null || value.trim() === "") {return;@@ -35,18 +40,117 @@ export const getFileTreeListSortMode = (element: Element) => {export const isCustomFileTreeList = (element: Element) => getFileTreeListSortMode(element) === 6;-export const updateFileTreeSortMode = (data?: IDocSortModeChanged) => {+const findElement = (element: Element, match: (item: Element) => boolean): Element | undefined => {+ for (const child of Array.from(element?.children || [])) {+ if (match(child)) {+ return child;+ }+ const result = findElement(child, match);+ if (result) {+ return result;+ }+ }+};++const getNotebookElements = (element: Element) => Array.from(element?.children || []).filter((item) =>+ item.tagName === "UL" && Boolean(item.getAttribute("data-url"))+);++const getChildListElement = (element: Element) => {+ const listElement = element?.nextElementSibling;+ return listElement?.tagName === "UL" ? listElement : undefined;+};++const addInheritedRefreshTargets = (parentElement: Element, notebookId: string,+ targets: Map<string, IFileTreeSortRefreshTarget>) => {+ const listElement = getChildListElement(parentElement);+ const path = parentElement?.getAttribute("data-path");+ if (!listElement || !path) {+ return;+ }+ targets.set(`${notebookId}:${path}`, {notebookId, path});+ Array.from(listElement.children).forEach((item) => {+ if (item.tagName !== "LI" || item.getAttribute("data-type") !== "navigation-file" ||+ getConfiguredChildrenSortMode(item) !== null) {+ return;+ }+ addInheritedRefreshTargets(item, notebookId, targets);+ });+};++export const getFileTreeSortRefreshTargets = (element: Element, changes: IDocSortModeChanged[]) => {+ const targets = new Map<string, IFileTreeSortRefreshTarget>();+ changes.forEach((change) => {+ if (change.scope === "global") {+ getNotebookElements(element).forEach((notebookElement) => {+ if (parseSortMode(notebookElement.getAttribute("data-sortmode")) !== 15) {+ return;+ }+ addInheritedRefreshTargets(notebookElement.firstElementChild, notebookElement.getAttribute("data-url"),+ targets);+ });+ return;+ }+ const notebookElement = getNotebookElements(element).find((item) =>+ item.getAttribute("data-url") === change.box+ );+ if (!notebookElement) {+ return;+ }+ if (change.scope === "notebook") {+ addInheritedRefreshTargets(notebookElement.firstElementChild, change.box, targets);+ return;+ }+ const documentElement = findElement(notebookElement, (item) =>+ item.tagName === "LI" && item.getAttribute("data-node-id") === change.id+ );+ if (documentElement) {+ addInheritedRefreshTargets(documentElement, change.box, targets);+ }+ });+ return Array.from(targets.values());+};++export const reorderFileTreeNotebooks = (element: Element, closedListElement: Element,+ notebooks: Array<Pick<INotebook, "id" | "closed">>) => {+ const openedElements = new Map(getNotebookElements(element).map((item) => [item.getAttribute("data-url"), item]));+ const closedElements = new Map(Array.from(closedListElement?.children || []).map((item) =>+ [item.getAttribute("data-url"), item]+ ));+ notebooks.forEach((notebook) => {+ const notebookElement = notebook.closed ? closedElements.get(notebook.id) : openedElements.get(notebook.id);+ if (notebookElement) {+ (notebook.closed ? closedListElement : element).append(notebookElement);+ }+ });+};++export const updateFileTreeSortMode = (data?: IDocSortModeChanged, element?: Element) => {const sortMode = data?.sortMode;- if (typeof sortMode !== "number" || !Number.isInteger(sortMode)) {+ if (!data || (sortMode !== null && (typeof sortMode !== "number" || !Number.isInteger(sortMode)))) {return;}if (data.scope === "global") {+ if (sortMode === null) {+ return;+ }window.siyuan.config.fileTree.sort = sortMode;} else if (data.scope === "notebook") {+ if (sortMode === null) {+ return;+ }const notebook = window.siyuan.notebooks.find((item) => item.id === data.box);if (notebook) {notebook.sortMode = sortMode;}+ getNotebookElements(element).find((item) => item.getAttribute("data-url") === data.box)?.setAttribute(+ "data-sortmode", sortMode.toString()+ );+ } else {+ const notebookElement = getNotebookElements(element).find((item) => item.getAttribute("data-url") === data.box);+ findElement(notebookElement, (item) =>+ item.tagName === "LI" && item.getAttribute("data-node-id") === data.id+ )?.setAttribute(FILE_TREE_CHILDREN_SORT_MODE, sortMode?.toString() || "");}};