Skip to content

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

:sparkles: Improve manual reordering in the document tree with active sort rules https://github.com/siyuan-note/siyuan/issues/19176

Danielac0c339af2b6
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 983ab6a235..5ad4332529 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "تتعارض هذه النقلة مع قاعدة الفرز الحالية. هل تريد تحويل هذه القائمة إلى ترتيب مخصص وحفظ الترتيب الكامل بعد السحب؟",
"pasteAndKeepSourceFormat": "لصق مع الاحتفاظ بتنسيق المصدر",
"templatePackageMoveTip": "لا يمكن إعادة تسمية مجلدات حزم القوالب أو نقلها",
"avDragRemoveSorts": "يتعارض هذا النقل مع قواعد الفرز الحالية. هل تريد إزالة قواعد الفرز لهذا العرض وحفظ الترتيب الكامل الناتج عن السحب كترتيب مخصص؟",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index e2a20a119f..c214fda2bd 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Diese Verschiebung widerspricht der aktuellen Sortierregel. Diese Liste auf benutzerdefinierte Sortierung umstellen und die vollständige Reihenfolge nach dem Ziehen speichern?",
"pasteAndKeepSourceFormat": "Einfügen und Quellformatierung beibehalten",
"templatePackageMoveTip": "Ordner von Vorlagenpaketen können nicht umbenannt oder verschoben werden",
"avDragRemoveSorts": "Diese Verschiebung widerspricht den aktuellen Sortierregeln. Möchtest du die Sortierregeln dieser Ansicht entfernen und die vollständige Reihenfolge nach dem Ziehen als benutzerdefinierte Reihenfolge speichern?",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 8eab733323..843e2fbf0a 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "This move conflicts with the current sort rule. Switch this list to custom sorting and save the complete order after dragging?",
"pasteAndKeepSourceFormat": "Paste and keep source formatting",
"templatePackageMoveTip": "Template package folders cannot be renamed or moved",
"avDragRemoveSorts": "This move conflicts with the current sort rules. Remove the sort rules for this view and save the complete order after dragging as the custom order?",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index c530a6773d..d17cbfc6e2 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Este movimiento entra en conflicto con la regla de ordenación actual. ¿Cambiar esta lista a ordenación personalizada y guardar el orden completo después de arrastrar?",
"pasteAndKeepSourceFormat": "Pegar y conservar el formato de origen",
"templatePackageMoveTip": "Las carpetas de paquetes de plantillas no se pueden renombrar ni mover",
"avDragRemoveSorts": "Este movimiento entra en conflicto con las reglas de ordenación actuales. ¿Quieres eliminar las reglas de ordenación de esta vista y guardar el orden completo resultante del arrastre como orden personalizado?",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 381b44ec03..bfffbadf9a 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Ce déplacement est incompatible avec la règle de tri actuelle. Passer cette liste au tri personnalisé et enregistrer l’ordre complet après le déplacement ?",
"pasteAndKeepSourceFormat": "Coller en conservant la mise en forme source",
"templatePackageMoveTip": "Les dossiers de paquets de modèles ne peuvent pas être renommés ni déplacés",
"avDragRemoveSorts": "Ce déplacement est incompatible avec les règles de tri actuelles. Supprimer les règles de tri de cette vue et enregistrer l’ordre complet après le déplacement comme ordre personnalisé ?",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 2c3dd9a579..1d0d7a4fc7 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "העברה זו מתנגשת עם כלל המיון הנוכחי. להעביר רשימה זו למיון מותאם אישית ולשמור את הסדר המלא לאחר הגרירה?",
"pasteAndKeepSourceFormat": "הדבק ושמור על עיצוב המקור",
"templatePackageMoveTip": "לא ניתן לשנות שם או להעביר תיקיות של חבילות תבניות",
"avDragRemoveSorts": "ההעברה הזו מתנגשת עם כללי המיון הנוכחיים. להסיר את כללי המיון של התצוגה הזו ולשמור את הסדר המלא לאחר הגרירה כסדר מותאם אישית?",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index e419ce4c1d..8509f21a26 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "यह स्थानांतरण वर्तमान क्रमबद्ध करने के नियम से मेल नहीं खाता। क्या इस सूची को कस्टम क्रम में बदलकर खींचने के बाद का पूरा क्रम सहेजें?",
"pasteAndKeepSourceFormat": "स्रोत स्वरूपण बनाए रखते हुए चिपकाएँ",
"templatePackageMoveTip": "टेम्पलेट पैकेज फ़ोल्डर का नाम बदलना या उसे स्थानांतरित करना संभव नहीं है",
"avDragRemoveSorts": "यह स्थानांतरण मौजूदा क्रमबद्ध करने के नियमों से टकराता है। क्या इस दृश्य के क्रमबद्ध करने के नियम हटाकर खींचने के बाद के पूरे क्रम को कस्टम क्रम के रूप में सहेजना है?",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 2f06887d6b..04cd825eb2 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Pemindahan ini bertentangan dengan aturan pengurutan saat ini. Alihkan daftar ini ke pengurutan khusus dan simpan urutan lengkap setelah menyeret?",
"pasteAndKeepSourceFormat": "Tempel dan pertahankan pemformatan sumber",
"templatePackageMoveTip": "Folder paket templat tidak dapat diganti namanya atau dipindahkan",
"avDragRemoveSorts": "Pemindahan ini bertentangan dengan aturan pengurutan saat ini. Hapus aturan pengurutan untuk tampilan ini dan simpan urutan lengkap setelah penyeretan sebagai urutan khusus?",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 025890cb95..81925335f1 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Questo spostamento è in conflitto con la regola di ordinamento attuale. Passare questa lista all’ordinamento personalizzato e salvare l’ordine completo dopo il trascinamento?",
"pasteAndKeepSourceFormat": "Incolla mantenendo la formattazione originale",
"templatePackageMoveTip": "Le cartelle dei pacchetti di modelli non possono essere rinominate o spostate",
"avDragRemoveSorts": "Questo spostamento è in conflitto con le regole di ordinamento attuali. Rimuovere le regole di ordinamento di questa vista e salvare l’ordine completo dopo il trascinamento come ordine personalizzato?",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 4a85190b45..cc0417ef75 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "この移動は現在の並び替えルールと競合します。このリストをカスタム順に切り替え、ドラッグ後の全体の順序を保存しますか?",
"pasteAndKeepSourceFormat": "元の書式を保持して貼り付け",
"templatePackageMoveTip": "テンプレートパッケージのフォルダーは名前の変更や移動ができません",
"avDragRemoveSorts": "この移動は現在の並べ替えルールと競合します。このビューの並べ替えルールを削除し、ドラッグ後の全項目の順序をカスタム順序として保存しますか?",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index ddfe707c04..656806f57d 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "이 이동은 현재 정렬 규칙과 충돌합니다. 이 목록을 사용자 지정 정렬로 전환하고 드래그 후의 전체 순서를 저장하시겠습니까?",
"pasteAndKeepSourceFormat": "원본 서식을 유지하여 붙여넣기",
"templatePackageMoveTip": "템플릿 패키지 폴더는 이름을 변경하거나 이동할 수 없습니다",
"avDragRemoveSorts": "이 이동은 현재 정렬 규칙과 충돌합니다. 이 보기의 정렬 규칙을 제거하고 드래그 후의 전체 순서를 사용자 지정 순서로 저장할까요?",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index d16bfd3f33..2ae4c1a576 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Deze verplaatsing is in strijd met de huidige sorteerregel. Deze lijst omzetten naar een aangepaste sortering en de volledige volgorde na het slepen opslaan?",
"pasteAndKeepSourceFormat": "Plakken met behoud van bronopmaak",
"templatePackageMoveTip": "Mappen van sjabloonpakketten kunnen niet worden hernoemd of verplaatst",
"avDragRemoveSorts": "Deze verplaatsing is in strijd met de huidige sorteerregels. Wil je de sorteerregels voor deze weergave verwijderen en de volledige volgorde na het slepen opslaan als aangepaste volgorde?",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index c8fbff09a0..b100f26ff4 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "To przeniesienie jest sprzeczne z bieżącą regułą sortowania. Przełączyć tę listę na sortowanie niestandardowe i zapisać pełną kolejność po przeciągnięciu?",
"pasteAndKeepSourceFormat": "Wklej z zachowaniem formatowania źródłowego",
"templatePackageMoveTip": "Nie można zmieniać nazw ani przenosić folderów pakietów szablonów",
"avDragRemoveSorts": "To przeniesienie jest sprzeczne z bieżącymi regułami sortowania. Czy usunąć reguły sortowania tego widoku i zapisać pełną kolejność po przeciągnięciu jako kolejność niestandardową?",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index eade1375a4..f78e0185a5 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Este movimento entra em conflito com a regra de ordenação atual. Alterar esta lista para ordenação personalizada e salvar a ordem completa após arrastar?",
"pasteAndKeepSourceFormat": "Colar mantendo a formatação original",
"templatePackageMoveTip": "As pastas de pacotes de modelos não podem ser renomeadas ou movidas",
"avDragRemoveSorts": "Este movimento entra em conflito com as regras de ordenação atuais. Remover as regras de ordenação desta visualização e salvar a ordem completa após arrastar como ordem personalizada?",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 8e152c499f..0f47ed5a0a 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Это перемещение противоречит текущему правилу сортировки. Переключить этот список на пользовательскую сортировку и сохранить полный порядок после перетаскивания?",
"pasteAndKeepSourceFormat": "Вставить с сохранением исходного форматирования",
"templatePackageMoveTip": "Папки пакетов шаблонов нельзя переименовывать или перемещать",
"avDragRemoveSorts": "Это перемещение противоречит текущим правилам сортировки. Удалить правила сортировки для этого представления и сохранить полный порядок после перетаскивания как пользовательский?",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 06d1839042..fc710123e9 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Tento presun je v rozpore s aktuálnym pravidlom zoradenia. Prepnúť tento zoznam na vlastné zoradenie a uložiť úplné poradie po potiahnutí?",
"pasteAndKeepSourceFormat": "Prilepiť so zachovaním zdrojového formátovania",
"templatePackageMoveTip": "Priečinky balíkov šablón nemožno premenovať ani presunúť",
"avDragRemoveSorts": "Tento presun je v rozpore s aktuálnymi pravidlami zoradenia. Odstrániť pravidlá zoradenia tohto zobrazenia a uložiť úplné poradie po presunutí ako vlastné poradie?",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 28dd4cd007..525c8a9606 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "การย้ายนี้ขัดแย้งกับกฎการเรียงลำดับปัจจุบัน ต้องการเปลี่ยนรายการนี้เป็นการเรียงลำดับแบบกำหนดเองและบันทึกลำดับทั้งหมดหลังลากหรือไม่?",
"pasteAndKeepSourceFormat": "วางโดยคงการจัดรูปแบบต้นฉบับ",
"templatePackageMoveTip": "ไม่สามารถเปลี่ยนชื่อหรือย้ายโฟลเดอร์แพ็กเกจแม่แบบได้",
"avDragRemoveSorts": "การย้ายนี้ขัดแย้งกับกฎการเรียงลำดับปัจจุบัน ต้องการลบกฎการเรียงลำดับของมุมมองนี้และบันทึกลำดับทั้งหมดหลังการลากเป็นลำดับที่กำหนดเองหรือไม่?",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 1d7045edae..f1e8ebcb48 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Bu taşıma geçerli sıralama kuralıyla çakışıyor. Bu liste özel sıralamaya geçirilsin ve sürükleme sonrası tam sıralama kaydedilsin mi?",
"pasteAndKeepSourceFormat": "Kaynak biçimlendirmesini koruyarak yapıştır",
"templatePackageMoveTip": "Şablon paketi klasörleri yeniden adlandırılamaz veya taşınamaz",
"avDragRemoveSorts": "Bu taşıma mevcut sıralama kurallarıyla çelişiyor. Bu görünümün sıralama kuralları kaldırılsın ve sürükleme sonrasındaki tam sıra özel sıra olarak kaydedilsin mi?",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 410f7f7468..fabc5c95e8 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "Це переміщення суперечить поточному правилу сортування. Перемкнути цей список на власне сортування та зберегти повний порядок після перетягування?",
"pasteAndKeepSourceFormat": "Вставити зі збереженням вихідного форматування",
"templatePackageMoveTip": "Папки пакетів шаблонів не можна перейменовувати або переміщувати",
"avDragRemoveSorts": "Це переміщення суперечить поточним правилам сортування. Видалити правила сортування для цього подання та зберегти повний порядок після перетягування як користувацький?",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index db98a29815..c2938eaca4 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "此次拖拽与当前排序规则冲突,是否将此列表切换为自定义排序,并保存拖拽后的完整顺序?",
"pasteAndKeepSourceFormat": "粘贴并保留源格式",
"templatePackageMoveTip": "模板包文件夹不支持重命名或移动",
"avDragRemoveSorts": "此次拖拽与当前排序规则冲突。是否移除此视图的排序规则,并将拖拽后的完整顺序保存为自定义顺序?",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index a247936ccd..bdc472eec5 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "fileTreeDragRemoveSorts": "此次拖曳與目前排序規則衝突,是否將此清單切換為自訂排序,並儲存拖曳後的完整順序?",
"pasteAndKeepSourceFormat": "貼上並保留來源格式",
"templatePackageMoveTip": "範本套件資料夾不支援重新命名或移動",
"avDragRemoveSorts": "此次拖曳與目前的排序規則衝突。是否移除此檢視的排序規則,並將拖曳後的完整順序儲存為自訂順序?",
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 96e3135b51..bb0a761cf2 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -72,6 +72,7 @@ import {
updateFileTreeSortMode
} from "../../util/fileTreeSort";
import {clearDocumentTabMovePreview} from "../tabDrag";
+import {reorderSortedFileTree} from "../../util/fileTreeReorder";
import {getHostCapabilities} from "../../util/hostCapabilities";
export class Files extends Model {
@@ -672,7 +673,7 @@ export class Files extends Model {
}
if ((dragOverLastObj.sourceOnlyRoot && targetType === "navigation-root" && window.siyuan.config.fileTree.sort === 6) ||
(!dragOverLastObj.sourceOnlyRoot && targetType !== "navigation-root" &&
- isCustomFileTreeList(targetListElement))
+ (isCustomFileTreeList(targetListElement) || !gutterType))
) {
const nodeRect = liElement.getBoundingClientRect();
const dragHeight = nodeRect.height * .2;
@@ -932,6 +933,17 @@ export class Files extends Model {
toURL,
!newElement.classList.contains("dragover__top")
));
+ } else if (!isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
+ const after = newElement.classList.contains("dragover__bottom");
+ newElement.classList.remove("dragover", "dragover__bottom", "dragover__top");
+ 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]);
+ return;
+ }
+ await this.reorderSortedDocuments(selectFileElements.map(item => item.getAttribute("data-node-id")),
+ newElement.getAttribute("data-node-id"), after, oldScrollTop);
} else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
const toDir = pathPosix().dirname(toPath);
const newElementClassList = newElement.getAttribute("class");
@@ -1031,6 +1043,21 @@ export class Files extends Model {
this.init();
}
+ private async reorderSortedDocuments(sourceIDs: string[], targetID: string, after: boolean, scrollTop: number) {
+ const result = await reorderSortedFileTree(sourceIDs, targetID, after);
+ if (!result) {
+ return;
+ }
+ const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: result.notebook,
+ path: result.parentPath,
+ app: Constants.SIYUAN_APPID,
+ });
+ if (response.code === 0 && response.data?.files) {
+ this.onLsHTML(response.data, scrollTop);
+ }
+ }
+
private async dropDocumentTab(
documentTabData: IDocumentTabDragData,
targetElement: HTMLElement,
@@ -1079,6 +1106,8 @@ export class Files extends Model {
}
if (!isCustomFileTreeList(targetElement.parentElement)) {
+ await this.reorderSortedDocuments([documentTabData.rootId], targetElement.getAttribute("data-node-id"),
+ insertAfter, oldScrollTop);
return;
}
const targetDirectory = pathPosix().dirname(targetPath);
@@ -1591,7 +1620,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
const listPath = data.parentPath === "/" ? "/" : `${data.parentPath}.sy`;
const liElement = notebookElement.querySelector(`li[data-path="${listPath}"]`);
const listElement = liElement?.nextElementSibling;
- if (!listElement || listElement.tagName !== "UL" || !isCustomFileTreeList(listElement)) {
+ if (!listElement || listElement.tagName !== "UL") {
return;
}
fetchPost("/api/filetree/listDocsByPath", {
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index 2d6919d86b..2c36c52b79 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -11,6 +11,7 @@ import {
openPublishAccessDialog
} from "../../protyle/util/publishAccess";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
+import {reorderSortedFileTree} from "../../util/fileTreeReorder";
import {genUUID} from "../../util/genID";
import {openMobileFileById} from "../editor";
import {
@@ -367,7 +368,7 @@ export class MobileFiles extends Model {
}
return;
}
- if (isCustomFileTreeList(liElement.parentElement)) {
+ if (targetDataType === "navigation-file") {
const dragHeight = liRect.height * .2;
if (touch.clientY > liRect.bottom - dragHeight) {
liElement.classList.add("dragover__bottom");
@@ -465,6 +466,30 @@ export class MobileFiles extends Model {
toURL,
!newElement.classList.contains("dragover__top")
));
+ } else if (!isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
+ const after = newElement.classList.contains("dragover__bottom");
+ const sourceNotebookId = state.selectedElement.getAttribute("data-notebook-id") ||
+ state.selectedElement.closest("ul[data-url]")?.getAttribute("data-url") || "";
+ this.clearDragIndicators();
+ this.touchDragState = null;
+ if (!isMoveTargetAllowed([sourceNotebookId], toURL)) {
+ showMessage(window.siyuan.languages._kernel[313]);
+ return;
+ }
+ const result = await reorderSortedFileTree(
+ selectFileElements.map(item => item.getAttribute("data-node-id")),
+ newElement.getAttribute("data-node-id"), after);
+ if (result) {
+ const response = await fetchSyncPost("/api/filetree/listDocsByPath", {
+ notebook: result.notebook,
+ path: result.parentPath,
+ app: Constants.SIYUAN_APPID,
+ });
+ if (response.code === 0 && response.data?.files) {
+ this.onLsHTML(response.data, oldScrollTop);
+ }
+ }
+ return;
} else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
let hasMove = false;
const toDir = pathPosix().dirname(toPath);
@@ -1115,7 +1140,7 @@ export class MobileFiles extends Model {
const listPath = data.parentPath === "/" ? "/" : `${data.parentPath}.sy`;
const liElement = notebookElement.querySelector(`li[data-path="${listPath}"]`);
const listElement = liElement?.nextElementSibling;
- if (!listElement || listElement.tagName !== "UL" || !isCustomFileTreeList(listElement)) {
+ if (!listElement || listElement.tagName !== "UL") {
return;
}
fetchPost("/api/filetree/listDocsByPath", {
diff --git a/app/src/util/fileTreeReorder.test.ts b/app/src/util/fileTreeReorder.test.ts
new file mode 100644
index 0000000000..42950a3b91
--- /dev/null
+++ b/app/src/util/fileTreeReorder.test.ts
@@ -0,0 +1,84 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/util/fileTreeReorder.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = (responses: any[], accept = false) => {
+ const requests: any[] = [];
+ let confirmations = 0;
+ const exports: any = {};
+ runInNewContext(compiled, {
+ exports,
+ window: {siyuan: {languages: {removeSorts: "Sort", fileTreeDragRemoveSorts: "Confirm"}}},
+ require: () => ({
+ getRelativeReorderRequest: (sourceIDs: string[], targetID: string, after: boolean) => ({
+ sourceIDs, targetID, position: after ? "after" : "before",
+ }),
+ fetchSyncPost: async (_url: string, data: any) => {
+ requests.push(data);
+ assert.ok(responses.length > 0);
+ return responses.shift();
+ },
+ confirmDialog: (_title: string, _text: string, confirm: () => void, cancel: () => void) => {
+ confirmations++;
+ assert.equal(requests[requests.length - 1].preview, true);
+ (accept ? confirm : cancel)();
+ },
+ }),
+ });
+ return {
+ requests,
+ confirmations: () => confirmations,
+ sort: () => exports.reorderSortedFileTree(["a", "b"], "c", false),
+ };
+};
+
+const preview = (conflict: boolean) => ({code: 0, data: {changed: true, conflict}});
+const applied = {code: 0, data: {notebook: "notebook", parentPath: "/"}};
+
+test("canceling or closing a conflict dialog does not move documents", async () => {
+ const f = fixture([preview(true)]);
+ assert.equal(await f.sort(), undefined);
+ assert.equal(f.requests.length, 1);
+ assert.equal(f.requests[0].preview, true);
+ assert.equal(f.confirmations(), 1);
+});
+
+test("confirmation applies the full selection and relative anchor", async () => {
+ const f = fixture([preview(true), applied], true);
+ assert.equal(await f.sort(), applied.data);
+ assert.equal(f.requests.length, 2);
+ assert.equal(f.requests[1].removeSorts, true);
+ assert.equal(f.requests[1].sourceIDs.join(","), "a,b");
+ assert.equal(f.requests[1].targetID, "c");
+ assert.equal(f.requests[1].position, "before");
+});
+
+test("equal sort values apply without removing rules", async () => {
+ const f = fixture([preview(false), applied]);
+ await f.sort();
+ assert.equal(f.confirmations(), 0);
+ assert.equal(f.requests[1].removeSorts, false);
+});
+
+test("new conflicts after preview require confirmation", async () => {
+ const f = fixture([preview(false), preview(true), preview(true)]);
+ assert.equal(await f.sort(), undefined);
+ assert.equal(f.requests.length, 3);
+ assert.equal(f.requests[2].preview, true);
+ assert.equal(f.confirmations(), 1);
+});
+
+test("failed and unchanged previews do not write", async () => {
+ for (const response of [{code: -1}, {code: 0, data: {changed: false}}]) {
+ const f = fixture([response]);
+ await f.sort();
+ assert.equal(f.requests.length, 1);
+ assert.equal(f.confirmations(), 0);
+ }
+});
diff --git a/app/src/util/fileTreeReorder.ts b/app/src/util/fileTreeReorder.ts
new file mode 100644
index 0000000000..582c6fc1cc
--- /dev/null
+++ b/app/src/util/fileTreeReorder.ts
@@ -0,0 +1,32 @@
+import {confirmDialog} from "../dialog/confirmDialog";
+import {fetchSyncPost} from "./fetch";
+import {getRelativeReorderRequest} from "./fileTreeMove";
+
+// 确认前只请求预览,取消或关闭对话框不会移动文档。
+export const reorderSortedFileTree = async (sourceIDs: string[], targetID: string, after: boolean):
+ Promise<{notebook: string, parentPath: string} | undefined> => {
+ const request = {...getRelativeReorderRequest(sourceIDs, targetID, after), respectSort: true};
+ const preview = await fetchSyncPost("/api/filetree/reorderDocs", {...request, preview: true});
+ if (preview.code !== 0 || !preview.data?.changed) {
+ return;
+ }
+ let removeSorts = false;
+ if (preview.data.conflict) {
+ removeSorts = await new Promise<boolean>(resolve => {
+ confirmDialog(window.siyuan.languages.removeSorts, window.siyuan.languages.fileTreeDragRemoveSorts,
+ () => resolve(true), () => resolve(false));
+ });
+ if (!removeSorts) {
+ return;
+ }
+ }
+ const response = await fetchSyncPost("/api/filetree/reorderDocs", {...request, removeSorts});
+ if (response.code !== 0) {
+ return;
+ }
+ // 确认期间排序字段可能变化,新的冲突仍需获得确认。
+ if (response.data?.conflict && !removeSorts) {
+ return reorderSortedFileTree(sourceIDs, targetID, after);
+ }
+ return response.data;
+};
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index f5ecd17517..8d91499b2c 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1148,9 +1148,12 @@ func reorderDocs(c *gin.Context) {
defer c.JSON(http.StatusOK, ret)
request := &struct {
- SourceIDs []string `json:"sourceIDs"`
- TargetID string `json:"targetID"`
- Position string `json:"position"`
+ RespectSort bool `json:"respectSort"`
+ Preview bool `json:"preview"`
+ RemoveSorts bool `json:"removeSorts"`
+ SourceIDs []string `json:"sourceIDs"`
+ TargetID string `json:"targetID"`
+ Position string `json:"position"`
}{}
if err := c.ShouldBindJSON(request); nil != err {
ret.Code = -1
@@ -1161,6 +1164,16 @@ func reorderDocs(c *gin.Context) {
return
}
+ if request.RespectSort {
+ result, err := model.ReorderDocTree(request.SourceIDs, request.TargetID, request.Position, request.Preview, request.RemoveSorts)
+ ret.Data = result
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
+ return
+ }
+
result, err := model.ReorderDocs(request.SourceIDs, request.TargetID, request.Position)
ret.Data = result
if nil != err {
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 49cf16368c..b53ea83928 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -603,100 +603,9 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
}
start = time.Now()
- switch sortMode {
- case util.SortModeNameASC:
- emptyKey := Conf.Language(16)
- sort.Slice(docs, func(i, j int) bool {
- ni, nj := docs[i].Name, docs[j].Name
- if docs[i].TitleEmpty {
- ni = emptyKey
- }
- if docs[j].TitleEmpty {
- nj = emptyKey
- }
- return util.PinYinCompare4FileTree(ni, nj)
- })
- case util.SortModeNameDESC:
- emptyKey := Conf.Language(16)
- sort.Slice(docs, func(i, j int) bool {
- ni, nj := docs[i].Name, docs[j].Name
- if docs[i].TitleEmpty {
- ni = emptyKey
- }
- if docs[j].TitleEmpty {
- nj = emptyKey
- }
- return util.PinYinCompare4FileTree(nj, ni)
- })
- case util.SortModeUpdatedASC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].Mtime < docs[j].Mtime })
- case util.SortModeUpdatedDESC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].Mtime > docs[j].Mtime })
- case util.SortModeAlphanumASC:
- emptyKey := Conf.Language(16)
- sort.Slice(docs, func(i, j int) bool {
- ni, nj := docs[i].Name, docs[j].Name
- if docs[i].TitleEmpty {
- ni = emptyKey
- }
- if docs[j].TitleEmpty {
- nj = emptyKey
- }
- return util.NaturalCompare(ni, nj)
- })
- case util.SortModeAlphanumDESC:
- emptyKey := Conf.Language(16)
- sort.Slice(docs, func(i, j int) bool {
- ni, nj := docs[i].Name, docs[j].Name
- if docs[i].TitleEmpty {
- ni = emptyKey
- }
- if docs[j].TitleEmpty {
- nj = emptyKey
- }
- return util.NaturalCompare(nj, ni)
- })
- case util.SortModeCustom:
- fileTreeFiles := docs
- box.fillSort(&fileTreeFiles)
- sort.Slice(fileTreeFiles, func(i, j int) bool {
- if fileTreeFiles[i].Sort == fileTreeFiles[j].Sort {
- 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
- })
- ret = append(ret, fileTreeFiles...)
- totals = len(ret)
- if maxListCount < len(ret) {
- ret = ret[:maxListCount]
- }
- ret = ret[:]
- return
- case util.SortModeRefCountASC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].Count < docs[j].Count })
- case util.SortModeRefCountDESC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].Count > docs[j].Count })
- case util.SortModeCreatedASC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].CTime < docs[j].CTime })
- case util.SortModeCreatedDESC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].CTime > docs[j].CTime })
- case util.SortModeSizeASC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].Size < docs[j].Size })
- case util.SortModeSizeDESC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].Size > docs[j].Size })
- case util.SortModeSubDocCountASC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].SubFileCount < docs[j].SubFileCount })
- case util.SortModeSubDocCountDESC:
- sort.Slice(docs, func(i, j int) bool { return docs[i].SubFileCount > docs[j].SubFileCount })
- }
-
- if util.SortModeCustom != sortMode {
- ret = append(ret, docs...)
- }
+ box.fillSort(&docs)
+ sortDocTreeFiles(docs, sortMode)
+ ret = append(ret, docs...)
totals = len(ret)
if maxListCount < len(ret) {
@@ -2537,7 +2446,10 @@ func readSortConfMap(confPath string) (map[string]int, error) {
ret := map[string]int{}
if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil {
logging.LogWarnf("unmarshal sort conf [%s] failed: %s", confPath, err)
- return map[string]int{}, nil
+ return nil, err
+ }
+ if ret == nil {
+ return nil, fmt.Errorf("invalid sort conf [%s]: expected an object", confPath)
}
return ret, nil
}
diff --git a/kernel/model/file_tree_reorder.go b/kernel/model/file_tree_reorder.go
new file mode 100644
index 0000000000..5699e379e2
--- /dev/null
+++ b/kernel/model/file_tree_reorder.go
@@ -0,0 +1,209 @@
+package model
+
+import (
+ "fmt"
+ "maps"
+ "path"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// fileTreeSortLess 只比较排序规则字段,相同值由自定义顺序决定。
+func fileTreeSortLess(left, right *File, mode int) bool {
+ leftName, rightName := left.Name, right.Name
+ if left.TitleEmpty {
+ leftName = Conf.Language(16)
+ }
+ if right.TitleEmpty {
+ rightName = Conf.Language(16)
+ }
+ switch mode {
+ case util.SortModeNameASC:
+ return util.PinYinCompare4FileTree(leftName, rightName)
+ case util.SortModeNameDESC:
+ return util.PinYinCompare4FileTree(rightName, leftName)
+ case util.SortModeAlphanumASC:
+ return util.NaturalCompare(leftName, rightName) && !util.NaturalCompare(rightName, leftName)
+ case util.SortModeAlphanumDESC:
+ return util.NaturalCompare(rightName, leftName) && !util.NaturalCompare(leftName, rightName)
+ case util.SortModeUpdatedASC:
+ return left.Mtime < right.Mtime
+ case util.SortModeUpdatedDESC:
+ return left.Mtime > right.Mtime
+ case util.SortModeCreatedASC:
+ return left.CTime < right.CTime
+ case util.SortModeCreatedDESC:
+ return left.CTime > right.CTime
+ case util.SortModeRefCountASC:
+ return left.Count < right.Count
+ case util.SortModeRefCountDESC:
+ return left.Count > right.Count
+ case util.SortModeSizeASC:
+ return left.Size < right.Size
+ case util.SortModeSizeDESC:
+ return left.Size > right.Size
+ case util.SortModeSubDocCountASC:
+ return left.SubFileCount < right.SubFileCount
+ case util.SortModeSubDocCountDESC:
+ return left.SubFileCount > right.SubFileCount
+ }
+ return false
+}
+
+func sortDocTreeFiles(docs []*File, mode int) {
+ sort.SliceStable(docs, func(i, j int) bool {
+ left, right := docs[i], docs[j]
+ if fileTreeSortLess(left, right, mode) {
+ return true
+ }
+ if fileTreeSortLess(right, left, mode) {
+ return false
+ }
+ if left.Sort != right.Sort {
+ return left.Sort < right.Sort
+ }
+ return left.ID > right.ID
+ })
+}
+
+type DocTreeReorderResult struct {
+ Changed bool `json:"changed"`
+ Conflict bool `json:"conflict"`
+ Notebook string `json:"notebook"`
+ ParentPath string `json:"parentPath"`
+}
+
+// ReorderDocTree 在移动前检查完整列表,确认冲突后仅设置目标列表的排序方式。
+func ReorderDocTree(sourceIDs []string, targetID, position string, preview, removeSorts bool) (ret *DocTreeReorderResult, err error) {
+ if err = validateReorderArgs(sourceIDs, targetID, position); err != nil {
+ return
+ }
+ FlushTxQueue()
+ target := treenode.GetBlockTree(targetID)
+ if !isSortableDocument(target) || Conf.Box(target.BoxID) == nil {
+ return nil, fmt.Errorf("target document [%s] is unavailable", targetID)
+ }
+ box := Conf.Box(target.BoxID)
+ parentDir := path.Dir(target.Path)
+ confPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")
+ existingSorts, err := readSortConfMap(confPath)
+ if err != nil {
+ return nil, err
+ }
+ listPath := parentDir
+ if listPath != "/" {
+ listPath += ".sy"
+ }
+ mode, err := ResolveDocTreeSortMode(box.ID, listPath)
+ if err != nil {
+ return nil, err
+ }
+ // 隐藏文档和超过显示上限的文档也必须参与排序。
+ docs, _, err := ListDocTree(box.ID, listPath, mode, false, true, int(^uint(0)>>1))
+ if err != nil {
+ return nil, err
+ }
+ byID := map[string]*File{}
+ currentIDs := make([]string, 0, len(docs))
+ for _, doc := range docs {
+ byID[doc.ID] = doc
+ currentIDs = append(currentIDs, doc.ID)
+ }
+ siblingIDs, err := loadSiblingCustomOrder(box.ID, parentDir, existingSorts)
+ if err != nil {
+ return nil, err
+ }
+ for _, id := range siblingIDs {
+ if byID[id] == nil {
+ return nil, fmt.Errorf("document [%s] could not be read", id)
+ }
+ }
+ var fromPaths []string
+ for _, id := range sourceIDs {
+ source := treenode.GetBlockTree(id)
+ if !isSortableDocument(source) || Conf.Box(source.BoxID) == nil {
+ return nil, fmt.Errorf("source document [%s] is unavailable", id)
+ }
+ if source.BoxID == target.BoxID && (target.Path == source.Path ||
+ strings.HasPrefix(target.Path, strings.TrimSuffix(source.Path, ".sy")+"/")) {
+ return nil, fmt.Errorf("cannot move document [%s] into itself", id)
+ }
+ if byID[id] != nil {
+ continue
+ }
+ sourceParent := path.Dir(source.Path)
+ if sourceParent != "/" {
+ sourceParent += ".sy"
+ }
+ sourceDocs, _, loadErr := ListDocTree(source.BoxID, sourceParent, util.SortModeCustom, false, true, int(^uint(0)>>1))
+ if loadErr != nil {
+ return nil, loadErr
+ }
+ for _, doc := range sourceDocs {
+ if doc.ID == id {
+ byID[id] = doc
+ break
+ }
+ }
+ if byID[id] == nil {
+ return nil, fmt.Errorf("source document [%s] could not be read", id)
+ }
+ currentIDs = append(currentIDs, id)
+ fromPaths = append(fromPaths, source.Path)
+ }
+ orderedIDs, changed, err := reorderIDSequence(currentIDs, sourceIDs, targetID, position)
+ if err != nil {
+ return nil, err
+ }
+ ret = &DocTreeReorderResult{Changed: changed || len(fromPaths) > 0, Notebook: box.ID, ParentPath: listPath}
+ for i := 1; i < len(orderedIDs); i++ {
+ if fileTreeSortLess(byID[orderedIDs[i]], byID[orderedIDs[i-1]], mode) {
+ ret.Conflict = true
+ break
+ }
+ }
+ if preview || !ret.Changed || ret.Conflict && !removeSorts {
+ return ret, nil
+ }
+ if len(fromPaths) > 0 {
+ if err = MoveDocs(fromPaths, box.ID, listPath, nil); err != nil {
+ return ret, err
+ }
+ }
+ fileTreeSortLock.Lock()
+ fullSortIDs, err := readSortConfMap(confPath)
+ if err != nil {
+ fileTreeSortLock.Unlock()
+ return ret, err
+ }
+ sortIDs := map[string]int{}
+ for i, id := range orderedIDs {
+ sortIDs[id] = i + 1
+ }
+ maps.Copy(fullSortIDs, sortIDs)
+ err = writeSortConfMap(confPath, fullSortIDs)
+ fileTreeSortLock.Unlock()
+ if err != nil {
+ return ret, err
+ }
+ if ret.Conflict {
+ custom := util.SortModeCustom
+ if listPath == "/" {
+ boxConf := box.GetConf()
+ boxConf.SortMode = custom
+ if err = box.SaveConf(boxConf); err != nil {
+ return ret, err
+ }
+ PushDocSortModeChanged("notebook", box.ID, "", "/", &custom)
+ } else if _, err = SetDocSortMode(util.GetTreeID(listPath), &custom); err != nil {
+ return ret, err
+ }
+ }
+ IncSync()
+ pushFiletreeSortChanged(sortIDs)
+ return ret, nil
+}
diff --git a/kernel/model/file_tree_reorder_test.go b/kernel/model/file_tree_reorder_test.go
new file mode 100644
index 0000000000..0921713271
--- /dev/null
+++ b/kernel/model/file_tree_reorder_test.go
@@ -0,0 +1,136 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestDocTreeReorderConflictAndCompleteOrder(t *testing.T) {
+ f := setupFileOperationTest(t)
+ Conf.FileTree.Sort = util.SortModeNameASC
+ Conf.FileTree.MaxListCount = 1
+ hidden := addFileOperationTestDoc(t, f, "20260718000003-abcdefg", "Hidden", true)
+ unlisted := addFileOperationTestDoc(t, f, "20260718000004-abcdefg", "Unlisted", false)
+ confPath := filepath.Join(util.DataDir, f.box.ID, ".siyuan", "sort.json")
+ initial := map[string]int{unlisted.ID: 1, f.targetID: 2, f.sourceID: 3, hidden.ID: 4}
+ if err := writeSortConfMap(confPath, initial); err != nil {
+ t.Fatal(err)
+ }
+ for _, preview := range []bool{true, false} {
+ result, err := ReorderDocTree([]string{f.targetID}, f.sourceID, "before", preview, false)
+ if err != nil || !result.Conflict || !result.Changed {
+ t.Fatalf("unexpected conflict preview: %+v, %v", result, err)
+ }
+ actual, err := readSortConfMap(confPath)
+ if err != nil || !reflect.DeepEqual(actual, initial) {
+ t.Fatalf("unconfirmed move changed custom order: %v, %v", actual, err)
+ }
+ mode, err := ResolveDocTreeSortMode(f.box.ID, "/")
+ if err != nil || mode != util.SortModeNameASC {
+ t.Fatalf("unconfirmed move changed mode: %d, %v", mode, err)
+ }
+ }
+ result, err := ReorderDocTree([]string{f.targetID}, f.sourceID, "before", false, true)
+ if err != nil || !result.Changed {
+ t.Fatalf("confirmed move failed: %+v, %v", result, err)
+ }
+ assertSiblingCustomOrder(t, f.box.ID, "/", []string{hidden.ID, f.targetID, f.sourceID, unlisted.ID})
+ mode, err := ResolveDocTreeSortMode(f.box.ID, "/")
+ if err != nil || mode != util.SortModeCustom || Conf.FileTree.Sort != util.SortModeNameASC {
+ t.Fatalf("confirmation did not set only notebook mode: %d, %v", mode, err)
+ }
+}
+
+func TestDocTreeReorderEqualValuesPersist(t *testing.T) {
+ f := setupFileOperationTest(t)
+ Conf.FileTree.Sort = util.SortModeSubDocCountASC
+ result, err := ReorderDocTree([]string{f.sourceID}, f.targetID, "before", false, false)
+ if err != nil || result.Conflict || !result.Changed {
+ t.Fatalf("equal-value move failed: %+v, %v", result, err)
+ }
+ files, _, err := ListDocTree(f.box.ID, "/", util.SortModeUnassigned, false, true, 100)
+ if err != nil || len(files) != 2 || files[0].ID != f.sourceID || files[1].ID != f.targetID {
+ t.Fatalf("manual tie order was not displayed: %+v, %v", files, err)
+ }
+ mode, err := ResolveDocTreeSortMode(f.box.ID, "/")
+ if err != nil || mode != util.SortModeSubDocCountASC {
+ t.Fatalf("equal-value move changed sort rule: %d, %v", mode, err)
+ }
+ result, err = ReorderDocTree([]string{f.sourceID}, f.targetID, "before", false, false)
+ if err != nil || result.Changed {
+ t.Fatalf("repeated move should be a no-op: %+v, %v", result, err)
+ }
+}
+
+func TestDocTreeReorderRejectsUnreadableSort(t *testing.T) {
+ f := setupFileOperationTest(t)
+ confPath := filepath.Join(util.DataDir, f.box.ID, ".siyuan", "sort.json")
+ bad := []byte("invalid sort data")
+ if err := os.WriteFile(confPath, bad, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ReorderDocTree([]string{f.sourceID}, f.targetID, "before", false, true); err == nil {
+ t.Fatal("invalid sort data was accepted")
+ }
+ actual, err := os.ReadFile(confPath)
+ if err != nil || string(actual) != string(bad) {
+ t.Fatalf("invalid sort data was overwritten: %s, %v", actual, err)
+ }
+}
+
+func TestDocTreeSortAllModesRespectTies(t *testing.T) {
+ for mode := util.SortModeNameASC; mode <= util.SortModeSubDocCountDESC; mode++ {
+ left := &File{ID: "20260718000001-abcdefg", Name: "Same", Sort: 1}
+ right := &File{ID: "20260718000002-abcdefg", Name: "Same", Sort: 2}
+ docs := []*File{right, left}
+ sortDocTreeFiles(docs, mode)
+ if docs[0] != left || fileTreeSortLess(left, right, mode) || fileTreeSortLess(right, left, mode) {
+ t.Fatalf("mode %d did not preserve manual tie order", mode)
+ }
+ }
+}
+
+func TestDocTreeReorderCrossParentPreviewDoesNotMove(t *testing.T) {
+ f := setupFileOperationTest(t)
+ Conf.FileTree.Sort = util.SortModeNameASC
+ childPath := "/" + f.sourceID + "/20260718000003-abcdefg.sy"
+ child := treenode.NewTree(f.box.ID, childPath, "/Source/A", "A")
+ if _, err := filesys.WriteTree(child); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(child)
+ t.Cleanup(func() {
+ cache.RemoveTreeData(child.ID)
+ cache.RemoveDocIAL(child.Path)
+ })
+ for _, preview := range []bool{true, false} {
+ result, err := ReorderDocTree([]string{f.targetID}, child.ID, "before", preview, false)
+ if err != nil || !result.Conflict || result.ParentPath != f.sourcePath {
+ t.Fatalf("unexpected inherited sort preview: %+v, %v", result, err)
+ }
+ if source := treenode.GetBlockTree(f.targetID); source == nil || source.Path != f.targetPath {
+ t.Fatalf("unconfirmed cross-parent drag moved the source: %+v", source)
+ }
+ if _, err := os.Stat(filepath.Join(util.DataDir, f.box.ID, f.targetPath)); err != nil {
+ t.Fatalf("source file was moved: %v", err)
+ }
+ }
+}
+
+func TestDocTreeReorderMultipleSourcesKeepSelectionOrder(t *testing.T) {
+ f := setupFileOperationTest(t)
+ Conf.FileTree.Sort = util.SortModeNameASC
+ extra := addFileOperationTestDoc(t, f, "20260718000003-abcdefg", "Z", false)
+ result, err := ReorderDocTree([]string{extra.ID, f.targetID}, f.sourceID, "before", false, true)
+ if err != nil || !result.Conflict {
+ t.Fatalf("multi-document reorder failed: %+v, %v", result, err)
+ }
+ assertSiblingCustomOrder(t, f.box.ID, "/", []string{extra.ID, f.targetID, f.sourceID})
+}