Skip to content

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

:sparkles: Close detached windows with their last tab https://github.com/siyuan-note/siyuan/issues/20736

Danielcbeb0ecc21d2
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index b14438735b..c272487d2a 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "إغلاق النافذة الجديدة مع آخر علامة تبويب",
+ "closeWindowOnLastTabClosedTip": "إغلاق النافذة الجديدة عند إغلاق آخر علامة تبويب فيها أو سحبها إلى نافذة أخرى",
"tabToMainWindow": "نقل إلى النافذة الرئيسية",
"workspaceStorageView": "عرض",
"listMindmapDocumentLayout": "تخطيط المستند",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index e2e80f58f8..698cd6522e 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Neues Fenster mit dem letzten Tab schließen",
+ "closeWindowOnLastTabClosedTip": "Das neue Fenster schließen, wenn sein letzter Tab geschlossen oder in ein anderes Fenster gezogen wird",
"tabToMainWindow": "In das Hauptfenster verschieben",
"workspaceStorageView": "Anzeigen",
"listMindmapDocumentLayout": "Dokumentlayout",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index ee0cd70b66..844932f90d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Close new window with last tab",
+ "closeWindowOnLastTabClosedTip": "Close the new window when its last tab is closed or dragged to another window",
"tabToMainWindow": "Move to main window",
"workspaceStorageView": "View",
"listMindmapDocumentLayout": "Document layout",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index db5d8a6585..07f0b4e785 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Cerrar la nueva ventana con la última pestaña",
+ "closeWindowOnLastTabClosedTip": "Cerrar la nueva ventana al cerrar su última pestaña o arrastrarla a otra ventana",
"tabToMainWindow": "Mover a la ventana principal",
"workspaceStorageView": "Ver",
"listMindmapDocumentLayout": "Diseño del documento",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 84cea7b735..8cb59c797f 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Fermer la nouvelle fenêtre avec le dernier onglet",
+ "closeWindowOnLastTabClosedTip": "Fermer la nouvelle fenêtre lorsque son dernier onglet est fermé ou déplacé vers une autre fenêtre",
"tabToMainWindow": "Déplacer vers la fenêtre principale",
"workspaceStorageView": "Afficher",
"listMindmapDocumentLayout": "Disposition du document",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 59e2edde16..a63b2da5d2 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "סגירת החלון החדש עם הלשונית האחרונה",
+ "closeWindowOnLastTabClosedTip": "סגירת החלון החדש כאשר הלשונית האחרונה בו נסגרת או נגררת לחלון אחר",
"tabToMainWindow": "העברה לחלון הראשי",
"workspaceStorageView": "הצג",
"listMindmapDocumentLayout": "פריסת המסמך",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 5029ce2fe3..19e850e97f 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "अंतिम टैब के साथ नई विंडो बंद करें",
+ "closeWindowOnLastTabClosedTip": "अंतिम टैब बंद होने या दूसरी विंडो में खींचे जाने पर नई विंडो बंद करें",
"tabToMainWindow": "मुख्य विंडो में ले जाएँ",
"workspaceStorageView": "देखें",
"listMindmapDocumentLayout": "दस्तावेज़ लेआउट",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 3b99f15884..8755444816 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Tutup jendela baru bersama tab terakhir",
+ "closeWindowOnLastTabClosedTip": "Tutup jendela baru saat tab terakhirnya ditutup atau diseret ke jendela lain",
"tabToMainWindow": "Pindahkan ke jendela utama",
"workspaceStorageView": "Lihat",
"listMindmapDocumentLayout": "Tata letak dokumen",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index f2340c3b99..f166d489c1 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Chiudi la nuova finestra con l'ultima scheda",
+ "closeWindowOnLastTabClosedTip": "Chiudi la nuova finestra quando l'ultima scheda viene chiusa o trascinata in un'altra finestra",
"tabToMainWindow": "Sposta nella finestra principale",
"workspaceStorageView": "Visualizza",
"listMindmapDocumentLayout": "Layout del documento",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 5e3a4acf70..7bddc5c091 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "最後のタブとともに新しいウィンドウを閉じる",
+ "closeWindowOnLastTabClosedTip": "新しいウィンドウの最後のタブを閉じるか別のウィンドウへドラッグしたときに、そのウィンドウを閉じます",
"tabToMainWindow": "メインウィンドウに移動",
"workspaceStorageView": "表示",
"listMindmapDocumentLayout": "文書内のレイアウト",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index a4ddcbfee8..b69ef17ef0 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "마지막 탭과 함께 새 창 닫기",
+ "closeWindowOnLastTabClosedTip": "새 창의 마지막 탭을 닫거나 다른 창으로 드래그하면 해당 창 닫기",
"tabToMainWindow": "기본 창으로 이동",
"workspaceStorageView": "보기",
"listMindmapDocumentLayout": "문서 레이아웃",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index e27b597bae..dde5e5a1ff 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Nieuw venster sluiten met het laatste tabblad",
+ "closeWindowOnLastTabClosedTip": "Sluit het nieuwe venster wanneer het laatste tabblad wordt gesloten of naar een ander venster wordt gesleept",
"tabToMainWindow": "Naar hoofdvenster verplaatsen",
"workspaceStorageView": "Bekijken",
"listMindmapDocumentLayout": "Documentindeling",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 8684fc874b..553e5447ef 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Zamknij nowe okno wraz z ostatnią kartą",
+ "closeWindowOnLastTabClosedTip": "Zamknij nowe okno po zamknięciu jego ostatniej karty lub przeciągnięciu jej do innego okna",
"tabToMainWindow": "Przenieś do głównego okna",
"workspaceStorageView": "Pokaż",
"listMindmapDocumentLayout": "Układ dokumentu",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 6a1b176525..a0fc18367e 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Fechar a nova janela com a última aba",
+ "closeWindowOnLastTabClosedTip": "Fechar a nova janela quando sua última aba for fechada ou arrastada para outra janela",
"tabToMainWindow": "Mover para a janela principal",
"workspaceStorageView": "Ver",
"listMindmapDocumentLayout": "Layout do documento",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 97e65b6b43..96d9f66c9c 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Закрывать новое окно вместе с последней вкладкой",
+ "closeWindowOnLastTabClosedTip": "Закрывать новое окно при закрытии его последней вкладки или её перетаскивании в другое окно",
"tabToMainWindow": "Переместить в главное окно",
"workspaceStorageView": "Показать",
"listMindmapDocumentLayout": "Макет документа",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 919bb90dd9..f6cf74860a 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Zavrieť nové okno s poslednou kartou",
+ "closeWindowOnLastTabClosedTip": "Zavrieť nové okno po zatvorení jeho poslednej karty alebo jej presunutí do iného okna",
"tabToMainWindow": "Presunúť do hlavného okna",
"workspaceStorageView": "Zobraziť",
"listMindmapDocumentLayout": "Rozloženie dokumentu",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 448d10b8f5..6ee3f9b3c6 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Затвори нови прозор са последњом картицом",
+ "closeWindowOnLastTabClosedTip": "Затвори нови прозор када се његова последња картица затвори или превуче у други прозор",
"tabToMainWindow": "Премести у главни прозор",
"workspaceStorageView": "Прикажи",
"listMindmapDocumentLayout": "Распоред документа",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 769adf96bb..aa14fc624a 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "ปิดหน้าต่างใหม่พร้อมแท็บสุดท้าย",
+ "closeWindowOnLastTabClosedTip": "ปิดหน้าต่างใหม่เมื่อปิดแท็บสุดท้ายหรือลากแท็บนั้นไปยังหน้าต่างอื่น",
"tabToMainWindow": "ย้ายไปยังหน้าต่างหลัก",
"workspaceStorageView": "ดู",
"listMindmapDocumentLayout": "เค้าโครงเอกสาร",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 18fa9ab965..e8b2477a90 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Son sekmeyle birlikte yeni pencereyi kapat",
+ "closeWindowOnLastTabClosedTip": "Son sekmesi kapatıldığında veya başka bir pencereye sürüklendiğinde yeni pencereyi kapat",
"tabToMainWindow": "Ana pencereye taşı",
"workspaceStorageView": "Görüntüle",
"listMindmapDocumentLayout": "Belge düzeni",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index e70c3ce1ae..838faa2ef6 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "Закривати нове вікно разом з останньою вкладкою",
+ "closeWindowOnLastTabClosedTip": "Закривати нове вікно після закриття його останньої вкладки або перетягування її до іншого вікна",
"tabToMainWindow": "Перемістити до головного вікна",
"workspaceStorageView": "Переглянути",
"listMindmapDocumentLayout": "Макет документа",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 1542299b4a..1e7852c17b 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "新窗口随最后一个页签关闭",
+ "closeWindowOnLastTabClosedTip": "把新窗口的最后一个页签关闭或拖拽到其他窗口之后,关闭该窗口",
"tabToMainWindow": "移动到主窗口",
"workspaceStorageView": "查看",
"listMindmapDocumentLayout": "文档布局",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index b123134378..26e8978350 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "closeWindowOnLastTabClosed": "新視窗隨最後一個頁籤關閉",
+ "closeWindowOnLastTabClosedTip": "將新視窗的最後一個頁籤關閉或拖曳到其他視窗後,關閉該視窗",
"tabToMainWindow": "移動到主視窗",
"workspaceStorageView": "查看",
"listMindmapDocumentLayout": "文件版面",
diff --git a/app/src/config/tabs/fileTab.test.ts b/app/src/config/tabs/fileTab.test.ts
index 73838895f5..18f2f98471 100644
--- a/app/src/config/tabs/fileTab.test.ts
+++ b/app/src/config/tabs/fileTab.test.ts
@@ -16,6 +16,28 @@ const compile = (file: string, extra = "") => ts.transpileModule(
{compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}},
).outputText;
+test("desktop tab settings end with startup behavior and last-tab window closing", () => {
+ const {parse} = require("ifdef-loader/preprocessor");
+ for (const mode of [{MOBILE: false, BROWSER: false}, {MOBILE: false, BROWSER: true},
+ {MOBILE: true, BROWSER: false}]) {
+ const source = parse(readFileSync(join(__dirname, "fileTab.ts"), "utf8"), mode, false, true) +
+ "\nexport {registerTabStartupGroup};";
+ const code = ts.transpileModule(source, {compilerOptions: {module: ts.ModuleKind.CommonJS}}).outputText;
+ const exports: {registerTabStartupGroup?: (tab: unknown) => void} = {};
+ const items: string[] = [];
+ const record = (key: string) => items.push(key);
+ runInNewContext(code, {exports, require: () => ({}),
+ window: {siyuan: {languages: {}}}});
+ exports.registerTabStartupGroup({group: () => ({switch: record, number: record, select: record})});
+ if (mode.MOBILE || mode.BROWSER) {
+ assert.equal(items.at(-1), "fileTree.tabStartupMode");
+ assert.ok(!items.includes("fileTree.closeWindowOnLastTabClosed"));
+ } else {
+ assert.deepEqual(items.slice(-2), ["fileTree.tabStartupMode", "fileTree.closeWindowOnLastTabClosed"]);
+ }
+ }
+});
+
const loadBehaviorSettings = (config: {docIconClickMode?: number, parentDocTitleClickMode?: number} = {}) => {
const fileTree = {docIconClickMode: 0, parentDocTitleClickMode: 0, ...config};
const languages = {
diff --git a/app/src/config/tabs/fileTab.ts b/app/src/config/tabs/fileTab.ts
index 2d1e5c99c1..9862890d50 100644
--- a/app/src/config/tabs/fileTab.ts
+++ b/app/src/config/tabs/fileTab.ts
@@ -95,6 +95,16 @@ const registerTabStartupGroup = (tab: SettingTabBuilder) => {
min: 1,
max: 32,
});
+ /// #if !MOBILE
+ group.switch("fileTree.openFilesUseCurrentTab", {
+ title: window.siyuan.languages.fileTree7,
+ desc: window.siyuan.languages.fileTree8,
+ });
+ group.switch("fileTree.noSplitScreenWhenOpenTab", {
+ title: window.siyuan.languages.noSplitScreenWhenOpenTab,
+ desc: window.siyuan.languages.noSplitScreenWhenOpenTabTip,
+ });
+ /// #endif
group.select("fileTree.tabStartupMode", {
title: window.siyuan.languages.tabStartupMode,
desc: window.siyuan.languages.tabStartupModeTip,
@@ -104,14 +114,10 @@ const registerTabStartupGroup = (tab: SettingTabBuilder) => {
{value: 2, label: window.siyuan.languages.tabStartupClose},
],
});
- /// #if !MOBILE
- group.switch("fileTree.openFilesUseCurrentTab", {
- title: window.siyuan.languages.fileTree7,
- desc: window.siyuan.languages.fileTree8,
- });
- group.switch("fileTree.noSplitScreenWhenOpenTab", {
- title: window.siyuan.languages.noSplitScreenWhenOpenTab,
- desc: window.siyuan.languages.noSplitScreenWhenOpenTabTip,
+ /// #if !MOBILE && !BROWSER
+ group.switch("fileTree.closeWindowOnLastTabClosed", {
+ title: window.siyuan.languages.closeWindowOnLastTabClosed,
+ desc: window.siyuan.languages.closeWindowOnLastTabClosedTip,
});
/// #endif
};
diff --git a/app/src/layout/Wnd.ts b/app/src/layout/Wnd.ts
index 6d0c7cdd30..a6e041516b 100644
--- a/app/src/layout/Wnd.ts
+++ b/app/src/layout/Wnd.ts
@@ -26,6 +26,7 @@ import {Constants} from "../constants";
/// #if !BROWSER
import {ipcRenderer, webFrame} from "electron";
import {setModelsHash} from "../window/setHeader";
+import {closeWindowAfterLastTab, flushClosingWindowTab} from "../window/closeWin";
/// #endif
import {showMessage} from "../dialog/message";
import {openFileById, updatePanelByEditor} from "../editor/util";
@@ -998,10 +999,17 @@ export class Wnd {
}
private removeTabAction = (id: string, isBatchClose = false, animate = true, isSaveLayout = true) => {
+ let removedTab = false;
this.children.find((item, index) => {
if (item.id !== id) {
return;
}
+ removedTab = !!item.headElement;
+ /// #if !BROWSER
+ if (removedTab && item.model instanceof Editor && item.model.editor) {
+ flushClosingWindowTab(item.model.editor);
+ }
+ /// #endif
window.siyuan.storage[Constants.LOCAL_CLOSED_TABS] =
sanitizeClosedTabs(window.siyuan.storage[Constants.LOCAL_CLOSED_TABS]);
if (item.headElement && !isSensitiveTab(item)) {
@@ -1107,6 +1115,9 @@ export class Wnd {
webFrame.clearCache();
ipcRenderer.send(Constants.SIYUAN_CMD, "clearCache");
setModelsHash();
+ if (removedTab) {
+ void closeWindowAfterLastTab(this.app);
+ }
/// #endif
};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 8216d84243..fcb158e590 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -1912,7 +1912,7 @@ export type SetEntryVisibilityRequestInput = { "active"?: string | null; "profil
export type SetExportRequestInput = { "addTitle"?: boolean | null; "blockEmbedMode"?: number | null; "blockRefMode"?: number | null; "blockRefTextLeft"?: string | null; "blockRefTextRight"?: string | null; "fileAnnotationRefMode"?: number | null; "imageWatermarkDesc"?: string | null; "imageWatermarkStr"?: string | null; "includeRelatedDocs"?: boolean | null; "includeSubDocs"?: boolean | null; "inlineMemo"?: boolean | null; "markdownYFM"?: boolean | null; "pandocBin"?: string | null; "pandocParams"?: string | null; "paragraphBeginningSpace"?: boolean | null; "pdfFooter"?: string | null; "pdfWatermarkDesc"?: string | null; "pdfWatermarkStr"?: string | null; "removeAssetsID"?: boolean | null; "tagCloseMarker"?: string | null; "tagOpenMarker"?: string | null; };
-export type SetFiletreeRequestInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "recentDocsSort"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };
+export type SetFiletreeRequestInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "closeWindowOnLastTabClosed"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "recentDocsSort"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };
export type SetFlashcardRequestInput = { "blockquote"?: boolean | null; "callout"?: boolean | null; "deck"?: boolean | null; "heading"?: boolean | null; "list"?: boolean | null; "mark"?: boolean | null; "maximumInterval"?: number | null; "newCardLimit"?: number | null; "requestRetention"?: number | null; "reviewCardLimit"?: number | null; "reviewMode"?: number | null; "superBlock"?: boolean | null; "weights"?: string | null; };
@@ -2072,9 +2072,9 @@ export type SettingExport = { "addTitle": boolean; "blockEmbedMode": number; "bl
export type SettingExportInput = { "addTitle"?: boolean | null; "blockEmbedMode"?: number | null; "blockRefMode"?: number | null; "blockRefTextLeft"?: string | null; "blockRefTextRight"?: string | null; "fileAnnotationRefMode"?: number | null; "imageWatermarkDesc"?: string | null; "imageWatermarkStr"?: string | null; "includeRelatedDocs"?: boolean | null; "includeSubDocs"?: boolean | null; "inlineMemo"?: boolean | null; "markdownYFM"?: boolean | null; "pandocBin"?: string | null; "pandocParams"?: string | null; "paragraphBeginningSpace"?: boolean | null; "pdfFooter"?: string | null; "pdfWatermarkDesc"?: string | null; "pdfWatermarkStr"?: string | null; "removeAssetsID"?: boolean | null; "tagCloseMarker"?: string | null; "tagOpenMarker"?: string | null; };
-export type SettingFileTree = { "allowCreateDeeper": boolean; "alwaysSelectOpenedFile": boolean; "boxDocEnabled": boolean | null; "closeTabOnDoubleClick": boolean; "closeTabsOnStart": boolean; "createDocAtTop": boolean | null; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTemplatePath": string; "docIconClickMode": number; "largeFileWarningSize": number; "maxListCount": number; "maxOpenTabCount": number; "noSplitScreenWhenOpenTab": boolean; "openFilesUseCurrentTab": boolean; "parentDocTitleClickMode": number; "recentDocsMaxListCount": number; "recentDocsSort": string; "refCreateSaveBox": string; "refCreateSavePath": string; "removeDocWithoutConfirm": boolean; "shorthandSaveBox": string; "shorthandSavePath": string; "sort": number; "tabStartupMode": number | null; "useSVGDefaultIcon": boolean | null; "useSingleLineSave": boolean; };
+export type SettingFileTree = { "allowCreateDeeper": boolean; "alwaysSelectOpenedFile": boolean; "boxDocEnabled": boolean | null; "closeTabOnDoubleClick": boolean; "closeTabsOnStart": boolean; "closeWindowOnLastTabClosed": boolean | null; "createDocAtTop": boolean | null; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTemplatePath": string; "docIconClickMode": number; "largeFileWarningSize": number; "maxListCount": number; "maxOpenTabCount": number; "noSplitScreenWhenOpenTab": boolean; "openFilesUseCurrentTab": boolean; "parentDocTitleClickMode": number; "recentDocsMaxListCount": number; "recentDocsSort": string; "refCreateSaveBox": string; "refCreateSavePath": string; "removeDocWithoutConfirm": boolean; "shorthandSaveBox": string; "shorthandSavePath": string; "sort": number; "tabStartupMode": number | null; "useSVGDefaultIcon": boolean | null; "useSingleLineSave": boolean; };
-export type SettingFileTreeInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "recentDocsSort"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };
+export type SettingFileTreeInput = { "allowCreateDeeper"?: boolean | null; "alwaysSelectOpenedFile"?: boolean | null; "boxDocEnabled"?: boolean | null; "closeTabOnDoubleClick"?: boolean | null; "closeTabsOnStart"?: boolean | null; "closeWindowOnLastTabClosed"?: boolean | null; "createDocAtTop"?: boolean | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "docIconClickMode"?: number | null; "largeFileWarningSize"?: number | null; "maxListCount"?: number | null; "maxOpenTabCount"?: number | null; "noSplitScreenWhenOpenTab"?: boolean | null; "openFilesUseCurrentTab"?: boolean | null; "parentDocTitleClickMode"?: number | null; "recentDocsMaxListCount"?: number | null; "recentDocsSort"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "removeDocWithoutConfirm"?: boolean | null; "shorthandSaveBox"?: string | null; "shorthandSavePath"?: string | null; "sort"?: number | null; "tabStartupMode"?: number | null; "useSVGDefaultIcon"?: boolean | null; "useSingleLineSave"?: boolean | null; };
export type SettingFlashcard = { "blockquote": boolean; "callout": boolean; "deck": boolean; "heading": boolean; "list": boolean; "mark": boolean; "maximumInterval": number; "newCardLimit": number; "requestRetention": number; "reviewCardLimit": number; "reviewMode": number; "superBlock": boolean; "weights": string; };
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index ff22baeebe..a3fed3b709 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -1029,6 +1029,11 @@ declare namespace Config {
* Whether to close tabs by double-clicking
*/
closeTabOnDoubleClick: boolean;
+ /**
+ * Close a detached desktop window after its last tab is closed or moved out.
+ * Defaults to true; does not affect the main window.
+ */
+ closeWindowOnLastTabClosed: boolean;
/**
* The storage path of the new document created using block references
*/
diff --git a/app/src/window/closeWin.test.ts b/app/src/window/closeWin.test.ts
index 65c7c58db4..66c472d309 100644
--- a/app/src/window/closeWin.test.ts
+++ b/app/src/window/closeWin.test.ts
@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, transpileModule} from "typescript";
+import type {Protyle} from "../protyle";
test("窗口关闭等待持久化,保存失败时保留窗口并允许重试", async () => {
const compiled = transpileModule(readFileSync("src/window/closeWin.ts", "utf8"), {
@@ -31,3 +32,102 @@ test("窗口关闭等待持久化,保存失败时保留窗口并允许重试",
await saved;
assert.deepEqual(calls, ["error", "plugins", "destroy"]);
});
+
+test("last-tab closing respects window type, settings, remaining tabs and save-time changes", async () => {
+ const compiled = transpileModule(readFileSync("src/window/closeWin.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS},
+ }).outputText;
+ let detached = true;
+ let tabs: {headElement?: object}[] = [{}];
+ let finish: (saved: boolean) => void;
+ const calls: string[] = [];
+ const state = {config: {fileTree: {closeWindowOnLastTabClosed: true}},
+ layout: {centerLayout: {}}, languages: {windowWorkspaceSaveError: "error"}};
+ const dependencies = {
+ Constants: {SIYUAN_CMD: "cmd"},
+ ipcRenderer: {send: (_channel: string, cmd: string) => calls.push(cmd)},
+ flushWindowWorkspace: () => new Promise<boolean>(resolve => {
+ calls.push("save");
+ finish = resolve;
+ }),
+ destroyWindowPluginKernels: () => calls.push("plugins"),
+ showMessage: () => calls.push("error"),
+ isWindow: () => detached,
+ getAllTabs: () => tabs,
+ };
+ const api = {} as {closeWindowAfterLastTab: (app: object) => Promise<void>};
+ runInNewContext(compiled, {exports: api, require: () => dependencies, window: {siyuan: state}, console});
+ detached = false;
+ await api.closeWindowAfterLastTab({});
+ detached = true;
+ state.config.fileTree.closeWindowOnLastTabClosed = false;
+ await api.closeWindowAfterLastTab({});
+ state.config.fileTree.closeWindowOnLastTabClosed = true;
+ tabs = [{}, {headElement: {}}]; // Another split still contains a tab.
+ await api.closeWindowAfterLastTab({});
+ tabs = [{}];
+ const replacement = api.closeWindowAfterLastTab({});
+ tabs.push({headElement: {}});
+ await replacement;
+ assert.deepEqual(calls, []);
+
+ tabs = [{}];
+ const interrupted = api.closeWindowAfterLastTab({});
+ await Promise.resolve();
+ tabs.push({headElement: {}});
+ finish(true);
+ await interrupted;
+ assert.deepEqual(calls, ["save"]);
+
+ tabs = [{}];
+ const failed = api.closeWindowAfterLastTab({});
+ await Promise.resolve();
+ finish(false);
+ await failed;
+ assert.deepEqual(calls, ["save", "save", "error"]);
+ const closed = api.closeWindowAfterLastTab({});
+ await Promise.resolve();
+ finish(true);
+ await closed;
+ assert.deepEqual(calls, ["save", "save", "error", "save", "plugins", "destroy"]);
+});
+
+test("last-tab closing waits for input and transactions from all removed tabs", async () => {
+ const compiled = transpileModule(readFileSync("src/window/closeWin.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS},
+ }).outputText;
+ const calls: string[] = [];
+ const dependencies = {
+ Constants: {SIYUAN_CMD: "cmd"},
+ ipcRenderer: {send: (_channel: string, cmd: string) => calls.push(cmd)},
+ flushWindowWorkspace: async () => { calls.push("workspace"); return true; },
+ destroyWindowPluginKernels: () => calls.push("plugins"),
+ showMessage: () => calls.push("error"),
+ isWindow: () => true, getAllTabs: () => [{}],
+ };
+ const api = {} as {
+ closeWindowAfterLastTab: (app: object) => Promise<void>;
+ flushClosingWindowTab: (editor: Protyle) => void;
+ };
+ runInNewContext(compiled, {exports: api, require: () => dependencies,
+ console: {error: () => calls.push("save-failed")}, window: {siyuan: {
+ config: {fileTree: {closeWindowOnLastTabClosed: true}},
+ layout: {centerLayout: {}}, languages: {windowWorkspaceSaveError: "error"},
+ }}});
+ let finishFirst: () => void;
+ let finishSecond: () => void;
+ api.flushClosingWindowTab({flushPendingTransactions: () => new Promise<void>(resolve => finishFirst = resolve)} as Protyle);
+ api.flushClosingWindowTab({flushPendingTransactions: () => new Promise<void>(resolve => finishSecond = resolve)} as Protyle);
+ const closed = api.closeWindowAfterLastTab({});
+ finishSecond();
+ await Promise.resolve();
+ assert.deepEqual(calls, []);
+ finishFirst();
+ await closed;
+ assert.deepEqual(calls, ["workspace", "plugins", "destroy"]);
+
+ calls.length = 0;
+ api.flushClosingWindowTab({flushPendingTransactions: async (): Promise<void> => { throw Error("failed"); }} as Protyle);
+ await api.closeWindowAfterLastTab({});
+ assert.deepEqual(calls, ["save-failed", "error"]);
+});
diff --git a/app/src/window/closeWin.ts b/app/src/window/closeWin.ts
index df99ebb47a..252c02853e 100644
--- a/app/src/window/closeWin.ts
+++ b/app/src/window/closeWin.ts
@@ -4,9 +4,28 @@ import {ipcRenderer} from "electron";
import {destroyWindowPluginKernels} from "./closeWinCore";
import {flushWindowWorkspace} from "./workspace";
import {showMessage} from "../dialog/message";
+import {isWindow} from "../util/functions";
+import {getAllTabs} from "../layout/getAll";
+import type {Protyle} from "../protyle";
let closing = false;
-export const closeWindow = async (app: App) => {
+const pendingTabSaves = new Set<Promise<boolean>>();
+
+export const flushClosingWindowTab = (editor: Protyle) => {
+ if (!isWindow() || !window.siyuan.config.fileTree.closeWindowOnLastTabClosed) {
+ return;
+ }
+ const task = editor.flushPendingTransactions().then(() => {
+ pendingTabSaves.delete(task);
+ return true;
+ }, error => {
+ console.error(error);
+ return false;
+ });
+ pendingTabSaves.add(task);
+};
+
+export const closeWindow = async (app: App, shouldClose?: () => boolean) => {
if (closing) {
return;
}
@@ -16,6 +35,10 @@ export const closeWindow = async (app: App) => {
showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
return;
}
+ // A new tab can arrive while the detached window's workspace is saving.
+ if (shouldClose && !shouldClose()) {
+ return;
+ }
destroyWindowPluginKernels(app.plugins, error => console.error(error));
ipcRenderer.send(Constants.SIYUAN_CMD, "destroy");
} catch (error) {
@@ -25,3 +48,26 @@ export const closeWindow = async (app: App) => {
closing = false;
}
};
+
+export const closeWindowAfterLastTab = async (app: App) => {
+ const shouldClose = () => isWindow() &&
+ window.siyuan.config.fileTree.closeWindowOnLastTabClosed &&
+ !!window.siyuan.layout.centerLayout &&
+ !getAllTabs().some(tab => !!tab.headElement);
+ // Finish synchronous tab replacement/layout changes before checking the window.
+ await Promise.resolve();
+ if (shouldClose()) {
+ while (pendingTabSaves.size) {
+ const saves = Array.from(pendingTabSaves);
+ if ((await Promise.all(saves)).some(saved => !saved)) {
+ saves.forEach(save => pendingTabSaves.delete(save));
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ return;
+ }
+ }
+ if (!shouldClose()) {
+ return;
+ }
+ await closeWindow(app, shouldClose);
+ }
+};
diff --git a/kernel/api/contract_setting_close_window_test.go b/kernel/api/contract_setting_close_window_test.go
new file mode 100644
index 0000000000..144e9a2ca7
--- /dev/null
+++ b/kernel/api/contract_setting_close_window_test.go
@@ -0,0 +1,66 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractSettingCloseWindowOnLastTab(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ previousConf, previousReadOnly, previousConfDir := model.Conf, util.ReadOnly, util.ConfDir
+ util.ReadOnly, util.ConfDir = true, t.TempDir()
+ t.Cleanup(func() { model.Conf, util.ReadOnly, util.ConfDir = previousConf, previousReadOnly, previousConfDir })
+ engine := gin.New()
+ engine.POST("/api/setting/setFiletree", setFiletree)
+ engine.POST("/api/setting/patch", patchSetting)
+ for _, path := range []string{"/api/setting/setFiletree", "/api/setting/patch"} {
+ for _, entry := range []struct {
+ body string
+ want bool
+ ok bool
+ }{
+ {`{"maxOpenTabCount":8}`, false, true},
+ {`{"closeWindowOnLastTabClosed":true}`, true, true},
+ {`{"closeWindowOnLastTabClosed":false}`, false, true},
+ {`{"closeWindowOnLastTabClosed":null}`, true, true},
+ {`{"closeWindowOnLastTabClosed":"true"}`, false, false},
+ } {
+ model.Conf = model.NewAppConf()
+ fileTree := conf.NewFileTree()
+ fileTree.CloseWindowOnLastTabClosed = new(false)
+ model.Conf.FileTree.Store(fileTree)
+ body := entry.body
+ if path == "/api/setting/patch" {
+ body = `{"fileTree":` + body + `}`
+ }
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest("POST", path, strings.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+ requireAPIContract(t, "POST", path, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data *apicontract.SettingFileTree `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if (response.Code == 0) != entry.ok || *model.Conf.FileTree.Load().CloseWindowOnLastTabClosed != entry.want {
+ t.Fatalf("%s %s: unexpected result %s", path, body, recorder.Body.String())
+ }
+ if entry.ok && path == "/api/setting/setFiletree" &&
+ (response.Data == nil || response.Data.CloseWindowOnLastTabClosed == nil ||
+ *response.Data.CloseWindowOnLastTabClosed != entry.want) {
+ t.Fatalf("response lost last-tab close preference: %s", recorder.Body.String())
+ }
+ }
+ }
+}
diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.go
index 0490f274e9..49bc32f8f5 100644
--- a/kernel/api/setting_contract.go
+++ b/kernel/api/setting_contract.go
@@ -507,6 +507,7 @@ func settingFileTreePayload(value *conf.FileTree) *apicontract.SettingFileTree {
result.AlwaysSelectOpenedFile = value.AlwaysSelectOpenedFile
result.OpenFilesUseCurrentTab = value.OpenFilesUseCurrentTab
result.CloseTabOnDoubleClick = value.CloseTabOnDoubleClick
+ result.CloseWindowOnLastTabClosed = value.CloseWindowOnLastTabClosed
result.DocIconClickMode = value.DocIconClickMode
result.ParentDocTitleClickMode = value.ParentDocTitleClickMode
boxDocEnabled := value.BoxDocEnabled
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 5ece0ccfdb..352ef5db1b 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -41715,6 +41715,16 @@
}
]
},
+ "closeWindowOnLastTabClosed": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"createDocAtTop": {
"anyOf": [
{
@@ -46953,6 +46963,16 @@
"closeTabsOnStart": {
"type": "boolean"
},
+ "closeWindowOnLastTabClosed": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"createDocAtTop": {
"anyOf": [
{
@@ -47047,6 +47067,7 @@
"boxDocEnabled",
"closeTabOnDoubleClick",
"closeTabsOnStart",
+ "closeWindowOnLastTabClosed",
"createDocAtTop",
"docCreateSaveBox",
"docCreateSavePath",
@@ -47125,6 +47146,16 @@
}
]
},
+ "closeWindowOnLastTabClosed": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"createDocAtTop": {
"anyOf": [
{
diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.go
index 7a9f3fff39..033de61876 100644
--- a/kernel/apicontract/setting.go
+++ b/kernel/apicontract/setting.go
@@ -343,6 +343,8 @@ type SettingFileTree struct {
AlwaysSelectOpenedFile bool `json:"alwaysSelectOpenedFile" api:"optional,nullable"`
OpenFilesUseCurrentTab bool `json:"openFilesUseCurrentTab" api:"optional,nullable"`
CloseTabOnDoubleClick bool `json:"closeTabOnDoubleClick" api:"optional,nullable"`
+ // 默认 true;关闭或移走独立桌面窗口的最后一个页签后关闭该窗口,不影响主窗口。省略时保留现值,null 恢复默认。
+ CloseWindowOnLastTabClosed *bool `json:"closeWindowOnLastTabClosed" api:"optional,nullable"`
// 单击文档图标或笔记本图标的行为:0 修改图标,1 展开或折叠子文档。无子文档时,1 在有可打开文档时打开文档,否则修改图标。
// 超出取值范围的输入按 0 处理。已废弃的 docIconClickExpand 不再读取,旧配置升级后回到 0。
DocIconClickMode int `json:"docIconClickMode" api:"optional,nullable"`
diff --git a/kernel/conf/filetree.go b/kernel/conf/filetree.go
index 4de5f9e0ea..29d7fec713 100644
--- a/kernel/conf/filetree.go
+++ b/kernel/conf/filetree.go
@@ -21,55 +21,57 @@ import (
)
type FileTree struct {
- RecentDocsSort string `json:"recentDocsSort"` // 最近文档排序方式
- AlwaysSelectOpenedFile bool `json:"alwaysSelectOpenedFile"` // 是否自动选中当前打开的文件
- OpenFilesUseCurrentTab bool `json:"openFilesUseCurrentTab"` // 在当前页签打开文件
- CloseTabOnDoubleClick bool `json:"closeTabOnDoubleClick"` // 是否使用双击关闭页签
- DocIconClickMode int `json:"docIconClickMode"` // 单击文档图标或笔记本图标的行为:0 修改图标,1 展开或折叠子文档
- ParentDocTitleClickMode int `json:"parentDocTitleClickMode"` // 点击父文档标题的行为:0 打开文档,1 展开或折叠子文档,2 单击展开或折叠子文档、双击打开父文档
- BoxDocEnabled bool `json:"boxDocEnabled"` // 是否启用顶层笔记本文档
- UseSVGDefaultIcon bool `json:"useSVGDefaultIcon"` // 是否使用 SVG 默认图标
- RefCreateSaveBox string `json:"refCreateSaveBox"` // 块引时新建文档存储笔记本
- RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径
- DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本
- DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径
- DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径
- ShorthandSaveBox string `json:"shorthandSaveBox"` // 闪念速记存储笔记本
- ShorthandSavePath string `json:"shorthandSavePath"` // 闪念速记存储路径
- MaxListCount int `json:"maxListCount"` // 最大列出数量
- MaxOpenTabCount int `json:"maxOpenTabCount"` // 最大打开页签数量
- AllowCreateDeeper bool `json:"allowCreateDeeper"` // 允许创建超过 7 层深度的子文档
- RemoveDocWithoutConfirm bool `json:"removeDocWithoutConfirm"` // 删除文档时是否不需要确认
- CloseTabsOnStart bool `json:"closeTabsOnStart"` // 启动时关闭所有页签
- TabStartupMode *int `json:"tabStartupMode"` // 页签启动策略:0 恢复,1 新建空白页签,2 关闭已打开页签
- UseSingleLineSave bool `json:"useSingleLineSave"` // 使用单行保存文档 .sy 和属性视图 .json
- LargeFileWarningSize int `json:"largeFileWarningSize"` // 大文件警告大小(单位:MB)
- CreateDocAtTop *bool `json:"createDocAtTop"` // 在顶部创建新文档 https://github.com/siyuan-note/siyuan/issues/16327
- Sort int `json:"sort"` // 排序方式
- RecentDocsMaxListCount int `json:"recentDocsMaxListCount"` // 最近的文档最大列出数量
- NoSplitScreenWhenOpenTab bool `json:"noSplitScreenWhenOpenTab"` // 打开页签时不分屏 https://github.com/siyuan-note/siyuan/issues/16833
+ RecentDocsSort string `json:"recentDocsSort"` // 最近文档排序方式
+ AlwaysSelectOpenedFile bool `json:"alwaysSelectOpenedFile"` // 是否自动选中当前打开的文件
+ OpenFilesUseCurrentTab bool `json:"openFilesUseCurrentTab"` // 在当前页签打开文件
+ CloseTabOnDoubleClick bool `json:"closeTabOnDoubleClick"` // 是否使用双击关闭页签
+ CloseWindowOnLastTabClosed *bool `json:"closeWindowOnLastTabClosed"` // 关闭或移走最后一个页签后关闭独立窗口
+ DocIconClickMode int `json:"docIconClickMode"` // 单击文档图标或笔记本图标的行为:0 修改图标,1 展开或折叠子文档
+ ParentDocTitleClickMode int `json:"parentDocTitleClickMode"` // 点击父文档标题的行为:0 打开文档,1 展开或折叠子文档,2 单击展开或折叠子文档、双击打开父文档
+ BoxDocEnabled bool `json:"boxDocEnabled"` // 是否启用顶层笔记本文档
+ UseSVGDefaultIcon bool `json:"useSVGDefaultIcon"` // 是否使用 SVG 默认图标
+ RefCreateSaveBox string `json:"refCreateSaveBox"` // 块引时新建文档存储笔记本
+ RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径
+ DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本
+ DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径
+ DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径
+ ShorthandSaveBox string `json:"shorthandSaveBox"` // 闪念速记存储笔记本
+ ShorthandSavePath string `json:"shorthandSavePath"` // 闪念速记存储路径
+ MaxListCount int `json:"maxListCount"` // 最大列出数量
+ MaxOpenTabCount int `json:"maxOpenTabCount"` // 最大打开页签数量
+ AllowCreateDeeper bool `json:"allowCreateDeeper"` // 允许创建超过 7 层深度的子文档
+ RemoveDocWithoutConfirm bool `json:"removeDocWithoutConfirm"` // 删除文档时是否不需要确认
+ CloseTabsOnStart bool `json:"closeTabsOnStart"` // 启动时关闭所有页签
+ TabStartupMode *int `json:"tabStartupMode"` // 页签启动策略:0 恢复,1 新建空白页签,2 关闭已打开页签
+ UseSingleLineSave bool `json:"useSingleLineSave"` // 使用单行保存文档 .sy 和属性视图 .json
+ LargeFileWarningSize int `json:"largeFileWarningSize"` // 大文件警告大小(单位:MB)
+ CreateDocAtTop *bool `json:"createDocAtTop"` // 在顶部创建新文档 https://github.com/siyuan-note/siyuan/issues/16327
+ Sort int `json:"sort"` // 排序方式
+ RecentDocsMaxListCount int `json:"recentDocsMaxListCount"` // 最近的文档最大列出数量
+ NoSplitScreenWhenOpenTab bool `json:"noSplitScreenWhenOpenTab"` // 打开页签时不分屏 https://github.com/siyuan-note/siyuan/issues/16833
}
func NewFileTree() *FileTree {
return &FileTree{
- RecentDocsSort: "viewedAt",
- AlwaysSelectOpenedFile: false,
- OpenFilesUseCurrentTab: false,
- CloseTabOnDoubleClick: false,
- DocIconClickMode: 0,
- ParentDocTitleClickMode: 0,
- BoxDocEnabled: false,
- UseSVGDefaultIcon: true,
- Sort: util.SortModeCustom,
- MaxListCount: 512,
- MaxOpenTabCount: 8,
- AllowCreateDeeper: false,
- CloseTabsOnStart: false,
- TabStartupMode: new(int),
- UseSingleLineSave: util.DefaultUseSingleLineSave,
- LargeFileWarningSize: util.DefaultLargeFileWarningSize,
- CreateDocAtTop: new(bool),
- NoSplitScreenWhenOpenTab: false,
+ RecentDocsSort: "viewedAt",
+ AlwaysSelectOpenedFile: false,
+ OpenFilesUseCurrentTab: false,
+ CloseTabOnDoubleClick: false,
+ CloseWindowOnLastTabClosed: new(true),
+ DocIconClickMode: 0,
+ ParentDocTitleClickMode: 0,
+ BoxDocEnabled: false,
+ UseSVGDefaultIcon: true,
+ Sort: util.SortModeCustom,
+ MaxListCount: 512,
+ MaxOpenTabCount: 8,
+ AllowCreateDeeper: false,
+ CloseTabsOnStart: false,
+ TabStartupMode: new(int),
+ UseSingleLineSave: util.DefaultUseSingleLineSave,
+ LargeFileWarningSize: util.DefaultLargeFileWarningSize,
+ CreateDocAtTop: new(bool),
+ NoSplitScreenWhenOpenTab: false,
}
}
diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.go
index 4c0bbf588b..a38296e41f 100644
--- a/kernel/conf/settings_normalize.go
+++ b/kernel/conf/settings_normalize.go
@@ -13,6 +13,9 @@ func NormalizeFileTree(fileTree *FileTree) *FileTree {
if fileTree == nil {
fileTree = NewFileTree()
}
+ if fileTree.CloseWindowOnLastTabClosed == nil {
+ fileTree.CloseWindowOnLastTabClosed = NewFileTree().CloseWindowOnLastTabClosed
+ }
if fileTree.MaxListCount < 1 {
fileTree.MaxListCount = 512
}
diff --git a/kernel/conf/settings_normalize_test.go b/kernel/conf/settings_normalize_test.go
index 1f42817321..6b914998d8 100644
--- a/kernel/conf/settings_normalize_test.go
+++ b/kernel/conf/settings_normalize_test.go
@@ -51,6 +51,26 @@ func TestNormalizeSettingsFileTreeAndSearch(t *testing.T) {
}
}
+func TestNormalizeSettingsCloseWindowOnLastTab(t *testing.T) {
+ for _, input := range []string{`{}`, `{"closeWindowOnLastTabClosed":null}`, `{"closeWindowOnLastTabClosed":true}`, `{"closeWindowOnLastTabClosed":false}`} {
+ var fileTree FileTree
+ if err := json.Unmarshal([]byte(input), &fileTree); err != nil {
+ t.Fatal(err)
+ }
+ got := NormalizeFileTree(&fileTree)
+ want := !strings.Contains(input, "false")
+ if got.CloseWindowOnLastTabClosed == nil || *got.CloseWindowOnLastTabClosed != want {
+ t.Fatalf("%s: unexpected last-tab close preference: %+v", input, got)
+ }
+ if *NormalizeFileTree(got).CloseWindowOnLastTabClosed != want {
+ t.Fatal("normalization changed the saved preference")
+ }
+ }
+ if !*NewFileTree().CloseWindowOnLastTabClosed || !*NormalizeFileTree(nil).CloseWindowOnLastTabClosed {
+ t.Fatal("new and missing settings must enable last-tab closing")
+ }
+}
+
func TestNormalizeSettingsFlashcard(t *testing.T) {
for _, weight := range []string{"bad", "NaN", "+Inf"} {
weights := strings.Split(DefaultFSRSWeights(), ",")