An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve color management and share database palettes in the workspace (#19001)
Jeffrey Chen6cc6a9978880
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 421c4c960c..ba26f436a5 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "استخدام اللون الافتراضي للسمة","useSVGDefaultIcon": "استخدام أيقونات SVG","useSVGDefaultIconTip": "استخدام أيقونات SVG لدفاتر الملاحظات والمستندات التي لا تحتوي على أيقونة مخصصة","bootAppearance": "مظهر صفحة بدء التشغيل",@@ -6,9 +7,7 @@"monospaceFont": "خط أحادي المسافة","monospaceFontTip": "يُستخدم لكتل التعليمات البرمجية والتعليمات البرمجية المضمنة وأرقام أسطر كتل التعليمات البرمجية؛ عند عدم تحديد أي خط، يُستخدم خط السمة","manageColors": "إدارة الألوان",- "manageBuiltinColors": "إدارة الألوان المضمنة","showInColorPicker": "إظهار في منتقي الألوان",- "resetAll": "إعادة تعيين الكل","exportFile": "تصدير الملف","namingEmpty": "لا يمكن أن يكون الاسم فارغًا","recentCreated": "تم إنشاؤها مؤخرًا",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex ca51b91360..dd49eb5420 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Standardfarbe des Designs verwenden","useSVGDefaultIcon": "SVG-Symbole verwenden","useSVGDefaultIconTip": "SVG-Symbole für Notizbücher und Dokumente ohne benutzerdefiniertes Symbol verwenden","bootAppearance": "Erscheinungsbild der Startseite",@@ -6,9 +7,7 @@"monospaceFont": "Festbreitenschrift","monospaceFontTip": "Wird für Codeblöcke, Inline-Code und Codeblock-Zeilennummern verwendet; wenn keine Schrift ausgewählt ist, wird die Schrift des Themes verwendet","manageColors": "Farben verwalten",- "manageBuiltinColors": "Integrierte Farben verwalten","showInColorPicker": "In der Farbauswahl anzeigen",- "resetAll": "Alle zurücksetzen","exportFile": "Datei exportieren","namingEmpty": "Der Name darf nicht leer sein","recentCreated": "Kürzlich erstellt",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 076f8ba4d6..13194de695 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Use the theme default color","useSVGDefaultIcon": "Use SVG icons","useSVGDefaultIconTip": "Use SVG icons for notebooks and documents without a custom icon","bootAppearance": "Startup appearance",@@ -6,9 +7,7 @@"monospaceFont": "Monospace Font","monospaceFontTip": "Used for code blocks, inline code, and code block line numbers; when no font is selected, the theme's font is used","manageColors": "Manage colors",- "manageBuiltinColors": "Manage built-in colors","showInColorPicker": "Show in color picker",- "resetAll": "Reset all","exportFile": "Export file","namingEmpty": "Name cannot be empty","recentCreated": "Recently Created",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 649db04c08..f9091590ee 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Usar el color predeterminado del tema","useSVGDefaultIcon": "Usar iconos SVG","useSVGDefaultIconTip": "Usar iconos SVG para cuadernos y documentos sin un icono personalizado","bootAppearance": "Apariencia de la página de inicio",@@ -6,9 +7,7 @@"monospaceFont": "Fuente monoespaciada","monospaceFontTip": "Se utiliza para bloques de código, código en línea y números de línea de bloques de código; si no se selecciona ninguna fuente, se usa la fuente del tema","manageColors": "Gestionar colores",- "manageBuiltinColors": "Gestionar colores integrados","showInColorPicker": "Mostrar en el selector de color",- "resetAll": "Restablecer todo","exportFile": "Exportar archivo","namingEmpty": "El nombre no puede estar vacío","recentCreated": "Creados recientemente",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 81d42fa16c..8b1732e732 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Utiliser la couleur par défaut du thème","useSVGDefaultIcon": "Utiliser les icônes SVG","useSVGDefaultIconTip": "Utiliser des icônes SVG pour les carnets et les documents sans icône personnalisée","bootAppearance": "Apparence de la page de démarrage",@@ -6,9 +7,7 @@"monospaceFont": "Police à chasse fixe","monospaceFontTip": "Utilisée pour les blocs de code, le code en ligne et les numéros de ligne des blocs de code ; si aucune police n’est sélectionnée, la police du thème est utilisée","manageColors": "Gérer les couleurs",- "manageBuiltinColors": "Gérer les couleurs intégrées","showInColorPicker": "Afficher dans le sélecteur de couleurs",- "resetAll": "Tout réinitialiser","exportFile": "Exporter le fichier","namingEmpty": "Le nom ne peut pas être vide","recentCreated": "Récemment créés",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 3db2d0c072..8a75ec4a29 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "השתמש בצבע ברירת המחדל של ערכת הנושא","useSVGDefaultIcon": "שימוש בסמלי SVG","useSVGDefaultIconTip": "שימוש בסמלי SVG עבור מחברות ומסמכים ללא סמל מותאם אישית","bootAppearance": "מראה דף ההפעלה",@@ -6,9 +7,7 @@"monospaceFont": "גופן ברוחב קבוע","monospaceFontTip": "משמש לבלוקי קוד, קוד בתוך שורה ומספרי שורות בבלוקי קוד; כאשר לא נבחר גופן, נעשה שימוש בגופן של ערכת הנושא","manageColors": "ניהול צבעים",- "manageBuiltinColors": "ניהול צבעים מובנים","showInColorPicker": "הצגה בבורר הצבעים",- "resetAll": "איפוס הכול","exportFile": "ייצוא קובץ","namingEmpty": "השם לא יכול להיות ריק","recentCreated": "נוצרו לאחרונה",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex f995e1386b..69dc1ef341 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "थीम का डिफ़ॉल्ट रंग उपयोग करें","useSVGDefaultIcon": "SVG आइकन का उपयोग करें","useSVGDefaultIconTip": "कस्टम आइकन के बिना नोटबुक और दस्तावेज़ों के लिए SVG आइकन का उपयोग करें","bootAppearance": "स्टार्टअप पृष्ठ का रूप",@@ -6,9 +7,7 @@"monospaceFont": "मोनोस्पेस फ़ॉन्ट","monospaceFontTip": "कोड ब्लॉक, इनलाइन कोड और कोड ब्लॉक पंक्ति संख्याओं के लिए उपयोग किया जाता है; कोई फ़ॉन्ट चयनित न होने पर थीम का फ़ॉन्ट उपयोग किया जाता है","manageColors": "रंग प्रबंधित करें",- "manageBuiltinColors": "अंतर्निहित रंग प्रबंधित करें","showInColorPicker": "रंग चयनकर्ता में दिखाएँ",- "resetAll": "सभी रीसेट करें","exportFile": "फ़ाइल निर्यात करें","namingEmpty": "नाम खाली नहीं हो सकता","recentCreated": "हाल ही में बनाए गए",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex c2f37ca822..1c4fd6d189 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Gunakan warna bawaan tema","useSVGDefaultIcon": "Gunakan ikon SVG","useSVGDefaultIconTip": "Gunakan ikon SVG untuk buku catatan dan dokumen tanpa ikon khusus","bootAppearance": "Tampilan halaman mulai",@@ -6,9 +7,7 @@"monospaceFont": "Font monospace","monospaceFontTip": "Digunakan untuk blok kode, kode sebaris, dan nomor baris blok kode; jika tidak ada font yang dipilih, font bawaan tema akan digunakan","manageColors": "Kelola warna",- "manageBuiltinColors": "Kelola warna bawaan","showInColorPicker": "Tampilkan di pemilih warna",- "resetAll": "Atur ulang semua","exportFile": "Ekspor file","namingEmpty": "Nama tidak boleh kosong","recentCreated": "Baru dibuat",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 2156c3aa6f..c0ebb33aa5 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Usa il colore predefinito del tema","useSVGDefaultIcon": "Usa icone SVG","useSVGDefaultIconTip": "Usa icone SVG per taccuini e documenti senza un'icona personalizzata","bootAppearance": "Aspetto della pagina di avvio",@@ -6,9 +7,7 @@"monospaceFont": "Carattere monospaziato","monospaceFontTip": "Utilizzato per blocchi di codice, codice in linea e numeri di riga dei blocchi di codice; se non è selezionato alcun carattere, viene utilizzato quello del tema","manageColors": "Gestisci colori",- "manageBuiltinColors": "Gestisci colori integrati","showInColorPicker": "Mostra nel selettore colori",- "resetAll": "Reimposta tutto","exportFile": "Esporta file","namingEmpty": "Il nome non può essere vuoto","recentCreated": "Creati di recente",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex cf345ff5c7..7e4d5b5635 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "テーマのデフォルト色を使用","useSVGDefaultIcon": "SVG アイコンを使用","useSVGDefaultIconTip": "カスタムアイコンがないノートブックと文書に SVG アイコンを使用","bootAppearance": "起動画面の外観",@@ -6,9 +7,7 @@"monospaceFont": "等幅フォント","monospaceFontTip": "コードブロック、インラインコード、コードブロックの行番号に使用され、フォントが選択されていない場合はテーマのフォントが使用されます","manageColors": "色を管理",- "manageBuiltinColors": "組み込み色を管理","showInColorPicker": "カラーピッカーに表示",- "resetAll": "すべてリセット","exportFile": "ファイルをエクスポート","namingEmpty": "名前を空にすることはできません","recentCreated": "最近作成",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex a5c7c6f9e5..1b27e452f5 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "테마 기본 색상 사용","useSVGDefaultIcon": "SVG 아이콘 사용","useSVGDefaultIconTip": "사용자 지정 아이콘이 없는 노트북과 문서에 SVG 아이콘 사용","bootAppearance": "시작 페이지 모양",@@ -6,9 +7,7 @@"monospaceFont": "고정폭 글꼴","monospaceFontTip": "코드 블록, 인라인 코드 및 코드 블록 줄 번호에 사용되며 글꼴을 선택하지 않으면 테마의 글꼴을 사용합니다","manageColors": "색상 관리",- "manageBuiltinColors": "기본 제공 색상 관리","showInColorPicker": "색상 선택기에 표시",- "resetAll": "모두 초기화","exportFile": "파일 내보내기","namingEmpty": "이름은 비워 둘 수 없습니다","recentCreated": "최근 생성",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 38f1cb74e5..6dc025e987 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Standaardkleur van het thema gebruiken","useSVGDefaultIcon": "SVG-pictogrammen gebruiken","useSVGDefaultIconTip": "SVG-pictogrammen gebruiken voor notitieboeken en documenten zonder aangepast pictogram","bootAppearance": "Uiterlijk van de opstartpagina",@@ -6,9 +7,7 @@"monospaceFont": "Monospacelettertype","monospaceFontTip": "Wordt gebruikt voor codeblokken, inlinecode en regelnummers van codeblokken; als er geen lettertype is geselecteerd, wordt het lettertype van het thema gebruikt","manageColors": "Kleuren beheren",- "manageBuiltinColors": "Ingebouwde kleuren beheren","showInColorPicker": "Weergeven in de kleurkiezer",- "resetAll": "Alles resetten","exportFile": "Bestand exporteren","namingEmpty": "De naam mag niet leeg zijn","recentCreated": "Recent gemaakt",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 6b8ac8dffe..6e0f502692 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Użyj domyślnego koloru motywu","useSVGDefaultIcon": "Używaj ikon SVG","useSVGDefaultIconTip": "Używaj ikon SVG dla notatników i dokumentów bez niestandardowej ikony","bootAppearance": "Wygląd strony startowej",@@ -6,9 +7,7 @@"monospaceFont": "Czcionka o stałej szerokości","monospaceFontTip": "Używana w blokach kodu, kodzie wbudowanym i numerach wierszy bloków kodu; gdy nie wybrano czcionki, używana jest czcionka motywu","manageColors": "Zarządzaj kolorami",- "manageBuiltinColors": "Zarządzaj wbudowanymi kolorami","showInColorPicker": "Pokaż w selektorze kolorów",- "resetAll": "Resetuj wszystko","exportFile": "Eksportuj plik","namingEmpty": "Nazwa nie może być pusta","recentCreated": "Ostatnio utworzone",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex ea8f5bcf8f..bbf2f3f294 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Usar a cor padrão do tema","useSVGDefaultIcon": "Usar ícones SVG","useSVGDefaultIconTip": "Usar ícones SVG para cadernos e documentos sem um ícone personalizado","bootAppearance": "Aparência da tela de inicialização",@@ -6,9 +7,7 @@"monospaceFont": "Fonte monoespaçada","monospaceFontTip": "Usada em blocos de código, código em linha e números de linha de blocos de código; quando nenhuma fonte é selecionada, a fonte do tema é usada","manageColors": "Gerenciar cores",- "manageBuiltinColors": "Gerenciar cores integradas","showInColorPicker": "Mostrar no seletor de cores",- "resetAll": "Redefinir tudo","exportFile": "Exportar arquivo","namingEmpty": "O nome não pode ficar vazio","recentCreated": "Criados recentemente",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 9e84020ae3..fed65dca70 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Использовать цвет темы по умолчанию","useSVGDefaultIcon": "Использовать значки SVG","useSVGDefaultIconTip": "Использовать значки SVG для блокнотов и документов без пользовательского значка","bootAppearance": "Вид страницы запуска",@@ -6,9 +7,7 @@"monospaceFont": "Моноширинный шрифт","monospaceFontTip": "Используется для блоков кода, встроенного кода и номеров строк в блоках кода; если шрифт не выбран, используется шрифт темы","manageColors": "Управление цветами",- "manageBuiltinColors": "Управление встроенными цветами","showInColorPicker": "Показывать в палитре цветов",- "resetAll": "Сбросить всё","exportFile": "Экспортировать файл","namingEmpty": "Имя не может быть пустым","recentCreated": "Недавно созданные",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 3a2fc1bb2c..6ee79087b0 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Použiť predvolenú farbu témy","useSVGDefaultIcon": "Používať ikony SVG","useSVGDefaultIconTip": "Používať ikony SVG pre zápisníky a dokumenty bez vlastnej ikony","bootAppearance": "Vzhľad úvodnej stránky",@@ -6,9 +7,7 @@"monospaceFont": "Písmo s pevnou šírkou","monospaceFontTip": "Používa sa pre bloky kódu, riadkový kód a čísla riadkov v blokoch kódu; ak nie je vybrané žiadne písmo, použije sa písmo témy","manageColors": "Spravovať farby",- "manageBuiltinColors": "Spravovať vstavané farby","showInColorPicker": "Zobraziť vo výbere farieb",- "resetAll": "Obnoviť všetko","exportFile": "Exportovať súbor","namingEmpty": "Názov nemôže byť prázdny","recentCreated": "Nedávno vytvorené",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 42bdd39b30..013be58dda 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "ใช้สีเริ่มต้นของธีม","useSVGDefaultIcon": "ใช้ไอคอน SVG","useSVGDefaultIconTip": "ใช้ไอคอน SVG สำหรับสมุดบันทึกและเอกสารที่ไม่มีไอคอนแบบกำหนดเอง","bootAppearance": "รูปลักษณ์หน้าเริ่มต้น",@@ -6,9 +7,7 @@"monospaceFont": "แบบอักษรความกว้างคงที่","monospaceFontTip": "ใช้สำหรับบล็อกโค้ด โค้ดในบรรทัด และหมายเลขบรรทัดของบล็อกโค้ด หากไม่ได้เลือกแบบอักษร ระบบจะใช้แบบอักษรของธีม","manageColors": "จัดการสี",- "manageBuiltinColors": "จัดการสีในตัว","showInColorPicker": "แสดงในตัวเลือกสี",- "resetAll": "รีเซ็ตทั้งหมด","exportFile": "ส่งออกไฟล์","namingEmpty": "ชื่อต้องไม่ว่างเปล่า","recentCreated": "สร้างล่าสุด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 96affbd26d..face9e89d0 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Temanın varsayılan rengini kullan","useSVGDefaultIcon": "SVG simgelerini kullan","useSVGDefaultIconTip": "Özel simgesi olmayan not defterleri ve belgeler için SVG simgelerini kullan","bootAppearance": "Başlangıç sayfası görünümü",@@ -6,9 +7,7 @@"monospaceFont": "Eş aralıklı yazı tipi","monospaceFontTip": "Kod blokları, satır içi kod ve kod bloğu satır numaraları için kullanılır; hiçbir yazı tipi seçilmediğinde temanın yazı tipi kullanılır","manageColors": "Renkleri yönet",- "manageBuiltinColors": "Yerleşik renkleri yönet","showInColorPicker": "Renk seçicide göster",- "resetAll": "Tümünü sıfırla","exportFile": "Dosyayı dışa aktar","namingEmpty": "Ad boş olamaz","recentCreated": "Yakın zamanda oluşturulanlar",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 4613579b08..639448ee0a 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "Використовувати типовий колір теми","useSVGDefaultIcon": "Використовувати значки SVG","useSVGDefaultIconTip": "Використовувати значки SVG для блокнотів і документів без власного значка","bootAppearance": "Вигляд сторінки запуску",@@ -6,9 +7,7 @@"monospaceFont": "Моноширинний шрифт","monospaceFontTip": "Використовується для блоків коду, вбудованого коду та номерів рядків у блоках коду; якщо шрифт не вибрано, використовується шрифт теми","manageColors": "Керування кольорами",- "manageBuiltinColors": "Керування вбудованими кольорами","showInColorPicker": "Показувати в палітрі кольорів",- "resetAll": "Скинути все","exportFile": "Експортувати файл","namingEmpty": "Назва не може бути порожньою","recentCreated": "Нещодавно створені",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 12b6c86942..760fb9564d 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "使用主题默认颜色","useSVGDefaultIcon": "使用 SVG 图标","useSVGDefaultIconTip": "为未自定义图标的笔记本和文档使用 SVG 图标","bootAppearance": "启动页外观",@@ -6,9 +7,7 @@"monospaceFont": "等宽字体","monospaceFontTip": "用于代码块、行内代码和代码块行号,不选择任何字体时使用主题自带字体","manageColors": "管理颜色",- "manageBuiltinColors": "管理内置颜色","showInColorPicker": "在颜色选择器中显示",- "resetAll": "全部重置","exportFile": "导出文件","namingEmpty": "命名不能为空","recentCreated": "最近创建",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 6f49c5e66c..c69a0cfb90 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "useThemeDefaultColor": "使用主題預設顏色","useSVGDefaultIcon": "使用 SVG 圖示","useSVGDefaultIconTip": "為未自訂圖示的筆記本與文件使用 SVG 圖示","bootAppearance": "啟動頁外觀",@@ -6,9 +7,7 @@"monospaceFont": "等寬字型","monospaceFontTip": "用於程式碼區塊、行內程式碼與程式碼區塊行號,未選擇任何字型時使用主題內建字型","manageColors": "管理顏色",- "manageBuiltinColors": "管理內建顏色","showInColorPicker": "在顏色選擇器中顯示",- "resetAll": "全部重設","exportFile": "導出檔案","namingEmpty": "命名不能為空","recentCreated": "最近建立",diff --git a/app/src/assets/scss/component/_list.scss b/app/src/assets/scss/component/_list.scssindex 9d2ba0fa1c..3e546699fe 100644--- a/app/src/assets/scss/component/_list.scss+++ b/app/src/assets/scss/component/_list.scss@@ -2,6 +2,8 @@@use "../util/function";.b3-list {+ --file-toggle-width: 0px;+mark {background-color: var(--b3-protyle-inline-mark-background);color: var(--b3-protyle-inline-mark-color);diff --git a/app/src/dialog/themeColorEditor.ts b/app/src/dialog/themeColorEditor.tsindex 2831e0a9f9..e4136681a6 100644--- a/app/src/dialog/themeColorEditor.ts+++ b/app/src/dialog/themeColorEditor.ts@@ -22,29 +22,27 @@ const DEFAULT_THEME_COLOR_VALUE: IThemeColorValue = {},};-export const getThemeColorEditorHTML = () => `<div data-type="themeColorEditor" class="b3-label b3-label--inner fn__flex" style="align-items:flex-start;gap:24px;flex-wrap:wrap">- <div class="fn__flex-1" style="min-width:200px">- <div>${window.siyuan.languages.themeLight}</div>- <label class="fn__flex" data-property="color" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>- <input class="b3-text-field" data-field="lightColor" type="color">+const getThemeColorGroupHTML = (title: string, colorField: string, backgroundField: string) =>+ `<div class="fn__flex-1">+ <div>${title}</div>+ <div class="fn__hr"></div>+ <label class="fn__flex" data-property="color">+ <span class="fn__flex-center">${window.siyuan.languages.colorFont}</span>+ <span class="fn__space"></span>+ <input class="b3-text-field fn__flex-center" data-field="${colorField}" type="color"></label>- <label class="fn__flex" data-property="backgroundColor" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>- <input class="b3-text-field" data-field="lightBackgroundColor" type="color">+ <div class="fn__hr"></div>+ <label class="fn__flex" data-property="backgroundColor">+ <span class="fn__flex-center">${window.siyuan.languages.colorPrimary}</span>+ <span class="fn__space"></span>+ <input class="b3-text-field fn__flex-center" data-field="${backgroundField}" type="color"></label>- </div>- <div class="fn__flex-1" style="min-width:200px">- <div>${window.siyuan.languages.themeDark}</div>- <label class="fn__flex" data-property="color" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>- <input class="b3-text-field" data-field="darkColor" type="color">- </label>- <label class="fn__flex" data-property="backgroundColor" style="align-items:center;margin-top:8px">- <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>- <input class="b3-text-field" data-field="darkBackgroundColor" type="color">- </label>- </div>+ </div>`;++export const getThemeColorEditorHTML = () => `<div data-type="themeColorEditor" class="b3-label b3-label--inner fn__flex fn__flex-wrap">+ ${getThemeColorGroupHTML(window.siyuan.languages.themeLight, "lightColor", "lightBackgroundColor")}+ <div class="fn__space"></div>+ ${getThemeColorGroupHTML(window.siyuan.languages.themeDark, "darkColor", "darkBackgroundColor")}</div>`;export const bindThemeColorEditor = (element: Element) => {diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 15762b2b46..87e574a4aa 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -31,15 +31,14 @@ import {getBuiltinInlineStyleIDFromValue,getBuiltinInlineStylePreview,getBuiltinInlineStylePropertyValue,+ getInlineStyleByID,getInlineStyleByValue,getInlineStyleIDFromValue,getInlineStylePreview,getInlineStylesCache,- getInlineStyleType,- getVisibleBuiltinInlineStyleIDs,+ getVisibleOrderedStyleKeys,isBuiltinInlineStyleVisible,- INLINE_BACKGROUND_COLORS,- INLINE_FONT_COLORS,+ isBuiltinOrderKey,TBuiltinInlineStyleID,TInlineStyleType,} from "../../protyle/toolbar/inlineStyle";@@ -380,55 +379,51 @@ const getBuiltinStyleCSS = (id: TBuiltinInlineStyleID) =>`background-color: ${getBuiltinInlineStylePropertyValue(id, "backgroundColor")};`;export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {- let colorHTML = "";- INLINE_FONT_COLORS.forEach((item, index) => {- if (index > 0 && !isBuiltinInlineStyleVisible("color", index)) {- return;- }- colorHTML += `<button class="keyboard__slash-item" data-type="color">- <span class="keyboard__slash-icon" ${item ? `style="color:${item}"` : ""}>A</span>- <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${item ? index : window.siyuan.languages.default}</span>+ const renderOrderedItems = (type: TInlineStyleType) => {+ const data = getInlineStylesCache();+ return getVisibleOrderedStyleKeys(type, data).map(key => {+ if (isBuiltinOrderKey(type, key)) {+ if (type === "color") {+ const index = Number(key);+ return `<button class="keyboard__slash-item" data-type="color">+ <span class="keyboard__slash-icon" style="color:var(--b3-font-color${index})">A</span>+ <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${index}</span></button>`;- });- let bgHTML = "";- INLINE_BACKGROUND_COLORS.forEach((item, index) => {- if (index > 0 && !isBuiltinInlineStyleVisible("backgroundColor", index)) {- return;- }- bgHTML += `<button class="keyboard__slash-item" data-type="backgroundColor">- <span class="keyboard__slash-icon" ${item ? `style="background-color:${item}"` : ""}>A</span>- <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${item ? index : window.siyuan.languages.default}</span>+ }+ if (type === "backgroundColor") {+ const index = Number(key);+ return `<button class="keyboard__slash-item" data-type="backgroundColor">+ <span class="keyboard__slash-icon" style="background-color:var(--b3-font-background${index})">A</span>+ <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${index}</span></button>`;- });- let builtinStyleHTML = "";- getVisibleBuiltinInlineStyleIDs().forEach(id => {- const preview = getBuiltinInlineStylePreview(id);- builtinStyleHTML += `<button class="keyboard__slash-item" data-type="style1">+ }+ const preview = getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID);+ return `<button class="keyboard__slash-item" data-type="style1"><span class="keyboard__slash-icon" style="color:${preview.color};background-color:${preview.backgroundColor};">A</span>- <span class="keyboard__slash-text">${getBuiltinStyleLabel(id)}</span>+ <span class="keyboard__slash-text">${getBuiltinStyleLabel(key as TBuiltinInlineStyleID)}</span></button>`;- });- let customColorHTML = "";- let customBackgroundHTML = "";- let customStyleHTML = "";- getInlineStylesCache().styles.forEach(style => {- const type = getInlineStyleType(style);- if (!type) {- return;- }- const preview = getInlineStylePreview(style);- const html = `<button class="keyboard__slash-item" data-type="${type}" data-inline-style-id="${style.id}">+ }+ const style = getInlineStyleByID(key, data);+ if (!style) {+ return "";+ }+ const preview = getInlineStylePreview(style);+ return `<button class="keyboard__slash-item" data-type="${type}" data-inline-style-id="${style.id}"><span class="keyboard__slash-icon" style="${preview.color ? `color:${preview.color};` : ""}${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}">A</span><span class="keyboard__slash-text">${escapeHtml(style.name)}</span></button>`;- if (type === "color") {- customColorHTML += html;- } else if (type === "backgroundColor") {- customBackgroundHTML += html;- } else {- customStyleHTML += html;- }- });+ }).join("");+ };+ let colorHTML = `<button class="keyboard__slash-item" data-type="color">+ <span class="keyboard__slash-icon">A</span>+ <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${window.siyuan.languages.default}</span>+</button>`;+ colorHTML += renderOrderedItems("color");+ let bgHTML = `<button class="keyboard__slash-item" data-type="backgroundColor">+ <span class="keyboard__slash-icon">A</span>+ <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${window.siyuan.languages.default}</span>+</button>`;+ bgHTML += renderOrderedItems("backgroundColor");const getManageHTML = (type: TInlineStyleType) => window.siyuan.config.readonly || window.siyuan.isPublish ? "" :`<button class="keyboard__slash-item" data-action="manageInlineStyle" data-inline-style-type="${type}"><svg class="keyboard__slash-icon"><use xlink:href="#iconSettings"></use></svg>@@ -523,20 +518,17 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {<span class="keyboard__slash-icon">A</span><span class="keyboard__slash-text">${window.siyuan.languages.color} ${window.siyuan.languages.default}</span></button>- ${builtinStyleHTML}- ${customStyleHTML}+ ${renderOrderedItems("style1")}${getManageHTML("style1")}</div><div data-id="colorFont" class="keyboard__slash-title">${window.siyuan.languages.colorFont}</div><div data-id="colorFontWrap" class="keyboard__slash-block">${colorHTML}- ${customColorHTML}${getManageHTML("color")}</div><div data-id="colorPrimary" class="keyboard__slash-title">${window.siyuan.languages.colorPrimary}</div><div data-id="colorPrimaryWrap" class="keyboard__slash-block">${bgHTML}- ${customBackgroundHTML}${getManageHTML("backgroundColor")}</div><div data-id="fontStyle" class="keyboard__slash-title">${window.siyuan.languages.fontStyle}</div>diff --git a/app/src/protyle/render/av/color.test.ts b/app/src/protyle/render/av/color.test.tsindex 5571fb53cf..e5d2d97be5 100644--- a/app/src/protyle/render/av/color.test.ts+++ b/app/src/protyle/render/av/color.test.ts@@ -7,6 +7,7 @@ import {getAVColorStyle,getNextAVOptionColor,normalizeAVColorIndex,+ normalizeAVColorOrder,} from "./color";import {INLINE_STYLE_EMPTY, setInlineStylesCache} from "../../toolbar/inlineStyle";@@ -35,6 +36,7 @@ describe("AV color indexes", () => {it("cycles new options through built-in colors", () => {assert.equal(getNextAVOptionColor(0), "1");+ assert.equal(getNextAVOptionColor(13), "14");assert.equal(getNextAVOptionColor(14), "1");});@@ -53,7 +55,7 @@ describe("AV color indexes", () => {assert.equal(getNextAVOptionColor(12), "14");const html = getAVColorGridHTML([], "1", "Manage");assert.doesNotMatch(html, /data-color="1"/);- assert.match(html, /data-color="14"/);+ assert.match(html, /data-color="14" class="color__square" style="background-color:var\(--b3-font-background14\);color:var\(--b3-font-color14\)"/);});it("finds the first available custom index", () => {@@ -69,9 +71,12 @@ describe("AV resolved colors", () => {"light-dark(#ddeeff, #223344)");});- it("uses numbered variables for built-ins and a neutral fallback for unresolved custom colors", () => {+ it("uses numbered variables for built-ins including undefined 14", () => {assert.equal(getAVColorStyle("13"),"background-color:var(--b3-font-background13);color:var(--b3-font-color13)");+ assert.equal(getAVColorStyle("14"),+ "background-color:var(--b3-font-background14);color:var(--b3-font-color14)");+ assert.equal(getAVBackgroundColor("14"), "var(--b3-font-background14)");assert.equal(getAVColorStyle("42"),"background-color:var(--b3-font-background14);color:var(--b3-font-color14)");assert.equal(getAVBackgroundColor("42"), "var(--b3-font-background14)");@@ -84,11 +89,35 @@ describe("AV resolved colors", () => {}), "background-color:var(--b3-font-background14);color:var(--b3-font-color14)");});+ it("uses workspace custom color variables without inlining hex", () => {+ setInlineStylesCache({+ ...INLINE_STYLE_EMPTY,+ av: {+ colors: [customColor],+ order: INLINE_STYLE_EMPTY.av.order,+ },+ });+ assert.equal(getAVColorStyle("15"),+ "background-color:var(--b3-font-background15);color:var(--b3-font-color15)");+ assert.equal(getAVBackgroundColor("15"), "var(--b3-font-background15)");+ });+it("renders multi-digit custom swatches and the management entry", () => {const html = getAVColorGridHTML([customColor], "15", "Manage");assert.match(html, /type="button" data-color="15" class="color__square color__square--current"/);assert.match(html, /data-type="manageAVCustomColors"/);assert.match(html, /<svg class="svg--mid"><use xlink:href="#iconSettings"><\/use><\/svg>/);assert.match(html, /light-dark\(#ddeeff, #223344\)/);+ assert.match(html, /data-color="14" class="color__square" style="background-color:var\(--b3-font-background14\);color:var\(--b3-font-color14\)"/);+ });++ it("renders mixed order and skips hidden custom colors", () => {+ const hiddenColor: IAVCustomColor = {...customColor, index: 16, hidden: true};+ const html = getAVColorGridHTML([customColor, hiddenColor], "15", "Manage", ["15", "1", "14"]);+ const colors = [...html.matchAll(/data-color="(\d+)"/g)].map(match => match[1]);+ assert.deepEqual(colors.slice(0, 3), ["15", "1", "14"]);+ assert.doesNotMatch(html, /data-color="16"/);+ assert.deepEqual(normalizeAVColorOrder(["15", "1", "15", "99", "14"], [customColor]),+ ["15", "1", "14", ...Array.from({length: 12}, (_, index) => (index + 2).toString())]);});});diff --git a/app/src/protyle/render/av/color.ts b/app/src/protyle/render/av/color.tsindex ab5a3584c9..5a82e69991 100644--- a/app/src/protyle/render/av/color.ts+++ b/app/src/protyle/render/av/color.ts@@ -1,10 +1,20 @@import {escapeAttr} from "../../../util/escape";-import {getVisibleBuiltinColorIndexes} from "../../toolbar/inlineStyle";--export const AV_BUILTIN_COLOR_COUNT = 14;-export const AV_CUSTOM_COLOR_MIN = 15;-export const AV_CUSTOM_COLOR_MAX = 78;-export const AV_CUSTOM_COLOR_LIMIT = 64;+import {+ AV_BUILTIN_COLOR_COUNT,+ AV_CUSTOM_COLOR_LIMIT,+ AV_CUSTOM_COLOR_MAX,+ AV_CUSTOM_COLOR_MIN,+ getInlineStylesCache,+ getVisibleBuiltinColorIndexes,+ isBuiltinInlineStyleVisible,+} from "../../toolbar/inlineStyle";++export {+ AV_BUILTIN_COLOR_COUNT,+ AV_CUSTOM_COLOR_LIMIT,+ AV_CUSTOM_COLOR_MAX,+ AV_CUSTOM_COLOR_MIN,+};export const AV_MANAGE_CUSTOM_COLORS_TYPE = "manageAVCustomColors";type TAVColorReference = string | {@@ -35,6 +45,12 @@ const isResolvedColor = (color: IAVColor | undefined): color is IAVColor => !!coconst getModeColor = (light: string, dark: string) => `light-dark(${light}, ${dark})`;+const cssVarsForIndex = (index: number) =>+ `background-color:var(--b3-font-background${index});color:var(--b3-font-color${index})`;++const hasWorkspaceCustomColor = (index: number) =>+ getInlineStylesCache().av.colors.some(item => item.index === index);+export const getAVColorStyle = (value: TAVColorReference) => {const reference = getColorReference(value);if (isResolvedColor(reference.resolvedColor)) {@@ -42,9 +58,14 @@ export const getAVColorStyle = (value: TAVColorReference) => {reference.resolvedColor.dark.backgroundColor)};color:${getModeColor(reference.resolvedColor.light.color,reference.resolvedColor.dark.color)}`;}- const normalizedIndex = normalizeAVColorIndex(reference.color || AV_BUILTIN_COLOR_COUNT);- const index = normalizedIndex > AV_BUILTIN_COLOR_COUNT ? AV_BUILTIN_COLOR_COUNT : normalizedIndex;- return `background-color:var(--b3-font-background${index});color:var(--b3-font-color${index})`;+ const index = normalizeAVColorIndex(reference.color || AV_BUILTIN_COLOR_COUNT);+ if (index > AV_BUILTIN_COLOR_COUNT && hasWorkspaceCustomColor(index)) {+ return cssVarsForIndex(index);+ }+ if (index > AV_BUILTIN_COLOR_COUNT) {+ return cssVarsForIndex(AV_BUILTIN_COLOR_COUNT);+ }+ return cssVarsForIndex(index);};export const getAVBackgroundColor = (value: TAVColorReference) => {@@ -54,11 +75,20 @@ export const getAVBackgroundColor = (value: TAVColorReference) => {reference.resolvedColor.dark.backgroundColor);}const index = normalizeAVColorIndex(reference.color || AV_BUILTIN_COLOR_COUNT);- return `var(--b3-font-background${index > AV_BUILTIN_COLOR_COUNT ? AV_BUILTIN_COLOR_COUNT : index})`;+ if (index > AV_BUILTIN_COLOR_COUNT && hasWorkspaceCustomColor(index)) {+ return `var(--b3-font-background${index})`;+ }+ if (index > AV_BUILTIN_COLOR_COUNT) {+ return `var(--b3-font-background${AV_BUILTIN_COLOR_COUNT})`;+ }+ return `var(--b3-font-background${index})`;};export const getNextAVOptionColor = (optionCount: number) => {- const colors = [...getVisibleBuiltinColorIndexes("av"), AV_BUILTIN_COLOR_COUNT];+ const colors = getVisibleBuiltinColorIndexes("av");+ if (colors.length === 0) {+ return AV_BUILTIN_COLOR_COUNT.toString();+ }return colors[Math.max(0, optionCount) % colors.length].toString();};@@ -76,23 +106,60 @@ const normalizeAVCustomColors = (colors: IAVCustomColor[]) => colors.sort((a, b) => a.index - b.index).slice(0, AV_CUSTOM_COLOR_LIMIT);-export const getAVCustomColors = (data: IAV | undefined) => normalizeAVCustomColors(data?.customColors || []);+export const getDefaultAVColorOrder = (customColors: Pick<IAVCustomColor, "index">[] = []) => [+ ...Array.from({length: AV_BUILTIN_COLOR_COUNT}, (_, index) => (index + 1).toString()),+ ...normalizeAVCustomColors(customColors as IAVCustomColor[]).map(item => item.index.toString()),+];++export const normalizeAVColorOrder = (order: string[] | undefined, customColors: Pick<IAVCustomColor, "index">[] = []) => {+ const allowed = new Set(getDefaultAVColorOrder(customColors));+ const result: string[] = [];+ const seen = new Set<string>();+ (order || []).forEach(key => {+ if (typeof key !== "string" || !allowed.has(key) || seen.has(key)) {+ return;+ }+ seen.add(key);+ result.push(key);+ });+ getDefaultAVColorOrder(customColors).forEach(key => {+ if (!seen.has(key)) {+ result.push(key);+ }+ });+ return result;+};++export const getAVCustomColors = () => getInlineStylesCache().av.colors;-export const getAVResolvedColor = (data: IAV | undefined, color: string) => {+export const getAVColorOrder = () =>+ normalizeAVColorOrder(getInlineStylesCache().av.order, getAVCustomColors());++export const getAVResolvedColor = (color: string) => {const index = normalizeAVColorIndex(color);- return getAVCustomColors(data).find(item => item.index === index);+ return getAVCustomColors().find(item => item.index === index);};export const getAVColorGridHTML = (customColors: IAVCustomColor[], currentColor: string,- manageLabel: string) => {+ manageLabel: string, order?: string[]) => {const currentIndex = normalizeAVColorIndex(currentColor);- const colors: TAVColorReference[] = [...getVisibleBuiltinColorIndexes("av"), AV_BUILTIN_COLOR_COUNT]- .map(index => ({color: index.toString()}));- normalizeAVCustomColors(customColors).forEach(item => {- colors.push({- color: item.index.toString(),- resolvedColor: item,- });+ const colors: TAVColorReference[] = [];+ const customByIndex = new Map(normalizeAVCustomColors(customColors).map(item => [item.index.toString(), item]));+ normalizeAVColorOrder(order, customColors).forEach(key => {+ const index = Number(key);+ if (index >= 1 && index <= AV_BUILTIN_COLOR_COUNT) {+ if (isBuiltinInlineStyleVisible("av", index)) {+ colors.push({color: key});+ }+ return;+ }+ const custom = customByIndex.get(key);+ if (custom && !custom.hidden) {+ colors.push({+ color: custom.index.toString(),+ resolvedColor: custom,+ });+ }});const colorHTML = colors.map(item => {const reference = getColorReference(item);diff --git a/app/src/protyle/render/av/colorDialog.ts b/app/src/protyle/render/av/colorDialog.tsindex c635f7a066..65018af269 100644--- a/app/src/protyle/render/av/colorDialog.ts+++ b/app/src/protyle/render/av/colorDialog.ts@@ -2,21 +2,40 @@ import {Dialog} from "../../../dialog";import {confirmDialog} from "../../../dialog/confirmDialog";import {showMessage} from "../../../dialog/message";import {bindThemeColorEditor, getThemeColorEditorHTML} from "../../../dialog/themeColorEditor";-import {escapeAttr, escapeHtml} from "../../../util/escape";import {isMobile} from "../../../util/functions";-import {transaction} from "../../wysiwyg/transaction";import {AV_CUSTOM_COLOR_LIMIT,getAvailableAVCustomColorIndex,+ getAVColorOrder,getAVColorStyle,getAVCustomColors,+ normalizeAVColorOrder,} from "./color";-import {getInlineStyleType, getInlineStylesCache} from "../../toolbar/inlineStyle";-import {openBuiltinColorDialog} from "../../toolbar/builtinColorDialog";-import * as dayjs from "dayjs";+import {+ getInlineStylesCache,+ IInlineStyles,+ normalizeInlineStyles,+ saveWorkspaceAVPalette,+} from "../../toolbar/inlineStyle";+import {+ applyPreviewStyle,+ bindBuiltinEditor,+ bindColorListDrag,+ createBuiltinDialogEntry,+ getBuiltinEditorHTML,+ getColorListItemHTML,+ getProperties,+ isEntryCustomized,+ isEntryDefault,+ resetEntry,+ writeBuiltinEntry,+} from "../../toolbar/builtinColorDialog";const cloneCustomColors = (colors: IAVCustomColor[]) => JSON.parse(JSON.stringify(colors)) as IAVCustomColor[];+const cloneInlineStyles = () =>+ JSON.parse(JSON.stringify(normalizeInlineStyles(getInlineStylesCache()))) as IInlineStyles;+export const openAVCustomColorDialog = (options: {protyle: IProtyle,data: IAV,@@ -25,109 +44,158 @@ export const openAVCustomColorDialog = (options: {if (window.siyuan.config.readonly || window.siyuan.isPublish) {return;}- const originalColors = cloneCustomColors(getAVCustomColors(options.data));- const draft = cloneCustomColors(originalColors);+ const draft = cloneCustomColors(getAVCustomColors());+ let orderDraft = [...getAVColorOrder()];+ const builtinDraft = cloneInlineStyles();+ const modifiedBuiltinIndexes = new Set<number>();const usedIndexes = new Set(options.data.usedCustomColorIndexes || []);- const appearanceStyles = getInlineStylesCache().styles.filter(style => getInlineStyleType(style) === "style1");- let editingIndex: number | undefined;+ const properties = getProperties("av");let editingColorIndex: number | undefined;+ let editingBuiltinKey: string | undefined;+ let saving = false;const dialog = new Dialog({title: window.siyuan.languages.manageColors,width: isMobile() ? "92vw" : "600px",- content: `<div class="b3-dialog__content" style="max-height:70vh;overflow:auto">+ content: `<div class="b3-dialog__content" style="max-height:70vh"><div data-panel="list">- <div data-type="avCustomColorList" class="b3-list b3-list--background fn__selectnone" style="--file-toggle-width:0px"></div>+ <div data-type="avCustomColorList" class="b3-list b3-list--background fn__selectnone"></div>+ <div class="fn__hr" data-type="listSpacer"></div><div class="fn__flex" data-type="avColorButtons">- <button class="b3-button b3-button--outline" data-action="manageBuiltin" type="button">- <svg><use xlink:href="#iconSettings"></use></svg>${window.siyuan.languages.manageBuiltinColors}- </button>- <div class="fn__space"></div>- <button class="b3-button b3-button--outline" data-action="new" type="button">- <svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.new}- </button>+ <button class="b3-button b3-button--outline" data-action="new" type="button">+ <svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.new}+ </button></div></div>- <div data-panel="editor" class="fn__none">+ <div data-panel="customEditor" class="fn__none"><div class="b3-label b3-label--inner" data-field="colorIndex"></div>- ${appearanceStyles.length > 0 ? `<label class="b3-label b3-label--inner fn__flex" style="align-items:center">- <span style="min-width:96px">${window.siyuan.languages.appearance}</span>- <select class="b3-select fn__flex-1" data-field="appearance" style="margin-top:0">- <option value="">${window.siyuan.languages.select}</option>- ${appearanceStyles.map((style, index) => `<option value="${index}">${escapeHtml(style.name)}</option>`).join("")}- </select>- </label>` : ""}${getThemeColorEditorHTML()}</div>+ <div data-panel="builtinEditor" class="fn__none">+ ${getBuiltinEditorHTML("av")}+ </div></div><div class="b3-dialog__action">+ <button class="b3-button b3-button--outline fn__none" data-action="reset" type="button">${window.siyuan.languages.reset}</button>+ <div class="fn__flex-1"></div><button class="b3-button b3-button--cancel" data-action="cancel" type="button">${window.siyuan.languages.cancel}</button><div class="fn__space"></div><button class="b3-button b3-button--text" data-action="save" type="button">${window.siyuan.languages.save}</button></div>`,});const listPanel = dialog.element.querySelector('[data-panel="list"]') as HTMLElement;- const editorPanel = dialog.element.querySelector('[data-panel="editor"]') as HTMLElement;+ const customEditorPanel = dialog.element.querySelector('[data-panel="customEditor"]') as HTMLElement;+ const builtinEditorPanel = dialog.element.querySelector('[data-panel="builtinEditor"]') as HTMLElement;const listElement = dialog.element.querySelector('[data-type="avCustomColorList"]') as HTMLElement;const newElement = dialog.element.querySelector('[data-action="new"]') as HTMLButtonElement;- const buttonsElement = dialog.element.querySelector('[data-type="avColorButtons"]') as HTMLElement;+ const resetElement = dialog.element.querySelector('[data-action="reset"]') as HTMLButtonElement;const cancelElement = dialog.element.querySelector('[data-action="cancel"]') as HTMLButtonElement;const saveElement = dialog.element.querySelector('[data-action="save"]') as HTMLButtonElement;const colorIndexElement = dialog.element.querySelector('[data-field="colorIndex"]') as HTMLElement;- const themeColorEditor = bindThemeColorEditor(editorPanel);- const appearanceElement = dialog.element.querySelector('[data-field="appearance"]') as HTMLSelectElement;+ const themeColorEditor = bindThemeColorEditor(customEditorPanel);++ const getListKeys = () => normalizeAVColorOrder(orderDraft, draft);+ const findCustomColor = (index: number) => draft.find(item => item.index === index);+ const getBuiltinEntry = (key: string) => createBuiltinDialogEntry("av", Number(key), builtinDraft);+ const writeBuiltinDraft = (entry: ReturnType<typeof createBuiltinDialogEntry>) => {+ writeBuiltinEntry(builtinDraft, "av", entry);+ modifiedBuiltinIndexes.add(Number(entry.key));+ };++ const builtinEditor = bindBuiltinEditor(builtinEditorPanel, "av", () =>+ editingBuiltinKey ? getBuiltinEntry(editingBuiltinKey) : undefined);const renderList = () => {- listElement.innerHTML = draft.map((color, index) => {- const used = usedIndexes.has(color.index);- return `<div class="b3-list-item b3-list-item--narrow" data-index="${index}">- <span class="color__square color__square--list" style="${getAVColorStyle({- color: color.index.toString(),- resolvedColor: color,- })}">A</span>- <span class="b3-list-item__text">${window.siyuan.languages.color} ${color.index}</span>- <span class="b3-list-item__action ariaLabel" data-action="edit" data-index="${index}" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.edit)}"><svg><use xlink:href="#iconEdit"></use></svg></span>- <span class="b3-list-item__action b3-list-item__action--warning ariaLabel" data-action="delete" data-index="${index}" data-position="north" aria-disabled="${used}"${used ? ' style="cursor:not-allowed;opacity:.38"' : ""} aria-label="${escapeAttr(window.siyuan.languages.delete)}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>-</div>`;+ const keys = getListKeys();+ listElement.innerHTML = keys.map((key, index) => {+ const colorIndex = Number(key);+ const custom = findCustomColor(colorIndex);+ if (custom) {+ return getColorListItemHTML({+ kind: "custom",+ key,+ index,+ label: `${window.siyuan.languages.color} ${custom.index}`,+ previewStyle: getAVColorStyle({+ color: custom.index.toString(),+ resolvedColor: custom,+ }),+ show: !custom.hidden,+ canDelete: true,+ });+ }+ const entry = getBuiltinEntry(key);+ return getColorListItemHTML({+ kind: "builtin",+ key,+ index,+ label: entry.label,+ show: entry.show,+ customized: isEntryCustomized(entry, properties),+ resetHidden: isEntryDefault(entry, properties),+ });}).join("");+ listElement.querySelectorAll<HTMLElement>('[data-kind="builtin"][data-key]').forEach(item => {+ const preview = item.querySelector('[data-role="preview"]') as HTMLElement;+ if (preview) {+ applyPreviewStyle("av", preview, getBuiltinEntry(item.dataset.key));+ }+ });newElement.disabled = draft.length >= AV_CUSTOM_COLOR_LIMIT;- buttonsElement.style.marginTop = draft.length === 0 ? "0" : "8px";};- const setEditorActionMode = (editing: boolean) => {- cancelElement.dataset.action = editing ? "cancelEdit" : "cancel";- saveElement.dataset.action = editing ? "confirmEdit" : "save";- saveElement.textContent = editing ? window.siyuan.languages.confirm : window.siyuan.languages.save;+ const setEditorActionMode = (mode: "list" | "custom" | "builtin") => {+ listPanel.classList.toggle("fn__none", mode !== "list");+ customEditorPanel.classList.toggle("fn__none", mode !== "custom");+ builtinEditorPanel.classList.toggle("fn__none", mode !== "builtin");+ resetElement.classList.toggle("fn__none", mode !== "builtin");+ cancelElement.dataset.action = mode === "list" ? "cancel" : "cancelEdit";+ saveElement.dataset.action = mode === "list" ? "save" : "confirmEdit";+ saveElement.textContent = mode === "list" ? window.siyuan.languages.save : window.siyuan.languages.confirm;+ saveElement.removeAttribute("disabled");};+const showList = () => {- editingIndex = undefined;editingColorIndex = undefined;- editorPanel.classList.add("fn__none");- listPanel.classList.remove("fn__none");- setEditorActionMode(false);+ editingBuiltinKey = undefined;+ setEditorActionMode("list");renderList();};- const showEditor = (index?: number) => {- const color = typeof index === "number" ? draft[index] : undefined;- const colorIndex = color?.index || getAvailableAVCustomColorIndex(draft);- if (!colorIndex) {++ const showCustomEditor = (colorIndex?: number) => {+ const color = typeof colorIndex === "number" ? findCustomColor(colorIndex) : undefined;+ const nextIndex = color?.index || getAvailableAVCustomColorIndex(draft);+ if (!nextIndex) {showMessage(window.siyuan.languages.invalid, 6000, "error");return;}- editingIndex = index ?? -1;- editingColorIndex = colorIndex;- colorIndexElement.textContent = `${window.siyuan.languages.color} ${colorIndex}`;- if (appearanceElement) {- appearanceElement.value = "";- }+ editingColorIndex = nextIndex;+ editingBuiltinKey = undefined;+ colorIndexElement.textContent = `${window.siyuan.languages.color} ${nextIndex}`;themeColorEditor.setValue(color, "style1");- listPanel.classList.add("fn__none");- editorPanel.classList.remove("fn__none");- setEditorActionMode(true);+ setEditorActionMode("custom");};++ const showBuiltinEditor = (key: string) => {+ editingBuiltinKey = key;+ editingColorIndex = undefined;+ builtinEditor.fill(getBuiltinEntry(key));+ setEditorActionMode("builtin");+ };+const confirmEditor = () => {+ if (editingBuiltinKey) {+ writeBuiltinDraft(builtinEditor.commit(getBuiltinEntry(editingBuiltinKey)));+ showList();+ return;+ }+ if (typeof editingColorIndex !== "number") {+ return;+ }const value = themeColorEditor.getValue("style1");+ const previous = findCustomColor(editingColorIndex);const color: IAVCustomColor = {index: editingColorIndex,+ hidden: previous?.hidden,light: {color: value.light.color,backgroundColor: value.light.backgroundColor,@@ -137,37 +205,79 @@ export const openAVCustomColorDialog = (options: {backgroundColor: value.dark.backgroundColor,},};- if (editingIndex >= 0) {- draft[editingIndex] = color;+ if (previous) {+ draft[draft.indexOf(previous)] = color;} else {draft.push(color);- draft.sort((a, b) => a.index - b.index);+ if (!orderDraft.includes(color.index.toString())) {+ orderDraft.push(color.index.toString());+ }}showList();};- appearanceElement?.addEventListener("change", () => {- const style = appearanceStyles[parseInt(appearanceElement.value)];- if (style) {- themeColorEditor.setValue(style, "style1");+ bindColorListDrag(listElement, getListKeys, keys => {+ orderDraft = keys;+ renderList();+ });+ listElement.addEventListener("click", event => {+ if ((event.target as HTMLElement).closest('[data-action="toggleShow"]')) {+ event.stopPropagation();+ }+ });+ listElement.addEventListener("change", event => {+ const switchElement = (event.target as HTMLElement).closest<HTMLInputElement>('[data-action="toggleShow"]');+ const itemElement = switchElement?.closest<HTMLElement>("[data-key]");+ if (!switchElement || !itemElement) {+ return;+ }+ if (itemElement.dataset.kind === "builtin") {+ const entry = getBuiltinEntry(itemElement.dataset.key);+ entry.show = switchElement.checked;+ writeBuiltinDraft(entry);+ itemElement.querySelector('[data-action="resetItem"]')?.classList.toggle("fn__none", isEntryDefault(entry, properties));+ return;+ }+ const color = findCustomColor(Number(itemElement.dataset.key));+ if (color) {+ color.hidden = !switchElement.checked;}});- dialog.element.addEventListener("click", event => {+ dialog.element.addEventListener("click", async event => {const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");- if (!actionElement || actionElement.hasAttribute("disabled")) {+ if (!actionElement || actionElement.hasAttribute("disabled") || actionElement.classList.contains("fn__none")) {return;}const action = actionElement.dataset.action;- const index = parseInt(actionElement.dataset.index);+ if (action === "toggleShow") {+ event.stopPropagation();+ return;+ }+ const itemElement = actionElement.closest<HTMLElement>(".b3-list-item");+ const key = itemElement?.dataset.key;if (action === "new") {- showEditor();- } else if (action === "manageBuiltin") {- openBuiltinColorDialog("av");+ showCustomEditor();} else if (action === "edit") {- showEditor(index);- } else if (action === "delete") {- const color = draft[index];+ if (itemElement?.dataset.kind === "builtin" && key) {+ showBuiltinEditor(key);+ } else if (itemElement?.dataset.kind === "custom" && key) {+ showCustomEditor(Number(key));+ }+ } else if (action === "resetItem" && key) {+ const entry = getBuiltinEntry(key);+ resetEntry(entry, properties);+ writeBuiltinDraft(entry);+ renderList();+ } else if (action === "reset") {+ if (editingBuiltinKey) {+ const entry = getBuiltinEntry(editingBuiltinKey);+ resetEntry(entry, properties);+ writeBuiltinDraft(entry);+ showBuiltinEditor(editingBuiltinKey);+ }+ } else if (action === "delete" && key) {+ const color = findCustomColor(Number(key));if (!color) {return;}@@ -176,7 +286,8 @@ export const openAVCustomColorDialog = (options: {return;}confirmDialog(window.siyuan.languages.deleteOpConfirm, window.siyuan.languages.confirmDelete, () => {- draft.splice(index, 1);+ draft.splice(draft.indexOf(color), 1);+ orderDraft = orderDraft.filter(item => item !== key);renderList();}, undefined, true);} else if (action === "cancelEdit") {@@ -185,26 +296,40 @@ export const openAVCustomColorDialog = (options: {confirmEditor();} else if (action === "cancel") {dialog.destroy();- } else if (action === "save") {- transaction(options.protyle, [{- action: "setAttrViewCustomColors",- avID: options.data.id,- blockID: options.blockElement.dataset.nodeId,- data: draft,- }, {- action: "doUpdateUpdated",- id: options.blockElement.dataset.nodeId,- data: dayjs().format("YYYYMMDDHHmmss"),- }], [{- action: "setAttrViewCustomColors",- avID: options.data.id,- blockID: options.blockElement.dataset.nodeId,- data: originalColors,- }], {- callback: () => {- dialog.destroy();- },- });+ } else if (action === "save" && !saving) {+ saving = true;+ actionElement.setAttribute("disabled", "disabled");+ try {+ builtinDraft.av = {+ colors: cloneCustomColors(draft),+ order: normalizeAVColorOrder(orderDraft, draft),+ };+ const response = await saveWorkspaceAVPalette(builtinDraft.av,+ Array.from(modifiedBuiltinIndexes).map(index => {+ const color = builtinDraft.builtin.colors.find(item => item.index === index);+ return {+ index,+ customized: !!color,+ light: color?.light || {},+ dark: color?.dark || {},+ hidden: builtinDraft.builtin.hidden.av.includes(index),+ };+ }));+ if (response?.code !== 0) {+ showMessage(response?.msg || window.siyuan.languages.invalid, 6000, "error");+ saving = false;+ actionElement.removeAttribute("disabled");+ return;+ }+ options.data.customColors = cloneCustomColors(getInlineStylesCache().av.colors);+ options.data.colorOrder = [...getInlineStylesCache().av.order];+ void import("../../../util/assets").then(module => module.setInlineStyle());+ dialog.destroy();+ } catch (error) {+ showMessage(error instanceof Error ? error.message : window.siyuan.languages.invalid, 6000, "error");+ saving = false;+ actionElement.removeAttribute("disabled");+ }}event.preventDefault();event.stopPropagation();diff --git a/app/src/protyle/render/av/kanban/groupMenu.ts b/app/src/protyle/render/av/kanban/groupMenu.tsindex 612ecc1047..c7c294ca06 100644--- a/app/src/protyle/render/av/kanban/groupMenu.ts+++ b/app/src/protyle/render/av/kanban/groupMenu.ts@@ -8,6 +8,7 @@ import {AV_MANAGE_CUSTOM_COLORS_TYPE,applyAVColorPalette,getAVColorGridHTML,+ getAVColorOrder,getAVCustomColors,} from "../color";import {openAVCustomColorDialog} from "../colorDialog";@@ -37,7 +38,7 @@ export const openKanbanGroupMenu = (options: {if (!option) {return;}- applyAVColorPalette(menu.element, getAVCustomColors(data));+ applyAVColorPalette(menu.element, getAVCustomColors());menu.addItem({icon: "iconTrashcan",@@ -91,7 +92,7 @@ export const openKanbanGroupMenu = (options: {menu.addSeparator();const colorHTML = `<div class="b3-menu__labels">${window.siyuan.languages.color}</div><div class="fn__flex fn__flex-wrap" style="width:238px;max-height:238px;overflow:auto">${getAVColorGridHTML(- getAVCustomColors(data), option.color, window.siyuan.languages.manageColors)}</div>`;+ getAVCustomColors(), option.color, window.siyuan.languages.manageColors, getAVColorOrder())}</div>`;menu.addItem({type: "empty",iconHTML: "",diff --git a/app/src/protyle/render/av/locate.ts b/app/src/protyle/render/av/locate.tsindex 3d58b733b8..3d583bb2ba 100644--- a/app/src/protyle/render/av/locate.ts+++ b/app/src/protyle/render/av/locate.ts@@ -246,7 +246,7 @@ export const getAVLocateParams = (blockElement: HTMLElement, enabled = true) =>export const applyAVRenderContext = (blockElement: HTMLElement, data: IAV) => {blockElement.setAttribute(Constants.CUSTOM_SY_AV_VIEW, data.viewID);blockElement.setAttribute("data-av-type", data.viewType);- applyAVColorPalette(blockElement, getAVCustomColors(data));+ applyAVColorPalette(blockElement, getAVCustomColors());};export const persistAVLocateView = (blockElement: HTMLElement, protyle: IProtyle, data: IAV) => {diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex 55b927880b..1288ea468e 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -206,7 +206,7 @@ export const openMenuPanel = (options: {<div class="b3-menu${options.type === "filters" ? " av__filter-panel" : ""}${options.type === "relation" ? " av__relation-panel" : ""}" ${options.keepMenuOpen ? "data-menu=\"true\"" : ""} ${["select", "date", "asset", "relation", "rollup"].includes(options.type) ? `style="${["select", "asset", "relation"].includes(options.type) ? "max-height: calc(100vh - 32px);display: flex;flex-direction: column;" : ""}min-width: 200px;${options.type === "relation" ? `width: 760px;max-width: ${isMobile() ? "90vw" : "calc(100vw - 32px)"};` : isMobile() ? "max-width: 90vw;" : "max-width: 50vw;"}"` : ""}>${html}</div></div>`);avPanelElement = document.querySelector(".av__panel");- applyAVColorPalette(avPanelElement as HTMLElement, getAVCustomColors(data));+ applyAVColorPalette(avPanelElement as HTMLElement, getAVCustomColors());if (options.destroyCallback) {const renderedPanelElement = avPanelElement;const parentElement = renderedPanelElement.parentElement;diff --git a/app/src/protyle/render/av/select.ts b/app/src/protyle/render/av/select.tsindex 11a297cb63..b0836831fa 100644--- a/app/src/protyle/render/av/select.ts+++ b/app/src/protyle/render/av/select.ts@@ -19,6 +19,7 @@ import {AV_MANAGE_CUSTOM_COLORS_TYPE,applyAVColorPalette,getAVColorGridHTML,+ getAVColorOrder,getAVColorStyle,getAVCustomColors,getAVResolvedColor,@@ -276,7 +277,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,if (menu.isOpen) {return;}- applyAVColorPalette(menu.element, getAVCustomColors(data));+ applyAVColorPalette(menu.element, getAVCustomColors());menu.addItem({iconHTML: "",type: "empty",@@ -402,7 +403,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,});menu.addSeparator();const html = `<div class="fn__flex fn__flex-wrap" style="width:238px;max-height:238px;overflow:auto">${getAVColorGridHTML(- getAVCustomColors(data), color, window.siyuan.languages.manageColors)}</div>`;+ getAVCustomColors(), color, window.siyuan.languages.manageColors, getAVColorOrder())}</div>`;menu.addItem({type: "empty",iconHTML: "",@@ -458,7 +459,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,if (item.name === name) {item.name = inputElement.value;item.color = newColor;- item.resolvedColor = getAVResolvedColor(data, newColor);+ item.resolvedColor = getAVResolvedColor(newColor);return true;}});@@ -484,7 +485,7 @@ export const setColOption = (protyle: IProtyle, data: IAV, target: HTMLElement,if (item.content === name) {item.content = inputElement.value;item.color = newColor;- item.resolvedColor = getAVResolvedColor(data, newColor);+ item.resolvedColor = getAVResolvedColor(newColor);return true;}});@@ -606,7 +607,7 @@ export const addColOptionOrCell = (protyle: IProtyle, data: IAV, cellElements: Hconst cellDoOperations: IOperation[] = [];const cellUndoOperations: IOperation[] = [];const resolvedColor = colData.options.find(option => option.name === currentElement.dataset.name)?.resolvedColor ||- getAVResolvedColor(data, currentElement.dataset.color);+ getAVResolvedColor(currentElement.dataset.color);let mSelectValue: IAVCellSelectValue[];const batchMode = getAVBatchEditMode(cellElements[0]);cellElements.forEach((item, index) => {diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.tsindex 997f096895..6074dbbe95 100644--- a/app/src/protyle/toolbar/Font.ts+++ b/app/src/protyle/toolbar/Font.ts@@ -14,14 +14,15 @@ import {getBuiltinInlineStyleApplication,getBuiltinInlineStyleIDFromValue,getBuiltinInlineStylePreview,+ getInlineStyleApplication,+ getInlineStyleByID,getInlineStyleByValue,getInlineStyleIDFromValue,getInlineStylePreview,getInlineStylesCache,- getInlineStyleType,getRecentInlineStyleKey,- getVisibleBuiltinInlineStyleIDs,- isBuiltinInlineStyleVisible,+ getVisibleOrderedStyleKeys,+ isBuiltinOrderKey,INLINE_BACKGROUND_COLORS,INLINE_FONT_COLORS,TBuiltinInlineStyleID,@@ -125,51 +126,45 @@ export const convertFontSize = (fontSize: string, unit: "px" | "em", baseFontSizexport const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],onChange?: (type: string, color?: string) => void) => {- let colorHTML = "";- INLINE_FONT_COLORS.forEach((item, index) => {- if (index > 0 && !isBuiltinInlineStyleVisible("color", index)) {- return;- }- colorHTML += `<button ${item ? `class="color__square" style="color:${item}"` : `class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.default}"`} data-type="color">A</button>`;- });- let bgHTML = "";- INLINE_BACKGROUND_COLORS.forEach((item, index) => {- if (index > 0 && !isBuiltinInlineStyleVisible("backgroundColor", index)) {- return;- }- bgHTML += `<button ${item ? `class="color__square" style="background-color:${item}"` : `class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.default}"`} data-type="backgroundColor"></button>`;- });const builtinStyleLabels: Record<TBuiltinInlineStyleID, string> = {error: window.siyuan.languages.errorStyle,warning: window.siyuan.languages.warningStyle,info: window.siyuan.languages.infoStyle,success: window.siyuan.languages.successStyle,};- let builtinStyleHTML = "";- getVisibleBuiltinInlineStyleIDs().forEach(id => {- const preview = getBuiltinInlineStylePreview(id);- builtinStyleHTML += "<button class=\"color__square ariaLabel\" data-position=\"3south\" data-type=\"style1\" " +- `aria-label="${builtinStyleLabels[id]}" style="color:${preview.color};` +- `background-color:${preview.backgroundColor};">A</button>`;+ const renderOrderedButtons = (type: TInlineStyleType) => {+ const data = getInlineStylesCache();+ return getVisibleOrderedStyleKeys(type, data).map(key => {+ if (isBuiltinOrderKey(type, key)) {+ if (type === "color") {+ return `<button class="color__square" style="color:var(--b3-font-color${key})" data-type="color">A</button>`;+ }+ if (type === "backgroundColor") {+ return `<button class="color__square" style="background-color:var(--b3-font-background${key})" data-type="backgroundColor"></button>`;+ }+ const preview = getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID);+ return "<button class=\"color__square ariaLabel\" data-position=\"3south\" data-type=\"style1\" " ++ `aria-label="${builtinStyleLabels[key as TBuiltinInlineStyleID]}" style="color:${preview.color};` ++ `background-color:${preview.backgroundColor};">A</button>`;+ }+ const style = getInlineStyleByID(key, data);+ if (!style) {+ return "";+ }+ const preview = getInlineStylePreview(style);+ return `<button class="color__square ariaLabel" data-position="3south" aria-label="${escapeAttr(style.name)}" data-inline-style-id="${style.id}" data-type="${type}" style="${preview.color ? `color:${preview.color};` : ""}${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}">${type === "backgroundColor" ? "" : "A"}</button>`;+ }).join("");+ };+ let colorHTML = "";+ INLINE_FONT_COLORS.slice(0, 1).forEach(item => {+ colorHTML += `<button ${item ? `class="color__square" style="color:${item}"` : `class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.default}"`} data-type="color">A</button>`;});- let customColorHTML = "";- let customBackgroundHTML = "";- let customStyleHTML = "";- getInlineStylesCache().styles.forEach(style => {- const type = getInlineStyleType(style);- if (!type) {- return;- }- const preview = getInlineStylePreview(style);- const html = `<button class="color__square ariaLabel" data-position="3south" aria-label="${escapeAttr(style.name)}" data-inline-style-id="${style.id}" data-type="${type}" style="${preview.color ? `color:${preview.color};` : ""}${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}">${type === "backgroundColor" ? "" : "A"}</button>`;- if (type === "color") {- customColorHTML += html;- } else if (type === "backgroundColor") {- customBackgroundHTML += html;- } else {- customStyleHTML += html;- }+ colorHTML += renderOrderedButtons("color");+ let bgHTML = "";+ INLINE_BACKGROUND_COLORS.slice(0, 1).forEach(item => {+ bgHTML += `<button ${item ? `class="color__square" style="background-color:${item}"` : `class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.default}"`} data-type="backgroundColor"></button>`;});+ bgHTML += renderOrderedButtons("backgroundColor");const getManageHTML = (type: TInlineStyleType) => window.siyuan.config.readonly || window.siyuan.isPublish ? "" :`<button class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.manageColors}" data-action="manageInlineStyle" data-inline-style-type="${type}"><svg class="svg--mid"><use xlink:href="#iconSettings"></use></svg></button>`;@@ -241,8 +236,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],<div class="fn__hr--small"></div><div data-id="colorWrap" class="fn__flex fn__flex-wrap"><button class="color__square ariaLabel" data-position="3south" data-type="style1" aria-label="${window.siyuan.languages.default}">A</button>- ${builtinStyleHTML}- ${customStyleHTML}+ ${renderOrderedButtons("style1")}${getManageHTML("style1")}</div><div class="fn__hr"></div>@@ -250,7 +244,6 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],<div class="fn__hr--small"></div><div data-id="colorFontWrap" class="fn__flex fn__flex-wrap">${colorHTML}- ${customColorHTML}${getManageHTML("color")}</div><div class="fn__hr"></div>@@ -258,7 +251,6 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],<div class="fn__hr--small"></div><div data-id="colorPrimaryWrap" class="fn__flex fn__flex-wrap">${bgHTML}- ${customBackgroundHTML}${getManageHTML("backgroundColor")}</div><div class="fn__hr"></div>@@ -372,8 +364,13 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: strconst visibleFontStyles = filterHiddenRecentInlineStyles(localFontStyles);if (visibleFontStyles.length === 0) {type = "style1";- const builtinStyleID = getVisibleBuiltinInlineStyleIDs()[0];- color = builtinStyleID ? getBuiltinInlineStyleApplication(builtinStyleID).color : encodeStyle1();+ const firstKey = getVisibleOrderedStyleKeys("style1")[0];+ if (firstKey && isBuiltinOrderKey("style1", firstKey)) {+ color = getBuiltinInlineStyleApplication(firstKey as TBuiltinInlineStyleID).color;+ } else {+ const style = getInlineStyleByID(firstKey);+ color = (style && getInlineStyleApplication(style)?.color) || encodeStyle1();+ }} else {const fontStyles = visibleFontStyles[0].split(Constants.ZWSP);type = fontStyles.splice(0, 1)[0];diff --git a/app/src/protyle/toolbar/builtinColorDialog.ts b/app/src/protyle/toolbar/builtinColorDialog.tsindex 4a6796007e..1d3bc998d8 100644--- a/app/src/protyle/toolbar/builtinColorDialog.ts+++ b/app/src/protyle/toolbar/builtinColorDialog.ts@@ -1,44 +1,30 @@-import {Dialog} from "../../dialog";-import {showMessage} from "../../dialog/message";import {bindThemeColorEditor, getThemeColorEditorHTML} from "../../dialog/themeColorEditor";import {escapeAttr, escapeHtml} from "../../util/escape";-import {isMobile} from "../../util/functions";import {- BUILTIN_INLINE_COLOR_COUNT,- BUILTIN_INLINE_STYLE_IDS,getBuiltinColorPropertyValue,+ getBuiltinColorVariableName,getBuiltinInlineColor,getBuiltinInlineStyle,getBuiltinInlineStylePropertyValue,getCurrentInlineStyleMode,- getInlineStylesCache,- IBuiltinInlineColor,- IBuiltinInlineStyle,IInlineStyleColors,IInlineStyles,- saveInlineStyles,TBuiltinColorType,TBuiltinInlineStyleID,TInlineStyleProperty,} from "./inlineStyle";-interface IBuiltinColorDialogEntry {+export interface IBuiltinColorDialogEntry {key: number | TBuiltinInlineStyleID;label: string;- value?: IBuiltinInlineColor | IBuiltinInlineStyle;-}--interface IBuiltinColorDialogEditor {- entry: IBuiltinColorDialogEntry;- element: HTMLElement;- editor: ReturnType<typeof bindThemeColorEditor>;+ show: boolean;+ override: Record<TInlineStyleProperty, boolean>;+ value: { light: IInlineStyleColors, dark: IInlineStyleColors };fallback: { light: IInlineStyleColors, dark: IInlineStyleColors };- overrideElements: Map<TInlineStyleProperty, HTMLInputElement>;- showElement: HTMLInputElement;}-const cloneInlineStyles = (data = getInlineStylesCache()): IInlineStyles =>- JSON.parse(JSON.stringify(data)) as IInlineStyles;+const cloneThemeValue = (value: { light: IInlineStyleColors, dark: IInlineStyleColors }) =>+ JSON.parse(JSON.stringify(value)) as { light: IInlineStyleColors, dark: IInlineStyleColors };const getTypeLabel = (type: TBuiltinColorType) => {if (type === "color") {@@ -50,7 +36,7 @@ const getTypeLabel = (type: TBuiltinColorType) => {return window.siyuan.languages.color;};-const getProperties = (type: TBuiltinColorType): TInlineStyleProperty[] => {+export const getProperties = (type: TBuiltinColorType): TInlineStyleProperty[] => {if (type === "color") {return ["color"];}@@ -92,12 +78,25 @@ const colorToHex = (value: string, fallback: string) => {return `#${Array.from(color.slice(0, 3)).map(item => item.toString(16).padStart(2, "0")).join("")}`;};-const resolveThemeColor = (value: string, fallback: string) => {+const withThemeDefaults = <T>(fn: () => T) => {const siyuanStyle = document.getElementById("siyuanStyle") as HTMLStyleElement;const disabled = siyuanStyle?.disabled;if (siyuanStyle) {siyuanStyle.disabled = true;}+ try {+ return fn();+ } finally {+ if (siyuanStyle) {+ siyuanStyle.disabled = disabled;+ }+ }+};++const themeVariableValue = (name: string) =>+ withThemeDefaults(() => getComputedStyle(document.documentElement).getPropertyValue(name).trim());++const resolveThemeColor = (value: string, fallback: string) => withThemeDefaults(() => {const element = document.createElement("span");element.style.color = value;element.style.position = "fixed";@@ -105,74 +104,63 @@ const resolveThemeColor = (value: string, fallback: string) => {document.body.append(element);const color = colorToHex(getComputedStyle(element).color, fallback);element.remove();- if (siyuanStyle) {- siyuanStyle.disabled = disabled;- }return color;-};+});const getFallbackValue = (type: TBuiltinColorType, key: number | TBuiltinInlineStyleID) => {const getValue = (property: TInlineStyleProperty) => type === "style1" ?getBuiltinInlineStylePropertyValue(key as TBuiltinInlineStyleID, property) :getBuiltinColorPropertyValue(key as number, property);+ const resolve = (property: TInlineStyleProperty, lightFallback: string, darkFallback: string) => {+ if (typeof key === "number" && !themeVariableValue(getBuiltinColorVariableName(key, property))) {+ return {light: lightFallback, dark: darkFallback};+ }+ const cssValue = getValue(property);+ return {+ light: resolveThemeColor(cssValue, lightFallback),+ dark: resolveThemeColor(cssValue, darkFallback),+ };+ };+ const color = resolve("color", "#000000", "#ffffff");+ const backgroundColor = resolve("backgroundColor", "#ffffff", "#000000");return {light: {- color: resolveThemeColor(getValue("color"), "#000000"),- backgroundColor: resolveThemeColor(getValue("backgroundColor"), "#ffffff"),+ color: color.light,+ backgroundColor: backgroundColor.light,},dark: {- color: resolveThemeColor(getValue("color"), "#ffffff"),- backgroundColor: resolveThemeColor(getValue("backgroundColor"), "#000000"),+ color: color.dark,+ backgroundColor: backgroundColor.dark,},};};-const getEditorType = (type: TBuiltinColorType) => type === "av" ? "style1" : type;+export const getEditorType = (type: TBuiltinColorType) => type === "av" ? "style1" : type;-const hasOverride = (entry: IBuiltinColorDialogEntry, property: TInlineStyleProperty) =>- !!entry.value?.light[property] && !!entry.value?.dark[property];+const hasStoredOverride = (value: { light?: IInlineStyleColors, dark?: IInlineStyleColors } | undefined,+ property: TInlineStyleProperty) =>+ !!value?.light?.[property] && !!value?.dark?.[property];-const getEntryHTML = (type: TBuiltinColorType, entry: IBuiltinColorDialogEntry) => {- const properties = getProperties(type);- const customHTML = properties.map(property => `<label class="fn__flex" style="align-items:center">- <input class="b3-switch" data-role="override" data-property="${property}" type="checkbox"${- hasOverride(entry, property) ? " checked" : ""}>- <span class="fn__space"></span>${property === "color" ? window.siyuan.languages.colorFont :- window.siyuan.languages.colorPrimary}-</label>`).join('<span class="fn__space"></span>');- return `<div class="b3-label b3-label--inner" data-entry="${escapeAttr(entry.key.toString())}">- <div class="fn__flex" style="align-items:center;gap:8px">- <span class="color__square color__square--list" data-role="preview">A</span>- <span class="fn__flex-1">${escapeHtml(entry.label)}</span>- <label class="fn__flex" style="align-items:center">- ${window.siyuan.languages.showInColorPicker}<span class="fn__space"></span>- <input class="b3-switch" data-role="show" type="checkbox">- </label>- <button class="b3-button b3-button--outline" data-action="reset" type="button">- ${window.siyuan.languages.reset}- </button>- </div>- <div class="fn__flex" style="align-items:center;margin-top:12px">${customHTML}</div>- ${getThemeColorEditorHTML()}-</div>`;-};+export const isEntryCustomized = (entry: IBuiltinColorDialogEntry, properties: TInlineStyleProperty[]) =>+ properties.some(property => entry.override[property]);-const updatePropertyState = (editor: IBuiltinColorDialogEditor) => {- editor.overrideElements.forEach((input, property) => {- editor.element.querySelectorAll<HTMLInputElement>(`[data-property="${property}"] input[type="color"]`)- .forEach(item => item.disabled = !input.checked);- });+export const isEntryDefault = (entry: IBuiltinColorDialogEntry, properties: TInlineStyleProperty[]) =>+ entry.show && !isEntryCustomized(entry, properties);++const getPreviewValue = (type: TBuiltinColorType, entry: IBuiltinColorDialogEntry, property: TInlineStyleProperty) => {+ if (entry.override[property]) {+ return entry.value[getCurrentInlineStyleMode()][property] || "";+ }+ if (typeof entry.key === "number") {+ return getBuiltinColorPropertyValue(entry.key, property);+ }+ return getBuiltinInlineStylePropertyValue(entry.key, property);};-const updatePreview = (type: TBuiltinColorType, editor: IBuiltinColorDialogEditor) => {- const previewElement = editor.element.querySelector('[data-role="preview"]') as HTMLElement;- const mode = getCurrentInlineStyleMode();- const value = editor.editor.getValue(getEditorType(type));- const getValue = (property: TInlineStyleProperty) => editor.overrideElements.get(property)?.checked ?- value[mode][property] : editor.fallback[mode][property];- previewElement.style.color = type === "backgroundColor" ? "" : getValue("color");- previewElement.style.backgroundColor = type === "color" ? "" : getValue("backgroundColor");- previewElement.textContent = type === "backgroundColor" ? "" : "A";+export const applyPreviewStyle = (type: TBuiltinColorType, element: HTMLElement, entry: IBuiltinColorDialogEntry) => {+ element.style.color = type === "backgroundColor" ? "" : getPreviewValue(type, entry, "color");+ element.style.backgroundColor = type === "color" ? "" : getPreviewValue(type, entry, "backgroundColor");+ element.textContent = type === "backgroundColor" ? "" : "A";};const setProperty = (target: { light: IInlineStyleColors, dark: IInlineStyleColors },@@ -190,148 +178,260 @@ const setProperty = (target: { light: IInlineStyleColors, dark: IInlineStyleColoconst hasColors = (value: { light: IInlineStyleColors }) =>!!value.light.color || !!value.light.backgroundColor;-export const openBuiltinColorDialog = (type: TBuiltinColorType,- onChange?: (data: IInlineStyles) => void) => {- if (window.siyuan.config.readonly || window.siyuan.isPublish) {- return;- }- const initialData = cloneInlineStyles();- const entries: IBuiltinColorDialogEntry[] = type === "style1" ?- BUILTIN_INLINE_STYLE_IDS.map(id => ({- key: id,- label: getEntryLabel(type, id),- value: getBuiltinInlineStyle(id, initialData),- })) : Array.from({length: BUILTIN_INLINE_COLOR_COUNT}, (_, index) => ({- key: index + 1,- label: getEntryLabel(type, index + 1),- value: getBuiltinInlineColor(index + 1, initialData),- }));- let saving = false;- const dialog = new Dialog({- title: window.siyuan.languages.manageBuiltinColors,- width: isMobile() ? "92vw" : "720px",- content: `<div class="b3-dialog__content" style="max-height:70vh;overflow:auto">- ${entries.map(entry => getEntryHTML(type, entry)).join("")}-</div>-<div class="b3-dialog__action">- <button class="b3-button b3-button--outline" data-action="resetAll" type="button">${- window.siyuan.languages.resetAll}</button>- <div class="fn__flex-1"></div>- <button class="b3-button b3-button--cancel" data-action="cancel" type="button">${- window.siyuan.languages.cancel}</button>- <div class="fn__space"></div>- <button class="b3-button b3-button--text" data-action="save" type="button">${- window.siyuan.languages.save}</button>-</div>`,+export const resetEntry = (entry: IBuiltinColorDialogEntry, properties: TInlineStyleProperty[]) => {+ entry.show = true;+ properties.forEach(property => {+ entry.override[property] = false;});- const editors = new Map<string, IBuiltinColorDialogEditor>();- const hidden = initialData.builtin.hidden[type];- entries.forEach(entry => {- const element = dialog.element.querySelector(`[data-entry="${entry.key}"]`) as HTMLElement;- const editor = bindThemeColorEditor(element);- const fallback = getFallbackValue(type, entry.key);- const editorValue = {- light: {...fallback.light, ...entry.value?.light},- dark: {...fallback.dark, ...entry.value?.dark},+ entry.value = cloneThemeValue(entry.fallback);+};++export const createBuiltinDialogEntry = (type: TBuiltinColorType, key: number | TBuiltinInlineStyleID,+ data: IInlineStyles): IBuiltinColorDialogEntry => {+ const stored = type === "style1" ?+ getBuiltinInlineStyle(key as TBuiltinInlineStyleID, data) :+ getBuiltinInlineColor(key as number, data);+ const fallback = getFallbackValue(type, key);+ return {+ key,+ label: getEntryLabel(type, key),+ show: !data.builtin.hidden[type].includes(key as never),+ override: {+ color: hasStoredOverride(stored, "color"),+ backgroundColor: hasStoredOverride(stored, "backgroundColor"),+ },+ value: {+ light: {...fallback.light, ...stored?.light},+ dark: {...fallback.dark, ...stored?.dark},+ },+ fallback,+ };+};++export const writeBuiltinEntry = (data: IInlineStyles, type: TBuiltinColorType,+ entry: IBuiltinColorDialogEntry) => {+ const properties = getProperties(type);+ if (type === "style1") {+ const id = entry.key as TBuiltinInlineStyleID;+ const current = getBuiltinInlineStyle(id, data) || {+ id,+ light: {} as IInlineStyleColors,+ dark: {} as IInlineStyleColors,};- editor.setValue(editorValue, getEditorType(type));- const overrideElements = new Map<TInlineStyleProperty, HTMLInputElement>();- element.querySelectorAll<HTMLInputElement>('[data-role="override"]').forEach(item => {- overrideElements.set(item.dataset.property as TInlineStyleProperty, item);+ properties.forEach(property => setProperty(current, entry.value, property, entry.override[property]));+ data.builtin.styles = data.builtin.styles.filter(item => item.id !== id);+ if (hasColors(current)) {+ data.builtin.styles.push(current);+ }+ data.builtin.hidden.style1 = data.builtin.hidden.style1.filter(item => item !== id);+ if (!entry.show) {+ data.builtin.hidden.style1.push(id);+ }+ return;+ }+ const index = entry.key as number;+ const current = getBuiltinInlineColor(index, data) ||+ {index, light: {} as IInlineStyleColors, dark: {} as IInlineStyleColors};+ properties.forEach(property => setProperty(current, entry.value, property, entry.override[property]));+ data.builtin.colors = data.builtin.colors.filter(item => item.index !== index);+ if (hasColors(current)) {+ data.builtin.colors.push(current);+ }+ data.builtin.hidden[type] = data.builtin.hidden[type].filter(item => item !== index);+ if (!entry.show) {+ data.builtin.hidden[type].push(index);+ }+};++export const getBuiltinEditorHTML = (type: TBuiltinColorType) => {+ const properties = getProperties(type);+ return `<div class="fn__flex">+ <span class="color__square color__square--list fn__flex-center" data-role="preview">A</span>+ <span class="fn__flex-1 fn__flex-center" data-role="title"></span>+ </div>+ <div class="fn__hr--b"></div>+ <div data-role="overrides">${properties.map((property, index) => `<label class="fn__flex">+ <span class="fn__flex-center">${properties.length === 1 ? window.siyuan.languages.custom :+ (property === "color" ? window.siyuan.languages.colorFont : window.siyuan.languages.colorPrimary)}</span>+ <span class="fn__space"></span>+ <input class="b3-switch fn__flex-center" data-role="override" data-property="${property}" type="checkbox">+ </label>${index < properties.length - 1 ? "<div class=\"fn__hr\"></div>" : ""}`).join("")}</div>+ <div class="fn__hr--b"></div>+ <div class="ft__on-surface" data-role="defaultHint">${escapeHtml(window.siyuan.languages.useThemeDefaultColor)}</div>+ ${getThemeColorEditorHTML()}`;+};++export const getColorListItemHTML = (options: {+ kind: "builtin" | "custom",+ key: string,+ index: number,+ label: string,+ title?: string,+ previewStyle?: string,+ show: boolean,+ customized?: boolean,+ draggable?: boolean,+ canDelete?: boolean,+ resetHidden?: boolean,+}) => {+ const previewAttr = options.previewStyle ? ` style="${options.previewStyle}"` : " data-role=\"preview\"";+ return `<div class="b3-list-item b3-list-item--narrow" data-kind="${options.kind}" data-key="${escapeAttr(options.key)}" data-index="${options.index}">+ ${options.draggable !== false ? `<span class="b3-list-item__graphic ariaLabel fn__grab" data-drag="true" draggable="true" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.sort)}"><svg><use xlink:href="#iconDrag"></use></svg></span>` : ""}+ <span class="color__square color__square--list"${previewAttr}>${options.kind === "custom" || options.previewStyle ? "A" : ""}</span>+ <span class="b3-list-item__text"${options.title ? ` title="${escapeAttr(options.title)}"` : ""}>${escapeHtml(options.label)}</span>+ ${options.customized ? `<span class="b3-list-item__meta">${escapeHtml(window.siyuan.languages.custom)}</span>` : ""}+ ${options.kind === "builtin" ? `<span class="b3-list-item__action ariaLabel${options.resetHidden ? " fn__none" : ""}" data-action="resetItem" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.reset)}"><svg><use xlink:href="#iconUndo"></use></svg></span>` : ""}+ ${options.canDelete ? `<span class="b3-list-item__action b3-list-item__action--warning ariaLabel" data-action="delete" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.delete)}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>` : ""}+ <span class="b3-list-item__action ariaLabel" data-action="edit" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.edit)}"><svg><use xlink:href="#iconEdit"></use></svg></span>+ <span class="fn__space"></span>+ <input class="b3-switch fn__flex-center ariaLabel" data-action="toggleShow" data-position="north" type="checkbox" aria-label="${escapeAttr(window.siyuan.languages.showInColorPicker)}"${options.show ? " checked" : ""}>+</div>`;+};++export const bindColorListDrag = (listElement: HTMLElement, getKeys: () => string[],+ onReorder: (keys: string[]) => void) => {+ let draggingIndex = -1;+ const clearDragover = () => {+ listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-index]").forEach(item => {+ item.classList.remove("dragover__top", "dragover__bottom");});- const showElement = element.querySelector('[data-role="show"]') as HTMLInputElement;- showElement.checked = !hidden.includes(entry.key as never);- const state: IBuiltinColorDialogEditor = {entry, element, editor, fallback, overrideElements, showElement};- editors.set(entry.key.toString(), state);- updatePropertyState(state);- updatePreview(type, state);- element.addEventListener("input", () => updatePreview(type, state));- element.addEventListener("change", event => {- if ((event.target as HTMLElement).matches('[data-role="override"]')) {- updatePropertyState(state);- }- updatePreview(type, state);+ };+ const clearDragStyles = () => {+ clearDragover();+ listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-index]").forEach(item => {+ item.classList.remove("ft__on-surface");});+ };+ listElement.addEventListener("dragstart", (event: DragEvent) => {+ const handleElement = (event.target as HTMLElement).closest<HTMLElement>('[data-drag="true"]');+ const itemElement = handleElement?.closest<HTMLElement>(".b3-list-item[data-index]");+ if (!itemElement) {+ event.preventDefault();+ return;+ }+ draggingIndex = parseInt(itemElement.dataset.index);+ event.dataTransfer.effectAllowed = "move";+ event.dataTransfer.setData("text/plain", itemElement.dataset.index);+ itemElement.classList.add("ft__on-surface");+ });+ listElement.addEventListener("dragover", (event: DragEvent) => {+ const itemElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item[data-index]");+ if (!itemElement || draggingIndex < 0) {+ return;+ }+ event.preventDefault();+ event.dataTransfer.dropEffect = "move";+ clearDragover();+ const rect = itemElement.getBoundingClientRect();+ itemElement.classList.add(event.clientY < rect.top + rect.height / 2 ? "dragover__top" : "dragover__bottom");+ });+ listElement.addEventListener("drop", (event: DragEvent) => {+ const itemElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item[data-index]");+ if (!itemElement || draggingIndex < 0) {+ return;+ }+ event.preventDefault();+ const targetIndex = parseInt(itemElement.dataset.index);+ const rect = itemElement.getBoundingClientRect();+ const before = event.clientY < rect.top + rect.height / 2;+ let insertIndex = targetIndex + (before ? 0 : 1);+ if (draggingIndex < insertIndex) {+ insertIndex--;+ }+ if (draggingIndex !== insertIndex) {+ const keys = getKeys();+ const [key] = keys.splice(draggingIndex, 1);+ keys.splice(insertIndex, 0, key);+ onReorder(keys);+ }+ draggingIndex = -1;+ clearDragStyles();});+ listElement.addEventListener("dragend", () => {+ draggingIndex = -1;+ clearDragStyles();+ });+};- const resetEditor = (state: IBuiltinColorDialogEditor) => {- state.overrideElements.forEach(item => item.checked = false);- state.showElement.checked = true;- state.editor.setValue(state.fallback, getEditorType(type));- updatePropertyState(state);- updatePreview(type, state);+export const bindBuiltinEditor = (panel: HTMLElement, type: TBuiltinColorType,+ getBase: () => IBuiltinColorDialogEntry | undefined) => {+ const properties = getProperties(type);+ const previewElement = panel.querySelector('[data-role="preview"]') as HTMLElement;+ const titleElement = panel.querySelector('[data-role="title"]') as HTMLElement;+ const hintElement = panel.querySelector('[data-role="defaultHint"]') as HTMLElement;+ const themeColorEditor = bindThemeColorEditor(panel);+ const overrideElements = new Map(Array.from(panel.querySelectorAll<HTMLInputElement>('[data-role="override"]'))+ .map(item => [item.dataset.property as TInlineStyleProperty, item] as const));++ const readEntry = (base: IBuiltinColorDialogEntry): IBuiltinColorDialogEntry => {+ const value = themeColorEditor.getValue(getEditorType(type));+ return {+ ...base,+ override: {+ color: overrideElements.get("color")?.checked ?? base.override.color,+ backgroundColor: overrideElements.get("backgroundColor")?.checked ?? base.override.backgroundColor,+ },+ value: {+ light: {...base.fallback.light, ...base.value.light, ...value.light},+ dark: {...base.fallback.dark, ...base.value.dark, ...value.dark},+ },+ };};- dialog.element.addEventListener("click", async event => {- const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");- if (!actionElement || actionElement.hasAttribute("disabled")) {- return;+ const updateState = () => {+ let anyEnabled = false;+ properties.forEach(property => {+ const enabled = !!overrideElements.get(property)?.checked;+ anyEnabled = anyEnabled || enabled;+ panel.querySelectorAll<HTMLElement>(`[data-type="themeColorEditor"] [data-property="${property}"]`)+ .forEach(item => {+ item.classList.toggle("fn__none", !enabled);+ item.querySelectorAll<HTMLInputElement>("input[type=\"color\"]").forEach(input => {+ input.disabled = !enabled;+ });+ });+ });+ const themeEditorElement = panel.querySelector('[data-type="themeColorEditor"]') as HTMLElement;+ themeEditorElement.classList.toggle("fn__none", !anyEnabled);+ hintElement.classList.toggle("fn__none", anyEnabled);+ const base = getBase();+ if (base) {+ applyPreviewStyle(type, previewElement, readEntry(base));}- const action = actionElement.dataset.action;- if (action === "reset") {- const entryElement = actionElement.closest<HTMLElement>("[data-entry]");- const state = entryElement && editors.get(entryElement.dataset.entry);- if (state) {- resetEditor(state);- }- } else if (action === "resetAll") {- editors.forEach(resetEditor);- } else if (action === "cancel") {- dialog.destroy();- } else if (action === "save" && !saving) {- saving = true;- actionElement.setAttribute("disabled", "disabled");- const data = cloneInlineStyles();- const hiddenValues: Array<number | TBuiltinInlineStyleID> = [];- editors.forEach(state => {- if (!state.showElement.checked) {- hiddenValues.push(state.entry.key);- }- const value = state.editor.getValue(getEditorType(type));- if (type === "style1") {- const id = state.entry.key as TBuiltinInlineStyleID;- const current = getBuiltinInlineStyle(id, data) || {id, light: {}, dark: {}};- getProperties(type).forEach(property => setProperty(current, value, property,- state.overrideElements.get(property).checked));- data.builtin.styles = data.builtin.styles.filter(item => item.id !== id);- if (hasColors(current)) {- data.builtin.styles.push(current);- }- } else {- const index = state.entry.key as number;- const current = getBuiltinInlineColor(index, data) || {index, light: {}, dark: {}};- getProperties(type).forEach(property => setProperty(current, value, property,- state.overrideElements.get(property).checked));- data.builtin.colors = data.builtin.colors.filter(item => item.index !== index);- if (hasColors(current)) {- data.builtin.colors.push(current);- }- }- });- if (type === "style1") {- data.builtin.hidden.style1 = hiddenValues as TBuiltinInlineStyleID[];- } else {- data.builtin.hidden[type] = hiddenValues as number[];- }- try {- const response = await saveInlineStyles(data);- if (response?.code !== 0) {- showMessage(response?.msg || window.siyuan.languages.invalid, 6000, "error");- saving = false;- actionElement.removeAttribute("disabled");- return;- }- const savedData = getInlineStylesCache();- onChange?.(savedData);- void import("../../util/assets").then(module => module.setInlineStyle());- dialog.destroy();- } catch (error) {- showMessage(error instanceof Error ? error.message : window.siyuan.languages.invalid, 6000, "error");- saving = false;- actionElement.removeAttribute("disabled");+ };++ const fill = (entry: IBuiltinColorDialogEntry) => {+ titleElement.textContent = entry.label;+ properties.forEach(property => {+ const input = overrideElements.get(property);+ if (input) {+ input.checked = entry.override[property];}+ });+ themeColorEditor.setValue(entry.value, getEditorType(type));+ updateState();+ };++ const commit = (base: IBuiltinColorDialogEntry) => {+ const entry = readEntry(base);+ const value = themeColorEditor.getValue(getEditorType(type));+ properties.forEach(property => {+ entry.override[property] = !!overrideElements.get(property)?.checked;+ entry.value.light[property] = value.light[property] || entry.value.light[property];+ entry.value.dark[property] = value.dark[property] || entry.value.dark[property];+ });+ return entry;+ };++ panel.addEventListener("input", () => updateState());+ panel.addEventListener("change", event => {+ if ((event.target as HTMLElement).matches('[data-role="override"]')) {+ updateState();}- event.preventDefault();- event.stopPropagation();});+ return {+ fill,+ commit,+ updateState,+ };};diff --git a/app/src/protyle/toolbar/inlineStyle.test.ts b/app/src/protyle/toolbar/inlineStyle.test.tsindex bbaf73ff8e..b561358fcc 100644--- a/app/src/protyle/toolbar/inlineStyle.test.ts+++ b/app/src/protyle/toolbar/inlineStyle.test.ts@@ -1,6 +1,6 @@import {before, describe, it} from "node:test";import * as assert from "node:assert/strict";-import type {IInlineStyle, IInlineStyleBuiltin} from "./inlineStyle";+import type {IInlineStyle, IInlineStyleBuiltin, IInlineStyleOrder} from "./inlineStyle";let inlineStyle: typeof import("./inlineStyle");@@ -25,6 +25,21 @@ const combinedStyle: IInlineStyle = {},};+const defaultOrder = (styles: IInlineStyle[] = []): IInlineStyleOrder => {+ const order: IInlineStyleOrder = {+ color: [...inlineStyle.DEFAULT_INLINE_STYLE_ORDER.color],+ backgroundColor: [...inlineStyle.DEFAULT_INLINE_STYLE_ORDER.backgroundColor],+ style1: [...inlineStyle.DEFAULT_INLINE_STYLE_ORDER.style1],+ };+ styles.forEach(style => {+ const type = inlineStyle.getInlineStyleType(style);+ if (type && !order[type].includes(style.id)) {+ order[type].push(style.id);+ }+ });+ return order;+};+const emptyBuiltin: IInlineStyleBuiltin = {colors: [],styles: [],@@ -65,6 +80,13 @@ describe("normalizeInlineStyles", () => {light: {backgroundColor: "#aabbcc"},dark: {backgroundColor: "#001122"},}],+ order: defaultOrder([combinedStyle, {+ id: "20260821120001-bbcdefg",+ name: "Background",+ light: {backgroundColor: "#aabbcc"},+ dark: {backgroundColor: "#001122"},+ }]),+ av: inlineStyle.INLINE_STYLE_EMPTY.av,});});@@ -80,6 +102,10 @@ describe("normalizeInlineStyles", () => {index: 2,light: {color: "#ffffff"},dark: {color: "#000000"},+ }, {+ index: 15,+ light: {color: "#ffffff"},+ dark: {color: "#000000"},}, {index: 14,light: {color: "#ffffff"},@@ -109,6 +135,10 @@ describe("normalizeInlineStyles", () => {index: 2,light: {color: "#aabbcc"},dark: {color: "#001122"},+ }, {+ index: 14,+ light: {color: "#ffffff"},+ dark: {color: "#000000"},}],styles: [{id: "warning",@@ -123,9 +153,33 @@ describe("normalizeInlineStyles", () => {},},styles: [],+ order: defaultOrder(),+ av: inlineStyle.INLINE_STYLE_EMPTY.av,});});+ it("keeps mixed built-in and custom order and appends missing keys", () => {+ const custom = {+ ...combinedStyle,+ id: "20260821120003-dbcdefg",+ name: "Accent",+ light: {color: "#112233"},+ dark: {color: "#fefefe"},+ };+ const normalized = inlineStyle.normalizeInlineStyles({+ styles: [custom],+ order: {+ color: ["2", custom.id, "1", "2", "unknown", "14"],+ backgroundColor: ["13"],+ style1: ["success", "missing"],+ },+ });+ assert.deepEqual(normalized.order.color.slice(0, 3), ["2", custom.id, "1"]);+ assert.equal(normalized.order.color[normalized.order.color.length - 1], "13");+ assert.deepEqual(normalized.order.backgroundColor.slice(0, 2), ["13", "1"]);+ assert.deepEqual(normalized.order.style1, ["success", "error", "warning", "info"]);+ });+it("limits names by Unicode code points without splitting surrogate pairs", () => {const normalized = inlineStyle.normalizeInlineStyles({version: 1,@@ -266,7 +320,24 @@ describe("recent inline styles", () => {custom,]);assert.deepEqual(inlineStyle.getVisibleBuiltinColorIndexes("av", data),- [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13]);+ [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14]);+ assert.deepEqual(inlineStyle.getVisibleOrderedStyleKeys("color", data),+ ["1", "2", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]);+ assert.deepEqual(inlineStyle.getVisibleOrderedStyleKeys("style1", {+ ...data,+ order: {+ ...data.order,+ style1: ["success", "error", "warning", "info", combinedStyle.id],+ },+ }), ["success", "warning", "info", combinedStyle.id]);+ assert.deepEqual(inlineStyle.getVisibleOrderedStyleKeys("style1", {+ ...data,+ styles: [{...combinedStyle, hidden: true}],+ order: {+ ...data.order,+ style1: ["success", "error", "warning", "info", combinedStyle.id],+ },+ }), ["success", "warning", "info"]);});});diff --git a/app/src/protyle/toolbar/inlineStyle.ts b/app/src/protyle/toolbar/inlineStyle.tsindex 7058c25607..450df477d0 100644--- a/app/src/protyle/toolbar/inlineStyle.ts+++ b/app/src/protyle/toolbar/inlineStyle.ts@@ -11,11 +11,16 @@ export interface IInlineStyleColors {export interface IInlineStyle {id: string;name: string;+ hidden?: boolean;light: IInlineStyleColors;dark: IInlineStyleColors;}export const BUILTIN_INLINE_COLOR_COUNT = 13;+export const AV_BUILTIN_COLOR_COUNT = 14;+export const AV_CUSTOM_COLOR_MIN = 15;+export const AV_CUSTOM_COLOR_MAX = 78;+export const AV_CUSTOM_COLOR_LIMIT = 64;export const BUILTIN_INLINE_STYLE_IDS = ["error", "warning", "info", "success"] as const;export type TBuiltinInlineStyleID = typeof BUILTIN_INLINE_STYLE_IDS[number];@@ -45,10 +50,28 @@ export interface IInlineStyleBuiltin {hidden: IBuiltinInlineStyleHidden;}+export interface IInlineStyleOrder {+ color: string[];+ backgroundColor: string[];+ style1: string[];+}++export interface IInlineStyleAV {+ colors: IAVCustomColor[];+ order: string[];+}++export interface IWorkspaceAVBuiltinColorUpdate extends IBuiltinInlineColor {+ customized: boolean;+ hidden: boolean;+}+export interface IInlineStyles {version: 2;builtin: IInlineStyleBuiltin;styles: IInlineStyle[];+ order: IInlineStyleOrder;+ av: IInlineStyleAV;}export interface IInlineStyleApplication {@@ -56,6 +79,18 @@ export interface IInlineStyleApplication {color: string;}+export const DEFAULT_BUILTIN_COLOR_ORDER = Array.from({length: BUILTIN_INLINE_COLOR_COUNT}, (_, index) =>+ (index + 1).toString());++export const DEFAULT_INLINE_STYLE_ORDER: IInlineStyleOrder = {+ color: [...DEFAULT_BUILTIN_COLOR_ORDER],+ backgroundColor: [...DEFAULT_BUILTIN_COLOR_ORDER],+ style1: [...BUILTIN_INLINE_STYLE_IDS],+};++export const DEFAULT_AV_COLOR_ORDER = Array.from({length: AV_BUILTIN_COLOR_COUNT}, (_, index) =>+ (index + 1).toString());+export const INLINE_STYLE_EMPTY: IInlineStyles = {version: 2,builtin: {@@ -69,6 +104,15 @@ export const INLINE_STYLE_EMPTY: IInlineStyles = {},},styles: [],+ order: {+ color: [...DEFAULT_INLINE_STYLE_ORDER.color],+ backgroundColor: [...DEFAULT_INLINE_STYLE_ORDER.backgroundColor],+ style1: [...DEFAULT_INLINE_STYLE_ORDER.style1],+ },+ av: {+ colors: [],+ order: [...DEFAULT_AV_COLOR_ORDER],+ },};export const MAX_INLINE_STYLES = 64;@@ -134,6 +178,7 @@ const normalizeStyle = (value: unknown): IInlineStyle | undefined => {return {id: style.id,name: [...style.name.trim()].slice(0, MAX_INLINE_STYLE_NAME_LENGTH).join(""),+ ...(style.hidden === true ? {hidden: true} : {}),...colors,};};@@ -177,7 +222,7 @@ const normalizeBuiltinColors = (value: unknown) => {}const index = Number((item as Partial<IBuiltinInlineColor>).index);const pairedColors = normalizePairedColors(item);- if (!Number.isInteger(index) || index < 1 || index > BUILTIN_INLINE_COLOR_COUNT ||+ if (!Number.isInteger(index) || index < 1 || index > AV_BUILTIN_COLOR_COUNT ||indexes.has(index) || !pairedColors) {return;}@@ -209,12 +254,12 @@ const normalizeBuiltinStyles = (value: unknown) => {return styles.sort((a, b) => BUILTIN_INLINE_STYLE_IDS.indexOf(a.id) - BUILTIN_INLINE_STYLE_IDS.indexOf(b.id));};-const normalizeHiddenIndexes = (value: unknown) => {+const normalizeHiddenIndexes = (value: unknown, max = BUILTIN_INLINE_COLOR_COUNT) => {if (!Array.isArray(value)) {return [];}return Array.from(new Set(value.filter(item => Number.isInteger(item) && item >= 1 &&- item <= BUILTIN_INLINE_COLOR_COUNT) as number[])).sort((a, b) => a - b);+ item <= max) as number[])).sort((a, b) => a - b);};const normalizeHiddenStyleIDs = (value: unknown) => {@@ -237,11 +282,143 @@ const normalizeBuiltin = (value: unknown): IInlineStyleBuiltin => {color: normalizeHiddenIndexes(hidden.color),backgroundColor: normalizeHiddenIndexes(hidden.backgroundColor),style1: normalizeHiddenStyleIDs(hidden.style1),- av: normalizeHiddenIndexes(hidden.av),+ av: normalizeHiddenIndexes(hidden.av, AV_BUILTIN_COLOR_COUNT),},};};+const normalizeStoredAVColor = (value: unknown): IAVCustomColor | undefined => {+ if (!value || typeof value !== "object") {+ return;+ }+ const color = value as Partial<IAVCustomColor>;+ const index = Number(color.index);+ const lightColor = normalizeColor(color.light?.color);+ const lightBackground = normalizeColor(color.light?.backgroundColor);+ const darkColor = normalizeColor(color.dark?.color);+ const darkBackground = normalizeColor(color.dark?.backgroundColor);+ if (!Number.isInteger(index) || index < AV_CUSTOM_COLOR_MIN || index > AV_CUSTOM_COLOR_MAX ||+ !lightColor || !lightBackground || !darkColor || !darkBackground) {+ return;+ }+ return {+ index,+ ...(color.hidden === true ? {hidden: true} : {}),+ light: {color: lightColor, backgroundColor: lightBackground},+ dark: {color: darkColor, backgroundColor: darkBackground},+ };+};++const normalizeStoredAVColors = (value: unknown) => {+ const colors: IAVCustomColor[] = [];+ const indexes = new Set<number>();+ if (!Array.isArray(value)) {+ return colors;+ }+ value.forEach(item => {+ if (colors.length >= AV_CUSTOM_COLOR_LIMIT) {+ return;+ }+ const color = normalizeStoredAVColor(item);+ if (!color || indexes.has(color.index)) {+ return;+ }+ indexes.add(color.index);+ colors.push(color);+ });+ return colors.sort((a, b) => a.index - b.index);+};++const defaultAVColorOrder = (colors: Pick<IAVCustomColor, "index">[]) => [+ ...DEFAULT_AV_COLOR_ORDER,+ ...colors.map(item => item.index.toString()),+];++const normalizeStoredAVOrder = (value: unknown, colors: Pick<IAVCustomColor, "index">[]) => {+ const allowed = new Set(defaultAVColorOrder(colors));+ const result: string[] = [];+ const seen = new Set<string>();+ if (Array.isArray(value)) {+ value.forEach(item => {+ if (typeof item !== "string" || !allowed.has(item) || seen.has(item)) {+ return;+ }+ seen.add(item);+ result.push(item);+ });+ }+ defaultAVColorOrder(colors).forEach(key => {+ if (!seen.has(key)) {+ result.push(key);+ }+ });+ return result;+};++const normalizeAVPalette = (value: unknown): IInlineStyleAV => {+ const av = value && typeof value === "object" ? value as Partial<IInlineStyleAV> : {};+ const colors = normalizeStoredAVColors(av.colors);+ return {+ colors,+ order: normalizeStoredAVOrder(av.order, colors),+ };+};++export const getInlineStyleType = (style: IInlineStyle): TInlineStyleType | undefined => {+ const hasColor = !!style.light.color && !!style.dark.color;+ const hasBackground = !!style.light.backgroundColor && !!style.dark.backgroundColor;+ if (hasColor && hasBackground) {+ return "style1";+ }+ if (hasColor) {+ return "color";+ }+ if (hasBackground) {+ return "backgroundColor";+ }+};++export const getDefaultBuiltinOrderKeys = (type: TInlineStyleType) =>+ type === "style1" ? [...BUILTIN_INLINE_STYLE_IDS] : [...DEFAULT_BUILTIN_COLOR_ORDER];++export const isBuiltinOrderKey = (type: TInlineStyleType, key: string) =>+ getDefaultBuiltinOrderKeys(type).includes(key);++const getCustomOrderKeys = (type: TInlineStyleType, styles: IInlineStyle[]) =>+ styles.filter(style => getInlineStyleType(style) === type).map(style => style.id);++const normalizeOrderKeys = (value: unknown, type: TInlineStyleType, styles: IInlineStyle[]) => {+ const builtinKeys = getDefaultBuiltinOrderKeys(type);+ const customKeys = getCustomOrderKeys(type, styles);+ const allowed = new Set([...builtinKeys, ...customKeys]);+ const result: string[] = [];+ const seen = new Set<string>();+ if (Array.isArray(value)) {+ value.forEach(item => {+ if (typeof item !== "string" || !allowed.has(item) || seen.has(item)) {+ return;+ }+ seen.add(item);+ result.push(item);+ });+ }+ [...builtinKeys, ...customKeys].forEach(key => {+ if (!seen.has(key)) {+ result.push(key);+ }+ });+ return result;+};++const normalizeOrder = (value: unknown, styles: IInlineStyle[]): IInlineStyleOrder => {+ const order = value && typeof value === "object" ? value as Partial<IInlineStyleOrder> : {};+ return {+ color: normalizeOrderKeys(order.color, "color", styles),+ backgroundColor: normalizeOrderKeys(order.backgroundColor, "backgroundColor", styles),+ style1: normalizeOrderKeys(order.style1, "style1", styles),+ };+};+export const normalizeInlineStyles = (value: unknown): IInlineStyles => {const styles: IInlineStyle[] = [];const ids = new Set<string>();@@ -262,6 +439,10 @@ export const normalizeInlineStyles = (value: unknown): IInlineStyles => {builtin: normalizeBuiltin(value && typeof value === "object" ?(value as Partial<IInlineStyles>).builtin : undefined),styles,+ order: normalizeOrder(value && typeof value === "object" ?+ (value as Partial<IInlineStyles>).order : undefined, styles),+ av: normalizeAVPalette(value && typeof value === "object" ?+ (value as Partial<IInlineStyles>).av : undefined),};};@@ -329,18 +510,26 @@ export const saveInlineStyles = async (data: IInlineStyles) => {return response;};-export const getInlineStyleType = (style: IInlineStyle): TInlineStyleType | undefined => {- const hasColor = !!style.light.color && !!style.dark.color;- const hasBackground = !!style.light.backgroundColor && !!style.dark.backgroundColor;- if (hasColor && hasBackground) {- return "style1";- }- if (hasColor) {- return "color";+export const saveWorkspaceAVPalette = async (data: IInlineStyleAV,+ builtinColors: IWorkspaceAVBuiltinColorUpdate[]) => {+ const [{Constants}, {fetchSyncPost}] = await Promise.all([+ import("../../constants"),+ import("../../util/fetch"),+ ]);+ const response = await fetchSyncPost("/api/storage/setWorkspaceAVPalette", {+ colors: data.colors,+ order: data.order,+ builtinColors,+ app: Constants.SIYUAN_APPID,+ });+ if (response?.code !== 0) {+ return response;}- if (hasBackground) {- return "backgroundColor";+ inlineStylesRequestGeneration++;+ if (response.data) {+ setInlineStylesCache(response.data);}+ return response;};export const getCurrentInlineStyleMode = (): TInlineStyleMode =>@@ -441,18 +630,37 @@ export const isBuiltinInlineStyleVisible = (type: TBuiltinColorType, value: numb!data.builtin.hidden.style1.includes(value as TBuiltinInlineStyleID);}const index = Number(value);- return !Number.isInteger(index) || index < 1 || index > BUILTIN_INLINE_COLOR_COUNT ||+ const max = type === "av" ? AV_BUILTIN_COLOR_COUNT : BUILTIN_INLINE_COLOR_COUNT;+ return !Number.isInteger(index) || index < 1 || index > max ||!data.builtin.hidden[type].includes(index);};export const getVisibleBuiltinColorIndexes = (type: Exclude<TBuiltinColorType, "style1">,- data = getInlineStylesCache()) =>- Array.from({length: BUILTIN_INLINE_COLOR_COUNT}, (_, index) => index + 1)+ data = getInlineStylesCache()) => {+ const count = type === "av" ? AV_BUILTIN_COLOR_COUNT : BUILTIN_INLINE_COLOR_COUNT;+ return Array.from({length: count}, (_, index) => index + 1).filter(index => isBuiltinInlineStyleVisible(type, index, data));+};export const getVisibleBuiltinInlineStyleIDs = (data = getInlineStylesCache()) =>BUILTIN_INLINE_STYLE_IDS.filter(id => isBuiltinInlineStyleVisible("style1", id, data));+export const getOrderedStyleKeys = (type: TInlineStyleType, data = getInlineStylesCache()) =>+ normalizeInlineStyles(data).order[type];++export const getVisibleOrderedStyleKeys = (type: TInlineStyleType, data = getInlineStylesCache()) => {+ const normalized = normalizeInlineStyles(data);+ return normalized.order[type].filter(key => {+ if (!isBuiltinOrderKey(type, key)) {+ const style = normalized.styles.find(item => item.id === key);+ return !!style && !style.hidden;+ }+ return type === "style1" ?+ isBuiltinInlineStyleVisible("style1", key as TBuiltinInlineStyleID, normalized) :+ isBuiltinInlineStyleVisible(type, Number(key), normalized);+ });+};+export const getBuiltinInlineStyleIDFromValue = (value?: string): TBuiltinInlineStyleID | undefined => {const id = value?.match(/--b3-(?:inline-builtin-|card-)(error|warning|info|success)-(?:background(?:-color)?|color)/)?.[1];return BUILTIN_INLINE_STYLE_IDS.includes(id as TBuiltinInlineStyleID) ? id as TBuiltinInlineStyleID : undefined;@@ -462,17 +670,22 @@ export const isRecentInlineStyleVisible = (value: string, data = getInlineStylesconst [type, propertyValue] = value.split(INLINE_STYLE_SEPARATOR);if (type === "color") {const index = Number(propertyValue?.match(BUILTIN_FONT_COLOR_VARIABLE_PATTERN)?.[1]);- return !index || isBuiltinInlineStyleVisible("color", index, data);- }- if (type === "backgroundColor") {+ if (index) {+ return isBuiltinInlineStyleVisible("color", index, data);+ }+ } else if (type === "backgroundColor") {const index = Number(propertyValue?.match(BUILTIN_BACKGROUND_COLOR_VARIABLE_PATTERN)?.[1]);- return !index || isBuiltinInlineStyleVisible("backgroundColor", index, data);- }- if (type === "style1") {+ if (index) {+ return isBuiltinInlineStyleVisible("backgroundColor", index, data);+ }+ } else if (type === "style1") {const id = getBuiltinInlineStyleIDFromValue(value);- return !id || isBuiltinInlineStyleVisible("style1", id, data);+ if (id) {+ return isBuiltinInlineStyleVisible("style1", id, data);+ }}- return true;+ const style = getInlineStyleByValue(value, data);+ return !style || !style.hidden;};export const filterHiddenRecentInlineStyles = (values: string[], data = getInlineStylesCache()) =>@@ -486,7 +699,7 @@ export const getRecentInlineStyleKey = (value: string) => {return value.split(INLINE_STYLE_SEPARATOR)[0] + INLINE_STYLE_SEPARATOR + id;};-export const getInlineStylesCSS = (data = getInlineStylesCache()) => {+export const getInlineStylesCSS = (data: unknown = getInlineStylesCache()) => {const normalized = normalizeInlineStyles(data);return (["light", "dark"] as TInlineStyleMode[]).map(mode => {const declarations: string[] = [];@@ -500,6 +713,11 @@ export const getInlineStylesCSS = (data = getInlineStylesCache()) => {`${color[mode].backgroundColor};`);}});+ normalized.av.colors.forEach(color => {+ declarations.push(` ${getBuiltinColorVariableName(color.index, "color")}: ${color[mode].color};`);+ declarations.push(` ${getBuiltinColorVariableName(color.index, "backgroundColor")}: ` ++ `${color[mode].backgroundColor};`);+ });normalized.builtin.styles.forEach(style => {if (style[mode].color) {declarations.push(` ${getBuiltinInlineStyleVariableName(style.id, "color")}: ${style[mode].color};`);diff --git a/app/src/protyle/toolbar/inlineStyleDialog.ts b/app/src/protyle/toolbar/inlineStyleDialog.tsindex 8276f92fe9..17f399b11c 100644--- a/app/src/protyle/toolbar/inlineStyleDialog.ts+++ b/app/src/protyle/toolbar/inlineStyleDialog.ts@@ -1,24 +1,38 @@import {Dialog} from "../../dialog";import {confirmDialog} from "../../dialog/confirmDialog";import {showMessage} from "../../dialog/message";-import {escapeAttr, escapeHtml} from "../../util/escape";-import {isMobile} from "../../util/functions";import {bindThemeColorEditor, getThemeColorEditorHTML} from "../../dialog/themeColorEditor";+import {escapeHtml} from "../../util/escape";+import {isMobile} from "../../util/functions";import {getCurrentInlineStyleMode,+ getInlineStyleByID,getInlineStylePreview,getInlineStylesCache,- getInlineStyleType,+ getOrderedStyleKeys,IInlineStyle,IInlineStyles,+ isBuiltinOrderKey,MAX_INLINE_STYLE_NAME_LENGTH,MAX_INLINE_STYLES,+ normalizeInlineStyles,saveInlineStyles,+ TBuiltinInlineStyleID,TInlineStyleType,} from "./inlineStyle";-import {openBuiltinColorDialog} from "./builtinColorDialog";--const escapeAttribute = (value: string) => escapeAttr(value);+import {+ applyPreviewStyle,+ bindBuiltinEditor,+ bindColorListDrag,+ createBuiltinDialogEntry,+ getBuiltinEditorHTML,+ getColorListItemHTML,+ getProperties,+ isEntryCustomized,+ isEntryDefault,+ resetEntry,+ writeBuiltinEntry,+} from "./builtinColorDialog";const getTypeLabel = (type: TInlineStyleType) => {if (type === "color") {@@ -30,7 +44,8 @@ const getTypeLabel = (type: TInlineStyleType) => {return window.siyuan.languages.color;};-const cloneInlineStyles = (): IInlineStyles => JSON.parse(JSON.stringify(getInlineStylesCache())) as IInlineStyles;+const cloneInlineStyles = (data = getInlineStylesCache()): IInlineStyles =>+ JSON.parse(JSON.stringify(normalizeInlineStyles(data))) as IInlineStyles;const renderPreviewStyle = (style: IInlineStyle) => {const preview = getInlineStylePreview(style, getCurrentInlineStyleMode(), false);@@ -38,6 +53,9 @@ const renderPreviewStyle = (style: IInlineStyle) => {`${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}`;};+const getBuiltinKey = (type: TInlineStyleType, key: string) =>+ type === "style1" ? key as TBuiltinInlineStyleID : Number(key);+export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroundColor",onChange?: (data: IInlineStyles) => void) => {if (window.siyuan.config.readonly || window.siyuan.isPublish) {@@ -45,104 +63,150 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun}const draft = cloneInlineStyles();const persistedStyleIDs = new Set(draft.styles.map(style => style.id));- let editingIndex: number | undefined;+ const properties = getProperties(initialType);+ let editingKey: string | undefined;+ let editingKind: "builtin" | "custom" | "new" | undefined;let saving = false;const dialog = new Dialog({title: window.siyuan.languages.color,width: isMobile() ? "92vw" : "600px",- content: `<div class="b3-dialog__content" style="max-height:70vh;overflow:auto">+ content: `<div class="b3-dialog__content" style="max-height:70vh"><div data-panel="list">- <div data-type="inlineStyleList" class="b3-list b3-list--background fn__selectnone" style="--file-toggle-width:0px"></div>+ <div data-type="inlineStyleList" class="b3-list b3-list--background fn__selectnone"></div>+ <div class="fn__hr" data-type="listSpacer"></div><div class="fn__flex" data-type="inlineStyleButtons">- <button class="b3-button b3-button--outline" data-action="manageBuiltin" type="button">- <svg><use xlink:href="#iconSettings"></use></svg>${window.siyuan.languages.manageBuiltinColors}- </button>- <div class="fn__space"></div>- <button class="b3-button b3-button--outline" data-action="new" type="button">- <svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.new}- </button>+ <button class="b3-button b3-button--outline" data-action="new" type="button">+ <svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.new}+ </button></div></div>- <div data-panel="editor" class="fn__none">- <label class="b3-label b3-label--inner fn__flex" style="align-items:center">- <span style="min-width:96px">${window.siyuan.languages.name}</span>- <input class="b3-text-field fn__flex-1" data-field="name" style="margin-top:0">+ <div data-panel="customEditor" class="fn__none">+ <label class="b3-label b3-label--inner fn__flex">+ <span class="fn__size96 fn__flex-center">${window.siyuan.languages.name}</span>+ <input class="b3-text-field fn__flex-1 fn__flex-center" data-field="name"></label>- <label class="b3-label b3-label--inner fn__flex" style="align-items:center">- <span style="min-width:96px">${window.siyuan.languages.type}</span>- <select class="b3-select fn__flex-1" data-field="type" style="margin-top:0">- <option value="color">${window.siyuan.languages.colorFont}</option>- <option value="backgroundColor">${window.siyuan.languages.colorPrimary}</option>- <option value="style1">${window.siyuan.languages.color}</option>- </select>- <span class="fn__flex-1 fn__none" data-field="typeLabel"></span>+ <label class="b3-label b3-label--inner fn__flex">+ <span class="fn__size96 fn__flex-center">${window.siyuan.languages.type}</span>+ <span class="fn__flex-1 fn__flex-center" data-field="typeLabel"></span></label>${getThemeColorEditorHTML()}</div>+ <div data-panel="builtinEditor" class="fn__none">+ ${getBuiltinEditorHTML(initialType)}+ </div></div><div class="b3-dialog__action" data-panel="actions">+ <button class="b3-button b3-button--outline fn__none" data-action="reset" type="button">${window.siyuan.languages.reset}</button>+ <div class="fn__flex-1"></div><button class="b3-button b3-button--cancel" data-action="cancel" type="button">${window.siyuan.languages.cancel}</button><div class="fn__space"></div><button class="b3-button b3-button--text" data-action="save" type="button">${window.siyuan.languages.save}</button></div>`,});const listPanel = dialog.element.querySelector('[data-panel="list"]') as HTMLElement;- const editorPanel = dialog.element.querySelector('[data-panel="editor"]') as HTMLElement;+ const customEditorPanel = dialog.element.querySelector('[data-panel="customEditor"]') as HTMLElement;+ const builtinEditorPanel = dialog.element.querySelector('[data-panel="builtinEditor"]') as HTMLElement;const listElement = dialog.element.querySelector('[data-type="inlineStyleList"]') as HTMLElement;const newElement = dialog.element.querySelector('[data-action="new"]') as HTMLButtonElement;- const buttonsElement = dialog.element.querySelector('[data-type="inlineStyleButtons"]') as HTMLElement;+ const spacerElement = dialog.element.querySelector('[data-type="listSpacer"]') as HTMLElement;+ const resetElement = dialog.element.querySelector('[data-action="reset"]') as HTMLButtonElement;const cancelElement = dialog.element.querySelector('[data-action="cancel"]') as HTMLButtonElement;const saveElement = dialog.element.querySelector('[data-action="save"]') as HTMLButtonElement;const nameElement = dialog.element.querySelector('[data-field="name"]') as HTMLInputElement;- const typeElement = dialog.element.querySelector('[data-field="type"]') as HTMLSelectElement;const typeLabelElement = dialog.element.querySelector('[data-field="typeLabel"]') as HTMLElement;- const themeColorEditor = bindThemeColorEditor(editorPanel);+ const customThemeEditor = bindThemeColorEditor(customEditorPanel);++ const getListKeys = () => getOrderedStyleKeys(initialType, draft);++ const getBuiltinEntry = (key: string) =>+ createBuiltinDialogEntry(initialType, getBuiltinKey(initialType, key), draft);++ const builtinEditor = bindBuiltinEditor(builtinEditorPanel, initialType, () =>+ editingKind === "builtin" && editingKey ? getBuiltinEntry(editingKey) : undefined);const renderList = () => {- listElement.innerHTML = draft.styles.length === 0 ?- "" :- draft.styles.map((style, index) => `<div class="b3-list-item b3-list-item--narrow" data-id="${escapeAttribute(style.id)}" data-index="${index}">- <span class="b3-list-item__graphic ariaLabel fn__grab" data-drag="true" draggable="true" data-position="north" aria-label="${escapeAttribute(window.siyuan.languages.sort)}"><svg><use xlink:href="#iconDrag"></use></svg></span>- <span class="color__square color__square--list" style="${renderPreviewStyle(style)}">A</span>- <span class="b3-list-item__text" title="${escapeAttribute(style.name)}">${escapeHtml(style.name)}</span>- <span class="b3-list-item__meta">${escapeHtml(getTypeLabel(getInlineStyleType(style) || "color"))}</span>- <span class="b3-list-item__action ariaLabel" data-action="edit" data-index="${index}" data-position="north" aria-label="${escapeAttribute(window.siyuan.languages.edit)}"><svg><use xlink:href="#iconEdit"></use></svg></span>- <span class="b3-list-item__action b3-list-item__action--warning ariaLabel" data-action="delete" data-index="${index}" data-position="north" aria-label="${escapeAttribute(window.siyuan.languages.delete)}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>-</div>`).join("");+ const keys = getListKeys();+ listElement.innerHTML = keys.map((key, index) => {+ const builtin = isBuiltinOrderKey(initialType, key);+ if (builtin) {+ const entry = getBuiltinEntry(key);+ return getColorListItemHTML({+ kind: "builtin",+ key,+ index,+ label: entry.label,+ show: entry.show,+ customized: isEntryCustomized(entry, properties),+ resetHidden: isEntryDefault(entry, properties),+ });+ }+ const style = getInlineStyleByID(key, draft);+ if (!style) {+ return "";+ }+ return getColorListItemHTML({+ kind: "custom",+ key,+ index,+ label: style.name,+ title: style.name,+ previewStyle: renderPreviewStyle(style),+ show: !style.hidden,+ canDelete: true,+ });+ }).join("");+ listElement.querySelectorAll<HTMLElement>('[data-kind="builtin"][data-key]').forEach(item => {+ const preview = item.querySelector('[data-role="preview"]') as HTMLElement;+ if (preview) {+ applyPreviewStyle(initialType, preview, getBuiltinEntry(item.dataset.key));+ }+ });newElement.disabled = draft.styles.length >= MAX_INLINE_STYLES;- buttonsElement.style.marginTop = draft.styles.length === 0 ? "0" : "8px";+ spacerElement.classList.toggle("fn__none", keys.length === 0);};- const setEditorActionMode = (editing: boolean) => {- cancelElement.dataset.action = editing ? "cancelEdit" : "cancel";- saveElement.dataset.action = editing ? "confirmEdit" : "save";- saveElement.textContent = editing ? window.siyuan.languages.confirm : window.siyuan.languages.save;+ const setEditorActionMode = (mode: "list" | "custom" | "builtin") => {+ listPanel.classList.toggle("fn__none", mode !== "list");+ customEditorPanel.classList.toggle("fn__none", mode !== "custom");+ builtinEditorPanel.classList.toggle("fn__none", mode !== "builtin");+ resetElement.classList.toggle("fn__none", mode !== "builtin");+ cancelElement.dataset.action = mode === "list" ? "cancel" : "cancelEdit";+ saveElement.dataset.action = mode === "list" ? "save" : "confirmEdit";+ saveElement.textContent = mode === "list" ? window.siyuan.languages.save : window.siyuan.languages.confirm;+ saveElement.removeAttribute("disabled");};const showList = () => {- editingIndex = undefined;- editorPanel.classList.add("fn__none");- listPanel.classList.remove("fn__none");- setEditorActionMode(false);+ editingKey = undefined;+ editingKind = undefined;+ setEditorActionMode("list");renderList();};- const showEditor = (index?: number) => {- editingIndex = index ?? -1;- const style = typeof index === "number" ? draft.styles[index] : undefined;+ const showCustomEditor = (key?: string) => {+ const style = key ? getInlineStyleByID(key, draft) : undefined;+ editingKey = key;+ editingKind = style ? "custom" : "new";nameElement.value = style?.name || "";- typeElement.value = style ? getInlineStyleType(style) : initialType;- typeElement.classList.toggle("fn__none", !!style);- typeLabelElement.classList.toggle("fn__none", !style);- typeLabelElement.textContent = getTypeLabel(typeElement.value as TInlineStyleType);- themeColorEditor.setValue(style, typeElement.value as TInlineStyleType);- listPanel.classList.add("fn__none");- editorPanel.classList.remove("fn__none");- setEditorActionMode(true);+ typeLabelElement.textContent = getTypeLabel(initialType);+ customThemeEditor.setValue(style, initialType);+ setEditorActionMode("custom");nameElement.focus();};+ const showBuiltinEditor = (key: string) => {+ editingKey = key;+ editingKind = "builtin";+ builtinEditor.fill(getBuiltinEntry(key));+ setEditorActionMode("builtin");+ };+const confirmEditor = () => {+ if (editingKind === "builtin" && editingKey) {+ writeBuiltinEntry(draft, initialType, builtinEditor.commit(getBuiltinEntry(editingKey)));+ showList();+ return;+ }const name = nameElement.value.trim();if (!name) {showMessage(window.siyuan.languages.namingEmpty, 6000, "error");@@ -154,111 +218,100 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrounnameElement.focus();return;}- const type = typeElement.value as TInlineStyleType;- const previous = editingIndex >= 0 ? draft.styles[editingIndex] : undefined;- const value = themeColorEditor.getValue(type);+ const previous = editingKey ? getInlineStyleByID(editingKey, draft) : undefined;+ const value = customThemeEditor.getValue(initialType);const style: IInlineStyle = {id: previous?.id || Lute.NewNodeID(),name,+ hidden: previous?.hidden,light: value.light,dark: value.dark,};if (previous) {- draft.styles[editingIndex] = style;+ draft.styles = draft.styles.map(item => item.id === previous.id ? style : item);} else {draft.styles.push(style);+ if (!draft.order[initialType].includes(style.id)) {+ draft.order[initialType].push(style.id);+ }}showList();};- let draggingIndex = -1;- const clearDragover = () => {- listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-index]").forEach(item => {- item.classList.remove("dragover__top", "dragover__bottom");- });- };- const clearDragStyles = () => {- clearDragover();- listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-index]").forEach(item => {- item.style.opacity = "";- });- };- listElement.addEventListener("dragstart", (event: DragEvent) => {- const handleElement = (event.target as HTMLElement).closest<HTMLElement>('[data-drag="true"]');- const itemElement = handleElement?.closest<HTMLElement>(".b3-list-item[data-index]");- if (!itemElement) {- event.preventDefault();- return;- }- draggingIndex = parseInt(itemElement.dataset.index);- event.dataTransfer.effectAllowed = "move";- event.dataTransfer.setData("text/plain", itemElement.dataset.index);- itemElement.style.opacity = ".38";+ bindColorListDrag(listElement, getListKeys, keys => {+ draft.order[initialType] = keys;+ renderList();});- listElement.addEventListener("dragover", (event: DragEvent) => {- const itemElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item[data-index]");- if (!itemElement || draggingIndex < 0) {- return;+ listElement.addEventListener("click", event => {+ if ((event.target as HTMLElement).closest('[data-action="toggleShow"]')) {+ event.stopPropagation();}- event.preventDefault();- event.dataTransfer.dropEffect = "move";- clearDragover();- const rect = itemElement.getBoundingClientRect();- itemElement.classList.add(event.clientY < rect.top + rect.height / 2 ? "dragover__top" : "dragover__bottom");});- listElement.addEventListener("drop", (event: DragEvent) => {- const itemElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item[data-index]");- if (!itemElement || draggingIndex < 0) {+ listElement.addEventListener("change", event => {+ const switchElement = (event.target as HTMLElement).closest<HTMLInputElement>('[data-action="toggleShow"]');+ const itemElement = switchElement?.closest<HTMLElement>("[data-key]");+ if (!switchElement || !itemElement) {return;}- event.preventDefault();- const targetIndex = parseInt(itemElement.dataset.index);- const rect = itemElement.getBoundingClientRect();- const before = event.clientY < rect.top + rect.height / 2;- let insertIndex = targetIndex + (before ? 0 : 1);- if (draggingIndex < insertIndex) {- insertIndex--;+ if (itemElement.dataset.kind === "builtin") {+ const entry = getBuiltinEntry(itemElement.dataset.key);+ entry.show = switchElement.checked;+ writeBuiltinEntry(draft, initialType, entry);+ itemElement.querySelector('[data-action="resetItem"]')?.classList.toggle("fn__none", isEntryDefault(entry, properties));+ return;}- if (draggingIndex !== insertIndex) {- const [style] = draft.styles.splice(draggingIndex, 1);- draft.styles.splice(insertIndex, 0, style);- renderList();+ const style = getInlineStyleByID(itemElement.dataset.key, draft);+ if (style) {+ style.hidden = !switchElement.checked;}- draggingIndex = -1;- clearDragStyles();- });- listElement.addEventListener("dragend", () => {- draggingIndex = -1;- clearDragStyles();});- typeElement.addEventListener("change", () => {- themeColorEditor.setType(typeElement.value as TInlineStyleType);- });dialog.element.addEventListener("click", async event => {const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");- if (!actionElement || actionElement.hasAttribute("disabled")) {+ if (!actionElement || actionElement.hasAttribute("disabled") || actionElement.classList.contains("fn__none")) {return;}const action = actionElement.dataset.action;- const index = parseInt(actionElement.dataset.index);+ if (action === "toggleShow") {+ event.stopPropagation();+ return;+ }+ const itemElement = actionElement.closest<HTMLElement>("[data-key]");+ const key = itemElement?.dataset.key;if (action === "new") {if (draft.styles.length >= MAX_INLINE_STYLES) {showMessage(window.siyuan.languages.invalid, 6000, "error");return;}- showEditor();- } else if (action === "manageBuiltin") {- openBuiltinColorDialog(initialType, onChange);- } else if (action === "edit") {- showEditor(index);- } else if (action === "delete") {- const style = draft.styles[index];+ showCustomEditor();+ } else if (action === "edit" && key) {+ if (itemElement.dataset.kind === "builtin") {+ showBuiltinEditor(key);+ } else {+ showCustomEditor(key);+ }+ } else if (action === "resetItem" && key) {+ const entry = getBuiltinEntry(key);+ resetEntry(entry, properties);+ writeBuiltinEntry(draft, initialType, entry);+ renderList();+ } else if (action === "reset") {+ if (editingKind === "builtin" && editingKey) {+ const entry = getBuiltinEntry(editingKey);+ resetEntry(entry, properties);+ writeBuiltinEntry(draft, initialType, entry);+ showBuiltinEditor(editingKey);+ }+ } else if (action === "delete" && key) {+ const style = getInlineStyleByID(key, draft);if (!style) {return;}const removeStyle = () => {- draft.styles.splice(index, 1);+ draft.styles = draft.styles.filter(item => item.id !== key);+ (["color", "backgroundColor", "style1"] as TInlineStyleType[]).forEach(type => {+ draft.order[type] = draft.order[type].filter(item => item !== key);+ });renderList();};if (persistedStyleIDs.has(style.id)) {@@ -278,10 +331,7 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrounsaving = true;actionElement.setAttribute("disabled", "disabled");try {- const response = await saveInlineStyles({- ...draft,- builtin: cloneInlineStyles().builtin,- });+ const response = await saveInlineStyles(draft);if (response?.code !== 0) {showMessage(response?.msg || window.siyuan.languages.invalid, 6000, "error");saving = false;@@ -301,5 +351,6 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgrounevent.preventDefault();event.stopPropagation();});+ typeLabelElement.textContent = getTypeLabel(initialType);renderList();};diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 15ffcf2ef3..16bfe161de 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -1223,6 +1223,7 @@ interface IAVColor {interface IAVCustomColor extends IAVColor {index: number;+ hidden?: boolean;}interface IAV {@@ -1236,6 +1237,7 @@ interface IAV {newItemTemplates?: IAVNewItemTemplate[];defaultTemplateID?: string;customColors?: IAVCustomColor[];+ colorOrder?: string[];usedCustomColorIndexes?: number[];target?: IAVRenderTarget;}diff --git a/kernel/api/av.go b/kernel/api/av.goindex 297b1c7733..6da7ce6655 100644--- a/kernel/api/av.go+++ b/kernel/api/av.go@@ -1145,7 +1145,8 @@ func renderSnapshotAttributeView(c *gin.Context) {ret.Data = map[string]any{"name": attrView.Name,"id": attrView.ID,- "customColors": attrView.CustomColors,+ "customColors": attrView.Palette(),+ "colorOrder": attrView.PaletteOrder(),"usedCustomColorIndexes": attrView.UsedCustomColorIndexes(),"viewType": view.GetType(),"viewID": view.GetID(),@@ -1242,7 +1243,8 @@ func renderHistoryAttributeView(c *gin.Context) {ret.Data = map[string]any{"name": attrView.Name,"id": attrView.ID,- "customColors": attrView.CustomColors,+ "customColors": attrView.Palette(),+ "colorOrder": attrView.PaletteOrder(),"usedCustomColorIndexes": attrView.UsedCustomColorIndexes(),"viewType": view.GetType(),"viewID": view.GetID(),@@ -1399,7 +1401,8 @@ func renderAttrView(blockID, avID, viewID, query string, page, pageSize int, groretData := map[string]any{"name": attrView.Name,"id": attrView.ID,- "customColors": attrView.CustomColors,+ "customColors": attrView.Palette(),+ "colorOrder": attrView.PaletteOrder(),"usedCustomColorIndexes": attrView.UsedCustomColorIndexes(),"viewType": view.GetType(),"viewID": view.GetID(),diff --git a/kernel/api/inline_style.go b/kernel/api/inline_style.goindex b673aec9a4..7290c0d540 100644--- a/kernel/api/inline_style.go+++ b/kernel/api/inline_style.go@@ -95,3 +95,48 @@ func setInlineStyles(c *gin.Context) {util.ReloadPublishServiceSessions()}}++func setWorkspaceAVPalette(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }+ var app string+ var colors, order, builtinColors []any+ if !util.ParseJsonArgs(arg, ret,+ util.BindJsonArg("colors", &colors, true, false),+ util.BindJsonArg("order", &order, true, false),+ util.BindJsonArg("builtinColors", &builtinColors, false, false),+ util.BindJsonArg("app", &app, false, false),+ ) {+ return+ }+ data, err := gulu.JSON.MarshalJSON(arg)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ update := &model.WorkspaceAVPaletteUpdate{}+ if err = gulu.JSON.UnmarshalJSON(data, update); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ saved, changed, err := model.SetWorkspaceAVPalette(update)+ if err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ ret.Data = saved+ if changed {+ evt := util.NewCmdResult("reloadInlineStyles", 0, util.PushModeBroadcastMainExcludeSelfApp)+ evt.AppId = app+ util.PushEvent(evt)+ util.ReloadPublishServiceSessions()+ }+}diff --git a/kernel/api/inline_style_test.go b/kernel/api/inline_style_test.goindex 2d7f123c9b..3ba8129ce9 100644--- a/kernel/api/inline_style_test.go+++ b/kernel/api/inline_style_test.go@@ -21,6 +21,7 @@ import ("net/http""net/http/httptest""os"+ "reflect""strings""testing"@@ -37,6 +38,7 @@ func TestInlineStylesAPI(t *testing.T) {engine := gin.New()engine.POST("/api/storage/getInlineStyles", getInlineStyles)engine.POST("/api/storage/setInlineStyles", setInlineStyles)+ engine.POST("/api/storage/setWorkspaceAVPalette", setWorkspaceAVPalette)getRecorder := performInlineStylesRequest(engine, "/api/storage/getInlineStyles", "")getResponse := &struct {@@ -126,7 +128,7 @@ func TestInlineStylesAPI(t *testing.T) {}invalidBuiltinRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles",- `{"version":2,"styles":[],"builtin":{"hidden":{"av":[14]}}}`)+ `{"version":2,"styles":[],"builtin":{"hidden":{"av":[15]}}}`)if responseCode(t, invalidBuiltinRecorder) != -1 {t.Fatalf("invalid builtin inline styles were accepted: %s", invalidBuiltinRecorder.Body.String())}@@ -135,6 +137,35 @@ func TestInlineStylesAPI(t *testing.T) {if responseCode(t, missingVersionRecorder) != -1 || !strings.Contains(missingVersionRecorder.Body.String(), "version") {t.Fatalf("missing inline styles version was accepted: %s", missingVersionRecorder.Body.String())}++ paletteRecorder := performInlineStylesRequest(engine, "/api/storage/setWorkspaceAVPalette", `{+ "colors":[{+ "index":15,+ "light":{"color":"#010203","backgroundColor":"#040506"},+ "dark":{"color":"#070809","backgroundColor":"#0A0B0C"}+ }],+ "order":["15","1"],+ "builtinColors":[{+ "index":3,+ "customized":true,+ "light":{"backgroundColor":"#ABCDEF"},+ "dark":{"backgroundColor":"#123456"},+ "hidden":true+ }]+ }`)+ paletteResponse := &struct {+ Code int `json:"code"`+ Data *model.InlineStyles `json:"data"`+ }{}+ if err := json.Unmarshal(paletteRecorder.Body.Bytes(), paletteResponse); err != nil {+ t.Fatal(err)+ }+ if paletteResponse.Code != 0 || paletteResponse.Data == nil || len(paletteResponse.Data.Styles) != 1 ||+ len(paletteResponse.Data.AV.Colors) != 1 || paletteResponse.Data.AV.Order[0] != "15" ||+ len(paletteResponse.Data.Builtin.Colors) != 2 ||+ !reflect.DeepEqual(paletteResponse.Data.Builtin.Hidden.AV, []int{3, 5}) {+ t.Fatalf("unexpected workspace palette response: %s", paletteRecorder.Body.String())+ }}func TestInlineStylesAPIPermissions(t *testing.T) {@@ -156,6 +187,11 @@ func TestInlineStylesAPIPermissions(t *testing.T) {if setRecorder.Code != http.StatusForbidden {t.Fatalf("reader changed inline styles: status=%d, body=%s", setRecorder.Code, setRecorder.Body.String())}+ paletteRecorder := performInlineStylesRequest(engine, "/api/storage/setWorkspaceAVPalette", `{"colors":[],"order":[]}`)+ if paletteRecorder.Code != http.StatusForbidden {+ t.Fatalf("reader changed workspace palette: status=%d, body=%s", paletteRecorder.Code,+ paletteRecorder.Body.String())+ }}func performInlineStylesRequest(engine *gin.Engine, path, body string) *httptest.ResponseRecorder {diff --git a/kernel/api/router.go b/kernel/api/router.goindex 6e6dcaf46f..ad9c68662b 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -111,6 +111,8 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/storage/removeLocalStorageVals", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeLocalStorageVals)ginServer.Handle("POST", "/api/storage/getInlineStyles", model.CheckAuth, getInlineStyles)ginServer.Handle("POST", "/api/storage/setInlineStyles", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setInlineStyles)+ ginServer.Handle("POST", "/api/storage/setWorkspaceAVPalette", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly,+ setWorkspaceAVPalette)ginServer.Handle("POST", "/api/storage/getCriteria", model.CheckAuth, getCriteria)ginServer.Handle("POST", "/api/storage/setCriterion", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setCriterion)ginServer.Handle("POST", "/api/storage/removeCriterion", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeCriterion)diff --git a/kernel/av/av.go b/kernel/av/av.goindex e0d3d85473..fcc64ccd0c 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -41,15 +41,14 @@ import (// AttributeView 描述了属性视图的结构。type AttributeView struct {- Spec int `json:"spec"` // 格式版本- ID string `json:"id"` // 属性视图 ID- Name string `json:"name"` // 属性视图名称- KeyValues []*KeyValues `json:"keyValues"` // 属性视图属性键值- KeyIDs []string `json:"keyIDs"` // 属性视图属性键 ID,用于排序- Views []*View `json:"views"` // 视图- NewItemTemplates []*NewItemTemplate `json:"newItemTemplates,omitempty"` // 新增条目模板- DefaultTemplateID string `json:"defaultTemplateID,omitempty"` // 默认新增条目模板 ID- CustomColors []*AttributeViewCustomColor `json:"customColors,omitempty"` // 数据库级自定义选项颜色+ Spec int `json:"spec"` // 格式版本+ ID string `json:"id"` // 属性视图 ID+ Name string `json:"name"` // 属性视图名称+ KeyValues []*KeyValues `json:"keyValues"` // 属性视图属性键值+ KeyIDs []string `json:"keyIDs"` // 属性视图属性键 ID,用于排序+ Views []*View `json:"views"` // 视图+ NewItemTemplates []*NewItemTemplate `json:"newItemTemplates,omitempty"` // 新增条目模板+ DefaultTemplateID string `json:"defaultTemplateID,omitempty"` // 默认新增条目模板 ID// CustomColorRenderContext 保存只读渲染期间的关联数据库调色板上下文。CustomColorRenderContext *CustomColorRenderContext `json:"-"`// 卡片封面位置,条目 ID -> 封面来源 -> 位置@@ -62,7 +61,7 @@ type AttributeView struct {// CustomColorRenderContext 为历史和仓库快照渲染解析关联数据库当时的调色板。type CustomColorRenderContext struct {- ResolveRelatedCustomColors func(avID string) (colors []*AttributeViewCustomColor, found bool)+ ResolveRelatedCustomColors func(avID string) (colors []*AttributeViewCustomColor, order []string, found bool)}// NewItemTargetType 描述新增条目模板创建的目标类型。@@ -515,7 +514,6 @@ func NewAttributeView(id string) (ret *AttributeView) {ID: id,KeyValues: []*KeyValues{{Key: blockKey}, {Key: selectKey}},Views: []*View{view},- CustomColors: []*AttributeViewCustomColor{},RenderedViewables: map[string]Viewable{},}return@@ -791,6 +789,23 @@ func ParseAttributeViewByPath(avJSONPath string) (ret *AttributeView, err error)}func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeView, err error) {+ return parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID, true)+}++// ReadAttributeViewCustomColorUsageByPath 读取属性视图持久化数据中的自定义颜色引用,但不解析派生颜色。+func ReadAttributeViewCustomColorUsageByPath(avJSONPath string) (avID string, indexes []int, err error) {+ avID = strings.TrimSuffix(filepath.Base(avJSONPath), filepath.Ext(avJSONPath))+ attrView, err := parseAttributeViewByPathInBoxWithOptions(avJSONPath, avBoxIDFromPath(avJSONPath), false)+ if err != nil {+ return avID, nil, err+ }+ if attrView == nil {+ return avID, nil, errors.New("attribute view content is unavailable")+ }+ return avID, attrView.UsedCustomColorIndexes(), nil+}++func parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID string, resolveColors bool) (ret *AttributeView, err error) {if !filelock.IsExist(avJSONPath) {err = ErrViewNotFoundreturn@@ -892,9 +907,10 @@ func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeViewerr = CheckSpec(ret)}if nil == err {- _ = ret.NormalizeCustomColors(false)- ret.ResolveDirectColors()- cache.SetAVSearchDataInBox(avID, boxID, dataVersion, newAttributeViewSearchInfo(ret))+ if resolveColors {+ ret.ResolveDirectColors()+ cache.SetAVSearchDataInBox(avID, boxID, dataVersion, newAttributeViewSearchInfo(ret))+ }}return}@@ -913,9 +929,6 @@ func SaveAttributeView(av *AttributeView) (err error) {// 做一些数据兼容和订正处理UpgradeSpec(av)- if err = av.NormalizeCustomColors(true); nil != err {- return- }// 值去重blockValues := av.GetBlockKeyValues()diff --git a/kernel/av/av_fix.go b/kernel/av/av_fix.goindex 0912f865a8..0f449fb510 100644--- a/kernel/av/av_fix.go+++ b/kernel/av/av_fix.go@@ -68,9 +68,6 @@ func upgradeSpec8(av *AttributeView) {return}- if nil == av.CustomColors {- av.CustomColors = []*AttributeViewCustomColor{}- }av.Spec = 8}diff --git a/kernel/av/av_fix_test.go b/kernel/av/av_fix_test.goindex 6aada8ed8f..f58d3e9631 100644--- a/kernel/av/av_fix_test.go+++ b/kernel/av/av_fix_test.go@@ -78,24 +78,10 @@ func TestUpgradeSpec7RemovesPersistedCurrentView(t *testing.T) {}}-func TestUpgradeSpec8InitializesCustomColors(t *testing.T) {+func TestUpgradeSpec8(t *testing.T) {attrView := &AttributeView{Spec: 7}UpgradeSpec(attrView)if CurrentSpec != attrView.Spec {t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)}- if nil == attrView.CustomColors || 0 != len(attrView.CustomColors) {- t.Fatalf("spec 8 upgrade should initialize an empty custom palette: %+v", attrView.CustomColors)- }-- attrView = &AttributeView{Spec: 7, CustomColors: []*AttributeViewCustomColor{- testAttributeViewCustomColor(15, "#000000", "#ffffff", "#ffffff", "#000000"),- }}- UpgradeSpec(attrView)- if CurrentSpec != attrView.Spec {- t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)- }- if 1 != len(attrView.CustomColors) || 15 != attrView.CustomColors[0].Index {- t.Fatalf("spec 8 upgrade discarded an assigned custom palette: %+v", attrView.CustomColors)- }}diff --git a/kernel/av/color.go b/kernel/av/color.goindex 5849b769d2..2d0413ca5f 100644--- a/kernel/av/color.go+++ b/kernel/av/color.go@@ -31,10 +31,18 @@ const (CustomColorMinIndex = 15CustomColorMaxIndex = 78MaxCustomColors = CustomColorMaxIndex - CustomColorMinIndex + 1+ BuiltinColorCount = 14)var attributeViewColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)+// LoadWorkspacePalette 返回工作空间级数据库自定义色。由 model 在启动时绑定。+var LoadWorkspacePalette func() (colors []*AttributeViewCustomColor, order []string)++type persistedAttributeViewPalette struct {+ CustomColors []*AttributeViewCustomColor `json:"customColors"`+}+// AttributeViewColorTheme 描述一种主题模式下的数据库选项颜色。type AttributeViewColorTheme struct {Color string `json:"color"`@@ -49,7 +57,8 @@ type AttributeViewColor struct {// AttributeViewCustomColor 描述数据库级自定义选项颜色及其稳定编号。type AttributeViewCustomColor struct {- Index int `json:"index"`+ Index int `json:"index"`+ Hidden bool `json:"hidden,omitempty"`AttributeViewColor}@@ -128,7 +137,7 @@ func normalizeAttributeViewCustomColor(color *AttributeViewCustomColor) (ret *Atcolor.Index, CustomColorMinIndex, CustomColorMaxIndex)}- ret = &AttributeViewCustomColor{Index: color.Index}+ ret = &AttributeViewCustomColor{Index: color.Index, Hidden: color.Hidden}ret.Light, err = normalizeAttributeViewColorTheme(color.Light)if nil != err {return nil, fmt.Errorf("invalid light theme of attribute view custom color [%d]: %w", color.Index, err)@@ -152,27 +161,77 @@ func normalizeAttributeViewColorTheme(theme AttributeViewColorTheme) (ret Attribreturn}-// NormalizeCustomColors 校验并替换数据库自定义颜色。-func (av *AttributeView) NormalizeCustomColors(strict bool) error {- if nil == av {- return errors.New("attribute view must not be nil")+// WorkspacePalette 返回当前工作空间的数据库自定义色和混排顺序。+func WorkspacePalette() (colors []*AttributeViewCustomColor, order []string) {+ if LoadWorkspacePalette != nil {+ colors, order = LoadWorkspacePalette()}- colors, err := NormalizeAttributeViewCustomColors(av.CustomColors, strict)- if nil != err {- return err+ if nil == colors {+ colors = []*AttributeViewCustomColor{}}- av.CustomColors = colors- return nil+ order = NormalizeAttributeViewColorOrder(order, colors)+ return+}++// DecodePersistedPalette 从属性视图 JSON 中读取历史快照里的自定义色,不写入属性视图结构体。+func DecodePersistedPalette(data []byte) (colors []*AttributeViewCustomColor, err error) {+ parsed := &persistedAttributeViewPalette{}+ if err = json.Unmarshal(data, parsed); nil != err {+ return+ }+ return NormalizeAttributeViewCustomColors(parsed.CustomColors, false)+}++// DefaultAttributeViewColorOrder 返回内置色在前、自定义色按编号排列的默认顺序。+func DefaultAttributeViewColorOrder(colors []*AttributeViewCustomColor) []string {+ keys := make([]string, 0, BuiltinColorCount+len(colors))+ for index := 1; index <= BuiltinColorCount; index++ {+ keys = append(keys, strconv.Itoa(index))+ }+ for _, color := range colors {+ if nil != color {+ keys = append(keys, strconv.Itoa(color.Index))+ }+ }+ return keys+}++// NormalizeAttributeViewColorOrder 保留已保存的混排顺序,并补上新增的内置色或自定义色。+func NormalizeAttributeViewColorOrder(order []string, colors []*AttributeViewCustomColor) []string {+ allowed := make(map[string]struct{}, BuiltinColorCount+len(colors))+ defaults := DefaultAttributeViewColorOrder(colors)+ for _, key := range defaults {+ allowed[key] = struct{}{}+ }+ seen := make(map[string]struct{}, len(allowed))+ ret := make([]string, 0, len(allowed))+ for _, key := range order {+ if _, ok := allowed[key]; !ok {+ continue+ }+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ ret = append(ret, key)+ }+ for _, key := range defaults {+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ ret = append(ret, key)+ }+ return ret}// NextCustomColorIndex 返回最小的可用自定义颜色编号,没有可用编号时返回 0。func (av *AttributeView) NextCustomColorIndex() int {used := map[int]struct{}{}- if nil != av {- for _, color := range av.CustomColors {- if nil != color {- used[color.Index] = struct{}{}- }+ colors, _ := av.customColorPalette()+ for _, color := range colors {+ if nil != color {+ used[color.Index] = struct{}{}}}for index := CustomColorMinIndex; index <= CustomColorMaxIndex; index++ {@@ -183,13 +242,46 @@ func (av *AttributeView) NextCustomColorIndex() int {return 0}+func (av *AttributeView) customColorPalette() (colors []*AttributeViewCustomColor, order []string) {+ if av != nil && av.CustomColorRenderContext != nil &&+ av.CustomColorRenderContext.ResolveRelatedCustomColors != nil {+ colors, order, found := av.CustomColorRenderContext.ResolveRelatedCustomColors(av.ID)+ if !found {+ return []*AttributeViewCustomColor{}, DefaultAttributeViewColorOrder(nil)+ }+ normalized, _ := NormalizeAttributeViewCustomColors(colors, false)+ return normalized, NormalizeAttributeViewColorOrder(order, normalized)+ }+ return WorkspacePalette()+}++// Palette 返回当前渲染上下文或工作空间中的数据库自定义色。+func (av *AttributeView) Palette() []*AttributeViewCustomColor {+ colors, _ := av.customColorPalette()+ if nil == colors {+ return []*AttributeViewCustomColor{}+ }+ return colors+}++// PaletteOrder 返回当前渲染上下文或工作空间中的数据库颜色顺序。+func (av *AttributeView) PaletteOrder() []string {+ colors, order := av.customColorPalette()+ return NormalizeAttributeViewColorOrder(order, colors)+}+// ResolveColor 根据自定义颜色编号返回经过校验的明暗主题颜色。func (av *AttributeView) ResolveColor(color string) *AttributeViewColor {+ colors, _ := av.customColorPalette()+ return resolveColor(color, colors)+}++func resolveColor(color string, colors []*AttributeViewCustomColor) *AttributeViewColor {index, err := strconv.Atoi(strings.TrimSpace(color))- if nil != err || index < CustomColorMinIndex || CustomColorMaxIndex < index || nil == av {+ if nil != err || index < CustomColorMinIndex || CustomColorMaxIndex < index {return nil}- for _, customColor := range av.CustomColors {+ for _, customColor := range colors {if nil == customColor || customColor.Index != index {continue}@@ -220,6 +312,7 @@ func (av *AttributeView) ResolveDirectColors() {if nil == av {return}+ colors, _ := av.customColorPalette()for _, keyValues := range av.KeyValues {if nil == keyValues {continue@@ -227,16 +320,16 @@ func (av *AttributeView) ResolveDirectColors() {if nil != keyValues.Key {for _, option := range keyValues.Key.Options {if nil != option {- option.ResolvedColor = av.ResolveColor(option.Color)+ option.ResolvedColor = resolveColor(option.Color, colors)}}}for _, value := range keyValues.Values {- resolveValueSelectColors(value, av)+ resolveValueSelectColors(value, colors)}}for _, view := range av.Views {- av.resolveDirectViewGroupColors(view)+ av.resolveDirectViewGroupColors(view, colors)}}@@ -252,15 +345,10 @@ func (av *AttributeView) ApplyRelatedCustomColorRenderContext(target *AttributeVreturn}target.CustomColorRenderContext = context- colors, found := context.ResolveRelatedCustomColors(target.ID)- if !found {- colors = []*AttributeViewCustomColor{}- }- target.CustomColors, _ = NormalizeAttributeViewCustomColors(colors, false)target.ResolveDirectColors()}-func (av *AttributeView) resolveDirectViewGroupColors(view *View) {+func (av *AttributeView) resolveDirectViewGroupColors(view *View, colors []*AttributeViewCustomColor) {if nil == view {return}@@ -269,29 +357,30 @@ func (av *AttributeView) resolveDirectViewGroupColors(view *View) {(KeyTypeSelect == key.Type || KeyTypeMSelect == key.Type) {for _, option := range view.GroupKey.Options {if nil != option {- option.ResolvedColor = av.ResolveColor(option.Color)+ option.ResolvedColor = resolveColor(option.Color, colors)}}- resolveValueSelectColors(view.GroupVal, av)+ resolveValueSelectColors(view.GroupVal, colors)}}for _, group := range view.Groups {- av.resolveDirectViewGroupColors(group)+ av.resolveDirectViewGroupColors(group, colors)}}// ResolveValueSelectColors 为数据库上下文中的直接选择值填充派生颜色。func (av *AttributeView) ResolveValueSelectColors(value *Value) {- resolveValueSelectColors(value, av)+ colors, _ := av.customColorPalette()+ resolveValueSelectColors(value, colors)}-func resolveValueSelectColors(value *Value, av *AttributeView) {+func resolveValueSelectColors(value *Value, colors []*AttributeViewCustomColor) {if nil == value {return}for _, selection := range value.MSelect {if nil != selection {- selection.ResolvedColor = av.ResolveColor(selection.Color)+ selection.ResolvedColor = resolveColor(selection.Color, colors)}}}@@ -302,7 +391,6 @@ type resolvedColorBinding struct {color *AttributeViewColor}-// suspendResolvedColors 在序列化持久化数据期间临时清除所有派生颜色。func (av *AttributeView) suspendResolvedColors() (restore func()) {var bindings []resolvedColorBindingif nil != av {diff --git a/kernel/av/color_render_context_test.go b/kernel/av/color_render_context_test.goindex f002fec632..31cadb8fea 100644--- a/kernel/av/color_render_context_test.go+++ b/kernel/av/color_render_context_test.go@@ -26,14 +26,14 @@ func TestRollupFilterUsesHistoricalTargetCustomColorContext(t *testing.T) {}source := &AttributeView{CustomColorRenderContext: &CustomColorRenderContext{- ResolveRelatedCustomColors: func(string) ([]*AttributeViewCustomColor, bool) {+ ResolveRelatedCustomColors: func(string) ([]*AttributeViewCustomColor, []string, bool) {return []*AttributeViewCustomColor{{Index: 15,AttributeViewColor: AttributeViewColor{Light: AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},Dark: AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},},- }}, true+ }}, []string{"15", "1"}, true},},KeyValues: []*KeyValues{@@ -50,17 +50,22 @@ func TestRollupFilterUsesHistoricalTargetCustomColorContext(t *testing.T) {}target := &AttributeView{ID: "target",- CustomColors: []*AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: AttributeViewColor{- Light: AttributeViewColorTheme{Color: "#111213", BackgroundColor: "#141516"},- Dark: AttributeViewColorTheme{Color: "#171819", BackgroundColor: "#1a1b1c"},- },- }},KeyValues: []*KeyValues{{Key: &Key{ID: "select", Type: KeyTypeSelect}, Values: []*Value{targetValue},}},}+ current := []*AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: AttributeViewColor{+ Light: AttributeViewColorTheme{Color: "#111213", BackgroundColor: "#141516"},+ Dark: AttributeViewColorTheme{Color: "#171819", BackgroundColor: "#1a1b1c"},+ },+ }}+ old := LoadWorkspacePalette+ t.Cleanup(func() { LoadWorkspacePalette = old })+ LoadWorkspacePalette = func() ([]*AttributeViewCustomColor, []string) {+ return current, DefaultAttributeViewColorOrder(current)+ }target.ResolveDirectColors()rollupValue := &Value{KeyID: rollupKey.ID, BlockID: "source-item", Type: KeyTypeRollup, Rollup: &ValueRollup{}}filter := &ViewFilter{diff --git a/kernel/av/color_test.go b/kernel/av/color_test.goindex 1ef86abad8..3c6860c877 100644--- a/kernel/av/color_test.go+++ b/kernel/av/color_test.go@@ -35,6 +35,18 @@ func testAttributeViewCustomColor(index int, lightColor, lightBackground, darkCo}}+func withWorkspacePalette(t *testing.T, colors *[]*AttributeViewCustomColor) {+ t.Helper()+ old := LoadWorkspacePalette+ t.Cleanup(func() { LoadWorkspacePalette = old })+ LoadWorkspacePalette = func() ([]*AttributeViewCustomColor, []string) {+ if colors == nil {+ return nil, nil+ }+ return *colors, DefaultAttributeViewColorOrder(*colors)+ }+}+func TestFilterColorValuePreservesPaletteIndex(t *testing.T) {for _, color := range []string{"", "1", "14"} {if filtered := FilterColorValue(color); filtered != color {@@ -106,24 +118,29 @@ func TestNormalizeAttributeViewCustomColors(t *testing.T) {if err = json.Unmarshal(data, &fields); nil != err {t.Fatalf("unmarshal custom color fields failed: %s", err)}- if 3 != len(fields) || nil == fields["index"] || nil == fields["light"] || nil == fields["dark"] {- t.Fatalf("custom color JSON must contain only index/light/dark: %s", data)+ if nil == fields["index"] || nil == fields["light"] || nil == fields["dark"] {+ t.Fatalf("custom color JSON is missing required fields: %s", data)+ }+ for key := range fields {+ if key != "index" && key != "light" && key != "dark" && key != "hidden" {+ t.Fatalf("unexpected custom color JSON field [%s]: %s", key, data)+ }}- invalidView := &AttributeView{ID: "20260824120000-colors1", Spec: CurrentSpec}- invalidView.CustomColors = []*AttributeViewCustomColor{+ if _, err = NormalizeAttributeViewCustomColors([]*AttributeViewCustomColor{testAttributeViewCustomColor(14, "#000000", "#ffffff", "#000000", "#ffffff"),- }- if err = SaveAttributeView(invalidView); nil == err {- t.Fatal("save attribute view accepted an invalid custom palette")+ }, true); nil == err {+ t.Fatal("invalid custom palette index was accepted")}}func TestAttributeViewCustomColorIndexes(t *testing.T) {- attrView := &AttributeView{CustomColors: []*AttributeViewCustomColor{+ palette := []*AttributeViewCustomColor{testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),testAttributeViewCustomColor(17, "#111213", "#141516", "#171819", "#1a1b1c"),- }}+ }+ withWorkspacePalette(t, &palette)+ attrView := &AttributeView{}if 16 != attrView.NextCustomColorIndex() {t.Fatalf("expected the smallest free custom color index, got %d", attrView.NextCustomColorIndex())}@@ -159,9 +176,34 @@ func TestAttributeViewCustomColorIndexes(t *testing.T) {if 16 != attrView.NextCustomColorIndex() {t.Fatalf("existing gaps were unexpectedly reordered, got next index %d", attrView.NextCustomColorIndex())}- attrView.CustomColors = attrView.CustomColors[1:]- if 15 != attrView.NextCustomColorIndex() || 17 != attrView.CustomColors[0].Index {- t.Fatalf("deleting a color reordered stable indexes: %+v", attrView.CustomColors)+ palette = palette[1:]+ if 15 != attrView.NextCustomColorIndex() || 17 != palette[0].Index {+ t.Fatalf("deleting a color reordered stable indexes: %+v", palette)+ }+}++func TestResolveDirectColorsLoadsWorkspacePaletteOnce(t *testing.T) {+ color := testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c")+ old := LoadWorkspacePalette+ t.Cleanup(func() { LoadWorkspacePalette = old })+ calls := 0+ LoadWorkspacePalette = func() ([]*AttributeViewCustomColor, []string) {+ calls+++ return []*AttributeViewCustomColor{color}, []string{"15", "1"}+ }+ attrView := &AttributeView{+ KeyValues: []*KeyValues{{+ Key: &Key{ID: "select", Type: KeyTypeSelect, Options: []*SelectOption{{Color: "15"}, {Color: "15"}}},+ Values: []*Value{{MSelect: []*ValueSelect{{Color: "15"}, {Color: "15"}}}},+ }},+ Views: []*View{{+ GroupKey: &Key{ID: "select", Type: KeyTypeSelect, Options: []*SelectOption{{Color: "15"}}},+ GroupVal: &Value{MSelect: []*ValueSelect{{Color: "15"}}},+ }},+ }+ attrView.ResolveDirectColors()+ if calls != 1 {+ t.Fatalf("workspace palette was loaded %d times, want 1", calls)}}@@ -231,14 +273,15 @@ func TestResolvedColorCannotBeLoadedFromJSON(t *testing.T) {}attrView := &AttributeView{- CustomColors: []*AttributeViewCustomColor{- testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),- },KeyValues: []*KeyValues{{Key: &Key{Options: []*SelectOption{option}},Values: []*Value{{Type: KeyTypeSelect, MSelect: []*ValueSelect{selection}}},}},}+ palette := []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),+ }+ withWorkspacePalette(t, &palette)attrView.ResolveDirectColors()if nil == option.ResolvedColor || nil == selection.ResolvedColor {t.Fatal("direct option and value colors were not resolved from the validated palette")@@ -271,10 +314,9 @@ func TestGroupResolvedColorSurvivesPersistenceRoundTrip(t *testing.T) {selectKey := &Key{ID: "select", Type: KeyTypeSelect}selectKey.Options = []*SelectOption{{Name: "Group", Color: "15"}}attrView := &AttributeView{- Spec: CurrentSpec,- ID: "20260824120000-colors2",- CustomColors: []*AttributeViewCustomColor{testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c")},- KeyValues: []*KeyValues{{Key: selectKey}},+ Spec: CurrentSpec,+ ID: "20260824120000-colors2",+ KeyValues: []*KeyValues{{Key: selectKey}},Views: []*View{{ID: "view",LayoutType: LayoutTypeTable,@@ -285,6 +327,10 @@ func TestGroupResolvedColorSurvivesPersistenceRoundTrip(t *testing.T) {}},}},}+ palette := []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),+ }+ withWorkspacePalette(t, &palette)attrView.ResolveDirectColors()if nil == attrView.Views[0].Groups[0].GroupVal.MSelect[0].ResolvedColor {t.Fatal("group value color was not initially resolved")@@ -310,3 +356,43 @@ func TestGroupResolvedColorSurvivesPersistenceRoundTrip(t *testing.T) {t.Fatalf("group value color was not resolved after persistence round trip: %+v", groupValue)}}++func TestNormalizeAttributeViewColorOrder(t *testing.T) {+ color := testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c")+ color.Hidden = true+ got := NormalizeAttributeViewColorOrder([]string{"15", "1", "15", "99", "14"}, []*AttributeViewCustomColor{color})+ if 15 != len(got) || "15" != got[0] || "1" != got[1] || "14" != got[2] || "2" != got[3] || "13" != got[len(got)-1] {+ t.Fatalf("unexpected mixed color order: %+v", got)+ }++ normalized, err := NormalizeAttributeViewCustomColors([]*AttributeViewCustomColor{color}, true)+ if nil != err {+ t.Fatalf("normalize hidden custom color failed: %s", err)+ }+ if 1 != len(normalized) || !normalized[0].Hidden {+ t.Fatalf("custom color hidden flag was not preserved: %+v", normalized)+ }++ defaults := DefaultAttributeViewColorOrder(normalized)+ if BuiltinColorCount+1 != len(defaults) || "1" != defaults[0] || "14" != defaults[BuiltinColorCount-1] ||+ "15" != defaults[len(defaults)-1] {+ t.Fatalf("unexpected default color order: %+v", defaults)+ }+}++func TestResolveColorUsesWorkspacePalette(t *testing.T) {+ old := LoadWorkspacePalette+ t.Cleanup(func() { LoadWorkspacePalette = old })+ LoadWorkspacePalette = func() ([]*AttributeViewCustomColor, []string) {+ return []*AttributeViewCustomColor{testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c")}, nil+ }++ attrView := &AttributeView{}+ if 16 != attrView.NextCustomColorIndex() {+ t.Fatalf("workspace palette was not considered: %d", attrView.NextCustomColorIndex())+ }+ resolved := attrView.ResolveColor("15")+ if nil == resolved || "#010203" != resolved.Light.Color {+ t.Fatalf("workspace palette was not resolved: %+v", resolved)+ }+}diff --git a/kernel/av/value.go b/kernel/av/value.goindex 41ec6db19e..9f1af0121c 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -1009,6 +1009,10 @@ func (r *ValueRollup) BuildContents(attrView *AttributeView, destKey *Key, relatif nil == attrView {return}+ var customColors []*AttributeViewCustomColor+ if KeyTypeSelect == destKey.Type || KeyTypeMSelect == destKey.Type {+ customColors, _ = attrView.customColorPalette()+ }for _, blockID := range relationVal.Relation.BlockIDs {if nil != context && nil != context.EligibleItemIDs && !context.EligibleItemIDs[blockID] {continue@@ -1049,7 +1053,7 @@ func (r *ValueRollup) BuildContents(attrView *AttributeView, destKey *Key, relatcloned := destVal.Clone()if KeyTypeSelect == destKey.Type || KeyTypeMSelect == destKey.Type {- resolveValueSelectColors(cloned, attrView)+ resolveValueSelectColors(cloned, customColors)}r.Contents = append(r.Contents, cloned)}diff --git a/kernel/av/value_test.go b/kernel/av/value_test.goindex 08fc85fa19..55faa480c1 100644--- a/kernel/av/value_test.go+++ b/kernel/av/value_test.go@@ -213,9 +213,6 @@ func TestValueRollupBuildContentsPreservesBlockRefSubtype(t *testing.T) {func TestValueRollupBuildContentsResolvesTargetCustomColor(t *testing.T) {destKey := &Key{ID: "select", Type: KeyTypeSelect}destView := &AttributeView{- CustomColors: []*AttributeViewCustomColor{- testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),- },KeyValues: []*KeyValues{{Key: destKey,Values: []*Value{{@@ -225,6 +222,15 @@ func TestValueRollupBuildContentsResolvesTargetCustomColor(t *testing.T) {}},}},}+ palette := []*AttributeViewCustomColor{+ testAttributeViewCustomColor(15, "#010203", "#040506", "#070809", "#0a0b0c"),+ }+ old := LoadWorkspacePalette+ t.Cleanup(func() { LoadWorkspacePalette = old })+ LoadWorkspacePalette = func() ([]*AttributeViewCustomColor, []string) {+ return palette, DefaultAttributeViewColorOrder(palette)+ }+relationValue := &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"item-a"}}}rollup := &ValueRollup{}diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex da0e27c0cd..915af3efc1 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -2551,7 +2551,7 @@ func GetAttributeViewRelationCandidates(srcAvID, relationKeyID, keyword string,}attributeViewName = getAttrViewName(attrView)databaseBlockIDs = treenode.GetMirrorAttrViewBlockIDs(attrView.ID)- customColors = attrView.CustomColors+ customColors = attrView.Palette()table := renderAttributeViewRelationCandidates(attrView)if nil == table {@@ -2817,7 +2817,7 @@ func NewAttributeViewData(attrView *av.AttributeView) (ret *AttributeViewData) {ret = &AttributeViewData{Spec: attrView.Spec, ID: attrView.ID, Name: attrView.Name, KeyValues: attrView.KeyValues, KeyIDs: attrView.KeyIDs,Views: attrView.Views, NewItemTemplates: attrView.NewItemTemplates, DefaultTemplateID: attrView.DefaultTemplateID,- CardCoverPositions: attrView.CardCoverPositions, CustomColors: attrView.CustomColors,+ CardCoverPositions: attrView.CardCoverPositions, CustomColors: attrView.Palette(),}if view, _ := attrView.GetFirstView(); nil != view {ret.ViewID = view.ID@@ -3616,7 +3616,7 @@ func GetAttributeViewItemKeys(avID, itemID, valueID string) (ret []*BlockAttriburet = append(ret, &BlockAttributeViewKeys{AvID: avID,AvName: getAttrViewName(attrView),- CustomColors: attrView.CustomColors,+ CustomColors: attrView.Palette(),BlockIDs: treenode.GetMirrorAttrViewBlockIDs(avID),KeyValues: keyValues,ItemPositions: getAttributeViewItemPositions(attrView, itemID),@@ -3728,7 +3728,7 @@ func GetBlockAttributeViewKeys(nodeID string) (ret []*BlockAttributeViewKeys) {ret = append(ret, &BlockAttributeViewKeys{AvID: avID,AvName: getAttrViewName(attrView),- CustomColors: attrView.CustomColors,+ CustomColors: attrView.Palette(),BlockIDs: blockIDs,KeyValues: keyValues,ItemPositions: getAttributeViewItemPositions(attrView, itemID),@@ -8440,21 +8440,38 @@ func (tx *Transaction) doSetAttrViewCustomColors(operation *Operation) (ret *TxEreturn}+func parseAttrViewCustomColorsData(data []byte) (colors []*av.AttributeViewCustomColor, order []string, err error) {+ trimmed := bytes.TrimSpace(data)+ if len(trimmed) > 0 && trimmed[0] == '{' {+ decoded := struct {+ Colors []*av.AttributeViewCustomColor `json:"colors"`+ Order []string `json:"order"`+ }{}+ if err = gulu.JSON.UnmarshalJSON(data, &decoded); nil != err {+ return+ }+ return decoded.Colors, decoded.Order, nil+ }+ colors = []*av.AttributeViewCustomColor{}+ err = gulu.JSON.UnmarshalJSON(data, &colors)+ return+}+func setAttrViewCustomColors(operation *Operation) (err error) {attrView, err := avParseView(operation.AvID, operation.BlockID)if nil != err {return}if nil == operation.Data {- return errors.New("attribute view custom colors must be an array")+ return errors.New("attribute view custom colors must not be empty")}data, err := gulu.JSON.MarshalJSON(operation.Data)if nil != err {return}- colors := []*av.AttributeViewCustomColor{}- if err = gulu.JSON.UnmarshalJSON(data, &colors); nil != err {+ colors, order, err := parseAttrViewCustomColorsData(data)+ if nil != err {return}colors, err = av.NormalizeAttributeViewCustomColors(colors, true)@@ -8462,6 +8479,16 @@ func setAttrViewCustomColors(operation *Operation) (err error) {return}+ oldColors := []*av.AttributeViewCustomColor{}+ oldOrder := []string{}+ if styles, stylesErr := GetInlineStyles(); nil == stylesErr && styles != nil && styles.AV != nil {+ oldColors = styles.AV.Colors+ oldOrder = styles.AV.Order+ }+ if nil == order {+ order = oldOrder+ }+retainedIndexes := map[int]struct{}{}for _, color := range colors {retainedIndexes[color.Index] = struct{}{}@@ -8470,7 +8497,7 @@ func setAttrViewCustomColors(operation *Operation) (err error) {for _, index := range attrView.UsedCustomColorIndexes() {usedIndexes[index] = struct{}{}}- for _, oldColor := range attrView.CustomColors {+ for _, oldColor := range oldColors {if nil == oldColor {continue}@@ -8481,8 +8508,7 @@ func setAttrViewCustomColors(operation *Operation) (err error) {}}- attrView.CustomColors = colors- if err = avSaveView(attrView, operation.BlockID); nil != err {+ if err = replaceWorkspaceAVPalette(colors, order); nil != err {return}ReloadAttrView(attrView.ID)diff --git a/kernel/model/attribute_view_custom_color_history_test.go b/kernel/model/attribute_view_custom_color_history_test.goindex 8a1070654a..5764ae7056 100644--- a/kernel/model/attribute_view_custom_color_history_test.go+++ b/kernel/model/attribute_view_custom_color_history_test.go@@ -34,7 +34,11 @@ func TestLoadHistoryAttributeViewCustomColors(t *testing.T) {if err := os.MkdirAll(filepath.Dir(path), 0755); nil != err {t.Fatal(err)}- data, err := json.Marshal(&av.AttributeView{+ data, err := json.Marshal(struct {+ Spec int `json:"spec"`+ ID string `json:"id"`+ CustomColors []*av.AttributeViewCustomColor `json:"customColors"`+ }{Spec: av.CurrentSpec,ID: avID,CustomColors: []*av.AttributeViewCustomColor{{@@ -52,22 +56,68 @@ func TestLoadHistoryAttributeViewCustomColors(t *testing.T) {t.Fatal(err)}- colors, found := loadHistoryAttributeViewCustomColors(historyDir, avID)+ colors, order, found := loadHistoryAttributeViewCustomColors(historyDir, avID)if !found || 1 != len(colors) || "#010203" != colors[0].Light.Color {t.Fatalf("unexpected historical palette: %+v, found %v", colors, found)}- if _, found = loadHistoryAttributeViewCustomColors(historyDir, "20260824000001-missing"); found {+ if len(order) != av.BuiltinColorCount+1 || order[len(order)-1] != "15" {+ t.Fatalf("unexpected historical palette order: %v", order)+ }+ if _, _, found = loadHistoryAttributeViewCustomColors(historyDir, "20260824000001-missing"); found {t.Fatal("missing historical palette was reported as found")}- if _, found = loadHistoryAttributeViewCustomColors(historyDir, "../target1"); found {+ if _, _, found = loadHistoryAttributeViewCustomColors(historyDir, "../target1"); found {t.Fatal("invalid related attribute view ID was accepted")}}+func TestLoadHistoryAttributeViewUsesWorkspacePaletteOrder(t *testing.T) {+ const avID = "20260824000002-target2"+ historyDir := t.TempDir()+ avPath := filepath.Join(historyDir, "storage", "av", avID+".json")+ if err := os.MkdirAll(filepath.Dir(avPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(avPath, []byte(`{"spec":13,"id":"20260824000002-target2"}`), 0644); err != nil {+ t.Fatal(err)+ }+ stylesPath := filepath.Join(historyDir, "storage", "inline-styles.json")+ styles := &InlineStyles{+ Version: InlineStylesVersion,+ AV: &InlineStyleAV{+ Colors: []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }},+ Order: []string{"15", "2", "1"},+ },+ }+ data, err := json.Marshal(styles)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(stylesPath, data, 0644); err != nil {+ t.Fatal(err)+ }++ colors, order, found := loadHistoryAttributeViewCustomColors(historyDir, avID)+ if !found || len(colors) != 1 || len(order) != av.BuiltinColorCount+1 ||+ order[0] != "15" || order[1] != "2" || order[2] != "1" {+ t.Fatalf("unexpected historical workspace palette: colors=%+v order=%v found=%v", colors, order, found)+ }+ attrView := &av.AttributeView{ID: avID, CustomColorRenderContext: newHistoryAttributeViewCustomColorRenderContext(historyDir)}+ if resolvedOrder := attrView.PaletteOrder(); len(resolvedOrder) == 0 || resolvedOrder[0] != "15" {+ t.Fatalf("historical render context lost palette order: %v", resolvedOrder)+ }+}+func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(t *testing.T) {var calls atomic.Int32resolver := newCachedAttributeViewCustomColorResolver(- func(string) ([]*av.AttributeViewCustomColor, bool) {+ func(string) ([]*av.AttributeViewCustomColor, []string, bool) {calls.Add(1)return []*av.AttributeViewCustomColor{{Index: 15,@@ -75,7 +125,7 @@ func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(tLight: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},},- }}, true+ }}, []string{"15", "1"}, true},)@@ -86,10 +136,13 @@ func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(twaitGroup.Add(1)go func() {defer waitGroup.Done()- colors, found := resolver("20260824000000-target1")+ colors, order, found := resolver("20260824000000-target1")if !found || 1 != len(colors) || "#0a0b0c" != colors[0].Dark.BackgroundColor {errs <- "resolver returned an invalid palette"}+ if len(order) == 0 || order[0] != "15" {+ errs <- "resolver returned an invalid palette order"+ }}()}waitGroup.Wait()@@ -103,12 +156,12 @@ func TestCachedAttributeViewCustomColorResolverIsRequestLocalAndConcurrentSafe(tsecondCalls := atomic.Int32{}secondResolver := newCachedAttributeViewCustomColorResolver(- func(string) ([]*av.AttributeViewCustomColor, bool) {+ func(string) ([]*av.AttributeViewCustomColor, []string, bool) {secondCalls.Add(1)- return nil, false+ return nil, nil, false},)- if _, found := secondResolver("20260824000000-target1"); found || 1 != secondCalls.Load() {+ if _, _, found := secondResolver("20260824000000-target1"); found || 1 != secondCalls.Load() {t.Fatal("separate request resolver reused another request cache")}}diff --git a/kernel/model/attribute_view_default_test.go b/kernel/model/attribute_view_default_test.goindex 8917cdb62d..a564eda9b1 100644--- a/kernel/model/attribute_view_default_test.go+++ b/kernel/model/attribute_view_default_test.go@@ -162,13 +162,18 @@ func TestAddingDefaultValueResolvesCustomSelectColor(t *testing.T) {selectKey.Options = []*av.SelectOption{{Name: "Custom", Color: "15",}}- attrView.CustomColors = []*av.AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: av.AttributeViewColor{- Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},- Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},- },- }}+ if _, _, err := SetInlineStylesData(&InlineStyles{+ Version: InlineStylesVersion,+ AV: &InlineStyleAV{Colors: []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }}},+ }); err != nil {+ t.Fatal(err)+ }view := attrView.Views[0]view.Filters = []*av.ViewFilter{{Column: selectKey.ID,diff --git a/kernel/model/attribute_view_options_test.go b/kernel/model/attribute_view_options_test.goindex b711fe8f3d..2f73ad2ed4 100644--- a/kernel/model/attribute_view_options_test.go+++ b/kernel/model/attribute_view_options_test.go@@ -17,7 +17,9 @@package modelimport (+ "os""reflect"+ "strings""testing""github.com/siyuan-note/siyuan/kernel/av"@@ -101,13 +103,7 @@ func TestUpdateAttributeViewColumnOptionsSynchronizesOptionColorReferences(t *tesetupAttributeViewValidationTest(t)attrView := av.NewAttributeView("20260824120000-options")- attrView.CustomColors = []*av.AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: av.AttributeViewColor{- Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},- Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},- },- }}+ saveTestWorkspacePalette(t, []*av.AttributeViewCustomColor{testAVCustomColor(15, false)}, nil)selectKey := attrView.KeyValues[1].KeyselectKey.Options = []*av.SelectOption{{Name: "Used", Color: "15"}}selectValue := func() *av.Value {@@ -153,13 +149,7 @@ func TestSetAttrViewCustomColorsRejectsDeletingUsedColor(t *testing.T) {setupAttributeViewValidationTest(t)attrView := av.NewAttributeView("20260824130000-colors1")- attrView.CustomColors = []*av.AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: av.AttributeViewColor{- Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},- Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},- },- }}+ saveTestWorkspacePalette(t, []*av.AttributeViewCustomColor{testAVCustomColor(15, false)}, nil)selectKey := attrView.KeyValues[1].KeyselectKey.Options = []*av.SelectOption{{Name: "Used", Color: "15"}}if err := av.SaveAttributeView(attrView); nil != err {@@ -190,22 +180,67 @@ func TestSetAttrViewCustomColorsRejectsDeletingUsedColor(t *testing.T) {if nil != err {t.Fatalf("parse attribute view failed: %s", err)}- if 1 != len(parsed.CustomColors) || "#111111" != parsed.CustomColors[0].Light.Color {- t.Fatalf("custom palette update was not saved: %+v", parsed.CustomColors)+ if 1 != len(parsed.Palette()) || "#111111" != parsed.Palette()[0].Light.Color {+ t.Fatalf("custom palette update was not saved: %+v", parsed.Palette())}+ assertWorkspaceAVPalette(t, parsed.Palette(), parsed.PaletteOrder())+ assertAttributeViewDiskOmitsPalette(t, attrView.ID)}-func TestGenerateAttributeViewGroupsPreservesResolvedCustomColor(t *testing.T) {+func TestSetAttrViewCustomColorsSavesOrder(t *testing.T) {setupAttributeViewValidationTest(t)- attrView := av.NewAttributeView("20260824140000-colors2")- attrView.CustomColors = []*av.AttributeViewCustomColor{{- Index: 15,+ attrView := av.NewAttributeView("20260827130000-corder1")+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatalf("save attribute view failed: %s", err)+ }++ color := &av.AttributeViewCustomColor{+ Index: 15,+ Hidden: true,AttributeViewColor: av.AttributeViewColor{Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},},- }}+ }+ if err := setAttrViewCustomColors(&Operation{AvID: attrView.ID, Data: map[string]any{+ "colors": []*av.AttributeViewCustomColor{color},+ "order": []string{"15", "1", "14"},+ }}); nil != err {+ t.Fatalf("save custom colors with order failed: %s", err)+ }++ parsed, err := av.ParseAttributeView(attrView.ID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ if 1 != len(parsed.Palette()) || !parsed.Palette()[0].Hidden {+ t.Fatalf("custom color hidden flag was not saved: %+v", parsed.Palette())+ }+ if 15 != len(parsed.PaletteOrder()) || "15" != parsed.PaletteOrder()[0] || "1" != parsed.PaletteOrder()[1] ||+ "14" != parsed.PaletteOrder()[2] {+ t.Fatalf("custom color order was not saved: %+v", parsed.PaletteOrder())+ }++ if err = setAttrViewCustomColors(&Operation{AvID: attrView.ID, Data: parsed.Palette()}); nil != err {+ t.Fatalf("array-only custom color update failed: %s", err)+ }+ parsed, err = av.ParseAttributeView(attrView.ID)+ if nil != err {+ t.Fatalf("parse attribute view failed: %s", err)+ }+ if "15" != parsed.PaletteOrder()[0] || "1" != parsed.PaletteOrder()[1] || "14" != parsed.PaletteOrder()[2] {+ t.Fatalf("array-only update reset color order: %+v", parsed.PaletteOrder())+ }+ assertWorkspaceAVPalette(t, parsed.Palette(), parsed.PaletteOrder())+ assertAttributeViewDiskOmitsPalette(t, attrView.ID)+}++func TestGenerateAttributeViewGroupsPreservesResolvedCustomColor(t *testing.T) {+ setupAttributeViewValidationTest(t)++ attrView := av.NewAttributeView("20260824140000-colors2")+ saveTestWorkspacePalette(t, []*av.AttributeViewCustomColor{testAVCustomColor(15, false)}, nil)selectKey := attrView.KeyValues[1].KeyselectKey.Options = []*av.SelectOption{{Name: "Custom", Color: "15"}}attrView.ResolveDirectColors()@@ -223,6 +258,27 @@ func TestGenerateAttributeViewGroupsPreservesResolvedCustomColor(t *testing.T) {}}+func testAVCustomColor(index int, hidden bool) *av.AttributeViewCustomColor {+ return &av.AttributeViewCustomColor{+ Index: index,+ Hidden: hidden,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }+}++func saveTestWorkspacePalette(t *testing.T, colors []*av.AttributeViewCustomColor, order []string) {+ t.Helper()+ if _, _, err := SetInlineStylesData(&InlineStyles{+ Version: InlineStylesVersion,+ AV: &InlineStyleAV{Colors: colors, Order: order},+ }); err != nil {+ t.Fatalf("save workspace palette failed: %s", err)+ }+}+func assertSelectOptionNames(t *testing.T, options []*av.SelectOption, expected []string) {t.Helper()@@ -234,3 +290,29 @@ func assertSelectOptionNames(t *testing.T, options []*av.SelectOption, expectedt.Fatalf("expected option names %v, got %v", expected, actual)}}++func assertWorkspaceAVPalette(t *testing.T, colors []*av.AttributeViewCustomColor, order []string) {+ t.Helper()+ styles, err := GetInlineStyles()+ if err != nil {+ t.Fatalf("get inline styles failed: %s", err)+ }+ if !reflect.DeepEqual(styles.AV.Colors, colors) || !reflect.DeepEqual(styles.AV.Order, order) {+ t.Fatalf("workspace palette mismatch: %#v vs colors=%+v order=%+v", styles.AV, colors, order)+ }+}++func assertAttributeViewDiskOmitsPalette(t *testing.T, avID string) {+ t.Helper()+ path, _ := av.FindAttributeViewPath(avID)+ if path == "" {+ path = av.GetAttributeViewDataPath(avID)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read attribute view failed: %s", err)+ }+ if strings.Contains(string(data), "\"customColors\"") || strings.Contains(string(data), "\"colorOrder\"") {+ t.Fatalf("attribute view file persisted workspace palette: %s", data)+ }+}diff --git a/kernel/model/attribute_view_output.go b/kernel/model/attribute_view_output.goindex 3ebd0c175b..28e6295a41 100644--- a/kernel/model/attribute_view_output.go+++ b/kernel/model/attribute_view_output.go@@ -36,7 +36,7 @@ func NewAttributeViewMetadata(attrView *av.AttributeView) (ret *AttributeViewMetret = &AttributeViewMetadata{ID: attrView.ID,Name: attrView.Name,- CustomColors: attrView.CustomColors,+ CustomColors: attrView.Palette(),Keys: []*av.Key{},Views: []*av.ViewData{},}@@ -101,7 +101,7 @@ func NewAttributeViewRenderData(attrView *av.AttributeView, view av.Viewable, quret = &AttributeViewRenderData{ID: attrView.ID,Name: attrView.Name,- CustomColors: attrView.CustomColors,+ CustomColors: attrView.Palette(),ViewID: view.GetID(),ViewType: view.GetType(),Query: query,diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.goindex b021b2b74e..031b09e32a 100644--- a/kernel/model/attribute_view_render.go+++ b/kernel/model/attribute_view_render.go@@ -1204,27 +1204,31 @@ func ResolveHistoryAttributeViewBoxID(avID, created string) (string, error) {type attributeViewCustomColorPaletteCacheEntry struct {colors []*av.AttributeViewCustomColor+ order []stringfound bool}// newCachedAttributeViewCustomColorResolver 将历史调色板解析限制在单次渲染请求内,并避免并发重复读取。func newCachedAttributeViewCustomColorResolver(- loader func(avID string) (colors []*av.AttributeViewCustomColor, found bool),-) func(avID string) (colors []*av.AttributeViewCustomColor, found bool) {+ loader func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool),+) func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {cache := map[string]attributeViewCustomColorPaletteCacheEntry{}var lock sync.Mutex- return func(avID string) (colors []*av.AttributeViewCustomColor, found bool) {+ return func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {lock.Lock()defer lock.Unlock()if entry, ok := cache[avID]; ok {colors, _ = av.NormalizeAttributeViewCustomColors(entry.colors, false)- return colors, entry.found+ order = av.NormalizeAttributeViewColorOrder(entry.order, colors)+ return colors, order, entry.found}- colors, found = loader(avID)+ colors, order, found = loader(avID)colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)- cache[avID] = attributeViewCustomColorPaletteCacheEntry{colors: colors, found: found}+ order = av.NormalizeAttributeViewColorOrder(order, colors)+ cache[avID] = attributeViewCustomColorPaletteCacheEntry{colors: colors, order: order, found: found}colors, _ = av.NormalizeAttributeViewCustomColors(colors, false)+ order = av.NormalizeAttributeViewColorOrder(order, colors)return}}@@ -1234,23 +1238,14 @@ func decodeHistoricalAttributeViewCustomColors(boxID, avID string, data []byte)if nil != err {return}- attrView := &av.AttributeView{}- if err = gulu.JSON.UnmarshalJSON(data, attrView); nil != err {- return- }- if err = av.CheckSpec(attrView); nil != err {- return- }- if err = attrView.NormalizeCustomColors(false); nil != err {- return- }- ret = attrView.CustomColors- return+ return av.DecodePersistedPalette(data)}-func loadHistoryAttributeViewCustomColors(historyDir, avID string) (ret []*av.AttributeViewCustomColor, found bool) {+func loadHistoryAttributeViewCustomColors(historyDir, avID string) (+ ret []*av.AttributeViewCustomColor, order []string, found bool,+) {if !ast.IsNodeIDPattern(avID) {- return nil, false+ return nil, nil, false}type source struct {path string@@ -1272,25 +1267,62 @@ func loadHistoryAttributeViewCustomColors(historyDir, avID string) (ret []*av.At}}if 1 != len(sources) {- return nil, false+ return nil, nil, false}data, err := os.ReadFile(sources[0].path)if nil != err {logging.LogWarnf("read related history attribute view [%s] failed: %s", avID, err)- return nil, false+ return nil, nil, false}ret, err = decodeHistoricalAttributeViewCustomColors(sources[0].boxID, avID, data)if nil != err {logging.LogWarnf("parse related history attribute view [%s] failed: %s", avID, err)- return nil, false+ return nil, nil, false}- return ret, true+ if 0 < len(ret) {+ return ret, av.DefaultAttributeViewColorOrder(ret), true+ }+ return loadHistoryWorkspacePalette(historyDir)+}++func loadHistoryWorkspacePalette(historyDir string) (+ ret []*av.AttributeViewCustomColor, order []string, found bool,+) {+ path := filepath.Join(historyDir, "storage", "inline-styles.json")+ if !gulu.File.IsExist(path) {+ return nil, nil, false+ }+ data, err := os.ReadFile(path)+ if nil != err {+ logging.LogWarnf("read historical inline styles failed: %s", err)+ return nil, nil, false+ }+ return decodeHistoricalWorkspacePalette(data)+}++func decodeHistoricalWorkspacePalette(data []byte) (+ ret []*av.AttributeViewCustomColor, order []string, found bool,+) {+ var styles struct {+ AV *struct {+ Colors []*av.AttributeViewCustomColor `json:"colors"`+ Order []string `json:"order"`+ } `json:"av"`+ }+ if err := gulu.JSON.UnmarshalJSON(data, &styles); nil != err || nil == styles.AV {+ return nil, nil, false+ }+ colors, err := av.NormalizeAttributeViewCustomColors(styles.AV.Colors, false)+ if nil != err {+ return nil, nil, false+ }+ return colors, av.NormalizeAttributeViewColorOrder(styles.AV.Order, colors), true}func newHistoryAttributeViewCustomColorRenderContext(historyDir string) *av.CustomColorRenderContext {return &av.CustomColorRenderContext{ResolveRelatedCustomColors: newCachedAttributeViewCustomColorResolver(- func(avID string) (colors []*av.AttributeViewCustomColor, found bool) {+ func(avID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {return loadHistoryAttributeViewCustomColors(historyDir, avID)},)}@@ -1356,13 +1388,26 @@ func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID stringif err = av.CheckSpec(attrView); nil != err {return}- _ = attrView.NormalizeCustomColors(false)- attrView.ResolveDirectColors()+ var snapshotColors []*av.AttributeViewCustomColor+ var snapshotOrder []string+ var snapshotPaletteFound bool+ for _, file := range files {+ if !isInlineStylesRepoPath(file.Path) {+ continue+ }+ inlineStylesData, openErr := repo.OpenFile(file)+ if openErr != nil {+ logging.LogWarnf("read snapshot inline styles failed: %s", openErr)+ break+ }+ snapshotColors, snapshotOrder, snapshotPaletteFound = decodeHistoricalWorkspacePalette(inlineStylesData)+ break+ }attrView.CustomColorRenderContext = &av.CustomColorRenderContext{ResolveRelatedCustomColors: newCachedAttributeViewCustomColorResolver(- func(targetAvID string) (colors []*av.AttributeViewCustomColor, found bool) {+ func(targetAvID string) (colors []*av.AttributeViewCustomColor, order []string, found bool) {if !ast.IsNodeIDPattern(targetAvID) {- return nil, false+ return nil, nil, false}var matches []*entity.Filefor _, file := range files {@@ -1371,23 +1416,30 @@ func RenderRepoSnapshotAttributeView(indexID, avID, viewID, carrierViewID string}}if 1 != len(matches) {- return nil, false+ return nil, nil, false}data, readErr := repo.OpenFile(matches[0])if nil != readErr {logging.LogWarnf("read related snapshot attribute view [%s] failed: %s", targetAvID, readErr)- return nil, false+ return nil, nil, false}colors, parseErr := decodeHistoricalAttributeViewCustomColors(avBoxIDFromRepoPath(matches[0].Path), targetAvID, data)if nil != parseErr {logging.LogWarnf("parse related snapshot attribute view [%s] failed: %s", targetAvID, parseErr)- return nil, false+ return nil, nil, false+ }+ if 0 < len(colors) {+ return colors, av.DefaultAttributeViewColorOrder(colors), true}- return colors, true+ if snapshotPaletteFound {+ return snapshotColors, snapshotOrder, true+ }+ return []*av.AttributeViewCustomColor{}, av.DefaultAttributeViewColorOrder(nil), true},),}+ attrView.ResolveDirectColors()viewable, err = renderAttributeView(attrView, "", viewID, carrierViewID, "", 1, -1, nil, false, false, nil, "")return@@ -1473,9 +1525,8 @@ func RenderHistoryAttributeView(avID, viewID, carrierViewID, query string, page,if err = av.CheckSpec(attrView); nil != err {return}- _ = attrView.NormalizeCustomColors(false)- attrView.ResolveDirectColors()attrView.CustomColorRenderContext = newHistoryAttributeViewCustomColorRenderContext(source.historyDir)+ attrView.ResolveDirectColors()viewable, err = renderAttributeView(attrView, "", viewID, carrierViewID, query, page, pageSize, groupPaging, false, false, nil, "")returndiff --git a/kernel/model/inline_style.go b/kernel/model/inline_style.goindex 99c8d73bcd..5fcb0c216a 100644--- a/kernel/model/inline_style.go+++ b/kernel/model/inline_style.go@@ -24,6 +24,7 @@ import ("path/filepath""regexp""sort"+ "strconv""strings""sync""unicode/utf8"@@ -31,6 +32,8 @@ import ("github.com/88250/gulu""github.com/88250/lute/ast""github.com/siyuan-note/filelock"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/util")@@ -46,9 +49,11 @@ const ()var (- inlineStylesLock sync.Mutex- inlineStyleColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)- builtinStyleOrder = map[string]int{+ inlineStylesLock sync.Mutex+ workspaceAVPaletteCache *InlineStyleAV+ workspaceAVPaletteCachePath string+ inlineStyleColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)+ builtinStyleOrder = map[string]int{"error": 0,"warning": 1,"info": 2,@@ -62,10 +67,11 @@ type InlineStyleTheme struct {}type InlineStyle struct {- ID string `json:"id"`- Name string `json:"name"`- Light *InlineStyleTheme `json:"light"`- Dark *InlineStyleTheme `json:"dark"`+ ID string `json:"id"`+ Name string `json:"name"`+ Hidden bool `json:"hidden,omitempty"`+ Light *InlineStyleTheme `json:"light"`+ Dark *InlineStyleTheme `json:"dark"`}type InlineStyleBuiltinColor struct {@@ -93,17 +99,48 @@ type InlineStyleBuiltin struct {Hidden *InlineStyleBuiltinHidden `json:"hidden"`}+type InlineStyleOrder struct {+ Color []string `json:"color"`+ BackgroundColor []string `json:"backgroundColor"`+ Style1 []string `json:"style1"`+}++type InlineStyleAV struct {+ Colors []*av.AttributeViewCustomColor `json:"colors"`+ Order []string `json:"order"`+}++type WorkspaceAVBuiltinColorUpdate struct {+ Index int `json:"index"`+ Customized bool `json:"customized"`+ Light *InlineStyleTheme `json:"light"`+ Dark *InlineStyleTheme `json:"dark"`+ Hidden bool `json:"hidden"`+}++type WorkspaceAVPaletteUpdate struct {+ Colors []*av.AttributeViewCustomColor `json:"colors"`+ Order []string `json:"order"`+ BuiltinColors []*WorkspaceAVBuiltinColorUpdate `json:"builtinColors"`+}+type InlineStyles struct {Version int `json:"version"`Styles []*InlineStyle `json:"styles"`Builtin *InlineStyleBuiltin `json:"builtin"`+ Order *InlineStyleOrder `json:"order"`+ AV *InlineStyleAV `json:"av"`}func GetInlineStyles() (ret *InlineStyles, err error) {waitForSyncingStorages()inlineStylesLock.Lock()defer inlineStylesLock.Unlock()- return loadInlineStyles()+ ret, err = loadInlineStyles()+ if err == nil {+ cacheWorkspaceAVPalette(ret.AV)+ }+ return}func SetInlineStyles(styles []*InlineStyle) (ret *InlineStyles, changed bool, err error) {@@ -115,8 +152,9 @@ func SetInlineStyles(styles []*InlineStyle) (ret *InlineStyles, changed bool, erif err != nil {return nil, false, err}+ currentAV := current.AVcurrent.Styles = styles- return setInlineStylesData(current)+ return setInlineStylesData(current, currentAV)}// SetInlineStylesData 全量保存行级样式和内置颜色配置。@@ -125,19 +163,79 @@ func SetInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool,inlineStylesLock.Lock()defer inlineStylesLock.Unlock()- if _, err = loadInlineStyles(); err != nil {+ current, err := loadInlineStyles()+ if err != nil {+ return nil, false, err+ }+ return setInlineStylesData(styles, current.AV)+}++// SetWorkspaceAVPalette 只更新数据库颜色配置,保留其他窗口可能同时修改的行级样式设置。+func SetWorkspaceAVPalette(update *WorkspaceAVPaletteUpdate) (ret *InlineStyles, changed bool, err error) {+ waitForSyncingStorages()+ inlineStylesLock.Lock()+ defer inlineStylesLock.Unlock()++ if update == nil {+ return nil, false, errors.New("workspace attribute view palette update must not be null")+ }+ current, err := loadInlineStyles()+ if err != nil {return nil, false, err}- return setInlineStylesData(styles)+ currentAV := current.AV+ current.AV = &InlineStyleAV{Colors: update.Colors, Order: update.Order}+ updatedIndexes := map[int]struct{}{}+ for _, patch := range update.BuiltinColors {+ if patch == nil {+ return nil, false, errors.New("workspace attribute view builtin color update must not be null")+ }+ if patch.Index < minBuiltinColorIndex || neutralAVColorIndex < patch.Index {+ return nil, false, fmt.Errorf("builtin color index [%d] must be between %d and %d", patch.Index,+ minBuiltinColorIndex, neutralAVColorIndex)+ }+ if _, duplicated := updatedIndexes[patch.Index]; duplicated {+ return nil, false, fmt.Errorf("duplicate workspace attribute view builtin color update [%d]", patch.Index)+ }+ updatedIndexes[patch.Index] = struct{}{}+ filtered := current.Builtin.Colors[:0]+ for _, color := range current.Builtin.Colors {+ if color.Index != patch.Index {+ filtered = append(filtered, color)+ }+ }+ current.Builtin.Colors = filtered+ if patch.Customized {+ current.Builtin.Colors = append(current.Builtin.Colors, &InlineStyleBuiltinColor{+ Index: patch.Index,+ Light: patch.Light,+ Dark: patch.Dark,+ })+ }+ filteredHidden := current.Builtin.Hidden.AV[:0]+ for _, index := range current.Builtin.Hidden.AV {+ if index != patch.Index {+ filteredHidden = append(filteredHidden, index)+ }+ }+ current.Builtin.Hidden.AV = filteredHidden+ if patch.Hidden {+ current.Builtin.Hidden.AV = append(current.Builtin.Hidden.AV, patch.Index)+ }+ }+ return setInlineStylesData(current, currentAV)}-func setInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool, err error) {+func setInlineStylesData(styles *InlineStyles, currentAV *InlineStyleAV) (ret *InlineStyles, changed bool, err error) {if styles == nil {return nil, false, errors.New("inline styles must not be null")}if styles.Version != InlineStylesVersion {return nil, false, fmt.Errorf("unsupported inline styles version [%d]", styles.Version)}+ if currentAV == nil {+ currentAV = newEmptyInlineStyleAV()+ }normalizedStyles, err := normalizeInlineStyles(styles.Styles, true)if err != nil {@@ -147,7 +245,35 @@ func setInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool,if err != nil {return nil, false, err}- ret = &InlineStyles{Version: InlineStylesVersion, Styles: normalizedStyles, Builtin: normalizedBuiltin}+ normalizedAV, err := normalizeInlineStyleAV(styles.AV, true)+ if err != nil {+ return nil, false, err+ }+ ret = &InlineStyles{+ Version: InlineStylesVersion,+ Styles: normalizedStyles,+ Builtin: normalizedBuiltin,+ Order: normalizeInlineStyleOrder(styles.Order, normalizedStyles),+ AV: normalizedAV,+ }+ changedCustomColorIndexes := changedAttributeViewCustomColorIndexes(currentAV.Colors, ret.AV.Colors)+ var customColorUsage map[string]map[int]struct{}+ if 0 < len(changedCustomColorIndexes) {+ removedIndexes := removedAttributeViewCustomColorIndexes(currentAV.Colors, ret.AV.Colors)+ customColorUsage, err = workspaceAttributeViewCustomColorUsage(0 < len(removedIndexes))+ if err != nil {+ return nil, false, err+ }+ for _, avID := range sortedAttributeViewUsageIDs(customColorUsage) {+ indexes := customColorUsage[avID]+ for index := range removedIndexes {+ if _, used := indexes[index]; used {+ return nil, false, fmt.Errorf("attribute view custom color [%d] is still in use by attribute view [%s]",+ index, avID)+ }+ }+ }+ }data, err := gulu.JSON.MarshalIndentJSON(ret, "", " ")if err != nil {return nil, false, fmt.Errorf("marshal inline styles failed: %w", err)@@ -162,6 +288,7 @@ func setInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool,return nil, false, fmt.Errorf("read inline styles failed: %w", readErr)}if bytes.Equal(oldData, data) {+ cacheWorkspaceAVPalette(ret.AV)return ret, false, nil}@@ -171,7 +298,14 @@ func setInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool,if err = filelock.WriteFile(dataPath, data); err != nil {return nil, false, fmt.Errorf("write inline styles failed: %w", err)}+ cacheWorkspaceAVPalette(ret.AV)IncSync()+ for _, avID := range sortedAttributeViewUsageIDs(customColorUsage) {+ indexes := customColorUsage[avID]+ if intersectsCustomColorIndexes(indexes, changedCustomColorIndexes) {+ pushReloadAttrView(avID)+ }+ }return ret, true, nil}@@ -179,6 +313,144 @@ func inlineStylesPath() string {return filepath.Join(util.DataDir, "storage", "inline-styles.json")}+func cacheWorkspaceAVPalette(palette *InlineStyleAV) {+ workspaceAVPaletteCache, _ = normalizeInlineStyleAV(palette, false)+ workspaceAVPaletteCachePath = inlineStylesPath()+}++func invalidateWorkspaceAVPaletteCache() {+ inlineStylesLock.Lock()+ defer inlineStylesLock.Unlock()+ workspaceAVPaletteCache = nil+ workspaceAVPaletteCachePath = ""+}++func changedAttributeViewCustomColorIndexes(oldColors, newColors []*av.AttributeViewCustomColor) map[int]struct{} {+ oldByIndex := attributeViewCustomColorsByIndex(oldColors)+ newByIndex := attributeViewCustomColorsByIndex(newColors)+ ret := map[int]struct{}{}+ for index, oldColor := range oldByIndex {+ newColor := newByIndex[index]+ if newColor == nil || oldColor.Light != newColor.Light || oldColor.Dark != newColor.Dark {+ ret[index] = struct{}{}+ }+ }+ for index := range newByIndex {+ if oldByIndex[index] == nil {+ ret[index] = struct{}{}+ }+ }+ return ret+}++func removedAttributeViewCustomColorIndexes(oldColors, newColors []*av.AttributeViewCustomColor) map[int]struct{} {+ newByIndex := attributeViewCustomColorsByIndex(newColors)+ ret := map[int]struct{}{}+ for index := range attributeViewCustomColorsByIndex(oldColors) {+ if newByIndex[index] == nil {+ ret[index] = struct{}{}+ }+ }+ return ret+}++func attributeViewCustomColorsByIndex(colors []*av.AttributeViewCustomColor) map[int]*av.AttributeViewCustomColor {+ ret := make(map[int]*av.AttributeViewCustomColor, len(colors))+ for _, color := range colors {+ if color != nil {+ ret[color.Index] = color+ }+ }+ return ret+}++func intersectsCustomColorIndexes(indexes, changed map[int]struct{}) bool {+ for index := range changed {+ if _, ok := indexes[index]; ok {+ return true+ }+ }+ return false+}++func sortedAttributeViewUsageIDs(usage map[string]map[int]struct{}) []string {+ ret := make([]string, 0, len(usage))+ for avID := range usage {+ ret = append(ret, avID)+ }+ sort.Strings(ret)+ return ret+}++func workspaceAttributeViewCustomColorUsage(strict bool) (ret map[string]map[int]struct{}, err error) {+ ret = map[string]map[int]struct{}{}+ var paths []string+ appendPaths := func(dir string) error {+ entries, readErr := os.ReadDir(dir)+ if os.IsNotExist(readErr) {+ return nil+ }+ if readErr != nil {+ return readErr+ }+ for _, entry := range entries {+ if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {+ continue+ }+ avID := strings.TrimSuffix(entry.Name(), filepath.Ext(entry.Name()))+ if ast.IsNodeIDPattern(avID) {+ paths = append(paths, filepath.Join(dir, entry.Name()))+ }+ }+ return nil+ }+ if err = appendPaths(filepath.Join(util.DataDir, "storage", "av")); err != nil {+ if strict {+ return nil, fmt.Errorf("list attribute views failed: %w", err)+ }+ logging.LogWarnf("list attribute views for custom color refresh failed: %s", err)+ }+ entries, readErr := os.ReadDir(util.DataDir)+ if readErr != nil && !os.IsNotExist(readErr) {+ if strict {+ return nil, fmt.Errorf("list workspace data directory failed: %w", readErr)+ }+ logging.LogWarnf("list workspace data directory for custom color refresh failed: %s", readErr)+ }+ for _, entry := range entries {+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {+ continue+ }+ if err = appendPaths(filepath.Join(util.DataDir, entry.Name(), "storage", "av")); err != nil {+ if strict {+ return nil, fmt.Errorf("list notebook attribute views [%s] failed: %w", entry.Name(), err)+ }+ logging.LogWarnf("list notebook attribute views [%s] for custom color refresh failed: %s",+ entry.Name(), err)+ }+ }+ sort.Strings(paths)+ for _, path := range paths {+ avID, indexes, readErr := av.ReadAttributeViewCustomColorUsageByPath(path)+ if readErr != nil {+ if strict {+ return nil, fmt.Errorf("read attribute view custom color usage [%s] failed: %w", avID, readErr)+ }+ logging.LogWarnf("read attribute view custom color usage [%s] for refresh failed: %s", avID, readErr)+ continue+ }+ used := ret[avID]+ if used == nil {+ used = map[int]struct{}{}+ ret[avID] = used+ }+ for _, index := range indexes {+ used[index] = struct{}{}+ }+ }+ return ret, nil+}+func isInlineStylesRepoPath(filePath string) bool {return filePath == inlineStylesRepoPath}@@ -209,6 +481,11 @@ func loadInlineStyles() (ret *InlineStyles, err error) {if err != nil {return nil, fmt.Errorf("invalid inline styles data: %w", err)}+ ret.Order = normalizeInlineStyleOrder(ret.Order, ret.Styles)+ ret.AV, err = normalizeInlineStyleAV(ret.AV, false)+ if err != nil {+ return nil, fmt.Errorf("invalid inline styles data: %w", err)+ }ret.Version = InlineStylesVersionreturn ret, nil}@@ -218,6 +495,15 @@ func newEmptyInlineStyles() *InlineStyles {Version: InlineStylesVersion,Styles: []*InlineStyle{},Builtin: newEmptyInlineStyleBuiltin(),+ Order: defaultInlineStyleOrder(),+ AV: newEmptyInlineStyleAV(),+ }+}++func newEmptyInlineStyleAV() *InlineStyleAV {+ return &InlineStyleAV{+ Colors: []*av.AttributeViewCustomColor{},+ Order: av.DefaultAttributeViewColorOrder(nil),}}@@ -234,6 +520,105 @@ func newEmptyInlineStyleBuiltin() *InlineStyleBuiltin {}}+func defaultBuiltinColorOrderKeys() []string {+ keys := make([]string, 0, maxBuiltinColorIndex)+ for index := minBuiltinColorIndex; index <= maxBuiltinColorIndex; index++ {+ keys = append(keys, strconv.Itoa(index))+ }+ return keys+}++func defaultInlineStyleOrder() *InlineStyleOrder {+ colorKeys := defaultBuiltinColorOrderKeys()+ return &InlineStyleOrder{+ Color: append([]string{}, colorKeys...),+ BackgroundColor: append([]string{}, colorKeys...),+ Style1: []string{"error", "warning", "info", "success"},+ }+}++func getInlineStyleKind(style *InlineStyle) string {+ if style == nil || style.Light == nil {+ return ""+ }+ hasColor := style.Light.Color != ""+ hasBackground := style.Light.BackgroundColor != ""+ if hasColor && hasBackground {+ return "style1"+ }+ if hasColor {+ return "color"+ }+ if hasBackground {+ return "backgroundColor"+ }+ return ""+}++func builtinOrderKeys(styleType string) []string {+ if styleType == "style1" {+ return []string{"error", "warning", "info", "success"}+ }+ return defaultBuiltinColorOrderKeys()+}++func customOrderKeys(styleType string, styles []*InlineStyle) []string {+ keys := make([]string, 0)+ for _, style := range styles {+ if getInlineStyleKind(style) == styleType {+ keys = append(keys, style.ID)+ }+ }+ return keys+}++func normalizeOrderKeys(saved []string, styleType string, styles []*InlineStyle) []string {+ builtinKeys := builtinOrderKeys(styleType)+ customKeys := customOrderKeys(styleType, styles)+ allowed := make(map[string]struct{}, len(builtinKeys)+len(customKeys))+ for _, key := range builtinKeys {+ allowed[key] = struct{}{}+ }+ for _, key := range customKeys {+ allowed[key] = struct{}{}+ }+ seen := make(map[string]struct{}, len(allowed))+ ret := make([]string, 0, len(allowed))+ for _, key := range saved {+ if _, ok := allowed[key]; !ok {+ continue+ }+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ ret = append(ret, key)+ }+ for _, key := range append(append([]string{}, builtinKeys...), customKeys...) {+ if _, ok := seen[key]; ok {+ continue+ }+ seen[key] = struct{}{}+ ret = append(ret, key)+ }+ return ret+}++// normalizeInlineStyleOrder 保留已保存的混排顺序,并补上新增的内置色或自定义色。+func normalizeInlineStyleOrder(order *InlineStyleOrder, styles []*InlineStyle) *InlineStyleOrder {+ var color, backgroundColor, style1 []string+ if order != nil {+ color = order.Color+ backgroundColor = order.BackgroundColor+ style1 = order.Style1+ }+ return &InlineStyleOrder{+ Color: normalizeOrderKeys(color, "color", styles),+ BackgroundColor: normalizeOrderKeys(backgroundColor, "backgroundColor", styles),+ Style1: normalizeOrderKeys(style1, "style1", styles),+ }+}+func getVisibleAVBuiltinColorIndexes() []int {styles, err := GetInlineStyles()if err != nil {@@ -243,13 +628,16 @@ func getVisibleAVBuiltinColorIndexes() []int {for _, index := range styles.Builtin.Hidden.AV {hidden[index] = struct{}{}}- ret := make([]int, 0, maxBuiltinColorIndex+1)- for index := minBuiltinColorIndex; index <= maxBuiltinColorIndex; index++ {+ ret := make([]int, 0, neutralAVColorIndex)+ for index := minBuiltinColorIndex; index <= neutralAVColorIndex; index++ {if _, ok := hidden[index]; !ok {ret = append(ret, index)}}- return append(ret, neutralAVColorIndex)+ if len(ret) == 0 {+ return []int{neutralAVColorIndex}+ }+ return ret}func normalizeInlineStyles(styles []*InlineStyle, generateIDs bool) (ret []*InlineStyle, err error) {@@ -308,7 +696,7 @@ func normalizeInlineStyles(styles []*InlineStyle, generateIDs bool) (ret []*Inlireturn nil, fmt.Errorf("inline style [%s] must use the same fields in light and dark themes", id)}- ret = append(ret, &InlineStyle{ID: id, Name: name, Light: light, Dark: dark})+ ret = append(ret, &InlineStyle{ID: id, Name: name, Hidden: style.Hidden, Light: light, Dark: dark})}return ret, nil}@@ -324,9 +712,9 @@ func normalizeInlineStyleBuiltin(builtin *InlineStyleBuiltin) (ret *InlineStyleBif color == nil {return nil, errors.New("builtin color must not be null")}- if color.Index < minBuiltinColorIndex || maxBuiltinColorIndex < color.Index {+ if color.Index < minBuiltinColorIndex || neutralAVColorIndex < color.Index {return nil, fmt.Errorf("builtin color index [%d] must be between %d and %d", color.Index,- minBuiltinColorIndex, maxBuiltinColorIndex)+ minBuiltinColorIndex, neutralAVColorIndex)}if _, exists := colorIndexes[color.Index]; exists {return nil, fmt.Errorf("duplicate builtin color index [%d]", color.Index)@@ -385,6 +773,20 @@ func normalizeInlineStyleBuiltin(builtin *InlineStyleBuiltin) (ret *InlineStyleBreturn ret, nil}+func normalizeInlineStyleAV(palette *InlineStyleAV, strict bool) (ret *InlineStyleAV, err error) {+ ret = newEmptyInlineStyleAV()+ if palette == nil {+ return ret, nil+ }+ colors, err := av.NormalizeAttributeViewCustomColors(palette.Colors, strict)+ if err != nil {+ return nil, err+ }+ ret.Colors = colors+ ret.Order = av.NormalizeAttributeViewColorOrder(palette.Order, colors)+ return ret, nil+}+func normalizeInlineStyleThemePair(light, dark *InlineStyleTheme, description string) (normalizedLight,normalizedDark *InlineStyleTheme, err error) {if light == nil || dark == nil {@@ -410,10 +812,14 @@ func normalizeInlineStyleThemePair(light, dark *InlineStyleTheme, description stfunc normalizeHiddenBuiltinColorIndexes(indexes []int, field string) (ret []int, err error) {ret = make([]int, 0, len(indexes))seen := make(map[int]struct{}, len(indexes))+ maxIndex := maxBuiltinColorIndex+ if field == "av" {+ maxIndex = neutralAVColorIndex+ }for _, index := range indexes {- if index < minBuiltinColorIndex || maxBuiltinColorIndex < index {+ if index < minBuiltinColorIndex || maxIndex < index {return nil, fmt.Errorf("hidden builtin %s index [%d] must be between %d and %d", field, index,- minBuiltinColorIndex, maxBuiltinColorIndex)+ minBuiltinColorIndex, maxIndex)}if _, exists := seen[index]; exists {continue@@ -465,3 +871,42 @@ func normalizeInlineStyleColor(color string) (ret string, err error) {}return ret, nil}++func init() {+ av.LoadWorkspacePalette = loadWorkspaceAVPalette+}++func loadWorkspaceAVPalette() (colors []*av.AttributeViewCustomColor, order []string) {+ waitForSyncingStorages()+ inlineStylesLock.Lock()+ defer inlineStylesLock.Unlock()+ if workspaceAVPaletteCache == nil || workspaceAVPaletteCachePath != inlineStylesPath() {+ styles, err := loadInlineStyles()+ if err != nil {+ return nil, nil+ }+ cacheWorkspaceAVPalette(styles.AV)+ }+ palette, err := normalizeInlineStyleAV(workspaceAVPaletteCache, false)+ if err != nil {+ return+ }+ return palette.Colors, palette.Order+}++func replaceWorkspaceAVPalette(colors []*av.AttributeViewCustomColor, order []string) error {+ waitForSyncingStorages()+ inlineStylesLock.Lock()+ defer inlineStylesLock.Unlock()+ styles, err := loadInlineStyles()+ if err != nil {+ return err+ }+ currentAV := styles.AV+ styles.AV = &InlineStyleAV{+ Colors: colors,+ Order: av.NormalizeAttributeViewColorOrder(order, colors),+ }+ _, _, err = setInlineStylesData(styles, currentAV)+ return err+}diff --git a/kernel/model/inline_style_test.go b/kernel/model/inline_style_test.goindex f86aee72e8..aa7e43c3a5 100644--- a/kernel/model/inline_style_test.go+++ b/kernel/model/inline_style_test.go@@ -27,6 +27,7 @@ import ("github.com/88250/lute/ast"ignore "github.com/sabhiram/go-gitignore"+ "github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util")@@ -42,7 +43,9 @@ func TestInlineStylesCRUD(t *testing.T) {styles.Builtin == nil || styles.Builtin.Colors == nil || styles.Builtin.Styles == nil ||styles.Builtin.Hidden == nil || styles.Builtin.Hidden.Color == nil ||styles.Builtin.Hidden.BackgroundColor == nil || styles.Builtin.Hidden.Style1 == nil ||- styles.Builtin.Hidden.AV == nil {+ styles.Builtin.Hidden.AV == nil || styles.Order == nil || len(styles.Order.Color) != maxBuiltinColorIndex ||+ len(styles.Order.Style1) != 4 || styles.AV == nil || styles.AV.Colors == nil ||+ len(styles.AV.Order) != av.BuiltinColorCount {t.Fatalf("unexpected empty inline styles: %#v", styles)}if _, err = os.Stat(inlineStylesPath()); !os.IsNotExist(err) {@@ -81,6 +84,10 @@ func TestInlineStylesCRUD(t *testing.T) {loaded.Styles[1].ID != saved.Styles[1].ID {t.Fatalf("inline style order or IDs changed: %#v", loaded)}+ if loaded.Order == nil || loaded.Order.Style1[len(loaded.Order.Style1)-1] != saved.Styles[0].ID ||+ loaded.Order.BackgroundColor[len(loaded.Order.BackgroundColor)-1] != saved.Styles[1].ID {+ t.Fatalf("custom styles were not appended to order: %#v", loaded.Order)+ }if _, changed, err = SetInlineStyles(loaded.Styles); err != nil || changed {t.Fatalf("unchanged inline styles were rewritten: changed=%t, err=%v", changed, err)}@@ -168,6 +175,170 @@ func TestInlineStylesBuiltinCRUD(t *testing.T) {}}+func TestInlineStylesOrder(t *testing.T) {+ setupInlineStylesTest(t)+ customID := "20260821000000-abcdefg"+ saved, _, err := SetInlineStylesData(&InlineStyles{+ Version: InlineStylesVersion,+ Styles: []*InlineStyle{{+ ID: customID,+ Name: "Accent",+ Light: &InlineStyleTheme{Color: "#abcdef"},+ Dark: &InlineStyleTheme{Color: "#123456"},+ }},+ Builtin: newEmptyInlineStyleBuiltin(),+ Order: &InlineStyleOrder{+ Color: []string{"2", customID, "1", "2", "unknown"},+ BackgroundColor: []string{"13"},+ Style1: []string{"success"},+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(saved.Order.Color) < 3 || saved.Order.Color[0] != "2" || saved.Order.Color[1] != customID ||+ saved.Order.Color[2] != "1" || saved.Order.Color[len(saved.Order.Color)-1] != "13" {+ t.Fatalf("unexpected color order: %#v", saved.Order.Color)+ }+ if saved.Order.BackgroundColor[0] != "13" || saved.Order.BackgroundColor[1] != "1" {+ t.Fatalf("unexpected background color order: %#v", saved.Order.BackgroundColor)+ }+ if !reflect.DeepEqual(saved.Order.Style1, []string{"success", "error", "warning", "info"}) {+ t.Fatalf("unexpected style order: %#v", saved.Order.Style1)+ }+}++func TestInlineStylesAVPalette(t *testing.T) {+ setupInlineStylesTest(t)+ color := &av.AttributeViewCustomColor{+ Index: 15,+ Hidden: true,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }+ saved, _, err := SetInlineStylesData(&InlineStyles{+ Version: InlineStylesVersion,+ Styles: []*InlineStyle{},+ AV: &InlineStyleAV{+ Colors: []*av.AttributeViewCustomColor{color},+ Order: []string{"15", "1", "14"},+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ if 1 != len(saved.AV.Colors) || 15 != saved.AV.Colors[0].Index || !saved.AV.Colors[0].Hidden ||+ "#010203" != saved.AV.Colors[0].Light.Color || 15 != len(saved.AV.Order) ||+ "15" != saved.AV.Order[0] || "1" != saved.AV.Order[1] || "14" != saved.AV.Order[2] {+ t.Fatalf("unexpected attribute view palette: %#v", saved.AV)+ }++ loaded, err := GetInlineStyles()+ if err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(saved.AV, loaded.AV) {+ t.Fatalf("attribute view palette was not persisted: %#v", loaded.AV)+ }+}++func TestWorkspaceAVPaletteRejectsColorsUsedByOtherAttributeViews(t *testing.T) {+ setupInlineStylesTest(t)+ color := &av.AttributeViewCustomColor{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }+ if _, _, err := SetInlineStylesData(&InlineStyles{+ Version: InlineStylesVersion,+ AV: &InlineStyleAV{Colors: []*av.AttributeViewCustomColor{color}},+ }); err != nil {+ t.Fatal(err)+ }+ const otherAvID = "20260827000000-colors1"+ attrView := &av.AttributeView{Spec: av.CurrentSpec, ID: otherAvID}+ attrView.KeyValues = []*av.KeyValues{{Key: &av.Key{+ ID: "select", Type: av.KeyTypeSelect, Options: []*av.SelectOption{{Name: "Used", Color: "15"}},+ }}}+ data, err := json.Marshal(attrView)+ if err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(util.DataDir, "storage", "av", otherAvID+".json")+ if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(path, data, 0644); err != nil {+ t.Fatal(err)+ }++ if _, _, err = SetWorkspaceAVPalette(&WorkspaceAVPaletteUpdate{}); err == nil ||+ !strings.Contains(err.Error(), otherAvID) {+ t.Fatalf("used workspace color was deleted: %v", err)+ }+ loaded, err := GetInlineStyles()+ if err != nil {+ t.Fatal(err)+ }+ if len(loaded.AV.Colors) != 1 || loaded.AV.Colors[0].Index != 15 {+ t.Fatalf("rejected palette update changed persisted colors: %#v", loaded.AV.Colors)+ }+}++func TestSetWorkspaceAVPalettePreservesUnrelatedInlineStyles(t *testing.T) {+ setupInlineStylesTest(t)+ styleID := "20260827000001-colors2"+ if _, _, err := SetInlineStylesData(&InlineStyles{+ Version: InlineStylesVersion,+ Styles: []*InlineStyle{{+ ID: styleID, Name: "Accent",+ Light: &InlineStyleTheme{Color: "#010203"},+ Dark: &InlineStyleTheme{Color: "#040506"},+ }},+ Builtin: &InlineStyleBuiltin{Colors: []*InlineStyleBuiltinColor{{+ Index: 1,+ Light: &InlineStyleTheme{Color: "#111111"},+ Dark: &InlineStyleTheme{Color: "#eeeeee"},+ }}},+ }); err != nil {+ t.Fatal(err)+ }+ color := &av.AttributeViewCustomColor{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#112233", BackgroundColor: "#445566"},+ Dark: av.AttributeViewColorTheme{Color: "#778899", BackgroundColor: "#aabbcc"},+ },+ }+ saved, changed, err := SetWorkspaceAVPalette(&WorkspaceAVPaletteUpdate{+ Colors: []*av.AttributeViewCustomColor{color},+ Order: []string{"15", "1"},+ BuiltinColors: []*WorkspaceAVBuiltinColorUpdate{{+ Index: 2, Customized: true,+ Light: &InlineStyleTheme{BackgroundColor: "#abcdef"},+ Dark: &InlineStyleTheme{BackgroundColor: "#123456"},+ Hidden: true,+ }},+ })+ if err != nil {+ t.Fatal(err)+ }+ if !changed || len(saved.Styles) != 1 || saved.Styles[0].ID != styleID {+ t.Fatalf("unrelated inline styles were changed: %#v", saved.Styles)+ }+ if len(saved.Builtin.Colors) != 2 || saved.Builtin.Colors[0].Index != 1 || saved.Builtin.Colors[1].Index != 2 ||+ !reflect.DeepEqual(saved.Builtin.Hidden.AV, []int{2}) {+ t.Fatalf("builtin color patch replaced unrelated configuration: %#v", saved.Builtin)+ }+ if len(saved.AV.Colors) != 1 || saved.AV.Order[0] != "15" {+ t.Fatalf("workspace palette was not saved: %#v", saved.AV)+ }+}+func TestInlineStylesVersion1Migration(t *testing.T) {setupInlineStylesTest(t)legacyData := []byte(`{"version":1,"styles":[{"id":"20260821000000-abcdefg","name":"Legacy","light":{"color":"#abcdef"},"dark":{"color":"#123456"}}]}`)@@ -347,7 +518,7 @@ func TestInlineStylesBuiltinValidation(t *testing.T) {}},{name: "high color index", styles: func() *InlineStyles {styles := valid()- styles.Builtin.Colors[0].Index = 14+ styles.Builtin.Colors[0].Index = 15return styles}},{name: "duplicate color index", styles: func() *InlineStyles {@@ -416,7 +587,7 @@ func TestInlineStylesBuiltinValidation(t *testing.T) {}},{name: "invalid hidden av", styles: func() *InlineStyles {styles := valid()- styles.Builtin.Hidden.AV = []int{14}+ styles.Builtin.Hidden.AV = []int{15}return styles}},}@@ -440,7 +611,7 @@ func TestInlineStylesInvalidFileIsNotOverwritten(t *testing.T) {}{{name: "invalid JSON", data: []byte(`{"version":`)},{name: "future version", data: []byte(`{"version":3,"styles":[]}`)},- {name: "invalid builtin", data: []byte(`{"version":2,"styles":[],"builtin":{"colors":[{"index":14,"light":{"color":"#abcdef"},"dark":{"color":"#123456"}}]}}`)},+ {name: "invalid builtin", data: []byte(`{"version":2,"styles":[],"builtin":{"colors":[{"index":15,"light":{"color":"#abcdef"},"dark":{"color":"#123456"}}]}}`)},{name: "oversized", data: bytes.Repeat([]byte("x"), maxInlineStylesFileSize+1)},}for _, test := range tests {diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex 05227abc2a..24e04a6615 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -372,13 +372,6 @@ func TestFilterBlockAttributeViewKeysByPublishAccess(t *testing.T) {newKeys := func(avID, blockID string) *BlockAttributeViewKeys {attrView := av.NewAttributeView(avID)attrView.Name = avID- attrView.CustomColors = []*av.AttributeViewCustomColor{{- Index: 15,- AttributeViewColor: av.AttributeViewColor{- Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},- Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},- },- }}blockKey := attrView.GetBlockKey()textKey := av.NewKey(ast.NewNodeID(), "Text", "", av.KeyTypeText)rowID := ast.NewNodeID()@@ -467,11 +460,17 @@ func newTestBlockAttributeViewKeys(attrView *av.AttributeView, blockIDs []string}}return &BlockAttributeViewKeys{- AvID: attrView.ID,- AvName: attrView.Name,- CustomColors: attrView.CustomColors,- BlockIDs: blockIDs,- KeyValues: keyValues,+ AvID: attrView.ID,+ AvName: attrView.Name,+ CustomColors: []*av.AttributeViewCustomColor{{+ Index: 15,+ AttributeViewColor: av.AttributeViewColor{+ Light: av.AttributeViewColorTheme{Color: "#010203", BackgroundColor: "#040506"},+ Dark: av.AttributeViewColorTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},+ },+ }},+ BlockIDs: blockIDs,+ KeyValues: keyValues,}}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 1795159f60..e6076cecc9 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -2488,6 +2488,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,syncingFiles = sync.Map{}syncingStorages.Store(false)if needReloadInlineStyles && !exit {+ invalidateWorkspaceAVPaletteCache()util.BroadcastByType("main", "reloadInlineStyles", 0, "", nil)util.ReloadPublishServiceSessions()}diff --git a/kernel/model/theme.go b/kernel/model/theme.goindex 6534f6aed0..ecf4ede740 100644--- a/kernel/model/theme.go+++ b/kernel/model/theme.go@@ -115,6 +115,24 @@ func mergeInlineStyleThemeVars(themeStyles map[string]string, styles *InlineStyl}}}+ if styles.AV != nil {+ for _, color := range styles.AV.Colors {+ if color == nil {+ continue+ }+ theme := color.Light+ if isDarkMode {+ theme = color.Dark+ }+ index := strconv.Itoa(color.Index)+ if theme.Color != "" {+ themeStyles["--b3-font-color"+index] = theme.Color+ }+ if theme.BackgroundColor != "" {+ themeStyles["--b3-font-background"+index] = theme.BackgroundColor+ }+ }+ }for _, style := range styles.Styles {if style == nil {continuediff --git a/kernel/sql/av_custom_color_context_test.go b/kernel/sql/av_custom_color_context_test.goindex dfdb67957f..1e3a03ccf7 100644--- a/kernel/sql/av_custom_color_context_test.go+++ b/kernel/sql/av_custom_color_context_test.go@@ -24,11 +24,13 @@ import (func TestApplyRelatedCustomColorRenderContext(t *testing.T) {historicalColor := customColorForContextTest("#010203", "#040506", "#070809", "#0a0b0c")- context := &av.CustomColorRenderContext{ResolveRelatedCustomColors: func(string) ([]*av.AttributeViewCustomColor, bool) {- return []*av.AttributeViewCustomColor{historicalColor}, true+ context := &av.CustomColorRenderContext{ResolveRelatedCustomColors: func(string) (+ []*av.AttributeViewCustomColor, []string, bool,+ ) {+ return []*av.AttributeViewCustomColor{historicalColor}, []string{"15", "1"}, true}}source := &av.AttributeView{CustomColorRenderContext: context}- target, key, value := relatedCustomColorTargetForContextTest()+ target, key, value := relatedCustomColorTargetForContextTest(t)applyRelatedCustomColorRenderContext(source, target)@@ -38,8 +40,8 @@ func TestApplyRelatedCustomColorRenderContext(t *testing.T) {if target.KeyValues[0].Key != key || target.KeyValues[0].Values[0] != value || "Current value" != value.MSelect[0].Content {t.Fatal("applying a historical palette changed the current target value source")}- if 1 != len(target.CustomColors) || "#010203" != target.CustomColors[0].Light.Color {- t.Fatalf("unexpected historical palette: %+v", target.CustomColors)+ if 1 != len(target.Palette()) || "#010203" != target.Palette()[0].Light.Color {+ t.Fatalf("unexpected historical palette: %+v", target.Palette())}if nil == key.Options[0].ResolvedColor || "#010203" != key.Options[0].ResolvedColor.Light.Color {t.Fatalf("option did not use the historical target palette: %+v", key.Options[0].ResolvedColor)@@ -50,18 +52,20 @@ func TestApplyRelatedCustomColorRenderContext(t *testing.T) {}func TestApplyRelatedCustomColorRenderContextMissingPalette(t *testing.T) {- target, key, value := relatedCustomColorTargetForContextTest()+ target, key, value := relatedCustomColorTargetForContextTest(t)if nil == key.Options[0].ResolvedColor || nil == value.MSelect[0].ResolvedColor {t.Fatal("test target was not initialized with its current palette")}source := &av.AttributeView{CustomColorRenderContext: &av.CustomColorRenderContext{- ResolveRelatedCustomColors: func(string) ([]*av.AttributeViewCustomColor, bool) { return nil, false },+ ResolveRelatedCustomColors: func(string) ([]*av.AttributeViewCustomColor, []string, bool) {+ return nil, nil, false+ },}}applyRelatedCustomColorRenderContext(source, target)- if 0 != len(target.CustomColors) {- t.Fatalf("missing historical palette retained current colors: %+v", target.CustomColors)+ if 0 != len(target.Palette()) {+ t.Fatalf("missing historical palette retained current colors: %+v", target.Palette())}if nil != key.Options[0].ResolvedColor || nil != value.MSelect[0].ResolvedColor {t.Fatal("missing historical palette retained a derived current color")@@ -69,25 +73,30 @@ func TestApplyRelatedCustomColorRenderContextMissingPalette(t *testing.T) {}func TestApplyRelatedCustomColorRenderContextOrdinaryRenderDoesNotLeak(t *testing.T) {- target, key, value := relatedCustomColorTargetForContextTest()+ target, key, value := relatedCustomColorTargetForContextTest(t)applyRelatedCustomColorRenderContext(&av.AttributeView{}, target)- if 1 != len(target.CustomColors) || "#111213" != target.CustomColors[0].Light.Color {- t.Fatalf("ordinary render palette changed: %+v", target.CustomColors)+ if 1 != len(target.Palette()) || "#111213" != target.Palette()[0].Light.Color {+ t.Fatalf("ordinary render palette changed: %+v", target.Palette())}if nil == key.Options[0].ResolvedColor || nil == value.MSelect[0].ResolvedColor {t.Fatal("ordinary render lost its current derived color")}}-func relatedCustomColorTargetForContextTest() (target *av.AttributeView, key *av.Key, value *av.Value) {+func relatedCustomColorTargetForContextTest(t *testing.T) (target *av.AttributeView, key *av.Key, value *av.Value) {+ t.Helper()currentColor := customColorForContextTest("#111213", "#141516", "#171819", "#1a1b1c")key = &av.Key{ID: "select", Type: av.KeyTypeSelect, Options: []*av.SelectOption{{Name: "Current", Color: "15"}}}value = &av.Value{Type: av.KeyTypeSelect, MSelect: []*av.ValueSelect{{Content: "Current value", Color: "15"}}}target = &av.AttributeView{- ID: "target",- CustomColors: []*av.AttributeViewCustomColor{currentColor},- KeyValues: []*av.KeyValues{{Key: key, Values: []*av.Value{value}}},+ ID: "target",+ KeyValues: []*av.KeyValues{{Key: key, Values: []*av.Value{value}}},+ }+ old := av.LoadWorkspacePalette+ t.Cleanup(func() { av.LoadWorkspacePalette = old })+ av.LoadWorkspacePalette = func() ([]*av.AttributeViewCustomColor, []string) {+ return []*av.AttributeViewCustomColor{currentColor}, nil}target.ResolveDirectColors()return