Skip to content

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

:sparkles: Support saving and restoring new window layouts https://github.com/siyuan-note/siyuan/issues/10809

Vanessa721a05d10016
diff --git a/AGENTS.md b/AGENTS.md
index 63a1f02030..a4f04b4358 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -216,6 +216,7 @@ All Go libraries above are dependencies in `kernel/go.mod`. GitHub org: `siyuan-
- **Editing Go dependencies:** To test a local change, add a temporary `replace` in `kernel/go.mod` pointing at your local checkout; **never commit that temporary `replace`**.
- **Rebuilding `lute.min.js`:** Change `lute`, rebuild with GopherJS, and copy the artifact into `app/stage/protyle/js/lute/`.
- **Type declarations:** when changing files under `app/src/types/` or other TypeScript declarations and constants exposed to plugins, synchronize the corresponding declarations and constants in the `petal` repository in the same task.
+- **Petal changelog:** Whenever changing files in the `petal` repository, update `petal/CHANGELOG.md` in the same task. Add a concise entry under the current unreleased version before committing the Petal change.
- **Petal documentation:** Keep `petal/README.md` limited to the project title and the `plugin-sample` link. Do not add feature descriptions, API usage explanations, or code examples to the README. Document API behavior, constraints, and lifecycle in comments on the corresponding API declarations in `petal`; put executable usage examples in the actual source code of `plugin-sample`.
---
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 03ee2463da..8f2731f8c1 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "تبديل",
+ "mainWindowLayouts": "تخطيطات النافذة الرئيسية",
+ "windowWorkspaces": "تخطيطات النافذة الجديدة",
+ "windowWorkspaceSave": "حفظ كتخطيط للنافذة الجديدة",
+ "windowWorkspaceRemoveTip": "هل تريد إزالة «${x}»؟ ستُحفظ المستندات والمرفقات، وستبقى النوافذ المفتوحة كما هي.",
+ "windowWorkspaceSaveError": "تعذر حفظ تخطيط النافذة الجديدة. يرجى المحاولة مرة أخرى.",
+ "windowWorkspaceUnavailable": "تخطيط النافذة الجديدة غير متاح أو يستخدم تنسيقًا غير مدعوم.",
"listMindmapExpandToLevel": "توسيع حتى المستوى ${level}",
"checkBlockRefProgress": "جارٍ التحقق من مراجع الكتل وارتباطات قواعد البيانات...",
"calendarRowLimit": "عدد صفوف العناصر المعروضة",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index d58bf55776..27db2b3f90 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Wechseln",
+ "mainWindowLayouts": "Layouts des Hauptfensters",
+ "windowWorkspaces": "Layouts für neue Fenster",
+ "windowWorkspaceSave": "Als Layout für ein neues Fenster speichern",
+ "windowWorkspaceRemoveTip": "„${x}“ entfernen? Dokumente und Anhänge bleiben erhalten, und geöffnete Fenster bleiben geöffnet.",
+ "windowWorkspaceSaveError": "Das Layout für ein neues Fenster konnte nicht gespeichert werden. Bitte erneut versuchen.",
+ "windowWorkspaceUnavailable": "Das Layout für ein neues Fenster ist nicht verfügbar oder verwendet ein nicht unterstütztes Format.",
"listMindmapExpandToLevel": "Bis Ebene ${level} aufklappen",
"checkBlockRefProgress": "Blockreferenzen und Datenbankverknüpfungen werden geprüft...",
"calendarRowLimit": "Angezeigte Eintragszeilen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 65aa2c8fad..534a443c7d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Switch",
+ "mainWindowLayouts": "Main window layouts",
+ "windowWorkspaces": "New window layouts",
+ "windowWorkspaceSave": "Save as new window layout",
+ "windowWorkspaceRemoveTip": "Remove “${x}”? Documents and attachments will be kept, and open windows will remain open.",
+ "windowWorkspaceSaveError": "Could not save the new window layout. Please try again.",
+ "windowWorkspaceUnavailable": "The new window layout is unavailable or uses an unsupported format.",
"listMindmapExpandToLevel": "Expand to level ${level}",
"checkBlockRefProgress": "Checking block references and database bindings...",
"calendarRowLimit": "Visible item rows",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 784ae34a24..2a259a8dba 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Cambiar",
+ "mainWindowLayouts": "Diseños de la ventana principal",
+ "windowWorkspaces": "Diseños de nueva ventana",
+ "windowWorkspaceSave": "Guardar como diseño de nueva ventana",
+ "windowWorkspaceRemoveTip": "¿Eliminar «${x}»? Se conservarán los documentos y los archivos adjuntos, y las ventanas abiertas seguirán abiertas.",
+ "windowWorkspaceSaveError": "No se pudo guardar el diseño de nueva ventana. Inténtalo de nuevo.",
+ "windowWorkspaceUnavailable": "El diseño de nueva ventana no está disponible o utiliza un formato no compatible.",
"listMindmapExpandToLevel": "Expandir hasta el nivel ${level}",
"checkBlockRefProgress": "Comprobando referencias de bloques y vínculos con bases de datos...",
"calendarRowLimit": "Filas de elementos visibles",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 70ca184f4a..6be643c864 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Basculer",
+ "mainWindowLayouts": "Dispositions de la fenêtre principale",
+ "windowWorkspaces": "Dispositions de nouvelle fenêtre",
+ "windowWorkspaceSave": "Enregistrer comme disposition de nouvelle fenêtre",
+ "windowWorkspaceRemoveTip": "Supprimer « ${x} » ? Les documents et les pièces jointes seront conservés, et les fenêtres ouvertes resteront ouvertes.",
+ "windowWorkspaceSaveError": "Impossible d’enregistrer la disposition de nouvelle fenêtre. Veuillez réessayer.",
+ "windowWorkspaceUnavailable": "La disposition de nouvelle fenêtre est indisponible ou utilise un format non pris en charge.",
"listMindmapExpandToLevel": "Développer jusqu’au niveau ${level}",
"checkBlockRefProgress": "Vérification des références de blocs et des liaisons aux bases de données...",
"calendarRowLimit": "Lignes d’éléments visibles",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index b62098b7d5..a036191c83 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "מעבר",
+ "mainWindowLayouts": "פריסות החלון הראשי",
+ "windowWorkspaces": "פריסות חלון חדש",
+ "windowWorkspaceSave": "שמירה כפריסת חלון חדש",
+ "windowWorkspaceRemoveTip": "להסיר את ״${x}״? המסמכים והקבצים המצורפים יישמרו, והחלונות הפתוחים יישארו פתוחים.",
+ "windowWorkspaceSaveError": "לא ניתן לשמור את פריסת החלון החדש. יש לנסות שוב.",
+ "windowWorkspaceUnavailable": "פריסת החלון החדש אינה זמינה או משתמשת בתבנית שאינה נתמכת.",
"listMindmapExpandToLevel": "הרחבה עד לרמה ${level}",
"checkBlockRefProgress": "בודק הפניות לבלוקים וקישורים למסדי נתונים...",
"calendarRowLimit": "שורות פריטים מוצגות",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index a93df29ca5..acc651a0d1 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "स्विच करें",
+ "mainWindowLayouts": "मुख्य विंडो के लेआउट",
+ "windowWorkspaces": "नई विंडो के लेआउट",
+ "windowWorkspaceSave": "नई विंडो के लेआउट के रूप में सहेजें",
+ "windowWorkspaceRemoveTip": "“${x}” हटाएं? दस्तावेज़ और संलग्नक सुरक्षित रहेंगे, और खुली विंडो खुली रहेंगी।",
+ "windowWorkspaceSaveError": "नई विंडो का लेआउट सहेजा नहीं जा सका। कृपया फिर से प्रयास करें।",
+ "windowWorkspaceUnavailable": "नई विंडो का लेआउट उपलब्ध नहीं है या असमर्थित प्रारूप का उपयोग करता है।",
"listMindmapExpandToLevel": "स्तर ${level} तक विस्तृत करें",
"checkBlockRefProgress": "ब्लॉक संदर्भों और डेटाबेस बाइंडिंग की जाँच हो रही है...",
"calendarRowLimit": "दिखाई देने वाली आइटम पंक्तियाँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index b9653a4437..c97233d16a 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Beralih",
+ "mainWindowLayouts": "Tata letak jendela utama",
+ "windowWorkspaces": "Tata letak jendela baru",
+ "windowWorkspaceSave": "Simpan sebagai tata letak jendela baru",
+ "windowWorkspaceRemoveTip": "Hapus “${x}”? Dokumen dan lampiran akan tetap disimpan, dan jendela yang terbuka akan tetap terbuka.",
+ "windowWorkspaceSaveError": "Tidak dapat menyimpan tata letak jendela baru. Silakan coba lagi.",
+ "windowWorkspaceUnavailable": "Tata letak jendela baru tidak tersedia atau menggunakan format yang tidak didukung.",
"listMindmapExpandToLevel": "Perluas hingga tingkat ${level}",
"checkBlockRefProgress": "Memeriksa referensi blok dan pengikatan basis data...",
"calendarRowLimit": "Baris item yang ditampilkan",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index ec3aa903b6..b23c9cf1cb 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Passa",
+ "mainWindowLayouts": "Layout della finestra principale",
+ "windowWorkspaces": "Layout della nuova finestra",
+ "windowWorkspaceSave": "Salva come layout della nuova finestra",
+ "windowWorkspaceRemoveTip": "Rimuovere «${x}»? I documenti e gli allegati verranno conservati e le finestre aperte rimarranno aperte.",
+ "windowWorkspaceSaveError": "Impossibile salvare il layout della nuova finestra. Riprova.",
+ "windowWorkspaceUnavailable": "Il layout della nuova finestra non è disponibile o utilizza un formato non supportato.",
"listMindmapExpandToLevel": "Espandi fino al livello ${level}",
"checkBlockRefProgress": "Verifica dei riferimenti ai blocchi e dei collegamenti ai database...",
"calendarRowLimit": "Righe di elementi visibili",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b7e14c91c2..ee406b338c 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "切り替え",
+ "mainWindowLayouts": "メインウィンドウのレイアウト",
+ "windowWorkspaces": "新しいウィンドウのレイアウト",
+ "windowWorkspaceSave": "新しいウィンドウのレイアウトとして保存",
+ "windowWorkspaceRemoveTip": "「${x}」を削除しますか?ドキュメントと添付ファイルは保持され、開いているウィンドウもそのまま残ります。",
+ "windowWorkspaceSaveError": "新しいウィンドウのレイアウトを保存できませんでした。もう一度お試しください。",
+ "windowWorkspaceUnavailable": "新しいウィンドウのレイアウトが利用できないか、非対応の形式です。",
"listMindmapExpandToLevel": "第 ${level} 階層まで展開",
"checkBlockRefProgress": "ブロック参照とデータベースの紐付けを確認しています...",
"calendarRowLimit": "項目の表示行数",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index f6631e093f..194b12d8ec 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "전환",
+ "mainWindowLayouts": "주 창 레이아웃",
+ "windowWorkspaces": "새 창 레이아웃",
+ "windowWorkspaceSave": "새 창 레이아웃으로 저장",
+ "windowWorkspaceRemoveTip": "“${x}”을(를) 제거할까요? 문서와 첨부 파일은 유지되며 열려 있는 창도 그대로 유지됩니다.",
+ "windowWorkspaceSaveError": "새 창 레이아웃을 저장하지 못했습니다. 다시 시도해 주세요.",
+ "windowWorkspaceUnavailable": "새 창 레이아웃을 사용할 수 없거나 지원하지 않는 형식입니다.",
"listMindmapExpandToLevel": "${level}단계까지 펼치기",
"checkBlockRefProgress": "블록 참조 및 데이터베이스 바인딩 확인 중...",
"calendarRowLimit": "표시할 항목 행 수",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 45ba0ca7fb..8c146d1b19 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Overschakelen",
+ "mainWindowLayouts": "Indelingen van het hoofdvenster",
+ "windowWorkspaces": "Indelingen voor nieuwe vensters",
+ "windowWorkspaceSave": "Opslaan als indeling voor een nieuw venster",
+ "windowWorkspaceRemoveTip": "‘${x}’ verwijderen? Documenten en bijlagen blijven bewaard en geopende vensters blijven open.",
+ "windowWorkspaceSaveError": "De indeling voor een nieuw venster kon niet worden opgeslagen. Probeer het opnieuw.",
+ "windowWorkspaceUnavailable": "De indeling voor een nieuw venster is niet beschikbaar of gebruikt een niet-ondersteund formaat.",
"listMindmapExpandToLevel": "Uitvouwen tot niveau ${level}",
"checkBlockRefProgress": "Blokverwijzingen en databasekoppelingen controleren...",
"calendarRowLimit": "Zichtbare itemrijen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 06556a847c..3fe1b4b9fd 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Przełącz",
+ "mainWindowLayouts": "Układy głównego okna",
+ "windowWorkspaces": "Układy nowego okna",
+ "windowWorkspaceSave": "Zapisz jako układ nowego okna",
+ "windowWorkspaceRemoveTip": "Usunąć „${x}”? Dokumenty i załączniki zostaną zachowane, a otwarte okna pozostaną otwarte.",
+ "windowWorkspaceSaveError": "Nie udało się zapisać układu nowego okna. Spróbuj ponownie.",
+ "windowWorkspaceUnavailable": "Układ nowego okna jest niedostępny lub używa nieobsługiwanego formatu.",
"listMindmapExpandToLevel": "Rozwiń do poziomu ${level}",
"checkBlockRefProgress": "Sprawdzanie odwołań do bloków i powiązań z bazami danych...",
"calendarRowLimit": "Widoczne wiersze elementów",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index ec1924d951..ec5db92017 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Alternar",
+ "mainWindowLayouts": "Layouts da janela principal",
+ "windowWorkspaces": "Layouts da nova janela",
+ "windowWorkspaceSave": "Salvar como layout da nova janela",
+ "windowWorkspaceRemoveTip": "Remover “${x}”? Os documentos e anexos serão preservados, e as janelas abertas permanecerão abertas.",
+ "windowWorkspaceSaveError": "Não foi possível salvar o layout da nova janela. Tente novamente.",
+ "windowWorkspaceUnavailable": "O layout da nova janela não está disponível ou usa um formato não compatível.",
"listMindmapExpandToLevel": "Expandir até o nível ${level}",
"checkBlockRefProgress": "Verificando referências de blocos e vínculos com bancos de dados...",
"calendarRowLimit": "Linhas de itens visíveis",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 02fd884240..0dac5e5671 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Перейти",
+ "mainWindowLayouts": "Макеты главного окна",
+ "windowWorkspaces": "Макеты нового окна",
+ "windowWorkspaceSave": "Сохранить как макет нового окна",
+ "windowWorkspaceRemoveTip": "Удалить «${x}»? Документы и вложения сохранятся, а открытые окна останутся открытыми.",
+ "windowWorkspaceSaveError": "Не удалось сохранить макет нового окна. Попробуйте ещё раз.",
+ "windowWorkspaceUnavailable": "Макет нового окна недоступен или использует неподдерживаемый формат.",
"listMindmapExpandToLevel": "Развернуть до уровня ${level}",
"checkBlockRefProgress": "Проверка ссылок на блоки и привязок к базам данных...",
"calendarRowLimit": "Число видимых строк записей",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 3a9804b037..1ee0b7536d 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Prepnúť",
+ "mainWindowLayouts": "Rozloženia hlavného okna",
+ "windowWorkspaces": "Rozloženia nového okna",
+ "windowWorkspaceSave": "Uložiť ako rozloženie nového okna",
+ "windowWorkspaceRemoveTip": "Odstrániť „${x}“? Dokumenty a prílohy zostanú zachované a otvorené okná zostanú otvorené.",
+ "windowWorkspaceSaveError": "Rozloženie nového okna sa nepodarilo uložiť. Skúste to znova.",
+ "windowWorkspaceUnavailable": "Rozloženie nového okna nie je dostupné alebo používa nepodporovaný formát.",
"listMindmapExpandToLevel": "Rozbaliť po úroveň ${level}",
"checkBlockRefProgress": "Kontrolujú sa odkazy na bloky a prepojenia s databázami...",
"calendarRowLimit": "Počet zobrazených riadkov položiek",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index f2c6c717a8..606da6078a 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Пребаци",
+ "mainWindowLayouts": "Распореди главног прозора",
+ "windowWorkspaces": "Распореди новог прозора",
+ "windowWorkspaceSave": "Сачувај као распоред новог прозора",
+ "windowWorkspaceRemoveTip": "Уклонити „${x}“? Документи и прилози ће бити сачувани, а отворени прозори ће остати отворени.",
+ "windowWorkspaceSaveError": "Није могуће сачувати распоред новог прозора. Покушајте поново.",
+ "windowWorkspaceUnavailable": "Распоред новог прозора није доступан или користи неподржан формат.",
"listMindmapExpandToLevel": "Прошири до нивоа ${level}",
"checkBlockRefProgress": "Провера референци на блокове и веза са базама података...",
"calendarRowLimit": "Број видљивих редова ставки",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 6e7f414148..0a80b44b5d 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "สลับ",
+ "mainWindowLayouts": "เค้าโครงหน้าต่างหลัก",
+ "windowWorkspaces": "เค้าโครงหน้าต่างใหม่",
+ "windowWorkspaceSave": "บันทึกเป็นเค้าโครงหน้าต่างใหม่",
+ "windowWorkspaceRemoveTip": "ลบ “${x}” หรือไม่? เอกสารและไฟล์แนบจะยังคงอยู่ และหน้าต่างที่เปิดอยู่จะไม่ถูกปิด",
+ "windowWorkspaceSaveError": "ไม่สามารถบันทึกเค้าโครงหน้าต่างใหม่ได้ โปรดลองอีกครั้ง",
+ "windowWorkspaceUnavailable": "เค้าโครงหน้าต่างใหม่ไม่พร้อมใช้งาน หรือใช้รูปแบบที่ไม่รองรับ",
"listMindmapExpandToLevel": "ขยายถึงระดับ ${level}",
"checkBlockRefProgress": "กำลังตรวจสอบการอ้างอิงบล็อกและการเชื่อมโยงฐานข้อมูล...",
"calendarRowLimit": "จำนวนแถวรายการที่แสดง",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index a40fb975df..5432654783 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Geçiş yap",
+ "mainWindowLayouts": "Ana pencere düzenleri",
+ "windowWorkspaces": "Yeni pencere düzenleri",
+ "windowWorkspaceSave": "Yeni pencere düzeni olarak kaydet",
+ "windowWorkspaceRemoveTip": "“${x}” kaldırılsın mı? Belgeler ve ekler korunur, açık pencereler açık kalır.",
+ "windowWorkspaceSaveError": "Yeni pencere düzeni kaydedilemedi. Lütfen yeniden deneyin.",
+ "windowWorkspaceUnavailable": "Yeni pencere düzeni kullanılamıyor veya desteklenmeyen bir biçim kullanıyor.",
"listMindmapExpandToLevel": "${level}. düzeye kadar genişlet",
"checkBlockRefProgress": "Blok referansları ve veritabanı bağlantıları kontrol ediliyor...",
"calendarRowLimit": "Görünür öğe satırları",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index bce4c6dea3..809011bc0c 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "Перейти",
+ "mainWindowLayouts": "Макети головного вікна",
+ "windowWorkspaces": "Макети нового вікна",
+ "windowWorkspaceSave": "Зберегти як макет нового вікна",
+ "windowWorkspaceRemoveTip": "Видалити «${x}»? Документи й вкладення буде збережено, а відкриті вікна залишаться відкритими.",
+ "windowWorkspaceSaveError": "Не вдалося зберегти макет нового вікна. Спробуйте ще раз.",
+ "windowWorkspaceUnavailable": "Макет нового вікна недоступний або використовує непідтримуваний формат.",
"listMindmapExpandToLevel": "Розгорнути до рівня ${level}",
"checkBlockRefProgress": "Перевірка посилань на блоки та прив’язок до баз даних...",
"calendarRowLimit": "Кількість видимих рядків записів",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 1c92db9bb6..8508f0005c 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "切换",
+ "mainWindowLayouts": "主窗口布局",
+ "windowWorkspaces": "新窗口布局",
+ "windowWorkspaceSave": "保存为新窗口布局",
+ "windowWorkspaceRemoveTip": "移除「${x}」?文档和附件会保留,已打开的窗口也会保留。",
+ "windowWorkspaceSaveError": "新窗口布局保存失败,请重试。",
+ "windowWorkspaceUnavailable": "新窗口布局不可用或使用了不支持的格式。",
"listMindmapExpandToLevel": "展开到第 ${level} 级",
"checkBlockRefProgress": "正在检查块引用和数据库绑定...",
"calendarRowLimit": "条目显示行数",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index f975a844e4..48631e5944 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,11 @@
{
+ "windowWorkspaceSwitch": "切換",
+ "mainWindowLayouts": "主視窗版面配置",
+ "windowWorkspaces": "新視窗版面配置",
+ "windowWorkspaceSave": "儲存為新視窗版面配置",
+ "windowWorkspaceRemoveTip": "移除「${x}」?文件與附件會保留,已開啟的視窗也會保留。",
+ "windowWorkspaceSaveError": "新視窗版面配置儲存失敗,請重試。",
+ "windowWorkspaceUnavailable": "新視窗版面配置無法使用或使用了不支援的格式。",
"listMindmapExpandToLevel": "展開到第 ${level} 級",
"checkBlockRefProgress": "正在檢查區塊引用與資料庫綁定...",
"calendarRowLimit": "項目顯示行數",
diff --git a/app/electron/main.js b/app/electron/main.js
index 33fe6860a8..9eb4ae7c82 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -73,6 +73,8 @@ const {
unsafeRemoteChromiumSwitchNames,
} = require("./remoteKernel");
const {dispatchWindowMessage} = require("./windowMessaging");
+const {WindowWorkspaceRegistry, flushWindowWorkspaces} = require("./windowWorkspaces");
+const windowWorkspaces = new WindowWorkspaceRegistry();
const {createNotebookSystemLock, prepareNotebookSystemLock} = require("./notebookSystemLock");
const {
readAccessibilitySetting, writeAccessibilitySetting, getAccessibilityOverride, configureAccessibility,
@@ -3340,6 +3342,32 @@ app.whenReady().then(() => {
if (data.cmd === "getContentsId") {
return event.sender.id;
}
+ if (["setWindowWorkspace", "focusWindowWorkspace", "getOpenWindowWorkspaces", "flushWindowWorkspaces"].includes(data.cmd)) {
+ const kernelTarget = getWindowKernelTarget(event.sender.id);
+ if (!kernelTarget) {
+ return false;
+ }
+ if (data.cmd === "getOpenWindowWorkspaces") {
+ return windowWorkspaces.list(kernelTarget.origin);
+ }
+ if (data.cmd === "flushWindowWorkspaces") {
+ return flushWindowWorkspaces(windowWorkspaces.list(kernelTarget.origin)
+ .map(id => windowWorkspaces.get(kernelTarget.origin, id)).filter(Boolean), ipcMain);
+ }
+ if (data.cmd === "focusWindowWorkspace") {
+ const window = windowWorkspaces.get(kernelTarget.origin, data.id);
+ if (window) {
+ showWindow(window);
+ return true;
+ }
+ return false;
+ }
+ const window = getWindowByContentId(event.sender.id);
+ if (!window || getWindowPathname(window) !== "/stage/build/app/window.html") {
+ return false;
+ }
+ return windowWorkspaces.associate(window, kernelTarget.origin, data.id);
+ }
if (data.cmd === "isAlwaysOnTop") {
const wnd = getWindowByContentId(event.sender.id);
if (!wnd) {
@@ -3739,6 +3767,17 @@ app.whenReady().then(() => {
if (kernelTarget.mode === "remote") {
windowURL.searchParams.set("remote", "1");
}
+ const workspaceID = windowURL.searchParams.get("windowWorkspace");
+ if (workspaceID) {
+ if (!/^\d{14}-[a-z0-9]{7}$/.test(workspaceID)) {
+ return;
+ }
+ const existingWindow = windowWorkspaces.get(kernelTarget.origin, workspaceID);
+ if (existingWindow) {
+ showWindow(existingWindow);
+ return;
+ }
+ }
const mainWindow = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
const mainBounds = mainWindow.getBounds();
const mainScreen = screen.getDisplayNearestPoint({x: mainBounds.x, y: mainBounds.y});
@@ -3769,6 +3808,10 @@ app.whenReady().then(() => {
bindSpellcheckContextMenu(win.webContents);
rememberWindowKernelTarget(win, kernelTarget);
+ if (workspaceID) {
+ windowWorkspaces.associate(win, kernelTarget.origin, workspaceID);
+ }
+
if (data.position) {
win.setPosition(data.position.x, data.position.y);
} else {
diff --git a/app/electron/windowWorkspaces.js b/app/electron/windowWorkspaces.js
new file mode 100644
index 0000000000..89dda97004
--- /dev/null
+++ b/app/electron/windowWorkspaces.js
@@ -0,0 +1,90 @@
+class WindowWorkspaceRegistry {
+ constructor() {
+ this.windows = new Map();
+ this.observed = new WeakSet();
+ }
+
+ get(origin, id) {
+ const key = `${origin}\n${id}`;
+ const window = this.windows.get(key);
+ if (window?.isDestroyed()) {
+ this.windows.delete(key);
+ return;
+ }
+ return window;
+ }
+
+ associate(window, origin, id) {
+ if (!window || window.isDestroyed() || !origin ||
+ (id !== "" && (typeof id !== "string" || !/^\d{14}-[a-z0-9]{7}$/.test(id)))) {
+ return false;
+ }
+ const existing = id && this.get(origin, id);
+ if (existing && existing !== window) {
+ return false;
+ }
+ this.release(window);
+ if (id) {
+ this.windows.set(`${origin}\n${id}`, window);
+ }
+ if (!this.observed.has(window)) {
+ this.observed.add(window);
+ window.once("closed", () => this.release(window));
+ }
+ return true;
+ }
+
+ release(window) {
+ for (const [key, value] of this.windows) {
+ if (value === window) {
+ this.windows.delete(key);
+ }
+ }
+ }
+
+ list(origin) {
+ return [...this.windows].filter(([key, window]) => key.startsWith(`${origin}\n`) && !window.isDestroyed())
+ .map(([key]) => key.slice(origin.length + 1));
+ }
+}
+
+let saveRequestID = 0;
+
+// 退出工作空间前等待窗口布局保存完成,超时或写入失败时保留窗口。
+const flushWindowWorkspaces = (windows, ipcMain, timeoutMs = 11000) => {
+ const contents = windows.filter(window => !window.isDestroyed()).map(window => window.webContents);
+ if (!contents.length) {
+ return Promise.resolve(true);
+ }
+ return new Promise(resolve => {
+ const id = ++saveRequestID;
+ const pending = new Set(contents.map(content => content.id));
+ const finish = saved => {
+ clearTimeout(timeout);
+ ipcMain.removeListener("siyuan-window-workspace-saved", onSaved);
+ resolve(saved);
+ };
+ const onSaved = (event, response) => {
+ if (response?.id !== id || event.senderFrame !== event.sender.mainFrame || !pending.has(event.sender.id)) {
+ return;
+ }
+ pending.delete(event.sender.id);
+ if (response.saved !== true) {
+ finish(false);
+ } else if (!pending.size) {
+ finish(true);
+ }
+ };
+ const timeout = setTimeout(() => finish(false), timeoutMs);
+ ipcMain.on("siyuan-window-workspace-saved", onSaved);
+ contents.forEach(content => {
+ try {
+ content.send("siyuan-send-windows", {cmd: "flushWindowWorkspace", data: id});
+ } catch {
+ finish(false);
+ }
+ });
+ });
+};
+
+module.exports = {WindowWorkspaceRegistry, flushWindowWorkspaces};
diff --git a/app/electron/windowWorkspaces.test.js b/app/electron/windowWorkspaces.test.js
new file mode 100644
index 0000000000..96457589ca
--- /dev/null
+++ b/app/electron/windowWorkspaces.test.js
@@ -0,0 +1,95 @@
+const {test} = require("node:test");
+const assert = require("node:assert/strict");
+const {EventEmitter} = require("node:events");
+const {WindowWorkspaceRegistry, flushWindowWorkspaces} = require("./windowWorkspaces");
+
+const id = "20260922100000-abcdefg";
+const origin = "http://127.0.0.1:6806";
+const createWindow = () => Object.assign(new EventEmitter(), {isDestroyed: () => false});
+
+test("加载中的窗口也只能与一个工作区关联", () => {
+ const registry = new WindowWorkspaceRegistry();
+ const first = createWindow();
+ const second = createWindow();
+ assert.equal(registry.associate(first, origin, id), true);
+ assert.equal(registry.associate(second, origin, id), false);
+ assert.equal(registry.get(origin, id), first);
+ assert.deepEqual(registry.list(origin), [id]);
+});
+
+test("不同内核的同名工作区互不干扰", () => {
+ const registry = new WindowWorkspaceRegistry();
+ const local = createWindow();
+ const remote = createWindow();
+ registry.associate(local, origin, id);
+ registry.associate(remote, "https://notes.example.com", id);
+ assert.equal(registry.get(origin, id), local);
+ assert.equal(registry.get("https://notes.example.com", id), remote);
+ assert.deepEqual(registry.list("http://127.0.0.1:6807"), []);
+});
+
+test("移除关联保留窗口,关闭后允许重新打开", () => {
+ const registry = new WindowWorkspaceRegistry();
+ const window = createWindow();
+ registry.associate(window, origin, id);
+ registry.associate(window, origin, "");
+ assert.equal(window.isDestroyed(), false);
+ assert.equal(registry.get(origin, id), undefined);
+ registry.associate(window, origin, id);
+ window.emit("closed");
+ assert.equal(registry.get(origin, id), undefined);
+ const reopened = createWindow();
+ assert.equal(registry.associate(reopened, origin, id), true);
+});
+
+test("销毁窗口与非法标识不会占用工作区", () => {
+ const registry = new WindowWorkspaceRegistry();
+ const window = createWindow();
+ for (const invalid of [undefined, null, 123, "../layout", "bad\nkey"]) {
+ assert.equal(registry.associate(window, origin, invalid), false);
+ }
+ assert.equal(registry.associate(window, "", id), false);
+ registry.associate(window, origin, id);
+ window.isDestroyed = () => true;
+ assert.deepEqual(registry.list(origin), []);
+ assert.equal(registry.get(origin, id), undefined);
+});
+
+test("退出前等待所有窗口保存,忽略其他窗口和子帧的确认", async () => {
+ const ipc = new EventEmitter();
+ const messages = [];
+ const windows = [1, 2].map(id => ({isDestroyed: () => false,
+ webContents: {id, mainFrame: {}, send: (_channel, message) => messages.push(message)},
+ }));
+ const task = flushWindowWorkspaces(windows, ipc);
+ let completed = false;
+ void task.then(() => completed = true);
+ const respond = (index, saved, frame = windows[index].webContents.mainFrame) => {
+ ipc.emit("siyuan-window-workspace-saved", {sender: windows[index].webContents, senderFrame: frame},
+ {id: messages[index].data, saved});
+ };
+ respond(0, true);
+ respond(1, true, {});
+ ipc.emit("siyuan-window-workspace-saved", {sender: {id: 3, mainFrame: 1}, senderFrame: 1},
+ {id: messages[0].data, saved: true});
+ await Promise.resolve();
+ assert.equal(completed, false);
+ respond(1, true);
+ assert.equal(await task, true);
+ assert.equal(ipc.listenerCount("siyuan-window-workspace-saved"), 0);
+});
+
+test("保存失败或窗口无响应时取消退出并清理监听器", async () => {
+ for (const timeout of [false, true]) {
+ const ipc = new EventEmitter();
+ let requestID;
+ const contents = {id: 1, mainFrame: {}, send: (_channel, message) => requestID = message.data};
+ const task = flushWindowWorkspaces([{isDestroyed: () => false, webContents: contents}], ipc, 10);
+ if (!timeout) {
+ ipc.emit("siyuan-window-workspace-saved", {sender: contents, senderFrame: contents.mainFrame},
+ {id: requestID, saved: false});
+ }
+ assert.equal(await task, false);
+ assert.equal(ipc.listenerCount("siyuan-window-workspace-saved"), 0);
+ }
+});
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy
index e769928e32..375d80c8c7 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy
@@ -6,7 +6,7 @@
"id": "20200924100906-0u4zfq3",
"title": "Window and Tab",
"type": "doc",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260809170000-fdf0e30",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -779,6 +779,194 @@
}
]
},
+ {
+ "ID": "20260922155242-zq7j067",
+ "Type": "NodeHeading",
+ "HeadingLevel": 3,
+ "Properties": {
+ "id": "20260922155242-zq7j067",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "New window layouts"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-he816jm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-he816jm",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "A new window layout saves the tabs, splits, and reading positions of a named window. Main window layouts and new window layouts are grouped in the same layout menu and saved separately. This feature is available in the desktop client; tabs from encrypted notebooks are excluded."
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-py20wzf",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-py20wzf",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Create: Arrange the tabs in a new window, click "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Save as new window layout"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " beside the pin button, enter a name, and save. Changes to tabs, splits, document reading positions, and PDF pages are then saved automatically."
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-q8e48jj",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-q8e48jj",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Reopen: In the main window, open "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Layout"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "New window layouts"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " and select a layout to restore it in a new window. If its window is already open, SiYuan switches to that window. You can search the list by name."
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-ikklk4b",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-ikklk4b",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Manage: Click "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Save"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to the right of "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Main window layouts"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to save the current main window layout. Move the pointer over an entry or its right arrow to open a submenu while keeping the layout list visible. New window layouts provide "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Open"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "( "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Switch"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " when the window is already open), "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Rename"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ", and "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Delete"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". Main window layouts provide "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Use"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to load the selected layout and "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Update"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " to save the current main window into that entry. New window layouts save automatically. Both types show the latest save time at the bottom of the submenu. You can also rename a new window layout using the layout icon beside the pin button. Rename dialogs are titled "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Main window layouts"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " or "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "New window layouts"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " and provide Cancel and Confirm buttons. Deleting a layout keeps its documents, attachments, and open window. The search field stays at the top while the list scrolls below it."
+ }
+ ]
+ },
{
"ID": "20260613204526-tboolrb",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy
index e6719c7c9f..b80bc5055c 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy
@@ -6,7 +6,7 @@
"id": "20200822191536-rm6hwid",
"title": "窗口和页签",
"type": "doc",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260809170000-d150748",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -783,6 +783,194 @@
}
]
},
+ {
+ "ID": "20260922155242-z5t2n3l",
+ "Type": "NodeHeading",
+ "HeadingLevel": 3,
+ "Properties": {
+ "id": "20260922155242-z5t2n3l",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新窗口布局"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-5nc0zym",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-5nc0zym",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新窗口布局用于保存一个已命名窗口的页签、分屏和阅读位置。主窗口布局和新窗口布局在同一个布局菜单内分组显示,分别保存。此功能适用于桌面客户端;加密笔记本的页签不会写入布局配置。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-h17mu6r",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-h17mu6r",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "创建:在新窗口中安排好页签,点击钉住按钮旁的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存为新窗口布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",输入名称并保存。之后会自动保存页签、分屏、文档阅读位置和 PDF 页码的变化。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-v64m1ym",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-v64m1ym",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "重新打开:在主窗口中打开 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新窗口布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 并选择布局,即可在新窗口中恢复保存的布局。如果对应窗口已打开,则会切换到已有窗口。列表支持按名称搜索。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-sujwuib",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-sujwuib",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "管理:点击 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "主窗口布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 右侧的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 可保存当前主窗口布局。将鼠标移到条目或其右侧箭头上,会展开子菜单并保留布局列表。新窗口布局依次提供 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "打开"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "(对应窗口已打开时显示 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "切换"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "重命名"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 和 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "删除"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。主窗口布局提供 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "使用"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",可加载选中的布局,以及 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "更新"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",可将当前主窗口保存到该条目;新窗口布局会自动保存。两类布局的子菜单末尾均显示最近保存时间。也可点击钉住按钮旁的布局图标重命名新窗口布局。重命名弹窗分别以 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "主窗口布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 和 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新窗口布局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 为标题,提供取消和确定按钮。删除布局会保留文档、附件和已打开的窗口。搜索框固定在顶部,下方列表可独立滚动。"
+ }
+ ]
+ },
{
"ID": "20260613204349-qlvuia3",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy
index 8a49a6db44..41ee6c8464 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy
@@ -6,7 +6,7 @@
"id": "20211226123216-tlxw66f",
"title": "視窗和分頁",
"type": "doc",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -44,7 +44,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260809170000-3a8f750",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -783,6 +783,194 @@
}
]
},
+ {
+ "ID": "20260922155242-cvaq88b",
+ "Type": "NodeHeading",
+ "HeadingLevel": 3,
+ "Properties": {
+ "id": "20260922155242-cvaq88b",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新視窗版面配置"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-4dgh9o5",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-4dgh9o5",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新視窗版面配置用於儲存已命名視窗的分頁、分割畫面和閱讀位置。主視窗版面配置和新視窗版面配置在同一個版面配置選單內分組顯示,分別儲存。此功能適用於桌面用戶端;加密筆記本的分頁不會寫入版面配置。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-ez4wspy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-ez4wspy",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "建立:在新視窗中安排好分頁,點擊釘選按鈕旁的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "儲存為新視窗版面配置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",輸入名稱並儲存。之後會自動儲存分頁、分割畫面、文件閱讀位置和 PDF 頁碼的變更。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-chpn51p",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-chpn51p",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "重新開啟:在主視窗中開啟 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "佈局"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新視窗版面配置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 並選取版面配置,即可在新視窗中還原儲存的版面配置。如果對應視窗已開啟,則會切換到既有視窗。清單支援依名稱搜尋。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-j375giy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-j375giy",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "管理:點擊 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "主視窗版面配置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 右側的 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 可儲存目前的主視窗版面配置。將滑鼠移到項目或其右側箭頭上,會展開子選單並保留版面配置清單。新視窗版面配置依序提供 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "打開"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "(對應視窗已開啟時顯示 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "切換"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "重命名"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 和 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "刪除"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。主視窗版面配置提供 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "使用"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",可載入選取的版面配置,以及 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "更新"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ",可將目前的主視窗儲存至該項目;新視窗版面配置會自動儲存。兩類版面配置的子選單末尾均顯示最近儲存時間。也可點擊釘選按鈕旁的版面配置圖示重新命名新視窗版面配置。重新命名對話方塊分別以 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "主視窗版面配置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 和 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新視窗版面配置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 為標題,提供取消和確定按鈕。刪除版面配置會保留文件、附件和已開啟的視窗。搜尋框固定在頂部,下方清單可獨立捲動。"
+ }
+ ]
+ },
{
"ID": "20260613204619-dyapikx",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy
index 7ec8a3d253..963bc55606 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-7yv4y5z",
"title": "ウィンドウとタブ",
"type": "doc",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -45,7 +45,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260809170000-5b80d49",
- "updated": "20260903130000"
+ "updated": "20260923114823"
},
"Children": [
{
@@ -788,6 +788,194 @@
}
]
},
+ {
+ "ID": "20260922155242-vua2yiz",
+ "Type": "NodeHeading",
+ "HeadingLevel": 3,
+ "Properties": {
+ "id": "20260922155242-vua2yiz",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新しいウィンドウのレイアウト"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-d7ab3nk",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-d7ab3nk",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "新しいウィンドウのレイアウトには、名前を付けたウィンドウのタブ、画面分割、閲覧位置が保存されます。メインウィンドウのレイアウトと新しいウィンドウのレイアウトは同じレイアウトメニュー内でグループ分けされ、別々に保存されます。この機能はデスクトップクライアントで利用できます。暗号化されたノートブックのタブは保存されません。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-30pjomk",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-30pjomk",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "作成:新しいウィンドウでタブを配置し、ピン留めボタンの横にある "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新しいウィンドウのレイアウトとして保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " をクリックして、名前を入力して保存します。その後はタブ、画面分割、ドキュメントの閲覧位置、PDF のページ番号の変更が自動的に保存されます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-k4faa32",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-k4faa32",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "再度開く:メインウィンドウで "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "レイアウト"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新しいウィンドウのレイアウト"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " を開き、レイアウトを選択すると、新しいウィンドウに保存したレイアウトが復元されます。対応するウィンドウが開いている場合は、そのウィンドウに切り替わります。一覧は名前で検索できます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260922155242-hc8rau9",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260922155242-hc8rau9",
+ "updated": "20260923114823"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "管理:"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "メインウィンドウのレイアウト"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " の右側にある "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "保存"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " をクリックすると、現在のメインウィンドウのレイアウトを保存できます。各項目または右側の矢印にマウスポインターを合わせると、一覧を表示したままサブメニューが開きます。新しいウィンドウのレイアウトでは "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "開く"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "(対応するウィンドウが開いている場合は "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "切り替え"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ")、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "名前の変更"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "削除"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " の順に表示されます。メインウィンドウのレイアウトには "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "使用する"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " と "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "更新"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " があり、前者は選択したレイアウトを読み込み、後者は現在のメインウィンドウをその項目に保存します。新しいウィンドウのレイアウトは自動的に保存されます。どちらもサブメニューの末尾に最終保存日時が表示されます。ピン留めボタンの横にあるレイアウトアイコンからも名前を変更できます。名前変更ダイアログのタイトルはそれぞれ "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "メインウィンドウのレイアウト"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " と "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "新しいウィンドウのレイアウト"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で、キャンセルと確認のボタンが表示されます。レイアウトを削除しても、ドキュメント、添付ファイル、開いているウィンドウは保持されます。検索欄は上部に固定され、その下の一覧だけをスクロールできます。"
+ }
+ ]
+ },
{
"ID": "20260613204552-tm8kqnq",
"Type": "NodeHeading",
diff --git a/app/src/assets/scss/base.scss b/app/src/assets/scss/base.scss
index 49c1811e0d..31d71be862 100644
--- a/app/src/assets/scss/base.scss
+++ b/app/src/assets/scss/base.scss
@@ -17,6 +17,7 @@
@use "component/list" as *;
@use "business/graph" as *;
@use "business/layout" as *;
+@use "business/window-workspace" as *;
@use "business/block" as *;
@use "util/reset" as *;
@use "component/card" as *;
diff --git a/app/src/assets/scss/business/_window-workspace.scss b/app/src/assets/scss/business/_window-workspace.scss
new file mode 100644
index 0000000000..3b0b4e9b44
--- /dev/null
+++ b/app/src/assets/scss/business/_window-workspace.scss
@@ -0,0 +1,17 @@
+.window-workspace {
+ &__list {
+ width: min(256px, 70vw);
+ }
+
+ &__search {
+ padding: 2px;
+ }
+
+ &__entries {
+ overscroll-behavior: contain;
+ }
+
+ &__name {
+ min-width: 0;
+ }
+}
diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.ts
index bb0d3757d9..5a25b707fd 100644
--- a/app/src/boot/onGetConfig.ts
+++ b/app/src/boot/onGetConfig.ts
@@ -366,6 +366,7 @@ ${response.data.replace("%pages", "<span class=totalPages></span>").replace("%pa
</svg>
</div></div>`);
const pinElement = document.getElementById("pinWindow");
+ void import("../window/workspace").then(({initWindowWorkspace}) => initWindowWorkspace());
pinElement.addEventListener("click", () => {
if (pinElement.getAttribute("aria-label") === window.siyuan.languages.pin) {
pinElement.querySelector("use").setAttribute("xlink:href", "#iconUnpin");
diff --git a/app/src/constants.ts b/app/src/constants.ts
index cd647a2e93..eb1489f276 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -187,6 +187,7 @@ export abstract class Constants {
public static readonly LOCAL_BAZAAR = "local-bazaar";
public static readonly LOCAL_PDFTHEME = "local-pdftheme";
public static readonly LOCAL_LAYOUTS = "local-layouts";
+ public static readonly LOCAL_WINDOW_WORKSPACE = "local-window-workspace-";
public static readonly LOCAL_PLUGINTOPUNPIN = "local-plugintopunpin";
public static readonly LOCAL_FLASHCARD = "local-flashcard";
public static readonly LOCAL_FILEPOSITION = "local-fileposition";
diff --git a/app/src/dialog/processSystem.ts b/app/src/dialog/processSystem.ts
index 71e4d12f09..26cf8c6c4b 100644
--- a/app/src/dialog/processSystem.ts
+++ b/app/src/dialog/processSystem.ts
@@ -209,6 +209,18 @@ const installNewVersion = (installPkgPath: string, setCurrentWorkspace: boolean)
export const exitSiYuan = async (setCurrentWorkspace = true) => {
hideAllElements(["util"]);
+ /// #if !BROWSER
+ try {
+ if (!await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "flushWindowWorkspaces"})) {
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ return;
+ }
+ } catch (error) {
+ console.error(error);
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ return;
+ }
+ /// #endif
/// #if MOBILE
if (window.siyuan.mobile.editor) {
await saveScroll(window.siyuan.mobile.editor.protyle);
diff --git a/app/src/editor/index.ts b/app/src/editor/index.ts
index 5e9972e5e7..2109e01078 100644
--- a/app/src/editor/index.ts
+++ b/app/src/editor/index.ts
@@ -29,7 +29,8 @@ export class Editor extends Model {
mode?: TEditorMode,
action?: TProtyleAction[],
afterInitProtyle?: (editor: Protyle) => void,
- scrollPosition?: ScrollLogicalPosition
+ scrollPosition?: ScrollLogicalPosition,
+ scrollAttr?: IScrollAttr,
}) {
super({
app: options.app,
@@ -51,6 +52,7 @@ export class Editor extends Model {
notebookId?: string,
mode?: TEditorMode,
scrollPosition?: ScrollLogicalPosition,
+ scrollAttr?: IScrollAttr,
afterInitProtyle?: (editor: Protyle) => void,
}) {
this.editor = new Protyle(this.app, this.element, {
@@ -67,6 +69,7 @@ export class Editor extends Model {
},
typewriterMode: true,
scrollPosition: options.scrollPosition,
+ scrollAttr: options.scrollAttr,
after: (editor) => {
if (window.siyuan.editorIsFullscreen) {
editor.setFullscreen(true);
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index 8167b7264d..25bdac546c 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -197,6 +197,7 @@ export const saveLayout = () => {
saveCount = 0;
if (isWindow()) {
sessionStorage.setItem("layout", JSON.stringify(layoutJSON));
+ window.dispatchEvent(new Event("siyuan-window-layout"));
} else {
if (!window.siyuan.config.readonly) {
const request = {
@@ -234,6 +235,7 @@ export const exportLayout = async (options: {
};
layoutToJSON(window.siyuan.layout.layout, layoutJSON.layout);
sessionStorage.setItem("layout", JSON.stringify(layoutJSON));
+ window.dispatchEvent(new Event("siyuan-window-layout"));
options.cb();
return;
}
@@ -736,6 +738,13 @@ export const layoutToJSON = (layout: Layout | Wnd | Tab | Model, json: any, brea
json.action = (layout.editor.protyle.block.showAll && layout.editor.protyle.block.id !== layout.editor.protyle.block.rootID) ? Constants.CB_GET_ALL : Constants.CB_GET_SCROLL;
json.databaseRowId = layout.editor.protyle.element.dataset.databaseRowId;
json.instance = "Editor";
+ if (isWindow()) {
+ const scrollAttr = saveScroll(layout.editor.protyle, true);
+ if (scrollAttr && "rootId" in scrollAttr) {
+ json.scrollAttr = scrollAttr;
+ json.action = Constants.CB_GET_SCROLL;
+ }
+ }
} else if (layout instanceof Asset) {
json.path = layout.path;
if (layout.pdfObject) {
@@ -941,6 +950,7 @@ export const newModelByInitData = (app: App, tab: Tab, json: any) => {
notebookId: json.notebookId,
mode: json.mode,
scrollPosition: json.scrollPosition,
+ scrollAttr: json.scrollAttr,
action,
afterInitProtyle(editor) {
if (json.databaseRowId) {
diff --git a/app/src/layout/windowWorkspace.test.ts b/app/src/layout/windowWorkspace.test.ts
new file mode 100644
index 0000000000..ed33185a11
--- /dev/null
+++ b/app/src/layout/windowWorkspace.test.ts
@@ -0,0 +1,73 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+test("窗口布局保存各页签独立阅读位置并沿用加密页签过滤", () => {
+ const compiled = transpileModule(readFileSync("src/layout/util.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ class Layout {
+ direction = "lr";
+ children: unknown[] = [];
+ }
+ class Wnd {
+ element = {style: {}};
+ children: unknown[] = [];
+ }
+ class Editor {
+ editor: any;
+ constructor(public options: any) {
+ this.editor = {protyle: options.protyle};
+ }
+ }
+ class Tab {
+ title = "Document";
+ headElement = {classList: {contains: () => false}, getAttribute: () => "1"};
+ constructor(public model: Editor) {}
+ }
+ let detached = true;
+ const dependencies = {
+ Layout, Wnd, Tab, Editor,
+ Asset: class {}, Backlink: class {}, Bookmark: class {}, Files: class {},
+ Graph: class {}, Outline: class {}, Tag: class {}, Search: class {}, Custom: class {},
+ Constants: {CB_GET_SCROLL: "scroll", CB_GET_ALL: "all", CB_GET_FOCUS: "focus"},
+ isWindow: () => detached,
+ isPhablet: () => false,
+ isEncryptedBox: (id: string) => id === "encrypted",
+ saveScroll: (protyle: any, getObject: boolean) => {
+ assert.equal(getObject, true);
+ return protyle.scroll;
+ },
+ };
+ const api = {} as {layoutToJSON: (layout: unknown, json: object) => void,
+ newModelByInitData: (app: object, tab: Tab, json: object) => Editor};
+ runInNewContext(compiled, {exports: api, require: () => dependencies});
+ const makeTab = (position: number, notebookId = "plain") => new Tab(new Editor({protyle: {
+ notebookId,
+ block: {id: "zoomed-block", rootID: "doc", showAll: true},
+ preview: {element: {classList: {contains: () => true}}},
+ element: {dataset: {}},
+ scroll: {rootId: "doc", zoomInId: "zoomed-block", scrollTop: position},
+ }}));
+ const root = new Layout();
+ const wnd = new Wnd();
+ root.children = [wnd];
+ wnd.children = [makeTab(100), makeTab(500), makeTab(900, "encrypted")];
+ const json: any = {};
+ api.layoutToJSON(root, json);
+ assert.equal(json.children[0].children.length, 2);
+ const tabs = json.children[0].children;
+ assert.equal(tabs[0].children.scrollAttr.scrollTop, 100);
+ assert.equal(tabs[1].children.scrollAttr.scrollTop, 500);
+ assert.equal(tabs[0].children.action, "scroll");
+ assert.equal(JSON.stringify(json).includes("encrypted"), false);
+ const editor = api.newModelByInitData({}, wnd.children[0] as Tab, tabs[0].children);
+ assert.equal(editor.options.scrollAttr.scrollTop, 100);
+ assert.equal(editor.options.scrollAttr.zoomInId, "zoomed-block");
+ detached = false;
+ const mainJSON: any = {};
+ api.layoutToJSON(root, mainJSON);
+ assert.equal(mainJSON.children[0].children[0].children.scrollAttr, undefined);
+});
diff --git a/app/src/menus/layouts.test.ts b/app/src/menus/layouts.test.ts
new file mode 100644
index 0000000000..cf305c3641
--- /dev/null
+++ b/app/src/menus/layouts.test.ts
@@ -0,0 +1,99 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync("src/menus/layouts.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = () => {
+ const layouts = [{name: "Reading", time: 1, layout: {saved: true}, filesPaths: ["saved-path"]}];
+ const calls: Array<{action: string, value?: unknown}> = [];
+ let dialog: any;
+ const dependencies = {
+ Constants: {LOCAL_LAYOUTS: "layouts", LOCAL_FILESPATHS: "paths"},
+ setStorageVal: (key: string, value: unknown, callback?: () => void) => {
+ calls.push({action: key, value: JSON.parse(JSON.stringify(value))});
+ callback?.();
+ },
+ fetchPost: (url: string, value: unknown, callback: () => void) => {
+ calls.push({action: url, value});
+ callback();
+ },
+ getAllLayout: () => ({current: true}),
+ openInputDialog: (options: unknown) => {
+ dialog = options;
+ return {element: {setAttribute: () => {}}};
+ },
+ showMessage: (value: string) => calls.push({action: "message", value}),
+ escapeHtml: (value: string) => value.replace(/</g, "&lt;").replace(/>/g, "&gt;"),
+ editWindowWorkspace: (value: string) => calls.push({action: "rename", value}),
+ openWindowWorkspace: (value: string) => calls.push({action: "open", value}),
+ removeWindowWorkspace: (value: string) => calls.push({action: "delete", value}),
+ };
+ const window = {siyuan: {
+ storage: {layouts, paths: ["current-path"]},
+ languages: {openBy: "Open", windowWorkspaceSwitch: "Switch", use: "Use", update: "Update", rename: "Rename",
+ delete: "Delete", confirm: "Confirm", mainWindowLayouts: "Main window layouts", _kernel: {142: "Empty"}},
+ }, location: {reload: () => calls.push({action: "reload"})}};
+ const api = {} as typeof import("./layouts");
+ runInNewContext(compiled, {exports: api, require: () => dependencies, window});
+ return {api, window, calls, dialog: () => dialog};
+};
+
+test("主窗口布局更多菜单按使用、更新、重命名、删除排列", () => {
+ const {api} = fixture();
+ const actions = api.getLayoutActions({type: "main", name: "Reading"});
+ assert.deepEqual(Array.from(actions, action => action.id), ["open", "update", "rename", "delete"]);
+ assert.equal(actions[0].label, "Use");
+ assert.equal(actions[0].icon, "iconReplace");
+ assert.equal(actions[1].label, "Update");
+});
+
+test("新窗口布局不提供更新,已打开时显示切换", () => {
+ const f = fixture();
+ for (const opened of [true, false]) {
+ const actions = f.api.getLayoutActions({type: "window", id: "workspace", opened});
+ assert.equal(actions[0].label, opened ? "Switch" : "Open");
+ assert.equal(actions[0].icon, opened ? "iconFocus" : "iconOpen");
+ assert.deepEqual(Array.from(actions, action => action.id), ["open", "rename", "delete"]);
+ }
+ const actions = f.api.getLayoutActions({type: "window", id: "workspace", opened: true});
+ [0, 1, 2].forEach(index => actions[index].click(undefined, undefined));
+ assert.deepEqual(f.calls, ["open", "rename", "delete"].map(action => ({action, value: "workspace"})));
+});
+
+test("重命名仅改变名称,弹窗以主窗口布局为标题并使用确定按钮", () => {
+ const f = fixture();
+ f.api.getLayoutActions({type: "main", name: "Reading"})[2].click(undefined, undefined);
+ assert.equal(f.dialog().title, "Main window layouts");
+ assert.equal(f.dialog().confirmText, "Confirm");
+ assert.equal(f.dialog().actions, undefined);
+ f.dialog().onConfirm(" Renamed ", {destroy: () => {}});
+ assert.equal(f.window.siyuan.storage.layouts[0].name, "Renamed");
+ assert.deepEqual(f.window.siyuan.storage.layouts[0].layout, {saved: true});
+ assert.deepEqual(f.window.siyuan.storage.layouts[0].filesPaths, ["saved-path"]);
+});
+
+test("更新保存当前布局和文档树状态,打开恢复已保存布局", () => {
+ const f = fixture();
+ const actions = f.api.getLayoutActions({type: "main", name: "Reading"});
+ actions[1].click(undefined, undefined);
+ assert.equal(f.window.siyuan.storage.layouts[0].name, "Reading");
+ assert.deepEqual(JSON.parse(JSON.stringify(f.window.siyuan.storage.layouts[0].layout)), {current: true});
+ assert.deepEqual(f.window.siyuan.storage.layouts[0].filesPaths, ["current-path"]);
+ actions[0].click(undefined, undefined);
+ assert.equal(f.calls[1].action, "/api/system/setUILayout");
+ assert.deepEqual(JSON.parse(JSON.stringify(f.calls[1].value)), {layout: {current: true}});
+ assert.equal(f.calls[f.calls.length - 1].action, "reload");
+});
+
+test("删除只移除选中的布局", () => {
+ const f = fixture();
+ f.window.siyuan.storage.layouts.push({name: "Other", time: 1, layout: {saved: true}, filesPaths: []});
+ f.api.getLayoutActions({type: "main", name: "Reading"})[3].click(undefined, undefined);
+ assert.deepEqual(f.window.siyuan.storage.layouts.map(item => item.name), ["Other"]);
+ assert.deepEqual(f.window.siyuan.storage.paths, ["current-path"]);
+});
diff --git a/app/src/menus/layouts.ts b/app/src/menus/layouts.ts
new file mode 100644
index 0000000000..7f3e095ec6
--- /dev/null
+++ b/app/src/menus/layouts.ts
@@ -0,0 +1,291 @@
+import {Constants} from "../constants";
+import {setStorageVal} from "../protyle/util/compatibility";
+import {fetchPost} from "../util/fetch";
+import {getAllLayout} from "../layout/util";
+import {showMessage} from "../dialog/message";
+import {openInputDialog} from "../dialog/inputDialog";
+import {confirmDialog} from "../dialog/confirmDialog";
+import {escapeHtml} from "../util/escape";
+import {upDownHint} from "../util/upDownHint";
+import {isBrowser} from "../util/functions";
+import {editWindowWorkspace, getWindowWorkspaces, openWindowWorkspace, removeWindowWorkspace} from "../window/workspace";
+import {MenuItem} from "./Menu";
+import * as dayjs from "dayjs";
+/// #if !BROWSER
+import {ipcRenderer} from "electron";
+/// #endif
+
+const editLayout = (layoutName?: string) => {
+ const dialog = openInputDialog({
+ positionId: Constants.DIALOG_SAVEWORKSPACE,
+ title: layoutName ? window.siyuan.languages.mainWindowLayouts :
+ window.siyuan.languages.save,
+ value: layoutName || "",
+ placeholder: window.siyuan.languages.memo,
+ width: "520px",
+ confirmText: window.siyuan.languages.confirm,
+ onConfirm: (value, dialog) => {
+ value = value.trim();
+ if (!value) {
+ showMessage(window.siyuan.languages["_kernel"]["142"]);
+ return;
+ }
+ dialog.destroy();
+ if (layoutName) {
+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {
+ if (layoutItem.name === layoutName) {
+ layoutItem.name = value;
+ layoutItem.time = Date.now();
+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
+ return true;
+ }
+ });
+ return;
+ }
+ const hadName = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: ISaveLayout) => {
+ if (item.name === value) {
+ confirmDialog(window.siyuan.languages.save, window.siyuan.languages.exportTplTip, () => {
+ item.layout = getAllLayout();
+ item.time = Date.now();
+ item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
+ });
+ return true;
+ }
+ });
+ if (hadName) {
+ return;
+ }
+ window.siyuan.storage[Constants.LOCAL_LAYOUTS].push({
+ name: value,
+ time: Date.now(),
+ layout: getAllLayout(),
+ filesPaths: window.siyuan.storage[Constants.LOCAL_FILESPATHS]
+ });
+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
+ },
+ });
+ dialog.element.setAttribute("data-key", Constants.DIALOG_SAVEWORKSPACE);
+};
+
+const openLayout = (name: string) => {
+ const item: ISaveLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS]
+ .find((layout: ISaveLayout) => layout.name === name);
+ if (!item) {
+ return;
+ }
+ fetchPost("/api/system/setUILayout", {layout: item.layout}, () => {
+ if (item.filesPaths) {
+ window.siyuan.storage[Constants.LOCAL_FILESPATHS] = item.filesPaths;
+ setStorageVal(Constants.LOCAL_FILESPATHS, item.filesPaths, () => window.location.reload());
+ } else {
+ window.location.reload();
+ }
+ });
+};
+
+type LayoutTarget = {type: "main", name: string} | {type: "window", id: string, opened: boolean};
+
+export const getLayoutActions = (target: LayoutTarget, time?: number): IMenu[] => {
+ const actions: IMenu[] = [{
+ id: "open",
+ icon: target.type === "main" ? "iconReplace" : target.opened ? "iconFocus" : "iconOpen",
+ label: target.type === "main" ? window.siyuan.languages.use :
+ target.opened ? window.siyuan.languages.windowWorkspaceSwitch : window.siyuan.languages.openBy,
+ click: () => {
+ if (target.type === "window") {
+ void openWindowWorkspace(target.id);
+ } else {
+ openLayout(target.name);
+ }
+ },
+ }, ...(target.type === "main" ? [{
+ id: "update",
+ icon: "iconRefresh",
+ label: window.siyuan.languages.update,
+ click: () => {
+ const item: ISaveLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS]
+ .find((layout: ISaveLayout) => layout.name === target.name);
+ if (item) {
+ item.layout = getAllLayout();
+ item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
+ item.time = Date.now();
+ setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
+ }
+ },
+ }] : []), {
+ id: "rename",
+ icon: "iconEdit",
+ label: window.siyuan.languages.rename,
+ click: () => {
+ if (target.type === "window") {
+ editWindowWorkspace(target.id);
+ } else {
+ editLayout(target.name);
+ }
+ },
+ }, {
+ id: "delete",
+ icon: "iconTrashcan",
+ label: window.siyuan.languages.delete,
+ click: () => {
+ if (target.type === "window") {
+ removeWindowWorkspace(target.id);
+ return;
+ }
+ const layouts: ISaveLayout[] = window.siyuan.storage[Constants.LOCAL_LAYOUTS];
+ const index = layouts.findIndex(layout => layout.name === target.name);
+ if (index > -1) {
+ layouts.splice(index, 1);
+ setStorageVal(Constants.LOCAL_LAYOUTS, layouts);
+ }
+ },
+ }];
+ if (time) {
+ actions.push({id: "separator_time", type: "separator"}, {
+ id: "modifiedAt",
+ iconHTML: "",
+ type: "readonly",
+ label: `${window.siyuan.languages.modifiedAt} ${dayjs(time).format("YYYY-MM-DD HH:mm:ss")}`,
+ });
+ }
+ return actions;
+};
+
+export const getLayoutSubMenu = (): IMenu[] => {
+ return [{
+ iconHTML: "",
+ type: "empty",
+ label: `<div class="fn__flex-column b3-menu__filter window-workspace__list"><div class="window-workspace__search fn__flex-shrink"><input spellcheck="false" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.searchPlaceholder}"></div>
+<div class="fn__hr"></div><div class="fn__flex-1 window-workspace__entries"></div></div>`,
+ bind(menuElement) {
+ const input = menuElement.querySelector<HTMLInputElement>(".b3-text-field");
+ const list = menuElement.querySelector<HTMLElement>(".window-workspace__entries");
+ const menu = window.siyuan.menus.menu;
+ let openIDs: string[] = [];
+ const closeActions = () => {
+ list.querySelectorAll<HTMLElement>(":scope > .b3-menu__item").forEach(row => {
+ row.classList.remove("b3-menu__item--show");
+ row.querySelectorAll(".b3-menu__item--current").forEach(item => {
+ item.classList.remove("b3-menu__item--current");
+ });
+ });
+ };
+ list.addEventListener("scroll", closeActions);
+ const focusActions = (row: HTMLElement) => {
+ closeActions();
+ const submenu = row.querySelector<HTMLElement>(":scope > .b3-menu__submenu");
+ menu.element.querySelectorAll(".b3-menu__item--current").forEach(item => {
+ item.classList.remove("b3-menu__item--current");
+ });
+ row.classList.add("b3-menu__item--show");
+ menu.showSubMenu(submenu);
+ const first = submenu.querySelector<HTMLElement>(".b3-menu__item:not([disabled])");
+ first.focus();
+ first.classList.add("b3-menu__item--current");
+ };
+ const appendRow = (target: LayoutTarget, name: string, time?: number) => {
+ const element = new MenuItem({
+ icon: target.type === "main" ? "iconLayout" : "iconOpenWindow",
+ label: escapeHtml(name),
+ type: "submenu",
+ submenu: getLayoutActions(target, time),
+ click: (element, event) => {
+ if (element.querySelector(":scope > .b3-menu__submenu").contains(event.target as Node)) {
+ return true;
+ }
+ if (target.type === "window") {
+ void openWindowWorkspace(target.id);
+ } else {
+ openLayout(target.name);
+ }
+ },
+ }).element;
+ if (target.type === "window") {
+ element.dataset.workspaceId = target.id;
+ } else {
+ element.dataset.name = target.name;
+ }
+ const label = element.querySelector<HTMLElement>(".b3-menu__label");
+ label.classList.add("fn__ellipsis", "window-workspace__name");
+ label.setAttribute("title", name);
+ list.append(element);
+ };
+ const render = (selectFirst = document.activeElement === input) => {
+ const query = input.value.toLowerCase();
+ const layouts: ISaveLayout[] = window.siyuan.storage[Constants.LOCAL_LAYOUTS];
+ list.innerHTML = `<div class="b3-menu__item b3-menu__item--readonly">
+<span class="b3-menu__label">${window.siyuan.languages.mainWindowLayouts}</span>
+<button data-id="save" class="b3-button b3-button--outline b3-button--small">${window.siyuan.languages.save}</button></div>`;
+ const save = list.querySelector<HTMLElement>("[data-id='save']");
+ save.addEventListener("keydown", event => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.stopPropagation();
+ }
+ });
+ save.addEventListener("click", event => {
+ event.preventDefault();
+ event.stopPropagation();
+ menu.remove();
+ editLayout();
+ });
+ layouts.slice().sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}))
+ .filter(item => item.name.toLowerCase().includes(query))
+ .forEach(item => appendRow({type: "main", name: item.name}, item.name, item.time));
+ const workspaces = isBrowser() ? [] : getWindowWorkspaces().filter(item => item.name.toLowerCase().includes(query));
+ if (!isBrowser() && (!query || workspaces.length)) {
+ list.insertAdjacentHTML("beforeend", `<div class="b3-menu__item b3-menu__item--readonly"><span class="b3-menu__label">${window.siyuan.languages.windowWorkspaces}</span></div>`);
+ workspaces.forEach(item => appendRow({type: "window", id: item.id, opened: openIDs.includes(item.id)}, item.name, item.time));
+ }
+ if (selectFirst) {
+ menu.element.querySelectorAll(".b3-menu__item--current").forEach(item => {
+ item.classList.remove("b3-menu__item--current");
+ });
+ list.querySelector(".b3-menu__item:not(.b3-menu__item--readonly)")?.classList.add("b3-menu__item--current");
+ }
+ };
+ input.addEventListener("focus", () => {
+ closeActions();
+ menu.element.querySelectorAll(".b3-menu__item--current").forEach(item => {
+ item.classList.remove("b3-menu__item--current");
+ });
+ list.querySelector(".b3-menu__item:not(.b3-menu__item--readonly)")?.classList.add("b3-menu__item--current");
+ });
+ input.addEventListener("blur", () => list.querySelector(".b3-menu__item--current")?.classList.remove("b3-menu__item--current"));
+ input.addEventListener("keydown", event => {
+ event.stopPropagation();
+ if (event.isComposing) {
+ return;
+ }
+ upDownHint(list, event, "b3-menu__item--current");
+ if (event.key === "Escape" || (event.key === "ArrowLeft" && !input.value)) {
+ menu.remove(true);
+ } else if (event.key === "Enter") {
+ list.querySelector<HTMLElement>(".b3-menu__item--current")?.click();
+ } else if (event.key === "ArrowRight") {
+ const current = list.querySelector<HTMLElement>(".b3-menu__item--current");
+ if (current && input.selectionStart === input.value.length) {
+ event.preventDefault();
+ focusActions(current);
+ }
+ }
+ });
+ input.addEventListener("compositionend", () => render(true));
+ input.addEventListener("input", (event: InputEvent) => {
+ if (!event.isComposing) {
+ event.stopPropagation();
+ render(true);
+ }
+ });
+ render();
+ /// #if !BROWSER
+ void ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "getOpenWindowWorkspaces"}).then((ids: string[]) => {
+ openIDs = Array.isArray(ids) ? ids : [];
+ if (menuElement.isConnected) {
+ render();
+ }
+ });
+ /// #endif
+ },
+ }];
+};
diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.ts
index ba4c28be45..7af6500148 100644
--- a/app/src/menus/workspace.ts
+++ b/app/src/menus/workspace.ts
@@ -1,3 +1,5 @@
+import {getLayoutSubMenu} from "./layouts";
+import {hasClosestByClassName} from "../protyle/util/hasClosest";
import {MenuItem} from "./Menu";
/// #if !BROWSER
import {ipcRenderer} from "electron";
@@ -20,7 +22,7 @@ import {openCard} from "../card/openCard";
import {openSetting} from "../config";
import {getAllDocks, getAllModels} from "../layout/getAll";
import {getDockHotkey} from "../layout/dock/hotkey";
-import {exportLayout, getAllLayout} from "../layout/util";
+import {exportLayout} from "../layout/util";
import {getDockByType} from "../layout/tabUtil";
import {exitSiYuan, lockScreen} from "../dialog/processSystem";
import {showMessage} from "../dialog/message";
@@ -30,104 +32,16 @@ import {escapeAttr, escapeHtml} from "../util/escape";
import {viewCards} from "../card/viewCards";
import {Dialog} from "../dialog";
import {openInputDialog} from "../dialog/inputDialog";
-import {hasClosestByClassName} from "../protyle/util/hasClosest";
import {confirmDialog} from "../dialog/confirmDialog";
import type {App} from "../index";
import {isBrowser} from "../util/functions";
import {openRecentDocs} from "../business/openRecentDocs";
-import * as dayjs from "dayjs";
-import {upDownHint} from "../util/upDownHint";
import {openDataMigration} from "./dataMigration";
import {openLink} from "../editor/openLink";
import {adjustEditorFontSize} from "../util/editorFontSize";
import {getHostCapabilities} from "../util/hostCapabilities";
import {openTemplateManager} from "../template/manager";
-const editLayout = (layoutName?: string) => {
- const dialog = openInputDialog({
- positionId: Constants.DIALOG_SAVEWORKSPACE,
- title: layoutName ? window.siyuan.languages.edit : window.siyuan.languages.save,
- value: layoutName || "",
- placeholder: window.siyuan.languages.memo,
- width: "520px",
- confirmText: window.siyuan.languages[layoutName ? "updateLayout" : "confirm"],
- actions: layoutName ? [{
- text: window.siyuan.languages.delete,
- danger: true,
- position: "beforeCancel",
- onClick: (value, dialog) => {
- window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout, index: number) => {
- if (layoutItem.name === layoutName) {
- window.siyuan.storage[Constants.LOCAL_LAYOUTS].splice(index, 1);
- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
- return true;
- }
- });
- dialog.destroy();
- },
- }, {
- text: window.siyuan.languages.rename,
- onClick: (value, dialog) => {
- if (!value) {
- showMessage(window.siyuan.languages["_kernel"]["142"]);
- return;
- }
- dialog.destroy();
- window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {
- if (layoutItem.name === layoutName) {
- layoutItem.name = value;
- layoutItem.time = Date.now();
- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
- return true;
- }
- });
- },
- }] : [],
- onConfirm: (value, dialog) => {
- if (!value) {
- showMessage(window.siyuan.languages["_kernel"]["142"]);
- return;
- }
- dialog.destroy();
- if (layoutName) {
- window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((layoutItem: ISaveLayout) => {
- if (layoutItem.name === layoutName) {
- layoutItem.name = value;
- layoutItem.time = Date.now();
- layoutItem.layout = getAllLayout();
- layoutItem.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
- return true;
- }
- });
- return;
- }
- const hadName = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: ISaveLayout) => {
- if (item.name === value) {
- confirmDialog(window.siyuan.languages.save, window.siyuan.languages.exportTplTip, () => {
- item.layout = getAllLayout();
- item.time = Date.now();
- item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
- });
- return true;
- }
- });
- if (hadName) {
- return;
- }
- window.siyuan.storage[Constants.LOCAL_LAYOUTS].push({
- name: value,
- time: Date.now(),
- layout: getAllLayout(),
- filesPaths: window.siyuan.storage[Constants.LOCAL_FILESPATHS]
- });
- setStorageVal(Constants.LOCAL_LAYOUTS, window.siyuan.storage[Constants.LOCAL_LAYOUTS]);
- },
- });
- dialog.element.setAttribute("data-key", Constants.DIALOG_SAVEWORKSPACE);
-};
-
const getApplicationZoomSubMenu = () => {
const zoom = window.siyuan.storage[Constants.LOCAL_ZOOM];
const index = Constants.SIZE_ZOOM.findIndex((item) => item.zoom === zoom);
@@ -423,115 +337,7 @@ export const workspaceMenu = async (app: App, rect: DOMRect) => {
}).element);
}
}
- const layoutSubMenu: IMenu[] = [{
- id: "save",
- iconHTML: "",
- label: window.siyuan.languages.save,
- click() {
- editLayout();
- }
- }];
- if (window.siyuan.storage[Constants.LOCAL_LAYOUTS].length > 0) {
- layoutSubMenu.push({id: "separator_1", type: "separator"});
- layoutSubMenu.push({
- iconHTML: "",
- type: "empty",
- label: `<input spellcheck="false" class="b3-text-field fn__block" style="margin: 4px 0" placeholder="${window.siyuan.languages.searchPlaceholder}">
-<div class="b3-list b3-list--background" style="width: 220px"></div>`,
- bind(menuElement) {
- const genListHTML = (isInit = false) => {
- let html = "";
- window.siyuan.storage[Constants.LOCAL_LAYOUTS].sort((a: ISaveLayout, b: ISaveLayout) => {
- return a.name.localeCompare(b.name, undefined, {numeric: true});
- }).forEach((item: ISaveLayout) => {
- if (inputElement.value === "" || item.name.toLowerCase().indexOf(inputElement.value.toLowerCase()) > -1) {
- html += `<div data-name="${item.name}" class="b3-list-item b3-list-item--narrow b3-list-item--hide-action${!isInit && !html ? " b3-list-item--focus" : ""} ariaLabel" data-position="8east" aria-label="${escapeAttr(item.name)}" >
- <div class="b3-list-item__text">${item.name}</div>
- <span class="b3-list-item__meta">${item.time ? dayjs(item.time).format("YYYY-MM-DD HH:mm") : ""}</span>
- <span class="b3-list-item__action">
- <svg><use xlink:href="#iconEdit"></use></svg>
- </span>
-</div>`;
- }
- });
- return html;
- };
- const inputElement = menuElement.querySelector(".b3-text-field") as HTMLInputElement;
- const listElement = menuElement.querySelector(".b3-list");
- inputElement.addEventListener("focus", () => {
- if (!menuElement.querySelector(".b3-list-item--focus")) {
- menuElement.querySelector(".b3-list-item")?.classList.add("b3-list-item--focus");
- }
- });
- inputElement.addEventListener("blur", () => {
- menuElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");
- });
- inputElement.addEventListener("keydown", (event) => {
- event.stopPropagation();
- if (event.isComposing) {
- return;
- }
- upDownHint(listElement, event);
- if (event.key === "Escape" || (event.key === "ArrowLeft" && inputElement.value === "")) {
- window.siyuan.menus.menu.remove(true);
- } else if (event.key === "Enter") {
- const currentElement = listElement.querySelector(".b3-list-item--focus");
- if (currentElement) {
- listElement.dispatchEvent(new CustomEvent("click", {detail: currentElement.getAttribute("data-name")}));
- }
- }
- });
- inputElement.addEventListener("compositionend", () => {
- listElement.innerHTML = genListHTML();
- });
- inputElement.addEventListener("input", (event: InputEvent) => {
- if (event.isComposing) {
- return;
- }
- event.stopPropagation();
- listElement.innerHTML = genListHTML();
- });
- listElement.addEventListener("click", (event: MouseEvent) => {
- if (window.siyuan.config.readonly) {
- return;
- }
- const actionElement = hasClosestByClassName(event.target as Element, "b3-list-item__action");
- if (actionElement) {
- event.preventDefault();
- event.stopPropagation();
- editLayout(actionElement.parentElement.dataset.name);
- window.siyuan.menus.menu.remove();
- return;
- }
- const liElement = hasClosestByClassName(event.target as Element, "b3-list-item");
- if (liElement || event.detail) {
- const itemData: ISaveLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: ISaveLayout) => {
- if (typeof event.detail === "string") {
- return item.name === event.detail;
- } else if (liElement) {
- return item.name === liElement.dataset.name;
- }
- });
- if (itemData) {
- fetchPost("/api/system/setUILayout", {layout: itemData.layout}, () => {
- if (itemData.filesPaths) {
- window.siyuan.storage[Constants.LOCAL_FILESPATHS] = itemData.filesPaths;
- setStorageVal(Constants.LOCAL_FILESPATHS, itemData.filesPaths, () => {
- window.location.reload();
- });
- } else {
- window.location.reload();
- }
- });
- }
- event.preventDefault();
- event.stopPropagation();
- }
- });
- listElement.innerHTML = genListHTML(true);
- }
- });
- }
+ const layoutSubMenu = getLayoutSubMenu();
if (!window.siyuan.config.readonly) {
window.siyuan.menus.menu.append(new MenuItem({
id: "layout",
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index 011057969a..34fba6dd2f 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -441,8 +441,10 @@ export class Protyle {
return;
}
+ const savedScroll = options.scrollAttr?.rootId === options.rootId ? options.scrollAttr :
+ window.siyuan.storage?.[Constants.LOCAL_FILEPOSITION]?.[options.rootId];
if (this.protyle.options.mode !== "preview" &&
- options.rootId && window.siyuan.storage[Constants.LOCAL_FILEPOSITION][options.rootId] &&
+ options.rootId && savedScroll &&
(
mergedOptions.action.includes(Constants.CB_GET_SCROLL) ||
(mergedOptions.action.includes(Constants.CB_GET_ROOTSCROLL) && options.rootId === options.blockId)
@@ -450,7 +452,7 @@ export class Protyle {
) {
getDocByScroll({
protyle: this.protyle,
- scrollAttr: window.siyuan.storage[Constants.LOCAL_FILEPOSITION][options.rootId],
+ scrollAttr: savedScroll,
mergedOptions,
cb: () => {
this.afterOnGet(mergedOptions);
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index c910c9782f..2ac48d5c04 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -920,7 +920,7 @@ const sanitizeFilesPaths = (filesPaths: IFilesPath[]) => {
return filesPaths.filter((item) => !isEncryptedBox(item.notebookId));
};
-export const setStorageVal = (key: string, val: any, cb?: () => void) => {
+export const setStorageVal = (key: string, val: any, cb?: () => void, timeout = 0) => {
if (window.siyuan.config.readonly || window.siyuan.isPublish) {
return;
}
@@ -935,7 +935,7 @@ export const setStorageVal = (key: string, val: any, cb?: () => void) => {
if ([Constants.LOCAL_SEARCHDATA, Constants.LOCAL_FILESPATHS, Constants.LOCAL_CLOSED_TABS].includes(key)) {
window.siyuan.storage[key] = storageVal;
}
- fetchPost("/api/storage/setLocalStorageVal", {
+ return fetchPost("/api/storage/setLocalStorageVal", {
app: Constants.SIYUAN_APPID,
key,
val: storageVal,
@@ -943,7 +943,7 @@ export const setStorageVal = (key: string, val: any, cb?: () => void) => {
if (cb) {
cb();
}
- });
+ }, undefined, undefined, undefined, timeout);
};
export const initWindowOpenOverride = (app: App, openExternal?: (url: string) => void) => {
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 4312f9a954..6b4fdc6654 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -2224,7 +2224,7 @@ declare namespace Config {
({instance?: "Layout"} & Partial<Pick<IUILayoutLayout, "direction" | "size" | "type" | "resize">>) |
({instance: "Wnd"} & Partial<Pick<IUILayoutWnd, "resize" | "width" | "height">>) |
({instance: "Tab"} & Partial<Pick<IUILayoutTab, "title" | "lang" | "icon" | "docIcon" | "pin" | "active" | "activeTime">>) |
- ({instance: "Editor"} & Partial<Pick<IUILayoutTabEditor, "blockId" | "rootId" | "notebookId">>) |
+ ({instance: "Editor"} & Partial<Pick<IUILayoutTabEditor, "blockId" | "rootId" | "notebookId" | "scrollAttr">>) |
({instance: "Asset"} & Partial<Pick<IUILayoutTabAsset, "path" | "page">>) |
({instance: "Backlink"} & Partial<Pick<IUILayoutTabBacklink, "blockId" | "rootId" | "notebookId" | "type">>) |
({instance: "Graph"} & Partial<Pick<IUILayoutTabGraph, "blockId" | "rootId" | "notebookId" | "type">>) |
@@ -2474,6 +2474,10 @@ declare namespace Config {
* (Editor) Document block ID
*/
rootId: string;
+ /**
+ * 窗口布局独立保存的阅读位置,优先于全局文档阅读位置
+ */
+ scrollAttr?: IScrollAttr;
}
/**
diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.ts
index 8304d100c0..132e65d246 100644
--- a/app/src/types/protyle.d.ts
+++ b/app/src/types/protyle.d.ts
@@ -499,6 +499,7 @@ interface IProtyleOptions {
}[],
action?: TProtyleAction[],
scrollPosition?: ScrollLogicalPosition,
+ scrollAttr?: IScrollAttr,
mode?: TEditorMode,
blockId?: string
rootId?: string
diff --git a/app/src/util/processTitle.ts b/app/src/util/processTitle.ts
index 35f18a29b7..d5d946e116 100644
--- a/app/src/util/processTitle.ts
+++ b/app/src/util/processTitle.ts
@@ -2,6 +2,15 @@ import {escapeHtml} from "./escape";
import {Constants} from "../constants";
import {pathPosix} from "./pathName";
+let windowWorkspaceTitle = "";
+
+export const setWindowWorkspaceTitle = (name: string) => {
+ const prefix = windowWorkspaceTitle ? `${windowWorkspaceTitle} - ` : "";
+ const title = prefix && document.title.startsWith(prefix) ? document.title.slice(prefix.length) : document.title;
+ windowWorkspaceTitle = name;
+ document.title = name ? `${name} - ${title}` : title;
+};
+
export const getWorkspaceName = () => {
const dir = window.siyuan.config.system.workspaceDir;
// 浏览器环境下内核不返回工作空间绝对路径,回退到“工作空间”(Workspace)。
@@ -30,4 +39,7 @@ export const setTitle = (title: string, showVersionTitle = false) => {
dragElement.innerHTML = escapeHtml(title);
}
}
+ if (windowWorkspaceTitle) {
+ document.title = `${windowWorkspaceTitle} - ${document.title}`;
+ }
};
diff --git a/app/src/util/upDownHint.ts b/app/src/util/upDownHint.ts
index 78299072ad..c49b664500 100644
--- a/app/src/util/upDownHint.ts
+++ b/app/src/util/upDownHint.ts
@@ -1,5 +1,6 @@
export const isAbnormalItem = (currentHintElement: HTMLElement, className: string) => {
- return currentHintElement && (!currentHintElement.classList.contains(className) || currentHintElement.getBoundingClientRect().height === 0);
+ return currentHintElement && (!currentHintElement.classList.contains(className) ||
+ currentHintElement.classList.contains("b3-menu__item--readonly") || currentHintElement.getBoundingClientRect().height === 0);
};
export const upDownHint = (listElement: Element, event: KeyboardEvent, classActiveName = "b3-list-item--focus", defaultElement?: Element) => {
@@ -50,8 +51,7 @@ export const upDownHint = (listElement: Element, event: KeyboardEvent, classActi
if (!currentHintElement) {
currentHintElement = listElement.children[listElement.children.length - 1] as HTMLElement;
- while (currentHintElement &&
- (currentHintElement.classList.contains("fn__none") || !currentHintElement.classList.contains(className))) {
+ while (isAbnormalItem(currentHintElement, className)) {
currentHintElement = currentHintElement.previousElementSibling as HTMLElement;
}
}
diff --git a/app/src/window/closeWin.test.ts b/app/src/window/closeWin.test.ts
new file mode 100644
index 0000000000..65c7c58db4
--- /dev/null
+++ b/app/src/window/closeWin.test.ts
@@ -0,0 +1,33 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, transpileModule} from "typescript";
+
+test("窗口关闭等待持久化,保存失败时保留窗口并允许重试", async () => {
+ const compiled = transpileModule(readFileSync("src/window/closeWin.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS},
+ }).outputText;
+ let finish: (saved: boolean) => void;
+ const calls: string[] = [];
+ const dependencies = {
+ Constants: {SIYUAN_CMD: "cmd"},
+ ipcRenderer: {send: (_channel: string, cmd: string) => calls.push(cmd)},
+ flushWindowWorkspace: () => new Promise<boolean>(resolve => finish = resolve),
+ destroyWindowPluginKernels: () => calls.push("plugins"),
+ showMessage: () => calls.push("error"),
+ };
+ const api = {} as {closeWindow: (app: object) => Promise<void>};
+ runInNewContext(compiled, {exports: api, require: () => dependencies,
+ window: {siyuan: {languages: {windowWorkspaceSaveError: "error"}}}, console});
+ const failed = api.closeWindow({plugins: []});
+ await api.closeWindow({plugins: []});
+ assert.deepEqual(calls, []);
+ finish(false);
+ await failed;
+ assert.deepEqual(calls, ["error"]);
+ const saved = api.closeWindow({plugins: []});
+ finish(true);
+ await saved;
+ assert.deepEqual(calls, ["error", "plugins", "destroy"]);
+});
diff --git a/app/src/window/closeWin.ts b/app/src/window/closeWin.ts
index 84c63bec84..df99ebb47a 100644
--- a/app/src/window/closeWin.ts
+++ b/app/src/window/closeWin.ts
@@ -2,8 +2,26 @@ import type {App} from "../index";
import {Constants} from "../constants";
import {ipcRenderer} from "electron";
import {destroyWindowPluginKernels} from "./closeWinCore";
+import {flushWindowWorkspace} from "./workspace";
+import {showMessage} from "../dialog/message";
-export const closeWindow = (app: App) => {
- destroyWindowPluginKernels(app.plugins, error => console.error(error));
- ipcRenderer.send(Constants.SIYUAN_CMD, "destroy");
+let closing = false;
+export const closeWindow = async (app: App) => {
+ if (closing) {
+ return;
+ }
+ closing = true;
+ try {
+ if (!await flushWindowWorkspace()) {
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ return;
+ }
+ destroyWindowPluginKernels(app.plugins, error => console.error(error));
+ ipcRenderer.send(Constants.SIYUAN_CMD, "destroy");
+ } catch (error) {
+ console.error(error);
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ } finally {
+ closing = false;
+ }
};
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index fcd53000aa..cc0918de05 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -1,3 +1,4 @@
+import {onWindowWorkspaceStorageChanged} from "./workspace";
import {Constants} from "../constants";
import {systemConfig} from "../config/systemConfig";
import {Menus} from "../menus";
@@ -118,19 +119,23 @@ class App {
case "setLocalStorageVal":
if (window.siyuan.storage) {
window.siyuan.storage[data.data.key] = data.data.val;
+ onWindowWorkspaceStorageChanged(data.data.key);
}
break;
case "setLocalStorageVals":
Object.keys(data.data.keyVals).forEach((k) => {
window.siyuan.storage[k] = data.data.keyVals[k];
+ onWindowWorkspaceStorageChanged(k);
});
break;
case "removeLocalStorageVal":
delete window.siyuan.storage[data.data.key];
+ onWindowWorkspaceStorageChanged(data.data.key);
break;
case "removeLocalStorageVals":
data.data.keys.forEach((k: string) => {
delete window.siyuan.storage[k];
+ onWindowWorkspaceStorageChanged(k);
});
break;
case "rename":
diff --git a/app/src/window/init.ts b/app/src/window/init.ts
index 8c4819f3ea..597aaec35b 100644
--- a/app/src/window/init.ts
+++ b/app/src/window/init.ts
@@ -2,7 +2,7 @@ import {Constants} from "../constants";
import {ipcRenderer, webFrame} from "electron";
import {fetchPost} from "../util/fetch";
import {adjustLayout, getInstanceById, JSONToCenter} from "../layout/util";
-import {resizeTabs, setTabPosition} from "../layout/tabUtil";
+import {newCenterEmptyTab, resizeTabs, setTabPosition} from "../layout/tabUtil";
import {initStatus} from "../layout/status";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
import {initAssets, setInlineStyle} from "../util/assets";
@@ -17,7 +17,9 @@ import {initWindowOpenOverride} from "../protyle/util/compatibility";
import {initNativeDialogOverride} from "../protyle/util/compatibility";
/// #endif
import {initWindowEvent} from "../boot/globalEvent/event";
-import {getAllEditor} from "../layout/getAll";
+import {getAllEditor, getAllWnds} from "../layout/getAll";
+import {activateWindowWorkspace, getWindowWorkspaceLayout} from "./workspace";
+import {Wnd} from "../layout/Wnd";
export const init = async (app: App) => {
@@ -34,13 +36,19 @@ export const init = async (app: App) => {
fetchPost("/api/system/getEmojiConf", {}, response => {
window.siyuan.emojis = response.data as IEmoji[];
+ const workspaceLayout = getWindowWorkspaceLayout();
const layout = JSON.parse(sessionStorage.getItem("layout") || "{}");
+ if (!layout.layout && workspaceLayout) {
+ layout.layout = workspaceLayout;
+ }
if (layout.layout) {
JSONToCenter(app, layout.layout);
window.siyuan.layout.centerLayout = window.siyuan.layout.layout;
} else {
- const tabsJSON = JSON.parse(getSearch("json"));
- tabsJSON[tabsJSON.length - 1].active = true;
+ const tabsJSON = JSON.parse(getSearch("json") || "[]");
+ if (tabsJSON.length) {
+ tabsJSON[tabsJSON.length - 1].active = true;
+ }
JSONToCenter(app, {
direction: "lr",
resize: "lr",
@@ -55,7 +63,18 @@ export const init = async (app: App) => {
window.siyuan.layout.centerLayout = window.siyuan.layout.layout;
adjustLayout(window.siyuan.layout.centerLayout);
}
+ const wnds: Wnd[] = [];
+ getAllWnds(window.siyuan.layout.centerLayout, wnds);
+ if (!wnds.length) {
+ const wnd = new Wnd(app);
+ window.siyuan.layout.centerLayout.addWnd(wnd);
+ wnds.push(wnd);
+ }
+ wnds.filter(wnd => !wnd.children.length).forEach(wnd => {
+ wnd.addTab(newCenterEmptyTab(app), false, false);
+ });
afterLayout(app);
+ activateWindowWorkspace();
// 等待 dock 面板动画结束
setTimeout(() => {
setTabPosition();
diff --git a/app/src/window/onWindowsMsg.ts b/app/src/window/onWindowsMsg.ts
index fd5ec9b39b..739615e490 100644
--- a/app/src/window/onWindowsMsg.ts
+++ b/app/src/window/onWindowsMsg.ts
@@ -4,6 +4,7 @@ import {lockScreen} from "../dialog/processSystem";
import {clearTabDragPreview} from "../layout/tabDrag";
import {getAllEditor} from "../layout/getAll";
import {ipcRenderer} from "electron";
+import {flushWindowWorkspace} from "./workspace";
const closeTab = (ipcData: IWebSocketData) => {
const tab = getInstanceById(ipcData.data);
@@ -13,6 +14,13 @@ const closeTab = (ipcData: IWebSocketData) => {
};
export const onWindowsMsg = (ipcData: IWebSocketData) => {
switch (ipcData.cmd) {
+ case "flushWindowWorkspace":
+ void flushWindowWorkspace().then(saved => {
+ ipcRenderer.send("siyuan-window-workspace-saved", {id: ipcData.data, saved});
+ }).catch(() => {
+ ipcRenderer.send("siyuan-window-workspace-saved", {id: ipcData.data, saved: false});
+ });
+ break;
case "prepareNotebookSystemLock":
void Promise.all(getAllEditor().filter(editor => editor?.protyle?.wysiwyg)
.map(editor => editor.flushPendingTransactions())).then(() => {
diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.ts
index 2b00b2a78b..5671134524 100644
--- a/app/src/window/openNewWindow.ts
+++ b/app/src/window/openNewWindow.ts
@@ -28,6 +28,14 @@ const getWindowURL = (layout: unknown) => {
return appendRemoteQuery(url).href;
};
+export const openNewWindowByWorkspace = (id: string) => {
+ /// #if !BROWSER
+ const url = new URL(getWindowURL([]));
+ url.searchParams.set("windowWorkspace", id);
+ ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: url.href, alwaysOnTop: false});
+ /// #endif
+};
+
export const openNewWindow = (tab: Tab, options: windowOptions = {}) => {
const json = {};
layoutToJSON(tab, json);
diff --git a/app/src/window/workspace.test.ts b/app/src/window/workspace.test.ts
new file mode 100644
index 0000000000..b971e178f7
--- /dev/null
+++ b/app/src/window/workspace.test.ts
@@ -0,0 +1,248 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import * as core from "./workspaceCore";
+
+const compiled = transpileModule(readFileSync("src/window/workspace.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+const prefix = "local-window-workspace-";
+const id = "20260922100000-abcdefg";
+const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
+const tick = () => new Promise<void>(resolve => setImmediate(resolve));
+const layout = () => ({instance: "Layout", direction: "lr", children: [{instance: "Wnd", children: [{
+ instance: "Tab", title: "Document", active: true, children: {
+ instance: "Editor", blockId: "doc", rootId: "doc", notebookId: "box", scrollAttr: {rootId: "doc", scrollTop: 120},
+ }}, {
+ instance: "Tab", title: "PDF", children: {instance: "Asset", path: "assets/book.pdf", page: 4},
+ }]}]});
+
+const fixture = (initialStorage: Record<string, unknown> = {}, workspaceID = "") => {
+ const storage = clone(initialStorage);
+ const disk = clone(initialStorage);
+ const state = {
+ layout: layout(),
+ fail: false,
+ incomplete: false,
+ focus: false,
+ gate: undefined as Promise<void> | undefined,
+ };
+ let dialogOptions: any;
+ let url = new URL(`http://127.0.0.1:6806/stage/build/app/window.html?windowWorkspace=${workspaceID}`);
+ const writes: Array<{key: string, value: any}> = [];
+ const messages: string[] = [];
+ const opened: string[] = [];
+ const associated: string[] = [];
+ const dependencies = {
+ ...core,
+ Constants: {LOCAL_WINDOW_WORKSPACE: prefix, SIYUAN_APPID: "test", SIYUAN_GET: "get"},
+ getSearch: (key: string) => url.searchParams.get(key),
+ isBrowser: () => false,
+ isWindow: () => true,
+ setStorageVal: async (key: string, value: unknown, callback: () => void) => {
+ writes.push({key, value: clone(value)});
+ if (state.gate) {
+ await state.gate;
+ }
+ if (!state.fail) {
+ disk[key] = clone(value);
+ callback();
+ }
+ },
+ fetchSyncPost: async (_url: string, data: {keys: string[]}) => {
+ data.keys.forEach(key => delete disk[key]);
+ return {code: 0};
+ },
+ layoutToJSON: (_layout: unknown, target: object, incomplete: Record<string, string>) => {
+ Object.assign(target, clone(state.layout));
+ if (state.incomplete) {
+ incomplete.editor = "true";
+ }
+ },
+ setTabPosition: () => {},
+ setWindowWorkspaceTitle: () => {},
+ openInputDialog: (options: unknown) => dialogOptions = options,
+ confirmDialog: (_title: string, _message: string, confirm: () => void) => confirm(),
+ showMessage: (message: string) => messages.push(message),
+ escapeHtml: (text: string) => text,
+ openNewWindowByWorkspace: (workspace: string) => opened.push(workspace),
+ ipcRenderer: {invoke: async (_channel: string, data: {cmd: string, id: string}) => {
+ if (data.cmd === "setWindowWorkspace") {
+ associated.push(data.id);
+ return true;
+ }
+ return state.focus;
+ }},
+ };
+ const api = {} as typeof import("./workspace");
+ const window = {
+ siyuan: {
+ storage,
+ config: {readonly: false},
+ isPublish: false,
+ layout: {layout: {}},
+ languages: new Proxy<Record<string, unknown>>({windowWorkspaces: "New window layouts", confirm: "Confirm"}, {
+ get: (target, key) => typeof key === "string" && key in target ? target[key] : String(key),
+ }),
+ },
+ location: {href: url.href},
+ history: {replaceState: (_state: unknown, _title: string, nextURL: URL) => url = nextURL},
+ clearTimeout: () => {},
+ dispatchEvent: () => {},
+ };
+ runInNewContext(compiled, {
+ exports: api, require: () => dependencies, window, document: {getElementById: (): HTMLElement | null => null},
+ console, URL, Event, Lute: {NewNodeID: () => id},
+ });
+ return {
+ api, state, storage, disk, writes, messages, opened, associated, window,
+ dialog: () => dialogOptions,
+ boot: () => {
+ const restored = api.getWindowWorkspaceLayout();
+ api.activateWindowWorkspace();
+ return restored;
+ },
+ };
+};
+
+const savedStorage = () => ({
+ [prefix + id]: {version: 1, id, name: "Reading"},
+ [prefix + id + "-layout"]: {version: 1, time: 1, layout: layout()},
+});
+
+test("保存命名窗口,重新加载后恢复文档、PDF 页码和阅读位置", async () => {
+ const f = fixture();
+ f.boot();
+ f.api.editWindowWorkspace();
+ await f.dialog().onConfirm(" Reading ", {destroy: () => {}});
+ assert.equal((f.disk[prefix + id] as core.IWindowWorkspace).name, "Reading");
+ assert.deepEqual(f.associated, [id]);
+ const reopened = fixture(f.disk, id);
+ assert.equal(reopened.api.getWindowWorkspaces()[0].time,
+ (f.disk[prefix + id + "-layout"] as core.IWindowWorkspaceSnapshot).time);
+ assert.deepEqual(clone(reopened.boot()), layout());
+ await reopened.api.openWindowWorkspace(id);
+ assert.deepEqual(reopened.opened, [id]);
+ reopened.state.focus = true;
+ await reopened.api.openWindowWorkspace(id);
+ assert.deepEqual(reopened.opened, [id]);
+});
+
+test("自动保存布局不会覆盖其他窗口写入的工作区名称", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.state.layout.children[0].children[0].children.scrollAttr.scrollTop = 480;
+ let release: () => void;
+ f.state.gate = new Promise<void>(resolve => release = resolve);
+ const saved = f.api.flushWindowWorkspace();
+ await tick();
+ f.storage[prefix + id] = {version: 1, id, name: "Renamed"};
+ f.disk[prefix + id] = clone(f.storage[prefix + id]);
+ f.api.onWindowWorkspaceStorageChanged(prefix + id);
+ release();
+ assert.equal(await saved, true);
+ assert.equal((f.disk[prefix + id] as core.IWindowWorkspace).name, "Renamed");
+ assert.deepEqual(f.writes.map(item => item.key), [prefix + id + "-layout"]);
+ assert.deepEqual(clone(fixture(f.disk, id).boot()), f.state.layout);
+});
+
+test("关闭前等待最新保存,状态回退到前一次内容时也不跳过在途请求", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.state.layout.children[0].children[1].children.page = 8;
+ let release: () => void;
+ f.state.gate = new Promise<void>(resolve => release = resolve);
+ const first = f.api.flushWindowWorkspace();
+ await tick();
+ f.state.layout = layout();
+ const last = f.api.flushWindowWorkspace();
+ release();
+ assert.equal(await first, true);
+ assert.equal(await last, true);
+ assert.deepEqual(clone(fixture(f.disk, id).boot()), layout());
+ assert.equal(f.writes.length, 2);
+});
+
+test("保存失败保留持久化快照并允许重试,加载未完成时不覆盖", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.state.layout.children[0].children[1].children.page = 8;
+ f.state.fail = true;
+ assert.equal(await f.api.flushWindowWorkspace(), false);
+ assert.deepEqual(f.disk, savedStorage());
+ assert.deepEqual(f.storage, savedStorage());
+ f.state.fail = false;
+ f.state.incomplete = true;
+ assert.equal(await f.api.flushWindowWorkspace(), false);
+ assert.equal(f.writes.length, 1);
+ f.state.incomplete = false;
+ assert.equal(await f.api.flushWindowWorkspace(), true);
+ assert.deepEqual(clone(fixture(f.disk, id).boot()), f.state.layout);
+});
+
+test("尚未发出请求时也以最后一次布局为准", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.state.layout.children[0].children[1].children.page = 8;
+ const first = f.api.flushWindowWorkspace();
+ f.state.layout = layout();
+ const last = f.api.flushWindowWorkspace();
+ assert.equal(await first, true);
+ assert.equal(await last, true);
+ assert.deepEqual(clone(fixture(f.disk, id).boot()), layout());
+});
+
+test("移除工作区不会让在途自动保存重新创建列表项或留下布局", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.state.layout.children[0].children[1].children.page = 8;
+ let release: () => void;
+ f.state.gate = new Promise<void>(resolve => release = resolve);
+ const pending = f.api.flushWindowWorkspace();
+ await tick();
+ const tombstone = {version: 1, id, name: "Reading", deleted: true};
+ f.storage[prefix + id] = tombstone;
+ f.disk[prefix + id] = clone(tombstone);
+ f.api.onWindowWorkspaceStorageChanged(prefix + id);
+ release();
+ await pending;
+ await tick();
+ assert.equal(f.api.getWindowWorkspaces().length, 0);
+ assert.equal(prefix + id + "-layout" in f.disk, false);
+ assert.deepEqual(f.associated, [""]);
+ assert.equal(await f.api.flushWindowWorkspace(), true);
+ assert.equal(f.writes.length, 1);
+});
+
+test("未知快照和只读状态不触发写入", async () => {
+ const storage = savedStorage();
+ storage[prefix + id + "-layout"].version = 2;
+ const f = fixture(storage, id);
+ assert.equal(f.boot(), undefined);
+ assert.equal(await f.api.flushWindowWorkspace(), true);
+ assert.deepEqual(f.disk, storage);
+ assert.equal(f.writes.length, 0);
+ assert.deepEqual(f.messages, ["windowWorkspaceUnavailable"]);
+ const readonly = fixture(savedStorage(), id);
+ readonly.boot();
+ readonly.window.siyuan.config.readonly = true;
+ readonly.state.layout.children[0].children[1].children.page = 8;
+ assert.equal(await readonly.api.flushWindowWorkspace(), true);
+ assert.equal(readonly.writes.length, 0);
+});
+
+test("新窗口布局重命名弹窗只提交名称,使用对应标题及确定按钮且无命名标签", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.api.editWindowWorkspace(id);
+ assert.equal(f.dialog().title, "New window layouts");
+ assert.equal(f.dialog().label, undefined);
+ assert.equal(f.dialog().confirmText, "Confirm");
+ assert.equal(f.dialog().actions, undefined);
+ assert.equal(f.dialog().description, undefined);
+ await f.dialog().onConfirm("Renamed", {destroy: () => {}});
+ assert.equal((f.disk[prefix + id] as core.IWindowWorkspace).name, "Renamed");
+ assert.deepEqual(f.disk[prefix + id + "-layout"], savedStorage()[prefix + id + "-layout"]);
+});
diff --git a/app/src/window/workspace.ts b/app/src/window/workspace.ts
new file mode 100644
index 0000000000..c30ab4e352
--- /dev/null
+++ b/app/src/window/workspace.ts
@@ -0,0 +1,340 @@
+import {Constants} from "../constants";
+import {getSearch, isBrowser, isWindow} from "../util/functions";
+import {setStorageVal} from "../protyle/util/compatibility";
+import {fetchSyncPost} from "../util/fetch";
+import {layoutToJSON} from "../layout/util";
+import {setTabPosition} from "../layout/tabUtil";
+import {openInputDialog} from "../dialog/inputDialog";
+import {confirmDialog} from "../dialog/confirmDialog";
+import {showMessage} from "../dialog/message";
+import {escapeHtml} from "../util/escape";
+import {setWindowWorkspaceTitle} from "../util/processTitle";
+import {openNewWindowByWorkspace} from "./openNewWindow";
+import {
+ isWindowWorkspace,
+ isWindowWorkspaceID,
+ isWindowWorkspaceSnapshot,
+ WindowWorkspaceWriter,
+} from "./workspaceCore";
+import type {IWindowWorkspace, IWindowWorkspaceSnapshot} from "./workspaceCore";
+/// #if !BROWSER
+import {ipcRenderer} from "electron";
+/// #endif
+
+const infoKey = (id: string) => Constants.LOCAL_WINDOW_WORKSPACE + id;
+const layoutKey = (id: string) => infoKey(id) + "-layout";
+let currentID: string | undefined;
+let ready = false;
+let initialized = false;
+let saveTimer = 0;
+let lastSaved = "";
+let lastSaveOK = true;
+
+export const getWindowWorkspace = (id: string) => {
+ const value: unknown = window.siyuan.storage?.[infoKey(id)];
+ return isWindowWorkspace(value) && value.id === id ? value : undefined;
+};
+
+export const getWindowWorkspaces = () => Object.keys(window.siyuan.storage || {})
+ .filter(key => key.startsWith(Constants.LOCAL_WINDOW_WORKSPACE))
+ .map(key => getWindowWorkspace(key.slice(Constants.LOCAL_WINDOW_WORKSPACE.length)))
+ .filter((value): value is IWindowWorkspace => !!value)
+ .map(value => {
+ const snapshot: unknown = window.siyuan.storage[layoutKey(value.id)];
+ return {...value, time: isWindowWorkspaceSnapshot(snapshot) ? snapshot.time : undefined};
+ })
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
+
+const persist = async (key: string, value: IWindowWorkspace | IWindowWorkspaceSnapshot) => {
+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {
+ return false;
+ }
+ const previous = window.siyuan.storage[key];
+ window.siyuan.storage[key] = value;
+ let saved = false;
+ try {
+ await setStorageVal(key, value, () => saved = true, 10000);
+ } catch (error) {
+ console.error(error);
+ }
+ if (!saved && window.siyuan.storage[key] === value) {
+ window.siyuan.storage[key] = previous;
+ }
+ if (saved) {
+ onWindowWorkspaceStorageChanged(key);
+ }
+ return saved;
+};
+
+const removeSnapshot = async (id: string) => {
+ const key = layoutKey(id);
+ try {
+ const response = await fetchSyncPost("/api/storage/removeLocalStorageVals", {
+ app: Constants.SIYUAN_APPID,
+ keys: [key],
+ });
+ if (response.code === 0) {
+ delete window.siyuan.storage[key];
+ return true;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+ return false;
+};
+
+const writer = new WindowWorkspaceWriter<{id: string, snapshot: IWindowWorkspaceSnapshot}>(async ({id, snapshot}) => {
+ if (!getWindowWorkspace(id) || currentID !== id) {
+ return true;
+ }
+ lastSaveOK = false;
+ const saved = await persist(layoutKey(id), snapshot);
+ if (currentID === id) {
+ if (saved) {
+ lastSaved = JSON.stringify(snapshot.layout);
+ }
+ lastSaveOK = saved;
+ }
+ return saved;
+});
+
+const capture = (): IWindowWorkspaceSnapshot | undefined => {
+ if (!window.siyuan.layout?.layout) {
+ return;
+ }
+ const layout: Config.TPersistedUILayoutItem = {instance: "Layout", children: []};
+ const incomplete: IObject = {};
+ layoutToJSON(window.siyuan.layout.layout, layout, incomplete);
+ if (Object.keys(incomplete).length) {
+ return;
+ }
+ const snapshot: IWindowWorkspaceSnapshot = {version: 1, time: Date.now(), layout};
+ return isWindowWorkspaceSnapshot(snapshot) ? snapshot : undefined;
+};
+
+export const flushWindowWorkspace = async () => {
+ window.clearTimeout(saveTimer);
+ if (!currentID || !ready || window.siyuan.config.readonly || !getWindowWorkspace(currentID)) {
+ return true;
+ }
+ const snapshot = capture();
+ if (!snapshot) {
+ return false;
+ }
+ if (lastSaveOK && JSON.stringify(snapshot.layout) === lastSaved) {
+ return true;
+ }
+ lastSaveOK = false;
+ return writer.save({id: currentID, snapshot});
+};
+
+const scheduleSave = () => {
+ if (!currentID || !ready) {
+ return;
+ }
+ window.clearTimeout(saveTimer);
+ saveTimer = window.setTimeout(() => {
+ void flushWindowWorkspace();
+ }, 800);
+};
+
+const associate = async (id?: string) => {
+ /// #if !BROWSER
+ if (!await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "setWindowWorkspace", id: id || ""})) {
+ return false;
+ }
+ /// #endif
+ currentID = id;
+ const url = new URL(window.location.href);
+ if (id) {
+ url.searchParams.set("windowWorkspace", id);
+ } else {
+ url.searchParams.delete("windowWorkspace");
+ }
+ window.history.replaceState(window.history.state, "", url);
+ updateWindowWorkspaceButton();
+ return true;
+};
+
+export const getWindowWorkspaceLayout = () => {
+ const id = getSearch("windowWorkspace");
+ if (!isWindowWorkspaceID(id)) {
+ return;
+ }
+ const snapshot: unknown = window.siyuan.storage[layoutKey(id)];
+ if (!getWindowWorkspace(id) || !isWindowWorkspaceSnapshot(snapshot)) {
+ showMessage(window.siyuan.languages.windowWorkspaceUnavailable, 6000, "error");
+ void associate();
+ return;
+ }
+ currentID = id;
+ lastSaved = JSON.stringify(snapshot.layout);
+ return JSON.parse(JSON.stringify(snapshot.layout)) as Config.TPersistedUILayoutItem;
+};
+
+export const activateWindowWorkspace = () => {
+ ready = true;
+ updateWindowWorkspaceButton();
+};
+
+export const openWindowWorkspace = async (id: string) => {
+ if (isBrowser()) {
+ return;
+ }
+ /// #if !BROWSER
+ if (await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "focusWindowWorkspace", id})) {
+ return;
+ }
+ /// #endif
+ if (!getWindowWorkspace(id) || !isWindowWorkspaceSnapshot(window.siyuan.storage[layoutKey(id)])) {
+ showMessage(window.siyuan.languages.windowWorkspaceUnavailable, 6000, "error");
+ return;
+ }
+ openNewWindowByWorkspace(id);
+};
+
+const removeWorkspace = async (id: string) => {
+ const workspace = getWindowWorkspace(id);
+ if (!workspace) {
+ return;
+ }
+ // 保留移除标记,使在途的布局写入无法重新创建列表项。
+ if (!await persist(infoKey(id), {...workspace, deleted: true})) {
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ return;
+ }
+ if (!await removeSnapshot(id)) {
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ }
+};
+
+export const removeWindowWorkspace = (id: string) => {
+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {
+ return;
+ }
+ const workspace = getWindowWorkspace(id);
+ if (workspace) {
+ confirmDialog(window.siyuan.languages.delete, window.siyuan.languages.windowWorkspaceRemoveTip
+ .replace("${x}", escapeHtml(workspace.name)), () => {
+ void removeWorkspace(id);
+ });
+ }
+};
+
+export const editWindowWorkspace = (id?: string) => {
+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {
+ return;
+ }
+ const workspace = id ? getWindowWorkspace(id) : undefined;
+ if (id && !workspace) {
+ showMessage(window.siyuan.languages.windowWorkspaceUnavailable, 6000, "error");
+ return;
+ }
+ let saving = false;
+ openInputDialog({
+ title: workspace ? window.siyuan.languages.windowWorkspaces :
+ window.siyuan.languages.windowWorkspaceSave,
+ value: workspace?.name || "",
+ maxLength: 100,
+ confirmText: window.siyuan.languages[workspace ? "confirm" : "save"],
+ onConfirm: async (value, dialog) => {
+ const name = value.trim();
+ if (!name || saving) {
+ if (!name) {
+ showMessage(window.siyuan.languages._kernel[142]);
+ }
+ return;
+ }
+ saving = true;
+ try {
+ if (workspace) {
+ const latest = getWindowWorkspace(id);
+ if (!latest || !await persist(infoKey(id), {...latest, name})) {
+ throw new Error("Window workspace rename failed");
+ }
+ } else {
+ const snapshot = capture();
+ if (!snapshot) {
+ throw new Error("Window layout is not ready");
+ }
+ const newID = Lute.NewNodeID();
+ if (!await persist(layoutKey(newID), snapshot) ||
+ !await persist(infoKey(newID), {version: 1, id: newID, name})) {
+ void removeSnapshot(newID);
+ throw new Error("Window workspace save failed");
+ }
+ if (!await associate(newID)) {
+ throw new Error("Window workspace association failed");
+ }
+ lastSaved = JSON.stringify(snapshot.layout);
+ lastSaveOK = true;
+ }
+ dialog.destroy();
+ } catch (error) {
+ console.error(error);
+ showMessage(window.siyuan.languages.windowWorkspaceSaveError, 6000, "error");
+ } finally {
+ saving = false;
+ }
+ },
+ });
+};
+
+const updateWindowWorkspaceButton = () => {
+ const button = document.getElementById("windowWorkspace");
+ if (!button) {
+ return;
+ }
+ const workspace = currentID ? getWindowWorkspace(currentID) : undefined;
+ button.setAttribute("aria-label", workspace?.name || window.siyuan.languages.windowWorkspaceSave);
+ setWindowWorkspaceTitle(workspace?.name || "");
+ const disabled = window.siyuan.config.readonly || !!window.siyuan.isPublish;
+ button.toggleAttribute("disabled", disabled);
+ button.classList.toggle("toolbar__item--disabled", disabled);
+ setTabPosition(true);
+};
+
+export const onWindowWorkspaceStorageChanged = (key: string) => {
+ if (!key.startsWith(Constants.LOCAL_WINDOW_WORKSPACE)) {
+ return;
+ }
+ if (!currentID || key !== infoKey(currentID)) {
+ return;
+ }
+ if (getWindowWorkspace(currentID)) {
+ updateWindowWorkspaceButton();
+ } else {
+ const id = currentID;
+ currentID = undefined;
+ window.clearTimeout(saveTimer);
+ void writer.stop().then(() => removeSnapshot(id)).catch(console.error);
+ void associate();
+ }
+};
+
+export const initWindowWorkspace = () => {
+ if (initialized || !isWindow()) {
+ return;
+ }
+ const toolbar = document.querySelector(".toolbar__window");
+ if (!toolbar) {
+ return;
+ }
+ initialized = true;
+ const button = document.createElement("button");
+ button.id = "windowWorkspace";
+ button.className = "toolbar__item ariaLabel window-workspace__button";
+ button.innerHTML = '<svg><use xlink:href="#iconLayout"></use></svg>';
+ toolbar.insertBefore(button, document.getElementById("pinWindow"));
+ button.addEventListener("click", () => editWindowWorkspace(currentID));
+ window.addEventListener("siyuan-window-layout", scheduleSave);
+ document.addEventListener("scroll", scheduleSave, true);
+ window.addEventListener("blur", () => void flushWindowWorkspace());
+ // PDF 页码由嵌入页面更新,定期比较快照,仅在布局或阅读位置改变时写入。
+ window.setInterval(() => {
+ if (currentID && document.visibilityState === "visible") {
+ void flushWindowWorkspace();
+ }
+ }, 3000);
+ updateWindowWorkspaceButton();
+};
diff --git a/app/src/window/workspaceCore.test.ts b/app/src/window/workspaceCore.test.ts
new file mode 100644
index 0000000000..0953313978
--- /dev/null
+++ b/app/src/window/workspaceCore.test.ts
@@ -0,0 +1,101 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {isWindowWorkspace, isWindowWorkspaceSnapshot, WindowWorkspaceWriter} from "./workspaceCore";
+
+const tick = () => new Promise<void>(resolve => setImmediate(resolve));
+
+test("工作区接受分屏和空页签,拒绝未知版本及损坏的层级", () => {
+ const snapshot = {
+ version: 1, time: 1, layout: {instance: "Layout", children: [{
+ instance: "Wnd", children: [{instance: "Tab", children: {}}, {
+ instance: "Tab", children: {instance: "Editor", rootId: "doc", scrollAttr: {rootId: "doc", scrollTop: 120}},
+ }],
+ }]},
+ };
+ assert.equal(isWindowWorkspaceSnapshot(snapshot), true);
+ assert.equal(isWindowWorkspaceSnapshot({...snapshot, version: 2}), false);
+ assert.equal(isWindowWorkspaceSnapshot({...snapshot, time: NaN}), false);
+ assert.equal(isWindowWorkspaceSnapshot({...snapshot, layout: {instance: "Layout", children: [{instance: "Editor"}]}}), false);
+ assert.equal(isWindowWorkspaceSnapshot({...snapshot, layout: {instance: "Layout", children: [{instance: "Wnd", children: [null]}]}}), false);
+ const cyclic = {instance: "Layout", children: [] as unknown[]};
+ cyclic.children.push(cyclic);
+ assert.equal(isWindowWorkspaceSnapshot({...snapshot, layout: cyclic}), false);
+});
+
+test("移除标记和不受支持的元数据不出现在工作区列表中", () => {
+ const workspace = {version: 1, id: "20260922100000-abcdefg", name: "阅读"};
+ assert.equal(isWindowWorkspace(workspace), true);
+ for (const invalid of [{...workspace, deleted: true}, {...workspace, version: 2}, {...workspace, id: "../layout"}, {...workspace, name: " "}]) {
+ assert.equal(isWindowWorkspace(invalid), false);
+ }
+});
+
+test("连续更新只保留最新等待值,并等待最后一次持久化", async () => {
+ const values: number[] = [];
+ const releases: Array<(saved: boolean) => void> = [];
+ const writer = new WindowWorkspaceWriter<number>(value => {
+ values.push(value);
+ return new Promise(resolve => releases.push(resolve));
+ });
+ const saved = writer.save(1);
+ await tick();
+ writer.save(2);
+ writer.save(3);
+ releases.shift()(true);
+ await tick();
+ assert.deepEqual(values, [1, 3]);
+ let finished = false;
+ void saved.then(() => finished = true);
+ await tick();
+ assert.equal(finished, false);
+ releases.shift()(true);
+ assert.equal(await saved, true);
+});
+
+test("请求失败后允许重试最新状态", async () => {
+ let succeed = false;
+ const values: number[] = [];
+ const writer = new WindowWorkspaceWriter<number>(async value => {
+ values.push(value);
+ return succeed;
+ });
+ assert.equal(await writer.save(1), false);
+ succeed = true;
+ assert.equal(await writer.save(2), true);
+ assert.deepEqual(values, [1, 2]);
+});
+
+test("完成写入同一轮微任务中的更新不会遗漏", async () => {
+ const values: number[] = [];
+ const writer = new WindowWorkspaceWriter<number>(async value => {
+ values.push(value);
+ if (value === 1) {
+ queueMicrotask(() => queueMicrotask(() => writer.save(2)));
+ }
+ return true;
+ });
+ await writer.save(1);
+ await tick();
+ assert.deepEqual(values, [1, 2]);
+});
+
+test("移除时等待在途请求结束并丢弃待写入状态", async () => {
+ const values: number[] = [];
+ let finish: (saved: boolean) => void;
+ const writer = new WindowWorkspaceWriter<number>(value => {
+ values.push(value);
+ return new Promise(resolve => finish = resolve);
+ });
+ writer.save(1);
+ await tick();
+ writer.save(2);
+ const stopped = writer.stop();
+ finish(false);
+ await stopped;
+ assert.deepEqual(values, [1]);
+ const next = writer.save(3);
+ await tick();
+ finish(true);
+ assert.equal(await next, true);
+ assert.deepEqual(values, [1, 3]);
+});
diff --git a/app/src/window/workspaceCore.ts b/app/src/window/workspaceCore.ts
new file mode 100644
index 0000000000..4acc5ababc
--- /dev/null
+++ b/app/src/window/workspaceCore.ts
@@ -0,0 +1,129 @@
+export interface IWindowWorkspace {
+ version: 1;
+ id: string;
+ name: string;
+ deleted?: true;
+}
+
+export interface IWindowWorkspaceSnapshot {
+ version: 1;
+ time: number;
+ layout: Config.TPersistedUILayoutItem;
+}
+
+const isObject = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === "object" && !Array.isArray(value);
+
+export const isWindowWorkspaceID = (value: unknown): value is string =>
+ typeof value === "string" && /^\d{14}-[a-z0-9]{7}$/.test(value);
+
+export const isWindowWorkspace = (value: unknown): value is IWindowWorkspace =>
+ isObject(value) && value.version === 1 && isWindowWorkspaceID(value.id) &&
+ typeof value.name === "string" && !!value.name.trim() && value.deleted === undefined;
+
+export const isWindowWorkspaceSnapshot = (value: unknown): value is IWindowWorkspaceSnapshot => {
+ if (!isObject(value) || value.version !== 1 || typeof value.time !== "number" ||
+ !Number.isFinite(value.time) || !isObject(value.layout) || value.layout.instance !== "Layout") {
+ return false;
+ }
+ const pending: unknown[] = [value.layout];
+ const visited = new Set<unknown>();
+ while (pending.length) {
+ const item = pending.pop();
+ if (!isObject(item) || visited.has(item) || visited.size > 100000) {
+ return false;
+ }
+ visited.add(item);
+ for (const key of ["title", "lang", "icon", "docIcon", "notebookId", "blockId", "rootId", "path",
+ "direction", "resize", "size", "type", "width", "height", "mode", "customModelType"]) {
+ if (item[key] !== undefined && typeof item[key] !== "string") {
+ return false;
+ }
+ }
+ if (item.scrollAttr !== undefined) {
+ const scroll = item.scrollAttr;
+ if (item.instance !== "Editor" || !isObject(scroll) || typeof scroll.rootId !== "string" ||
+ scroll.rootId !== item.rootId) {
+ return false;
+ }
+ for (const key of ["startId", "endId", "focusId", "zoomInId"]) {
+ if (scroll[key] !== undefined && typeof scroll[key] !== "string") {
+ return false;
+ }
+ }
+ for (const key of ["scrollTop", "focusStart", "focusEnd"]) {
+ if (scroll[key] !== undefined && (typeof scroll[key] !== "number" || !Number.isFinite(scroll[key]))) {
+ return false;
+ }
+ }
+ }
+ if (item.instance === "Layout" || item.instance === "Wnd") {
+ const allowed = item.instance === "Layout" ? ["Layout", "Wnd"] : ["Tab"];
+ if (!Array.isArray(item.children) || item.children.some(child => !isObject(child) ||
+ !allowed.includes(String(child.instance)))) {
+ return false;
+ }
+ for (const child of item.children) {
+ pending.push(child);
+ }
+ } else if (item.instance === "Tab") {
+ if (!isObject(item.children)) {
+ return false;
+ }
+ if (["Layout", "Wnd", "Tab"].includes(String(item.children.instance))) {
+ return false;
+ }
+ if (Object.keys(item.children).length) {
+ pending.push(item.children);
+ }
+ } else if (!["Editor", "Asset", "Backlink", "Graph", "Outline", "Search", "Custom", "Bookmark", "Files", "Tag"].includes(String(item.instance))) {
+ return false;
+ }
+ }
+ return true;
+};
+
+// 串行写入窗口状态,等待中的更新只保留最新值,避免较早的请求覆盖新状态。
+export class WindowWorkspaceWriter<T> {
+ private pending?: T;
+ private running?: Promise<boolean>;
+
+ constructor(private readonly write: (value: T) => Promise<boolean>) {
+ }
+
+ save(value: T) {
+ this.pending = value;
+ if (!this.running) {
+ this.running = Promise.resolve().then(() => this.flush());
+ }
+ return this.running;
+ }
+
+ private async flush() {
+ try {
+ while (this.pending !== undefined) {
+ const value = this.pending;
+ this.pending = undefined;
+ let saved = false;
+ try {
+ saved = await this.write(value);
+ } catch (error) {
+ console.error(error);
+ }
+ if (!saved) {
+ this.pending = this.pending ?? value;
+ return false;
+ }
+ }
+ return true;
+ } finally {
+ this.running = undefined;
+ }
+ }
+
+ async stop() {
+ this.pending = undefined;
+ await this.running;
+ this.pending = undefined;
+ }
+}