An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve custom document and notebook sorting https://github.com/siyuan-note/siyuan/issues/19069 https://github.com/siyuan-note/siyuan/issues/19070
Danield0da40138e47
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 5d76b9b61e..6187eaccc9 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -49,6 +49,7 @@ import {updateNotebookRootForBoxDoc} from "../../util/notebookRoot";import {collectExpandedDocIDs,findMovedFileTreeItem,+ getRelativeReorderRequest,getFileTreeChildList,IDocumentTabDragData,IFileTreeMove,@@ -856,6 +857,11 @@ export class Files extends Model {const targetListElement = newElement.parentElement;if (window.siyuan.config.fileTree.sort === 6 && selectRootElements.length > 0 &&newElement.getAttribute("data-path") === "/") {+ const sourceIDs = selectRootElements.map(item => item.parentElement.getAttribute("data-url"));+ if (sourceIDs.includes(toURL)) {+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");+ return;+ }if (newElement.classList.contains("dragover__top")) {selectRootElements.forEach(item => {newElement.parentElement.before(item.parentElement);@@ -865,13 +871,11 @@ export class Files extends Model {newElement.parentElement.after(item.parentElement);});}- const notebooks: string[] = [];- Array.from(this.element.children).forEach(item => {- notebooks.push(item.getAttribute("data-url"));- });- fetchPost("/api/notebook/changeSortNotebook", {- notebooks,- });+ fetchPost("/api/notebook/reorder", getRelativeReorderRequest(+ sourceIDs,+ toURL,+ !newElement.classList.contains("dragover__top")+ ));} else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {const toDir = pathPosix().dirname(toPath);const newElementClassList = newElement.getAttribute("class");@@ -943,10 +947,11 @@ export class Files extends Model {}});}- const sortResponse = await fetchSyncPost("/api/filetree/changeSort", {- paths: sortedPaths,- notebook: toURL- });+ const sortResponse = await fetchSyncPost("/api/filetree/reorderDocs", getRelativeReorderRequest(+ selectFileElements.map(item => item.getAttribute("data-node-id")),+ newElement.getAttribute("data-node-id"),+ !newElementClassList.includes("dragover__top")+ ));if (sortResponse.code !== 0) {newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");return;@@ -1050,10 +1055,11 @@ export class Files extends Model {if (moveResponse.code !== 0) {return;}- const sortResponse = await fetchSyncPost("/api/filetree/changeSort", {- paths: sortedPaths,- notebook: targetNotebook,- });+ const sortResponse = await fetchSyncPost("/api/filetree/reorderDocs", getRelativeReorderRequest(+ [documentTabData.rootId],+ targetElement.getAttribute("data-node-id"),+ insertAfter+ ));if (sortResponse.code !== 0) {return;}diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex c5ec5bf75c..c1539fdcee 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -710,16 +710,10 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, licon: "iconBefore",label: window.siyuan.languages.newDocAbove,click: () => {- const paths: string[] = [];- Array.from(liElement.parentElement.children).forEach((item) => {- if (item.tagName === "LI") {- if (item === liElement) {- paths.push(undefined);- }- paths.push(item.getAttribute("data-path"));- }+ newFileInTree(app, notebookId, pathPosix().dirname(pathString), {+ targetID: id,+ position: "before",});- newFileInTree(app, notebookId, pathPosix().dirname(pathString), paths);}}).element);window.siyuan.menus.menu.append(new MenuItem({@@ -727,16 +721,10 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, licon: "iconAfter",label: window.siyuan.languages.newDocBelow,click: () => {- const paths: string[] = [];- Array.from(liElement.parentElement.children).forEach((item) => {- if (item.tagName === "LI") {- paths.push(item.getAttribute("data-path"));- if (item === liElement) {- paths.push(undefined);- }- }+ newFileInTree(app, notebookId, pathPosix().dirname(pathString), {+ targetID: id,+ position: "after",});- newFileInTree(app, notebookId, pathPosix().dirname(pathString), paths);}}).element);window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex 9300b95eb2..b273ee3beb 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -38,6 +38,7 @@ import {bindMousePointerTouchBridge, isMousePointerTouchEvent} from "../util/mouimport {collectExpandedDocIDs,findMovedFileTreeItem,+ getRelativeReorderRequest,getFileTreeChildList,IFileTreeMove,restoreMovedExpandedDocItems,@@ -442,6 +443,12 @@ export class MobileFiles extends Model {const targetListElement = newElement.parentElement;if (window.siyuan.config.fileTree.sort === 6 && selectRootElements.length > 0 &&newElement.getAttribute("data-path") === "/") {+ const sourceIDs = selectRootElements.map(item => item.parentElement.getAttribute("data-url"));+ if (sourceIDs.includes(toURL)) {+ this.clearDragIndicators();+ this.touchDragState = null;+ return;+ }if (newElement.classList.contains("dragover__top")) {selectRootElements.forEach(item => {newElement.parentElement.before(item.parentElement);@@ -451,13 +458,11 @@ export class MobileFiles extends Model {newElement.parentElement.after(item.parentElement);});}- const notebooks: string[] = [];- Array.from(this.element.children).forEach(item => {- notebooks.push(item.getAttribute("data-url"));- });- fetchPost("/api/notebook/changeSortNotebook", {- notebooks,- });+ fetchPost("/api/notebook/reorder", getRelativeReorderRequest(+ sourceIDs,+ toURL,+ !newElement.classList.contains("dragover__top")+ ));} else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {let hasMove = false;const toDir = pathPosix().dirname(toPath);@@ -511,16 +516,11 @@ export class MobileFiles 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,- notebook: toURL- }, () => {+ fetchPost("/api/filetree/reorderDocs", getRelativeReorderRequest(+ selectFileElements.map(item => item.getAttribute("data-node-id")),+ newElement.getAttribute("data-node-id"),+ !newElement.classList.contains("dragover__top")+ ), () => {if (hasMove) {fetchPost("/api/filetree/listDocsByPath", {notebook: toURL,diff --git a/app/src/util/fileTreeMove.test.ts b/app/src/util/fileTreeMove.test.tsindex 3942013af6..588efd6fc4 100644--- a/app/src/util/fileTreeMove.test.ts+++ b/app/src/util/fileTreeMove.test.ts@@ -2,6 +2,7 @@ import {describe, it} from "node:test";import * as assert from "node:assert/strict";import {findMovedFileTreeItem,+ getRelativeReorderRequest,IFileTreeMove,insertDocumentSortPath,insertDocumentsSortPaths,@@ -11,6 +12,19 @@ import {updateMovedSubtree} from "./fileTreeMove";+describe("getRelativeReorderRequest", () => {+ it("keeps source order and encodes the relative position", () => {+ const sourceIDs = ["20260802120000-abcdefg", "20260802120001-abcdefg"];++ assert.deepEqual(getRelativeReorderRequest(sourceIDs, "20260802120002-abcdefg", false), {+ sourceIDs,+ targetID: "20260802120002-abcdefg",+ position: "before",+ });+ assert.equal(getRelativeReorderRequest(sourceIDs, "20260802120002-abcdefg", true).position, "after");+ });+});+describe("parseDocumentTabDragData", () => {it("parses a document tab payload", () => {assert.deepEqual(parseDocumentTabDragData(JSON.stringify({diff --git a/app/src/util/fileTreeMove.ts b/app/src/util/fileTreeMove.tsindex c5f4b43123..019fbdfcbd 100644--- a/app/src/util/fileTreeMove.ts+++ b/app/src/util/fileTreeMove.ts@@ -14,6 +14,12 @@ export interface IDocumentTabDragData {const BLOCK_ID_PATTERN = /^\d{14}-[0-9a-z]{7}$/;+export const getRelativeReorderRequest = (sourceIDs: string[], targetID: string, insertAfter: boolean) => ({+ sourceIDs,+ targetID,+ position: insertAfter ? "after" as const : "before" as const,+});+export const parseDocumentTabDragData = (data: string) => {try {const result = JSON.parse(data) as IDocumentTabDragData;diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.tsindex 3c140b8efe..cf0cf8af65 100644--- a/app/src/util/newFile.ts+++ b/app/src/util/newFile.ts@@ -46,7 +46,8 @@ type NewDocRequest = {/** 是否有来自编辑器或文件树选中项的焦点目标 */hasFocusTarget: boolean;name?: string;- paths?: string[];+ sortTargetID?: string;+ sortPosition?: "before" | "after";listDocTree?: boolean;onCreated?: (id: string, title: string) => void;};@@ -87,13 +88,17 @@ export const newFileInProtyle = (protyle: IProtyle, onCreated: (id: string, titl});};-export const newFileInTree = (app: App, notebookId: string, currentPath: string, paths?: string[]) => {+export const newFileInTree = (app: App, notebookId: string, currentPath: string, sortPlacement?: {+ targetID: string;+ position: "before" | "after";+}) => {runNewDocInTree({app,notebookId,currentPath,hasFocusTarget: true,- paths,+ sortTargetID: sortPlacement?.targetID,+ sortPosition: sortPlacement?.position,listDocTree: true,});};@@ -404,16 +409,14 @@ function createNewDocByHPath(request: NewDocRequest, target: NewDocTargetByHPathfunction createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc, docCreateTemplatePath: string) {const id = Lute.NewNodeID();const newPath = pathPosix().join(getDisplayName(target.parentPath, false, true), id + ".sy");- if (request.paths) {- request.paths[request.paths.indexOf(undefined)] = newPath;- }fetchPost("/api/filetree/createDoc", {notebook: target.targetNotebookId,path: newPath,title: target.title,md: "",docCreateTemplatePath,- sorts: request.paths,+ sortTargetID: request.sortTargetID,+ sortPosition: request.sortPosition,listDocTree: request.listDocTree,}, () => {openCreatedDoc(request.app, id, request.onCreated, target.title);diff --git a/docs/API.ja.md b/docs/API.ja.mdindex b5e28a65fc..be03eec61f 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -528,6 +528,66 @@}```+### 兄弟ドキュメントを基準にドキュメントの順序を変更++* `/api/filetree/reorderDocs`+* パラメータ++ ```json+ {+ "sourceIDs": ["20210917220056-yxtyl7i"],+ "targetID": "20210917220057-abcdefg",+ "position": "before"+ }+ ```++ * `sourceIDs`: 配列順に挿入する移動元ドキュメント ID+ * `targetID`: 基準となる兄弟ドキュメント ID+ * `position`: `before` または `after`+ * 移動後、すべての移動元ドキュメントは対象と同じノートブックおよび親ドキュメントに属する必要があります。非表示および未一覧表示のドキュメントを含む完全な兄弟リストを使用して並べ替えます+* 戻り値++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "changed": true,+ "notebook": "20210817205410-2kvfpfn",+ "parentPath": "/"+ }+ }+ ```++### 別のノートブックを基準にノートブックの順序を変更++* `/api/notebook/reorder`+* パラメータ++ ```json+ {+ "sourceIDs": ["20210817205410-2kvfpfn"],+ "targetID": "20210817205411-abcdefg",+ "position": "after"+ }+ ```++ * `sourceIDs`: 配列順に挿入する移動元ノートブック ID+ * `targetID`: 基準となるノートブック ID+ * `position`: `before` または `after`+ * 閉じたノートブックを含む完全なノートブックリストを使用して並べ替えます+* 戻り値++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "changed": true+ }+ }+ ```+### ノートブックとドキュメントのソート値を設定* `/api/filetree/setSort`diff --git a/docs/API.md b/docs/API.mdindex ec3b22b3f8..86af107ac6 100644--- a/docs/API.md+++ b/docs/API.md@@ -529,6 +529,66 @@ Move documents by `id`:}```+### Reorder documents relative to a sibling++* `/api/filetree/reorderDocs`+* Parameters++ ```json+ {+ "sourceIDs": ["20210917220056-yxtyl7i"],+ "targetID": "20210917220057-abcdefg",+ "position": "before"+ }+ ```++ * `sourceIDs`: Source document IDs inserted in array order+ * `targetID`: Target sibling document ID+ * `position`: `before` or `after`+ * After moving, every source document must have the same notebook and parent as the target; sorting uses the complete sibling list, including hidden and unlisted documents+* Return value++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "changed": true,+ "notebook": "20210817205410-2kvfpfn",+ "parentPath": "/"+ }+ }+ ```++### Reorder notebooks relative to another notebook++* `/api/notebook/reorder`+* Parameters++ ```json+ {+ "sourceIDs": ["20210817205410-2kvfpfn"],+ "targetID": "20210817205411-abcdefg",+ "position": "after"+ }+ ```++ * `sourceIDs`: Source notebook IDs inserted in array order+ * `targetID`: Target notebook ID+ * `position`: `before` or `after`+ * Sorting uses the complete notebook list, including closed notebooks+* Return value++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "changed": true+ }+ }+ ```+### Set notebook and document sort values* `/api/filetree/setSort`diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 3edcbefd49..8b252852ee 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -528,6 +528,66 @@}```+### 相对调整文档顺序++* `/api/filetree/reorderDocs`+* 参数++ ```json+ {+ "sourceIDs": ["20210917220056-yxtyl7i"],+ "targetID": "20210917220057-abcdefg",+ "position": "before"+ }+ ```++ * `sourceIDs`:按数组顺序插入的源文档 ID+ * `targetID`:目标兄弟文档 ID+ * `position`:`before` 或 `after`+ * 源文档必须在移动后与目标文档属于同一笔记本和父文档;排序基于包含隐藏文档和未列出文档的完整子文档列表+* 返回值++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "changed": true,+ "notebook": "20210817205410-2kvfpfn",+ "parentPath": "/"+ }+ }+ ```++### 相对调整笔记本顺序++* `/api/notebook/reorder`+* 参数++ ```json+ {+ "sourceIDs": ["20210817205410-2kvfpfn"],+ "targetID": "20210817205411-abcdefg",+ "position": "after"+ }+ ```++ * `sourceIDs`:按数组顺序插入的源笔记本 ID+ * `targetID`:目标笔记本 ID+ * `position`:`before` 或 `after`+ * 排序基于包含已关闭笔记本的完整列表+* 返回值++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "changed": true+ }+ }+ ```+### 设置笔记本和文档排序值* `/api/filetree/setSort`diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 9ca03eaef9..f5ecd17517 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -1143,6 +1143,66 @@ func changeSort(c *gin.Context) {model.ChangeFileTreeSort(notebook, paths)}+func reorderDocs(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ request := &struct {+ SourceIDs []string `json:"sourceIDs"`+ TargetID string `json:"targetID"`+ Position string `json:"position"`+ }{}+ if err := c.ShouldBindJSON(request); nil != err {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Parses request [%s] failed: %s", c.Request.URL.Path, err)+ return+ }+ if !validateReorderRequest(request.SourceIDs, request.TargetID, request.Position, ret) {+ return+ }++ result, err := model.ReorderDocs(request.SourceIDs, request.TargetID, request.Position)+ ret.Data = result+ if nil != err {+ ret.Code = -1+ ret.Msg = err.Error()+ }+}++func validateReorderRequest(sourceIDs []string, targetID, position string, ret *gulu.Result) bool {+ if 1 > len(sourceIDs) {+ ret.Code = -1+ ret.Msg = "Field [sourceIDs] must not be empty"+ return false+ }+ if util.InvalidIDPattern(targetID, ret) {+ return false+ }+ if "before" != position && "after" != position {+ ret.Code = -1+ ret.Msg = "Field [position] must be [before] or [after]"+ return false+ }+ ids := map[string]struct{}{}+ for i, sourceID := range sourceIDs {+ if util.InvalidIDPattern(sourceID, ret) {+ return false+ }+ if sourceID == targetID {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [targetID] must not be included in [sourceIDs] at index [%d]", i)+ return false+ }+ if _, exists := ids[sourceID]; exists {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [sourceIDs] contains duplicate ID [%s]", sourceID)+ return false+ }+ ids[sourceID] = struct{}{}+ }+ return true+}+type sortRequestItem struct {ID string `json:"id"`Sort *int `json:"sort"`diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.goindex 199b5cb774..407fc66459 100644--- a/kernel/api/filetree_test.go+++ b/kernel/api/filetree_test.go@@ -74,6 +74,42 @@ func TestSetSortRejectsInvalidRequest(t *testing.T) {}}+func TestReorderDocsRejectsInvalidRequest(t *testing.T) {+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.POST("/api/filetree/reorderDocs", reorderDocs)++ tests := []struct {+ name string+ body string+ }{+ {name: "empty", body: `{}`},+ {name: "invalid source ID", body: `{"sourceIDs":["invalid"],"targetID":"20260718000002-abcdefg","position":"before"}`},+ {name: "invalid target ID", body: `{"sourceIDs":["20260718000001-abcdefg"],"targetID":"invalid","position":"before"}`},+ {name: "invalid position", body: `{"sourceIDs":["20260718000001-abcdefg"],"targetID":"20260718000002-abcdefg","position":"middle"}`},+ {name: "target in sources", body: `{"sourceIDs":["20260718000002-abcdefg"],"targetID":"20260718000002-abcdefg","position":"after"}`},+ {name: "duplicate source", body: `{"sourceIDs":["20260718000001-abcdefg","20260718000001-abcdefg"],"targetID":"20260718000002-abcdefg","position":"after"}`},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/filetree/reorderDocs", strings.NewReader(test.body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ response := &struct {+ Code int `json:"code"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); nil != err {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ if -1 != response.Code {+ t.Fatalf("invalid request returned code %d: %s", response.Code, recorder.Body.String())+ }+ })+ }+}+func TestSetDocSortModeRejectsInvalidRequest(t *testing.T) {gin.SetMode(gin.TestMode)engine := gin.New()diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 45c0ed8199..766720298a 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -17,6 +17,7 @@package apiimport (+ "fmt""io""net/http""sort"@@ -118,6 +119,32 @@ func changeSortNotebook(c *gin.Context) {model.ChangeBoxSort(ids)}+func reorderNotebooks(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ request := &struct {+ SourceIDs []string `json:"sourceIDs"`+ TargetID string `json:"targetID"`+ Position string `json:"position"`+ }{}+ if err := c.ShouldBindJSON(request); nil != err {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Parses request [%s] failed: %s", c.Request.URL.Path, err)+ return+ }+ if !validateReorderRequest(request.SourceIDs, request.TargetID, request.Position, ret) {+ return+ }++ result, err := model.ReorderNotebooks(request.SourceIDs, request.TargetID, request.Position)+ ret.Data = result+ if nil != err {+ ret.Code = -1+ ret.Msg = err.Error()+ }+}+func renameNotebook(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/router.go b/kernel/api/router.goindex 771f22b008..98fe7dee6f 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -143,6 +143,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/notebook/removeNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeNotebook)ginServer.Handle("POST", "/api/notebook/renameNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, renameNotebook)ginServer.Handle("POST", "/api/notebook/changeSortNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, changeSortNotebook)+ ginServer.Handle("POST", "/api/notebook/reorder", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, reorderNotebooks)ginServer.Handle("POST", "/api/notebook/setNotebookIcon", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setNotebookIcon)ginServer.Handle("POST", "/api/notebook/getNotebookInfo", model.CheckAuth, getNotebookInfo)ginServer.Handle("POST", "/api/notebook/enableEncryptedNotebooks", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, enableEncryptedNotebooks)@@ -165,6 +166,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/filetree/getRefCreateSavePath", model.CheckAuth, getRefCreateSavePath)ginServer.Handle("POST", "/api/filetree/getShorthandSavePath", model.CheckAuth, getShorthandSavePath)ginServer.Handle("POST", "/api/filetree/changeSort", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, changeSort)+ ginServer.Handle("POST", "/api/filetree/reorderDocs", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, reorderDocs)ginServer.Handle("POST", "/api/filetree/setSort", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setSort)ginServer.Handle("POST", "/api/filetree/setDocSortMode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setDocSortMode)ginServer.Handle("POST", "/api/filetree/createDocWithMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDocWithMd)diff --git a/kernel/model/box.go b/kernel/model/box.goindex 2ae1566a54..c3e12f29ba 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -244,7 +244,12 @@ func ListNotebooks() (ret []*Box, err error) {return util.NaturalCompare(ret[j].Name, ret[i].Name)})case util.SortModeCustom:- sort.Slice(ret, func(i, j int) bool { return ret[i].Sort < ret[j].Sort })+ sort.Slice(ret, func(i, j int) bool {+ if ret[i].Sort != ret[j].Sort {+ return ret[i].Sort < ret[j].Sort+ }+ return ret[i].ID > ret[j].ID+ })case util.SortModeCreatedASC:sort.Slice(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID })case util.SortModeCreatedDESC:@@ -961,23 +966,134 @@ func fullReindex() {}func ChangeBoxSort(boxIDs []string) {+ if 1 > len(boxIDs) {+ return+ }+fileTreeSortLock.Lock()- defer fileTreeSortLock.Unlock()+ boxes, currentIDs := loadNotebookCustomOrder()+ orderedIDs := mergeRequestedIDOrder(currentIDs, boxIDs)+ if equalStringSlices(currentIDs, orderedIDs) {+ fileTreeSortLock.Unlock()+ return+ }+ if err := saveNotebookCustomOrder(boxes, orderedIDs); nil != err {+ fileTreeSortLock.Unlock()+ logging.LogErrorf("change notebook sort failed: %s", err)+ return+ }+ fileTreeSortLock.Unlock()+ IncSync()+ pushNotebookSortChanged()+}- for i, boxID := range boxIDs {- box := &Box{ID: boxID}- boxConf := box.GetConf()- boxConf.Sort = i + 1- box.SaveConf(boxConf)+// ReorderNotebooks 将笔记本移动到目标笔记本之前或之后。+func ReorderNotebooks(sourceIDs []string, targetID, position string) (ret *ReorderResult, err error) {+ ret = &ReorderResult{}+ if err = validateReorderArgs(sourceIDs, targetID, position); nil != err {+ return}++ fileTreeSortLock.Lock()+ boxes, currentIDs := loadNotebookCustomOrder()+ orderedIDs, changed, reorderErr := reorderIDSequence(currentIDs, sourceIDs, targetID, position)+ if nil != reorderErr || !changed {+ fileTreeSortLock.Unlock()+ return ret, reorderErr+ }+ if err = saveNotebookCustomOrder(boxes, orderedIDs); nil != err {+ fileTreeSortLock.Unlock()+ return ret, err+ }+ fileTreeSortLock.Unlock()++ ret.Changed = true+ IncSync()pushNotebookSortChanged()+ return}-func pushNotebookSortChanged() {- var notebookIDs []string- for _, box := range Conf.GetOpenedBoxes() {- notebookIDs = append(notebookIDs, box.ID)+func loadNotebookCustomOrder() (boxes map[string]*Box, ids []string) {+ allBoxes, err := ListNotebooks()+ if nil != err {+ return map[string]*Box{}, nil+ }+ sort.Slice(allBoxes, func(i, j int) bool {+ if allBoxes[i].Sort != allBoxes[j].Sort {+ return allBoxes[i].Sort < allBoxes[j].Sort+ }+ return allBoxes[i].ID > allBoxes[j].ID+ })+ boxes = make(map[string]*Box, len(allBoxes))+ for _, box := range allBoxes {+ boxes[box.ID] = box+ ids = append(ids, box.ID)+ }+ return+}++func mergeRequestedIDOrder(currentIDs, requestedIDs []string) (ret []string) {+ currentSet := make(map[string]struct{}, len(currentIDs))+ for _, id := range currentIDs {+ currentSet[id] = struct{}{}+ }+ requestedSet := map[string]struct{}{}+ var validRequestedIDs []string+ for _, id := range requestedIDs {+ if _, exists := currentSet[id]; !exists {+ continue+ }+ if _, exists := requestedSet[id]; exists {+ continue+ }+ validRequestedIDs = append(validRequestedIDs, id)+ requestedSet[id] = struct{}{}+ }+ requestedIndex := 0+ for _, id := range currentIDs {+ if _, requested := requestedSet[id]; requested {+ ret = append(ret, validRequestedIDs[requestedIndex])+ requestedIndex+++ } else {+ ret = append(ret, id)+ }}+ return+}++func saveNotebookCustomOrder(boxes map[string]*Box, orderedIDs []string) error {+ oldSorts := map[string]int{}+ writtenIDs := []string{}+ for i, id := range orderedIDs {+ box := boxes[id]+ if nil == box {+ return fmt.Errorf("notebook [%s] not found", id)+ }+ boxConf := box.GetConf()+ oldSorts[id] = boxConf.Sort+ newSort := i + 1+ if boxConf.Sort == newSort {+ continue+ }+ boxConf.Sort = newSort+ if err := box.SaveConf(boxConf); nil != err {+ for _, writtenID := range writtenIDs {+ writtenBox := boxes[writtenID]+ writtenConf := writtenBox.GetConf()+ writtenConf.Sort = oldSorts[writtenID]+ if rollbackErr := writtenBox.SaveConf(writtenConf); nil != rollbackErr {+ logging.LogErrorf("rollback notebook [%s] sort failed: %s", writtenID, rollbackErr)+ }+ }+ return err+ }+ writtenIDs = append(writtenIDs, id)+ }+ return nil+}++func pushNotebookSortChanged() {+ _, notebookIDs := loadNotebookCustomOrder()util.BroadcastByType("main", "notebookSortChanged", 0, "", map[string]any{"notebookIDs": notebookIDs,})diff --git a/kernel/model/file.go b/kernel/model/file.goindex 26cf2651cf..937851c1e3 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -21,7 +21,6 @@ import ("fmt""io/fs""maps"- "math""os""path""path/filepath"@@ -662,7 +661,11 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boobox.fillSort(&fileTreeFiles)sort.Slice(fileTreeFiles, func(i, j int) bool {if fileTreeFiles[i].Sort == fileTreeFiles[j].Sort {- return util.TimeFromID(fileTreeFiles[i].ID) > util.TimeFromID(fileTreeFiles[j].ID)+ leftTime, rightTime := util.TimeFromID(fileTreeFiles[i].ID), util.TimeFromID(fileTreeFiles[j].ID)+ if leftTime != rightTime {+ return leftTime > rightTime+ }+ return fileTreeFiles[i].ID > fileTreeFiles[j].ID}return fileTreeFiles[i].Sort < fileTreeFiles[j].Sort})@@ -1367,6 +1370,19 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string, arg map[string]anif nil != err {return}+ sortTargetID, _ := arg["sortTargetID"].(string)+ sortPosition, _ := arg["sortPosition"].(string)+ if "" != sortTargetID {+ if "before" != sortPosition && "after" != sortPosition {+ return nil, fmt.Errorf("invalid sort position [%s]", sortPosition)+ }+ target := treenode.GetBlockTree(sortTargetID)+ if !isSortableDocument(target) || target.BoxID != boxID || path.Dir(target.Path) != path.Dir(p) {+ return nil, fmt.Errorf("sort target document [%s] is not a sibling of the new document", sortTargetID)+ }+ } else if "" != sortPosition {+ return nil, errors.New("sort target ID is required when sort position is specified")+ }luteEngine := util.NewLute()luteEngine.SetHTMLTag2TextMark(true)@@ -1377,7 +1393,12 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string, arg map[string]an}FlushTxQueue()- if 0 < len(sorts) {+ if "" != sortTargetID {+ if _, sortErr := ReorderDocs([]string{tree.ID}, sortTargetID, sortPosition); nil != sortErr {+ logging.LogErrorf("reorder created document [%s] failed: %s", tree.ID, sortErr)+ box.setSortByConf(path.Dir(tree.Path), tree.ID)+ }+ } else if 0 < len(sorts) {ChangeFileTreeSort(box.ID, sorts)} else {box.setSortByConf(path.Dir(tree.Path), tree.ID)@@ -2625,14 +2646,14 @@ func moveSorts(rootID, fromBox, toBox string) {bt := treenode.GetBlockTree(rootID)if nil != bt {parentPath := path.Dir(bt.Path)- docs, _, listErr := ListDocTree(toBox, parentPath, util.SortModeCustom, false, false, math.MaxInt)- if listErr != nil {- logging.LogErrorf("list doc tree failed: %s", listErr)+ childIDs, loadErr := loadSiblingCustomOrder(toBox, parentPath, toFullSortIDs)+ if loadErr != nil {+ logging.LogErrorf("load sibling custom order failed: %s", loadErr)return}- for _, doc := range docs {- sortIDs[doc.ID] = doc.Sort+ for _, id := range childIDs {+ sortIDs[id] = toFullSortIDs[id]}pushFiletreeSortChanged(sortIDs)@@ -2647,63 +2668,240 @@ func ChangeFileTreeSort(boxID string, paths []string) {FlushTxQueue()fileTreeSortLock.Lock()- defer fileTreeSortLock.Unlock()box := Conf.Box(boxID)- sortIDs := map[string]int{}- max := 0- for i, p := range paths {- id := util.GetTreeID(p)- sortIDs[id] = i + 1- if i == len(paths)-1 {- max = i + 2- }+ if nil == box {+ fileTreeSortLock.Unlock()+ return}p := paths[0]parentPath := path.Dir(p)- absParentPath := filepath.Join(util.DataDir, boxID, parentPath)- files, err := os.ReadDir(absParentPath)- if err != nil {- logging.LogErrorf("read dir [%s] failed: %s", absParentPath, err)- }-- sortFolderIDs := map[string]int{}- for _, f := range files {- if !strings.HasSuffix(f.Name(), ".sy") {- continue- }-- id := strings.TrimSuffix(f.Name(), ".sy")- val := sortIDs[id]- if 0 == val {- val = max- max++- }- sortFolderIDs[id] = val- }-confDir := filepath.Join(util.DataDir, box.ID, ".siyuan")- if err = os.MkdirAll(confDir, 0755); err != nil {+ if err := os.MkdirAll(confDir, 0755); err != nil {+ fileTreeSortLock.Unlock()logging.LogErrorf("create conf dir failed: %s", err)return}confPath := filepath.Join(confDir, "sort.json")fullSortIDs, err := readSortConfMap(confPath)if err != nil {+ fileTreeSortLock.Unlock()+ return+ }+ currentIDs, err := loadSiblingCustomOrder(boxID, parentPath, fullSortIDs)+ if err != nil {+ fileTreeSortLock.Unlock()+ logging.LogErrorf("load sibling custom order failed: %s", err)+ return+ }+ orderedIDs := mergeRequestedSortOrder(currentIDs, paths)+ if 1 > len(orderedIDs) || equalStringSlices(currentIDs, orderedIDs) {+ fileTreeSortLock.Unlock()return}+ sortFolderIDs := map[string]int{}+ for i, id := range orderedIDs {+ sortFolderIDs[id] = i + 1+ }maps.Copy(fullSortIDs, sortFolderIDs)-if err = writeSortConfMap(confPath, fullSortIDs); err != nil {+ fileTreeSortLock.Unlock()return}+ fileTreeSortLock.Unlock()IncSync()pushFiletreeSortChanged(sortFolderIDs)}+// ReorderResult 描述相对排序操作的结果。+type ReorderResult struct {+ Changed bool `json:"changed"`+ Notebook string `json:"notebook,omitempty"`+ ParentPath string `json:"parentPath,omitempty"`+}++// ReorderDocs 将同级文档移动到目标文档之前或之后。+func ReorderDocs(sourceIDs []string, targetID, position string) (ret *ReorderResult, err error) {+ ret = &ReorderResult{}+ if err = validateReorderArgs(sourceIDs, targetID, position); nil != err {+ return+ }++ FlushTxQueue()+ target := treenode.GetBlockTree(targetID)+ if !isSortableDocument(target) {+ return ret, fmt.Errorf("target document [%s] not found", targetID)+ }+ box := Conf.Box(target.BoxID)+ if nil == box {+ return ret, fmt.Errorf("target document [%s] is not in an opened and unlocked notebook", targetID)+ }+ parentPath := path.Dir(target.Path)+ for _, sourceID := range sourceIDs {+ source := treenode.GetBlockTree(sourceID)+ if !isSortableDocument(source) {+ return ret, fmt.Errorf("source document [%s] not found", sourceID)+ }+ if source.BoxID != target.BoxID || path.Dir(source.Path) != parentPath {+ return ret, fmt.Errorf("source document [%s] is not a sibling of target document [%s]", sourceID, targetID)+ }+ }++ fileTreeSortLock.Lock()+ confPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")+ fullSortIDs, readErr := readSortConfMap(confPath)+ if nil != readErr {+ fileTreeSortLock.Unlock()+ return ret, readErr+ }+ currentIDs, loadErr := loadSiblingCustomOrder(box.ID, parentPath, fullSortIDs)+ if nil != loadErr {+ fileTreeSortLock.Unlock()+ return ret, loadErr+ }+ orderedIDs, changed, reorderErr := reorderIDSequence(currentIDs, sourceIDs, targetID, position)+ if nil != reorderErr || !changed {+ fileTreeSortLock.Unlock()+ return ret, reorderErr+ }+ sortIDs := map[string]int{}+ for i, id := range orderedIDs {+ sortIDs[id] = i + 1+ }+ maps.Copy(fullSortIDs, sortIDs)+ if writeErr := writeSortConfMap(confPath, fullSortIDs); nil != writeErr {+ fileTreeSortLock.Unlock()+ return ret, writeErr+ }+ fileTreeSortLock.Unlock()++ ret.Changed = true+ ret.Notebook = box.ID+ ret.ParentPath = parentPath+ IncSync()+ pushFiletreeSortChanged(sortIDs)+ return+}++func validateReorderArgs(sourceIDs []string, targetID, position string) error {+ if 1 > len(sourceIDs) {+ return errors.New("source IDs must not be empty")+ }+ if "before" != position && "after" != position {+ return fmt.Errorf("invalid reorder position [%s]", position)+ }+ seen := map[string]struct{}{}+ for _, sourceID := range sourceIDs {+ if sourceID == targetID {+ return fmt.Errorf("target ID [%s] must not be included in source IDs", targetID)+ }+ if _, ok := seen[sourceID]; ok {+ return fmt.Errorf("duplicate source ID [%s]", sourceID)+ }+ seen[sourceID] = struct{}{}+ }+ return nil+}++func isSortableDocument(tree *treenode.BlockTree) bool {+ return nil != tree && tree.ID == tree.RootID && "d" == tree.Type && !IsBoxDoc(tree.BoxID, tree.RootID)+}++func loadSiblingCustomOrder(boxID, parentPath string, fullSortIDs map[string]int) (ret []string, err error) {+ absParentPath := filepath.Join(util.DataDir, boxID, parentPath)+ files, err := os.ReadDir(absParentPath)+ if nil != err {+ return nil, fmt.Errorf("read dir [%s] failed: %w", absParentPath, err)+ }+ for _, file := range files {+ if file.IsDir() || !strings.HasSuffix(file.Name(), ".sy") {+ continue+ }+ id := strings.TrimSuffix(file.Name(), ".sy")+ if !ast.IsNodeIDPattern(id) || ("/" == parentPath && id == boxID) {+ continue+ }+ ret = append(ret, id)+ }+ sort.Slice(ret, func(i, j int) bool {+ leftSort, rightSort := fullSortIDs[ret[i]], fullSortIDs[ret[j]]+ if leftSort != rightSort {+ return leftSort < rightSort+ }+ leftTime, rightTime := util.TimeFromID(ret[i]), util.TimeFromID(ret[j])+ if leftTime != rightTime {+ return leftTime > rightTime+ }+ return ret[i] > ret[j]+ })+ return+}++func mergeRequestedSortOrder(currentIDs, requestedPaths []string) (ret []string) {+ requestedIDs := make([]string, 0, len(requestedPaths))+ for _, requestedPath := range requestedPaths {+ requestedIDs = append(requestedIDs, util.GetTreeID(requestedPath))+ }+ return mergeRequestedIDOrder(currentIDs, requestedIDs)+}++func reorderIDSequence(currentIDs, sourceIDs []string, targetID, position string) (ret []string, changed bool, err error) {+ if err = validateReorderArgs(sourceIDs, targetID, position); nil != err {+ return+ }+ currentSet := make(map[string]struct{}, len(currentIDs))+ for _, id := range currentIDs {+ currentSet[id] = struct{}{}+ }+ if _, exists := currentSet[targetID]; !exists {+ return nil, false, fmt.Errorf("target ID [%s] is not in the current order", targetID)+ }+ sourceSet := make(map[string]struct{}, len(sourceIDs))+ for _, sourceID := range sourceIDs {+ if _, exists := currentSet[sourceID]; !exists {+ return nil, false, fmt.Errorf("source ID [%s] is not in the current order", sourceID)+ }+ sourceSet[sourceID] = struct{}{}+ }+ remaining := make([]string, 0, len(currentIDs)-len(sourceIDs))+ for _, id := range currentIDs {+ if _, source := sourceSet[id]; !source {+ remaining = append(remaining, id)+ }+ }+ targetIndex := -1+ for i, id := range remaining {+ if id == targetID {+ targetIndex = i+ break+ }+ }+ if "after" == position {+ targetIndex+++ }+ ret = make([]string, 0, len(currentIDs))+ ret = append(ret, remaining[:targetIndex]...)+ ret = append(ret, sourceIDs...)+ ret = append(ret, remaining[targetIndex:]...)+ changed = !equalStringSlices(currentIDs, ret)+ return+}++func equalStringSlices(left, right []string) bool {+ if len(left) != len(right) {+ return false+ }+ for i := range left {+ if left[i] != right[i] {+ return false+ }+ }+ return true+}+var fileTreeSortLock sync.Mutextype SortItem struct {@@ -2919,111 +3117,84 @@ func (box *Box) setSortByConf(parentPath, id string) {}func (box *Box) addMaxSort(parentPath, id string) {- docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeCustom, false, false, math.MaxInt)- if err != nil {- logging.LogErrorf("list doc tree failed: %s", err)- return- }-- sortVal := 0- if 0 < len(docs) {- sortVal = docs[len(docs)-1].Sort + 1+ if err := box.placeDocInSiblingOrder(parentPath, id, "", "after"); nil != err {+ logging.LogErrorf("append document sort failed: %s", err)}-- box.setSortVal(id, sortVal)-- sortIDs := map[string]int{}- for _, doc := range docs {- sortIDs[doc.ID] = doc.Sort- }- sortIDs[id] = sortVal- pushFiletreeSortChanged(sortIDs)}func (box *Box) addMinSort(parentPath, id string) {- docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeCustom, false, false, 1)- if err != nil {- logging.LogErrorf("list doc tree failed: %s", err)- return- }-- sortVal := 0- if 0 < len(docs) {- sortVal = docs[0].Sort - 1- }-- box.setSortVal(id, sortVal)-- sortIDs := map[string]int{}- for _, doc := range docs {- sortIDs[doc.ID] = doc.Sort+ if err := box.placeDocInSiblingOrder(parentPath, id, "", "before"); nil != err {+ logging.LogErrorf("prepend document sort failed: %s", err)}- sortIDs[id] = sortVal- pushFiletreeSortChanged(sortIDs)}-func (box *Box) setSortVal(id string, sortVal int) {+func (box *Box) placeDocInSiblingOrder(parentPath, id, targetID, position string) error {fileTreeSortLock.Lock()- defer fileTreeSortLock.Unlock()-- var err errorconfDir := filepath.Join(util.DataDir, box.ID, ".siyuan")- if err = os.MkdirAll(confDir, 0755); err != nil {- logging.LogErrorf("create conf dir failed: %s", err)- return+ if err := os.MkdirAll(confDir, 0755); nil != err {+ fileTreeSortLock.Unlock()+ return fmt.Errorf("create conf dir failed: %w", err)}confPath := filepath.Join(confDir, "sort.json")fullSortIDs, err := readSortConfMap(confPath)- if err != nil {- return- }-- fullSortIDs[id] = sortVal- if err = writeSortConfMap(confPath, fullSortIDs); err != nil {- return+ if nil != err {+ fileTreeSortLock.Unlock()+ return err}-}--func (box *Box) addSort(previousPath, id string) {- fileTreeSortLock.Lock()- defer fileTreeSortLock.Unlock()-- confDir := filepath.Join(util.DataDir, box.ID, ".siyuan")- if err := os.MkdirAll(confDir, 0755); err != nil {- logging.LogErrorf("create conf dir failed: %s", err)- return+ currentIDs, err := loadSiblingCustomOrder(box.ID, parentPath, fullSortIDs)+ if nil != err {+ fileTreeSortLock.Unlock()+ return err}- confPath := filepath.Join(confDir, "sort.json")- fullSortIDs, err := readSortConfMap(confPath)- if err != nil {- return+ orderedIDs := make([]string, 0, len(currentIDs)+1)+ for _, currentID := range currentIDs {+ if currentID != id {+ orderedIDs = append(orderedIDs, currentID)+ }}-- parentPath := path.Dir(previousPath)- docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeCustom, false, false, math.MaxInt)- if err != nil {- logging.LogErrorf("list doc tree failed: %s", err)- return+ insertIndex := 0+ if "after" == position {+ insertIndex = len(orderedIDs)}-- sortIDs := map[string]int{}- previousID := util.GetTreeID(previousPath)- sortVal := 0- for _, doc := range docs {- fullSortIDs[doc.ID] = sortVal- if doc.ID == previousID {- sortVal++- fullSortIDs[id] = sortVal+ if "" != targetID {+ insertIndex = -1+ for i, currentID := range orderedIDs {+ if currentID == targetID {+ insertIndex = i+ if "after" == position {+ insertIndex+++ }+ break+ }+ }+ if 0 > insertIndex {+ fileTreeSortLock.Unlock()+ return fmt.Errorf("sort target document [%s] not found", targetID)}- sortVal++- sortIDs[doc.ID] = sortVal}-- if err = writeSortConfMap(confPath, fullSortIDs); err != nil {- return+ orderedIDs = append(orderedIDs, "")+ copy(orderedIDs[insertIndex+1:], orderedIDs[insertIndex:])+ orderedIDs[insertIndex] = id+ sortIDs := make(map[string]int, len(orderedIDs))+ for i, orderedID := range orderedIDs {+ sortIDs[orderedID] = i + 1}-+ maps.Copy(fullSortIDs, sortIDs)+ if err = writeSortConfMap(confPath, fullSortIDs); nil != err {+ fileTreeSortLock.Unlock()+ return err+ }+ fileTreeSortLock.Unlock()pushFiletreeSortChanged(sortIDs)+ return nil+}++func (box *Box) addSort(previousPath, id string) {+ parentPath := path.Dir(previousPath)+ previousID := util.GetTreeID(previousPath)+ if err := box.placeDocInSiblingOrder(parentPath, id, previousID, "after"); nil != err {+ logging.LogErrorf("insert document sort failed: %s", err)+ }}func (box *Box) setSort(sortIDVals map[string]int) {@@ -3054,24 +3225,45 @@ func pushFiletreeSortChanged(sortIDs map[string]int) {return}- var childIDs []string- for sortID := range sortIDs {- childIDs = append(childIDs, sortID)+ type siblingGroup struct {+ boxID string+ parentPath string+ changed map[string]int}- sort.Slice(childIDs, func(i, j int) bool {- return sortIDs[childIDs[i]] < sortIDs[childIDs[j]]- })-- firstID := childIDs[0]- bt := treenode.GetBlockTree(firstID)- if nil == bt {- return+ groups := map[string]*siblingGroup{}+ for id, sortValue := range sortIDs {+ bt := treenode.GetBlockTree(id)+ if !isSortableDocument(bt) {+ continue+ }+ parentPath := path.Dir(bt.Path)+ key := bt.BoxID + "\x00" + parentPath+ group := groups[key]+ if nil == group {+ group = &siblingGroup{boxID: bt.BoxID, parentPath: parentPath, changed: map[string]int{}}+ groups[key] = group+ }+ group.changed[id] = sortValue+ }+ for _, group := range groups {+ confPath := filepath.Join(util.DataDir, group.boxID, ".siyuan", "sort.json")+ fullSortIDs, err := readSortConfMap(confPath)+ var childIDs []string+ if nil == err {+ childIDs, err = loadSiblingCustomOrder(group.boxID, group.parentPath, fullSortIDs)+ }+ if nil != err {+ for id := range group.changed {+ childIDs = append(childIDs, id)+ }+ sort.Slice(childIDs, func(i, j int) bool {+ return group.changed[childIDs[i]] < group.changed[childIDs[j]]+ })+ }+ util.BroadcastByType("main", "filetreeSortChanged", 0, "", map[string]any{+ "notebook": group.boxID,+ "parentPath": group.parentPath,+ "childIDs": childIDs,+ })}-- parentPath := path.Dir(bt.Path)- util.BroadcastByType("main", "filetreeSortChanged", 0, "", map[string]any{- "notebook": bt.BoxID,- "parentPath": parentPath,- "childIDs": childIDs,- })}diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex 6af1974abf..361ec9b72e 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -38,6 +38,7 @@ type fileOperationTestFixture struct {sourcePath stringtargetPath stringsourceID string+ targetID stringchildID string}@@ -106,10 +107,29 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {sourcePath: sourcePath,targetPath: targetPath,sourceID: sourceTree.ID,+ targetID: targetTree.ID,childID: sourceTree.Root.FirstChild.ID,}}+func addFileOperationTestDoc(t *testing.T, fixture *fileOperationTestFixture, id, title string, hidden bool) *parse.Tree {+ t.Helper()+ docPath := "/" + id + ".sy"+ tree := treenode.NewTree(fixture.box.ID, docPath, "/"+title, title)+ if hidden {+ tree.Root.SetIALAttr(DocHiddenAttr, "true")+ }+ if _, err := filesys.WriteTree(tree); nil != err {+ t.Fatalf("write test document failed: %v", err)+ }+ treenode.UpsertBlockTree(tree)+ t.Cleanup(func() {+ cache.RemoveTreeData(tree.ID)+ cache.RemoveDocIAL(tree.Path)+ })+ return tree+}+func TestListDocTreeUsesPathIDForInvalidPropertiesID(t *testing.T) {fixture := setupFileOperationTest(t)ial := filesys.DocIAL(filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath))@@ -247,6 +267,7 @@ func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {extraID := "20260718000003-abcdefg"extraPath := "/" + extraID + ".sy"extraTree := treenode.NewTree(fixture.box.ID, extraPath, "/Extra", "Extra")+ extraTree.Root.SetIALAttr(DocHiddenAttr, "true")if _, err := filesys.WriteTree(extraTree); nil != err {t.Fatalf("write extra document failed: %v", err)}@@ -266,33 +287,177 @@ func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {}maxID := "20260718000004-abcdefg"+ addFileOperationTestDoc(t, fixture, maxID, "Max", false)fixture.box.addMaxSort("/", maxID)sorts, err := readSortConfMap(confPath)if nil != err {t.Fatalf("read custom sort after append failed: %v", err)}- if 31 != sorts[maxID] {- t.Fatalf("append used effective display mode instead of custom order: got %d, want 31", sorts[maxID])+ if 4 != sorts[maxID] {+ t.Fatalf("append used effective display mode instead of complete custom order: got %d, want 4", sorts[maxID])}minID := "20260718000005-abcdefg"+ addFileOperationTestDoc(t, fixture, minID, "Min", false)fixture.box.addMinSort("/", minID)sorts, err = readSortConfMap(confPath)if nil != err {t.Fatalf("read custom sort after prepend failed: %v", err)}- if 9 != sorts[minID] {- t.Fatalf("prepend used effective display mode instead of custom order: got %d, want 9", sorts[minID])+ if 1 != sorts[minID] || 5 != sorts[maxID] {+ t.Fatalf("prepend did not preserve the complete custom order: prepend=%d, trailing=%d", sorts[minID], sorts[maxID])}insertID := "20260718000006-abcdefg"+ addFileOperationTestDoc(t, fixture, insertID, "Insert", false)fixture.box.addSort(fixture.sourcePath, insertID)sorts, err = readSortConfMap(confPath)if nil != err {t.Fatalf("read custom sort after adjacent insert failed: %v", err)}- if 2 != sorts[insertID] || 3 != sorts[extraID] {- t.Fatalf("adjacent insert was truncated by MaxListCount: insert=%d, trailing=%d", sorts[insertID], sorts[extraID])+ if 4 != sorts[insertID] || 5 != sorts[extraID] || 6 != sorts[maxID] {+ t.Fatalf("adjacent insert omitted hidden or unlisted documents: insert=%d, hidden=%d, trailing=%d",+ sorts[insertID], sorts[extraID], sorts[maxID])+ }+}++func TestReorderDocsUsesCompleteSiblingOrder(t *testing.T) {+ fixture := setupFileOperationTest(t)+ Conf.FileTree.MaxListCount = 2+ hiddenTree := addFileOperationTestDoc(t, fixture, "20260718000003-abcdefg", "Hidden", true)+ unlistedTree := addFileOperationTestDoc(t, fixture, "20260718000004-abcdefg", "Unlisted", false)+ confPath := filepath.Join(util.DataDir, fixture.box.ID, ".siyuan", "sort.json")+ if err := writeSortConfMap(confPath, map[string]int{+ fixture.targetID: 10,+ hiddenTree.ID: 20,+ fixture.sourceID: 30,+ unlistedTree.ID: 40,+ }); nil != err {+ t.Fatalf("write initial custom sort failed: %v", err)+ }++ result, err := ReorderDocs([]string{fixture.sourceID}, fixture.targetID, "before")+ if nil != err {+ t.Fatalf("reorder documents failed: %v", err)+ }+ if !result.Changed || result.Notebook != fixture.box.ID || result.ParentPath != "/" {+ t.Fatalf("unexpected reorder result: %#v", result)+ }+ assertSiblingCustomOrder(t, fixture.box.ID, "/", []string{+ fixture.sourceID,+ fixture.targetID,+ hiddenTree.ID,+ unlistedTree.ID,+ })++ ChangeFileTreeSort(fixture.box.ID, []string{fixture.targetPath, fixture.sourcePath})+ assertSiblingCustomOrder(t, fixture.box.ID, "/", []string{+ fixture.targetID,+ fixture.sourceID,+ hiddenTree.ID,+ unlistedTree.ID,+ })+}++func TestCreateDocByMdPlacesDocumentRelativeToCompleteOrder(t *testing.T) {+ fixture := setupFileOperationTest(t)+ hiddenTree := addFileOperationTestDoc(t, fixture, "20260718000003-abcdefg", "Hidden", true)+ confPath := filepath.Join(util.DataDir, fixture.box.ID, ".siyuan", "sort.json")+ if err := writeSortConfMap(confPath, map[string]int{+ fixture.targetID: 10,+ hiddenTree.ID: 20,+ fixture.sourceID: 30,+ }); nil != err {+ t.Fatalf("write initial custom sort failed: %v", err)+ }++ newID := "20260718000004-abcdefg"+ tree, err := CreateDocByMd(fixture.box.ID, "/"+newID+".sy", "Relative", "", nil, map[string]any{+ "sortTargetID": fixture.targetID,+ "sortPosition": "after",+ })+ if nil != err {+ t.Fatalf("create relative document failed: %v", err)+ }+ t.Cleanup(func() {+ cache.RemoveTreeData(tree.ID)+ cache.RemoveDocIAL(tree.Path)+ })+ assertSiblingCustomOrder(t, fixture.box.ID, "/", []string{+ fixture.targetID,+ newID,+ hiddenTree.ID,+ fixture.sourceID,+ })+}++func TestReorderNotebooksIncludesClosedNotebooks(t *testing.T) {+ fixture := setupFileOperationTest(t)+ ids := []string{+ fixture.box.ID,+ "20260718000010-abcdefg",+ "20260718000011-abcdefg",+ "20260718000012-abcdefg",+ }+ for i, id := range ids {+ box := &Box{ID: id}+ boxConf := conf.NewBoxConf()+ boxConf.Name = id+ boxConf.Sort = i + 1+ boxConf.Closed = 1 == i || 3 == i+ if err := box.SaveConf(boxConf); nil != err {+ t.Fatalf("save notebook [%s] failed: %v", id, err)+ }+ }++ result, err := ReorderNotebooks([]string{ids[2]}, ids[0], "before")+ if nil != err {+ t.Fatalf("reorder notebooks failed: %v", err)+ }+ if !result.Changed {+ t.Fatalf("notebook reorder was not reported as changed")+ }+ assertNotebookCustomOrder(t, []string{ids[2], ids[0], ids[1], ids[3]})++ ChangeBoxSort([]string{ids[0], ids[2]})+ assertNotebookCustomOrder(t, []string{ids[0], ids[2], ids[1], ids[3]})+}++func TestReorderIDSequence(t *testing.T) {+ current := []string{"a", "b", "c", "d", "e"}+ ordered, changed, err := reorderIDSequence(current, []string{"b", "d"}, "e", "after")+ if nil != err || !changed {+ t.Fatalf("reorder sequence failed: changed=%t, err=%v", changed, err)+ }+ if expected := []string{"a", "c", "e", "b", "d"}; !reflect.DeepEqual(ordered, expected) {+ t.Fatalf("unexpected sequence: got %v, want %v", ordered, expected)+ }+ if _, _, err = reorderIDSequence(current, []string{"missing"}, "e", "before"); nil == err {+ t.Fatal("missing source ID was accepted")+ }+}++func assertSiblingCustomOrder(t *testing.T, boxID, parentPath string, expected []string) {+ t.Helper()+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")+ sorts, err := readSortConfMap(confPath)+ if nil != err {+ t.Fatalf("read custom sort failed: %v", err)+ }+ actual, err := loadSiblingCustomOrder(boxID, parentPath, sorts)+ if nil != err {+ t.Fatalf("load custom sibling order failed: %v", err)+ }+ if !reflect.DeepEqual(actual, expected) {+ t.Fatalf("unexpected sibling order: got %v, want %v", actual, expected)+ }+}++func assertNotebookCustomOrder(t *testing.T, expected []string) {+ t.Helper()+ _, actual := loadNotebookCustomOrder()+ if !reflect.DeepEqual(actual, expected) {+ t.Fatalf("unexpected notebook order: got %v, want %v", actual, expected)}}diff --git a/kernel/model/import.go b/kernel/model/import.goindex 22c4e9d166..60d350b582 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -29,7 +29,6 @@ import ("io""io/fs""maps"- "math""net/url""os""path"@@ -243,7 +242,12 @@ func applyImportedSYSort(boxID, targetPath string, importedDocs []*importedSYSorfileTreeSortLock.Lock()defer fileTreeSortLock.Unlock()- docs, _, err := ListDocTree(boxID, targetPath, util.SortModeCustom, false, false, math.MaxInt)+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")+ fullSortIDs, err := readSortConfMap(confPath)+ if nil != err {+ return err+ }+ existingIDs, err := loadSiblingCustomOrder(boxID, targetPath, fullSortIDs)if nil != err {return err}@@ -253,10 +257,10 @@ func applyImportedSYSort(boxID, targetPath string, importedDocs []*importedSYSorimportedIDs[doc.newID] = struct{}{}}}- existingRootIDs := make([]string, 0, len(docs))- for _, doc := range docs {- if _, imported := importedIDs[doc.ID]; !imported {- existingRootIDs = append(existingRootIDs, doc.ID)+ existingRootIDs := make([]string, 0, len(existingIDs))+ for _, id := range existingIDs {+ if _, imported := importedIDs[id]; !imported {+ existingRootIDs = append(existingRootIDs, id)}}@@ -265,11 +269,6 @@ func applyImportedSYSort(boxID, targetPath string, importedDocs []*importedSYSorif 1 > len(sortValues) {return nil}- confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")- fullSortIDs, err := readSortConfMap(confPath)- if nil != err {- return err- }maps.Copy(fullSortIDs, sortValues)return writeSortConfMap(confPath, fullSortIDs)}