Skip to content

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

:art: Simplify custom entry visibility profiles https://github.com/siyuan-note/siyuan/issues/18803

Daniel519c3c36797e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index e6a77e7f5c..e048342aeb 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -185,8 +185,6 @@
"entryBasedOn": "استنادًا إلى",
"entryCustomProfile": "ملف تعريف مخصص",
"entryCreateProfile": "إنشاء ملف تعريف",
- "entryRestoreBase": "استعادة إلى [${x}]",
- "entryRestoreBaseConfirm": "هل تريد استعادة جميع عناصر هذا الملف إلى [${x}]؟",
"entryImportInvalid": "ملف تعريف القوائم وشريط الإرساء غير صالح",
"mobileMenuQuickActions": "إجراءات سريعة",
"mobileMenuCreate": "إنشاء",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 7001e35862..2da23f7cf7 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Basierend auf",
"entryCustomProfile": "Benutzerdefiniertes Profil",
"entryCreateProfile": "Profil erstellen",
- "entryRestoreBase": "Auf [${x}] zurücksetzen",
- "entryRestoreBaseConfirm": "Alle Einträge dieses Profils auf [${x}] zurücksetzen?",
"entryImportInvalid": "Ungültige Menü- und Dock-Profildatei",
"mobileMenuQuickActions": "Schnellaktionen",
"mobileMenuCreate": "Erstellen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 784cc14bd4..3ba8983eb5 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Based on",
"entryCustomProfile": "Custom profile",
"entryCreateProfile": "Create profile",
- "entryRestoreBase": "Restore to [${x}]",
- "entryRestoreBaseConfirm": "Restore all entries in this profile to [${x}]?",
"entryImportInvalid": "Invalid menu and dock profile file",
"mobileMenuQuickActions": "Quick actions",
"mobileMenuCreate": "Create",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index abe5db1434..f5ad11d933 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Basado en",
"entryCustomProfile": "Perfil personalizado",
"entryCreateProfile": "Crear perfil",
- "entryRestoreBase": "Restaurar a [${x}]",
- "entryRestoreBaseConfirm": "¿Restaurar todas las entradas de este perfil a [${x}]?",
"entryImportInvalid": "El archivo de perfil de menús y panel acoplable no es válido",
"mobileMenuQuickActions": "Acciones rápidas",
"mobileMenuCreate": "Crear",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index e8e6d64177..3af17eb38e 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Basé sur",
"entryCustomProfile": "Profil personnalisé",
"entryCreateProfile": "Créer un profil",
- "entryRestoreBase": "Restaurer vers [${x}]",
- "entryRestoreBaseConfirm": "Restaurer toutes les entrées de ce profil vers [${x}] ?",
"entryImportInvalid": "Fichier de profil des menus et de la barre d'ancrage non valide",
"mobileMenuQuickActions": "Actions rapides",
"mobileMenuCreate": "Créer",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 80d21153a6..a5019d4926 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -185,8 +185,6 @@
"entryBasedOn": "מבוסס על",
"entryCustomProfile": "פרופיל מותאם אישית",
"entryCreateProfile": "יצירת פרופיל",
- "entryRestoreBase": "שחזור אל [${x}]",
- "entryRestoreBaseConfirm": "לשחזר את כל הפריטים בפרופיל זה אל [${x}]?",
"entryImportInvalid": "קובץ פרופיל התפריטים וסרגל העגינה אינו תקין",
"mobileMenuQuickActions": "פעולות מהירות",
"mobileMenuCreate": "יצירה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 2d7192eaba..0394221bbb 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -185,8 +185,6 @@
"entryBasedOn": "इस पर आधारित",
"entryCustomProfile": "कस्टम प्रोफ़ाइल",
"entryCreateProfile": "प्रोफ़ाइल बनाएँ",
- "entryRestoreBase": "[${x}] पर पुनर्स्थापित करें",
- "entryRestoreBaseConfirm": "क्या इस प्रोफ़ाइल की सभी प्रविष्टियाँ [${x}] पर पुनर्स्थापित करनी हैं?",
"entryImportInvalid": "मेनू और डॉक प्रोफ़ाइल फ़ाइल अमान्य है",
"mobileMenuQuickActions": "त्वरित कार्रवाइयाँ",
"mobileMenuCreate": "बनाएँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 0b4047bab9..4bcd9e2e67 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Berdasarkan",
"entryCustomProfile": "Profil kustom",
"entryCreateProfile": "Buat profil",
- "entryRestoreBase": "Pulihkan ke [${x}]",
- "entryRestoreBaseConfirm": "Pulihkan semua entri dalam profil ini ke [${x}]?",
"entryImportInvalid": "Berkas profil menu dan dok tidak valid",
"mobileMenuQuickActions": "Tindakan cepat",
"mobileMenuCreate": "Buat",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 87bf8d75a8..1818c4377d 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Basato su",
"entryCustomProfile": "Profilo personalizzato",
"entryCreateProfile": "Crea profilo",
- "entryRestoreBase": "Ripristina a [${x}]",
- "entryRestoreBaseConfirm": "Ripristinare tutte le voci di questo profilo a [${x}]?",
"entryImportInvalid": "File del profilo di menu e barra di ancoraggio non valido",
"mobileMenuQuickActions": "Azioni rapide",
"mobileMenuCreate": "Crea",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b3430f6a14..fba66f2987 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -185,8 +185,6 @@
"entryBasedOn": "ベース",
"entryCustomProfile": "カスタムプロファイル",
"entryCreateProfile": "プロファイルを作成",
- "entryRestoreBase": "[${x}]に戻す",
- "entryRestoreBaseConfirm": "このプロファイルのすべての項目を [${x}] に戻しますか?",
"entryImportInvalid": "メニューとドックのプロファイルファイルが無効です",
"mobileMenuQuickActions": "クイック操作",
"mobileMenuCreate": "作成",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index f002de8dc2..4eab245487 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -185,8 +185,6 @@
"entryBasedOn": "기준",
"entryCustomProfile": "사용자 지정 프로필",
"entryCreateProfile": "프로필 만들기",
- "entryRestoreBase": "[${x}](으)로 복원",
- "entryRestoreBaseConfirm": "이 프로필의 모든 항목을 [${x}](으)로 복원하시겠습니까?",
"entryImportInvalid": "메뉴 및 도크 프로필 파일이 올바르지 않습니다",
"mobileMenuQuickActions": "빠른 작업",
"mobileMenuCreate": "만들기",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 3120d15071..dd1ed94f9b 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Gebaseerd op",
"entryCustomProfile": "Aangepast profiel",
"entryCreateProfile": "Profiel maken",
- "entryRestoreBase": "Herstellen naar [${x}]",
- "entryRestoreBaseConfirm": "Alle items in dit profiel herstellen naar [${x}]?",
"entryImportInvalid": "Ongeldig profielbestand voor menu's en dock",
"mobileMenuQuickActions": "Snelle acties",
"mobileMenuCreate": "Maken",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index f956ae1b64..7e4cfb7bad 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Na podstawie",
"entryCustomProfile": "Profil niestandardowy",
"entryCreateProfile": "Utwórz profil",
- "entryRestoreBase": "Przywróć do [${x}]",
- "entryRestoreBaseConfirm": "Przywrócić wszystkie pozycje tego profilu do [${x}]?",
"entryImportInvalid": "Nieprawidłowy plik profilu menu i doku",
"mobileMenuQuickActions": "Szybkie działania",
"mobileMenuCreate": "Utwórz",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index bdb6130eb2..6fae43f969 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Baseado em",
"entryCustomProfile": "Perfil personalizado",
"entryCreateProfile": "Criar perfil",
- "entryRestoreBase": "Restaurar para [${x}]",
- "entryRestoreBaseConfirm": "Restaurar todas as entradas deste perfil para [${x}]?",
"entryImportInvalid": "Arquivo de perfil de menus e dock inválido",
"mobileMenuQuickActions": "Ações rápidas",
"mobileMenuCreate": "Criar",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index e44343fa23..7b80b640ad 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -185,8 +185,6 @@
"entryBasedOn": "На основе",
"entryCustomProfile": "Пользовательский профиль",
"entryCreateProfile": "Создать профиль",
- "entryRestoreBase": "Восстановить до [${x}]",
- "entryRestoreBaseConfirm": "Восстановить все элементы этого профиля до [${x}]?",
"entryImportInvalid": "Недопустимый файл профиля меню и док-панели",
"mobileMenuQuickActions": "Быстрые действия",
"mobileMenuCreate": "Создание",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 2bb3c7db6b..4c96526aac 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Založené na",
"entryCustomProfile": "Vlastný profil",
"entryCreateProfile": "Vytvoriť profil",
- "entryRestoreBase": "Obnoviť na [${x}]",
- "entryRestoreBaseConfirm": "Obnoviť všetky položky tohto profilu na [${x}]?",
"entryImportInvalid": "Neplatný súbor profilu ponúk a doku",
"mobileMenuQuickActions": "Rýchle akcie",
"mobileMenuCreate": "Vytvoriť",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index bdf1a2bffc..e2d0e795fd 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -185,8 +185,6 @@
"entryBasedOn": "อ้างอิงจาก",
"entryCustomProfile": "โปรไฟล์กำหนดเอง",
"entryCreateProfile": "สร้างโปรไฟล์",
- "entryRestoreBase": "คืนค่าเป็น [${x}]",
- "entryRestoreBaseConfirm": "คืนค่ารายการทั้งหมดในโปรไฟล์นี้เป็น [${x}] หรือไม่?",
"entryImportInvalid": "ไฟล์โปรไฟล์เมนูและแถบเชื่อมต่อไม่ถูกต้อง",
"mobileMenuQuickActions": "การดำเนินการด่วน",
"mobileMenuCreate": "สร้าง",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 34dcb43eb8..0bfa65e648 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -185,8 +185,6 @@
"entryBasedOn": "Temel alınan",
"entryCustomProfile": "Özel profil",
"entryCreateProfile": "Profil oluştur",
- "entryRestoreBase": "[${x}] durumuna geri yükle",
- "entryRestoreBaseConfirm": "Bu profildeki tüm öğeler [${x}] durumuna geri yüklensin mi?",
"entryImportInvalid": "Menü ve yuva profil dosyası geçersiz",
"mobileMenuQuickActions": "Hızlı işlemler",
"mobileMenuCreate": "Oluştur",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 405635aecf..9784a5b963 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -185,8 +185,6 @@
"entryBasedOn": "На основі",
"entryCustomProfile": "Користувацький профіль",
"entryCreateProfile": "Створити профіль",
- "entryRestoreBase": "Відновити до [${x}]",
- "entryRestoreBaseConfirm": "Відновити всі елементи цього профілю до [${x}]?",
"entryImportInvalid": "Недійсний файл профілю меню та док-панелі",
"mobileMenuQuickActions": "Швидкі дії",
"mobileMenuCreate": "Створення",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 0908548d2a..919bf7bb97 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -185,8 +185,6 @@
"entryBasedOn": "基于",
"entryCustomProfile": "自定义方案",
"entryCreateProfile": "新建方案",
- "entryRestoreBase": "恢复为 [${x}]",
- "entryRestoreBaseConfirm": "确定将此方案的所有入口恢复为 [${x}] 吗?",
"entryImportInvalid": "菜单与停靠栏方案文件无效",
"mobileMenuQuickActions": "快捷操作",
"mobileMenuCreate": "创建",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index b03d41fd48..9c52db7edf 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -185,8 +185,6 @@
"entryBasedOn": "基於",
"entryCustomProfile": "自訂方案",
"entryCreateProfile": "新增方案",
- "entryRestoreBase": "還原為 [${x}]",
- "entryRestoreBaseConfirm": "確定將此方案的所有入口還原為 [${x}] 嗎?",
"entryImportInvalid": "選單與停靠欄方案檔案無效",
"mobileMenuQuickActions": "快速操作",
"mobileMenuCreate": "建立",
diff --git a/app/src/config/entryVisibility/profile.test.ts b/app/src/config/entryVisibility/profile.test.ts
new file mode 100644
index 0000000000..3e0f73c9c3
--- /dev/null
+++ b/app/src/config/entryVisibility/profile.test.ts
@@ -0,0 +1,68 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {
+ getProfileEntryVisibility,
+ isEntryVisibilityImportVersionSupported,
+ normalizeEntryVisibilityImportProfile,
+} from "./profile";
+
+test("custom entry visibility preserves saved values", () => {
+ const profile = {entries: {visible: true, hidden: false}};
+ assert.equal(getProfileEntryVisibility(profile, "visible"), true);
+ assert.equal(getProfileEntryVisibility(profile, "hidden"), false);
+});
+
+test("custom entry visibility shows missing entries", () => {
+ assert.equal(getProfileEntryVisibility({entries: {}}, "new-entry"), true);
+ assert.equal(getProfileEntryVisibility(undefined, "new-entry"), true);
+});
+
+test("entry visibility import supports versions 1, 2, and 3", () => {
+ assert.equal(isEntryVisibilityImportVersionSupported(1, 3), true);
+ assert.equal(isEntryVisibilityImportVersionSupported(2, 3), true);
+ assert.equal(isEntryVisibilityImportVersionSupported(3, 3), true);
+ assert.equal(isEntryVisibilityImportVersionSupported(4, 3), false);
+});
+
+test("legacy entry visibility imports require base without persisting it", () => {
+ const profile = normalizeEntryVisibilityImportProfile({
+ name: "Legacy",
+ base: "simple",
+ entries: {visible: true, hidden: false, invalid: "false"},
+ orders: {menu: ["known", 1, "plugin"]},
+ }, 2, {});
+ assert.deepEqual(profile, {
+ name: "Legacy",
+ entries: {visible: true, hidden: false},
+ orders: {menu: ["known", "plugin"]},
+ });
+ assert.equal(normalizeEntryVisibilityImportProfile({
+ name: "Legacy",
+ entries: {},
+ }, 2, {}), undefined);
+});
+
+test("current entry visibility imports do not require base", () => {
+ const defaultOrders = {menu: ["default"]};
+ assert.deepEqual(normalizeEntryVisibilityImportProfile({
+ name: "Current",
+ entries: {},
+ }, 3, defaultOrders), {
+ name: "Current",
+ entries: {},
+ orders: defaultOrders,
+ });
+});
+
+test("version 1 entry visibility imports use default orders", () => {
+ const defaultOrders = {menu: ["default"]};
+ assert.deepEqual(normalizeEntryVisibilityImportProfile({
+ name: "Version 1",
+ base: "full",
+ entries: {},
+ }, 1, defaultOrders), {
+ name: "Version 1",
+ entries: {},
+ orders: defaultOrders,
+ });
+});
diff --git a/app/src/config/entryVisibility/profile.ts b/app/src/config/entryVisibility/profile.ts
new file mode 100644
index 0000000000..06c609a589
--- /dev/null
+++ b/app/src/config/entryVisibility/profile.ts
@@ -0,0 +1,41 @@
+export const getProfileEntryVisibility = (profile: Pick<Config.IEntryVisibilityProfile, "entries"> | undefined,
+ path: string) =>
+ typeof profile?.entries[path] === "boolean" ? profile.entries[path] : true;
+
+export type TEntryVisibilityImportProfile = {
+ name?: unknown;
+ base?: unknown;
+ entries?: unknown;
+ orders?: unknown;
+};
+
+export const isEntryVisibilityImportVersionSupported = (version: number, currentVersion: number) =>
+ Number.isInteger(version) && version >= 1 && version <= currentVersion;
+
+export const normalizeEntryVisibilityImportProfile = (
+ profile: TEntryVisibilityImportProfile,
+ version: number,
+ defaultOrders: Record<string, string[]>,
+): Pick<Config.IEntryVisibilityProfile, "name" | "entries" | "orders"> | undefined => {
+ if (!profile || typeof profile.name !== "string" || !profile.name.trim() || !profile.entries ||
+ typeof profile.entries !== "object" || Array.isArray(profile.entries) ||
+ (version < 3 && profile.base !== "simple" && profile.base !== "full")) {
+ return;
+ }
+ const entries = Object.entries(profile.entries)
+ .reduce<Record<string, boolean>>((result, [path, visible]) => {
+ if (typeof visible === "boolean") {
+ result[path] = visible;
+ }
+ return result;
+ }, {});
+ const orders = profile.orders && typeof profile.orders === "object" && !Array.isArray(profile.orders)
+ ? Object.entries(profile.orders).reduce<Record<string, string[]>>((result, [path, order]) => {
+ if (Array.isArray(order)) {
+ result[path] = order.filter((key): key is string => typeof key === "string");
+ }
+ return result;
+ }, {})
+ : defaultOrders;
+ return {name: profile.name, entries, orders};
+};
diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.ts
index 9101c1b040..9afd952d7c 100644
--- a/app/src/config/entryVisibility/runtime.ts
+++ b/app/src/config/entryVisibility/runtime.ts
@@ -9,10 +9,12 @@ import {
} from "./catalog";
import {reorderEntrySlots, resolveEntryOrder} from "./order";
import {getDocTreeEntryScope} from "./docTreeScope";
+import {getProfileEntryVisibility} from "./profile";
-export const ENTRY_VISIBILITY_VERSION = 2;
+export const ENTRY_VISIBILITY_VERSION = 3;
export const ENTRY_PROFILE_SIMPLE = "simple";
export const ENTRY_PROFILE_FULL = "full";
+export type TEntryVisibilityTemplate = typeof ENTRY_PROFILE_SIMPLE | typeof ENTRY_PROFILE_FULL;
const getConfig = () => window.siyuan.config.appearance.entryVisibility;
@@ -21,8 +23,8 @@ export const getActiveEntryProfile = () => {
return config.profiles.find((item) => item.id === config.active);
};
-const getBaseVisibility = (path: string, base: Config.TEntryVisibilityBase) =>
- base === ENTRY_PROFILE_FULL || getEntryCatalogNode(path)?.simple !== false;
+const getTemplateVisibility = (path: string, template: TEntryVisibilityTemplate) =>
+ template === ENTRY_PROFILE_FULL || getEntryCatalogNode(path)?.simple !== false;
export const isEntryVisible = (path: string): boolean => {
/// #if MOBILE
@@ -33,12 +35,9 @@ export const isEntryVisible = (path: string): boolean => {
if (config.active === ENTRY_PROFILE_FULL) {
visible = true;
} else if (config.active === ENTRY_PROFILE_SIMPLE) {
- visible = getBaseVisibility(path, ENTRY_PROFILE_SIMPLE);
+ visible = getTemplateVisibility(path, ENTRY_PROFILE_SIMPLE);
} else {
- const profile = getActiveEntryProfile();
- visible = typeof profile?.entries[path] === "boolean"
- ? profile.entries[path]
- : getBaseVisibility(path, profile?.base || ENTRY_PROFILE_FULL);
+ visible = getProfileEntryVisibility(getActiveEntryProfile(), path);
}
if (!visible) {
return false;
@@ -51,9 +50,9 @@ export const isEntryVisible = (path: string): boolean => {
/// #endif
};
-export const createEntryProfileSnapshot = (base: Config.TEntryVisibilityBase) => {
+export const createEntryProfileSnapshot = (template: TEntryVisibilityTemplate) => {
return getEntryPaths().reduce<Record<string, boolean>>((entries, path) => {
- entries[path] = getBaseVisibility(path, base);
+ entries[path] = getTemplateVisibility(path, template);
return entries;
}, {});
};
diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.ts
index 7b207f128b..300ff7fb60 100644
--- a/app/src/config/entryVisibility/ui.ts
+++ b/app/src/config/entryVisibility/ui.ts
@@ -18,24 +18,30 @@ import {
ENTRY_PROFILE_FULL,
ENTRY_PROFILE_SIMPLE,
ENTRY_VISIBILITY_VERSION,
- getActiveEntryProfile,
isEntryVisible,
saveEntryVisibility,
+ TEntryVisibilityTemplate,
} from "./runtime";
import {mergeEntryOrderPreservingUnknown, moveEntryOrder, resolveEntryOrder} from "./order";
+import {
+ getProfileEntryVisibility,
+ isEntryVisibilityImportVersionSupported,
+ normalizeEntryVisibilityImportProfile,
+ TEntryVisibilityImportProfile,
+} from "./profile";
type TImportFile = {
type: "siyuan-entry-profile" | "siyuan-entry-profile-bundle";
version: number;
- profile?: Config.IEntryVisibilityProfile;
- profiles?: Config.IEntryVisibilityProfile[];
+ profile?: TEntryVisibilityImportProfile;
+ profiles?: TEntryVisibilityImportProfile[];
};
const cloneConfig = () => JSON.parse(JSON.stringify(
window.siyuan.config.appearance.entryVisibility
)) as Config.IEntryVisibility;
-const baseLabel = (base: Config.TEntryVisibilityBase) => base === ENTRY_PROFILE_SIMPLE
+const templateLabel = (template: TEntryVisibilityTemplate) => template === ENTRY_PROFILE_SIMPLE
? window.siyuan.languages.entrySimple
: window.siyuan.languages.entryFull;
@@ -77,20 +83,11 @@ const exportBundle = () => {
} satisfies TImportFile);
};
-const getCurrentBase = (): Config.TEntryVisibilityBase => {
- const active = window.siyuan.config.appearance.entryVisibility.active;
- if (active === ENTRY_PROFILE_SIMPLE || active === ENTRY_PROFILE_FULL) {
- return active;
- }
- return getActiveEntryProfile()?.base || ENTRY_PROFILE_FULL;
-};
-
-const createProfile = (base: Config.TEntryVisibilityBase, current = false, name?: string) => {
+const createProfile = (template: TEntryVisibilityTemplate, current = false, name?: string) => {
const profile: Config.IEntryVisibilityProfile = {
id: genUUID(),
name: uniqueName(name || window.siyuan.languages.entryCustomProfile),
- base,
- entries: createEntryProfileSnapshot(base),
+ entries: createEntryProfileSnapshot(template),
orders: createEntryOrderSnapshot(current),
};
if (current) {
@@ -148,14 +145,13 @@ const createEntryView = (root: HTMLElement) => {
const profileCard = (
id: string,
name: string,
- base: Config.TEntryVisibilityBase,
builtin: boolean,
active: boolean,
) => `<div class="b3-card${active ? " b3-card--current" : ""}" data-profile-id="${escapeAttr(id)}" data-action="${builtin ? "view" : "edit"}">
<div class="fn__flex-1 fn__flex-column">
<div class="b3-card__info b3-card__info--left fn__flex-1">
<div class="fn__ellipsis config-name">${escapeHtml(name)}</div>
- <div class="b3-card__desc">${builtin ? window.siyuan.languages.entryBuiltin : `${window.siyuan.languages.entryCustom} · ${window.siyuan.languages.entryBasedOn} ${baseLabel(base)}`}${active ? ` · ${window.siyuan.languages.current}` : ""}${builtin ? ` · ${base === ENTRY_PROFILE_SIMPLE ? window.siyuan.languages.entrySimpleTip : window.siyuan.languages.entryFullTip}` : ""}</div>
+ <div class="b3-card__desc">${builtin ? window.siyuan.languages.entryBuiltin : window.siyuan.languages.entryCustom}${active ? ` · ${window.siyuan.languages.current}` : ""}${builtin ? ` · ${id === ENTRY_PROFILE_SIMPLE ? window.siyuan.languages.entrySimpleTip : window.siyuan.languages.entryFullTip}` : ""}</div>
</div>
</div>
<div class="b3-card__actions b3-card__actions--right">
@@ -173,21 +169,16 @@ const renderProfileCards = (root: HTMLElement) => {
}
const config = window.siyuan.config.appearance.entryVisibility;
const cards = [
- profileCard(ENTRY_PROFILE_SIMPLE, window.siyuan.languages.entrySimple, ENTRY_PROFILE_SIMPLE, true,
+ profileCard(ENTRY_PROFILE_SIMPLE, window.siyuan.languages.entrySimple, true,
config.active === ENTRY_PROFILE_SIMPLE),
- profileCard(ENTRY_PROFILE_FULL, window.siyuan.languages.entryFull, ENTRY_PROFILE_FULL, true,
+ profileCard(ENTRY_PROFILE_FULL, window.siyuan.languages.entryFull, true,
config.active === ENTRY_PROFILE_FULL),
- ...config.profiles.map((profile) => profileCard(profile.id, profile.name, profile.base, false,
+ ...config.profiles.map((profile) => profileCard(profile.id, profile.name, false,
config.active === profile.id)),
];
container.innerHTML = `<div class="b3-cards b3-cards--nowrap">${cards.join("")}</div>`;
};
-const isEntryChecked = (profile: Config.IEntryVisibilityProfile, path: string, item: IEntryCatalogNode) =>
- typeof profile.entries[path] === "boolean"
- ? profile.entries[path]
- : profile.base === ENTRY_PROFILE_FULL || item.simple;
-
const getProfileEntryOrder = (profile: Config.IEntryVisibilityProfile, parentPath: string,
nodes = getEntryCatalogChildren(parentPath) || []) => {
const defaultOrder = nodes.map((item) => item.key);
@@ -205,7 +196,7 @@ const orderEntryNodes = (profile: Config.IEntryVisibilityProfile, parentPath: st
const renderEntrySwitch = (profile: Config.IEntryVisibilityProfile, path: string, item: IEntryCatalogNode,
parentEnabled: boolean, readOnly: boolean) => `<input class="b3-switch" type="checkbox"
aria-label="${escapeAttr(item.label())}" data-entry-path="${escapeAttr(path)}"${readOnly ? ' data-entry-readonly aria-disabled="true"' : ""}
- ${!parentEnabled && !readOnly ? " disabled" : ""}${isEntryChecked(profile, path, item) ? " checked" : ""}>`;
+ ${!parentEnabled && !readOnly ? " disabled" : ""}${getProfileEntryVisibility(profile, path) ? " checked" : ""}>`;
const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: string, prefix: string,
nodes: IEntryCatalogNode[], depth: number, selectedPaths: string[],
@@ -302,7 +293,7 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:
let prefix = directDisplayRoot ? directDisplayRootPath : section.key;
let title = directDisplayRoot?.label() || section.label();
let parentEnabled = directDisplayRoot
- ? isEntryChecked(profile, directDisplayRootPath, directDisplayRoot)
+ ? getProfileEntryVisibility(profile, directDisplayRootPath)
: true;
let depth = 0;
while (nodes.length > 0) {
@@ -320,7 +311,7 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:
if (!selectedNode?.children?.length) {
break;
}
- parentEnabled = parentEnabled && isEntryChecked(profile, selectedPath, selectedNode);
+ parentEnabled = parentEnabled && getProfileEntryVisibility(profile, selectedPath);
nodes = selectedNode.children;
prefix = selectedPath;
title = selectedNode.label();
@@ -371,14 +362,14 @@ const getEntrySearchFilter = (query: string) => {
const openProfileEditor = (root: HTMLElement, profileID?: string) => {
refreshSlashMenuCatalog(window.siyuan.ws?.app?.plugins || []);
const builtin = profileID === ENTRY_PROFILE_SIMPLE || profileID === ENTRY_PROFILE_FULL;
+ let selectedTemplate: TEntryVisibilityTemplate | "current" = ENTRY_PROFILE_SIMPLE;
const existing = profileID
? window.siyuan.config.appearance.entryVisibility.profiles.find((item) => item.id === profileID)
: undefined;
const draft: Config.IEntryVisibilityProfile = builtin
? {
id: profileID,
- name: baseLabel(profileID),
- base: profileID,
+ name: templateLabel(profileID),
entries: createEntryProfileSnapshot(profileID),
orders: createEntryOrderSnapshot(),
}
@@ -399,23 +390,21 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
<span class="fn__space"></span>
<input class="b3-text-field fn__flex-center fn__size200" data-profile-field="name" value="${escapeAttr(draft.name)}">
</label>
- <label class="fn__flex b3-label config-item config-wrap">
+ ${creating ? `<label class="fn__flex b3-label config-item config-wrap">
<div class="fn__flex-1"><div class="config-name">${window.siyuan.languages.entryBasedOn}</div></div>
<span class="fn__space"></span>
- ${creating ? `<select class="b3-select fn__flex-center fn__size200" data-profile-field="base">
- <option value="simple"${draft.base === ENTRY_PROFILE_SIMPLE ? " selected" : ""}>${window.siyuan.languages.entrySimple}</option>
- <option value="full"${draft.base === ENTRY_PROFILE_FULL ? " selected" : ""}>${window.siyuan.languages.entryFull}</option>
+ <select class="b3-select fn__flex-center fn__size200" data-profile-field="template">
+ <option value="simple">${window.siyuan.languages.entrySimple}</option>
+ <option value="full">${window.siyuan.languages.entryFull}</option>
<option value="current">${window.siyuan.languages.current}</option>
- </select>` : `<div class="fn__size200">${baseLabel(draft.base)}</div>`}
- </label>
+ </select>
+ </label>` : ""}
</div>
</div>`}
<div class="config-group">
${builtin ? `<div class="config-title">${escapeHtml(draft.name)}</div>` : ""}
<div class="fn__flex">
<input class="b3-text-field fn__flex-1" data-type="entry-search" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">
- ${builtin ? "" : `<span class="fn__space"></span>
- <button class="b3-button b3-button--outline" data-action="restore">${window.siyuan.languages.entryRestoreBase.replace("${x}", baseLabel(draft.base))}</button>`}
</div>
</div>
<div class="config-entry-visibility__browser" data-type="entry-browser"></div>
@@ -427,7 +416,6 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
</div>`;
const browser = view.querySelector<HTMLElement>("[data-type='entry-browser']");
const searchInput = view.querySelector<HTMLInputElement>("[data-type='entry-search']");
- const restoreButton = view.querySelector<HTMLButtonElement>("[data-action='restore']");
let selectedSectionKey = entryCatalog[0].key;
let selectedPaths: string[] = [];
let previousQuery = "";
@@ -437,11 +425,6 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
.forEach((item) => item.classList.remove("config-entry-visibility__row--drop-before",
"config-entry-visibility__row--drop-after"));
};
- const updateRestoreButton = () => {
- if (restoreButton) {
- restoreButton.textContent = window.siyuan.languages.entryRestoreBase.replace("${x}", baseLabel(draft.base));
- }
- };
const renderBrowser = (scrollToEnd = false, resetEntryColumns = false, revealSelection = false) => {
const oldColumns = Array.from(browser.querySelectorAll<HTMLElement>("[data-entry-column]"));
const oldScrollTops = oldColumns.map((column) => column.querySelector<HTMLElement>(
@@ -585,19 +568,19 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
renderBrowser();
return;
}
- if (target.dataset.profileField !== "base") {
+ if (target.dataset.profileField !== "template") {
return;
}
- const selection = target.value;
- draft.base = selection === "current" ? getCurrentBase() : selection as Config.TEntryVisibilityBase;
- draft.entries = createEntryProfileSnapshot(draft.base);
- draft.orders = createEntryOrderSnapshot(selection === "current");
- if (selection === "current") {
+ selectedTemplate = target.value as TEntryVisibilityTemplate | "current";
+ draft.entries = createEntryProfileSnapshot(selectedTemplate === "current"
+ ? ENTRY_PROFILE_FULL
+ : selectedTemplate);
+ draft.orders = createEntryOrderSnapshot(selectedTemplate === "current");
+ if (selectedTemplate === "current") {
getEntryPaths().forEach((path) => {
draft.entries[path] = isEntryVisible(path);
});
}
- updateRestoreButton();
renderBrowser();
});
view.addEventListener("click", (event) => {
@@ -626,14 +609,6 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
selectedPaths = selectedPaths.slice(0, depth);
selectedPaths[depth] = actionElement.dataset.entryPath;
renderBrowser(true);
- } else if (!builtin && action === "restore") {
- const restoreTarget = baseLabel(draft.base);
- confirmDialog(window.siyuan.languages.entryRestoreBase.replace("${x}", restoreTarget),
- window.siyuan.languages.entryRestoreBaseConfirm.replace("${x}", restoreTarget), () => {
- draft.entries = createEntryProfileSnapshot(draft.base);
- draft.orders = createEntryOrderSnapshot();
- renderBrowser();
- });
} else if (!builtin && action === "confirm") {
const nameInput = view.querySelector<HTMLInputElement>("[data-profile-field='name']");
const name = draft.name.trim();
@@ -662,10 +637,10 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
const importProfiles = async (root: HTMLElement, file: File) => {
try {
const data = JSON.parse(await file.text()) as TImportFile;
- if (data.version !== 1 && data.version !== ENTRY_VISIBILITY_VERSION) {
+ if (!isEntryVisibilityImportVersionSupported(data.version, ENTRY_VISIBILITY_VERSION)) {
throw new Error("unsupported version");
}
- let imported: Config.IEntryVisibilityProfile[];
+ let imported: TEntryVisibilityImportProfile[];
if (data.type === "siyuan-entry-profile" && data.profile) {
imported = [data.profile];
} else if (data.type === "siyuan-entry-profile-bundle" && Array.isArray(data.profiles)) {
@@ -676,31 +651,15 @@ const importProfiles = async (root: HTMLElement, file: File) => {
const config = cloneConfig();
let importedCount = 0;
imported.forEach((item) => {
- if (!item || typeof item.name !== "string" || !item.name.trim() || !item.entries ||
- Array.isArray(item.entries) ||
- (item.base !== ENTRY_PROFILE_SIMPLE && item.base !== ENTRY_PROFILE_FULL)) {
+ const profile = normalizeEntryVisibilityImportProfile(item, data.version, createEntryOrderSnapshot());
+ if (!profile) {
return;
}
- const entries = Object.entries(item.entries).reduce<Record<string, boolean>>((result, [path, visible]) => {
- if (typeof visible === "boolean") {
- result[path] = visible;
- }
- return result;
- }, {});
- const orders = item.orders && !Array.isArray(item.orders)
- ? Object.entries(item.orders).reduce<Record<string, string[]>>((result, [path, order]) => {
- if (Array.isArray(order)) {
- result[path] = order.filter((key): key is string => typeof key === "string");
- }
- return result;
- }, {})
- : createEntryOrderSnapshot();
config.profiles.push({
id: genUUID(),
- name: uniqueName(item.name, config.profiles),
- base: item.base,
- entries,
- orders,
+ name: uniqueName(profile.name, config.profiles),
+ entries: profile.entries,
+ orders: profile.orders,
});
importedCount++;
});
@@ -761,8 +720,9 @@ export const mountEntryVisibility = (root: HTMLElement) => {
} else if (action === "edit" || action === "view") {
openProfileEditor(root, id);
} else if (action === "duplicate") {
- const copy = profile ? duplicateProfile(profile) : createProfile(id as Config.TEntryVisibilityBase, false,
- `${baseLabel(id as Config.TEntryVisibilityBase)} ${window.siyuan.languages.duplicateCopy}`);
+ const template = id as TEntryVisibilityTemplate;
+ const copy = profile ? duplicateProfile(profile) : createProfile(template, false,
+ `${templateLabel(template)} ${window.siyuan.languages.duplicateCopy}`);
config.profiles.push(copy);
saveEntryVisibility(config);
renderProfileCards(root);
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 8aedda7dcd..8796d5b437 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -381,12 +381,9 @@ declare namespace Config {
frontends?: string[];
}
- export type TEntryVisibilityBase = "simple" | "full";
-
export interface IEntryVisibilityProfile {
id: string;
name: string;
- base: TEntryVisibilityBase;
entries: Record<string, boolean>;
orders: Record<string, string[]>;
}
diff --git a/kernel/conf/appearance.go b/kernel/conf/appearance.go
index 908de478f4..c101215304 100644
--- a/kernel/conf/appearance.go
+++ b/kernel/conf/appearance.go
@@ -61,7 +61,7 @@ func NewAppearance() *Appearance {
}
const (
- EntryVisibilityVersion = 2
+ EntryVisibilityVersion = 3
EntryVisibilityProfileSimple = "simple"
EntryVisibilityProfileFull = "full"
)
@@ -75,7 +75,6 @@ type EntryVisibility struct {
type EntryVisibilityProfile struct {
ID string `json:"id"`
Name string `json:"name"`
- Base string `json:"base"`
Entries map[string]bool `json:"entries"`
Orders map[string][]string `json:"orders"`
}
@@ -107,9 +106,6 @@ func NormalizeEntryVisibility(entryVisibility *EntryVisibility, fallback string)
profile.ID == EntryVisibilityProfileFull || profileIDs[profile.ID] {
continue
}
- if profile.Base != EntryVisibilityProfileSimple && profile.Base != EntryVisibilityProfileFull {
- profile.Base = EntryVisibilityProfileFull
- }
if nil == profile.Entries {
profile.Entries = map[string]bool{}
}
diff --git a/kernel/conf/appearance_test.go b/kernel/conf/appearance_test.go
index 6e375f881c..6cfdb9fe4e 100644
--- a/kernel/conf/appearance_test.go
+++ b/kernel/conf/appearance_test.go
@@ -16,7 +16,11 @@
package conf
-import "testing"
+import (
+ "bytes"
+ "encoding/json"
+ "testing"
+)
func TestNormalizeEntryVisibilityDefaults(t *testing.T) {
entryVisibility := NormalizeEntryVisibility(nil, EntryVisibilityProfileSimple)
@@ -36,7 +40,7 @@ func TestNormalizeEntryVisibilityProfiles(t *testing.T) {
nil,
{ID: "", Name: "missing-id"},
{ID: EntryVisibilityProfileSimple, Name: "Reserved"},
- {ID: "custom", Name: "Custom", Base: "invalid", Entries: map[string]bool{"future.entry": false},
+ {ID: "custom", Name: "Custom", Entries: map[string]bool{"future.entry": false},
Orders: map[string][]string{"future": {"entry"}}},
{ID: "custom", Name: "Duplicate"},
},
@@ -49,7 +53,7 @@ func TestNormalizeEntryVisibilityProfiles(t *testing.T) {
t.Fatalf("unexpected profiles: %+v", entryVisibility.Profiles)
}
profile := entryVisibility.Profiles[0]
- if profile.Base != EntryVisibilityProfileFull || profile.Entries["future.entry"] {
+ if profile.Entries["future.entry"] {
t.Fatalf("unexpected normalized profile: %+v", profile)
}
if len(profile.Orders["future"]) != 1 || profile.Orders["future"][0] != "entry" {
@@ -61,7 +65,7 @@ func TestNormalizeEntryVisibilityActiveCustomProfile(t *testing.T) {
entryVisibility := NormalizeEntryVisibility(&EntryVisibility{
Active: "custom",
Profiles: []*EntryVisibilityProfile{
- {ID: "custom", Name: "Custom", Base: EntryVisibilityProfileSimple},
+ {ID: "custom", Name: "Custom"},
},
}, EntryVisibilityProfileFull)
@@ -72,3 +76,24 @@ func TestNormalizeEntryVisibilityActiveCustomProfile(t *testing.T) {
t.Fatal("profile orders should be initialized")
}
}
+
+func TestNormalizeEntryVisibilityRemovesLegacyBase(t *testing.T) {
+ legacy := []byte(`{"version":2,"active":"custom","profiles":[{"id":"custom","name":"Custom","base":"simple","entries":{"future.entry":false},"orders":{}}]}`)
+ entryVisibility := &EntryVisibility{}
+ if err := json.Unmarshal(legacy, entryVisibility); nil != err {
+ t.Fatalf("unmarshal legacy config failed: %v", err)
+ }
+
+ entryVisibility = NormalizeEntryVisibility(entryVisibility, EntryVisibilityProfileFull)
+ data, err := json.Marshal(entryVisibility)
+ if nil != err {
+ t.Fatalf("marshal normalized config failed: %v", err)
+ }
+ if bytes.Contains(data, []byte(`"base"`)) {
+ t.Fatalf("legacy base should not be persisted: %s", data)
+ }
+ if entryVisibility.Version != EntryVisibilityVersion || entryVisibility.Active != "custom" ||
+ entryVisibility.Profiles[0].Entries["future.entry"] {
+ t.Fatalf("unexpected normalized legacy config: %+v", entryVisibility)
+ }
+}