Skip to content

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

:sparkles: Support per-document child sorting rules https://github.com/siyuan-note/siyuan/issues/11688

Daniel1f25b42dc5a3
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 94b0affa2c..fa69c8d6a2 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "استخدام قواعد الفرز للمستوى الأعلى",
"agentUserSkills": "المهارات الخارجية",
"agentUserSkillsTip": "فعّل بشكل فردي مهارات القراءة فقط من ~/.agents/skills؛ قد لا تكون المهارات الخارجية متوافقة مع أدوات SiYuan",
"agentUserSkillsEmpty": "لم يتم العثور على مهارات في ~/.agents/skills",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 634956d70c..b346d92c4d 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Sortierregeln des übergeordneten Elements verwenden",
"agentUserSkills": "Externe Skills",
"agentUserSkillsTip": "Schreibgeschützte Skills aus ~/.agents/skills einzeln aktivieren; externe Skills sind möglicherweise nicht mit den SiYuan-Werkzeugen kompatibel",
"agentUserSkillsEmpty": "Keine Skills in ~/.agents/skills gefunden",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index ec6717d2be..dd87f4eb20 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Use parent sorting rules",
"agentUserSkills": "External skills",
"agentUserSkillsTip": "Individually enable read-only skills from ~/.agents/skills; external skills may be incompatible with SiYuan tools",
"agentUserSkillsEmpty": "No skills found in ~/.agents/skills",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index b5d2af9453..4c222af50c 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Usar las reglas de ordenación del elemento superior",
"agentUserSkills": "Habilidades externas",
"agentUserSkillsTip": "Activa individualmente las habilidades de solo lectura de ~/.agents/skills; las habilidades externas pueden ser incompatibles con las herramientas de SiYuan",
"agentUserSkillsEmpty": "No se encontraron habilidades en ~/.agents/skills",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index ae888f43dc..975c73ea91 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Utiliser les règles de tri de l’élément parent",
"agentUserSkills": "Compétences externes",
"agentUserSkillsTip": "Activez individuellement les compétences en lecture seule depuis ~/.agents/skills ; les compétences externes peuvent être incompatibles avec les outils SiYuan",
"agentUserSkillsEmpty": "Aucune compétence trouvée dans ~/.agents/skills",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 52537d5bba..663cf6a975 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "השתמש בכללי המיון של פריט האב",
"agentUserSkills": "מיומנויות חיצוניות",
"agentUserSkillsTip": "הפעל בנפרד מיומנויות לקריאה בלבד מתוך ~/.agents/skills; ייתכן שמיומנויות חיצוניות לא יתאימו לכלי SiYuan",
"agentUserSkillsEmpty": "לא נמצאו מיומנויות ב־~/.agents/skills",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 6fece99d5b..106e7dca5f 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "ऊपरी स्तर के क्रमबद्धता नियमों का उपयोग करें",
"agentUserSkills": "बाहरी कौशल",
"agentUserSkillsTip": "~/.agents/skills से केवल-पढ़ने योग्य कौशल अलग-अलग सक्षम करें; बाहरी कौशल SiYuan टूल के साथ असंगत हो सकते हैं",
"agentUserSkillsEmpty": "~/.agents/skills में कोई कौशल नहीं मिला",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 96f2a1e309..4ef3fb93aa 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Gunakan aturan pengurutan induk",
"agentUserSkills": "Keterampilan eksternal",
"agentUserSkillsTip": "Aktifkan keterampilan hanya-baca dari ~/.agents/skills satu per satu; keterampilan eksternal mungkin tidak kompatibel dengan alat SiYuan",
"agentUserSkillsEmpty": "Tidak ada keterampilan yang ditemukan di ~/.agents/skills",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 9d1be331cc..540b9ef0c9 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Usa le regole di ordinamento dell'elemento padre",
"agentUserSkills": "Competenze esterne",
"agentUserSkillsTip": "Abilita singolarmente le competenze di sola lettura da ~/.agents/skills; le competenze esterne potrebbero non essere compatibili con gli strumenti di SiYuan",
"agentUserSkillsEmpty": "Nessuna competenza trovata in ~/.agents/skills",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 8527b8ddf9..3f993441a0 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "親の並べ替えルールを使う",
"agentUserSkills": "外部スキル",
"agentUserSkillsTip": "~/.agents/skills の読み取り専用スキルを個別に有効にします。外部スキルは SiYuan のツールと互換性がない場合があります",
"agentUserSkillsEmpty": "~/.agents/skills にスキルが見つかりません",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index acfa589f94..3e028acc43 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "상위 항목의 정렬 규칙 사용",
"agentUserSkills": "외부 스킬",
"agentUserSkillsTip": "~/.agents/skills의 읽기 전용 스킬을 개별적으로 활성화합니다. 외부 스킬은 SiYuan 도구와 호환되지 않을 수 있습니다",
"agentUserSkillsEmpty": "~/.agents/skills에서 스킬을 찾을 수 없습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 05696b398f..33ee3906b9 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Sorteerregels van bovenliggend item gebruiken",
"agentUserSkills": "Externe vaardigheden",
"agentUserSkillsTip": "Schakel alleen-lezenvaardigheden uit ~/.agents/skills afzonderlijk in; externe vaardigheden zijn mogelijk niet compatibel met SiYuan-hulpmiddelen",
"agentUserSkillsEmpty": "Geen vaardigheden gevonden in ~/.agents/skills",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 901aac4513..1eb26f0962 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Użyj reguł sortowania elementu nadrzędnego",
"agentUserSkills": "Umiejętności zewnętrzne",
"agentUserSkillsTip": "Włączaj osobno umiejętności tylko do odczytu z ~/.agents/skills; zewnętrzne umiejętności mogą być niezgodne z narzędziami SiYuan",
"agentUserSkillsEmpty": "Nie znaleziono umiejętności w ~/.agents/skills",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 64d42ca5fc..19091aeba1 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Usar regras de ordenação do item pai",
"agentUserSkills": "Habilidades externas",
"agentUserSkillsTip": "Ative individualmente as habilidades somente leitura de ~/.agents/skills; habilidades externas podem ser incompatíveis com as ferramentas do SiYuan",
"agentUserSkillsEmpty": "Nenhuma habilidade encontrada em ~/.agents/skills",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index aabf496032..f32ed8fa1d 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Использовать правила сортировки родительского элемента",
"agentUserSkills": "Внешние навыки",
"agentUserSkillsTip": "Включайте по отдельности навыки только для чтения из ~/.agents/skills; внешние навыки могут быть несовместимы с инструментами SiYuan",
"agentUserSkillsEmpty": "В ~/.agents/skills навыки не найдены",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 7abacbf83d..d80d5814b4 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Použiť pravidlá radenia nadradenej položky",
"agentUserSkills": "Externé zručnosti",
"agentUserSkillsTip": "Jednotlivo povoľte zručnosti iba na čítanie z ~/.agents/skills; externé zručnosti nemusia byť kompatibilné s nástrojmi SiYuan",
"agentUserSkillsEmpty": "V ~/.agents/skills sa nenašli žiadne zručnosti",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index e0ccdb0164..9d91ae47bf 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "ใช้กฎการเรียงลำดับของระดับบน",
"agentUserSkills": "ทักษะภายนอก",
"agentUserSkillsTip": "เปิดใช้ทักษะแบบอ่านอย่างเดียวจาก ~/.agents/skills ทีละรายการ ทักษะภายนอกอาจไม่เข้ากันกับเครื่องมือของ SiYuan",
"agentUserSkillsEmpty": "ไม่พบทักษะใน ~/.agents/skills",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 729f991bef..0c0b034d05 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Üst öğenin sıralama kurallarını kullan",
"agentUserSkills": "Harici beceriler",
"agentUserSkillsTip": "~/.agents/skills içindeki salt okunur becerileri ayrı ayrı etkinleştirin; harici beceriler SiYuan araçlarıyla uyumlu olmayabilir",
"agentUserSkillsEmpty": "~/.agents/skills içinde beceri bulunamadı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index bc733cb71c..2d41c2e4fe 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "Використовувати правила сортування батьківського елемента",
"agentUserSkills": "Зовнішні навички",
"agentUserSkillsTip": "Вмикайте окремо навички лише для читання з ~/.agents/skills; зовнішні навички можуть бути несумісними з інструментами SiYuan",
"agentUserSkillsEmpty": "У ~/.agents/skills навичок не знайдено",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 9e66cbf8ae..a800da294f 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "使用父级排序规则",
"agentUserSkills": "外部技能",
"agentUserSkillsTip": "逐个启用 ~/.agents/skills 中的只读技能;外部技能可能与 SiYuan 工具不兼容",
"agentUserSkillsEmpty": "未在 ~/.agents/skills 中找到技能",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 2831692f70..d84eb8d85f 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "sortByParent": "使用父級排序規則",
"agentUserSkills": "外部技能",
"agentUserSkillsTip": "逐一啟用 ~/.agents/skills 中的唯讀技能;外部技能可能與 SiYuan 工具不相容",
"agentUserSkillsEmpty": "未在 ~/.agents/skills 中找到技能",
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 926b89114f..3f3c66f700 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -176,6 +176,52 @@ test("multiple document and notebook entries follow their document tree menus",
assert.ok(getEntryCatalogChildren("docTree.multi").some((item) => item.key === "delete"));
});
+test("document tree sort menus follow their scope inheritance options", () => {
+ const documentEntries = getEntryCatalogChildren("docTree.document");
+ const attrIndex = documentEntries.findIndex((item) => item.key === "attr");
+ assert.deepEqual(documentEntries.slice(attrIndex, attrIndex + 3).map((item) => item.key), [
+ "attr",
+ "sort",
+ "riffCard",
+ ]);
+
+ const commonSortEntries = [
+ "fileNameASC",
+ "fileNameDESC",
+ "fileNameNatASC",
+ "fileNameNatDESC",
+ "separator_1",
+ "createdASC",
+ "createdDESC",
+ "modifiedASC",
+ "modifiedDESC",
+ "separator_2",
+ "refCountASC",
+ "refCountDESC",
+ "separator_3",
+ "docSizeASC",
+ "docSizeDESC",
+ "separator_4",
+ "subDocCountASC",
+ "subDocCountDESC",
+ "separator_5",
+ "customSort",
+ ];
+ assert.deepEqual(getEntryCatalogChildren("docTree.panel.sort").map((item) => item.key), commonSortEntries);
+ assert.deepEqual(getEntryCatalogChildren("docTree.notebooks.sort").map((item) => item.key), [
+ ...commonSortEntries,
+ "sortByFiletree",
+ ]);
+ assert.deepEqual(getEntryCatalogChildren("docTree.notebook.sort").map((item) => item.key), [
+ ...commonSortEntries,
+ "sortByFiletree",
+ ]);
+ assert.deepEqual(getEntryCatalogChildren("docTree.document.sort").map((item) => item.key), [
+ ...commonSortEntries,
+ "sortByParent",
+ ]);
+});
+
test("multiple document and notebook settings have distinct labels", () => {
const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
Object.defineProperty(globalThis, "window", {
@@ -237,6 +283,8 @@ test("simple profile follows the reviewed defaults", () => {
"document.more.keepLazyLoad",
"document.more.headingNumber",
"docTree.notebook.sort.fileNameNatASC",
+ "docTree.document.sort.fileNameNatASC",
+ "docTree.document.sort.sortByParent",
];
const hidden = [
"document.title.copy.copyDoc",
@@ -248,6 +296,7 @@ test("simple profile follows the reviewed defaults", () => {
"document.more.netAssets2LocalAssets",
"document.more.fullWidth",
"docTree.notebook.sort.fileNameASC",
+ "docTree.document.sort.fileNameASC",
"inline.image.copyFile",
];
shown.forEach((path) => assert.equal(getEntryCatalogNode(path)?.simple, true, path));
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 7f3519c657..fb667061ff 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -47,7 +47,7 @@ const copyChildren = () => [
node("copyID", lang("copyID"), false),
];
-const sortChildren = () => [
+const sortChildren = (inheritKey?: "sortByFiletree" | "sortByParent") => [
node("fileNameASC", lang("fileNameASC"), false),
node("fileNameDESC", lang("fileNameDESC"), false),
node("fileNameNatASC", lang("fileNameNatASC")),
@@ -68,7 +68,7 @@ const sortChildren = () => [
node("subDocCountDESC", lang("subDocCountDESC")),
separator("separator_5"),
node("customSort", lang("customSort")),
- node("sortByFiletree", lang("sortByFiletree")),
+ ...(inheritKey ? [node(inheritKey, lang(inheritKey))] : []),
];
const exportChildren = () => [
@@ -144,6 +144,7 @@ const docTreeDocument = () => {
separator("separator_2"),
node("rename", lang("rename")),
node("attr", lang("attr")),
+ node("sort", lang("sort"), true, sortChildren("sortByParent")),
riffCard,
node("search", lang("search")),
node("replace", lang("replace")),
@@ -438,7 +439,7 @@ export const entryCatalog: IEntryCatalogSection[] = [
node("openDocument", lang("openDocument")),
node("rename", lang("rename")),
node("config", lang("config")),
- node("sort", lang("sort"), true, sortChildren()),
+ node("sort", lang("sort"), true, sortChildren("sortByFiletree")),
node("riffCard", lang("riffCard"), false),
node("search", lang("search")),
node("replace", lang("replace")),
@@ -468,7 +469,7 @@ export const entryCatalog: IEntryCatalogSection[] = [
key: "docTree.notebooks",
label: location(lang("entryDocPanel"), lang("agentCatNotebook"), lang("multiSelect"), lang("more")),
children: [
- node("sort", lang("sort"), true, sortChildren()),
+ node("sort", lang("sort"), true, sortChildren("sortByFiletree")),
node("search", lang("search")),
node("replace", lang("replace")),
separator("separator_1"),
diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.ts
index 1a0e6db9fd..5d9d656bc5 100644
--- a/app/src/config/entryVisibility/order.test.ts
+++ b/app/src/config/entryVisibility/order.test.ts
@@ -13,6 +13,13 @@ test("entry order inserts the code block Tab setting before the existing code op
), ["saveCodeBlockAsFile", "md27", "md29", "md31", "md2"]);
});
+test("entry order inserts document sorting after attributes in existing profiles", () => {
+ assert.deepEqual(mergeEntryOrder(
+ ["rename", "attr", "sort", "riffCard", "search"],
+ ["search", "rename", "attr", "riffCard"],
+ ), ["search", "rename", "attr", "sort", "riffCard"]);
+});
+
test("entry order ignores unknown and duplicate keys", () => {
assert.deepEqual(mergeEntryOrder(["a", "b", "c"], ["missing", "c", "c", "a"]), ["c", "a", "b"]);
});
diff --git a/app/src/index.ts b/app/src/index.ts
index 2492119b8e..4eff5a34ba 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -234,6 +234,13 @@ export class App {
}
break;
}
+ case "docSortModeChanged": {
+ const fileDock = getDockByType("file");
+ if (fileDock) {
+ (fileDock.data.file as Files).onDocSortModeChanged(data.data);
+ }
+ break;
+ }
case "notebookSortChanged": {
const fileDock = getDockByType("file");
if (fileDock) {
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 4f6ce693aa..88dec574e8 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -20,7 +20,6 @@ import {newEncryptedNotebook, newNotebook, openEncryptedNotebook} from "../../ut
import {isNotCtrl, isOnlyMeta, setStorageVal, updateHotkeyAfterTip} from "../../protyle/util/compatibility";
import {openFileById} from "../../editor/util";
import {
- hasClosestByAttribute,
hasClosestByClassName,
hasClosestByTag,
hasTopClosestByTag
@@ -51,6 +50,14 @@ import {
restoreMovedExpandedDocItems,
updateMovedSubtree
} from "../../util/fileTreeMove";
+import {
+ FILE_TREE_CHILDREN_SORT_MODE,
+ FILE_TREE_EFFECTIVE_SORT_MODE,
+ getResponseEffectiveSortMode,
+ isCustomFileTreeList,
+ type IDocSortModeChanged,
+ updateFileTreeSortMode
+} from "../../util/fileTreeSort";
export class Files extends Model {
public element: HTMLElement;
@@ -59,6 +66,7 @@ export class Files extends Model {
public lastSelectedElement: Element = null;
private actionsElement: HTMLElement;
private reloadNotebookInfoTimeout: number;
+ private docSortModeRefreshTimeout: number;
private movedExpandedDocIDs = new Set<string>();
constructor(options: { tab: Tab, app: App }) {
@@ -608,16 +616,15 @@ export class Files extends Model {
}
}
if (dragOverLastObj.element && dragOverLastObj.element === liElement && dragOverLastObj.positionY !== event.clientY) {
- const notebookElement = hasClosestByAttribute(liElement, "data-sortmode", null);
- if (!notebookElement) {
+ const targetListElement = liElement.parentElement;
+ if (!targetListElement) {
hideDragTip();
event.preventDefault();
return;
}
- const notebookSort = notebookElement.getAttribute("data-sortmode");
if ((dragOverLastObj.sourceOnlyRoot && targetType === "navigation-root" && window.siyuan.config.fileTree.sort === 6) ||
(!dragOverLastObj.sourceOnlyRoot && targetType !== "navigation-root" &&
- (notebookSort === "6" || (window.siyuan.config.fileTree.sort === 6 && notebookSort === "15")))
+ isCustomFileTreeList(targetListElement))
) {
const nodeRect = liElement.getBoundingClientRect();
const dragHeight = nodeRect.height * .2;
@@ -820,7 +827,7 @@ export class Files extends Model {
return;
}
if (newElement.classList.contains("dragover__bottom") || newElement.classList.contains("dragover__top")) {
- const ulSort = newUlElement.getAttribute("data-sortmode");
+ const targetListElement = newElement.parentElement;
if (window.siyuan.config.fileTree.sort === 6 && selectRootElements.length > 0 &&
newElement.getAttribute("data-path") === "/") {
if (newElement.classList.contains("dragover__top")) {
@@ -839,7 +846,7 @@ export class Files extends Model {
fetchPost("/api/notebook/changeSortNotebook", {
notebooks,
});
- } else if ((ulSort === "6" || (window.siyuan.config.fileTree.sort === 6 && ulSort === "15")) && selectFileElements.length > 0) {
+ } else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
const toDir = pathPosix().dirname(toPath);
const newElementClassList = newElement.getAttribute("class");
const sourceNotebookIds = selectFileElements.map((item) =>
@@ -984,8 +991,7 @@ export class Files extends Model {
return;
}
- const notebookSort = notebookElement.getAttribute("data-sortmode");
- if (notebookSort !== "6" && !(window.siyuan.config.fileTree.sort === 6 && notebookSort === "15")) {
+ if (!isCustomFileTreeList(targetElement.parentElement)) {
return;
}
const targetDirectory = pathPosix().dirname(targetPath);
@@ -1501,14 +1507,10 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
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") {
+ const listElement = liElement?.nextElementSibling;
+ if (!listElement || listElement.tagName !== "UL" || !isCustomFileTreeList(listElement)) {
return;
}
fetchPost("/api/filetree/listDocsByPath", {
@@ -1520,6 +1522,14 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
});
}
+ public onDocSortModeChanged(data?: IDocSortModeChanged) {
+ updateFileTreeSortMode(data);
+ window.clearTimeout(this.docSortModeRefreshTimeout);
+ this.docSortModeRefreshTimeout = window.setTimeout(() => {
+ this.init(false);
+ }, 100);
+ }
+
public onNotebookSortChanged() {
if (window.siyuan.config.fileTree.sort !== 6) {
return;
@@ -1530,8 +1540,12 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
}
private onMove(response: IWebSocketData) {
+ const moves = response.data.moves as IFileTreeMove[];
+ const needsSortModeRefresh = moves.some((move) =>
+ move.fromNotebook !== move.toNotebook ||
+ pathPosix().dirname(move.fromPath) !== pathPosix().dirname(move.newPath));
const refreshTargets = new Map<string, { element: HTMLElement, notebookId: string }>();
- (response.data.moves as IFileTreeMove[]).forEach((move) => {
+ moves.forEach((move) => {
const expandedDocIDs = new Set<string>();
const movedItem = findMovedFileTreeItem(this.element, move);
const sourceElement = movedItem?.element;
@@ -1621,6 +1635,11 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
});
}
});
+ if (needsSortModeRefresh) {
+ this.getOpenPaths();
+ this.onDocSortModeChanged();
+ return;
+ }
if (response.callback !== Constants.CB_MOVE_NOLIST) {
refreshTargets.forEach((target) => {
this.getLeaf(target.element, target.notebookId, true);
@@ -1634,7 +1653,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
});
}
- private onLsHTML(data: { files: IFile[], box: string, path: string }, scrollTop?: number) {
+ private onLsHTML(data: IFileTreeList, scrollTop?: number) {
if (data.files.length === 0) {
return;
}
@@ -1646,6 +1665,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
data.files.forEach((item: IFile) => {
fileHTML += this.genFileHTML(item);
});
+ const effectiveSortMode = getResponseEffectiveSortMode(data, data.box);
let nextElement = liElement.nextElementSibling;
if (nextElement && nextElement.tagName === "UL") {
// 文件展开时,刷新
@@ -1663,6 +1683,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
}
});
nextElement.innerHTML = tempElement.innerHTML;
+ nextElement.setAttribute(FILE_TREE_EFFECTIVE_SORT_MODE, effectiveSortMode.toString());
this.restoreMovedExpandedItems(nextElement, data.box);
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
@@ -1671,7 +1692,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
return;
}
liElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
- liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
+ liElement.insertAdjacentHTML("afterend", `<ul ${FILE_TREE_EFFECTIVE_SORT_MODE}="${effectiveSortMode}">${fileHTML}</ul>`);
nextElement = liElement.nextElementSibling;
this.restoreMovedExpandedItems(nextElement, data.box);
expandFileTree(nextElement as HTMLElement, () => {
@@ -1682,11 +1703,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
this.refreshPublishAccessSwitch();
}
- private async onLsSelect(data: {
- files: IFile[],
- box: string,
- path: string
- }, filePath: string, setStorage: boolean, isSetCurrent: boolean) {
+ private async onLsSelect(data: IFileTreeList, filePath: string, setStorage: boolean, isSetCurrent: boolean) {
let fileHTML = "";
data.files.forEach((item: IFile) => {
fileHTML += this.genFileHTML(item);
@@ -1709,7 +1726,8 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
if (emojiElement.textContent === unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].file)) {
emojiElement.textContent = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder);
}
- liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
+ const effectiveSortMode = getResponseEffectiveSortMode(data, data.box);
+ liElement.insertAdjacentHTML("afterend", `<ul ${FILE_TREE_EFFECTIVE_SORT_MODE}="${effectiveSortMode}">${fileHTML}</ul>`);
this.restoreMovedExpandedItems(liElement.nextElementSibling, data.box);
let newLiElement;
for (let i = 0; i < data.files.length; i++) {
@@ -1788,11 +1806,8 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
});
}
- public async selectItem(notebookId: string, filePath: string, data?: {
- files: IFile[],
- box: string,
- path: string
- }, setStorage = true, isSetCurrent = true) {
+ public async selectItem(notebookId: string, filePath: string, data?: IFileTreeList,
+ setStorage = true, isSetCurrent = true) {
filePath = filePath.replace(/\/\/+/g, "/");
const treeElement = this.element.querySelector(`[data-url="${notebookId}"]`);
if (!treeElement) {
@@ -1904,7 +1919,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
const actionClasses = `${iconExpands && item.subFileCount > 0 && !editingPublishAccess ? " file-tree__item--icon-expand" : ""}${
iconExpands && item.subFileCount === 0 && !editingPublishAccess ? " file-tree__item--icon-open" : ""}${
window.siyuan.config.fileTree.parentDocClickExpand && item.subFileCount > 0 ? " file-tree__item--title-expand" : ""}`;
- return `<li data-node-id="${item.id}" data-name="${Lute.EscapeHTMLStr(item.name)}" draggable="true" data-count="${item.subFileCount}"
+ return `<li data-node-id="${item.id}" data-name="${Lute.EscapeHTMLStr(item.name)}" draggable="true" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}"
data-type="navigation-file"
style="--file-toggle-width:${paddingLeft + 18}px;--file-action-offset:${paddingLeft + 20}px"
class="b3-list-item b3-list-item--hide-action${actionClasses}" data-path="${item.path}">
@@ -1963,7 +1978,10 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}
}
}).element);
if (!window.siyuan.config.readonly) {
- const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort: number) => {
+ const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {
+ if (sort === null) {
+ return;
+ }
fetchPost("/api/setting/setFiletree", {
...window.siyuan.config.fileTree,
sort,
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 734d6391cb..7eb933e6b8 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -17,7 +17,7 @@ import {popSearch} from "../mobile/menu/search";
/// #endif
import {Constants} from "../constants";
import {newFileInTree} from "../util/newFile";
-import {hasClosestByTag, hasTopClosestByTag} from "../protyle/util/hasClosest";
+import {hasClosestByTag} from "../protyle/util/hasClosest";
import {deleteFiles, deleteNotebooks} from "../editor/deleteFile";
/// #if !MOBILE
import {openFileById} from "../editor/util";
@@ -36,6 +36,11 @@ import {saveExportFile} from "../protyle/util/compatibility";
import {exportMarkdownZip} from "../protyle/export/exportMd";
import {addFilesToDatabase} from "../protyle/render/av/addToDatabase";
import {getDocTreeMenuItems, getDocTreeMenuType} from "./navigationSelection";
+import {
+ FILE_TREE_CHILDREN_SORT_MODE,
+ getConfiguredChildrenSortMode,
+ isCustomFileTreeList
+} from "../util/fileTreeSort";
/// #if MOBILE
import {openEmojiPanel} from "../emoji";
import {openMobileFileByIdInNewTab} from "../mobile/editor";
@@ -62,12 +67,16 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
const sortModes = selectedItems.map((item) => parseInt(item.parentElement?.getAttribute("data-sortmode")));
const sortMode = sortModes.every((item) => item === sortModes[0]) ? sortModes[0] : -1;
const subMenu = sortMenu("notebook", sortMode, async (sort) => {
+ if (sort === null) {
+ return;
+ }
let files;
/// #if MOBILE
files = window.siyuan.mobile.docks.file;
/// #else
files = (getDockByType("file").data["file"] as Files);
/// #endif
+ let sortModeChanged = false;
for (const item of selectedItems) {
const notebookId = item.parentElement?.getAttribute("data-url");
if (!notebookId) {
@@ -81,12 +90,14 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
continue;
}
item.parentElement.setAttribute("data-sortmode", sort.toString());
- const toggleElement = item.querySelector(".b3-list-item__arrow--open");
- if (toggleElement) {
- toggleElement.classList.remove("b3-list-item__arrow--open");
- item.nextElementSibling?.remove();
- files.getLeaf(item, notebookId);
+ const notebook = window.siyuan.notebooks.find((notebookItem) => notebookItem.id === notebookId);
+ if (notebook) {
+ notebook.sortMode = sort;
}
+ sortModeChanged = true;
+ }
+ if (sortModeChanged) {
+ files?.onDocSortModeChanged();
}
});
window.siyuan.menus.menu.append(new MenuItem({
@@ -453,12 +464,18 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {
}
}).element);
const subMenu = sortMenu("notebook", parseInt(liElement.parentElement.getAttribute("data-sortmode")), (sort) => {
+ if (sort === null) {
+ return;
+ }
fetchPost("/api/notebook/setNotebookConf", {
notebook: notebookId,
conf: {
sortMode: sort
}
- }, () => {
+ }, (response) => {
+ if (response.code !== 0) {
+ return;
+ }
liElement.parentElement.setAttribute("data-sortmode", sort.toString());
let files;
/// #if MOBILE
@@ -466,12 +483,11 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {
/// #else
files = (getDockByType("file").data["file"] as Files);
/// #endif
- const toggleElement = liElement.querySelector(".b3-list-item__arrow--open");
- if (toggleElement) {
- toggleElement.classList.remove("b3-list-item__arrow--open");
- liElement.nextElementSibling?.remove();
- files.getLeaf(liElement, notebookId);
+ const notebook = window.siyuan.notebooks.find((item) => item.id === notebookId);
+ if (notebook) {
+ notebook.sortMode = sort;
}
+ files?.onDocSortModeChanged();
});
return true;
});
@@ -691,8 +707,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
}
/// #endif
if (!window.siyuan.config.readonly) {
- const topElement = hasTopClosestByTag(liElement, "UL");
- if (window.siyuan.config.fileTree.sort === 6 || (topElement && topElement.dataset.sortmode === "6")) {
+ if (isCustomFileTreeList(liElement.parentElement)) {
window.siyuan.menus.menu.append(new MenuItem({
id: "newDocAbove",
icon: "iconBefore",
@@ -791,6 +806,32 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
});
}
}).element);
+ const configuredSortMode = getConfiguredChildrenSortMode(liElement);
+ const sortSubMenu = sortMenu("document", configuredSortMode, (sortMode) => {
+ fetchPost("/api/filetree/setDocSortMode", {
+ id,
+ sortMode,
+ }, (response) => {
+ if (response.code !== 0) {
+ return;
+ }
+ liElement.setAttribute(FILE_TREE_CHILDREN_SORT_MODE, sortMode?.toString() || "");
+ let files;
+ /// #if MOBILE
+ files = window.siyuan.mobile.docks.file;
+ /// #else
+ files = (getDockByType("file").data["file"] as Files);
+ /// #endif
+ files?.onDocSortModeChanged();
+ });
+ });
+ window.siyuan.menus.menu.append(new MenuItem({
+ id: "sort",
+ icon: "iconSort",
+ label: window.siyuan.languages.sort,
+ type: "submenu",
+ submenu: sortSubMenu,
+ }).element);
if (!window.siyuan.config.readonly && !isEncryptedBox(notebookId)) {
const riffCardMenu = [{
id: "spaceRepetition",
@@ -1050,7 +1091,8 @@ export const genImportMenu = (notebookId: string, pathString: string) => {
}).element);
};
-export const sortMenu = (type: "notebooks" | "notebook", sortMode: number, clickEvent: (sort: number) => void) => {
+export const sortMenu = (type: "notebooks" | "notebook" | "document", sortMode: number | null,
+ clickEvent: (sort: number | null) => void) => {
const sortMenu: IMenu[] = [{
id: "fileNameASC",
checked: sortMode === 0,
@@ -1182,6 +1224,16 @@ export const sortMenu = (type: "notebooks" | "notebook", sortMode: number, click
clickEvent(15);
}
});
+ } else if (type === "document") {
+ sortMenu.push({
+ id: "sortByParent",
+ checked: sortMode === null,
+ iconHTML: "",
+ label: window.siyuan.languages.sortByParent,
+ click: () => {
+ clickEvent(null);
+ }
+ });
}
return sortMenu;
};
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index 5fd8c298e9..7afc668119 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -37,12 +37,21 @@ import {
restoreMovedExpandedDocItems,
updateMovedSubtree
} from "../../util/fileTreeMove";
+import {
+ FILE_TREE_CHILDREN_SORT_MODE,
+ FILE_TREE_EFFECTIVE_SORT_MODE,
+ getResponseEffectiveSortMode,
+ isCustomFileTreeList,
+ type IDocSortModeChanged,
+ updateFileTreeSortMode
+} from "../../util/fileTreeSort";
export class MobileFiles extends Model {
public element: HTMLElement;
private actionsElement: HTMLElement;
private closeElement: HTMLElement;
private reloadNotebookInfoTimeout: number;
+ private docSortModeRefreshTimeout: number;
private movedExpandedDocIDs = new Set<string>();
private touchDragState: {
selectedElement: HTMLElement;
@@ -271,10 +280,6 @@ export class MobileFiles extends Model {
if (dataType === "navigation-root") {
if (window.siyuan.config.fileTree.sort !== 6) return;
- } else {
- const ulElement = liElement.closest("ul[data-sortmode]") as HTMLElement;
- const sortMode = ulElement?.getAttribute("data-sortmode");
- if (sortMode !== "6" && !(window.siyuan.config.fileTree.sort === 6 && sortMode === "15")) return;
}
this.touchDragState = {
isDragging: false,
@@ -350,11 +355,13 @@ export class MobileFiles extends Model {
}
return;
}
- const dragHeight = liRect.height * .2;
- if (touch.clientY > liRect.bottom - dragHeight) {
- liElement.classList.add("dragover__bottom");
- } else if (touch.clientY < liRect.top + dragHeight) {
- liElement.classList.add("dragover__top");
+ if (isCustomFileTreeList(liElement.parentElement)) {
+ const dragHeight = liRect.height * .2;
+ if (touch.clientY > liRect.bottom - dragHeight) {
+ liElement.classList.add("dragover__bottom");
+ } else if (touch.clientY < liRect.top + dragHeight) {
+ liElement.classList.add("dragover__top");
+ }
}
if (!liElement.classList.contains("dragover__top") && !liElement.classList.contains("dragover__bottom") &&
@@ -423,7 +430,7 @@ export class MobileFiles extends Model {
return;
}
if (newElement.classList.contains("dragover__bottom") || newElement.classList.contains("dragover__top")) {
- const ulSort = newUlElement.getAttribute("data-sortmode");
+ const targetListElement = newElement.parentElement;
if (window.siyuan.config.fileTree.sort === 6 && selectRootElements.length > 0 &&
newElement.getAttribute("data-path") === "/") {
if (newElement.classList.contains("dragover__top")) {
@@ -442,7 +449,7 @@ export class MobileFiles extends Model {
fetchPost("/api/notebook/changeSortNotebook", {
notebooks,
});
- } else if ((ulSort === "6" || (window.siyuan.config.fileTree.sort === 6 && ulSort === "15")) && selectFileElements.length > 0) {
+ } else if (isCustomFileTreeList(targetListElement) && selectFileElements.length > 0) {
let hasMove = false;
const toDir = pathPosix().dirname(toPath);
if (fromPaths.length > 0) {
@@ -697,7 +704,10 @@ export class MobileFiles extends Model {
private genSort() {
window.siyuan.menus.menu.remove();
- const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort: number) => {
+ const subMenu = sortMenu("notebooks", window.siyuan.config.fileTree.sort, (sort) => {
+ if (sort === null) {
+ return;
+ }
fetchPost("/api/setting/setFiletree", {
...window.siyuan.config.fileTree,
sort,
@@ -895,8 +905,12 @@ export class MobileFiles extends Model {
}
private onMove(response: IWebSocketData) {
+ const moves = response.data.moves as IFileTreeMove[];
+ const needsSortModeRefresh = moves.some((move) =>
+ move.fromNotebook !== move.toNotebook ||
+ pathPosix().dirname(move.fromPath) !== pathPosix().dirname(move.newPath));
const refreshTargets = new Map<string, { element: HTMLElement, notebookId: string }>();
- (response.data.moves as IFileTreeMove[]).forEach((move) => {
+ moves.forEach((move) => {
const expandedDocIDs = new Set<string>();
const movedItem = findMovedFileTreeItem(this.element, move);
const sourceElement = movedItem?.element;
@@ -986,6 +1000,11 @@ export class MobileFiles extends Model {
});
}
});
+ if (needsSortModeRefresh) {
+ this.getOpenPaths();
+ this.onDocSortModeChanged();
+ return;
+ }
if (response.callback !== Constants.CB_MOVE_NOLIST) {
refreshTargets.forEach((target) => {
this.getLeaf(target.element, target.notebookId, true);
@@ -1078,14 +1097,10 @@ export class MobileFiles extends Model {
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") {
+ const listElement = liElement?.nextElementSibling;
+ if (!listElement || listElement.tagName !== "UL" || !isCustomFileTreeList(listElement)) {
return;
}
fetchPost("/api/filetree/listDocsByPath", {
@@ -1097,6 +1112,14 @@ export class MobileFiles extends Model {
});
}
+ public onDocSortModeChanged(data?: IDocSortModeChanged) {
+ updateFileTreeSortMode(data);
+ window.clearTimeout(this.docSortModeRefreshTimeout);
+ this.docSortModeRefreshTimeout = window.setTimeout(() => {
+ this.init(false);
+ }, 100);
+ }
+
public onNotebookSortChanged() {
if (window.siyuan.config.fileTree.sort !== 6) {
return;
@@ -1149,7 +1172,7 @@ export class MobileFiles extends Model {
}
- private onLsHTML(data: { files: IFile[], box: string, path: string }, scrollTop?: number) {
+ private onLsHTML(data: IFileTreeList, scrollTop?: number) {
if (data.files.length === 0) {
return;
}
@@ -1161,6 +1184,7 @@ export class MobileFiles extends Model {
data.files.forEach((item: IFile) => {
fileHTML += this.genFileHTML(item);
});
+ const effectiveSortMode = getResponseEffectiveSortMode(data, data.box);
let nextElement = liElement.nextElementSibling;
if (nextElement && nextElement.tagName === "UL") {
// 文件展开时,刷新
@@ -1178,6 +1202,7 @@ export class MobileFiles extends Model {
}
});
nextElement.innerHTML = tempElement.innerHTML;
+ nextElement.setAttribute(FILE_TREE_EFFECTIVE_SORT_MODE, effectiveSortMode.toString());
this.restoreMovedExpandedItems(nextElement, data.box);
if (typeof scrollTop === "number") {
this.element.scroll({top: scrollTop, behavior: "smooth"});
@@ -1186,7 +1211,7 @@ export class MobileFiles extends Model {
return;
}
liElement.querySelector(".b3-list-item__arrow").classList.add("b3-list-item__arrow--open");
- liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
+ liElement.insertAdjacentHTML("afterend", `<ul ${FILE_TREE_EFFECTIVE_SORT_MODE}="${effectiveSortMode}">${fileHTML}</ul>`);
nextElement = liElement.nextElementSibling;
this.restoreMovedExpandedItems(nextElement, data.box);
expandFileTree(nextElement as HTMLElement, () => {
@@ -1197,11 +1222,7 @@ export class MobileFiles extends Model {
this.refreshPublishAccessSwitch();
}
- private async onLsSelect(data: {
- files: IFile[],
- box: string,
- path: string
- }, filePath: string, setStorage: boolean, isSetCurrent: boolean) {
+ private async onLsSelect(data: IFileTreeList, filePath: string, setStorage: boolean, isSetCurrent: boolean) {
let fileHTML = "";
data.files.forEach((item: IFile) => {
fileHTML += this.genFileHTML(item);
@@ -1221,7 +1242,8 @@ export class MobileFiles extends Model {
if (emojiElement.textContent === unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].file)) {
emojiElement.textContent = unicode2Emoji(window.siyuan.storage[Constants.LOCAL_IMAGES].folder);
}
- liElement.insertAdjacentHTML("afterend", `<ul>${fileHTML}</ul>`);
+ const effectiveSortMode = getResponseEffectiveSortMode(data, data.box);
+ liElement.insertAdjacentHTML("afterend", `<ul ${FILE_TREE_EFFECTIVE_SORT_MODE}="${effectiveSortMode}">${fileHTML}</ul>`);
this.restoreMovedExpandedItems(liElement.nextElementSibling, data.box);
let newLiElement;
for (let i = 0; i < data.files.length; i++) {
@@ -1287,11 +1309,8 @@ export class MobileFiles extends Model {
});
}
- public async selectItem(notebookId: string, filePath: string, data?: {
- files: IFile[],
- box: string,
- path: string
- }, setStorage = true, isSetCurrent = true) {
+ public async selectItem(notebookId: string, filePath: string, data?: IFileTreeList,
+ setStorage = true, isSetCurrent = true) {
const treeElement = this.element.querySelector(`[data-url="${notebookId}"]`);
if (!treeElement) {
// 有文件树和编辑器的布局初始化时,文件树还未挂载
@@ -1385,7 +1404,7 @@ export class MobileFiles extends Model {
}
const paddingLeft = (item.path.split("/").length - 1) * 20;
const editingPublishAccess = this.actionsElement.querySelector('[data-type="publish-access"]').classList.contains("block__icon--active");
- return `<li data-node-id="${item.id}" data-name="${Lute.EscapeHTMLStr(item.name)}" data-count="${item.subFileCount}" data-type="navigation-file"
+ return `<li data-node-id="${item.id}" data-name="${Lute.EscapeHTMLStr(item.name)}" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}" data-type="navigation-file"
class="b3-list-item" data-path="${item.path}" style="--file-toggle-width:${paddingLeft + 20}px" >
<span style="padding-left: ${paddingLeft}px" class="b3-list-item__toggle${item.subFileCount === 0 ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index 1b789587dc..48ea31ae88 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -120,6 +120,9 @@ export const onMessage = (app: App, data: IWebSocketData) => {
case "filetreeSortChanged":
window.siyuan.mobile.docks.file?.onFiletreeSortChanged(data.data);
break;
+ case "docSortModeChanged":
+ window.siyuan.mobile.docks.file?.onDocSortModeChanged(data.data);
+ break;
case "notebookSortChanged":
window.siyuan.mobile.docks.file?.onNotebookSortChanged();
break;
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 3b948b91bd..30a31365f7 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -932,6 +932,14 @@ interface IFile {
id: string;
count: number;
subFileCount: number;
+ childrenSortMode?: number | null;
+}
+
+interface IFileTreeList {
+ files: IFile[];
+ box: string;
+ path: string;
+ effectiveSortMode?: number;
}
interface IBlockTree {
diff --git a/app/src/util/fileTreeSort.test.ts b/app/src/util/fileTreeSort.test.ts
new file mode 100644
index 0000000000..52a362abc6
--- /dev/null
+++ b/app/src/util/fileTreeSort.test.ts
@@ -0,0 +1,67 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {
+ FILE_TREE_CHILDREN_SORT_MODE,
+ FILE_TREE_EFFECTIVE_SORT_MODE,
+ getConfiguredChildrenSortMode,
+ getFileTreeListSortMode,
+ isCustomFileTreeList,
+ updateFileTreeSortMode
+} from "./fileTreeSort";
+
+const withWindow = (callback: () => void) => {
+ const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ siyuan: {
+ config: {fileTree: {sort: 6}},
+ notebooks: [{id: "notebook", sortMode: 15}],
+ },
+ },
+ });
+ try {
+ callback();
+ } finally {
+ if (windowDescriptor) {
+ Object.defineProperty(globalThis, "window", windowDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, "window");
+ }
+ }
+};
+
+const elementWithAttrs = (attrs: Record<string, string>, notebookSortMode = "15") => ({
+ getAttribute: (name: string) => attrs[name] ?? null,
+ closest: () => ({
+ getAttribute: (name: string) => name === "data-sortmode" ? notebookSortMode : null,
+ }),
+}) as unknown as Element;
+
+test("effective list sort mode takes precedence over notebook sorting", () => withWindow(() => {
+ const listElement = elementWithAttrs({[FILE_TREE_EFFECTIVE_SORT_MODE]: "3"});
+ assert.equal(getFileTreeListSortMode(listElement), 3);
+}));
+
+test("notebook inheritance falls back to the global document tree sort mode", () => withWindow(() => {
+ assert.equal(getFileTreeListSortMode(elementWithAttrs({})), 6);
+}));
+
+test("configured child sorting distinguishes inheritance from an explicit mode", () => withWindow(() => {
+ assert.equal(getConfiguredChildrenSortMode(elementWithAttrs({[FILE_TREE_CHILDREN_SORT_MODE]: ""})), null);
+ assert.equal(getConfiguredChildrenSortMode(elementWithAttrs({[FILE_TREE_CHILDREN_SORT_MODE]: "6x"})), null);
+ assert.equal(getConfiguredChildrenSortMode(elementWithAttrs({[FILE_TREE_CHILDREN_SORT_MODE]: "0"})), 0);
+}));
+
+test("custom sorting checks the target list effective mode", () => withWindow(() => {
+ assert.equal(isCustomFileTreeList(elementWithAttrs({[FILE_TREE_EFFECTIVE_SORT_MODE]: "6"}, "0")), true);
+ assert.equal(isCustomFileTreeList(elementWithAttrs({[FILE_TREE_EFFECTIVE_SORT_MODE]: "0"}, "6")), false);
+ assert.equal(isCustomFileTreeList(elementWithAttrs({[FILE_TREE_EFFECTIVE_SORT_MODE]: "6x"}, "0")), false);
+}));
+
+test("sort mode events update global and notebook fallback state", () => withWindow(() => {
+ updateFileTreeSortMode({scope: "global", box: "", id: "", path: "/", sortMode: 3});
+ assert.equal(window.siyuan.config.fileTree.sort, 3);
+ updateFileTreeSortMode({scope: "notebook", box: "notebook", id: "", path: "/", sortMode: 6});
+ assert.equal(window.siyuan.notebooks[0].sortMode, 6);
+}));
diff --git a/app/src/util/fileTreeSort.ts b/app/src/util/fileTreeSort.ts
new file mode 100644
index 0000000000..afc7825d87
--- /dev/null
+++ b/app/src/util/fileTreeSort.ts
@@ -0,0 +1,61 @@
+export const FILE_TREE_EFFECTIVE_SORT_MODE = "data-effective-sort-mode";
+export const FILE_TREE_CHILDREN_SORT_MODE = "data-children-sort-mode";
+
+export interface IDocSortModeChanged {
+ scope: "document" | "notebook" | "global";
+ box: string;
+ id: string;
+ path: string;
+ sortMode: number | null;
+}
+
+const parseSortMode = (value: string | null) => {
+ if (value === null || value.trim() === "") {
+ return;
+ }
+ const sortMode = Number(value);
+ return Number.isInteger(sortMode) ? sortMode : undefined;
+};
+
+export const getConfiguredChildrenSortMode = (element: Element) => {
+ return parseSortMode(element?.getAttribute(FILE_TREE_CHILDREN_SORT_MODE)) ?? null;
+};
+
+export const getFileTreeListSortMode = (element: Element) => {
+ const effectiveSortMode = parseSortMode(element?.getAttribute(FILE_TREE_EFFECTIVE_SORT_MODE));
+ if (typeof effectiveSortMode === "number") {
+ return effectiveSortMode;
+ }
+
+ const notebookElement = element?.closest("ul[data-url][data-sortmode]");
+ const notebookSortMode = parseSortMode(notebookElement?.getAttribute("data-sortmode"));
+ return notebookSortMode === 15 || typeof notebookSortMode !== "number" ?
+ window.siyuan.config.fileTree.sort : notebookSortMode;
+};
+
+export const isCustomFileTreeList = (element: Element) => getFileTreeListSortMode(element) === 6;
+
+export const updateFileTreeSortMode = (data?: IDocSortModeChanged) => {
+ const sortMode = data?.sortMode;
+ if (typeof sortMode !== "number" || !Number.isInteger(sortMode)) {
+ return;
+ }
+ if (data.scope === "global") {
+ window.siyuan.config.fileTree.sort = sortMode;
+ } else if (data.scope === "notebook") {
+ const notebook = window.siyuan.notebooks.find((item) => item.id === data.box);
+ if (notebook) {
+ notebook.sortMode = sortMode;
+ }
+ }
+};
+
+export const getResponseEffectiveSortMode = (data: IFileTreeList, notebookId: string) => {
+ if (Number.isInteger(data.effectiveSortMode)) {
+ return data.effectiveSortMode;
+ }
+
+ const notebookSortMode = window.siyuan.notebooks.find((item) => item.id === notebookId)?.sortMode;
+ return notebookSortMode === 15 || typeof notebookSortMode !== "number" ?
+ window.siyuan.config.fileTree.sort : notebookSortMode;
+};
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 61b2b398af..e36338921a 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -21,6 +21,7 @@
* [ドキュメントを削除](#ドキュメントを削除)
* [ドキュメントを移動](#ドキュメントを移動)
* [ノートブックとドキュメントのソート値を設定](#ノートブックとドキュメントのソート値を設定)
+ * [ドキュメントの子ドキュメント用ソート方式を設定](#ドキュメントの子ドキュメント用ソート方式を設定)
* [パスから人間が読めるパスを取得](#パスから人間が読めるパスを取得)
* [IDから人間が読めるパスを取得](#IDから人間が読めるパスを取得)
* [IDからストレージパスを取得](#IDからストレージパスを取得)
@@ -562,6 +563,40 @@
}
```
+### ドキュメントの子ドキュメント用ソート方式を設定
+
+* `/api/filetree/setDocSortMode`
+* パラメータ
+
+ ```json
+ {
+ "id": "20210917220056-yxtyl7i",
+ "sortMode": 4
+ }
+ ```
+
+ * `id`: 子ドキュメントのソート方式を宣言する通常のドキュメントID。ノートブックのルートドキュメントIDは指定できません
+ * `sortMode`: `0`から`14`までの整数。`null`を指定するとドキュメントの明示的な設定が解除され、最も近い親ドキュメント、ノートブック、グローバルドキュメントツリーの順にソートルールを継承します
+ * 値:`0`/`1` ファイル名の昇順/降順、`2`/`3` 更新日時の昇順/降順、`4`/`5` ファイル名の自然順昇順/降順、`6` カスタム、`7`/`8` 参照数の昇順/降順、`9`/`10` 作成日時の昇順/降順、`11`/`12` サイズの昇順/降順、`13`/`14` 子ドキュメント数の昇順/降順
+ * 宣言したソート方式は、別のドキュメントが独自のソート方式を宣言するまで、より深い階層の子孫に継承されます
+* 戻り値
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "box": "20210817205410-2kvfpfn",
+ "id": "20210917220056-yxtyl7i",
+ "path": "/20210917220056-yxtyl7i.sy",
+ "sortMode": 4,
+ "effectiveSortMode": 4
+ }
+ }
+ ```
+
+ * `sortMode`は明示的な設定値(継承時は`null`)、`effectiveSortMode`は継承を解決した後に実際に適用される値です
+
### パスから人間が読めるパスを取得
* `/api/filetree/getHPathByPath`
diff --git a/docs/API.md b/docs/API.md
index 918a53d7a8..4c5d14ed0f 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -21,6 +21,7 @@
* [Remove a document](#Remove-a-document)
* [Move documents](#Move-documents)
* [Set notebook and document sort values](#Set-notebook-and-document-sort-values)
+ * [Set a document's child document sort mode](#Set-a-documents-child-document-sort-mode)
* [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)
@@ -563,6 +564,40 @@ Move documents by `id`:
}
```
+### Set a document's child document sort mode
+
+* `/api/filetree/setDocSortMode`
+* Parameters
+
+ ```json
+ {
+ "id": "20210917220056-yxtyl7i",
+ "sortMode": 4
+ }
+ ```
+
+ * `id`: ID of the regular document whose child documents use this sort mode; notebook root document IDs are not accepted
+ * `sortMode`: Integer from `0` through `14`; `null` clears the document's explicit setting and inherits the nearest parent document, notebook, or global document tree sort rule, in that order
+ * Values: `0`/`1` file name ascending/descending; `2`/`3` update time ascending/descending; `4`/`5` natural file name ascending/descending; `6` custom; `7`/`8` reference count ascending/descending; `9`/`10` creation time ascending/descending; `11`/`12` size ascending/descending; `13`/`14` child document count ascending/descending
+ * The declared sort mode is inherited by deeper descendants until another document declares its own sort mode
+* Return value
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "box": "20210817205410-2kvfpfn",
+ "id": "20210917220056-yxtyl7i",
+ "path": "/20210917220056-yxtyl7i.sy",
+ "sortMode": 4,
+ "effectiveSortMode": 4
+ }
+ }
+ ```
+
+ * `sortMode` is the explicit setting (`null` when inheriting), while `effectiveSortMode` is the actual sort mode after inheritance is resolved
+
### Get human-readable path based on path
* `/api/filetree/getHPathByPath`
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 27b5272634..db04ef8d27 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -21,6 +21,7 @@
* [删除文档](#删除文档)
* [移动文档](#移动文档)
* [设置笔记本和文档排序值](#设置笔记本和文档排序值)
+ * [设置文档的子文档排序方式](#设置文档的子文档排序方式)
* [根据路径获取人类可读路径](#根据路径获取人类可读路径)
* [根据 ID 获取人类可读路径](#根据-ID-获取人类可读路径)
* [根据 ID 获取存储路径](#根据-ID-获取存储路径)
@@ -562,6 +563,40 @@
}
```
+### 设置文档的子文档排序方式
+
+* `/api/filetree/setDocSortMode`
+* 参数
+
+ ```json
+ {
+ "id": "20210917220056-yxtyl7i",
+ "sortMode": 4
+ }
+ ```
+
+ * `id`:声明子文档排序方式的普通文档 ID,不接受笔记本根文档 ID
+ * `sortMode`:`0` 到 `14` 的整数;传入 `null` 会清除该文档的显式设置,并依次继承最近父文档、笔记本或全局文档树的排序规则
+ * 取值:`0`/`1` 文件名升序/降序;`2`/`3` 更新时间升序/降序;`4`/`5` 文件名自然数升序/降序;`6` 自定义排序;`7`/`8` 引用数升序/降序;`9`/`10` 创建时间升序/降序;`11`/`12` 大小升序/降序;`13`/`14` 子文档数升序/降序
+ * 声明的排序方式会由更深层后代继承,直到其他文档声明自己的排序方式
+* 返回值
+
+ ```json
+ {
+ "code": 0,
+ "msg": "",
+ "data": {
+ "box": "20210817205410-2kvfpfn",
+ "id": "20210917220056-yxtyl7i",
+ "path": "/20210917220056-yxtyl7i.sy",
+ "sortMode": 4,
+ "effectiveSortMode": 4
+ }
+ }
+ ```
+
+ * `sortMode` 为显式设置值(继承时为 `null`),`effectiveSortMode` 为解析继承后的实际生效值
+
### 根据路径获取人类可读路径
* `/api/filetree/getHPathByPath`
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 9b1f390bdd..4c09dd6203 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -17,6 +17,8 @@
package api
import (
+ "bytes"
+ "encoding/json"
"errors"
"fmt"
"math"
@@ -1176,6 +1178,47 @@ func setSort(c *gin.Context) {
}
}
+func setDocSortMode(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ request := &struct {
+ ID string `json:"id"`
+ SortMode json.RawMessage `json:"sortMode"`
+ }{}
+ 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 util.InvalidIDPattern(request.ID, ret) {
+ return
+ }
+ if 0 == len(request.SortMode) {
+ ret.Code = -1
+ ret.Msg = "Field [sortMode] is required"
+ return
+ }
+
+ var sortMode *int
+ if !bytes.Equal(bytes.TrimSpace(request.SortMode), []byte("null")) {
+ value := 0
+ if err := json.Unmarshal(request.SortMode, &value); nil != err {
+ ret.Code = -1
+ ret.Msg = fmt.Sprintf("Field [sortMode] must be an integer or null: %s", err)
+ return
+ }
+ sortMode = &value
+ }
+
+ result, err := model.SetDocSortMode(request.ID, sortMode)
+ ret.Data = result
+ if nil != err {
+ 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 {
@@ -1255,9 +1298,10 @@ func listDocsByPath(c *gin.Context) {
if isEncryptedNotebookDeniedForPublish(c, notebook) {
ret.Data = map[string]any{
- "box": notebook,
- "path": p,
- "files": []*model.File{},
+ "box": notebook,
+ "path": p,
+ "files": []*model.File{},
+ "effectiveSortMode": model.Conf.FileTree.Sort,
}
return
}
@@ -1267,6 +1311,16 @@ func listDocsByPath(c *gin.Context) {
if nil != sortParam {
sortMode = int(sortParam.(float64))
}
+ effectiveSortMode := sortMode
+ if util.SortModeUnassigned == effectiveSortMode {
+ var resolveErr error
+ effectiveSortMode, resolveErr = model.ResolveDocTreeSortMode(notebook, p)
+ if nil != resolveErr {
+ ret.Code = -1
+ ret.Msg = resolveErr.Error()
+ return
+ }
+ }
flashcard := false
if arg["flashcard"] != nil {
flashcard = arg["flashcard"].(bool)
@@ -1284,7 +1338,7 @@ func listDocsByPath(c *gin.Context) {
showHidden = arg["showHidden"].(bool)
}
- files, totals, err := model.ListDocTree(notebook, p, sortMode, flashcard, showHidden, maxListCount)
+ files, totals, err := model.ListDocTree(notebook, p, effectiveSortMode, flashcard, showHidden, maxListCount)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
@@ -1319,9 +1373,10 @@ func listDocsByPath(c *gin.Context) {
}
ret.Data = map[string]any{
- "box": notebook,
- "path": p,
- "files": files,
+ "box": notebook,
+ "path": p,
+ "files": files,
+ "effectiveSortMode": effectiveSortMode,
}
}
diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.go
index 29f7be53fe..b09a16ef31 100644
--- a/kernel/api/filetree_test.go
+++ b/kernel/api/filetree_test.go
@@ -74,6 +74,43 @@ func TestSetSortRejectsInvalidRequest(t *testing.T) {
}
}
+func TestSetDocSortModeRejectsInvalidRequest(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.POST("/api/filetree/setDocSortMode", setDocSortMode)
+
+ tests := []struct {
+ name string
+ body string
+ }{
+ {name: "empty", body: `{}`},
+ {name: "missing sort mode", body: `{"id":"20260718000001-abcdefg"}`},
+ {name: "invalid ID", body: `{"id":"invalid","sortMode":0}`},
+ {name: "fractional sort mode", body: `{"id":"20260718000001-abcdefg","sortMode":1.5}`},
+ {name: "string sort mode", body: `{"id":"20260718000001-abcdefg","sortMode":"1"}`},
+ {name: "notebook fallback mode", body: `{"id":"20260718000001-abcdefg","sortMode":15}`},
+ {name: "internal unassigned mode", body: `{"id":"20260718000001-abcdefg","sortMode":256}`},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "/api/filetree/setDocSortMode", 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 TestAuthFilePublishAccessReturnsUniformFailure(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index e0f75bc1a3..45c0ed8199 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -422,6 +422,7 @@ func setNotebookConf(c *gin.Context) {
}
boxConf := box.GetConf()
+ oldSortMode := boxConf.SortMode
// 深拷贝加密相关字段,防止反序列化请求体时被覆盖
// BoxCrypt 是指针,UnmarshalJSON 会修改同一指针对象,必须用 model 层辅助函数深拷贝
savedBoxCrypt := model.DeepCopyBoxEncryption(boxConf.BoxCrypt)
@@ -458,6 +459,9 @@ func setNotebookConf(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ if oldSortMode != boxConf.SortMode {
+ model.PushDocSortModeChanged("notebook", notebook, "", "/", &boxConf.SortMode)
+ }
ret.Data = boxConf
}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index f51f4cc722..1889e44765 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -158,6 +158,7 @@ func ServeAPI(ginServer *gin.Engine) {
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/setDocSortMode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setDocSortMode)
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/api/setting.go b/kernel/api/setting.go
index d78d4c8c7c..089afeebcf 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -557,6 +557,7 @@ func setFiletree(c *gin.Context) {
return
}
+ oldSortMode := model.Conf.FileTree.Sort
param, err := gulu.JSON.MarshalJSON(arg)
if err != nil {
ret.Code = -1
@@ -618,6 +619,9 @@ func setFiletree(c *gin.Context) {
model.Conf.FileTree = fileTree
model.Conf.Save()
+ if oldSortMode != fileTree.Sort {
+ model.PushDocSortModeChanged("global", "", "", "/", &fileTree.Sort)
+ }
if oldBoxDocEnabled != model.IsBoxDocEnabled() {
model.RefreshBoxDocFeature()
}
diff --git a/kernel/model/blockial.go b/kernel/model/blockial.go
index 68dc638188..2448f84e0d 100644
--- a/kernel/model/blockial.go
+++ b/kernel/model/blockial.go
@@ -148,6 +148,12 @@ func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error) {
trees := filesys.LoadTrees(blockIDs)
var nodes []*ast.Node
+ type docSortModeChange struct {
+ oldAttrs map[string]string
+ node *ast.Node
+ tree *parse.Tree
+ }
+ var docSortModeChanges []docSortModeChange
boxIcons := map[string]string{}
for _, blockAttr := range blockAttrs {
id := blockAttr["id"].(string)
@@ -176,6 +182,7 @@ func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error) {
cache.PutBlockIALInBox(node.ID, tree.Box, parse.IAL2Map(node.KramdownIAL))
pushBlockAttrs(oldAttrs, node)
+ docSortModeChanges = append(docSortModeChanges, docSortModeChange{oldAttrs: oldAttrs, node: node, tree: tree})
nodes = append(nodes, node)
}
@@ -196,6 +203,14 @@ func BatchSetBlockAttrs(blockAttrs []map[string]any) (err error) {
pushNotebookIconChanged(boxID, icon)
}
}
+ for _, change := range docSortModeChanges {
+ newAttrs := parse.IAL2Map(change.node.KramdownIAL)
+ if change.oldAttrs[DocSortModeAttr] != newAttrs[DocSortModeAttr] && ast.NodeDocument == change.node.Type {
+ cache.RemoveDocIALInBox(change.tree.Path, change.tree.Box)
+ cache.PutDocIALInBox(change.tree.Path, change.tree.Box, newAttrs)
+ }
+ pushDocSortModeChanged(change.oldAttrs, change.node, change.tree)
+ }
IncSync()
// 不做锚文本刷新
@@ -255,9 +270,15 @@ func setNodeAttrs(node *ast.Node, tree *parse.Tree, nameValues map[string]string
}
IncSync()
- cache.PutBlockIALInBox(node.ID, tree.Box, parse.IAL2Map(node.KramdownIAL))
+ newAttrs := parse.IAL2Map(node.KramdownIAL)
+ cache.PutBlockIALInBox(node.ID, tree.Box, newAttrs)
+ if oldAttrs[DocSortModeAttr] != newAttrs[DocSortModeAttr] && ast.NodeDocument == node.Type {
+ cache.RemoveDocIALInBox(tree.Path, tree.Box)
+ cache.PutDocIALInBox(tree.Path, tree.Box, newAttrs)
+ }
pushBlockAttrs(oldAttrs, node)
+ pushDocSortModeChanged(oldAttrs, node, tree)
if ("true" == oldAttrs[DocHiddenAttr]) != ("true" == nameValues[DocHiddenAttr]) {
ReloadFiletree()
@@ -326,8 +347,14 @@ func setNodeAttrsWithTx(tx *Transaction, node *ast.Node, tree *parse.Tree, nameV
tx.writeTree(tree)
IncSync()
- cache.PutBlockIALInBox(node.ID, tree.Box, parse.IAL2Map(node.KramdownIAL))
+ newAttrs := parse.IAL2Map(node.KramdownIAL)
+ cache.PutBlockIALInBox(node.ID, tree.Box, newAttrs)
+ if oldAttrs[DocSortModeAttr] != newAttrs[DocSortModeAttr] && ast.NodeDocument == node.Type {
+ cache.RemoveDocIALInBox(tree.Path, tree.Box)
+ cache.PutDocIALInBox(tree.Path, tree.Box, newAttrs)
+ }
pushBlockAttrs(oldAttrs, node)
+ pushDocSortModeChanged(oldAttrs, node, tree)
return
}
@@ -364,6 +391,20 @@ func setNodeAttrs0(node *ast.Node, nameValues map[string]string, boxID string) (
err = errors.New(`setting or removing [data-task] attribute is not allowed via this interface. Please use "/api/block/updateTaskListItemMarker" or "/api/block/batchUpdateTaskListItemMarker" to update the task list item marker`)
return
}
+ if DocSortModeAttr == lowerName {
+ if ast.NodeDocument != node.Type || IsBoxDoc(boxID, node.ID) {
+ err = fmt.Errorf("attribute [%s] is only supported on regular document roots", DocSortModeAttr)
+ return
+ }
+ if "" != value {
+ sortMode, parseErr := strconv.Atoi(value)
+ if nil != parseErr || !IsValidDocSortMode(sortMode) {
+ err = fmt.Errorf("invalid document sort mode [%s]", value)
+ return
+ }
+ value = strconv.Itoa(sortMode)
+ }
+ }
// 处理文档标签 https://github.com/siyuan-note/siyuan/issues/13311
if lowerName == "tags" {
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 515735bd70..d7834aaf00 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -21,6 +21,7 @@ import (
"fmt"
"io/fs"
"maps"
+ "math"
"os"
"path"
"path/filepath"
@@ -52,24 +53,25 @@ import (
)
type File struct {
- Path string `json:"path"`
- Name string `json:"name"` // 标题,即 ial["title"]
- TitleEmpty bool `json:"titleEmpty,omitempty"`
- Icon string `json:"icon"`
- Name1 string `json:"name1"` // 命名,即 ial["name"]
- Alias string `json:"alias"`
- Memo string `json:"memo"`
- Bookmark string `json:"bookmark"`
- ID string `json:"id"`
- Count int `json:"count"`
- Size uint64 `json:"size"`
- HSize string `json:"hSize"`
- Mtime int64 `json:"mtime"`
- CTime int64 `json:"ctime"`
- HMtime string `json:"hMtime"`
- HCtime string `json:"hCtime"`
- Sort int `json:"sort"`
- SubFileCount int `json:"subFileCount"`
+ Path string `json:"path"`
+ Name string `json:"name"` // 标题,即 ial["title"]
+ TitleEmpty bool `json:"titleEmpty,omitempty"`
+ Icon string `json:"icon"`
+ Name1 string `json:"name1"` // 命名,即 ial["name"]
+ Alias string `json:"alias"`
+ Memo string `json:"memo"`
+ Bookmark string `json:"bookmark"`
+ ID string `json:"id"`
+ Count int `json:"count"`
+ Size uint64 `json:"size"`
+ HSize string `json:"hSize"`
+ Mtime int64 `json:"mtime"`
+ CTime int64 `json:"ctime"`
+ HMtime string `json:"hMtime"`
+ HCtime string `json:"hCtime"`
+ Sort int `json:"sort"`
+ SubFileCount int `json:"subFileCount"`
+ ChildrenSortMode *int `json:"childrenSortMode"`
NewFlashcardCount int `json:"newFlashcardCount"`
DueFlashcardCount int `json:"dueFlashcardCount"`
@@ -90,6 +92,7 @@ func (box *Box) docFromFileInfo(fileInfo *FileInfo, ial map[string]string) (ret
ret.Alias = ial["alias"]
ret.Memo = ial["memo"]
ret.Bookmark = ial["bookmark"]
+ ret.ChildrenSortMode = docSortModeFromIAL(ial)
t, _ := time.ParseInLocation("20060102150405", ret.ID[:14], time.Local)
ret.CTime = t.Unix()
ret.HCtime = t.Format("2006-01-02 15:04:05") + ", " + util.HumanizeTime(t, Conf.Lang)
@@ -107,6 +110,24 @@ func (box *Box) docFromFileInfo(fileInfo *FileInfo, ial map[string]string) (ret
return
}
+const DocSortModeAttr = "custom-sy-subdoc-sort-mode"
+
+func IsValidDocSortMode(sortMode int) bool {
+ return util.SortModeNameASC <= sortMode && sortMode <= util.SortModeSubDocCountDESC
+}
+
+func docSortModeFromIAL(ial map[string]string) *int {
+ value := ial[DocSortModeAttr]
+ if "" == value {
+ return nil
+ }
+ sortMode, err := strconv.Atoi(value)
+ if nil != err || !IsValidDocSortMode(sortMode) {
+ return nil
+ }
+ return &sortMode
+}
+
func (box *Box) docIAL(p string) (ret map[string]string) {
name := strings.ToLower(filepath.Base(p))
if !strings.HasSuffix(name, ".sy") {
@@ -377,6 +398,49 @@ type FileInfo struct {
isdir bool
}
+// ResolveDocTreeSortMode 按当前父文档、最近祖先文档、笔记本和全局配置的顺序解析子文档排序方式。
+func ResolveDocTreeSortMode(boxID, listPath string) (sortMode int, err error) {
+ box := Conf.Box(boxID)
+ if nil == box {
+ return 0, errors.New(Conf.Language(0))
+ }
+
+ normalized, err := box.validateBoxPath(listPath)
+ if nil != err {
+ return 0, err
+ }
+ normalized = filepath.ToSlash(normalized)
+ if "" != normalized {
+ docPath := "/" + strings.TrimPrefix(path.Clean("/"+normalized), "/")
+ if !strings.HasSuffix(docPath, ".sy") {
+ docPath += ".sy"
+ }
+
+ for "" != docPath && !IsBoxDocPath(boxID, docPath) {
+ // 仅探测确实存在的文档,避免将同步中的临时缺失误判为损坏数据。
+ if box.Exist(docPath) {
+ if declared := docSortModeFromIAL(box.docIAL(docPath)); nil != declared {
+ return *declared, nil
+ }
+ }
+
+ docDir := strings.TrimSuffix(docPath, ".sy")
+ parentDir := path.Dir(docDir)
+ if "/" == parentDir || "." == parentDir {
+ break
+ }
+ docPath = parentDir + ".sy"
+ }
+ }
+
+ sortMode = Conf.FileTree.Sort
+ boxConf := box.GetConf()
+ if util.SortModeFileTree != boxConf.SortMode {
+ sortMode = boxConf.SortMode
+ }
+ return
+}
+
func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden bool, maxListCount int) (ret []*File, totals int, err error) {
//os.MkdirAll("pprof", 0755)
//cpuProfile, _ := os.Create("pprof/cpu_profile_list_doc_tree")
@@ -404,12 +468,9 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
return nil, 0, errors.New(Conf.Language(0))
}
- boxConf := box.GetConf()
-
if util.SortModeUnassigned == sortMode {
- sortMode = Conf.FileTree.Sort
- if util.SortModeFileTree != boxConf.SortMode {
- sortMode = boxConf.SortMode
+ if sortMode, err = ResolveDocTreeSortMode(boxID, listPath); nil != err {
+ return
}
}
@@ -2419,6 +2480,78 @@ func writeSortConfMap(confPath string, fullSortIDs map[string]int) error {
return nil
}
+type DocSortModeResult struct {
+ Box string `json:"box"`
+ ID string `json:"id"`
+ Path string `json:"path"`
+ SortMode *int `json:"sortMode"`
+ EffectiveSortMode int `json:"effectiveSortMode"`
+}
+
+// SetDocSortMode 设置文档对子文档列表声明的排序方式,sortMode 为 nil 时恢复继承。
+func SetDocSortMode(id string, sortMode *int) (ret *DocSortModeResult, err error) {
+ if nil != sortMode && !IsValidDocSortMode(*sortMode) {
+ return nil, fmt.Errorf("invalid document sort mode [%d]", *sortMode)
+ }
+
+ FlushTxQueue()
+ tree, err := LoadTreeByBlockID(id)
+ if nil != err {
+ return nil, err
+ }
+ if tree.ID != id || tree.Root.ID != id || ast.NodeDocument != tree.Root.Type || IsBoxDoc(tree.Box, tree.ID) {
+ return nil, fmt.Errorf("block [%s] is not a document that can declare a child document sort mode", id)
+ }
+
+ value := ""
+ if nil != sortMode {
+ value = strconv.Itoa(*sortMode)
+ }
+ if tree.Root.IALAttr(DocSortModeAttr) != value {
+ if err = setNodeAttrs(tree.Root, tree, map[string]string{DocSortModeAttr: value}); nil != err {
+ return nil, err
+ }
+ }
+
+ effectiveSortMode, resolveErr := ResolveDocTreeSortMode(tree.Box, tree.Path)
+ if nil != resolveErr {
+ return nil, resolveErr
+ }
+ ret = &DocSortModeResult{
+ Box: tree.Box,
+ ID: tree.ID,
+ Path: tree.Path,
+ SortMode: sortMode,
+ EffectiveSortMode: effectiveSortMode,
+ }
+ return
+}
+
+func pushDocSortModeChanged(oldAttrs map[string]string, node *ast.Node, tree *parse.Tree) {
+ if nil == node || nil == tree || ast.NodeDocument != node.Type || node.ID != tree.ID || IsBoxDoc(tree.Box, tree.ID) {
+ return
+ }
+
+ oldSortMode := docSortModeFromIAL(oldAttrs)
+ newSortMode := docSortModeFromIAL(parse.IAL2Map(node.KramdownIAL))
+ if (nil == oldSortMode) == (nil == newSortMode) && (nil == oldSortMode || *oldSortMode == *newSortMode) {
+ return
+ }
+
+ PushDocSortModeChanged("document", tree.Box, tree.ID, tree.Path, newSortMode)
+}
+
+// PushDocSortModeChanged 广播会改变子文档有效排序方式的配置变更。
+func PushDocSortModeChanged(scope, boxID, id, p string, sortMode *int) {
+ util.BroadcastByType("main", "docSortModeChanged", 0, "", map[string]any{
+ "scope": scope,
+ "box": boxID,
+ "id": id,
+ "path": p,
+ "sortMode": sortMode,
+ })
+}
+
func moveSorts(rootID, fromBox, toBox string) {
root := treenode.GetBlockTree(rootID)
if nil == root {
@@ -2454,7 +2587,7 @@ func moveSorts(rootID, fromBox, toBox string) {
bt := treenode.GetBlockTree(rootID)
if nil != bt {
parentPath := path.Dir(bt.Path)
- docs, _, listErr := ListDocTree(toBox, parentPath, util.SortModeUnassigned, false, false, 102400)
+ docs, _, listErr := ListDocTree(toBox, parentPath, util.SortModeCustom, false, false, math.MaxInt)
if listErr != nil {
logging.LogErrorf("list doc tree failed: %s", listErr)
return
@@ -2748,7 +2881,7 @@ func (box *Box) setSortByConf(parentPath, id string) {
}
func (box *Box) addMaxSort(parentPath, id string) {
- docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeUnassigned, false, false, 102400)
+ docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeCustom, false, false, math.MaxInt)
if err != nil {
logging.LogErrorf("list doc tree failed: %s", err)
return
@@ -2770,7 +2903,7 @@ func (box *Box) addMaxSort(parentPath, id string) {
}
func (box *Box) addMinSort(parentPath, id string) {
- docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeUnassigned, false, false, 1)
+ docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeCustom, false, false, 1)
if err != nil {
logging.LogErrorf("list doc tree failed: %s", err)
return
@@ -2829,7 +2962,7 @@ func (box *Box) addSort(previousPath, id string) {
}
parentPath := path.Dir(previousPath)
- docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)
+ docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeCustom, false, false, math.MaxInt)
if err != nil {
logging.LogErrorf("list doc tree failed: %s", err)
return
diff --git a/kernel/model/file_doc_sort_test.go b/kernel/model/file_doc_sort_test.go
new file mode 100644
index 0000000000..87d51511c6
--- /dev/null
+++ b/kernel/model/file_doc_sort_test.go
@@ -0,0 +1,144 @@
+// SiYuan - From thought to insight, with agents
+// 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/>.
+
+//go:build fts5
+
+package model
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const setDocSortModeTestEnv = "SIYUAN_TEST_SET_DOC_SORT_MODE"
+
+func TestSetDocSortModeValidationAndPersistence(t *testing.T) {
+ if "1" != os.Getenv(setDocSortModeTestEnv) {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestSetDocSortModeValidationAndPersistence$", "-test.v")
+ cmd.Env = append(os.Environ(), setDocSortModeTestEnv+"=1")
+ output, err := cmd.CombinedOutput()
+ if nil != err {
+ t.Fatalf("set document sort mode subprocess failed: %v\n%s", err, output)
+ }
+ return
+ }
+
+ fixture := setupFileOperationTest(t)
+ originalTempDir := util.TempDir
+ originalQueueDir := util.QueueDir
+ originalConfDir := util.ConfDir
+ originalDBPath := util.DBPath
+ originalHistoryDBPath := util.HistoryDBPath
+ originalAssetContentDBPath := util.AssetContentDBPath
+ util.TempDir = t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.ConfDir = filepath.Join(util.TempDir, "conf")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ for _, dir := range []string{util.QueueDir, util.ConfDir} {
+ if err := os.MkdirAll(dir, 0755); nil != err {
+ t.Fatalf("create test directory [%s] failed: %v", dir, err)
+ }
+ }
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ for _, p := range []string{fixture.sourcePath, fixture.targetPath} {
+ tree, loadErr := filesys.LoadTree(fixture.box.ID, p, util.NewLute())
+ if nil != loadErr {
+ t.Fatalf("reload fixture document [%s] failed: %v", p, loadErr)
+ }
+ treenode.UpsertBlockTree(tree)
+ }
+ t.Cleanup(func() {
+ sql.CloseDatabase()
+ util.TempDir = originalTempDir
+ util.QueueDir = originalQueueDir
+ util.ConfDir = originalConfDir
+ util.DBPath = originalDBPath
+ util.HistoryDBPath = originalHistoryDBPath
+ util.AssetContentDBPath = originalAssetContentDBPath
+ })
+ if warmed := fixture.box.docIAL(fixture.sourcePath); nil == warmed {
+ t.Fatal("failed to warm source document IAL cache")
+ }
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if nil != err {
+ t.Fatalf("load source document failed: %v", err)
+ }
+ updated := tree.Root.IALAttr("updated")
+ mode := util.SortModeSubDocCountDESC
+ result, err := SetDocSortMode(fixture.sourceID, &mode)
+ if nil != err {
+ t.Fatalf("set document sort mode failed: %v", err)
+ }
+ if result.ID != fixture.sourceID || nil == result.SortMode || mode != *result.SortMode || mode != result.EffectiveSortMode {
+ t.Fatalf("unexpected set document sort mode result: %#v", result)
+ }
+ if immediate := fixture.box.docIAL(fixture.sourcePath); "14" != immediate[DocSortModeAttr] {
+ t.Fatalf("immediate document IAL read returned a stale sort mode: %q", immediate[DocSortModeAttr])
+ }
+ resolvedMode, resolveErr := ResolveDocTreeSortMode(fixture.box.ID, fixture.sourcePath)
+ if nil != resolveErr || mode != resolvedMode {
+ t.Fatalf("immediate sort mode resolution returned mode=%d, err=%v", resolvedMode, resolveErr)
+ }
+
+ tree, err = LoadTreeByBlockID(fixture.sourceID)
+ if nil != err {
+ t.Fatalf("reload source document failed: %v", err)
+ }
+ if tree.Root.IALAttr(DocSortModeAttr) != "14" {
+ t.Fatalf("document sort mode was not persisted: %q", tree.Root.IALAttr(DocSortModeAttr))
+ }
+ if tree.Root.IALAttr("updated") != updated {
+ t.Fatalf("setting document sort mode changed updated: got %q, want %q", tree.Root.IALAttr("updated"), updated)
+ }
+
+ for _, invalid := range []int{-1, util.SortModeFileTree, util.SortModeUnassigned} {
+ if _, setErr := SetDocSortMode(fixture.sourceID, &invalid); nil == setErr {
+ t.Fatalf("invalid document sort mode [%d] was accepted", invalid)
+ }
+ }
+ if err = SetBlockAttrs(fixture.sourceID, map[string]string{DocSortModeAttr: "15"}); nil == err {
+ t.Fatal("generic block attribute API accepted an invalid document sort mode")
+ }
+ if err = SetBlockAttrs(fixture.childID, map[string]string{DocSortModeAttr: "1"}); nil == err {
+ t.Fatal("generic block attribute API accepted a document sort mode on a non-document block")
+ }
+
+ clearResult, err := SetDocSortMode(fixture.sourceID, nil)
+ if nil != err {
+ t.Fatalf("remove document sort mode failed: %v", err)
+ }
+ if nil != clearResult.SortMode || Conf.FileTree.Sort != clearResult.EffectiveSortMode {
+ t.Fatalf("cleared document sort mode did not inherit the global mode: %#v", clearResult)
+ }
+ tree, err = LoadTreeByBlockID(fixture.sourceID)
+ if nil != err {
+ t.Fatalf("reload source document after removing sort mode failed: %v", err)
+ }
+ if "" != tree.Root.IALAttr(DocSortModeAttr) {
+ t.Fatalf("document sort mode was not removed: %q", tree.Root.IALAttr(DocSortModeAttr))
+ }
+}
diff --git a/kernel/model/file_test.go b/kernel/model/file_test.go
index e3e855a8d3..7a5786f141 100644
--- a/kernel/model/file_test.go
+++ b/kernel/model/file_test.go
@@ -44,10 +44,19 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {
originalConf := Conf
originalDataDir := util.DataDir
originalBlockTreeDBPath := util.BlockTreeDBPath
+ const testLang = "file-operation-test"
+ originalTimeLang, hadTimeLang := util.TimeLangs[testLang]
+ util.TimeLangs[testLang] = map[string]any{
+ "albl": "ago", "blbl": "from now", "now": "now", "1s": "1 second %s", "xs": "%d seconds %s",
+ "1m": "1 minute %s", "xm": "%d minutes %s", "1h": "1 hour %s", "xh": "%d hours %s", "1d": "1 day %s",
+ "xd": "%d days %s", "1w": "1 week %s", "xw": "%d weeks %s", "1M": "1 month %s", "xM": "%d months %s",
+ "1y": "1 year %s", "2y": "2 years %s", "xy": "%d years %s", "max": "a long while %s",
+ }
tempDir := t.TempDir()
util.DataDir = filepath.Join(tempDir, "data")
util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")
Conf = NewAppConf()
+ Conf.Lang = testLang
Conf.FileTree = conf.NewFileTree()
Conf.NotebookCrypto = conf.NewNotebookCrypto()
Conf.Sync = conf.NewSync()
@@ -78,6 +87,11 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {
cache.RemoveDocIAL(sourceTree.Path)
cache.RemoveDocIAL(targetTree.Path)
treenode.CloseDatabase()
+ if hadTimeLang {
+ util.TimeLangs[testLang] = originalTimeLang
+ } else {
+ delete(util.TimeLangs, testLang)
+ }
Conf = originalConf
util.DataDir = originalDataDir
util.BlockTreeDBPath = originalBlockTreeDBPath
@@ -95,6 +109,147 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {
}
}
+func TestResolveDocTreeSortModeInheritance(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.FileTree.Sort = util.SortModeSizeDESC
+ boxConf := fixture.box.GetConf()
+ boxConf.SortMode = util.SortModeCreatedASC
+ if err := fixture.box.SaveConf(boxConf); nil != err {
+ t.Fatalf("save notebook sort mode failed: %v", err)
+ }
+
+ parentTree, err := LoadTreeByBlockID(util.GetTreeID(fixture.targetPath))
+ if nil != err {
+ t.Fatalf("load parent document failed: %v", err)
+ }
+ parentTree.Root.SetIALAttr(DocSortModeAttr, "3")
+ if _, err = filesys.WriteTree(parentTree); nil != err {
+ t.Fatalf("write parent document sort mode failed: %v", err)
+ }
+ treenode.UpsertBlockTree(parentTree)
+
+ childID := "20260718000003-abcdefg"
+ childPath := strings.TrimSuffix(parentTree.Path, ".sy") + "/" + childID + ".sy"
+ childTree := treenode.NewTree(fixture.box.ID, childPath, parentTree.HPath+"/Child", "Child")
+ if _, err = filesys.WriteTree(childTree); nil != err {
+ t.Fatalf("write child document failed: %v", err)
+ }
+ treenode.UpsertBlockTree(childTree)
+ t.Cleanup(func() {
+ cache.RemoveTreeData(childTree.ID)
+ cache.RemoveDocIAL(childTree.Path)
+ })
+
+ for _, listPath := range []string{childTree.Path, strings.TrimSuffix(childTree.Path, ".sy")} {
+ mode, resolveErr := ResolveDocTreeSortMode(fixture.box.ID, listPath)
+ if nil != resolveErr {
+ t.Fatalf("resolve inherited sort mode for [%s] failed: %v", listPath, resolveErr)
+ }
+ if util.SortModeUpdatedDESC != mode {
+ t.Fatalf("unexpected inherited sort mode for [%s]: got %d, want %d", listPath, mode, util.SortModeUpdatedDESC)
+ }
+ }
+
+ childTree.Root.SetIALAttr(DocSortModeAttr, "6")
+ if _, err = filesys.WriteTree(childTree); nil != err {
+ t.Fatalf("write child document override failed: %v", err)
+ }
+ cache.RemoveDocIALInBox(childTree.Path, childTree.Box)
+ mode, err := ResolveDocTreeSortMode(fixture.box.ID, childTree.Path)
+ if nil != err || util.SortModeCustom != mode {
+ t.Fatalf("child override was not resolved: mode=%d, err=%v", mode, err)
+ }
+
+ mode, err = ResolveDocTreeSortMode(fixture.box.ID, "/")
+ if nil != err || util.SortModeCreatedASC != mode {
+ t.Fatalf("notebook fallback was not resolved: mode=%d, err=%v", mode, err)
+ }
+ boxConf.SortMode = util.SortModeFileTree
+ if err = fixture.box.SaveConf(boxConf); nil != err {
+ t.Fatalf("save notebook inherited sort mode failed: %v", err)
+ }
+ mode, err = ResolveDocTreeSortMode(fixture.box.ID, "/")
+ if nil != err || util.SortModeSizeDESC != mode {
+ t.Fatalf("global fallback was not resolved: mode=%d, err=%v", mode, err)
+ }
+
+ files, _, err := ListDocTree(fixture.box.ID, "/", util.SortModeNameASC, false, false, 128)
+ if nil != err {
+ t.Fatalf("list root documents failed: %v", err)
+ }
+ for _, file := range files {
+ if file.ID == parentTree.ID {
+ if nil == file.ChildrenSortMode || util.SortModeUpdatedDESC != *file.ChildrenSortMode {
+ t.Fatalf("parent declaration missing from listed file: %#v", file.ChildrenSortMode)
+ }
+ return
+ }
+ }
+ t.Fatalf("parent document [%s] was not listed", parentTree.ID)
+}
+
+func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.FileTree.Sort = util.SortModeNameASC
+ Conf.FileTree.MaxListCount = 1
+ boxConf := fixture.box.GetConf()
+ boxConf.SortMode = util.SortModeFileTree
+ if err := fixture.box.SaveConf(boxConf); nil != err {
+ t.Fatalf("save notebook sort mode failed: %v", err)
+ }
+
+ extraID := "20260718000003-abcdefg"
+ extraPath := "/" + extraID + ".sy"
+ extraTree := treenode.NewTree(fixture.box.ID, extraPath, "/Extra", "Extra")
+ if _, err := filesys.WriteTree(extraTree); nil != err {
+ t.Fatalf("write extra document failed: %v", err)
+ }
+ treenode.UpsertBlockTree(extraTree)
+ t.Cleanup(func() {
+ cache.RemoveTreeData(extraTree.ID)
+ cache.RemoveDocIAL(extraTree.Path)
+ })
+
+ confPath := filepath.Join(util.DataDir, fixture.box.ID, ".siyuan", "sort.json")
+ if err := writeSortConfMap(confPath, map[string]int{
+ util.GetTreeID(fixture.targetPath): 10,
+ fixture.sourceID: 20,
+ extraID: 30,
+ }); nil != err {
+ t.Fatalf("write initial custom sort failed: %v", err)
+ }
+
+ maxID := "20260718000004-abcdefg"
+ 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])
+ }
+
+ minID := "20260718000005-abcdefg"
+ 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])
+ }
+
+ insertID := "20260718000006-abcdefg"
+ 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])
+ }
+}
+
func TestGetDocOptionallyIncludesDocInfo(t *testing.T) {
fixture := setupFileOperationTest(t)
Conf.Editor = conf.NewEditor()