An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:technologist: Add kernel API /api/filetree/setSort https://github.com/siyuan-note/siyuan/issues/15776
Danielbaac2ea1af93
diff --git a/app/src/index.ts b/app/src/index.tsindex f62f2aba16..148920e1d1 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -43,6 +43,7 @@ import {processIOSPurchaseResponse} from "./util/iOSPurchase";import {ipcRenderer} from "electron";/// #endifimport {getDockByType} from "./layout/tabUtil";+import {Files} from "./layout/dock/Files";import {Tag} from "./layout/dock/Tag";import {appearanceConfigApi} from "./config/tabs/appearanceRuntime";import {renderSnippet} from "./config/util/snippets";@@ -218,6 +219,20 @@ export class App {case "openFileById":openFileById({app: this, id: data.data.id, action: [Constants.CB_GET_FOCUS]});break;+ case "filetreeSortChanged": {+ const fileDock = getDockByType("file");+ if (fileDock) {+ (fileDock.data.file as Files).onFiletreeSortChanged(data.data);+ }+ break;+ }+ case "notebookSortChanged": {+ const fileDock = getDockByType("file");+ if (fileDock) {+ (fileDock.data.file as Files).onNotebookSortChanged();+ }+ break;+ }case "exit":if (isBrowser() && !isInMobileApp()) {window.location.href = "about:blank";diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 6b9bedb36b..b4cadcb696 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -1268,6 +1268,39 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"fileItemElement.querySelector(".b3-list-item__text").innerHTML = escapeHtml(data.title);}+ public onFiletreeSortChanged(data: { notebook: string, parentPath: string }) {+ const notebookElement = this.element.querySelector(`ul[data-url="${data.notebook}"]`);+ if (!notebookElement) {+ return;+ }+ const sortMode = notebookElement.getAttribute("data-sortmode");+ if (sortMode !== "6" && !(sortMode === "15" && window.siyuan.config.fileTree.sort === 6)) {+ return;+ }++ const listPath = data.parentPath === "/" ? "/" : `${data.parentPath}.sy`;+ const liElement = notebookElement.querySelector(`li[data-path="${listPath}"]`);+ if (!liElement?.nextElementSibling || liElement.nextElementSibling.tagName !== "UL") {+ return;+ }+ fetchPost("/api/filetree/listDocsByPath", {+ notebook: data.notebook,+ path: listPath,+ app: Constants.SIYUAN_APPID,+ }, response => {+ this.onLsHTML(response.data);+ });+ }++ public onNotebookSortChanged() {+ if (window.siyuan.config.fileTree.sort !== 6) {+ return;+ }+ setNoteBook(() => {+ this.init(false);+ });+ }+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) {@@ -1340,8 +1373,10 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"const openLiElement = hasClosestByClassName(item, "b3-list-item");if (openLiElement) {const tempOpenLiElement = tempElement.content.querySelector(`.b3-list-item[data-node-id="${openLiElement.getAttribute("data-node-id")}"]`);- tempOpenLiElement.after(openLiElement.nextElementSibling);- tempOpenLiElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");+ if (tempOpenLiElement) {+ tempOpenLiElement.after(openLiElement.nextElementSibling);+ tempOpenLiElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");+ }}});nextElement.innerHTML = tempElement.innerHTML;diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.tsindex 066ef6ffdd..6d858e871c 100644--- a/app/src/mobile/dock/MobileFiles.ts+++ b/app/src/mobile/dock/MobileFiles.ts@@ -902,6 +902,39 @@ export class MobileFiles extends Model {fileItemElement.querySelector(".b3-list-item__text").innerHTML = escapeHtml(data.title);}+ public onFiletreeSortChanged(data: { notebook: string, parentPath: string }) {+ const notebookElement = this.element.querySelector(`ul[data-url="${data.notebook}"]`);+ if (!notebookElement) {+ return;+ }+ const sortMode = notebookElement.getAttribute("data-sortmode");+ if (sortMode !== "6" && !(sortMode === "15" && window.siyuan.config.fileTree.sort === 6)) {+ return;+ }++ const listPath = data.parentPath === "/" ? "/" : `${data.parentPath}.sy`;+ const liElement = notebookElement.querySelector(`li[data-path="${listPath}"]`);+ if (!liElement?.nextElementSibling || liElement.nextElementSibling.tagName !== "UL") {+ return;+ }+ fetchPost("/api/filetree/listDocsByPath", {+ notebook: data.notebook,+ path: listPath,+ app: Constants.SIYUAN_APPID,+ }, response => {+ this.onLsHTML(response.data);+ });+ }++ public onNotebookSortChanged() {+ if (window.siyuan.config.fileTree.sort !== 6) {+ return;+ }+ setNoteBook(() => {+ this.init(false);+ });+ }+private onMount(data: IWebSocketData) {if (data.data.existed) {return;@@ -967,8 +1000,10 @@ export class MobileFiles extends Model {const openLiElement = hasClosestByClassName(item, "b3-list-item");if (openLiElement) {const tempOpenLiElement = tempElement.content.querySelector(`.b3-list-item[data-node-id="${openLiElement.getAttribute("data-node-id")}"]`);- tempOpenLiElement.after(openLiElement.nextElementSibling);- tempOpenLiElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");+ if (tempOpenLiElement) {+ tempOpenLiElement.after(openLiElement.nextElementSibling);+ tempOpenLiElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");+ }}});nextElement.innerHTML = tempElement.innerHTML;diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex c63bd9bdf7..1e5ae85c76 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -125,6 +125,12 @@ export const onMessage = (app: App, data: IWebSocketData) => {case "openFileById":openMobileFileById(app, data.data.id);break;+ case "filetreeSortChanged":+ window.siyuan.mobile.docks.file?.onFiletreeSortChanged(data.data);+ break;+ case "notebookSortChanged":+ window.siyuan.mobile.docks.file?.onNotebookSortChanged();+ break;case"txerr":transactionError(data.msg);break;diff --git a/docs/API.ja.md b/docs/API.ja.mdindex 0ce2e2f132..eeb69a2863 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -19,6 +19,7 @@* [ドキュメントの名前を変更](#ドキュメントの名前を変更)* [ドキュメントを削除](#ドキュメントを削除)* [ドキュメントを移動](#ドキュメントを移動)+ * [ノートブックとドキュメントのソート値を設定](#ノートブックとドキュメントのソート値を設定)* [パスから人間が読めるパスを取得](#パスから人間が読めるパスを取得)* [IDから人間が読めるパスを取得](#IDから人間が読めるパスを取得)* [IDからストレージパスを取得](#IDからストレージパスを取得)@@ -508,6 +509,45 @@}```+### ノートブックとドキュメントのソート値を設定++* `/api/filetree/setSort`+* パラメータ++ ```json+ {+ "notebookSorts": [+ {+ "id": "20210817205410-2kvfpfn",+ "sort": -10+ }+ ],+ "docSorts": [+ {+ "id": "20210917220056-yxtyl7i",+ "sort": -8+ }+ ]+ }+ ```++ * `notebookSorts`: ノートブックIDとソート値、省略可能+ * `docSorts`: ドキュメントIDとソート値、省略可能+ * `docSorts`のドキュメントは、開かれていてロック解除済みのノートブックに属している必要があります。ノートブックのルートドキュメントIDは指定できません+ * `notebookSorts`と`docSorts`の少なくとも一方を空でない配列にする必要があります。配列の順序はソートに影響せず、各`sort`値が直接保存されます+* 戻り値++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "notebookIDs": ["20210817205410-2kvfpfn"],+ "docIDs": ["20210917220056-yxtyl7i"]+ }+ }+ ```+### パスから人間が読めるパスを取得* `/api/filetree/getHPathByPath`diff --git a/docs/API.md b/docs/API.mdindex 0368724108..112a8fae3a 100644--- a/docs/API.md+++ b/docs/API.md@@ -19,6 +19,7 @@* [Rename a document](#Rename-a-document)* [Remove a document](#Remove-a-document)* [Move documents](#Move-documents)+ * [Set notebook and document sort values](#Set-notebook-and-document-sort-values)* [Get human-readable path based on path](#Get-human-readable-path-based-on-path)* [Get human-readable path based on ID](#Get-human-readable-path-based-on-ID)* [Get storage path based on ID](#Get-storage-path-based-on-ID)@@ -510,6 +511,45 @@ Move documents by `id`:}```+### Set notebook and document sort values++* `/api/filetree/setSort`+* Parameters++ ```json+ {+ "notebookSorts": [+ {+ "id": "20210817205410-2kvfpfn",+ "sort": -10+ }+ ],+ "docSorts": [+ {+ "id": "20210917220056-yxtyl7i",+ "sort": -8+ }+ ]+ }+ ```++ * `notebookSorts`: Notebook IDs and their sort values, optional+ * `docSorts`: Document IDs and their sort values, optional+ * Documents in `docSorts` must belong to opened and unlocked notebooks; notebook root document IDs are not accepted+ * At least one of `notebookSorts` and `docSorts` must be non-empty. Array order does not affect sorting; each `sort` value is stored directly+* Return value++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "notebookIDs": ["20210817205410-2kvfpfn"],+ "docIDs": ["20210917220056-yxtyl7i"]+ }+ }+ ```+### Get human-readable path based on path* `/api/filetree/getHPathByPath`diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex fd59961975..ad0c5c6912 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -19,6 +19,7 @@* [重命名文档](#重命名文档)* [删除文档](#删除文档)* [移动文档](#移动文档)+ * [设置笔记本和文档排序值](#设置笔记本和文档排序值)* [根据路径获取人类可读路径](#根据路径获取人类可读路径)* [根据 ID 获取人类可读路径](#根据-ID-获取人类可读路径)* [根据 ID 获取存储路径](#根据-ID-获取存储路径)@@ -508,6 +509,45 @@}```+### 设置笔记本和文档排序值++* `/api/filetree/setSort`+* 参数++ ```json+ {+ "notebookSorts": [+ {+ "id": "20210817205410-2kvfpfn",+ "sort": -10+ }+ ],+ "docSorts": [+ {+ "id": "20210917220056-yxtyl7i",+ "sort": -8+ }+ ]+ }+ ```++ * `notebookSorts`:笔记本 ID 及其排序值,可选+ * `docSorts`:文档 ID 及其排序值,可选+ * `docSorts` 中的文档必须属于已打开且已解锁的笔记本,不接受笔记本根文档 ID+ * `notebookSorts` 和 `docSorts` 至少有一个非空;数组顺序不影响排序,每个 `sort` 值会直接存储+* 返回值++ ```json+ {+ "code": 0,+ "msg": "",+ "data": {+ "notebookIDs": ["20210817205410-2kvfpfn"],+ "docIDs": ["20210917220056-yxtyl7i"]+ }+ }+ ```+### 根据路径获取人类可读路径* `/api/filetree/getHPathByPath`diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 7011f27627..a22a99af0e 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -1079,6 +1079,73 @@ func changeSort(c *gin.Context) {model.ChangeFileTreeSort(notebook, paths)}+type sortRequestItem struct {+ ID string `json:"id"`+ Sort *int `json:"sort"`+}++func setSort(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ request := &struct {+ NotebookSorts []*sortRequestItem `json:"notebookSorts"`+ DocSorts []*sortRequestItem `json:"docSorts"`+ }{}+ if err := c.ShouldBindJSON(request); err != nil {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Parses request [%s] failed: %s", c.Request.URL.Path, err)+ return+ }+ if 1 > len(request.NotebookSorts)+len(request.DocSorts) {+ ret.Code = -1+ ret.Msg = "Fields [notebookSorts] and [docSorts] must not both be empty"+ return+ }+ notebookSorts, ok := parseSortItems("notebookSorts", request.NotebookSorts, ret)+ if !ok {+ return+ }+ docSorts, ok := parseSortItems("docSorts", request.DocSorts, ret)+ if !ok {+ return+ }++ result, err := model.SetFileTreeSort(notebookSorts, docSorts)+ ret.Data = result+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ }+}++func parseSortItems(field string, items []*sortRequestItem, ret *gulu.Result) (retItems []*model.SortItem, ok bool) {+ ids := map[string]struct{}{}+ for i, item := range items {+ if nil == item {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [%s][%d] must not be null", field, i)+ return+ }+ if util.InvalidIDPattern(item.ID, ret) {+ return+ }+ if nil == item.Sort {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [%s][%d].sort is required", field, i)+ return+ }+ if _, ok := ids[item.ID]; ok {+ ret.Code = -1+ ret.Msg = fmt.Sprintf("Field [%s] contains duplicate ID [%s]", field, item.ID)+ return nil, false+ }+ ids[item.ID] = struct{}{}+ retItems = append(retItems, &model.SortItem{ID: item.ID, Sort: *item.Sort})+ }+ return retItems, true+}+func searchDocs(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.gonew file mode 100644index 0000000000..eac83647a0--- /dev/null+++ b/kernel/api/filetree_test.go@@ -0,0 +1,63 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+)++func TestSetSortRejectsInvalidRequest(t *testing.T) {+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.POST("/api/filetree/setSort", setSort)++ tests := []struct {+ name string+ body string+ }{+ {name: "empty", body: `{}`},+ {name: "null item", body: `{"docSorts":[null]}`},+ {name: "invalid ID", body: `{"docSorts":[{"id":"invalid","sort":0}]}`},+ {name: "missing sort", body: `{"docSorts":[{"id":"20260718000001-abcdefg"}]}`},+ {name: "fractional sort", body: `{"docSorts":[{"id":"20260718000001-abcdefg","sort":1.5}]}`},+ {name: "duplicate ID", body: `{"docSorts":[{"id":"20260718000001-abcdefg","sort":0},{"id":"20260718000001-abcdefg","sort":1}]}`},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/filetree/setSort", 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); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ if response.Code != -1 {+ t.Fatalf("invalid request returned code %d: %s", response.Code, recorder.Body.String())+ }+ })+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 4f76206e3b..a9db30d3cc 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -141,6 +141,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/setSort", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setSort)ginServer.Handle("POST", "/api/filetree/createDocWithMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDocWithMd)ginServer.Handle("POST", "/api/filetree/createDailyNote", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDailyNote)ginServer.Handle("POST", "/api/filetree/createDoc", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDoc)diff --git a/kernel/model/box.go b/kernel/model/box.goindex 69c10104f9..1e4dd52cf3 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -911,13 +911,19 @@ func fullReindex() {}func ChangeBoxSort(boxIDs []string) {+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()+for i, boxID := range boxIDs {box := &Box{ID: boxID}boxConf := box.GetConf()boxConf.Sort = i + 1box.SaveConf(boxConf)}+ pushNotebookSortChanged()+}+func pushNotebookSortChanged() {var notebookIDs []stringfor _, box := range Conf.GetOpenedBoxes() {notebookIDs = append(notebookIDs, box.ID)diff --git a/kernel/model/file.go b/kernel/model/file.goindex 9beb8830c1..6fdeed5755 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -2226,6 +2226,8 @@ func moveSorts(rootID, fromBox, toBox string) {if nil == root {return}+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()fromRootSorts := map[string]int{}ids := treenode.RootChildIDs(rootID)@@ -2275,6 +2277,8 @@ func ChangeFileTreeSort(boxID string, paths []string) {}FlushTxQueue()+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()box := Conf.Box(boxID)sortIDs := map[string]int{}max := 0@@ -2331,6 +2335,176 @@ func ChangeFileTreeSort(boxID string, paths []string) {pushFiletreeSortChanged(sortFolderIDs)}+var fileTreeSortLock sync.Mutex++type SortItem struct {+ ID string `json:"id"`+ Sort int `json:"sort"`+}++type SetFileTreeSortResult struct {+ NotebookIDs []string `json:"notebookIDs"`+ DocIDs []string `json:"docIDs"`+}++type notebookSortPlan struct {+ item *SortItem+ box *Box+}++type docSortPlan struct {+ item *SortItem+ boxID string+ parentPath string+}++type docSortGroup struct {+ fullSortIDs map[string]int+ changed map[string]int+ parentSorts map[string]map[string]int+ writeSuccess bool+}++func SetFileTreeSort(notebookSorts, docSorts []*SortItem) (ret *SetFileTreeSortResult, err error) {+ ret = &SetFileTreeSortResult{+ NotebookIDs: []string{},+ DocIDs: []string{},+ }++ FlushTxQueue()+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()+ boxes := map[string]*Box{}+ for _, box := range Conf.GetBoxes() {+ boxes[box.ID] = box+ }+ openedBoxes := map[string]*Box{}+ for _, box := range Conf.GetOpenedBoxes() {+ openedBoxes[box.ID] = box+ }++ notebookPlans := make([]*notebookSortPlan, 0, len(notebookSorts))+ notebookIDs := map[string]struct{}{}+ for _, item := range notebookSorts {+ if nil == item {+ return ret, errors.New("notebook sort item must not be nil")+ }+ if _, ok := notebookIDs[item.ID]; ok {+ return ret, fmt.Errorf("duplicate notebook ID [%s]", item.ID)+ }+ notebookIDs[item.ID] = struct{}{}++ box := boxes[item.ID]+ if nil == box {+ return ret, fmt.Errorf("notebook [%s] not found", item.ID)+ }+ notebookPlans = append(notebookPlans, ¬ebookSortPlan{item: item, box: box})+ }++ docPlans := make([]*docSortPlan, 0, len(docSorts))+ docIDs := map[string]struct{}{}+ for _, item := range docSorts {+ if nil == item {+ return ret, errors.New("document sort item must not be nil")+ }+ if _, ok := docIDs[item.ID]; ok {+ return ret, fmt.Errorf("duplicate document ID [%s]", item.ID)+ }+ docIDs[item.ID] = struct{}{}++ bt := treenode.GetBlockTree(item.ID)+ if nil == bt || nil == openedBoxes[bt.BoxID] {+ return ret, fmt.Errorf("document [%s] not found in opened and unlocked notebooks", item.ID)+ }+ if bt.ID != bt.RootID || "d" != bt.Type || IsBoxDoc(bt.BoxID, bt.RootID) {+ return ret, fmt.Errorf("block [%s] is not a sortable document", item.ID)+ }+ if nil == boxes[bt.BoxID] {+ return ret, fmt.Errorf("notebook [%s] not found for document [%s]", bt.BoxID, item.ID)+ }+ docPlans = append(docPlans, &docSortPlan{item: item, boxID: bt.BoxID, parentPath: path.Dir(bt.Path)})+ }++ docGroups := map[string]*docSortGroup{}+ for _, plan := range docPlans {+ group := docGroups[plan.boxID]+ if nil == group {+ confPath := filepath.Join(util.DataDir, plan.boxID, ".siyuan", "sort.json")+ fullSortIDs, readErr := readSortConfMap(confPath)+ if readErr != nil {+ return ret, readErr+ }+ group = &docSortGroup{+ fullSortIDs: fullSortIDs,+ changed: map[string]int{},+ parentSorts: map[string]map[string]int{},+ }+ docGroups[plan.boxID] = group+ }++ if group.fullSortIDs[plan.item.ID] == plan.item.Sort {+ continue+ }+ group.changed[plan.item.ID] = plan.item.Sort+ if nil == group.parentSorts[plan.parentPath] {+ group.parentSorts[plan.parentPath] = map[string]int{}+ }+ group.parentSorts[plan.parentPath][plan.item.ID] = plan.item.Sort+ }++ var writeErr error+ for _, plan := range notebookPlans {+ boxConf := plan.box.GetConf()+ if boxConf.Sort == plan.item.Sort {+ continue+ }+ boxConf.Sort = plan.item.Sort+ if saveErr := plan.box.SaveConf(boxConf); saveErr != nil {+ writeErr = errors.Join(writeErr, saveErr)+ continue+ }+ ret.NotebookIDs = append(ret.NotebookIDs, plan.item.ID)+ }++ for boxID, group := range docGroups {+ if 0 == len(group.changed) {+ continue+ }+ maps.Copy(group.fullSortIDs, group.changed)+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")+ if writeErr0 := writeSortConfMap(confPath, group.fullSortIDs); writeErr0 != nil {+ writeErr = errors.Join(writeErr, writeErr0)+ continue+ }+ group.writeSuccess = true+ }++ for _, plan := range docPlans {+ group := docGroups[plan.boxID]+ if group.writeSuccess {+ if _, ok := group.changed[plan.item.ID]; ok {+ ret.DocIDs = append(ret.DocIDs, plan.item.ID)+ }+ }+ }++ if 0 < len(ret.NotebookIDs) {+ pushNotebookSortChanged()+ }+ for _, group := range docGroups {+ if !group.writeSuccess {+ continue+ }+ for _, parentSorts := range group.parentSorts {+ pushFiletreeSortChanged(parentSorts)+ }+ }+ if 0 < len(ret.NotebookIDs)+len(ret.DocIDs) {+ IncSync()+ }+ return ret, writeErr+}+func (box *Box) fillSort(files *[]*File) {confPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")fullSortIDs, err := readSortConfMap(confPath)@@ -2345,6 +2519,9 @@ func (box *Box) fillSort(files *[]*File) {}func (box *Box) removeSort(ids []string) {+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()+confPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")if !filelock.IsExist(confPath) {return@@ -2417,6 +2594,9 @@ func (box *Box) addMinSort(parentPath, id string) {}func (box *Box) setSortVal(id string, sortVal int) {+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()+var err errorconfDir := filepath.Join(util.DataDir, box.ID, ".siyuan")if err = os.MkdirAll(confDir, 0755); err != nil {@@ -2436,6 +2616,9 @@ func (box *Box) setSortVal(id string, sortVal int) {}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)@@ -2475,6 +2658,9 @@ func (box *Box) addSort(previousPath, id string) {}func (box *Box) setSort(sortIDVals map[string]int) {+ fileTreeSortLock.Lock()+ defer fileTreeSortLock.Unlock()+confPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")if !filelock.IsExist(confPath) {return@@ -2515,6 +2701,7 @@ func pushFiletreeSortChanged(sortIDs map[string]int) {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 7da4b70196..fdc3594fb5 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -49,6 +49,7 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {Conf = NewAppConf()Conf.FileTree = conf.NewFileTree()Conf.NotebookCrypto = conf.NewNotebookCrypto()+ Conf.Sync = conf.NewSync()box := &Box{ID: "20260718000000-abcdefg"}boxConf := conf.NewBoxConf()@@ -152,6 +153,97 @@ func TestMoveDocsRejectsInvalidPathsBeforeMoving(t *testing.T) {}}+func TestSetFileTreeSort(t *testing.T) {+ fixture := setupFileOperationTest(t)++ result, err := SetFileTreeSort(+ []*SortItem{{ID: fixture.box.ID, Sort: -10}},+ []*SortItem{{ID: fixture.sourceID, Sort: -8}},+ )+ if err != nil {+ t.Fatalf("set file tree sort failed: %v", err)+ }+ if len(result.NotebookIDs) != 1 || result.NotebookIDs[0] != fixture.box.ID {+ t.Fatalf("unexpected changed notebook IDs: %v", result.NotebookIDs)+ }+ if len(result.DocIDs) != 1 || result.DocIDs[0] != fixture.sourceID {+ t.Fatalf("unexpected changed document IDs: %v", result.DocIDs)+ }+ if sortVal := fixture.box.GetConf().Sort; sortVal != -10 {+ t.Fatalf("unexpected notebook sort: got %d, want -10", sortVal)+ }+ sortConfPath := filepath.Join(util.DataDir, fixture.box.ID, ".siyuan", "sort.json")+ sortValues, err := readSortConfMap(sortConfPath)+ if err != nil {+ t.Fatalf("read sort conf failed: %v", err)+ }+ if sortVal := sortValues[fixture.sourceID]; sortVal != -8 {+ t.Fatalf("unexpected document sort: got %d, want -8", sortVal)+ }++ result, err = SetFileTreeSort(+ []*SortItem{{ID: fixture.box.ID, Sort: -10}},+ []*SortItem{{ID: fixture.sourceID, Sort: -8}},+ )+ if err != nil {+ t.Fatalf("repeat file tree sort failed: %v", err)+ }+ if 0 != len(result.NotebookIDs) || 0 != len(result.DocIDs) {+ t.Fatalf("unchanged sorts reported changes: %+v", result)+ }+}++func TestSetFileTreeSortValidatesBeforeWriting(t *testing.T) {+ fixture := setupFileOperationTest(t)++ if _, err := SetFileTreeSort(+ []*SortItem{{ID: fixture.box.ID, Sort: -10}},+ []*SortItem{{ID: fixture.childID, Sort: -8}},+ ); err == nil {+ t.Fatal("expected a child block ID to be rejected")+ }+ if sortVal := fixture.box.GetConf().Sort; sortVal != 0 {+ t.Fatalf("notebook sort changed before request validation completed: %d", sortVal)+ }+}++func TestSetFileTreeSortRejectsNotebookRootDocument(t *testing.T) {+ fixture := setupFileOperationTest(t)+ boxDocPath := "/" + fixture.box.ID + ".sy"+ boxDocTree := treenode.NewTree(fixture.box.ID, boxDocPath, "/File operation test", "File operation test")+ if _, err := filesys.WriteTree(boxDocTree); err != nil {+ t.Fatalf("write notebook root document failed: %v", err)+ }+ treenode.UpsertBlockTree(boxDocTree)+ t.Cleanup(func() {+ cache.RemoveTreeData(boxDocTree.ID)+ cache.RemoveDocIAL(boxDocTree.Path)+ })++ if _, err := SetFileTreeSort(+ []*SortItem{{ID: fixture.box.ID, Sort: -10}},+ []*SortItem{{ID: fixture.box.ID, Sort: -8}},+ ); err == nil {+ t.Fatal("expected a notebook root document ID to be rejected")+ }+ if sortVal := fixture.box.GetConf().Sort; sortVal != 0 {+ t.Fatalf("notebook sort changed before notebook root document validation completed: %d", sortVal)+ }+}++func TestSetFileTreeSortRejectsDocumentInClosedNotebook(t *testing.T) {+ fixture := setupFileOperationTest(t)+ boxConf := fixture.box.GetConf()+ boxConf.Closed = true+ if err := fixture.box.SaveConf(boxConf); err != nil {+ t.Fatalf("close test notebook failed: %v", err)+ }++ if _, err := SetFileTreeSort(nil, []*SortItem{{ID: fixture.sourceID, Sort: -8}}); err == nil {+ t.Fatal("expected a document in a closed notebook to be rejected")+ }+}+func TestSortSearchDocResults(t *testing.T) {results := []searchDocResult{{data: map[string]string{"hPath": "A/初中数学"}},