🎨 Supports setting newly created sub-documents to be listed last https://github.com/siyuan-note/siyuan/issues/16327

Signed-off-by: Daniel <845765@qq.com>
This commit is contained in:
Daniel 2025-11-11 10:54:54 +08:00
parent 72acce2c86
commit 6196173898
No known key found for this signature in database
GPG key ID: 86211BA83DF03017
23 changed files with 90 additions and 9 deletions

View file

@ -1169,6 +1169,8 @@
"fileTree21": "‫بعد التمكين، سيتم استخدام تنسيق JSON ذي السطر الواحد عند حفظ مستندات .sy وقاعدة بيانات .json، مما يقلل حجم الملف بحوالي 30٪ وتحسين كفاءة القراءة والكتابة بنسبة 50٪",
"fileTree22": "تنبيه ملف كبير",
"fileTree23": "إشعار عند تجاوز ملفات .sy أو قاعدة بيانات .json لهذا الحجم",
"fileTree24": "وضع المستندات الفرعية الجديدة في الأعلى",
"fileTree25": "عند التمكين، سيتم وضع المستندات الفرعية الجديدة في أعلى قائمة المستندات الفرعية (ينطبق فقط عند تمكين الترتيب المخصص)",
"export10": "‫على سبيل المثال <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>‬، إذا كان فارغاً، سيتم استخدام العلامة المائية من النص المخصص أو مسار ملف العلامة المائية.",
"export11": "طريقة معالجة محتوى المراجع عند التصدير",
"export12": "طريقة معالجة محتوى كتلة التضمين عند التصدير",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "Nach der Aktivierung wird beim Speichern von .sy-Dokumenten und Datenbank-.json-Dateien das Einzeilige JSON-Format verwendet, was die Dateigröße um etwa 30 % reduzieren und die Lese- und Schreibgeschwindigkeit um 50 % verbessern kann",
"fileTree22": "Großdatei-Warnung",
"fileTree23": "Benachrichtigen, wenn .sy-Dateien oder die Datenbank .json diese Größe überschreiten",
"fileTree24": "Neue Unterdokumente oben platzieren",
"fileTree25": "Wenn aktiviert, werden neu erstellte Unterdokumente oben in der Liste der Unterdokumente platziert (wirkt nur, wenn die benutzerdefinierte Sortierung aktiviert ist)",
"export10": "Beispiel <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, wenn leer, verwenden Sie Wasserzeichentext oder den Pfad zur Wasserzeichen-Datei.",
"export11": "Inhaltsbehandlungsverfahren des Inhaltsreferenzblocks beim Exportieren",
"export12": "Inhaltsbehandlungsverfahren des Inhalteinbettungsblocks beim Exportieren",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "When enabled, the single-line JSON format will be used when saving .sy docs and database .json files, which can reduce the file size by about 30% and improve read and write efficiency by 50%",
"fileTree22": "Large File Warning",
"fileTree23": "Notify when .sy files or database .json exceed this size",
"fileTree24": "Place new subdocuments at the top",
"fileTree25": "When enabled, newly created subdocuments will be placed at the top of the subdocument list (only takes effect when custom sorting is enabled)",
"export10": "For example <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, if empty, use watermark text or watermark file path.",
"export11": "Content handling method of content ref block when exporting",
"export12": "Content handling method of content embed block when exporting",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "Después de habilitarlo, se utilizará el formato JSON de una sola línea al guardar documentos .sy y archivos .json de bases de datos, lo que puede reducir el tamaño del archivo en aproximadamente un 30 % y mejorar la eficiencia de lectura y escritura en un 50 %.",
"fileTree22": "Aviso de archivo grande",
"fileTree23": "Notificar cuando los archivos .sy o la base de datos .json superen este tamaño",
"fileTree24": "Colocar nuevos subdocumentos en la parte superior",
"fileTree25": "Al habilitar, los subdocumentos nuevos se colocarán en la parte superior de la lista de subdocumentos (solo surte efecto cuando el orden personalizado esté habilitado)",
"export10": "Por ejemplo <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, si está vacío, utilice texto de marca de agua o ruta del archivo de marca de agua.",
"export11": "Método de manejo de contenido del bloque de referencia de contenido al exportar",
"export12": "Método de manejo de contenido del bloque de incrustación de contenido al exportar",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "Après activation, le format JSON sur une seule ligne sera utilisé lors de l'enregistrement des documents .sy et des fichiers .json de base de données, ce qui peut réduire la taille du fichier d'environ 30 % et améliorer l'efficacité de lecture et d'écriture de 50 %",
"fileTree22": "Alerte de fichier volumineux",
"fileTree23": "Notifier lorsque les fichiers .sy ou la base de données .json dépassent cette taille",
"fileTree24": "Placer les sous-documents nouvellement créés en haut",
"fileTree25": "Si activé, les nouveaux sous-documents seront placés en haut de la liste des sous-documents (ne prend effet que lorsque le tri personnalisé est activé)",
"export10": "Par exemple <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, s'il est vide, utilisez le texte du filigrane ou le chemin du fichier du filigrane.",
"export11": "Traitement du contenu des blocs de référence lors de l'exportation",
"export12": "Gestion du contenu des blocs intégrés lors de l'exportation",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "לאחר הפעלת אפשרות זו, פורמט ה-JSON בשורה אחת ישמש בעת שמירת קבצי .sy ומסדי נתונים .json, מה שיכול להפחית את גודל הקובץ בכ-30% ולשפר את יעילות הקריאה והכתיבה ב-50%",
"fileTree22": "התראה על קובץ גדול",
"fileTree23": "הצג התראה כאשר קובץ .sy או מסד נתונים .json חורג מגודל זה",
"fileTree24": "מקם מסמך משנה חדש בחלק העליון",
"fileTree25": "כאשר מופעל, מסמכי המשנה החדשים יופיעו בראש רשימת מסמכי המשנה (פועל רק כאשר מיון מותאם אישית מופעל)",
"export10": "למשל <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, אם ריק, השתמש בטקסט סימן מים או בנתיב קובץ סימן מים.",
"export11": "שיטת טיפול תוכן של בלוק תוכן בעת הייצוא",
"export12": "שיטת טיפול תוכן של בלוק הטמעה בעת הייצוא",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "Dopo l'abilitazione, il formato JSON a riga singola verrà utilizzato quando si salvano documenti .sy e file di database .json, il che può ridurre le dimensioni del file del 30% circa e migliorare l'efficienza di lettura e scrittura del 50%",
"fileTree22": "Avviso file di grandi dimensioni",
"fileTree23": "Notifica quando i file .sy e il database .json superano questa dimensione",
"fileTree24": "Posiziona il nuovo sottodocumento in cima",
"fileTree25": "Se abilitato, i nuovi sottodocumenti verranno posizionati in cima all'elenco dei sottodocumenti (funziona solo quando l'ordinamento personalizzato è abilitato)",
"export10": "Ad esempio <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, se vuoto, utilizza il testo della filigrana o il percorso del file della filigrana.",
"export11": "Metodo di gestione del contenuto del blocco di riferimento durante l'esportazione",
"export12": "Metodo di gestione del contenuto del blocco incorporato durante l'esportazione",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "ドキュメントとデータベースファイルを保存する際に改行を行わない JSON フォーマットを使用します。これによりファイルサイズが約 30% 削減され、読み書きの効率が 50% 向上します",
"fileTree22": "大きなファイルの警告",
"fileTree23": ".sy ドキュメントやデータベース .json がこのサイズを超えると通知します",
"fileTree24": "新しい子ドキュメントを先頭に配置",
"fileTree25": "有効にすると、新しく作成された子ドキュメントは子ドキュメント一覧の先頭に配置されます(カスタム並び替えが有効な場合のみ動作します)",
"export10": "例: <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code><br>空の場合は透かしテキストまたは透かし画像ファイルのパスを使用します",
"export11": "エクスポート時のブロック参照コンテンツの処理方法",
"export12": "エクスポート時の埋め込みブロックコンテンツの処理方法",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "Po włączeniu, format JSON w pojedynczej linii będzie używany przy zapisywaniu .sy dokumentów i plików .json bazy danych, co może zmniejszyć rozmiar pliku o około 30% i poprawić wydajność odczytu i zapisu o 50%",
"fileTree22": "Powiadomienie o dużym pliku",
"fileTree23": "Powiadom, gdy plik .sy lub baza danych .json przekroczy ten rozmiar",
"fileTree24": "Umieść nowy poddokument na górze",
"fileTree25": "Po włączeniu nowe poddokumenty będą umieszczane na początku listy poddokumentów (działa tylko, gdy włączone jest niestandardowe sortowanie)",
"export10": "Na przykład <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, jeśli jest puste, użyj tekstu znaków wodnych lub ścieżki pliku znaku wodnego.",
"export11": "Sposób obsługi treści bloku odniesienia podczas eksportu",
"export12": "Sposób obsługi treści bloku osadzonego podczas eksportu",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "Quando ativado, o formato JSON de linha única será usado ao salvar documentos .sy e arquivos .json de banco de dados, o que pode reduzir o tamanho do arquivo em cerca de 30% e melhorar a eficiência de leitura/gravação em 50%",
"fileTree22": "Aviso de arquivo grande",
"fileTree23": "Notificar quando arquivos .sy e banco de dados .json excederem este tamanho",
"fileTree24": "Colocar novo subdocumento no topo",
"fileTree25": "Ao ativar, os novos subdocumentos serão colocados no topo da lista de subdocumentos (somente tem efeito quando a ordenação personalizada estiver ativada)",
"export10": "Por exemplo <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, se vazio, use texto de marca d'água ou caminho do arquivo de marca d'água.",
"export11": "Método de manipulação de conteúdo do bloco de referência ao exportar",
"export12": "Método de manipulação de conteúdo do bloco incorporado ao exportar",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "После включения однострочный формат JSON будет использоваться при сохранении .sy документов и файлов баз данных .json, что может снизить размер файла примерно на 30% и улучшить эффективность чтения и записи на 50%",
"fileTree22": "Уведомление о большом файле",
"fileTree23": "Появится уведомление, если размер файла .sy или базы данных .json превышает этот предел",
"fileTree24": "Размещать новые дочерние документы вверху",
"fileTree25": "Если включено, новые дочерние документы будут помещаться в начале списка дочерних документов (действует только при включенной пользовательской сортировке)",
"export10": "Например <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code>, если пусто, использовать текст водяного знака или путь к файлу водяного знака.",
"export11": "Обработка блока ссылок при экспорте",
"export12": "Обработка блока встроенного контента при экспорте",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "啟用後儲存 .sy 文件和資料庫 .json 時將使用單行 JSON 格式,大約能減少 30% 檔案大小並提升 50% 讀寫效率",
"fileTree22": "超大檔案提醒",
"fileTree23": ".sy 文件和資料庫 .json 超過該大小時彈出通知提醒",
"fileTree24": "新建子文檔放置在頂部",
"fileTree25": "啟用後新建的子文檔將放置在子文檔列表的頂部(僅在自訂排序啟用時生效)",
"export10": "例如 <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code> ,為空時使用水印文字或浮水印檔案路徑。",
"export11": "匯出時關於塊引用內容的處理方式",
"export12": "匯出時關於嵌入塊內容的處理方式",

View file

@ -1169,6 +1169,8 @@
"fileTree21": "启用后保存 .sy 文档和数据库 .json 时将使用单行 JSON 格式,大约能减少 30% 文件大小并提升 50% 读写效率",
"fileTree22": "超大文件提醒",
"fileTree23": ".sy 文档和数据库 .json 超过该大小时弹出通知提醒",
"fileTree24": "新建子文档放置在顶部",
"fileTree25": "启用后新建的子文档将放置在子文档列表的顶部(仅在自定义排序启用时生效)",
"export10": "例如 <code class='fn__code'>&lt;span style=\"color: #fff;background-color: black;padding: 4px;border-radius: 5px;float:right;\"&gt;SiYuan&lt;/span&gt;</code> ,为空时使用水印文本或水印文件路径。",
"export11": "导出时关于块引用内容的处理方式",
"export12": "导出时关于嵌入块内容的处理方式",

View file

@ -52,6 +52,14 @@ export const fileTree = {
<span class="fn__space"></span>
<input class="b3-switch fn__flex-center" id="useSingleLineSave" type="checkbox"${window.siyuan.config.fileTree.useSingleLineSave ? " checked" : ""}/>
</label>
<label class="fn__flex b3-label">
<div class="fn__flex-1">
${window.siyuan.languages.fileTree24}
<div class="b3-label__text">${window.siyuan.languages.fileTree25}</div>
</div>
<span class="fn__space"></span>
<input class="b3-switch fn__flex-center" id="createDocAtTop" type="checkbox"${window.siyuan.config.fileTree.createDocAtTop ? " checked" : ""}/>
</label>
<div class="fn__flex b3-label config__item">
<div class="fn__flex-1">
${window.siyuan.languages.fileTree22}
@ -125,6 +133,7 @@ export const fileTree = {
allowCreateDeeper: (fileTree.element.querySelector("#allowCreateDeeper") as HTMLInputElement).checked,
removeDocWithoutConfirm: (fileTree.element.querySelector("#removeDocWithoutConfirm") as HTMLInputElement).checked,
useSingleLineSave: (fileTree.element.querySelector("#useSingleLineSave") as HTMLInputElement).checked,
createDocAtTop: (fileTree.element.querySelector("#createDocAtTop") as HTMLInputElement).checked,
largeFileWarningSize: parseInt((fileTree.element.querySelector("#largeFileWarningSize") as HTMLInputElement).value),
maxListCount: parseInt((fileTree.element.querySelector("#maxListCount") as HTMLInputElement).value),
maxOpenTabCount: inputMaxOpenTabCount,

View file

@ -33,7 +33,8 @@ export const initConfigSearch = (element: HTMLElement, app: App) => {
// 文档树
getLang(["selectOpen", "tabLimit", "fileTree", "fileTree2", "fileTree3", "fileTree4", "fileTree5",
"fileTree6", "fileTree7", "fileTree8", "fileTree9", "fileTree10", "fileTree12", "fileTree13", "fileTree15",
"fileTree16", "fileTree17", "fileTree18", "fileTree19", "fileTree20", "fileTree21", "fileTree22", "fileTree23"]),
"fileTree16", "fileTree17", "fileTree18", "fileTree19", "fileTree20", "fileTree21", "fileTree22", "fileTree23",
"fileTree24", "fileTree25"]),
// 闪卡
getLang(["riffCard", "flashcardNewCardLimit", "flashcardNewCardLimitTip", "flashcardReviewCardLimit",

View file

@ -30,6 +30,14 @@ export const initFileTree = () => {
<span class="fn__space"></span>
<input class="b3-switch fn__flex-center" id="useSingleLineSave" type="checkbox"${window.siyuan.config.fileTree.useSingleLineSave ? " checked" : ""}/>
</label>
<label class="fn__flex b3-label">
<div class="fn__flex-1">
${window.siyuan.languages.fileTree24}
<div class="b3-label__text">${window.siyuan.languages.fileTree25}</div>
</div>
<span class="fn__space"></span>
<input class="b3-switch fn__flex-center" id="createDocAtTop" type="checkbox"${window.siyuan.config.fileTree.createDocAtTop ? " checked" : ""}/>
</label>
<div class="b3-label">
${window.siyuan.languages.fileTree22}
<span class="fn__hr"></span>
@ -79,6 +87,7 @@ export const initFileTree = () => {
allowCreateDeeper: (modelMainElement.querySelector("#allowCreateDeeper") as HTMLInputElement).checked,
removeDocWithoutConfirm: (modelMainElement.querySelector("#removeDocWithoutConfirm") as HTMLInputElement).checked,
useSingleLineSave: (modelMainElement.querySelector("#useSingleLineSave") as HTMLInputElement).checked,
createDocAtTop: (modelMainElement.querySelector("#createDocAtTop") as HTMLInputElement).checked,
largeFileWarningSize: parseInt((modelMainElement.querySelector("#largeFileWarningSize") as HTMLInputElement).value),
maxListCount: parseInt((modelMainElement.querySelector("#maxListCount") as HTMLInputElement).value),
maxOpenTabCount: window.siyuan.config.fileTree.maxOpenTabCount,

View file

@ -662,6 +662,10 @@ declare namespace Config {
* The .sy and database .json files larger than this value will prompt a warning (unit: MB)
*/
largeFileWarningSize: number;
/**
* Whether to create new documents at the top of the document tree
*/
createDocAtTop: boolean;
}
/**

View file

@ -34,8 +34,8 @@ type FileTree struct {
CloseTabsOnStart bool `json:"closeTabsOnStart"` // 启动时关闭所有页签
UseSingleLineSave bool `json:"useSingleLineSave"` // 使用单行保存文档 .sy 和属性视图 .json
LargeFileWarningSize int `json:"largeFileWarningSize"` // 大文件警告大小单位MB
Sort int `json:"sort"` // 排序方式
CreateDocAtTop *bool `json:"createDocAtTop"` // 在顶部创建新文档 https://github.com/siyuan-note/siyuan/issues/16327
Sort int `json:"sort"` // 排序方式
}
func NewFileTree() *FileTree {
@ -49,5 +49,6 @@ func NewFileTree() *FileTree {
CloseTabsOnStart: false,
UseSingleLineSave: util.UseSingleLineSave,
LargeFileWarningSize: util.LargeFileWarningSize,
CreateDocAtTop: func() *bool { b := false; return &b }(),
}
}

View file

@ -222,6 +222,9 @@ func InitConf() {
Conf.FileTree.LargeFileWarningSize = 8
}
util.LargeFileWarningSize = Conf.FileTree.LargeFileWarningSize
if nil == Conf.FileTree.CreateDocAtTop { // v3.4.0 之前的版本没有该字段,设置默认值为 true即在顶部创建新文档不改变用户习惯
Conf.FileTree.CreateDocAtTop = func() *bool { b := true; return &b }()
}
util.CurrentCloudRegion = Conf.CloudRegion

View file

@ -1032,7 +1032,7 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string) (tree *parse.Tree
if 0 < len(sorts) {
ChangeFileTreeSort(box.ID, sorts)
} else {
box.addMinSort(path.Dir(tree.Path), tree.ID)
box.setSortByConf(path.Dir(tree.Path), tree.ID)
}
return
}
@ -1079,7 +1079,7 @@ func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bo
logging.LogWarnf("get block tree by id [%s] failed after create", retID)
return
}
box.addMinSort(path.Dir(bt.Path), retID)
box.setSortByConf(path.Dir(bt.Path), retID)
return
}
@ -1994,6 +1994,29 @@ func (box *Box) removeSort(ids []string) {
}
}
func (box *Box) setSortByConf(parentPath, id string) {
if *Conf.FileTree.CreateDocAtTop {
box.addMinSort(parentPath, id)
} else {
box.addMaxSort(parentPath, id)
}
}
func (box *Box) addMaxSort(parentPath, id string) {
docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeUnassigned, false, false, 102400)
if err != nil {
logging.LogErrorf("list doc tree failed: %s", err)
return
}
sortVal := 0
if 0 < len(docs) {
sortVal = docs[len(docs)-1].Sort + 1
}
box.setSortVal(id, sortVal)
}
func (box *Box) addMinSort(parentPath, id string) {
docs, _, err := ListDocTree(box.ID, parentPath, util.SortModeUnassigned, false, false, 1)
if err != nil {
@ -2006,6 +2029,11 @@ func (box *Box) addMinSort(parentPath, id string) {
sortVal = docs[0].Sort - 1
}
box.setSortVal(id, sortVal)
}
func (box *Box) setSortVal(id string, sortVal int) {
var err error
confDir := filepath.Join(util.DataDir, box.ID, ".siyuan")
if err = os.MkdirAll(confDir, 0755); err != nil {
logging.LogErrorf("create conf dir failed: %s", err)
@ -2027,7 +2055,6 @@ func (box *Box) addMinSort(parentPath, id string) {
}
fullSortIDs[id] = sortVal
data, err = gulu.JSON.MarshalJSON(fullSortIDs)
if err != nil {
logging.LogErrorf("marshal sort conf failed: %s", err)
@ -2037,6 +2064,7 @@ func (box *Box) addMinSort(parentPath, id string) {
logging.LogErrorf("write sort conf failed: %s", err)
return
}
return
}
func (box *Box) addSort(previousPath, id string) {

View file

@ -431,7 +431,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string) (sr
if "" != previousPath {
box.addSort(previousPath, newTree.ID)
} else {
box.addMinSort(path.Dir(newTargetPath), newTree.ID)
box.setSortByConf(path.Dir(newTargetPath), newTree.ID)
}
if err = indexWriteTreeUpsertQueue(newTree); err != nil {
return "", "", err

View file

@ -132,7 +132,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string) (
if "" != previousPath {
box.addSort(previousPath, newTree.ID)
} else {
box.addMinSort(path.Dir(newTargetPath), newTree.ID)
box.setSortByConf(path.Dir(newTargetPath), newTree.ID)
}
if err = indexWriteTreeUpsertQueue(newTree); err != nil {
return "", "", err

View file

@ -106,7 +106,7 @@ func MoveLocalShorthands(boxID, hPath, parentID string) (retIDs []string, err er
retIDs = append(retIDs, retID)
toRemoves = append(toRemoves, p)
box.addMinSort("/", retID)
box.setSortByConf("/", retID)
}
} else { // 不为空的话将所有速记合并到指定路径的文档中
if !strings.HasPrefix(hPath, "/") {