Skip to content

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

:bug: Preserve multi-document drag order https://github.com/siyuan-note/siyuan/issues/18636

Daniel6882db586eef
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index a7d00780c6..c0888bde65 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -45,6 +45,7 @@ import {
IDocumentTabDragData,
IFileTreeMove,
insertDocumentSortPath,
+ insertDocumentsSortPaths,
parseDocumentTabDragData,
restoreMovedExpandedDocItems,
updateMovedSubtree
@@ -838,30 +839,49 @@ export class Files extends Model {
notebooks,
});
} else if ((ulSort === "6" || (window.siyuan.config.fileTree.sort === 6 && ulSort === "15")) && selectFileElements.length > 0) {
- let hasMove = false;
const toDir = pathPosix().dirname(toPath);
const newElementClassList = newElement.getAttribute("class");
- if (fromPaths.length > 0) {
- const sourceNotebookIds = selectFileElements.map((item) =>
- item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
- if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
- showMessage(window.siyuan.languages._kernel[313]);
- newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
- return;
+ const sourceNotebookIds = selectFileElements.map((item) =>
+ item.getAttribute("data-notebook-id") || item.closest("ul[data-url]")?.getAttribute("data-url") || "");
+ if (!isMoveTargetAllowed(sourceNotebookIds, toURL)) {
+ showMessage(window.siyuan.languages._kernel[313]);
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ return;
+ }
+ const siblingPaths: string[] = [];
+ Array.from(newElement.parentElement.children).forEach(item => {
+ const itemPath = item.getAttribute("data-path");
+ if (item.tagName === "LI" && itemPath) {
+ siblingPaths.push(itemPath);
}
- await fetchSyncPost("/api/filetree/moveDocs", {
- toNotebook: toURL,
- fromPaths,
- toPath: toDir === "/" ? "/" : toDir + ".sy",
- callback: Constants.CB_MOVE_NOLIST,
- });
- selectFileElements.forEach(item => {
- 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;
+ });
+ const newPaths = selectFileElements.map((item) =>
+ pathPosix().join(toDir, item.getAttribute("data-node-id") + ".sy"));
+ const sortedPaths = insertDocumentsSortPaths(
+ siblingPaths,
+ newPaths,
+ toPath,
+ newElementClassList.includes("dragover__bottom")
+ );
+ if (!sortedPaths || (sortedPaths.length === siblingPaths.length &&
+ sortedPaths.every((itemPath, index) => itemPath === siblingPaths[index]))) {
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ return;
+ }
+ const moveResponse = await fetchSyncPost("/api/filetree/moveDocs", {
+ toNotebook: toURL,
+ fromPaths,
+ toPath: toDir === "/" ? "/" : toDir + ".sy",
+ callback: Constants.CB_MOVE_NOLIST,
+ });
+ if (moveResponse.code !== 0) {
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ return;
}
+ selectFileElements.forEach((item, index) => {
+ const fromPath = item.getAttribute("data-path");
+ updateMovedSubtree(item, getFileTreeChildList(item), fromPath, newPaths[index]);
+ });
if (newElementClassList.includes("dragover__top")) {
selectFileElements.forEach(item => {
let nextULElement;
@@ -874,7 +894,7 @@ export class Files extends Model {
}
});
} else if (newElementClassList.includes("dragover__bottom")) {
- selectFileElements.reverse().forEach(item => {
+ [...selectFileElements].reverse().forEach(item => {
let nextULElement;
if (item.nextElementSibling && item.nextElementSibling.tagName === "UL") {
nextULElement = item.nextElementSibling;
@@ -889,30 +909,26 @@ export class Files extends Model {
}
});
}
- const paths: string[] = [];
- Array.from(newElement.parentElement.children).forEach(item => {
- if (item.tagName === "LI") {
- paths.push(item.getAttribute("data-path"));
- }
- });
- fetchPost("/api/filetree/changeSort", {
- paths,
+ const sortResponse = await fetchSyncPost("/api/filetree/changeSort", {
+ paths: sortedPaths,
notebook: toURL
- }, () => {
- if (hasMove) {
- fetchPost("/api/filetree/listDocsByPath", {
- notebook: toURL,
- path: toDir === "/" ? "/" : toDir + ".sy",
- app: Constants.SIYUAN_APPID,
- }, response => {
- if (response.data.path === "/" && response.data.files.length === 0) {
- showMessage(window.siyuan.languages.emptyContent);
- return;
- }
- this.onLsHTML(response.data, oldScrollTop);
- });
- }
});
+ if (sortResponse.code !== 0) {
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ return;
+ }
+ const listResponse = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: toURL,
+ path: toDir === "/" ? "/" : toDir + ".sy",
+ app: Constants.SIYUAN_APPID,
+ });
+ if (listResponse.code === 0 && listResponse.data?.files) {
+ if (listResponse.data.path === "/" && listResponse.data.files.length === 0) {
+ showMessage(window.siyuan.languages.emptyContent);
+ } else {
+ this.onLsHTML(listResponse.data, oldScrollTop);
+ }
+ }
}
}
newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
diff --git a/app/src/util/fileTreeMove.test.ts b/app/src/util/fileTreeMove.test.ts
index 624e321485..3942013af6 100644
--- a/app/src/util/fileTreeMove.test.ts
+++ b/app/src/util/fileTreeMove.test.ts
@@ -4,6 +4,7 @@ import {
findMovedFileTreeItem,
IFileTreeMove,
insertDocumentSortPath,
+ insertDocumentsSortPaths,
parseDocumentTabDragData,
remapMovedPath,
restoreMovedExpandedDocItems,
@@ -64,6 +65,50 @@ describe("insertDocumentSortPath", () => {
});
});
+describe("insertDocumentsSortPaths", () => {
+ it("inserts documents from another parent after the target in source order", () => {
+ assert.deepEqual(insertDocumentsSortPaths(
+ ["/target-a.sy", "/target-b.sy", "/target-c.sy"],
+ ["/source-a.sy", "/source-b.sy", "/source-c.sy"],
+ "/target-b.sy",
+ true
+ ), ["/target-a.sy", "/target-b.sy", "/source-a.sy", "/source-b.sy", "/source-c.sy", "/target-c.sy"]);
+ });
+
+ it("reorders documents already under the target parent before the target", () => {
+ assert.deepEqual(insertDocumentsSortPaths(
+ ["/a.sy", "/source-a.sy", "/b.sy", "/source-b.sy", "/c.sy"],
+ ["/source-a.sy", "/source-b.sy"],
+ "/b.sy",
+ false
+ ), ["/a.sy", "/source-a.sy", "/source-b.sy", "/b.sy", "/c.sy"]);
+ });
+
+ it("removes source documents by ID when their parent paths change", () => {
+ assert.deepEqual(insertDocumentsSortPaths(
+ ["/old/source-a.sy", "/target.sy", "/old/source-b.sy"],
+ ["/new/source-a.sy", "/new/source-b.sy"],
+ "/target.sy",
+ true
+ ), ["/target.sy", "/new/source-a.sy", "/new/source-b.sy"]);
+ });
+
+ it("does not modify its input arrays", () => {
+ const siblingPaths = ["/a.sy", "/b.sy"];
+ const newPaths = ["/source-a.sy", "/source-b.sy"];
+
+ insertDocumentsSortPaths(siblingPaths, newPaths, "/b.sy", true);
+
+ assert.deepEqual(siblingPaths, ["/a.sy", "/b.sy"]);
+ assert.deepEqual(newPaths, ["/source-a.sy", "/source-b.sy"]);
+ });
+
+ it("returns undefined for empty sources or a missing target", () => {
+ assert.equal(insertDocumentsSortPaths(["/a.sy"], [], "/a.sy", true), undefined);
+ assert.equal(insertDocumentsSortPaths(["/a.sy"], ["/source.sy"], "/missing.sy", true), undefined);
+ });
+});
+
const move: IFileTreeMove = {
fromNotebook: "source-notebook",
fromPath: "/parent/current.sy",
diff --git a/app/src/util/fileTreeMove.ts b/app/src/util/fileTreeMove.ts
index 444577ae5f..c5f4b43123 100644
--- a/app/src/util/fileTreeMove.ts
+++ b/app/src/util/fileTreeMove.ts
@@ -39,12 +39,39 @@ export const insertDocumentSortPath = (
targetPath: string,
insertAfter: boolean
) => {
- const paths = siblingPaths.filter((path) => getDocumentIDFromPath(path) !== sourceID);
+ return insertSortPaths(siblingPaths, [sourceID], [newPath], targetPath, insertAfter);
+};
+
+export const insertDocumentsSortPaths = (
+ siblingPaths: string[],
+ newPaths: string[],
+ targetPath: string,
+ insertAfter: boolean
+) => insertSortPaths(
+ siblingPaths,
+ newPaths.map(getDocumentIDFromPath),
+ newPaths,
+ targetPath,
+ insertAfter
+);
+
+const insertSortPaths = (
+ siblingPaths: string[],
+ sourceIDs: string[],
+ newPaths: string[],
+ targetPath: string,
+ insertAfter: boolean
+) => {
+ if (newPaths.length === 0 || newPaths.length !== sourceIDs.length) {
+ return;
+ }
+ const sourceIDSet = new Set(sourceIDs);
+ const paths = siblingPaths.filter((path) => !sourceIDSet.has(getDocumentIDFromPath(path)));
const targetIndex = paths.indexOf(targetPath);
if (targetIndex === -1) {
return;
}
- paths.splice(targetIndex + (insertAfter ? 1 : 0), 0, newPath);
+ paths.splice(targetIndex + (insertAfter ? 1 : 0), 0, ...newPaths);
return paths;
};
diff --git a/kernel/model/file.go b/kernel/model/file.go
index eec9f0724c..493c4637ae 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1648,6 +1648,26 @@ func (refresh *moveDocsRefresh) flushWith(refreshParent func(*parse.Tree), refre
}
}
+func orderMoveDocPaths(fromPaths []string, pathsBoxes map[string]*Box) (ret []string) {
+ canonicalPaths := map[string]string{}
+ for canonicalPath := range pathsBoxes {
+ canonicalPaths[util.GetTreeID(canonicalPath)] = canonicalPath
+ }
+ addedPaths := map[string]struct{}{}
+ for _, fromPath := range fromPaths {
+ canonicalPath := canonicalPaths[util.GetTreeID(fromPath)]
+ if "" == canonicalPath {
+ continue
+ }
+ if _, ok := addedPaths[canonicalPath]; ok {
+ continue
+ }
+ ret = append(ret, canonicalPath)
+ addedPaths[canonicalPath] = struct{}{}
+ }
+ return
+}
+
func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err error) {
toBox := Conf.Box(toBoxID)
if nil == toBox {
@@ -1655,7 +1675,8 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
return
}
toPath = normalizeBoxDocTarget(toBoxID, toPath)
- if _, err = getBoxesByPathsStrict(fromPaths); err != nil {
+ pathsBoxes, err := getBoxesByPathsStrict(fromPaths)
+ if err != nil {
return
}
@@ -1664,8 +1685,10 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
return
}
- pathsBoxes := getBoxesByPaths(fromPaths)
- for fromPath, fromBox := range pathsBoxes {
+ fromPaths = orderMoveDocPaths(fromPaths, pathsBoxes)
+
+ for _, fromPath := range fromPaths {
+ fromBox := pathsBoxes[fromPath]
if nil != fromBox && IsBoxDocPath(fromBox.ID, fromPath) {
return errors.New(Conf.Language(341))
}
@@ -1682,7 +1705,8 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
}
// 检查路径深度是否超过限制
- for fromPath, fromBox := range pathsBoxes {
+ for _, fromPath := range fromPaths {
+ fromBox := pathsBoxes[fromPath]
childDepth := util.GetChildDocDepth(filepath.Join(util.DataDir, fromBox.ID, fromPath))
if depth := strings.Count(toPath, "/") + childDepth; 6 < depth && !Conf.FileTree.AllowCreateDeeper {
err = errors.New(Conf.Language(118))
@@ -1692,7 +1716,8 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
// 禁止跨加密边界移动文档:加密笔记本是孤岛,不同加密笔记本各有独立 DEK,
// 跨边界移动(普通↔加密、加密 A↔加密 B)会导致密文用错 DEK 损坏数据
- for _, fromBox := range pathsBoxes {
+ for _, fromPath := range fromPaths {
+ fromBox := pathsBoxes[fromPath]
if fromBox.ID != toBox.ID && !IsSameCryptoBoundary(fromBox.ID, toBox.ID) {
err = errors.New(Conf.Language(313))
return
@@ -1701,7 +1726,8 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
// A progress layer appears when moving more than 64 documents at once https://github.com/siyuan-note/siyuan/issues/9356
subDocsCount := 0
- for fromPath, fromBox := range pathsBoxes {
+ for _, fromPath := range fromPaths {
+ fromBox := pathsBoxes[fromPath]
subDocsCount += countSubDocs(fromBox.ID, fromPath)
}
needShowProgress := 64 < subDocsCount
@@ -1712,7 +1738,7 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
FlushTxQueue()
luteEngine := util.NewLute()
refresh := newMoveDocsRefresh()
- movedDocs := make([]moveDocResult, 0, len(pathsBoxes))
+ movedDocs := make([]moveDocResult, 0, len(fromPaths))
defer func() {
if 0 < len(movedDocs) {
evt := util.NewCmdResult("moveDocs", 0, util.PushModeBroadcast)
@@ -1723,7 +1749,8 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
refresh.flush()
}()
count := 0
- for fromPath, fromBox := range pathsBoxes {
+ for _, fromPath := range fromPaths {
+ fromBox := pathsBoxes[fromPath]
count++
if needShowProgress {
util.PushEndlessProgress(fmt.Sprintf(Conf.Language(70), fmt.Sprintf("%d/%d", count, len(fromPaths))))
diff --git a/kernel/model/file_test.go b/kernel/model/file_test.go
index b0a43f2440..5ade9f212b 100644
--- a/kernel/model/file_test.go
+++ b/kernel/model/file_test.go
@@ -20,6 +20,7 @@ import (
"errors"
"path"
"path/filepath"
+ "reflect"
"strings"
"testing"
@@ -324,6 +325,26 @@ func TestMoveDocsRefreshDeduplicatesParentsAndNotebooks(t *testing.T) {
}
}
+func TestOrderMoveDocPathsPreservesInputOrder(t *testing.T) {
+ box := &Box{ID: "20260810000000-abcdefg"}
+ firstPath := "/20260810000001-abcdefg.sy"
+ secondPath := "/20260810000002-abcdefg.sy"
+ pathsBoxes := map[string]*Box{
+ firstPath: box,
+ secondPath: box,
+ }
+
+ got := orderMoveDocPaths([]string{
+ strings.TrimPrefix(secondPath, "/"),
+ firstPath,
+ secondPath,
+ }, pathsBoxes)
+ want := []string{secondPath, firstPath}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("unexpected ordered paths: got %v, want %v", got, want)
+ }
+}
+
func TestSetFileTreeSort(t *testing.T) {
fixture := setupFileOperationTest(t)
diff --git a/kernel/util/path.go b/kernel/util/path.go
index ef47e92815..3581703db4 100644
--- a/kernel/util/path.go
+++ b/kernel/util/path.go
@@ -24,7 +24,6 @@ import (
"path"
"path/filepath"
"runtime"
- "sort"
"strings"
"sync"
"time"
@@ -282,14 +281,19 @@ func FilterMoveDocFromPaths(fromPaths []string, toPath string) (ret []string) {
}
func FilterSelfChildDocs(paths []string) (ret []string) {
- sort.Slice(paths, func(i, j int) bool { return strings.Count(paths[i], "/") < strings.Count(paths[j], "/") })
+ selected := map[string]struct{}{}
+ for _, fromPath := range paths {
+ selected[fromPath] = struct{}{}
+ }
- dirs := map[string]string{}
+ added := map[string]struct{}{}
for _, fromPath := range paths {
- dir := strings.TrimSuffix(fromPath, ".sy")
+ if _, ok := added[fromPath]; ok {
+ continue
+ }
existParent := false
- for d := range dirs {
- if strings.HasPrefix(fromPath, d) {
+ for parentDir := path.Dir(fromPath); "/" != parentDir && "." != parentDir; parentDir = path.Dir(parentDir) {
+ if _, ok := selected[parentDir+".sy"]; ok {
existParent = true
break
}
@@ -297,8 +301,8 @@ func FilterSelfChildDocs(paths []string) (ret []string) {
if existParent {
continue
}
- dirs[dir] = fromPath
ret = append(ret, fromPath)
+ added[fromPath] = struct{}{}
}
return
}
diff --git a/kernel/util/path_test.go b/kernel/util/path_test.go
index 40abe7597e..573ae44694 100644
--- a/kernel/util/path_test.go
+++ b/kernel/util/path_test.go
@@ -19,9 +19,37 @@ package util
import (
"os"
"path/filepath"
+ "reflect"
"testing"
)
+func TestFilterSelfChildDocsPreservesInputOrder(t *testing.T) {
+ paths := []string{
+ "/20260810000001-abcdefg/20260810000002-abcdefg.sy",
+ "/20260810000003-abcdefg.sy",
+ "/20260810000004-abcdefg/20260810000005-abcdefg.sy",
+ }
+ want := append([]string(nil), paths...)
+
+ if got := FilterSelfChildDocs(paths); !reflect.DeepEqual(got, want) {
+ t.Fatalf("unexpected filtered paths: got %v, want %v", got, want)
+ }
+ if !reflect.DeepEqual(paths, want) {
+ t.Fatalf("input paths changed: got %v, want %v", paths, want)
+ }
+}
+
+func TestFilterSelfChildDocsRemovesChildrenAndDuplicates(t *testing.T) {
+ parentPath := "/20260810000001-abcdefg.sy"
+ childPath := "/20260810000001-abcdefg/20260810000002-abcdefg.sy"
+ otherPath := "/20260810000003-abcdefg.sy"
+ paths := []string{childPath, otherPath, parentPath, otherPath}
+
+ if got, want := FilterSelfChildDocs(paths), []string{otherPath, parentPath}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("unexpected filtered paths: got %v, want %v", got, want)
+ }
+}
+
// TestGetTreeID 校验使用不同路径分隔符时均能提取相同的文档 ID。
func TestGetTreeID(t *testing.T) {
id := "20240101120000-1a2b3c4"