Skip to content

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

:bug: Preserve expanded document tree state after moving documents https://github.com/siyuan-note/siyuan/issues/12110

Daniel6be819283b22
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 453b6dbace..25ea0fa266 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -39,6 +39,14 @@ import {
expandFileTree,
isFileTreeCollapsing
} from "./fileTreeAnimation";
+import {
+ collectExpandedDocIDs,
+ findMovedFileTreeItem,
+ getFileTreeChildList,
+ IFileTreeMove,
+ restoreMovedExpandedDocItems,
+ updateMovedSubtree
+} from "../../util/fileTreeMove";
export class Files extends Model {
public element: HTMLElement;
@@ -47,6 +55,7 @@ export class Files extends Model {
public lastSelectedElement: Element = null;
private actionsElement: HTMLElement;
private reloadNotebookInfoTimeout: number;
+ private movedExpandedDocIDs = new Set<string>();
constructor(options: { tab: Tab, app: App }) {
super({app: options.app});
@@ -805,7 +814,9 @@ export class Files extends Model {
callback: Constants.CB_MOVE_NOLIST,
});
selectFileElements.forEach(item => {
- item.setAttribute("data-path", pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy"));
+ const fromPath = item.getAttribute("data-path");
+ const newPath = pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy");
+ updateMovedSubtree(item, getFileTreeChildList(item), fromPath, newPath);
});
hasMove = true;
}
@@ -873,9 +884,11 @@ export class Files extends Model {
case "reloadDocInfo":
this.updateDocInfo(data);
break;
- case "moveDoc":
+ case "moveDocs":
this.onMove(data);
break;
+ case "moveDoc":
+ break;
case "reloadFiletree":
setNoteBook(() => {
this.init(false);
@@ -1305,55 +1318,110 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
}
private onMove(response: IWebSocketData) {
- const sourceElement = this.element.querySelector(`ul[data-url="${response.data.fromNotebook}"] li[data-path="${response.data.fromPath}"]`) as HTMLElement;
- if (sourceElement) {
- if (sourceElement.nextElementSibling && sourceElement.nextElementSibling.tagName === "UL") {
- sourceElement.nextElementSibling.remove();
+ const refreshTargets = new Map<string, { element: HTMLElement, notebookId: string }>();
+ (response.data.moves as IFileTreeMove[]).forEach((move) => {
+ const expandedDocIDs = new Set<string>();
+ const movedItem = findMovedFileTreeItem(this.element, move);
+ const sourceElement = movedItem?.element;
+ const sourceAtTarget = movedItem?.isAtTarget;
+ let childListElement: HTMLElement;
+ if (sourceElement) {
+ childListElement = getFileTreeChildList(sourceElement);
+ collectExpandedDocIDs(sourceElement, childListElement, expandedDocIDs);
+ updateMovedSubtree(sourceElement, childListElement, move.fromPath, move.newPath);
}
- if (sourceElement.parentElement.childElementCount === 1) {
- if (sourceElement.parentElement.previousElementSibling) {
- const parentLiElement = sourceElement.parentElement.previousElementSibling as HTMLElement;
- if (parentLiElement.getAttribute("data-type") !== "navigation-root" || parentLiElement.dataset.nodeId) {
- parentLiElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
- }
- parentLiElement.querySelector(".b3-list-item__arrow").classList.remove("b3-list-item__arrow--open");
- parentLiElement.setAttribute("data-count", "0");
- this.updateDocActionElement(parentLiElement);
- const emojiElement = parentLiElement.querySelector(".b3-list-item__icon");
- if (emojiElement.innerHTML === unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder)) {
- emojiElement.innerHTML = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].file);
+ if (sourceElement && !sourceAtTarget) {
+ const sourceListElement = sourceElement.parentElement;
+ childListElement?.remove();
+ if (sourceListElement.childElementCount === 1) {
+ const parentLiElement = sourceListElement.previousElementSibling as HTMLElement;
+ if (parentLiElement) {
+ if (parentLiElement.getAttribute("data-type") !== "navigation-root" ||
+ parentLiElement.dataset.nodeId) {
+ parentLiElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
+ }
+ parentLiElement.querySelector(".b3-list-item__arrow").classList.remove(
+ "b3-list-item__arrow--open"
+ );
+ parentLiElement.setAttribute("data-count", "0");
+ this.updateDocActionElement(parentLiElement);
+ const emojiElement = parentLiElement.querySelector(".b3-list-item__icon");
+ if (emojiElement.innerHTML === unicode2Emoji(
+ window.siyuan.storage[Constants.LOCAL_IMAGES].folder
+ )) {
+ emojiElement.innerHTML = unicode2Emoji(
+ window.siyuan.storage[Constants.LOCAL_IMAGES].file
+ );
+ }
}
+ sourceListElement.remove();
+ } else {
+ sourceElement.remove();
+ }
+ } else if (!sourceElement || sourceAtTarget) {
+ const parentPath = pathPosix().dirname(move.fromPath);
+ const parentElement = this.element.querySelector(
+ `ul[data-url="${move.fromNotebook}"] li[data-path="${parentPath === "/" ? "/" : parentPath + ".sy"}"]`
+ ) as HTMLElement;
+ if (parentElement && parentElement.getAttribute("data-count") === "1") {
+ parentElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
+ parentElement.querySelector(".b3-list-item__arrow").classList.remove(
+ "b3-list-item__arrow--open"
+ );
}
- sourceElement.parentElement.remove();
- } else {
- sourceElement.remove();
}
- } else {
- const parentElement = this.element.querySelector(`ul[data-url="${response.data.fromNotebook}"] li[data-path="${pathPosix().dirname(response.data.fromPath)}.sy"]`) as HTMLElement;
- if (parentElement && parentElement.getAttribute("data-count") === "1") {
- parentElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
- parentElement.querySelector(".b3-list-item__arrow").classList.remove("b3-list-item__arrow--open");
+
+ const targetElement = this.element.querySelector(
+ `[data-url="${move.toNotebook}"] li[data-path="${move.toPath}"]`
+ ) as HTMLElement;
+ if (!targetElement) {
+ expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
+ return;
}
- }
- const newElement = this.element.querySelector(`[data-url="${response.data.toNotebook}"] li[data-path="${response.data.toPath}"]`) as HTMLElement;
- // 更新移动到的新文件夹
- if (newElement) {
- newElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
- if (newElement.getAttribute("data-type") === "navigation-root") {
- newElement.setAttribute("data-count", Math.max(1, Number(newElement.getAttribute("data-count"))).toString());
- this.updateDocActionElement(newElement);
+ targetElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
+ if (targetElement.getAttribute("data-type") === "navigation-root") {
+ targetElement.setAttribute(
+ "data-count",
+ Math.max(1, Number(targetElement.getAttribute("data-count"))).toString()
+ );
+ this.updateDocActionElement(targetElement);
}
- const emojiElement = newElement.querySelector(".b3-list-item__icon");
+ const emojiElement = targetElement.querySelector(".b3-list-item__icon");
if (emojiElement.innerHTML === unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].file)) {
emojiElement.innerHTML = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder);
}
- const arrowElement = newElement.querySelector(".b3-list-item__arrow");
- if (arrowElement.classList.contains("b3-list-item__arrow--open") && response.callback !== Constants.CB_MOVE_NOLIST) {
- this.getLeaf(newElement, response.data.toNotebook, true);
+
+ const targetListElement = getFileTreeChildList(targetElement);
+ const targetExpanded = Boolean(targetElement.querySelector(".b3-list-item__arrow--open"));
+ if (sourceElement && targetListElement && !sourceAtTarget) {
+ targetListElement.append(sourceElement);
+ if (childListElement) {
+ sourceElement.after(childListElement);
+ }
+ }
+ if (!targetExpanded || !sourceElement || (!sourceAtTarget && !targetListElement)) {
+ expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
+ }
+ if (targetExpanded) {
+ refreshTargets.set(`${move.toNotebook}:${move.toPath}`, {
+ element: targetElement,
+ notebookId: move.toNotebook,
+ });
}
+ });
+ if (response.callback !== Constants.CB_MOVE_NOLIST) {
+ refreshTargets.forEach((target) => {
+ this.getLeaf(target.element, target.notebookId, true);
+ });
}
}
+ private restoreMovedExpandedItems(listElement: Element, notebookId: string) {
+ restoreMovedExpandedDocItems(listElement, this.movedExpandedDocIDs, (item) => {
+ this.getLeaf(item, notebookId, true);
+ });
+ }
+
private onLsHTML(data: { files: IFile[], box: string, path: string }, scrollTop?: number) {
if (data.files.length === 0) {
return;
@@ -1383,6 +1451,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
}
});
nextElement.innerHTML = tempElement.innerHTML;
+ this.restoreMovedExpandedItems(nextElement, data.box);
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
}
@@ -1392,6 +1461,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
liElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
nextElement = liElement.nextElementSibling;
+ this.restoreMovedExpandedItems(nextElement, data.box);
nextElement.setAttribute("style", "top: -1px;position: relative;");
expandFileTree(nextElement as HTMLElement, () => {
nextElement.removeAttribute("style");
@@ -1430,6 +1500,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
emojiElement.textContent = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder);
}
liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
+ this.restoreMovedExpandedItems(liElement.nextElementSibling, data.box);
let newLiElement;
for (let i = 0; i < data.files.length; i++) {
const item = data.files[i];
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index a09d4b5bd0..53256be77d 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -28,12 +28,21 @@ import {
isFileTreeCollapsing
} from "../../layout/dock/fileTreeAnimation";
import {bindMousePointerTouchBridge, isMousePointerTouchEvent} from "../util/mousePointerTouchBridge";
+import {
+ collectExpandedDocIDs,
+ findMovedFileTreeItem,
+ getFileTreeChildList,
+ IFileTreeMove,
+ restoreMovedExpandedDocItems,
+ updateMovedSubtree
+} from "../../util/fileTreeMove";
export class MobileFiles extends Model {
public element: HTMLElement;
private actionsElement: HTMLElement;
private closeElement: HTMLElement;
private reloadNotebookInfoTimeout: number;
+ private movedExpandedDocIDs = new Set<string>();
private touchDragState: {
selectedElement: HTMLElement;
startX: number;
@@ -427,7 +436,9 @@ export class MobileFiles extends Model {
callback: Constants.CB_MOVE_NOLIST,
});
selectFileElements.forEach(item => {
- item.setAttribute("data-path", pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy"));
+ const fromPath = item.getAttribute("data-path");
+ const newPath = pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy");
+ updateMovedSubtree(item, getFileTreeChildList(item), fromPath, newPath);
});
hasMove = true;
}
@@ -508,8 +519,10 @@ export class MobileFiles extends Model {
private handleMsgCallback(data: IWebSocketData) {
if (data) {
switch (data.cmd) {
+ case "moveDocs":
+ this.onMove(data);
+ break;
case "moveDoc":
- this.onMove(data.data);
break;
case "reloadFiletree":
setNoteBook(() => {
@@ -803,62 +816,111 @@ export class MobileFiles extends Model {
}
}
- private onMove(data: {
- fromNotebook: string,
- toNotebook: string,
- fromPath: string
- toPath: string
- }) {
- const sourceElement = this.element.querySelector(`ul[data-url="${data.fromNotebook}"] li[data-path="${data.fromPath}"]`) as HTMLElement;
- if (sourceElement) {
- if (sourceElement.nextElementSibling && sourceElement.nextElementSibling.tagName === "UL") {
- sourceElement.nextElementSibling.remove();
+ private onMove(response: IWebSocketData) {
+ const refreshTargets = new Map<string, { element: HTMLElement, notebookId: string }>();
+ (response.data.moves as IFileTreeMove[]).forEach((move) => {
+ const expandedDocIDs = new Set<string>();
+ const movedItem = findMovedFileTreeItem(this.element, move);
+ const sourceElement = movedItem?.element;
+ const sourceAtTarget = movedItem?.isAtTarget;
+ let childListElement: HTMLElement;
+ if (sourceElement) {
+ childListElement = getFileTreeChildList(sourceElement);
+ collectExpandedDocIDs(sourceElement, childListElement, expandedDocIDs);
+ updateMovedSubtree(sourceElement, childListElement, move.fromPath, move.newPath);
}
- if (sourceElement.parentElement.childElementCount === 1) {
- if (sourceElement.parentElement.previousElementSibling) {
- const parentLiElement = sourceElement.parentElement.previousElementSibling as HTMLElement;
- if (parentLiElement.getAttribute("data-type") !== "navigation-root" || parentLiElement.dataset.nodeId) {
- parentLiElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
- }
- parentLiElement.querySelector(".b3-list-item__arrow").classList.remove("b3-list-item__arrow--open");
- parentLiElement.setAttribute("data-count", "0");
- this.updateDocActionElement(parentLiElement);
- const emojiElement = parentLiElement.querySelector(".b3-list-item__icon");
- if (emojiElement.innerHTML === unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder)) {
- emojiElement.innerHTML = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].file);
+ if (sourceElement && !sourceAtTarget) {
+ const sourceListElement = sourceElement.parentElement;
+ childListElement?.remove();
+ if (sourceListElement.childElementCount === 1) {
+ const parentLiElement = sourceListElement.previousElementSibling as HTMLElement;
+ if (parentLiElement) {
+ if (parentLiElement.getAttribute("data-type") !== "navigation-root" ||
+ parentLiElement.dataset.nodeId) {
+ parentLiElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
+ }
+ parentLiElement.querySelector(".b3-list-item__arrow").classList.remove(
+ "b3-list-item__arrow--open"
+ );
+ parentLiElement.setAttribute("data-count", "0");
+ this.updateDocActionElement(parentLiElement);
+ const emojiElement = parentLiElement.querySelector(".b3-list-item__icon");
+ if (emojiElement.innerHTML === unicode2Emoji(
+ window.siyuan.storage[Constants.LOCAL_IMAGES].folder
+ )) {
+ emojiElement.innerHTML = unicode2Emoji(
+ window.siyuan.storage[Constants.LOCAL_IMAGES].file
+ );
+ }
}
+ sourceListElement.remove();
+ } else {
+ sourceElement.remove();
+ }
+ } else if (!sourceElement || sourceAtTarget) {
+ const parentPath = pathPosix().dirname(move.fromPath);
+ const parentElement = this.element.querySelector(
+ `ul[data-url="${move.fromNotebook}"] li[data-path="${parentPath === "/" ? "/" : parentPath + ".sy"}"]`
+ ) as HTMLElement;
+ if (parentElement && parentElement.getAttribute("data-count") === "1") {
+ parentElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
+ parentElement.querySelector(".b3-list-item__arrow").classList.remove(
+ "b3-list-item__arrow--open"
+ );
}
- sourceElement.parentElement.remove();
- } else {
- sourceElement.remove();
}
- } else {
- const parentElement = this.element.querySelector(`ul[data-url="${data.fromNotebook}"] li[data-path="${pathPosix().dirname(data.fromPath)}.sy"]`) as HTMLElement;
- if (parentElement && parentElement.getAttribute("data-count") === "1") {
- parentElement.querySelector(".b3-list-item__toggle").classList.add("fn__hidden");
- parentElement.querySelector(".b3-list-item__arrow").classList.remove("b3-list-item__arrow--open");
+
+ const targetElement = this.element.querySelector(
+ `[data-url="${move.toNotebook}"] li[data-path="${move.toPath}"]`
+ ) as HTMLElement;
+ if (!targetElement) {
+ expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
+ return;
}
- }
- const newElement = this.element.querySelector(`[data-url="${data.toNotebook}"] li[data-path="${data.toPath}"]`) as HTMLElement;
- // 重新展开移动到的新文件夹
- if (newElement) {
- const emojiElement = newElement.querySelector(".b3-list-item__icon");
+ targetElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
+ if (targetElement.getAttribute("data-type") === "navigation-root") {
+ targetElement.setAttribute(
+ "data-count",
+ Math.max(1, Number(targetElement.getAttribute("data-count"))).toString()
+ );
+ this.updateDocActionElement(targetElement);
+ }
+ const emojiElement = targetElement.querySelector(".b3-list-item__icon");
if (emojiElement.innerHTML === unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].file)) {
emojiElement.innerHTML = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder);
}
- newElement.querySelector(".b3-list-item__toggle").classList.remove("fn__hidden");
- if (newElement.getAttribute("data-type") === "navigation-root") {
- newElement.setAttribute("data-count", Math.max(1, Number(newElement.getAttribute("data-count"))).toString());
- this.updateDocActionElement(newElement);
+
+ const targetListElement = getFileTreeChildList(targetElement);
+ const targetExpanded = Boolean(targetElement.querySelector(".b3-list-item__arrow--open"));
+ if (sourceElement && targetListElement && !sourceAtTarget) {
+ targetListElement.append(sourceElement);
+ if (childListElement) {
+ sourceElement.after(childListElement);
+ }
+ }
+ if (!targetExpanded || !sourceElement || (!sourceAtTarget && !targetListElement)) {
+ expandedDocIDs.forEach((id) => this.movedExpandedDocIDs.add(id));
}
- newElement.querySelector(".b3-list-item__arrow").classList.remove("b3-list-item__arrow--open");
- if (newElement.nextElementSibling && newElement.nextElementSibling.tagName === "UL") {
- newElement.nextElementSibling.remove();
+ if (targetExpanded) {
+ refreshTargets.set(`${move.toNotebook}:${move.toPath}`, {
+ element: targetElement,
+ notebookId: move.toNotebook,
+ });
}
- this.getLeaf(newElement, data.toNotebook);
+ });
+ if (response.callback !== Constants.CB_MOVE_NOLIST) {
+ refreshTargets.forEach((target) => {
+ this.getLeaf(target.element, target.notebookId, true);
+ });
}
}
+ private restoreMovedExpandedItems(listElement: Element, notebookId: string) {
+ restoreMovedExpandedDocItems(listElement, this.movedExpandedDocIDs, (item) => {
+ this.getLeaf(item, notebookId, true);
+ });
+ }
+
private onRemove(data: IWebSocketData) {
// "doc2heading" 后删除文件或挂载帮助文档前的 unmount
if (data.cmd === "closeBox" || data.cmd === "removeBox") {
@@ -1038,6 +1100,7 @@ export class MobileFiles extends Model {
}
});
nextElement.innerHTML = tempElement.innerHTML;
+ this.restoreMovedExpandedItems(nextElement, data.box);
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
}
@@ -1047,6 +1110,7 @@ export class MobileFiles extends Model {
liElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
nextElement = liElement.nextElementSibling;
+ this.restoreMovedExpandedItems(nextElement, data.box);
expandFileTree(nextElement as HTMLElement, () => {
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
@@ -1080,6 +1144,7 @@ export class MobileFiles extends Model {
emojiElement.textContent = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder);
}
liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
+ this.restoreMovedExpandedItems(liElement.nextElementSibling, data.box);
let newLiElement;
for (let i = 0; i < data.files.length; i++) {
const item = data.files[i];
diff --git a/app/src/util/fileTreeMove.test.ts b/app/src/util/fileTreeMove.test.ts
new file mode 100644
index 0000000000..9999f23ac7
--- /dev/null
+++ b/app/src/util/fileTreeMove.test.ts
@@ -0,0 +1,192 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ findMovedFileTreeItem,
+ IFileTreeMove,
+ remapMovedPath,
+ restoreMovedExpandedDocItems,
+ updateMovedSubtree
+} from "./fileTreeMove";
+
+const move: IFileTreeMove = {
+ fromNotebook: "source-notebook",
+ fromPath: "/parent/current.sy",
+ toNotebook: "target-notebook",
+ toPath: "/target.sy",
+ newPath: "/target/current.sy",
+};
+
+const createFileTreeItem = (path: string) => {
+ const properties = new Map<string, string>();
+ const toggleElement = {
+ style: {
+ paddingLeft: "",
+ },
+ };
+ const element = {
+ dataset: {path},
+ style: {
+ setProperty(name: string, value: string) {
+ properties.set(name, value);
+ },
+ },
+ querySelector(selector: string) {
+ return selector === ":scope > .b3-list-item__toggle" ? toggleElement : undefined;
+ },
+ } as unknown as HTMLElement;
+ return {
+ element,
+ properties,
+ toggleElement,
+ };
+};
+
+const createFileTreeList = (items: HTMLElement[]) => ({
+ tagName: "UL",
+ querySelectorAll() {
+ return items;
+ },
+}) as unknown as HTMLElement;
+
+const createExpandableItem = (id: string, expanded: boolean, childListElement?: HTMLElement) => ({
+ dataset: {nodeId: id},
+ nextElementSibling: childListElement,
+ querySelector(selector: string) {
+ return expanded && selector === ".b3-list-item__arrow--open" ? {} : undefined;
+ },
+}) as unknown as HTMLElement;
+
+describe("remapMovedPath", () => {
+ it("remaps descendants when moving to another parent", () => {
+ assert.equal(
+ remapMovedPath("/parent/current/child.sy", "/parent/current.sy", "/target/current.sy"),
+ "/target/current/child.sy"
+ );
+ });
+
+ it("remaps descendants when moving to the notebook root", () => {
+ assert.equal(
+ remapMovedPath("/parent/current/child/grandchild.sy", "/parent/current.sy", "/current.sy"),
+ "/current/child/grandchild.sy"
+ );
+ });
+
+ it("does not remap paths outside the moved subtree", () => {
+ assert.equal(
+ remapMovedPath("/parent/current-other/child.sy", "/parent/current.sy", "/target/current.sy"),
+ "/parent/current-other/child.sy"
+ );
+ });
+});
+
+describe("findMovedFileTreeItem", () => {
+ it("uses the source item when the WebSocket event arrives first", () => {
+ const sourceElement = {} as HTMLElement;
+ const treeElement = {
+ querySelector(selector: string) {
+ return selector.includes(move.fromNotebook) ? sourceElement : undefined;
+ },
+ } as unknown as Element;
+
+ assert.deepEqual(findMovedFileTreeItem(treeElement, move), {
+ element: sourceElement,
+ isAtTarget: false,
+ });
+ });
+
+ it("uses the target item when the local move finishes first", () => {
+ const targetElement = {} as HTMLElement;
+ const treeElement = {
+ querySelector(selector: string) {
+ return selector.includes(move.toNotebook) ? targetElement : undefined;
+ },
+ } as unknown as Element;
+
+ assert.deepEqual(findMovedFileTreeItem(treeElement, move), {
+ element: targetElement,
+ isAtTarget: true,
+ });
+ });
+});
+
+describe("updateMovedSubtree", () => {
+ it("updates paths and indentation for the complete moved subtree", () => {
+ const root = createFileTreeItem(move.fromPath);
+ const child = createFileTreeItem("/parent/current/child.sy");
+ const grandchild = createFileTreeItem("/parent/current/child/grandchild.sy");
+ const childListElement = {
+ querySelectorAll() {
+ return [child.element, grandchild.element];
+ },
+ } as unknown as HTMLElement;
+
+ updateMovedSubtree(root.element, childListElement, move.fromPath, move.newPath);
+
+ assert.equal(root.element.dataset.path, move.newPath);
+ assert.equal(child.element.dataset.path, "/target/current/child.sy");
+ assert.equal(grandchild.element.dataset.path, "/target/current/child/grandchild.sy");
+ assert.equal(root.properties.get("--file-toggle-width"), "60px");
+ assert.equal(child.properties.get("--file-toggle-width"), "80px");
+ assert.equal(grandchild.properties.get("--file-toggle-width"), "100px");
+ assert.equal(root.toggleElement.style.paddingLeft, "40px");
+ assert.equal(child.toggleElement.style.paddingLeft, "60px");
+ assert.equal(grandchild.toggleElement.style.paddingLeft, "80px");
+ });
+
+ it("is idempotent when the local move and WebSocket event both update the subtree", () => {
+ const root = createFileTreeItem(move.fromPath);
+ const child = createFileTreeItem("/parent/current/child.sy");
+ const childListElement = {
+ querySelectorAll() {
+ return [child.element];
+ },
+ } as unknown as HTMLElement;
+
+ updateMovedSubtree(root.element, childListElement, move.fromPath, move.newPath);
+ updateMovedSubtree(root.element, childListElement, move.fromPath, move.newPath);
+
+ assert.equal(root.element.dataset.path, move.newPath);
+ assert.equal(child.element.dataset.path, "/target/current/child.sy");
+ assert.equal(root.properties.get("--file-toggle-width"), "60px");
+ assert.equal(child.properties.get("--file-toggle-width"), "80px");
+ });
+});
+
+describe("restoreMovedExpandedDocItems", () => {
+ it("keeps an existing expanded subtree and restores its descendants", () => {
+ const child = createExpandableItem("child", false);
+ const childList = createFileTreeList([child]);
+ const root = createExpandableItem("root", true, childList);
+ const rootList = createFileTreeList([root]);
+ const expandedDocIDs = new Set(["root", "child"]);
+ const expandedItems: string[] = [];
+
+ restoreMovedExpandedDocItems(rootList, expandedDocIDs, (item) => {
+ expandedItems.push(item.dataset.nodeId);
+ });
+
+ assert.deepEqual(expandedItems, ["child"]);
+ assert.equal(expandedDocIDs.size, 0);
+ });
+
+ it("restores descendants after a moved root is loaded under a collapsed target", () => {
+ const root = createExpandableItem("root", false);
+ const rootList = createFileTreeList([root]);
+ const child = createExpandableItem("child", false);
+ const childList = createFileTreeList([child]);
+ const expandedDocIDs = new Set(["root", "child"]);
+ const expandedItems: string[] = [];
+
+ restoreMovedExpandedDocItems(rootList, expandedDocIDs, (item) => {
+ expandedItems.push(item.dataset.nodeId);
+ });
+ assert.deepEqual(expandedItems, ["root"]);
+ assert.deepEqual([...expandedDocIDs], ["child"]);
+
+ restoreMovedExpandedDocItems(childList, expandedDocIDs, (item) => {
+ expandedItems.push(item.dataset.nodeId);
+ });
+ assert.deepEqual(expandedItems, ["root", "child"]);
+ assert.equal(expandedDocIDs.size, 0);
+ });
+});
diff --git a/app/src/util/fileTreeMove.ts b/app/src/util/fileTreeMove.ts
new file mode 100644
index 0000000000..5d2858167e
--- /dev/null
+++ b/app/src/util/fileTreeMove.ts
@@ -0,0 +1,100 @@
+export interface IFileTreeMove {
+ fromNotebook: string;
+ fromPath: string;
+ toNotebook: string;
+ toPath: string;
+ newPath: string;
+}
+
+export const findMovedFileTreeItem = (treeElement: Element, move: IFileTreeMove) => {
+ const sourceElement = treeElement.querySelector<HTMLElement>(
+ `ul[data-url="${move.fromNotebook}"] li[data-path="${move.fromPath}"]`
+ );
+ if (sourceElement) {
+ return {
+ element: sourceElement,
+ isAtTarget: false,
+ };
+ }
+ const targetElement = treeElement.querySelector<HTMLElement>(
+ `ul[data-url="${move.toNotebook}"] li[data-path="${move.newPath}"]`
+ );
+ if (targetElement) {
+ return {
+ element: targetElement,
+ isAtTarget: true,
+ };
+ }
+};
+
+export const getFileTreeChildList = (liElement: Element) => {
+ const nextElement = liElement.nextElementSibling;
+ return nextElement?.tagName === "UL" ? nextElement as HTMLElement : undefined;
+};
+
+export const collectExpandedDocIDs = (
+ liElement: HTMLElement,
+ childListElement: HTMLElement | undefined,
+ expandedDocIDs: Set<string>
+) => {
+ if (liElement.dataset.nodeId && liElement.querySelector(".b3-list-item__arrow--open")) {
+ expandedDocIDs.add(liElement.dataset.nodeId);
+ }
+ childListElement?.querySelectorAll(".b3-list-item__arrow--open").forEach((arrowElement) => {
+ const childItemElement = arrowElement.closest("li[data-node-id]") as HTMLElement;
+ if (childItemElement?.dataset.nodeId) {
+ expandedDocIDs.add(childItemElement.dataset.nodeId);
+ }
+ });
+};
+
+export const restoreMovedExpandedDocItems = (
+ listElement: Element,
+ expandedDocIDs: Set<string>,
+ expandItem: (item: HTMLElement) => void
+) => {
+ listElement.querySelectorAll<HTMLElement>(":scope > li[data-node-id]").forEach((item) => {
+ const id = item.dataset.nodeId;
+ if (!expandedDocIDs.has(id)) {
+ return;
+ }
+ expandedDocIDs.delete(id);
+ const childListElement = getFileTreeChildList(item);
+ if (item.querySelector(".b3-list-item__arrow--open") && childListElement) {
+ restoreMovedExpandedDocItems(childListElement, expandedDocIDs, expandItem);
+ } else {
+ expandItem(item);
+ }
+ });
+};
+
+export const remapMovedPath = (currentPath: string, fromPath: string, newPath: string) => {
+ const fromPrefix = fromPath.endsWith(".sy") ? fromPath.slice(0, -3) : fromPath;
+ const newPrefix = newPath.endsWith(".sy") ? newPath.slice(0, -3) : newPath;
+ if (!currentPath.startsWith(fromPrefix + "/")) {
+ return currentPath;
+ }
+ return newPrefix + currentPath.slice(fromPrefix.length);
+};
+
+const updateMovedItemPath = (item: HTMLElement, newPath: string) => {
+ item.dataset.path = newPath;
+ const paddingLeft = (newPath.split("/").length - 1) * 20;
+ item.style.setProperty("--file-toggle-width", `${paddingLeft + 20}px`);
+ const toggleElement = item.querySelector<HTMLElement>(":scope > .b3-list-item__toggle");
+ if (toggleElement) {
+ toggleElement.style.paddingLeft = `${paddingLeft}px`;
+ }
+};
+
+export const updateMovedSubtree = (
+ liElement: HTMLElement,
+ childListElement: HTMLElement | undefined,
+ fromPath: string,
+ newPath: string
+) => {
+ updateMovedItemPath(liElement, newPath);
+ childListElement?.querySelectorAll<HTMLElement>("li[data-path]").forEach((item) => {
+ updateMovedItemPath(item, remapMovedPath(item.dataset.path, fromPath, newPath));
+ });
+};
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 66687dc591..68a59a2d79 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1550,6 +1550,14 @@ type moveDocsRefresh struct {
notebooks map[string]struct{}
}
+type moveDocResult struct {
+ FromNotebook string `json:"fromNotebook"`
+ FromPath string `json:"fromPath"`
+ ToNotebook string `json:"toNotebook"`
+ ToPath string `json:"toPath"`
+ NewPath string `json:"newPath"`
+}
+
func newMoveDocsRefresh() *moveDocsRefresh {
return &moveDocsRefresh{
parents: map[moveDocsRefreshKey]*parse.Tree{},
@@ -1652,7 +1660,16 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
FlushTxQueue()
luteEngine := util.NewLute()
refresh := newMoveDocsRefresh()
- defer refresh.flush()
+ movedDocs := make([]moveDocResult, 0, len(pathsBoxes))
+ defer func() {
+ if 0 < len(movedDocs) {
+ evt := util.NewCmdResult("moveDocs", 0, util.PushModeBroadcast)
+ evt.Data = map[string]any{"moves": movedDocs}
+ evt.Callback = callback
+ util.PushEvent(evt)
+ }
+ refresh.flush()
+ }()
count := 0
for fromPath, fromBox := range pathsBoxes {
count++
@@ -1660,10 +1677,18 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
util.PushEndlessProgress(fmt.Sprintf(Conf.Language(70), fmt.Sprintf("%d/%d", count, len(fromPaths))))
}
- _, err = moveDoc(fromBox, fromPath, toBox, toPath, luteEngine, callback, refresh)
+ var newPath string
+ newPath, err = moveDoc(fromBox, fromPath, toBox, toPath, luteEngine, callback, refresh)
if err != nil {
return
}
+ movedDocs = append(movedDocs, moveDocResult{
+ FromNotebook: fromBox.ID,
+ FromPath: fromPath,
+ ToNotebook: toBox.ID,
+ ToPath: toPath,
+ NewPath: newPath,
+ })
}
cache.ClearDocsIAL()
IncSync()