Skip to content

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

:art: Improve top bar customization with visibility controls and drag-and-drop reordering https://github.com/siyuan-note/siyuan/issues/18285

Danielceb221c56bb2
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 0f69d87e35..80c46f508c 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "الشريط العلوي",
+ "entryTopBarDrag": "منطقة سحب النافذة",
"bazaarFrontendDesktop": "نافذة سطح المكتب الرئيسية",
"bazaarFrontendDesktopWindow": "نافذة سطح مكتب مستقلة",
"bazaarFrontendMobile": "تطبيق الهاتف المحمول",
@@ -256,8 +258,8 @@
"entryInlineMenu": "قائمة العناصر السطرية",
"entrySubmenu": "قائمة فرعية",
"splitMergedCellTip": "يجب تقسيم الخلايا المدمجة أولاً",
- "entryVisibility": "القوائم وشريط الأدوات وشريط الإرساء",
- "entryVisibilityTip": "اضبط إظهار وترتيب عناصر قوائم سطح المكتب وشريط الأدوات المضمنة، واضبط إظهار أيقونات شريط الإرساء",
+ "entryVisibility": "الشريط العلوي والقوائم وشريط الأدوات وشريط الإرساء",
+ "entryVisibilityTip": "اضبط إظهار وترتيب عناصر الشريط العلوي والعناصر المضمنة في قوائم سطح المكتب وشريط الأدوات، واضبط إظهار أيقونات شريط الإرساء",
"entrySimple": "مبسّط",
"entryFull": "كامل",
"entrySimpleTip": "يعرض العناصر شائعة الاستخدام لمساعدة المستخدمين الجدد على البدء بسرعة",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 5f9a3d6130..4531405f9d 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Obere Leiste",
+ "entryTopBarDrag": "Ziehbereich des Fensters",
"bazaarFrontendDesktop": "Desktop-Hauptfenster",
"bazaarFrontendDesktopWindow": "Separates Desktop-Fenster",
"bazaarFrontendMobile": "Mobile App",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Inline-Element-Menü",
"entrySubmenu": "Untermenü",
"splitMergedCellTip": "Zusammengeführte Zellen müssen zuerst geteilt werden",
- "entryVisibility": "Menüs, Symbolleiste und Dock",
- "entryVisibilityTip": "Konfigurieren Sie die Sichtbarkeit und Reihenfolge integrierter Desktop-Menü- und Symbolleisteneinträge sowie die Sichtbarkeit der Dock-Symbole",
+ "entryVisibility": "Obere Leiste, Menüs, Symbolleiste und Dock",
+ "entryVisibilityTip": "Konfigurieren Sie die Sichtbarkeit und Reihenfolge von Einträgen in der oberen Leiste sowie integrierten Einträgen in Desktop-Menüs und der Symbolleiste und die Sichtbarkeit der Dock-Symbole",
"entrySimple": "Einfach",
"entryFull": "Vollständig",
"entrySimpleTip": "Zeigt häufig verwendete Einträge für einen schnellen Einstieg",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index b5e2ffbaf2..69d3f4b800 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Top bar",
+ "entryTopBarDrag": "Window drag area",
"bazaarFrontendDesktop": "Desktop main window",
"bazaarFrontendDesktopWindow": "Desktop detached window",
"bazaarFrontendMobile": "Mobile app",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Inline element menu",
"entrySubmenu": "Submenu",
"splitMergedCellTip": "Split merged cells first",
- "entryVisibility": "Menus, toolbar and dock",
- "entryVisibilityTip": "Configure the visibility and order of built-in desktop menu and toolbar items, and the visibility of dock icons",
+ "entryVisibility": "Top bar, menus, toolbar and dock",
+ "entryVisibilityTip": "Configure the visibility and order of desktop top bar items and built-in menu and toolbar items, and the visibility of dock icons",
"entrySimple": "Simple",
"entryFull": "Full",
"entrySimpleTip": "Shows commonly used entries for getting started quickly",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 0f7e62b6b2..02b90380e6 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Barra superior",
+ "entryTopBarDrag": "Área de arrastre de la ventana",
"bazaarFrontendDesktop": "Ventana principal de escritorio",
"bazaarFrontendDesktopWindow": "Ventana de escritorio independiente",
"bazaarFrontendMobile": "Aplicación móvil",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menú de elementos en línea",
"entrySubmenu": "Submenú",
"splitMergedCellTip": "Primero hay que dividir las celdas combinadas",
- "entryVisibility": "Menús, barra de herramientas y panel acoplable",
- "entryVisibilityTip": "Configura la visibilidad y el orden de los elementos integrados de los menús y la barra de herramientas del escritorio, así como la visibilidad de los iconos del panel acoplable",
+ "entryVisibility": "Barra superior, menús, barra de herramientas y panel acoplable",
+ "entryVisibilityTip": "Configura la visibilidad y el orden de los elementos de la barra superior y de los elementos integrados de los menús y la barra de herramientas del escritorio, así como la visibilidad de los iconos del panel acoplable",
"entrySimple": "Sencillo",
"entryFull": "Completo",
"entrySimpleTip": "Muestra las entradas más utilizadas para empezar rápidamente",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index ee871f55a2..bede74eeb7 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Barre supérieure",
+ "entryTopBarDrag": "Zone de déplacement de la fenêtre",
"bazaarFrontendDesktop": "Fenêtre principale de bureau",
"bazaarFrontendDesktopWindow": "Fenêtre de bureau indépendante",
"bazaarFrontendMobile": "Application mobile",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menu des éléments en ligne",
"entrySubmenu": "Sous-menu",
"splitMergedCellTip": "Les cellules fusionnées doivent d'abord être fractionnées",
- "entryVisibility": "Menus, barre d’outils et barre d’ancrage",
- "entryVisibilityTip": "Configurez la visibilité et l’ordre des éléments intégrés des menus et de la barre d’outils du bureau, ainsi que la visibilité des icônes de la barre d’ancrage",
+ "entryVisibility": "Barre supérieure, menus, barre d’outils et barre d’ancrage",
+ "entryVisibilityTip": "Configurez la visibilité et l’ordre des éléments de la barre supérieure et des éléments intégrés des menus et de la barre d’outils du bureau, ainsi que la visibilité des icônes de la barre d’ancrage",
"entrySimple": "Simple",
"entryFull": "Complet",
"entrySimpleTip": "Affiche les entrées courantes pour démarrer rapidement",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 673769fe46..e3fc50687e 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "סרגל עליון",
+ "entryTopBarDrag": "אזור גרירת החלון",
"bazaarFrontendDesktop": "חלון שולחן עבודה ראשי",
"bazaarFrontendDesktopWindow": "חלון שולחן עבודה נפרד",
"bazaarFrontendMobile": "יישום נייד",
@@ -256,8 +258,8 @@
"entryInlineMenu": "תפריט רכיבים בשורה",
"entrySubmenu": "תפריט משנה",
"splitMergedCellTip": "יש לפצל תחילה תאים ממוזגים",
- "entryVisibility": "תפריטים, סרגל כלים וסרגל עגינה",
- "entryVisibilityTip": "הגדרת הנראות והסדר של פריטי התפריט וסרגל הכלים המובנים בשולחן העבודה, והנראות של סמלי סרגל העגינה",
+ "entryVisibility": "סרגל עליון, תפריטים, סרגל כלים וסרגל עגינה",
+ "entryVisibilityTip": "הגדרת הנראות והסדר של פריטי הסרגל העליון ושל הפריטים המובנים בתפריטי שולחן העבודה ובסרגל הכלים, והנראות של סמלי סרגל העגינה",
"entrySimple": "פשוט",
"entryFull": "מלא",
"entrySimpleTip": "מציג פריטים נפוצים כדי לעזור למשתמשים חדשים להתחיל במהירות",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d52095cb72..e5a166bbdb 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "शीर्ष पट्टी",
+ "entryTopBarDrag": "विंडो खींचने का क्षेत्र",
"bazaarFrontendDesktop": "डेस्कटॉप मुख्य विंडो",
"bazaarFrontendDesktopWindow": "स्वतंत्र डेस्कटॉप विंडो",
"bazaarFrontendMobile": "मोबाइल ऐप",
@@ -256,8 +258,8 @@
"entryInlineMenu": "इनलाइन तत्व मेनू",
"entrySubmenu": "उपमेनू",
"splitMergedCellTip": "पहले मर्ज किए गए सेल विभाजित करें",
- "entryVisibility": "मेनू, टूलबार और डॉक",
- "entryVisibilityTip": "डेस्कटॉप के अंतर्निहित मेनू और टूलबार आइटम की दृश्यता व क्रम तथा डॉक आइकन की दृश्यता कॉन्फ़िगर करें",
+ "entryVisibility": "शीर्ष पट्टी, मेनू, टूलबार और डॉक",
+ "entryVisibilityTip": "शीर्ष पट्टी के आइटम तथा डेस्कटॉप मेनू और टूलबार के अंतर्निहित आइटम की दृश्यता व क्रम और डॉक आइकन की दृश्यता कॉन्फ़िगर करें",
"entrySimple": "सरल",
"entryFull": "पूर्ण",
"entrySimpleTip": "नए उपयोगकर्ताओं को जल्दी शुरू करने के लिए आम तौर पर उपयोग की जाने वाली प्रविष्टियाँ दिखाता है",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index f71223e5cd..e55761aeb3 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Bilah atas",
+ "entryTopBarDrag": "Area seret jendela",
"bazaarFrontendDesktop": "Jendela utama desktop",
"bazaarFrontendDesktopWindow": "Jendela desktop terpisah",
"bazaarFrontendMobile": "Aplikasi seluler",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menu elemen sebaris",
"entrySubmenu": "Submenu",
"splitMergedCellTip": "Pisahkan sel yang digabungkan terlebih dahulu",
- "entryVisibility": "Menu, bilah alat, dan dok",
- "entryVisibilityTip": "Atur visibilitas dan urutan item menu dan bilah alat desktop bawaan, serta visibilitas ikon dok",
+ "entryVisibility": "Bilah atas, menu, bilah alat, dan dok",
+ "entryVisibilityTip": "Atur visibilitas dan urutan item bilah atas serta item bawaan di menu desktop dan bilah alat, juga visibilitas ikon dok",
"entrySimple": "Sederhana",
"entryFull": "Lengkap",
"entrySimpleTip": "Menampilkan entri yang umum digunakan agar pengguna baru dapat memulai dengan cepat",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 227c29e82d..34e99f4e4c 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Barra superiore",
+ "entryTopBarDrag": "Area di trascinamento della finestra",
"bazaarFrontendDesktop": "Finestra principale desktop",
"bazaarFrontendDesktopWindow": "Finestra desktop separata",
"bazaarFrontendMobile": "App mobile",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menu degli elementi in linea",
"entrySubmenu": "Sottomenu",
"splitMergedCellTip": "Prima dividi le celle unite",
- "entryVisibility": "Menu, barra degli strumenti e barra di ancoraggio",
- "entryVisibilityTip": "Configura la visibilità e l'ordine delle voci integrate dei menu e della barra degli strumenti desktop, nonché la visibilità delle icone della barra di ancoraggio",
+ "entryVisibility": "Barra superiore, menu, barra degli strumenti e barra di ancoraggio",
+ "entryVisibilityTip": "Configura la visibilità e l'ordine delle voci della barra superiore e delle voci integrate dei menu e della barra degli strumenti desktop, nonché la visibilità delle icone della barra di ancoraggio",
"entrySimple": "Semplice",
"entryFull": "Completo",
"entrySimpleTip": "Mostra le voci usate più spesso per iniziare rapidamente",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 6c7ebe037f..06e6b4af6f 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "トップバー",
+ "entryTopBarDrag": "ウィンドウのドラッグ領域",
"bazaarFrontendDesktop": "デスクトップメインウィンドウ",
"bazaarFrontendDesktopWindow": "デスクトップ独立ウィンドウ",
"bazaarFrontendMobile": "モバイルアプリ",
@@ -256,8 +258,8 @@
"entryInlineMenu": "インライン要素メニュー",
"entrySubmenu": "サブメニュー",
"splitMergedCellTip": "先に結合セルを分割する必要があります",
- "entryVisibility": "メニュー、ツールバー、ドック",
- "entryVisibilityTip": "デスクトップの組み込みメニュー項目とツールバー項目の表示と順序、およびドックアイコンの表示を設定します",
+ "entryVisibility": "トップバー、メニュー、ツールバー、ドック",
+ "entryVisibilityTip": "トップバー項目とデスクトップメニューおよびツールバーの組み込み項目の表示と順序、およびドックアイコンの表示を設定します",
"entrySimple": "シンプル",
"entryFull": "完全",
"entrySimpleTip": "よく使う項目を表示し、すぐに使い始められる構成",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 23506b2973..5d140a3b75 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "상단 표시줄",
+ "entryTopBarDrag": "창 끌기 영역",
"bazaarFrontendDesktop": "데스크톱 기본 창",
"bazaarFrontendDesktopWindow": "데스크톱 독립 창",
"bazaarFrontendMobile": "모바일 앱",
@@ -256,8 +258,8 @@
"entryInlineMenu": "인라인 요소 메뉴",
"entrySubmenu": "하위 메뉴",
"splitMergedCellTip": "먼저 병합된 셀을 분할해야 합니다",
- "entryVisibility": "메뉴, 도구 모음 및 도크",
- "entryVisibilityTip": "데스크톱 기본 메뉴 및 도구 모음 항목의 표시 여부와 순서, 도크 아이콘의 표시 여부를 설정합니다",
+ "entryVisibility": "상단 표시줄, 메뉴, 도구 모음 및 도크",
+ "entryVisibilityTip": "상단 표시줄 항목과 데스크톱 메뉴 및 도구 모음의 기본 항목 표시 여부와 순서, 도크 아이콘의 표시 여부를 설정합니다",
"entrySimple": "간단",
"entryFull": "전체",
"entrySimpleTip": "자주 사용하는 항목을 표시해 새 사용자가 빠르게 시작할 수 있도록 함",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 728f392ff4..bad01531f6 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Bovenbalk",
+ "entryTopBarDrag": "Sleepgebied voor venster",
"bazaarFrontendDesktop": "Hoofdvenster van desktop-app",
"bazaarFrontendDesktopWindow": "Afzonderlijk desktopvenster",
"bazaarFrontendMobile": "Mobiele app",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menu voor inline-elementen",
"entrySubmenu": "Submenu",
"splitMergedCellTip": "Splits eerst de samengevoegde cellen",
- "entryVisibility": "Menu's, werkbalk en dock",
- "entryVisibilityTip": "Configureer de zichtbaarheid en volgorde van ingebouwde desktopmenu- en werkbalkitems en de zichtbaarheid van dockpictogrammen",
+ "entryVisibility": "Bovenbalk, menu's, werkbalk en dock",
+ "entryVisibilityTip": "Configureer de zichtbaarheid en volgorde van bovenbalkitems en ingebouwde items in desktopmenu's en de werkbalk, en de zichtbaarheid van dockpictogrammen",
"entrySimple": "Eenvoudig",
"entryFull": "Volledig",
"entrySimpleTip": "Toont veelgebruikte items om snel aan de slag te gaan",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index e225b78bc1..7c97681061 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Górny pasek",
+ "entryTopBarDrag": "Obszar przeciągania okna",
"bazaarFrontendDesktop": "Główne okno aplikacji komputerowej",
"bazaarFrontendDesktopWindow": "Oddzielne okno aplikacji komputerowej",
"bazaarFrontendMobile": "Aplikacja mobilna",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menu elementów wbudowanych",
"entrySubmenu": "Podmenu",
"splitMergedCellTip": "Najpierw podziel scalone komórki",
- "entryVisibility": "Menu, pasek narzędzi i dok",
- "entryVisibilityTip": "Skonfiguruj widoczność i kolejność wbudowanych elementów menu i paska narzędzi pulpitu, a także widoczność ikon doku",
+ "entryVisibility": "Górny pasek, menu, pasek narzędzi i dok",
+ "entryVisibilityTip": "Skonfiguruj widoczność i kolejność elementów górnego paska oraz wbudowanych elementów menu i paska narzędzi pulpitu, a także widoczność ikon doku",
"entrySimple": "Prosty",
"entryFull": "Pełny",
"entrySimpleTip": "Wyświetla często używane pozycje, aby ułatwić szybki start",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index d568ab876f..8406589df5 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Barra superior",
+ "entryTopBarDrag": "Área de arrasto da janela",
"bazaarFrontendDesktop": "Janela principal do desktop",
"bazaarFrontendDesktopWindow": "Janela separada do desktop",
"bazaarFrontendMobile": "Aplicativo móvel",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Menu de elementos em linha",
"entrySubmenu": "Submenu",
"splitMergedCellTip": "Divida primeiro as células mescladas",
- "entryVisibility": "Menus, barra de ferramentas e dock",
- "entryVisibilityTip": "Configure a visibilidade e a ordem dos itens integrados dos menus e da barra de ferramentas da área de trabalho, bem como a visibilidade dos ícones do dock",
+ "entryVisibility": "Barra superior, menus, barra de ferramentas e dock",
+ "entryVisibilityTip": "Configure a visibilidade e a ordem dos itens da barra superior e dos itens integrados dos menus e da barra de ferramentas da área de trabalho, bem como a visibilidade dos ícones do dock",
"entrySimple": "Simples",
"entryFull": "Completo",
"entrySimpleTip": "Mostra os itens mais usados para começar rapidamente",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 8a21a98c4e..6c98adb070 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Верхняя панель",
+ "entryTopBarDrag": "Область перетаскивания окна",
"bazaarFrontendDesktop": "Главное окно приложения",
"bazaarFrontendDesktopWindow": "Отдельное окно приложения",
"bazaarFrontendMobile": "Мобильное приложение",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Меню строчных элементов",
"entrySubmenu": "Подменю",
"splitMergedCellTip": "Сначала разделите объединённые ячейки",
- "entryVisibility": "Меню, панель инструментов и док-панель",
- "entryVisibilityTip": "Настройте видимость и порядок встроенных пунктов меню и панели инструментов рабочего стола, а также видимость значков док-панели",
+ "entryVisibility": "Верхняя панель, меню, панель инструментов и док-панель",
+ "entryVisibilityTip": "Настройте видимость и порядок элементов верхней панели и встроенных пунктов меню и панели инструментов рабочего стола, а также видимость значков док-панели",
"entrySimple": "Простой",
"entryFull": "Полный",
"entrySimpleTip": "Показывает часто используемые пункты, чтобы быстрее начать работу",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 19e349809d..28865b391e 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Horný panel",
+ "entryTopBarDrag": "Oblasť na presúvanie okna",
"bazaarFrontendDesktop": "Hlavné okno počítačovej aplikácie",
"bazaarFrontendDesktopWindow": "Samostatné okno počítačovej aplikácie",
"bazaarFrontendMobile": "Mobilná aplikácia",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Ponuka vnorených prvkov",
"entrySubmenu": "Podponuka",
"splitMergedCellTip": "Najprv rozdeľte zlúčené bunky",
- "entryVisibility": "Ponuky, panel s nástrojmi a dok",
- "entryVisibilityTip": "Nastavte viditeľnosť a poradie vstavaných položiek ponúk a panela s nástrojmi na pracovnej ploche, ako aj viditeľnosť ikon doku",
+ "entryVisibility": "Horný panel, ponuky, panel s nástrojmi a dok",
+ "entryVisibilityTip": "Nastavte viditeľnosť a poradie položiek horného panela a vstavaných položiek ponúk a panela s nástrojmi na pracovnej ploche, ako aj viditeľnosť ikon doku",
"entrySimple": "Jednoduchý",
"entryFull": "Úplný",
"entrySimpleTip": "Zobrazuje často používané položky na rýchle začatie práce",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 867ada918a..f6cfb79c5b 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "แถบด้านบน",
+ "entryTopBarDrag": "พื้นที่ลากหน้าต่าง",
"bazaarFrontendDesktop": "หน้าต่างหลักเดสก์ท็อป",
"bazaarFrontendDesktopWindow": "หน้าต่างเดสก์ท็อปแยก",
"bazaarFrontendMobile": "แอปมือถือ",
@@ -256,8 +258,8 @@
"entryInlineMenu": "เมนูองค์ประกอบอินไลน์",
"entrySubmenu": "เมนูย่อย",
"splitMergedCellTip": "ต้องแยกเซลล์ที่ผสานก่อน",
- "entryVisibility": "เมนู แถบเครื่องมือ และแถบเชื่อมต่อ",
- "entryVisibilityTip": "กำหนดการแสดงผลและลำดับของรายการเมนูและแถบเครื่องมือเดสก์ท็อปในตัว ตลอดจนการแสดงผลของไอคอนแถบเชื่อมต่อ",
+ "entryVisibility": "แถบด้านบน เมนู แถบเครื่องมือ และแถบเชื่อมต่อ",
+ "entryVisibilityTip": "กำหนดการแสดงผลและลำดับของรายการแถบด้านบน และรายการในตัวของเมนูเดสก์ท็อปและแถบเครื่องมือ ตลอดจนการแสดงผลของไอคอนแถบเชื่อมต่อ",
"entrySimple": "เรียบง่าย",
"entryFull": "ครบถ้วน",
"entrySimpleTip": "แสดงรายการที่ใช้บ่อยเพื่อช่วยให้ผู้ใช้ใหม่เริ่มต้นได้อย่างรวดเร็ว",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index c8dfaa7346..5acaabeb6f 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Üst çubuk",
+ "entryTopBarDrag": "Pencere sürükleme alanı",
"bazaarFrontendDesktop": "Masaüstü ana penceresi",
"bazaarFrontendDesktopWindow": "Bağımsız masaüstü penceresi",
"bazaarFrontendMobile": "Mobil uygulama",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Satır içi öğe menüsü",
"entrySubmenu": "Alt menü",
"splitMergedCellTip": "Önce birleştirilmiş hücreleri bölün",
- "entryVisibility": "Menüler, araç çubuğu ve yuva",
- "entryVisibilityTip": "Yerleşik masaüstü menü ve araç çubuğu öğelerinin görünürlüğünü ve sırasını, ayrıca yuva simgelerinin görünürlüğünü yapılandırın",
+ "entryVisibility": "Üst çubuk, menüler, araç çubuğu ve yuva",
+ "entryVisibilityTip": "Üst çubuk öğeleri ile masaüstü menüleri ve araç çubuğundaki yerleşik öğelerin görünürlüğünü ve sırasını, ayrıca yuva simgelerinin görünürlüğünü yapılandırın",
"entrySimple": "Basit",
"entryFull": "Tam",
"entrySimpleTip": "Yeni kullanıcıların hızlıca başlayabilmesi için sık kullanılan öğeleri gösterir",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index ac6c770606..079ddfdf7c 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "Верхня панель",
+ "entryTopBarDrag": "Область перетягування вікна",
"bazaarFrontendDesktop": "Головне вікно програми",
"bazaarFrontendDesktopWindow": "Окреме вікно програми",
"bazaarFrontendMobile": "Мобільний застосунок",
@@ -256,8 +258,8 @@
"entryInlineMenu": "Меню рядкових елементів",
"entrySubmenu": "Підменю",
"splitMergedCellTip": "Спочатку розділіть об’єднані комірки",
- "entryVisibility": "Меню, панель інструментів і док-панель",
- "entryVisibilityTip": "Налаштуйте видимість і порядок вбудованих пунктів меню та панелі інструментів робочого столу, а також видимість піктограм док-панелі",
+ "entryVisibility": "Верхня панель, меню, панель інструментів і док-панель",
+ "entryVisibilityTip": "Налаштуйте видимість і порядок елементів верхньої панелі та вбудованих пунктів меню й панелі інструментів робочого столу, а також видимість піктограм док-панелі",
"entrySimple": "Простий",
"entryFull": "Повний",
"entrySimpleTip": "Показує часто використовувані пункти, щоб швидше почати роботу",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index deb694e87c..9354219683 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "顶栏",
+ "entryTopBarDrag": "窗口拖拽区域",
"bazaarFrontendDesktop": "桌面主窗口",
"bazaarFrontendDesktopWindow": "桌面独立窗口",
"bazaarFrontendMobile": "移动应用",
@@ -256,8 +258,8 @@
"entryInlineMenu": "行级元素菜单",
"entrySubmenu": "子菜单",
"splitMergedCellTip": "需要先拆分合并的单元格",
- "entryVisibility": "菜单、工具栏与停靠栏",
- "entryVisibilityTip": "配置桌面端内置菜单项与工具栏项的显隐与排序,以及停靠栏图标的显隐",
+ "entryVisibility": "顶栏、菜单、工具栏与停靠栏",
+ "entryVisibilityTip": "配置桌面端顶栏项、内置菜单项与工具栏项的显隐与排序,以及停靠栏图标的显隐",
"entrySimple": "简洁方案",
"entryFull": "完整方案",
"entrySimpleTip": "显示常用入口,适合新用户快速上手",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 597f11923e..f6663ed959 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "entryTopBar": "頂欄",
+ "entryTopBarDrag": "視窗拖曳區域",
"bazaarFrontendDesktop": "桌面主視窗",
"bazaarFrontendDesktopWindow": "桌面獨立視窗",
"bazaarFrontendMobile": "行動應用程式",
@@ -256,8 +258,8 @@
"entryInlineMenu": "行級元素菜單",
"entrySubmenu": "子菜單",
"splitMergedCellTip": "需要先拆分合併的單元格",
- "entryVisibility": "選單、工具列與停靠欄",
- "entryVisibilityTip": "設定桌面端內建選單項目與工具列項目的顯示與排序,以及停靠欄圖示的顯示",
+ "entryVisibility": "頂欄、選單、工具列與停靠欄",
+ "entryVisibilityTip": "設定桌面端頂欄項目、內建選單項目與工具列項目的顯示與排序,以及停靠欄圖示的顯示",
"entrySimple": "簡潔方案",
"entryFull": "完整方案",
"entrySimpleTip": "顯示常用入口,適合新使用者快速上手",
diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scss
index 3188b68d5b..a16f0557a8 100644
--- a/app/src/assets/scss/main/_main.scss
+++ b/app/src/assets/scss/main/_main.scss
@@ -77,6 +77,11 @@ html[data-frontend="browser-desktop"] {
padding: 0 5px 0 var(--b3-toolbar-left-mac);
overflow: hidden; // 最小化后右上角显示不全
+ & > [data-entry-hidden="true"],
+ & > [data-topbar-empty="true"] {
+ display: none !important;
+ }
+
&--browser {
padding-left: calc(env(titlebar-area-x, 0px) + 5px);
padding-right: calc(100% - env(titlebar-area-width, 100%) - env(titlebar-area-x, 0px) + 5px);
@@ -102,6 +107,10 @@ html[data-frontend="browser-desktop"] {
font-size: 12px;
min-width: 148px;
box-sizing: border-box;
+
+ &[data-topbar-reordering="true"] {
+ -webkit-app-region: no-drag;
+ }
}
&__item {
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 9429c20119..af39b9f915 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -12,20 +12,26 @@ import {
import {
entryCatalog,
getEntryCatalogChildren,
+ getEntryCatalogDefaultVisibility,
getEntryCatalogNode,
getEntryCatalogPathChain,
getEntryCatalogSection,
getEntryParentPath,
getEntryOrderParents,
getEntryPaths,
+ getLegacyPluginTopBarEntryKey,
getPluginDockEntryKey,
getPluginSlashEntryKey,
+ getPluginTopBarEntryKey,
getSlashMenuEntryPath,
+ isEntryCatalogNodeConfigurable,
isEntryOrderSortable,
refreshDockCatalog,
refreshSlashMenuCatalog,
+ refreshTopBarCatalog,
refreshToolbarCatalog,
SLASH_MENU_ROOT_PATH,
+ TOP_BAR_ROOT_PATH,
} from "./catalog";
const slashMenuBuiltinOrder = [
@@ -114,7 +120,185 @@ test("entry catalog paths are unique and indexed", () => {
};
entryCatalog.forEach((section) => visit(section.key, section.children));
assert.equal(new Set(paths).size, paths.length);
- assert.deepEqual(new Set(getEntryPaths()), new Set(paths));
+ assert.deepEqual(new Set(getEntryPaths()), new Set(paths.filter((path) =>
+ isEntryCatalogNodeConfigurable(getEntryCatalogNode(path)!))));
+});
+
+test("top bar catalog includes a fixed drag boundary in built-in DOM order", () => {
+ assert.equal(TOP_BAR_ROOT_PATH, "topBar");
+ assert.deepEqual(getEntryCatalogChildren(TOP_BAR_ROOT_PATH).map((item) => item.key), [
+ "barSync",
+ "barBack",
+ "barForward",
+ "drag",
+ "toolbarVIP",
+ "toolbarTitle",
+ "barPlugins",
+ "barCommand",
+ "barSearch",
+ "barZoom",
+ "barMode",
+ "barExit",
+ ]);
+ const drag = getEntryCatalogNode("topBar.drag")!;
+ assert.equal(drag.fixed, true);
+ assert.equal(isEntryCatalogNodeConfigurable(drag), false);
+ assert.equal(getEntryPaths().includes("topBar.drag"), false);
+ assert.equal(getEntryOrderParents().includes(TOP_BAR_ROOT_PATH), true);
+ assert.equal(getEntryCatalogNode("topBar.barWorkspace"), undefined);
+ assert.equal(getEntryCatalogNode("topBar.barMore"), undefined);
+ assert.equal(getEntryCatalogNode("topBar.windowControls"), undefined);
+});
+
+test("top bar markup stays aligned with its configurable built-in catalog", () => {
+ const source = readFileSync(resolve(process.cwd(), "src/layout/topBar.ts"), "utf8");
+ const markupKeys = Array.from(source.matchAll(/data-topbar-entry="([^"]+)"/g), (match) => match[1]);
+ const catalogKeys = getEntryCatalogChildren(TOP_BAR_ROOT_PATH)
+ .filter(isEntryCatalogNodeConfigurable)
+ .map((item) => item.key);
+ assert.deepEqual(markupKeys, catalogKeys);
+ assert.match(source, /id="drag"/);
+ assert.doesNotMatch(source, /id="drag"[^>]*data-topbar-entry/);
+});
+
+test("top bar account entries use legacy account switches only as defaults", () => {
+ const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ siyuan: {
+ config: {
+ account: {
+ displayVIP: false,
+ displayTitle: true,
+ },
+ },
+ },
+ },
+ });
+ try {
+ assert.equal(getEntryCatalogDefaultVisibility("topBar.toolbarVIP"), false);
+ assert.equal(getEntryCatalogDefaultVisibility("topBar.toolbarTitle"), true);
+ assert.equal(getEntryCatalogDefaultVisibility("topBar.barSearch"), true);
+ assert.equal(getEntryCatalogDefaultVisibility("topBar.drag"), true);
+ } finally {
+ if (windowDescriptor) {
+ Object.defineProperty(globalThis, "window", windowDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, "window");
+ }
+ }
+});
+
+const topBarElement = (attributes: Record<string, string>) => ({
+ getAttribute: (name: string) => attributes[name] ?? null,
+}) as unknown as Element;
+
+test("top bar catalog inserts plugin entries on their declared side of the fixed boundary", () => {
+ const leftKey = getPluginTopBarEntryKey("plugin.one", "left.item");
+ const rightKey = getPluginTopBarEntryKey("plugin.two", "right.item");
+ const legacyKey = getLegacyPluginTopBarEntryKey("plugin.two", 1);
+ try {
+ refreshTopBarCatalog([{
+ name: "plugin.one",
+ displayName: "Plugin One",
+ topBarIcons: [topBarElement({
+ id: "plugin_one:left.item",
+ "data-id": "left.item",
+ "data-topbar-entry": leftKey,
+ "data-location": "left",
+ "aria-label": "Left Item",
+ })],
+ }, {
+ name: "plugin.two",
+ topBarIcons: [topBarElement({
+ id: "plugin_two:right.item",
+ "data-id": "right.item",
+ "data-topbar-entry": rightKey,
+ "data-location": "right",
+ "aria-label": "Right Item",
+ }), topBarElement({
+ id: "plugin_two_1",
+ "data-topbar-entry": legacyKey,
+ "data-location": "right",
+ "aria-label": "Legacy Item",
+ })],
+ }]);
+ const children = getEntryCatalogChildren(TOP_BAR_ROOT_PATH);
+ const keys = children.map((item) => item.key);
+ assert.deepEqual(keys.slice(0, 5), ["barSync", "barBack", "barForward", leftKey, "drag"]);
+ assert.deepEqual(keys.slice(keys.indexOf("toolbarTitle"), keys.indexOf("barCommand")), [
+ "toolbarTitle",
+ rightKey,
+ legacyKey,
+ "barPlugins",
+ ]);
+ assert.equal(getEntryCatalogNode(`${TOP_BAR_ROOT_PATH}.${leftKey}`)?.label(),
+ "Plugin One - Left Item");
+ assert.equal(getEntryCatalogNode(`${TOP_BAR_ROOT_PATH}.${rightKey}`)?.label(),
+ "plugin.two - Right Item");
+ assert.equal(getEntryParentPath(`${TOP_BAR_ROOT_PATH}.${legacyKey}`), TOP_BAR_ROOT_PATH);
+ } finally {
+ refreshTopBarCatalog([]);
+ }
+ assert.equal(getEntryCatalogNode(`${TOP_BAR_ROOT_PATH}.${leftKey}`), undefined);
+ assert.equal(getEntryCatalogNode(`${TOP_BAR_ROOT_PATH}.${rightKey}`), undefined);
+});
+
+test("top bar catalog keeps the assigned key when a legacy item changes array index", () => {
+ const key = getLegacyPluginTopBarEntryKey("plugin.name", 2);
+ try {
+ refreshTopBarCatalog([{
+ name: "plugin.name",
+ topBarIcons: [topBarElement({
+ id: "plugin_name_2",
+ "data-topbar-entry": key,
+ "data-location": "right",
+ "aria-label": "Legacy Item",
+ })],
+ }]);
+ assert.equal(getEntryCatalogNode(`${TOP_BAR_ROOT_PATH}.${key}`)?.key, key);
+ assert.equal(getEntryCatalogNode(`${TOP_BAR_ROOT_PATH}.${getLegacyPluginTopBarEntryKey("plugin.name", 0)}`),
+ undefined);
+ } finally {
+ refreshTopBarCatalog([]);
+ }
+});
+
+test("plugin top bar entries use the legacy unpinned list as their default visibility", () => {
+ const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const key = getPluginTopBarEntryKey("plugin.name", "item");
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ siyuan: {
+ storage: {
+ "local-plugintopunpin": ["plugin_name:item"],
+ },
+ },
+ },
+ });
+ try {
+ refreshTopBarCatalog([{
+ name: "plugin.name",
+ topBarIcons: [topBarElement({
+ id: "plugin_name:item",
+ "data-id": "item",
+ "data-location": "right",
+ "aria-label": "Item",
+ })],
+ }]);
+ assert.equal(getEntryCatalogDefaultVisibility(`${TOP_BAR_ROOT_PATH}.${key}`), false);
+ window.siyuan.storage["local-plugintopunpin"] = [];
+ assert.equal(getEntryCatalogDefaultVisibility(`${TOP_BAR_ROOT_PATH}.${key}`), true);
+ } finally {
+ refreshTopBarCatalog([]);
+ if (windowDescriptor) {
+ Object.defineProperty(globalThis, "window", windowDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, "window");
+ }
+ }
});
test("toolbar catalog follows the default toolbar declaration", () => {
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index f22fe68c65..1f7ea5149c 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -7,8 +7,14 @@ import {
} from "../../protyle/toolbar/defaults";
import {mergeEntryOrderPreservingUnknown} from "./order";
import {getPluginDockEntryKey} from "../../plugin/dockKey";
+import {
+ getLegacyPluginTopBarEntryKey,
+ getPluginTopBarEntryKey,
+ isPluginTopBarEntryKey,
+} from "../../plugin/topBarKey";
export {getPluginDockEntryKey} from "../../plugin/dockKey";
+export {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "../../plugin/topBarKey";
export interface IEntryCatalogNode {
key: string;
@@ -17,6 +23,8 @@ export interface IEntryCatalogNode {
type: "entry" | "separator";
displayChildrenDirectly?: boolean;
sortable?: boolean;
+ fixed?: boolean;
+ defaultVisible?: () => boolean;
children?: IEntryCatalogNode[];
}
@@ -31,13 +39,14 @@ const lang = (key: string) => () => window.siyuan.languages[key] || key;
const literal = (value: string) => () => value;
const location = (...labels: Array<() => string>) => () => labels.map((label) => label()).join(" - ");
const node = (key: string, label: () => string, simple = true, children?: IEntryCatalogNode[],
- sortable?: boolean): IEntryCatalogNode => ({
+ sortable?: boolean, options?: Pick<IEntryCatalogNode, "defaultVisible" | "fixed">): IEntryCatalogNode => ({
key,
label,
simple,
type: "entry",
children,
sortable,
+ ...options,
});
const separator = (key: string): IEntryCatalogNode => ({
key,
@@ -45,6 +54,8 @@ const separator = (key: string): IEntryCatalogNode => ({
simple: true,
type: "separator",
});
+const fixed = (key: string, label: () => string): IEntryCatalogNode =>
+ node(key, label, true, undefined, undefined, {fixed: true});
const codeTabSpacesChildren = () => [
node("default", () => `${window.siyuan.languages.default} (${window.siyuan.config.editor.codeTabSpaces})`),
@@ -534,6 +545,33 @@ const toolbarCatalogSection: IEntryCatalogSection = {
children: toolbarBuiltinChildren,
};
+export const TOP_BAR_ROOT_PATH = "topBar";
+
+const topBarBuiltinChildren = [
+ node("barSync", lang("syncNow")),
+ node("barBack", lang("goBack")),
+ node("barForward", lang("goForward")),
+ fixed("drag", lang("entryTopBarDrag")),
+ node("toolbarVIP", lang("accountDisplayVIP"), true, undefined, undefined, {
+ defaultVisible: () => window.siyuan.config.account.displayVIP,
+ }),
+ node("toolbarTitle", lang("accountDisplayTitle"), true, undefined, undefined, {
+ defaultVisible: () => window.siyuan.config.account.displayTitle,
+ }),
+ node("barPlugins", lang("plugin")),
+ node("barCommand", lang("commandPanel")),
+ node("barSearch", lang("globalSearch")),
+ node("barZoom", lang("zoom")),
+ node("barMode", lang("appearanceMode")),
+ node("barExit", lang("safeQuit")),
+];
+
+const topBarCatalogSection: IEntryCatalogSection = {
+ key: TOP_BAR_ROOT_PATH,
+ label: lang("entryTopBar"),
+ children: topBarBuiltinChildren,
+};
+
const dockBuiltinChildren = [
node("file", lang("fileTree")),
node("outline", lang("outline")),
@@ -554,6 +592,7 @@ const dockCatalogSection: IEntryCatalogSection = {
};
export const entryCatalog: IEntryCatalogSection[] = [
+ topBarCatalogSection,
dockCatalogSection,
{
key: "docTree.panel",
@@ -951,7 +990,12 @@ rebuildCatalogIndexes();
export const getEntryCatalogNode = (path: string) => entryMap.get(path);
export const getEntryParentPath = (path: string) => parentMap.get(path);
-export const getEntryPaths = () => Array.from(entryMap.keys());
+export const isEntryCatalogNodeConfigurable = (item: IEntryCatalogNode) => item.fixed !== true;
+export const getEntryCatalogDefaultVisibility = (path: string) =>
+ getEntryCatalogNode(path)?.defaultVisible?.() ?? true;
+export const getEntryPaths = () => Array.from(entryMap.entries())
+ .filter(([, item]) => isEntryCatalogNodeConfigurable(item))
+ .map(([path]) => path);
export const getEntryCatalogSection = (key: string) => sectionMap.get(key);
export const getEntryCatalogChildren = (path: string) => childrenMap.get(path);
export const isEntryOrderSortable = (parentPath: string) => {
@@ -977,6 +1021,75 @@ export const getEntryCatalogPathChain = (sectionKey: string, path: string) => {
return current === sectionKey ? chain : [];
};
+export interface ITopBarCatalogPlugin {
+ name: string;
+ displayName?: string;
+ topBarIcons: Element[];
+}
+
+let topBarCatalogSignature = "[]";
+
+export const refreshTopBarCatalog = (plugins: ITopBarCatalogPlugin[]) => {
+ const signature = JSON.stringify(plugins.map((plugin) => ({
+ name: plugin.name,
+ displayName: plugin.displayName,
+ items: plugin.topBarIcons.map((item) => ({
+ id: item.getAttribute("data-id"),
+ elementID: item.getAttribute("id"),
+ entryKey: item.getAttribute("data-topbar-entry"),
+ location: item.getAttribute("data-location"),
+ title: item.getAttribute("aria-label"),
+ })),
+ })));
+ if (signature === topBarCatalogSignature) {
+ return;
+ }
+ const leftPluginNodes: IEntryCatalogNode[] = [];
+ const rightPluginNodes: IEntryCatalogNode[] = [];
+ const pluginKeys = new Set<string>();
+ plugins.forEach((plugin) => {
+ plugin.topBarIcons.forEach((item, index) => {
+ const id = item.getAttribute("data-id");
+ const elementKey = item.getAttribute("data-topbar-entry");
+ const key = isPluginTopBarEntryKey(elementKey)
+ ? elementKey
+ : id === null
+ ? getLegacyPluginTopBarEntryKey(plugin.name, index)
+ : getPluginTopBarEntryKey(plugin.name, id);
+ if (pluginKeys.has(key)) {
+ return;
+ }
+ pluginKeys.add(key);
+ const pluginName = plugin.displayName?.trim() || plugin.name;
+ const title = item.getAttribute("aria-label")?.trim() || id || item.getAttribute("id") || key;
+ const pluginNode = node(key, literal(`${pluginName} - ${title}`), true, undefined, undefined, {
+ defaultVisible: () => {
+ const elementID = item.getAttribute("id");
+ const unpinned = window.siyuan.storage?.["local-plugintopunpin"] as string[] | undefined;
+ return !elementID || !unpinned?.includes(elementID);
+ },
+ });
+ if (item.getAttribute("data-location") === "left") {
+ leftPluginNodes.push(pluginNode);
+ } else {
+ rightPluginNodes.push(pluginNode);
+ }
+ });
+ });
+ const dragIndex = topBarBuiltinChildren.findIndex((item) => item.key === "drag");
+ const pluginMenuIndex = topBarBuiltinChildren.findIndex((item) => item.key === "barPlugins");
+ topBarCatalogSection.children = [
+ ...topBarBuiltinChildren.slice(0, dragIndex),
+ ...leftPluginNodes,
+ topBarBuiltinChildren[dragIndex],
+ ...topBarBuiltinChildren.slice(dragIndex + 1, pluginMenuIndex),
+ ...rightPluginNodes,
+ ...topBarBuiltinChildren.slice(pluginMenuIndex),
+ ];
+ topBarCatalogSignature = signature;
+ rebuildCatalogIndexes();
+};
+
interface IDockCatalogPlugin {
name: string;
displayName?: string;
diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.ts
index ca6f61e377..4f5c9775a7 100644
--- a/app/src/config/entryVisibility/order.test.ts
+++ b/app/src/config/entryVisibility/order.test.ts
@@ -6,6 +6,7 @@ import {
moveEntryOrder,
reorderEntrySlots,
resolveEntryOrder,
+ resolveEntryOrderWithBoundaryDefaults,
} from "./order";
test("entry order keeps custom order and inserts new entries by their default neighbors", () => {
@@ -120,6 +121,53 @@ test("entry order preserves plugin registration slots", () => {
[{key: "b"}, {key: "plugin"}, {key: "separator"}, {key: "a"}]);
});
+test("top bar order can move entries across its fixed boundary while preserving an unavailable plugin slot", () => {
+ const defaultOrder = ["barSync", "barBack", "drag", "toolbarVIP", "barPlugins"];
+ const savedOrder = ["barBack", "plugin:missing:item", "drag", "barSync", "toolbarVIP", "barPlugins"];
+ assert.deepEqual(mergeEntryOrderPreservingUnknown(defaultOrder, savedOrder, [
+ "barBack",
+ "toolbarVIP",
+ "drag",
+ "barSync",
+ "barPlugins",
+ ]), [
+ "barBack",
+ "plugin:missing:item",
+ "toolbarVIP",
+ "drag",
+ "barSync",
+ "barPlugins",
+ ]);
+});
+
+test("new top bar entries use their default side while saved entries keep their user placement", () => {
+ const defaultOrder = ["leftBuiltin", "leftNew", "drag", "rightNew", "rightBuiltin"];
+ assert.deepEqual(resolveEntryOrderWithBoundaryDefaults(defaultOrder, [
+ "drag",
+ "leftBuiltin",
+ "rightBuiltin",
+ ], "drag", new Set()), [
+ "leftNew",
+ "drag",
+ "rightNew",
+ "leftBuiltin",
+ "rightBuiltin",
+ ]);
+ assert.deepEqual(resolveEntryOrderWithBoundaryDefaults(defaultOrder, [
+ "rightBuiltin",
+ "rightNew",
+ "drag",
+ "leftNew",
+ "leftBuiltin",
+ ], "drag", new Set()), [
+ "rightBuiltin",
+ "rightNew",
+ "drag",
+ "leftNew",
+ "leftBuiltin",
+ ]);
+});
+
test("tab menu ordering handles mutually exclusive and conditional entries", () => {
const order = [
"copy",
diff --git a/app/src/config/entryVisibility/order.ts b/app/src/config/entryVisibility/order.ts
index e10c6d943a..b56792bdd4 100644
--- a/app/src/config/entryVisibility/order.ts
+++ b/app/src/config/entryVisibility/order.ts
@@ -90,6 +90,34 @@ export const resolveEntryOrder = (defaultOrder: string[], savedOrder: string[] |
return isValidEntryOrder(merged, separatorKeys) ? merged : [...defaultOrder];
};
+export const resolveEntryOrderWithBoundaryDefaults = (
+ defaultOrder: string[],
+ savedOrder: string[] | undefined,
+ boundaryKey: string,
+ separatorKeys: Set<string>,
+) => {
+ const result = resolveEntryOrder(defaultOrder, savedOrder, separatorKeys);
+ const defaultBoundaryIndex = defaultOrder.indexOf(boundaryKey);
+ const boundaryIndex = result.indexOf(boundaryKey);
+ if (defaultBoundaryIndex < 0 || boundaryIndex < 0) {
+ return result;
+ }
+ const savedKeys = new Set(savedOrder || []);
+ const moveBefore = defaultOrder.slice(0, defaultBoundaryIndex).filter((key) =>
+ !savedKeys.has(key) && result.indexOf(key) > boundaryIndex);
+ const moveAfter = defaultOrder.slice(defaultBoundaryIndex + 1).filter((key) =>
+ !savedKeys.has(key) && result.indexOf(key) < boundaryIndex);
+ if (moveBefore.length === 0 && moveAfter.length === 0) {
+ return result;
+ }
+ const movedKeys = new Set([...moveBefore, ...moveAfter]);
+ const constrained = result.filter((key) => !movedKeys.has(key));
+ const constrainedBoundaryIndex = constrained.indexOf(boundaryKey);
+ constrained.splice(constrainedBoundaryIndex, 0, ...moveBefore);
+ constrained.splice(constrained.indexOf(boundaryKey) + 1, 0, ...moveAfter);
+ return isValidEntryOrder(constrained, separatorKeys) ? constrained : result;
+};
+
export const moveEntryOrder = (order: string[], sourceKey: string, targetKey: string, after: boolean,
separatorKeys: Set<string>) => {
if (sourceKey === targetKey || !order.includes(sourceKey) || !order.includes(targetKey)) {
diff --git a/app/src/config/entryVisibility/profile.test.ts b/app/src/config/entryVisibility/profile.test.ts
index 73e1305e4c..1ef96628f1 100644
--- a/app/src/config/entryVisibility/profile.test.ts
+++ b/app/src/config/entryVisibility/profile.test.ts
@@ -1,11 +1,20 @@
import * as assert from "node:assert/strict";
import test from "node:test";
import {
+ getBuiltinProfileEntryVisibility,
getProfileEntryVisibility,
isEntryVisibilityImportVersionSupported,
normalizeEntryVisibilityImportProfile,
} from "./profile";
+test("built-in profiles honor entry defaults", () => {
+ assert.equal(getBuiltinProfileEntryVisibility("full", false, true), true);
+ assert.equal(getBuiltinProfileEntryVisibility("full", true, false), false);
+ assert.equal(getBuiltinProfileEntryVisibility("simple", true, true), true);
+ assert.equal(getBuiltinProfileEntryVisibility("simple", false, true), false);
+ assert.equal(getBuiltinProfileEntryVisibility("simple", true, false), false);
+});
+
test("custom entry visibility preserves saved values", () => {
const profile = {entries: {visible: true, hidden: false}};
assert.equal(getProfileEntryVisibility(profile, "visible"), true);
@@ -17,6 +26,13 @@ test("custom entry visibility shows missing entries", () => {
assert.equal(getProfileEntryVisibility(undefined, "new-entry"), true);
});
+test("custom entry visibility uses a caller-provided default only when the entry is missing", () => {
+ const profile = {entries: {visible: true, hidden: false}};
+ assert.equal(getProfileEntryVisibility(profile, "missing", false), false);
+ assert.equal(getProfileEntryVisibility(profile, "visible", false), true);
+ assert.equal(getProfileEntryVisibility(profile, "hidden", true), false);
+});
+
test("entry visibility import supports versions 1 through 4", () => {
assert.equal(isEntryVisibilityImportVersionSupported(1, 4), true);
assert.equal(isEntryVisibilityImportVersionSupported(2, 4), true);
diff --git a/app/src/config/entryVisibility/profile.ts b/app/src/config/entryVisibility/profile.ts
index 365ce00b52..1885d04db4 100644
--- a/app/src/config/entryVisibility/profile.ts
+++ b/app/src/config/entryVisibility/profile.ts
@@ -1,6 +1,12 @@
export const getProfileEntryVisibility = (profile: Pick<Config.IEntryVisibilityProfile, "entries"> | undefined,
- path: string) =>
- typeof profile?.entries[path] === "boolean" ? profile.entries[path] : true;
+ path: string, defaultVisible = true) =>
+ typeof profile?.entries[path] === "boolean" ? profile.entries[path] : defaultVisible;
+
+export const getBuiltinProfileEntryVisibility = (
+ profile: "simple" | "full",
+ simple: boolean,
+ defaultVisible = true,
+) => defaultVisible && (profile === "full" || simple);
export type TEntryVisibilityImportProfile = {
name?: unknown;
diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.ts
index fcae10e28a..bcd1dc3df6 100644
--- a/app/src/config/entryVisibility/runtime.ts
+++ b/app/src/config/entryVisibility/runtime.ts
@@ -1,18 +1,28 @@
import {fetchPost} from "../../util/fetch";
import {Constants} from "../../constants";
import {
+ getEntryCatalogDefaultVisibility,
getEntryCatalogChildren,
getEntryCatalogNode,
getEntryOrderParents,
getEntryParentPath,
getEntryPaths,
+ isEntryCatalogNodeConfigurable,
+ refreshTopBarCatalog,
+ TOP_BAR_ROOT_PATH,
} from "./catalog";
-import {reorderEntrySlots, resolveEntryOrder} from "./order";
+import {
+ mergeEntryOrderPreservingUnknown,
+ reorderEntrySlots,
+ resolveEntryOrder,
+ resolveEntryOrderWithBoundaryDefaults,
+} from "./order";
import {getDocTreeEntryScope} from "./docTreeScope";
-import {getProfileEntryVisibility} from "./profile";
+import {getBuiltinProfileEntryVisibility, getProfileEntryVisibility} from "./profile";
import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
import {resolveToolbarItems} from "../../protyle/toolbar/entryVisibility";
import {syncDockBarVisibility} from "../../layout/dock/barVisibility";
+import {genUUID} from "../../util/genID";
export const ENTRY_VISIBILITY_VERSION = 4;
export const ENTRY_PROFILE_SIMPLE = "simple";
@@ -27,20 +37,25 @@ export const getActiveEntryProfile = () => {
};
const getTemplateVisibility = (path: string, template: TEntryVisibilityTemplate) =>
- template === ENTRY_PROFILE_FULL || getEntryCatalogNode(path)?.simple !== false;
+ getBuiltinProfileEntryVisibility(
+ template,
+ getEntryCatalogNode(path)?.simple !== false,
+ getEntryCatalogDefaultVisibility(path),
+ );
export const isEntryVisible = (path: string): boolean => {
/// #if MOBILE
return true;
/// #else
const config = getConfig();
+ const active = config.active;
let visible: boolean;
- if (config.active === ENTRY_PROFILE_FULL) {
- visible = true;
- } else if (config.active === ENTRY_PROFILE_SIMPLE) {
+ if (active === ENTRY_PROFILE_FULL) {
+ visible = getTemplateVisibility(path, ENTRY_PROFILE_FULL);
+ } else if (active === ENTRY_PROFILE_SIMPLE) {
visible = getTemplateVisibility(path, ENTRY_PROFILE_SIMPLE);
} else {
- visible = getProfileEntryVisibility(getActiveEntryProfile(), path);
+ visible = getProfileEntryVisibility(getActiveEntryProfile(), path, getEntryCatalogDefaultVisibility(path));
}
if (!visible) {
return false;
@@ -64,6 +79,9 @@ export const getEntryOrder = (parentPath: string, profile = getActiveEntryProfil
const nodes = getEntryCatalogChildren(parentPath) || [];
const defaultOrder = nodes.map((item) => item.key);
const separatorKeys = new Set(nodes.filter((item) => item.type === "separator").map((item) => item.key));
+ if (parentPath === TOP_BAR_ROOT_PATH) {
+ return resolveEntryOrderWithBoundaryDefaults(defaultOrder, profile?.orders?.[parentPath], "drag", separatorKeys);
+ }
return resolveEntryOrder(defaultOrder, profile?.orders?.[parentPath], separatorKeys);
};
@@ -76,6 +94,67 @@ export const createEntryOrderSnapshot = (current = false) => getEntryOrderParent
return orders;
}, {});
+const cloneEntryVisibilityConfig = () => JSON.parse(JSON.stringify(
+ window.siyuan.config.appearance.entryVisibility
+)) as Config.IEntryVisibility;
+
+const uniqueEntryProfileName = (name: string, profiles: Config.IEntryVisibilityProfile[]) => {
+ if (!profiles.some((item) => item.name === name)) {
+ return name;
+ }
+ let index = 2;
+ while (profiles.some((item) => item.name === `${name} (${index})`)) {
+ index++;
+ }
+ return `${name} (${index})`;
+};
+
+const getWritableEntryProfile = (config: Config.IEntryVisibility) => {
+ const activeProfile = config.profiles.find((item) => item.id === config.active);
+ if (activeProfile) {
+ return activeProfile;
+ }
+ const template = config.active === ENTRY_PROFILE_SIMPLE ? ENTRY_PROFILE_SIMPLE : ENTRY_PROFILE_FULL;
+ const profile: Config.IEntryVisibilityProfile = {
+ id: genUUID(),
+ name: uniqueEntryProfileName(window.siyuan.languages.entryCustomProfile, config.profiles),
+ entries: createEntryProfileSnapshot(template),
+ orders: createEntryOrderSnapshot(true),
+ };
+ config.profiles.push(profile);
+ config.active = profile.id;
+ return profile;
+};
+
+export const setEntryVisibilityValue = (path: string, visible: boolean) => {
+ const node = getEntryCatalogNode(path);
+ if (window.siyuan.config.readonly || !node || !isEntryCatalogNodeConfigurable(node)) {
+ return;
+ }
+ const config = cloneEntryVisibilityConfig();
+ const profile = getWritableEntryProfile(config);
+ profile.entries[path] = visible;
+ saveEntryVisibility(config);
+};
+
+export const setEntryOrderValue = (parentPath: string, order: string[]) => {
+ const nodes = getEntryCatalogChildren(parentPath);
+ if (window.siyuan.config.readonly || !nodes) {
+ return;
+ }
+ const config = cloneEntryVisibilityConfig();
+ const profile = getWritableEntryProfile(config);
+ const defaultOrder = nodes.map((item) => item.key);
+ const separatorKeys = new Set(nodes.filter((item) => item.type === "separator").map((item) => item.key));
+ profile.orders[parentPath] = mergeEntryOrderPreservingUnknown(
+ defaultOrder,
+ profile.orders[parentPath],
+ order,
+ separatorKeys,
+ );
+ saveEntryVisibility(config);
+};
+
let savePending: Config.IEntryVisibility | undefined;
let saveRunning = false;
@@ -274,10 +353,47 @@ export const applyToolbarEntryVisibility = (toolbarElement: HTMLElement) => {
/// #endif
};
+export const refreshTopBarEntryCatalog = () => {
+ /// #if !MOBILE
+ refreshTopBarCatalog(window.siyuan.ws?.app?.plugins || []);
+ /// #endif
+};
+
+export const applyTopBarEntryVisibility = () => {
+ /// #if !MOBILE
+ const toolbarElement = document.getElementById("toolbar");
+ const barMoreElement = document.getElementById("barMore");
+ const dragElement = document.getElementById("drag");
+ if (!toolbarElement || !barMoreElement || !dragElement) {
+ return;
+ }
+ refreshTopBarEntryCatalog();
+ const entryElements = Array.from(toolbarElement.querySelectorAll<HTMLElement>(
+ ":scope > [data-topbar-entry]"));
+ const elementByKey = new Map(entryElements.map((item) => [item.dataset.topbarEntry, item]));
+ getEntryOrder(TOP_BAR_ROOT_PATH).forEach((key) => {
+ const item = key === "drag" ? dragElement : elementByKey.get(key);
+ if (item) {
+ barMoreElement.before(item);
+ }
+ });
+ entryElements.forEach((item) => {
+ const key = item.dataset.topbarEntry;
+ const path = key ? `${TOP_BAR_ROOT_PATH}.${key}` : "";
+ if (path && getEntryCatalogNode(path) && !isEntryVisible(path)) {
+ item.setAttribute("data-entry-hidden", "true");
+ } else {
+ item.removeAttribute("data-entry-hidden");
+ }
+ });
+ /// #endif
+};
+
const applyEntryVisibilityLocal = (config: Config.IEntryVisibility) => {
window.siyuan.config.appearance.entryVisibility = config;
/// #if !MOBILE
window.siyuan.menus?.menu?.remove();
+ applyTopBarEntryVisibility();
applyDockEntryVisibility();
document.querySelectorAll<HTMLElement>(".protyle-toolbar").forEach(applyToolbarEntryVisibility);
window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));
diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.ts
index 77c0d39c54..0617d4bf54 100644
--- a/app/src/config/entryVisibility/ui.ts
+++ b/app/src/config/entryVisibility/ui.ts
@@ -5,13 +5,17 @@ import {genUUID} from "../../util/genID";
import {
entryCatalog,
getEntryCatalogChildren,
+ getEntryCatalogDefaultVisibility,
getEntryCatalogPathChain,
getEntryPaths,
IEntryCatalogNode,
IEntryCatalogSection,
+ isEntryCatalogNodeConfigurable,
isEntryOrderSortable,
refreshDockCatalog,
refreshSlashMenuCatalog,
+ refreshTopBarCatalog,
+ TOP_BAR_ROOT_PATH,
} from "./catalog";
import {
createEntryProfileSnapshot,
@@ -23,7 +27,12 @@ import {
saveEntryVisibility,
TEntryVisibilityTemplate,
} from "./runtime";
-import {mergeEntryOrderPreservingUnknown, moveEntryOrder, resolveEntryOrder} from "./order";
+import {
+ mergeEntryOrderPreservingUnknown,
+ moveEntryOrder,
+ resolveEntryOrder,
+ resolveEntryOrderWithBoundaryDefaults,
+} from "./order";
import {
getProfileEntryVisibility,
isEntryVisibilityImportVersionSupported,
@@ -187,8 +196,11 @@ const renderProfileCards = (root: HTMLElement) => {
const getProfileEntryOrder = (profile: Config.IEntryVisibilityProfile, parentPath: string,
nodes = getEntryCatalogChildren(parentPath) || []) => {
const defaultOrder = nodes.map((item) => item.key);
- return resolveEntryOrder(defaultOrder, profile.orders?.[parentPath],
- new Set(nodes.filter((item) => item.type === "separator").map((item) => item.key)));
+ const separatorKeys = new Set(nodes.filter((item) => item.type === "separator").map((item) => item.key));
+ if (parentPath === TOP_BAR_ROOT_PATH) {
+ return resolveEntryOrderWithBoundaryDefaults(defaultOrder, profile.orders?.[parentPath], "drag", separatorKeys);
+ }
+ return resolveEntryOrder(defaultOrder, profile.orders?.[parentPath], separatorKeys);
};
const orderEntryNodes = (profile: Config.IEntryVisibilityProfile, parentPath: string,
@@ -203,7 +215,8 @@ const renderEntrySwitch = (profile: Config.IEntryVisibilityProfile, path: string
const label = item.type === "separator" ? window.siyuan.languages.entrySeparator : item.label();
return `<input class="b3-switch" type="checkbox"
aria-label="${escapeAttr(label)}" data-entry-path="${escapeAttr(path)}"${readOnly ? ' data-entry-readonly aria-disabled="true"' : ""}
- ${!parentEnabled && !readOnly ? " disabled" : ""}${getProfileEntryVisibility(profile, path) ? " checked" : ""}>`;
+ ${!parentEnabled && !readOnly ? " disabled" : ""}${getProfileEntryVisibility(profile, path,
+ getEntryCatalogDefaultVisibility(path)) ? " checked" : ""}>`;
};
const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: string, prefix: string,
@@ -216,7 +229,8 @@ const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: strin
<div class="config-entry-visibility__column-list">
${nodes.map((item) => {
const path = `${prefix}.${item.key}`;
- const draggable = sortable && parentEnabled;
+ const configurable = isEntryCatalogNodeConfigurable(item);
+ const draggable = sortable && parentEnabled && configurable;
if (item.type === "separator") {
return `<div class="config-entry-visibility__row config-entry-visibility__row--separator${parentEnabled ? "" : " config-entry-visibility__row--disabled"}${readOnly ? " config-entry-visibility__row--readonly" : ""}"
data-entry-row data-entry-key="${escapeAttr(item.key)}" data-entry-parent="${escapeAttr(prefix)}">
@@ -229,15 +243,16 @@ const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: strin
const label = item.label();
const hasChildren = Boolean(item.children?.length);
const selected = selectedPaths[depth] === path;
- const rowTag = hasChildren ? "div" : "label";
- return `<${rowTag} class="config-entry-visibility__row config-entry-visibility__row--${hasChildren ? "navigable" : "toggleable"}${selected ? " config-entry-visibility__row--current" : ""}${parentEnabled ? "" : " config-entry-visibility__row--disabled"}${readOnly ? " config-entry-visibility__row--readonly" : ""}"
+ const rowTag = hasChildren || !configurable ? "div" : "label";
+ const rowType = hasChildren ? "navigable" : configurable ? "toggleable" : "fixed";
+ return `<${rowTag} class="config-entry-visibility__row config-entry-visibility__row--${rowType}${selected ? " config-entry-visibility__row--current" : ""}${parentEnabled ? "" : " config-entry-visibility__row--disabled"}${readOnly ? " config-entry-visibility__row--readonly" : ""}"
data-entry-row data-entry-key="${escapeAttr(item.key)}" data-entry-parent="${escapeAttr(prefix)}" data-entry-path-row="${escapeAttr(path)}"${hasChildren ? ` data-action="navigate-entry" data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}"` : ""}>
${draggable ? '<span class="config-entry-visibility__drag" draggable="true"><svg><use xlink:href="#iconDrag"></use></svg></span>' : ""}
${hasChildren ? `<button class="config-entry-visibility__navigate" data-action="navigate-entry"
data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}" title="${escapeAttr(label)}">
<span>${escapeHtml(label)}</span>
</button>` : `<span class="config-entry-visibility__label" title="${escapeAttr(label)}">${escapeHtml(label)}</span>`}
- ${renderEntrySwitch(profile, path, item, parentEnabled, readOnly)}
+ ${configurable ? renderEntrySwitch(profile, path, item, parentEnabled, readOnly) : ""}
${hasChildren ? `<button class="block__icon block__icon--show config-entry-visibility__arrow" data-action="navigate-entry"
data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}" aria-label="${escapeAttr(window.siyuan.languages.expand)}">
<svg><use xlink:href="#iconRight"></use></svg>
@@ -303,7 +318,8 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:
let prefix = directDisplayRoot ? directDisplayRootPath : section.key;
let title = directDisplayRoot?.label() || section.label();
let parentEnabled = directDisplayRoot
- ? getProfileEntryVisibility(profile, directDisplayRootPath)
+ ? getProfileEntryVisibility(profile, directDisplayRootPath,
+ getEntryCatalogDefaultVisibility(directDisplayRootPath))
: true;
let depth = 0;
while (nodes.length > 0) {
@@ -321,7 +337,8 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:
if (!selectedNode?.children?.length) {
break;
}
- parentEnabled = parentEnabled && getProfileEntryVisibility(profile, selectedPath);
+ parentEnabled = parentEnabled && getProfileEntryVisibility(profile, selectedPath,
+ getEntryCatalogDefaultVisibility(selectedPath));
nodes = selectedNode.children;
prefix = selectedPath;
title = selectedNode.label();
@@ -341,7 +358,7 @@ const getEntrySearchResults = (query: string) => {
const results: IEntrySearchResult[] = [];
const visit = (section: IEntryCatalogSection, prefix: string, nodes: IEntryCatalogNode[], labels: string[]) => {
nodes.forEach((item) => {
- if (item.type === "separator") {
+ if (item.type === "separator" || !isEntryCatalogNodeConfigurable(item)) {
return;
}
const path = `${prefix}.${item.key}`;
@@ -371,6 +388,7 @@ const getEntrySearchFilter = (query: string) => {
const openProfileEditor = (root: HTMLElement, profileID?: string) => {
const plugins = window.siyuan.ws?.app?.plugins || [];
+ refreshTopBarCatalog(plugins);
refreshDockCatalog(plugins);
refreshSlashMenuCatalog(plugins);
const builtin = profileID === ENTRY_PROFILE_SIMPLE || profileID === ENTRY_PROFILE_FULL;
diff --git a/app/src/config/tabs/accountUi.ts b/app/src/config/tabs/accountUi.ts
index 029bcce117..b84710e309 100644
--- a/app/src/config/tabs/accountUi.ts
+++ b/app/src/config/tabs/accountUi.ts
@@ -14,7 +14,7 @@ import {closePanel} from "../../mobile/util/closePanel";
/// #endif
import md5 from "blueimp-md5";
import type {SettingTabBuilder} from "../setting/builder";
-import {patchSyncConfig, refreshSyncCloudSpaceGroup, syncTabElement} from "./syncRuntime";
+import {refreshSyncCloudSpaceGroup, syncTabElement} from "./syncRuntime";
import {escapeAttr, escapeHtml} from "../../util/escape";
import {bindAccountAuthEnter, isAccountLoginDisabled} from "./accountAuth";
import {
@@ -73,16 +73,6 @@ export const registerAccountGroup = (tab: SettingTabBuilder) => {
html: genAccountPaymentHTML,
afterMount: bindAccountPaymentEvent,
});
- if (!isMobile()) {
- group.switch("account.displayVIP", {
- title: window.siyuan.languages.accountDisplayVIP,
- save: (value) => patchSyncConfig("account.displayVIP", value),
- });
- group.switch("account.displayTitle", {
- title: window.siyuan.languages.accountDisplayTitle,
- save: (value) => patchSyncConfig("account.displayTitle", value),
- });
- }
};
const genAccountMainHTML = () => {
@@ -551,11 +541,8 @@ const confirmDeactivateAccount = () => {
});
};
-export const updateAccountSwitchesVisibility = (accountSettingsRoot: Element) => {
- const user = window.siyuan.user;
- accountSettingsRoot.querySelector(`#${CSS.escape("account.displayTitle")}`)?.closest(".config-item")?.classList.toggle("fn__none", !user || user.userTitles.length === 0);
- accountSettingsRoot.querySelector(`#${CSS.escape("account.displayVIP")}`)?.closest(".config-item")?.classList.toggle("fn__none", !user);
- accountSettingsRoot.querySelector("#configAccountPayment")?.classList.toggle("fn__none", !user);
+export const updateAccountPanelVisibility = (accountSettingsRoot: Element) => {
+ accountSettingsRoot.querySelector("#configAccountPayment")?.classList.toggle("fn__none", !window.siyuan.user);
};
const renderAccount = (accountSettingsRoot: Element) => {
@@ -567,7 +554,7 @@ const renderAccount = (accountSettingsRoot: Element) => {
if (accountPaymentEl) {
accountPaymentEl.outerHTML = genAccountPaymentHTML();
}
- updateAccountSwitchesVisibility(accountSettingsRoot);
+ updateAccountPanelVisibility(accountSettingsRoot);
bindAccountMainEvent(accountSettingsRoot);
bindAccountPaymentEvent(accountSettingsRoot);
};
@@ -589,14 +576,20 @@ const genVIPIconHTML = (className = "") =>
const genToolbarItemHTML = (ariaLabel: string, svg: string) =>
`<div class="toolbar__item ariaLabel" aria-label="${ariaLabel}">${svg}</div>`;
+const setToolbarItems = (element: HTMLElement, parts: string[]) => {
+ element.innerHTML = parts.join("");
+ if (parts.length === 0) {
+ element.setAttribute("data-topbar-empty", "true");
+ } else {
+ element.removeAttribute("data-topbar-empty");
+ }
+};
+
export const onSetaccount = () => {
/// #if !MOBILE
const toolbarVIPEl = document.getElementById("toolbarVIP");
- if (!toolbarVIPEl) {
- return;
- }
- const parts: string[] = [];
- if (window.siyuan.config.account.displayVIP) {
+ if (toolbarVIPEl) {
+ const parts: string[] = [];
if (!window.siyuan.user) {
// 未登录
parts.push(genToolbarItemHTML(window.siyuan.languages.freeSub, genVIPIconHTML("ft__error")));
@@ -626,14 +619,19 @@ export const onSetaccount = () => {
parts.push(genToolbarItemHTML(window.siyuan.languages.onepay, genVIPIconHTML("ft__success")));
}
}
+ setToolbarItems(toolbarVIPEl, parts);
}
- if (window.siyuan.config.account.displayTitle && window.siyuan.user) {
- window.siyuan.user.userTitles.forEach(item => {
- parts.push(genToolbarItemHTML(`${item.name}:${item.desc}`, item.icon));
- });
+ const toolbarTitleEl = document.getElementById("toolbarTitle");
+ if (toolbarTitleEl) {
+ const parts: string[] = [];
+ if (window.siyuan.user) {
+ window.siyuan.user.userTitles.forEach(item => {
+ parts.push(genToolbarItemHTML(`${item.name}:${item.desc}`, item.icon));
+ });
+ }
+ setToolbarItems(toolbarTitleEl, parts);
}
-
- toolbarVIPEl.innerHTML = parts.join("");
+ window.dispatchEvent(new CustomEvent("siyuan-topbar-change"));
/// #endif
};
diff --git a/app/src/config/tabs/syncRuntime.ts b/app/src/config/tabs/syncRuntime.ts
index 8a4df25e90..e96bd791ad 100644
--- a/app/src/config/tabs/syncRuntime.ts
+++ b/app/src/config/tabs/syncRuntime.ts
@@ -1,9 +1,6 @@
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {processSync} from "../../dialog/processSystem";
-import {
- onSetaccount,
- updateAccountSwitchesVisibility,
-} from "./accountUi";
+import {updateAccountPanelVisibility} from "./accountUi";
import {
refreshLANSyncConfigItemVisibility,
refreshSyncModeRelatedItems,
@@ -24,7 +21,7 @@ export const clearSyncTabElement = (root?: HTMLElement) => {
export const mountSyncTabExtras = (root: HTMLElement) => {
syncTabElement = root;
refreshSyncTabPanels(root);
- updateAccountSwitchesVisibility(root);
+ updateAccountPanelVisibility(root);
};
export const refreshLANSyncStatus = (root: Element) => {
@@ -80,29 +77,6 @@ export const refreshSyncCloudSpaceGroup = (root: Element) => {
/** 账号同步 Tab:按控件 id 提交配置并更新本地运行时 */
export const patchSyncConfig = (controlId: string, value: unknown) => {
switch (controlId) {
- case "account.displayTitle": {
- const displayTitle = Boolean(value) as Config.IAccount["displayTitle"];
- fetchPost("/api/setting/setAccount", {
- ...window.siyuan.config.account,
- displayTitle,
- }, (response) => {
- window.siyuan.config.account = response.data;
- onSetaccount();
- });
- break;
- }
- case "account.displayVIP": {
- const displayVIP = Boolean(value) as Config.IAccount["displayVIP"];
- fetchPost("/api/setting/setAccount", {
- ...window.siyuan.config.account,
- displayVIP,
- }, (response) => {
- window.siyuan.config.account = response.data;
- onSetaccount();
- });
- break;
- }
-
case "sync.provider": {
const provider = value as Config.ISync["provider"];
fetchPost("/api/sync/setSyncProvider", {provider}, () => {
diff --git a/app/src/layout/topBar.ts b/app/src/layout/topBar.ts
index 0751330052..e86546ed16 100644
--- a/app/src/layout/topBar.ts
+++ b/app/src/layout/topBar.ts
@@ -25,6 +25,12 @@ import {setTabPosition} from "./tabUtil";
import {commandPanel} from "../boot/globalEvent/command/panel";
import {openTopBarMenu} from "../plugin/openTopBarMenu";
import {getWorkspaceName, setTitle} from "../util/processTitle";
+import {bindTopBarDrag} from "./topBarDrag";
+import {
+ applyTopBarEntryVisibility,
+ setEntryOrderValue,
+} from "../config/entryVisibility/runtime";
+import {TOP_BAR_ROOT_PATH} from "../config/entryVisibility/catalog";
const sendTrafficLightPosition = (zoom: number) => {
/// #if !BROWSER
@@ -72,39 +78,49 @@ export const initBar = (app: App) => {
<span class="toolbar__text">${getWorkspaceName()}</span>
<svg class="toolbar__svg"><use xlink:href="#iconDown"></use></svg>
</div>
-<div id="barSync" class="ariaLabel toolbar__item${window.siyuan.config.readonly ? " fn__none" : ""}">
+<div id="barSync" data-topbar-entry="barSync" class="ariaLabel toolbar__item${window.siyuan.config.readonly ? " fn__none" : ""}">
<svg><use xlink:href="#iconCloudSucc"></use></svg>
</div>
-<button id="barBack" class="ariaLabel toolbar__item toolbar__item--disabled" aria-label="${window.siyuan.languages.goBack} ${updateHotkeyTip(window.siyuan.config.keymap.general.goBack.custom)}">
+<button id="barBack" data-topbar-entry="barBack" class="ariaLabel toolbar__item toolbar__item--disabled" aria-label="${window.siyuan.languages.goBack} ${updateHotkeyTip(window.siyuan.config.keymap.general.goBack.custom)}">
<svg><use xlink:href="#iconBack"></use></svg>
</button>
-<button id="barForward" class="ariaLabel toolbar__item toolbar__item--disabled" aria-label="${window.siyuan.languages.goForward} ${updateHotkeyTip(window.siyuan.config.keymap.general.goForward.custom)}">
+<button id="barForward" data-topbar-entry="barForward" class="ariaLabel toolbar__item toolbar__item--disabled" aria-label="${window.siyuan.languages.goForward} ${updateHotkeyTip(window.siyuan.config.keymap.general.goForward.custom)}">
<svg><use xlink:href="#iconForward"></use></svg>
</button>
<div class="fn__flex-1 fn__ellipsis" id="drag"><span class="fn__none">开发版,使用前请进行备份 Development version, please backup before use</span></div>
-<div id="toolbarVIP" class="fn__flex${window.siyuan.config.readonly ? " fn__none" : ""}"></div>
-<div id="barPlugins" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.plugin}">
+<div id="toolbarVIP" data-topbar-entry="toolbarVIP" class="fn__flex${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.accountDisplayVIP}"></div>
+<div id="toolbarTitle" data-topbar-entry="toolbarTitle" class="fn__flex${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.accountDisplayTitle}"></div>
+<div id="barPlugins" data-topbar-entry="barPlugins" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.plugin}">
<svg><use xlink:href="#iconPlugin"></use></svg>
</div>
-<div id="barCommand" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.commandPanel} ${updateHotkeyTip(window.siyuan.config.keymap.general.commandPanel.custom)}">
+<div id="barCommand" data-topbar-entry="barCommand" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.commandPanel} ${updateHotkeyTip(window.siyuan.config.keymap.general.commandPanel.custom)}">
<svg><use xlink:href="#iconTerminal"></use></svg>
</div>
-<div id="barSearch" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.globalSearch} ${updateHotkeyTip(window.siyuan.config.keymap.general.globalSearch.custom)}">
+<div id="barSearch" data-topbar-entry="barSearch" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.globalSearch} ${updateHotkeyTip(window.siyuan.config.keymap.general.globalSearch.custom)}">
<svg><use xlink:href="#iconSearch"></use></svg>
</div>
-<div id="barZoom" class="toolbar__item ariaLabel${(window.siyuan.storage[Constants.LOCAL_ZOOM] === 1 || isBrowser()) ? " fn__none" : ""}" aria-label="${window.siyuan.languages.zoom}">
+<div id="barZoom" data-topbar-entry="barZoom" class="toolbar__item ariaLabel${(window.siyuan.storage[Constants.LOCAL_ZOOM] === 1 || isBrowser()) ? " fn__none" : ""}" aria-label="${window.siyuan.languages.zoom}">
<svg><use xlink:href="#iconZoom${window.siyuan.storage[Constants.LOCAL_ZOOM] > 1 ? "In" : "Out"}"></use></svg>
</div>
-<div id="barMode" class="toolbar__item ariaLabel${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.appearanceMode}">
+<div id="barMode" data-topbar-entry="barMode" class="toolbar__item ariaLabel${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.appearanceMode}">
<svg><use xlink:href="#icon${window.siyuan.config.appearance.modeOS ? "Mode" : (window.siyuan.config.appearance.mode === 0 ? "Light" : "Dark")}"></use></svg>
</div>
-<div id="barExit" class="ft__error toolbar__item ariaLabel${isInMobileApp() ? "" : " fn__none"}" aria-label="${window.siyuan.languages.safeQuit}">
+<div id="barExit" data-topbar-entry="barExit" class="ft__error toolbar__item ariaLabel${isInMobileApp() ? "" : " fn__none"}" aria-label="${window.siyuan.languages.safeQuit}">
<svg><use xlink:href="#iconQuit"></use></svg>
</div>
<div id="barMore" class="toolbar__item ariaLabel" aria-label="${window.siyuan.languages.more}">
<svg><use xlink:href="#iconMore"></use></svg>
</div>
<div class="fn__flex" id="windowControls"></div>`;
+ applyTopBarEntryVisibility();
+ bindTopBarDrag(toolbarElement, (order) => setEntryOrderValue(TOP_BAR_ROOT_PATH, order));
+ const updateTopBarLayout = () => {
+ applyTopBarEntryVisibility();
+ resizeTopBar();
+ setTabPosition(true);
+ };
+ window.addEventListener("siyuan-entry-visibility", updateTopBarLayout);
+ window.addEventListener("siyuan-topbar-change", updateTopBarLayout);
processSync();
toolbarElement.addEventListener("click", (event: MouseEvent) => {
let target = event.target as HTMLElement;
@@ -133,8 +149,9 @@ export const initBar = (app: App) => {
const hideElement = document.getElementById(itemId);
const useElement = hideElement.querySelector("use");
const menuOptions: IMenu = {
- label: itemId === "toolbarVIP" ? window.siyuan.languages.account : hideElement.getAttribute("aria-label"),
- icon: itemId === "toolbarVIP" ? "iconAccount" : (useElement ? useElement.getAttribute("xlink:href").substring(1) : undefined),
+ label: hideElement.getAttribute("aria-label"),
+ icon: itemId === "toolbarVIP" || itemId === "toolbarTitle" ? "iconAccount" :
+ (useElement ? useElement.getAttribute("xlink:href").substring(1) : undefined),
click: () => {
if (itemId.startsWith("plugin")) {
hideElement.dispatchEvent(new CustomEvent("click"));
@@ -215,7 +232,7 @@ export const initBar = (app: App) => {
window.siyuan.menus.menu.popup({x: rect.right, y: rect.bottom, isLeft: true});
event.stopPropagation();
break;
- } else if (targetId === "toolbarVIP") {
+ } else if (targetId === "toolbarVIP" || targetId === "toolbarTitle") {
if (!window.siyuan.config.readonly) {
openSetting(app, "sync");
}
diff --git a/app/src/layout/topBarDrag.test.ts b/app/src/layout/topBarDrag.test.ts
new file mode 100644
index 0000000000..ddf9c1e9d0
--- /dev/null
+++ b/app/src/layout/topBarDrag.test.ts
@@ -0,0 +1,317 @@
+import {after, before, describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+
+let topBarDrag: typeof import("./topBarDrag");
+const originalVersion = Object.getOwnPropertyDescriptor(globalThis, "SIYUAN_VERSION");
+const originalNodeEnv = Object.getOwnPropertyDescriptor(globalThis, "NODE_ENV");
+
+before(async () => {
+ Object.defineProperty(globalThis, "SIYUAN_VERSION", {configurable: true, value: "test"});
+ Object.defineProperty(globalThis, "NODE_ENV", {configurable: true, value: "test"});
+ topBarDrag = await import("./topBarDrag");
+});
+
+after(() => {
+ if (originalVersion) {
+ Object.defineProperty(globalThis, "SIYUAN_VERSION", originalVersion);
+ } else {
+ delete (globalThis as typeof globalThis & {SIYUAN_VERSION?: string}).SIYUAN_VERSION;
+ }
+ if (originalNodeEnv) {
+ Object.defineProperty(globalThis, "NODE_ENV", originalNodeEnv);
+ } else {
+ delete (globalThis as typeof globalThis & {NODE_ENV?: string}).NODE_ENV;
+ }
+});
+
+const createOrderElement = (id: string, key?: string) => ({
+ id,
+ getAttribute: (name: string) => name === "data-topbar-entry" && typeof key === "string" ? key : null,
+});
+
+class TestEvent {
+ public defaultPrevented = false;
+ public immediatePropagationStopped = false;
+ public propagationStopped = false;
+
+ constructor(public target: TestElement, public clientX: number, public clientY: number, public button = 0) {
+ }
+
+ public preventDefault() {
+ this.defaultPrevented = true;
+ }
+
+ public stopImmediatePropagation() {
+ this.immediatePropagationStopped = true;
+ }
+
+ public stopPropagation() {
+ this.propagationStopped = true;
+ }
+}
+
+class TestEventTarget {
+ private listeners = new Map<string, Set<(event: TestEvent) => void>>();
+
+ public addEventListener(type: string, listener: (event: TestEvent) => void) {
+ if (!this.listeners.has(type)) {
+ this.listeners.set(type, new Set());
+ }
+ this.listeners.get(type).add(listener);
+ }
+
+ public dispatch(type: string, event: TestEvent) {
+ this.listeners.get(type)?.forEach((listener) => listener(event));
+ }
+
+ public listenerCount(type: string) {
+ return this.listeners.get(type)?.size || 0;
+ }
+
+ public removeEventListener(type: string, listener: (event: TestEvent) => void) {
+ this.listeners.get(type)?.delete(listener);
+ }
+}
+
+class TestElement extends TestEventTarget {
+ public children: TestElement[] = [];
+ public className = "";
+ public parentElement: TestElement | null = null;
+ public style: Record<string, string> = {opacity: ""};
+ private attributes = new Map<string, string>();
+
+ constructor(public ownerDocument: TestDocument, public id = "", key?: string,
+ private rect = {left: 0, top: 0, width: 24, height: 24}) {
+ super();
+ if (typeof key === "string") {
+ this.attributes.set("data-topbar-entry", key);
+ }
+ }
+
+ public after(element: TestElement) {
+ this.insertRelative(element, 1);
+ }
+
+ public appendChild(element: TestElement) {
+ element.remove();
+ element.parentElement = this;
+ this.children.push(element);
+ return element;
+ }
+
+ public before(element: TestElement) {
+ this.insertRelative(element, 0);
+ }
+
+ public cloneNode() {
+ const clone = new TestElement(this.ownerDocument, this.id, undefined, this.rect);
+ this.attributes.forEach((value, key) => clone.attributes.set(key, value));
+ clone.className = this.className;
+ clone.style = {...this.style};
+ return clone;
+ }
+
+ public getAttribute(name: string) {
+ if (name === "id") {
+ return this.id || null;
+ }
+ return this.attributes.get(name) ?? null;
+ }
+
+ public getBoundingClientRect() {
+ return this.rect;
+ }
+
+ public hasAttribute(name: string) {
+ return this.attributes.has(name);
+ }
+
+ public remove() {
+ if (!this.parentElement) {
+ return;
+ }
+ const index = this.parentElement.children.indexOf(this);
+ if (index > -1) {
+ this.parentElement.children.splice(index, 1);
+ }
+ this.parentElement = null;
+ }
+
+ public removeAttribute(name: string) {
+ if (name === "id") {
+ this.id = "";
+ } else {
+ this.attributes.delete(name);
+ }
+ }
+
+ public replaceWith(element: TestElement) {
+ const parentElement = this.parentElement;
+ if (!parentElement) {
+ return;
+ }
+ element.remove();
+ const index = parentElement.children.indexOf(this);
+ parentElement.children.splice(index, 1, element);
+ this.parentElement = null;
+ element.parentElement = parentElement;
+ }
+
+ public setAttribute(name: string, value: string) {
+ if (name === "id") {
+ this.id = value;
+ } else {
+ this.attributes.set(name, value);
+ }
+ }
+
+ private insertRelative(element: TestElement, offset: number) {
+ const parentElement = this.parentElement;
+ if (!parentElement) {
+ return;
+ }
+ element.remove();
+ const index = parentElement.children.indexOf(this);
+ element.parentElement = parentElement;
+ parentElement.children.splice(index + offset, 0, element);
+ }
+}
+
+class TestDocument extends TestEventTarget {
+ public body = new TestElement(this, "body");
+ public readonly = false;
+ private timerId = 0;
+ private timers = new Set<number>();
+ public defaultView = {
+ siyuan: {config: {readonly: false}},
+ clearTimeout: (id: number) => this.timers.delete(id),
+ setTimeout: () => {
+ this.timerId++;
+ this.timers.add(this.timerId);
+ return this.timerId;
+ },
+ };
+
+ public createElement() {
+ return new TestElement(this);
+ }
+}
+
+const createToolbar = () => {
+ const documentSelf = new TestDocument();
+ const toolbar = new TestElement(documentSelf, "toolbar");
+ const workspace = new TestElement(documentSelf, "barWorkspace", undefined, {left: 0, top: 0, width: 20, height: 24});
+ const left = new TestElement(documentSelf, "barBack", "back", {left: 20, top: 0, width: 24, height: 24});
+ const drag = new TestElement(documentSelf, "drag", undefined, {left: 44, top: 0, width: 100, height: 24});
+ const right = new TestElement(documentSelf, "barSearch", "search", {left: 144, top: 0, width: 24, height: 24});
+ const more = new TestElement(documentSelf, "barMore", undefined, {left: 168, top: 0, width: 24, height: 24});
+ const controls = new TestElement(documentSelf, "windowControls", undefined, {left: 192, top: 0, width: 80, height: 24});
+ [workspace, left, drag, right, more, controls].forEach((item) => toolbar.appendChild(item));
+ return {controls, documentSelf, drag, left, more, right, toolbar, workspace};
+};
+
+describe("top bar drag", () => {
+ it("reads only direct configurable entries and the fixed drag key", () => {
+ const toolbar = {
+ children: [
+ createOrderElement("barWorkspace"),
+ createOrderElement("barBack", "back"),
+ createOrderElement("drag"),
+ createOrderElement("barSearch", "search"),
+ createOrderElement("barMore"),
+ createOrderElement("windowControls"),
+ ],
+ } as unknown as HTMLElement;
+
+ assert.deepEqual(topBarDrag.getTopBarOrder(toolbar), ["back", "drag", "search"]);
+ });
+
+ it("keeps fixed edge targets on their respective side", () => {
+ const rect = {left: 100, width: 40} as DOMRect;
+
+ assert.equal(topBarDrag.resolveTopBarDropSide("barWorkspace", 1000, rect), "after");
+ assert.equal(topBarDrag.resolveTopBarDropSide("barMore", 0, rect), "before");
+ assert.equal(topBarDrag.resolveTopBarDropSide("windowControls", 110, rect), undefined);
+ });
+
+ it("uses the horizontal midpoint for entries and the fixed drag area", () => {
+ const rect = {left: 100, width: 40} as DOMRect;
+
+ assert.equal(topBarDrag.resolveTopBarDropSide("left", 119, rect), "before");
+ assert.equal(topBarDrag.resolveTopBarDropSide("left", 120, rect), "after");
+ assert.equal(topBarDrag.resolveTopBarDropSide("drag", 101, rect), "before");
+ assert.equal(topBarDrag.resolveTopBarDropSide("drag", 139, rect), "after");
+ });
+
+ it("recognizes self and adjacent insertions as no-ops", () => {
+ assert.equal(topBarDrag.isTopBarDropNoop(2, 2, "before"), true);
+ assert.equal(topBarDrag.isTopBarDropNoop(1, 2, "before"), true);
+ assert.equal(topBarDrag.isTopBarDropNoop(2, 1, "after"), true);
+ assert.equal(topBarDrag.isTopBarDropNoop(0, 2, "before"), false);
+ assert.equal(topBarDrag.isTopBarDropNoop(2, 0, "after"), false);
+ });
+
+ it("moves an entry across drag, cleans up, and suppresses the generated click", () => {
+ const {documentSelf, drag, left, toolbar} = createToolbar();
+ const orders: string[][] = [];
+ const unbind = topBarDrag.bindTopBarDrag(
+ toolbar as unknown as HTMLElement,
+ (order) => orders.push(order),
+ );
+
+ toolbar.dispatch("mousedown", new TestEvent(left, 30, 12));
+ assert.equal(drag.getAttribute("data-topbar-reordering"), "true");
+ documentSelf.dispatch("mousemove", new TestEvent(drag, 120, 12));
+ assert.equal(documentSelf.body.children.length, 1);
+ assert.equal(left.style.opacity, "0.38");
+ documentSelf.dispatch("mouseup", new TestEvent(drag, 120, 12));
+
+ assert.deepEqual(topBarDrag.getTopBarOrder(toolbar as unknown as HTMLElement), ["drag", "back", "search"]);
+ assert.deepEqual(orders, [["drag", "back", "search"]]);
+ assert.equal(documentSelf.body.children.length, 0);
+ assert.equal(documentSelf.listenerCount("mousemove"), 0);
+ assert.equal(documentSelf.listenerCount("mouseup"), 0);
+ assert.equal(documentSelf.listenerCount("dragstart"), 0);
+ assert.equal(left.style.opacity, "");
+ assert.equal(drag.getAttribute("data-topbar-reordering"), null);
+
+ const generatedClick = new TestEvent(left, 120, 12);
+ toolbar.dispatch("click", generatedClick);
+ assert.equal(generatedClick.defaultPrevented, true);
+ assert.equal(generatedClick.immediatePropagationStopped, true);
+ const nextClick = new TestEvent(left, 120, 12);
+ toolbar.dispatch("click", nextClick);
+ assert.equal(nextClick.defaultPrevented, false);
+
+ unbind();
+ assert.equal(toolbar.listenerCount("mousedown"), 0);
+ assert.equal(toolbar.listenerCount("click"), 0);
+ });
+
+ it("ignores non-primary, readonly, and below-threshold mouse movement", () => {
+ const {documentSelf, drag, left, toolbar} = createToolbar();
+ let changeCount = 0;
+ const unbind = topBarDrag.bindTopBarDrag(toolbar as unknown as HTMLElement, () => {
+ changeCount++;
+ });
+
+ toolbar.dispatch("mousedown", new TestEvent(left, 30, 12, 2));
+ assert.equal(documentSelf.listenerCount("mousemove"), 0);
+ documentSelf.defaultView.siyuan.config.readonly = true;
+ toolbar.dispatch("mousedown", new TestEvent(left, 30, 12));
+ assert.equal(documentSelf.listenerCount("mousemove"), 0);
+
+ documentSelf.defaultView.siyuan.config.readonly = false;
+ toolbar.dispatch("mousedown", new TestEvent(left, 30, 12));
+ documentSelf.dispatch("mousemove", new TestEvent(drag, 34, 16));
+ documentSelf.dispatch("mouseup", new TestEvent(drag, 34, 16));
+ assert.equal(drag.getAttribute("data-topbar-reordering"), null);
+ const click = new TestEvent(left, 34, 16);
+ toolbar.dispatch("click", click);
+
+ assert.equal(changeCount, 0);
+ assert.equal(click.defaultPrevented, false);
+ assert.deepEqual(topBarDrag.getTopBarOrder(toolbar as unknown as HTMLElement), ["back", "drag", "search"]);
+ unbind();
+ });
+});
diff --git a/app/src/layout/topBarDrag.ts b/app/src/layout/topBarDrag.ts
new file mode 100644
index 0000000000..5c9ce4e7ad
--- /dev/null
+++ b/app/src/layout/topBarDrag.ts
@@ -0,0 +1,261 @@
+import {Constants} from "../constants";
+
+export type TTopBarDropSide = "before" | "after";
+
+const TOP_BAR_WORKSPACE_ID = "barWorkspace";
+const TOP_BAR_DRAG_ID = "drag";
+const TOP_BAR_MORE_ID = "barMore";
+const TOP_BAR_WINDOW_CONTROLS_ID = "windowControls";
+
+export const getTopBarOrder = (toolbarElement: HTMLElement) => {
+ const order: string[] = [];
+ Array.from(toolbarElement.children).forEach((item: HTMLElement) => {
+ if (item.id === TOP_BAR_DRAG_ID) {
+ order.push(TOP_BAR_DRAG_ID);
+ return;
+ }
+ const key = item.getAttribute("data-topbar-entry");
+ if (key !== null) {
+ order.push(key);
+ }
+ });
+ return order;
+};
+
+export const resolveTopBarDropSide = (
+ targetId: string,
+ clientX: number,
+ rect: Pick<DOMRect, "left" | "width">,
+): TTopBarDropSide | undefined => {
+ if (targetId === TOP_BAR_WINDOW_CONTROLS_ID) {
+ return;
+ }
+ if (targetId === TOP_BAR_WORKSPACE_ID) {
+ return "after";
+ }
+ if (targetId === TOP_BAR_MORE_ID) {
+ return "before";
+ }
+ return clientX < rect.left + rect.width / 2 ? "before" : "after";
+};
+
+export const isTopBarDropNoop = (
+ sourceIndex: number,
+ targetIndex: number,
+ side: TTopBarDropSide,
+) => sourceIndex === targetIndex ||
+ (side === "before" && sourceIndex + 1 === targetIndex) ||
+ (side === "after" && targetIndex + 1 === sourceIndex);
+
+const getDirectChild = (toolbarElement: HTMLElement, target: EventTarget | null) => {
+ if (!target || typeof target !== "object" || !("parentElement" in target)) {
+ return;
+ }
+ let element = target as Element;
+ while (element && element.parentElement !== toolbarElement) {
+ if (element === toolbarElement) {
+ return;
+ }
+ element = element.parentElement;
+ }
+ return element as HTMLElement | undefined;
+};
+
+const isDraggableEntry = (element?: HTMLElement) => element &&
+ element.parentElement &&
+ element.hasAttribute("data-topbar-entry") &&
+ element.id !== TOP_BAR_WORKSPACE_ID &&
+ element.id !== TOP_BAR_MORE_ID &&
+ element.id !== TOP_BAR_DRAG_ID &&
+ element.id !== TOP_BAR_WINDOW_CONTROLS_ID;
+
+const isDropTarget = (element?: HTMLElement) => element &&
+ (element.hasAttribute("data-topbar-entry") ||
+ element.id === TOP_BAR_WORKSPACE_ID ||
+ element.id === TOP_BAR_DRAG_ID ||
+ element.id === TOP_BAR_MORE_ID) &&
+ element.id !== TOP_BAR_WINDOW_CONTROLS_ID;
+
+export const bindTopBarDrag = (
+ toolbarElement: HTMLElement,
+ onOrderChange: (order: string[]) => void,
+) => {
+ const documentSelf = toolbarElement.ownerDocument;
+ const view = documentSelf.defaultView || window;
+ let cancelCurrentDrag: (() => void) | undefined;
+ let suppressClick = false;
+ let suppressClickTimer: number | undefined;
+
+ const clearClickSuppression = () => {
+ suppressClick = false;
+ if (typeof suppressClickTimer === "number") {
+ view.clearTimeout(suppressClickTimer);
+ suppressClickTimer = undefined;
+ }
+ };
+
+ const suppressNextClick = () => {
+ clearClickSuppression();
+ suppressClick = true;
+ suppressClickTimer = view.setTimeout(() => {
+ suppressClick = false;
+ suppressClickTimer = undefined;
+ });
+ };
+
+ const onClick = (event: MouseEvent) => {
+ if (!suppressClick) {
+ return;
+ }
+ clearClickSuppression();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ };
+
+ const onMouseDown = (event: MouseEvent) => {
+ if (event.button !== 0 || cancelCurrentDrag || view.siyuan.config.readonly) {
+ return;
+ }
+ const sourceElement = getDirectChild(toolbarElement, event.target);
+ if (!isDraggableEntry(sourceElement)) {
+ return;
+ }
+ const dragElement = Array.from(toolbarElement.children).find((item) => item.id === TOP_BAR_DRAG_ID);
+ dragElement?.setAttribute("data-topbar-reordering", "true");
+
+ const startX = event.clientX;
+ const startY = event.clientY;
+ const sourceRect = sourceElement.getBoundingClientRect();
+ const offsetX = startX - sourceRect.left;
+ const offsetY = startY - sourceRect.top;
+ const sourceOpacity = sourceElement.style.opacity;
+ let dragging = false;
+ let ghostElement: HTMLElement | undefined;
+ let placeholderElement: HTMLElement | undefined;
+
+ const preventNativeDrag = (dragEvent: DragEvent) => {
+ dragEvent.preventDefault();
+ };
+
+ const cleanup = () => {
+ documentSelf.removeEventListener("mousemove", onMouseMove);
+ documentSelf.removeEventListener("mouseup", onMouseUp);
+ documentSelf.removeEventListener("dragstart", preventNativeDrag);
+ sourceElement.style.opacity = sourceOpacity;
+ dragElement?.removeAttribute("data-topbar-reordering");
+ ghostElement?.remove();
+ placeholderElement?.remove();
+ if (cancelCurrentDrag === cleanup) {
+ cancelCurrentDrag = undefined;
+ }
+ };
+
+ const beginDrag = () => {
+ dragging = true;
+ sourceElement.style.opacity = "0.38";
+
+ ghostElement = sourceElement.cloneNode(true) as HTMLElement;
+ ghostElement.removeAttribute("id");
+ ghostElement.removeAttribute("data-topbar-entry");
+ ghostElement.removeAttribute("aria-label");
+ ghostElement.setAttribute("aria-hidden", "true");
+ ghostElement.setAttribute("data-topbar-drag-ghost", "true");
+ ghostElement.style.boxSizing = "border-box";
+ ghostElement.style.height = `${sourceRect.height}px`;
+ ghostElement.style.margin = "0";
+ ghostElement.style.pointerEvents = "none";
+ ghostElement.style.position = "fixed";
+ ghostElement.style.width = `${sourceRect.width}px`;
+ ghostElement.style.zIndex = "999997";
+ documentSelf.body.appendChild(ghostElement);
+
+ placeholderElement = documentSelf.createElement("span");
+ placeholderElement.className = "toolbar__item";
+ placeholderElement.setAttribute("aria-hidden", "true");
+ placeholderElement.setAttribute("data-topbar-drag-placeholder", "true");
+ placeholderElement.style.background = "var(--b3-theme-primary-light)";
+ placeholderElement.style.flex = `0 0 ${sourceRect.width}px`;
+ placeholderElement.style.height = `${sourceRect.height}px`;
+ placeholderElement.style.pointerEvents = "none";
+ placeholderElement.style.width = `${sourceRect.width}px`;
+ };
+
+ const onMouseMove = (moveEvent: MouseEvent) => {
+ if (!dragging) {
+ if (view.siyuan.config.readonly ||
+ Math.abs(moveEvent.clientX - startX) < Constants.SIZE_DRAG_THRESHOLD &&
+ Math.abs(moveEvent.clientY - startY) < Constants.SIZE_DRAG_THRESHOLD) {
+ return;
+ }
+ beginDrag();
+ }
+
+ moveEvent.preventDefault();
+ moveEvent.stopPropagation();
+ ghostElement.style.left = `${moveEvent.clientX - offsetX}px`;
+ ghostElement.style.top = `${moveEvent.clientY - offsetY}px`;
+
+ placeholderElement.remove();
+ const targetElement = getDirectChild(toolbarElement, moveEvent.target);
+ if (!isDropTarget(targetElement) || targetElement === sourceElement) {
+ return;
+ }
+ const side = resolveTopBarDropSide(
+ targetElement.id,
+ moveEvent.clientX,
+ targetElement.getBoundingClientRect(),
+ );
+ if (!side) {
+ return;
+ }
+ const children = Array.from(toolbarElement.children);
+ if (isTopBarDropNoop(
+ children.indexOf(sourceElement),
+ children.indexOf(targetElement),
+ side,
+ )) {
+ return;
+ }
+ if (side === "before") {
+ targetElement.before(placeholderElement);
+ } else {
+ targetElement.after(placeholderElement);
+ }
+ };
+
+ const onMouseUp = () => {
+ let changedOrder: string[] | undefined;
+ if (dragging && placeholderElement.parentElement === toolbarElement &&
+ sourceElement.parentElement === toolbarElement) {
+ const previousOrder = getTopBarOrder(toolbarElement);
+ placeholderElement.replaceWith(sourceElement);
+ const currentOrder = getTopBarOrder(toolbarElement);
+ if (previousOrder.some((item, index) => item !== currentOrder[index])) {
+ changedOrder = currentOrder;
+ }
+ }
+ cleanup();
+ if (dragging) {
+ suppressNextClick();
+ }
+ if (changedOrder) {
+ onOrderChange(changedOrder);
+ }
+ };
+
+ cancelCurrentDrag = cleanup;
+ documentSelf.addEventListener("mousemove", onMouseMove);
+ documentSelf.addEventListener("mouseup", onMouseUp);
+ documentSelf.addEventListener("dragstart", preventNativeDrag);
+ };
+
+ toolbarElement.addEventListener("mousedown", onMouseDown);
+ toolbarElement.addEventListener("click", onClick, true);
+
+ return () => {
+ cancelCurrentDrag?.();
+ clearClickSuppression();
+ toolbarElement.removeEventListener("mousedown", onMouseDown);
+ toolbarElement.removeEventListener("click", onClick, true);
+ };
+};
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index 4bc4fd481e..79cf0b4e28 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -825,33 +825,33 @@ export const resizeTopBar = () => {
item.removeAttribute("data-hide");
});
- let afterDragElement = dragElement.nextElementSibling;
+ let afterDragElement = dragElement.nextElementSibling as HTMLElement;
const hideIds: string[] = [];
- while (toolbarElement.scrollWidth > toolbarElement.clientWidth + 2) {
+ while (toolbarElement.scrollWidth > toolbarElement.clientWidth + 2 &&
+ afterDragElement && afterDragElement.id !== "barMore" && afterDragElement.id !== "windowControls") {
// 跳过默认即隐藏的元素(如桌面端 #barExit),它们本就不占溢出空间,
// 若为其打上 data-hide,最大化后恢复阶段会误将其显示出来
- if (!afterDragElement.classList.contains("fn__none")) {
+ if (!afterDragElement.classList.contains("fn__none") &&
+ afterDragElement.getAttribute("data-entry-hidden") !== "true" &&
+ afterDragElement.getAttribute("data-topbar-empty") !== "true") {
hideIds.push(afterDragElement.id);
afterDragElement.classList.add("fn__none");
afterDragElement.setAttribute("data-hide", "true");
}
- afterDragElement = afterDragElement.nextElementSibling;
- if (afterDragElement.id === "barMore") {
- break;
- }
+ afterDragElement = afterDragElement.nextElementSibling as HTMLElement;
}
- let beforeDragElement = dragElement.previousElementSibling;
- while (toolbarElement.scrollWidth > toolbarElement.clientWidth + 2) {
- if (!beforeDragElement.classList.contains("fn__none")) {
+ let beforeDragElement = dragElement.previousElementSibling as HTMLElement;
+ while (toolbarElement.scrollWidth > toolbarElement.clientWidth + 2 &&
+ beforeDragElement && beforeDragElement.id !== "barWorkspace") {
+ if (!beforeDragElement.classList.contains("fn__none") &&
+ beforeDragElement.getAttribute("data-entry-hidden") !== "true" &&
+ beforeDragElement.getAttribute("data-topbar-empty") !== "true") {
hideIds.push(beforeDragElement.id);
beforeDragElement.classList.add("fn__none");
beforeDragElement.setAttribute("data-hide", "true");
}
- beforeDragElement = beforeDragElement.previousElementSibling;
- if (beforeDragElement.id === "barWorkspace") {
- break;
- }
+ beforeDragElement = beforeDragElement.previousElementSibling as HTMLElement;
}
if (hideIds.length > 0) {
barMoreElement.classList.remove("fn__none");
@@ -872,9 +872,6 @@ export const resizeTopBar = () => {
}
}
- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].forEach((id: string) => {
- document.getElementById(id)?.classList.add("fn__none");
- });
};
// TODO: 需支持所有页签类型,避免其他类型页签没有使用到而加载
diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.ts
index 5722a3dfd5..e20f217495 100644
--- a/app/src/plugin/index.ts
+++ b/app/src/plugin/index.ts
@@ -38,6 +38,8 @@ import {
setPluginToolbarItem,
} from "./toolbarItem";
import {isBuiltinToolbarItemName} from "../protyle/toolbar/defaults";
+import {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "./topBarKey";
+import {applyTopBarEntryVisibility} from "../config/entryVisibility/runtime";
const disposedPlugins = new WeakSet<Plugin>();
@@ -247,12 +249,14 @@ export class Plugin {
if (typeof options.id === "string") {
iconElement.id = `plugin_${encodeURIComponent(this.name)}:${encodeURIComponent(options.id)}`;
iconElement.setAttribute("data-id", options.id);
+ iconElement.setAttribute("data-topbar-entry", getPluginTopBarEntryKey(this.name, options.id));
} else {
let index = this.topBarIcons.length;
do {
iconElement.id = `plugin_${this.name}_${index}`;
index++;
} while (this.topBarIcons.some(item => item.getAttribute("id") === iconElement.id));
+ iconElement.setAttribute("data-topbar-entry", getLegacyPluginTopBarEntryKey(this.name, index - 1));
}
}
const previousLocation = iconElement.getAttribute("data-location");
@@ -277,9 +281,6 @@ export class Plugin {
document.getElementById("menuPluginTopBar")?.after(iconElement);
}
} else if (!isWindow() && window.siyuan.storage) {
- if (window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].includes(iconElement.id)) {
- iconElement.classList.add("fn__none");
- }
if (!document.contains(iconElement) || previousLocation !== iconElement.getAttribute("data-location")) {
document.querySelector("#" + (iconElement.getAttribute("data-location") === "right" ? "barPlugins" : "drag"))?.before(iconElement);
}
@@ -289,6 +290,7 @@ export class Plugin {
}
/// #if !MOBILE
if (!isWindow()) {
+ applyTopBarEntryVisibility();
resizeTopBar();
setTabPosition(true);
}
@@ -308,6 +310,7 @@ export class Plugin {
this.topBarIcons.splice(index, 1);
/// #if !MOBILE
if (!isWindow()) {
+ applyTopBarEntryVisibility();
resizeTopBar();
setTabPosition(true);
}
diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.ts
index 142f7b9e48..b62f9b7adc 100644
--- a/app/src/plugin/loader.ts
+++ b/app/src/plugin/loader.ts
@@ -17,7 +17,11 @@ import {beginPluginTeardown, destroyPlugin} from "./uninstall";
import {setStorageVal} from "../protyle/util/compatibility";
import {getAllEditor} from "../layout/getAll";
import {getPluginDockEntryKey, refreshDockCatalog} from "../config/entryVisibility/catalog";
-import {applyDockEntryVisibility, isEntryVisible} from "../config/entryVisibility/runtime";
+import {
+ applyDockEntryVisibility,
+ applyTopBarEntryVisibility,
+ isEntryVisible,
+} from "../config/entryVisibility/runtime";
import {PluginLifecycleCoordinator} from "./lifecycle";
import {
activateCustomBlockPlugin,
@@ -224,9 +228,6 @@ const mountPlugin = (plugin: Plugin) => {
document.getElementById("menuPluginTopBar")?.after(element);
}
} else if (!isWindow()) {
- if (window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].includes(element.id)) {
- element.classList.add("fn__none");
- }
document.querySelector("#" + (element.getAttribute("data-location") === "right" ? "barPlugins" : "drag")).before(element);
}
});
@@ -243,6 +244,7 @@ const mountPlugin = (plugin: Plugin) => {
statusElement.insertAdjacentElement("afterbegin", element);
}
});
+ applyTopBarEntryVisibility();
resizeTopBar();
/// #endif
addPluginDock(plugin);
diff --git a/app/src/plugin/openTopBarMenu.ts b/app/src/plugin/openTopBarMenu.ts
index c5651f92be..4ed0e43ada 100644
--- a/app/src/plugin/openTopBarMenu.ts
+++ b/app/src/plugin/openTopBarMenu.ts
@@ -7,6 +7,9 @@ import {setTabPosition} from "../layout/tabUtil";
/// #endif
import {Constants} from "../constants";
import {hasPluginSetting} from "./index";
+import {isMobile} from "../util/functions";
+import {isEntryVisible, setEntryVisibilityValue} from "../config/entryVisibility/runtime";
+import {TOP_BAR_ROOT_PATH} from "../config/entryVisibility/catalog";
export const openTopBarMenu = (app: App, target?: Element) => {
const menu = new Menu(Constants.MENU_BAR_PLUGIN);
@@ -34,21 +37,33 @@ export const openTopBarMenu = (app: App, target?: Element) => {
i--;
continue;
}
- const hasUnpin = window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].includes(item.id);
- const submenu = [{
+ const entryKey = item.getAttribute("data-topbar-entry");
+ const entryPath = entryKey ? `${TOP_BAR_ROOT_PATH}.${entryKey}` : "";
+ const hasUnpin = isMobile() || !entryPath
+ ? window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].includes(item.id)
+ : !isEntryVisible(entryPath);
+ const submenu: IMenu[] = [{
id: hasUnpin ? "pin" : "unpin",
icon: hasUnpin ? "iconPin" : "iconUnpin",
label: hasUnpin ? window.siyuan.languages.pin : window.siyuan.languages.unpin,
+ disabled: !isMobile() && window.siyuan.config.readonly,
click() {
- if (hasUnpin) {
- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].splice(window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].indexOf(item.id), 1);
- item.classList.remove("fn__none");
+ if (!isMobile() && entryPath) {
+ setEntryVisibilityValue(entryPath, hasUnpin);
} else {
- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].push(item.id);
- window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN] = Array.from(new Set(window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]));
- item.classList.add("fn__none");
+ if (hasUnpin) {
+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].splice(
+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].indexOf(item.id), 1);
+ item.classList.remove("fn__none");
+ } else {
+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN].push(item.id);
+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN] = Array.from(new Set(
+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]));
+ item.classList.add("fn__none");
+ }
+ setStorageVal(Constants.LOCAL_PLUGINTOPUNPIN,
+ window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]);
}
- setStorageVal(Constants.LOCAL_PLUGINTOPUNPIN, window.siyuan.storage[Constants.LOCAL_PLUGINTOPUNPIN]);
/// #if !MOBILE
setTabPosition(true);
/// #endif
diff --git a/app/src/plugin/topBarKey.test.ts b/app/src/plugin/topBarKey.test.ts
new file mode 100644
index 0000000000..40498a4077
--- /dev/null
+++ b/app/src/plugin/topBarKey.test.ts
@@ -0,0 +1,32 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {
+ getLegacyPluginTopBarEntryKey,
+ getPluginTopBarEntryKey,
+ isPluginTopBarEntryKey,
+} from "./topBarKey";
+
+test("plugin top bar keys encode dotted names and IDs without ambiguity", () => {
+ const dottedPlugin = getPluginTopBarEntryKey("plugin.name", "entry");
+ const dottedEntry = getPluginTopBarEntryKey("plugin", "name.entry");
+ assert.equal(dottedPlugin, "plugin:plugin%2Ename:entry");
+ assert.equal(dottedEntry, "plugin:plugin:name%2Eentry");
+ assert.notEqual(dottedPlugin, dottedEntry);
+ assert.equal(dottedPlugin.includes("."), false);
+ assert.equal(dottedEntry.includes("."), false);
+});
+
+test("plugin top bar keys encode path and delimiter characters", () => {
+ const key = getPluginTopBarEntryKey("plugin/name:one", "entry/name:one");
+ assert.equal(key, "plugin:plugin%2Fname%3Aone:entry%2Fname%3Aone");
+ assert.equal(isPluginTopBarEntryKey(key), true);
+ assert.equal(isPluginTopBarEntryKey("plugin:plugin.name:entry"), true);
+ assert.equal(isPluginTopBarEntryKey("plugin:missing"), false);
+});
+
+test("legacy plugin top bar keys use a distinct best-effort index namespace", () => {
+ assert.equal(getLegacyPluginTopBarEntryKey("plugin.name", 2),
+ "plugin:plugin%2Ename:legacy-index%3A2");
+ assert.notEqual(getLegacyPluginTopBarEntryKey("plugin", 2),
+ getPluginTopBarEntryKey("plugin", "2"));
+});
diff --git a/app/src/plugin/topBarKey.ts b/app/src/plugin/topBarKey.ts
new file mode 100644
index 0000000000..0bb71c86dd
--- /dev/null
+++ b/app/src/plugin/topBarKey.ts
@@ -0,0 +1,12 @@
+export type PluginTopBarEntryKey = `plugin:${string}:${string}`;
+
+const encodeTopBarEntryKeyPart = (value: string) => encodeURIComponent(value).replace(/\./g, "%2E");
+
+export const getPluginTopBarEntryKey = (pluginName: string, topBarID: string): PluginTopBarEntryKey =>
+ `plugin:${encodeTopBarEntryKeyPart(pluginName)}:${encodeTopBarEntryKeyPart(topBarID)}`;
+
+export const getLegacyPluginTopBarEntryKey = (pluginName: string, index: number): PluginTopBarEntryKey =>
+ getPluginTopBarEntryKey(pluginName, `legacy-index:${index}`);
+
+export const isPluginTopBarEntryKey = (value: unknown): value is PluginTopBarEntryKey =>
+ typeof value === "string" && /^plugin:[^:]+:[^:]+$/.test(value);
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index 2eef46d5a0..0bf107b76c 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -20,6 +20,9 @@ import {destroyEventBus} from "./EventBusCore";
import {unregisterPluginCommands} from "./commandAdapter";
import {sendGlobalShortcut} from "../boot/globalEvent/globalShortcut";
import {releaseTrackedRangesByPlugin} from "../protyle/util/trackedRange";
+/// #if !MOBILE
+import {applyTopBarEntryVisibility} from "../config/entryVisibility/runtime";
+/// #endif
const runCleanup = (plugin: Plugin, step: string, callback: () => unknown) => {
try {
@@ -101,14 +104,17 @@ export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) =>
});
});
});
- runCleanup(plugin, "top bar layout", () => resizeTopBar());
- runCleanup(plugin, "tab layout", () => setTabPosition(true));
/// #endif
const index = app.plugins.indexOf(plugin);
if (index > -1) {
app.plugins.splice(index, 1);
}
runCleanup(plugin, "dock catalog", () => refreshDockCatalog(app.plugins));
+ /// #if !MOBILE
+ runCleanup(plugin, "top bar catalog", () => applyTopBarEntryVisibility());
+ runCleanup(plugin, "top bar layout", () => resizeTopBar());
+ runCleanup(plugin, "tab layout", () => setTabPosition(true));
+ /// #endif
/// #if MOBILE
// 移动端卸载插件后,若无任何插件停靠栏则隐藏插件入口图标。
runCleanup(plugin, "mobile plugin entry", () => {