Skip to content

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

:sparkles: Support customizing and hiding built-in colors https://github.com/siyuan-note/siyuan/issues/18966

Daniel7c8c446fada8
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index be99f6a906..be5b7971c5 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "إدارة الألوان",
+ "manageBuiltinColors": "إدارة الألوان المضمنة",
+ "showInColorPicker": "إظهار في منتقي الألوان",
+ "resetAll": "إعادة تعيين الكل",
"exportFile": "تصدير الملف",
"namingEmpty": "لا يمكن أن يكون الاسم فارغًا",
"recentCreated": "تم إنشاؤها مؤخرًا",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 64bf1a7790..3360d8cbad 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 0268d32df4..307479acb7 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 4729ba3e5a..39c3e5d4a3 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,8 @@
{
+ "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.json
index ffb1113600..b00be9202c 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 84b9b79bcc..cf9dcf3984 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "ניהול צבעים",
+ "manageBuiltinColors": "ניהול צבעים מובנים",
+ "showInColorPicker": "הצגה בבורר הצבעים",
+ "resetAll": "איפוס הכול",
"exportFile": "ייצוא קובץ",
"namingEmpty": "השם לא יכול להיות ריק",
"recentCreated": "נוצרו לאחרונה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 4833bdfc61..95b59c6ee5 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "रंग प्रबंधित करें",
+ "manageBuiltinColors": "अंतर्निहित रंग प्रबंधित करें",
+ "showInColorPicker": "रंग चयनकर्ता में दिखाएँ",
+ "resetAll": "सभी रीसेट करें",
"exportFile": "फ़ाइल निर्यात करें",
"namingEmpty": "नाम खाली नहीं हो सकता",
"recentCreated": "हाल ही में बनाए गए",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index de389b43e5..b83fddbf56 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,8 @@
{
+ "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.json
index e256303b04..69acc1406d 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 0ee8f6b1fb..b1be59a22f 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "色を管理",
+ "manageBuiltinColors": "組み込み色を管理",
+ "showInColorPicker": "カラーピッカーに表示",
+ "resetAll": "すべてリセット",
"exportFile": "ファイルをエクスポート",
"namingEmpty": "名前を空にすることはできません",
"recentCreated": "最近作成",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 833fbce898..ed35b33607 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "색상 관리",
+ "manageBuiltinColors": "기본 제공 색상 관리",
+ "showInColorPicker": "색상 선택기에 표시",
+ "resetAll": "모두 초기화",
"exportFile": "파일 내보내기",
"namingEmpty": "이름은 비워 둘 수 없습니다",
"recentCreated": "최근 생성",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 430b11b150..c43062070f 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 62a4c30117..bb9066ce04 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,8 @@
{
+ "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.json
index be01d7c68a..fb185943d5 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 7d1f2ca257..51c870e8c4 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "Управление цветами",
+ "manageBuiltinColors": "Управление встроенными цветами",
+ "showInColorPicker": "Показывать в палитре цветов",
+ "resetAll": "Сбросить всё",
"exportFile": "Экспортировать файл",
"namingEmpty": "Имя не может быть пустым",
"recentCreated": "Недавно созданные",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index d676d27bce..d49b3dc837 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 994e7d905c..afc962fde3 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "จัดการสี",
+ "manageBuiltinColors": "จัดการสีในตัว",
+ "showInColorPicker": "แสดงในตัวเลือกสี",
+ "resetAll": "รีเซ็ตทั้งหมด",
"exportFile": "ส่งออกไฟล์",
"namingEmpty": "ชื่อต้องไม่ว่างเปล่า",
"recentCreated": "สร้างล่าสุด",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 5bba07124f..ac94a9e3db 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,8 @@
{
+ "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.json
index 7dd33b6cd4..a73962f9e7 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "Керування кольорами",
+ "manageBuiltinColors": "Керування вбудованими кольорами",
+ "showInColorPicker": "Показувати в палітрі кольорів",
+ "resetAll": "Скинути все",
"exportFile": "Експортувати файл",
"namingEmpty": "Назва не може бути порожньою",
"recentCreated": "Нещодавно створені",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 4899867a53..915388f369 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "管理颜色",
+ "manageBuiltinColors": "管理内置颜色",
+ "showInColorPicker": "在颜色选择器中显示",
+ "resetAll": "全部重置",
"exportFile": "导出文件",
"namingEmpty": "命名不能为空",
"recentCreated": "最近创建",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 947f2d7c32..eb2fd3c1c5 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,8 @@
{
+ "manageColors": "管理顏色",
+ "manageBuiltinColors": "管理內建顏色",
+ "showInColorPicker": "在顏色選擇器中顯示",
+ "resetAll": "全部重設",
"exportFile": "導出檔案",
"namingEmpty": "命名不能為空",
"recentCreated": "最近建立",
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 2a1dcefd76..15762b2b46 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -27,13 +27,20 @@ import {getMobilePluginToolbarItems} from "./pluginToolbar";
import {escapeHtml} from "../../util/escape";
import {
encodeStyle1,
+ filterHiddenRecentInlineStyles,
+ getBuiltinInlineStyleIDFromValue,
+ getBuiltinInlineStylePreview,
+ getBuiltinInlineStylePropertyValue,
getInlineStyleByValue,
getInlineStyleIDFromValue,
getInlineStylePreview,
getInlineStylesCache,
getInlineStyleType,
+ getVisibleBuiltinInlineStyleIDs,
+ isBuiltinInlineStyleVisible,
INLINE_BACKGROUND_COLORS,
INLINE_FONT_COLORS,
+ TBuiltinInlineStyleID,
TInlineStyleType,
} from "../../protyle/toolbar/inlineStyle";
import {openInlineStyleDialog} from "../../protyle/toolbar/inlineStyleDialog";
@@ -361,9 +368,23 @@ const getSlashItem = (value: string, icon: string, text: string, focus = "false"
</button>`;
};
+const getBuiltinStyleLabel = (id: TBuiltinInlineStyleID) => ({
+ error: window.siyuan.languages.errorStyle,
+ warning: window.siyuan.languages.warningStyle,
+ info: window.siyuan.languages.infoStyle,
+ success: window.siyuan.languages.successStyle,
+})[id];
+
+const getBuiltinStyleCSS = (id: TBuiltinInlineStyleID) =>
+ `color: ${getBuiltinInlineStylePropertyValue(id, "color")};` +
+ `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>
@@ -371,9 +392,20 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
});
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>
+</button>`;
+ });
+ let builtinStyleHTML = "";
+ getVisibleBuiltinInlineStyleIDs().forEach(id => {
+ const preview = getBuiltinInlineStylePreview(id);
+ builtinStyleHTML += `<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>
</button>`;
});
let customColorHTML = "";
@@ -400,7 +432,7 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
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>
- <span class="keyboard__slash-text">${window.siyuan.languages.manageCustomColors}</span>
+ <span class="keyboard__slash-text">${window.siyuan.languages.manageColors}</span>
</button>`;
const nodeElements = getFontNodeElements(protyle);
@@ -413,7 +445,7 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
});
let lastColorHTML = "";
- const lastFonts = window.siyuan.storage[Constants.LOCAL_FONTSTYLES];
+ const lastFonts = filterHiddenRecentInlineStyles(window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);
if (lastFonts.length > 0) {
lastColorHTML = `<div data-id="lastUsed" class="keyboard__slash-title">
${window.siyuan.languages.lastUsed}
@@ -457,10 +489,14 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
break;
case "style1":
if (lastFontStatus[1]) {
- const builtInStyle = lastFontStatus[2]?.match(/^var\(--b3-card-([a-z]+)-color\)$/)?.[1];
+ const builtInStyle = getBuiltinInlineStyleIDFromValue(item);
+ const preview = builtInStyle ? getBuiltinInlineStylePreview(builtInStyle) : {
+ backgroundColor: lastFontStatus[1],
+ color: lastFontStatus[2],
+ };
lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
- <span class="keyboard__slash-icon" style="background-color:${lastFontStatus[1]};color:${lastFontStatus[2]}">A</span>
- <span class="keyboard__slash-text">${customLabel || (builtInStyle ? window.siyuan.languages[builtInStyle + "Style"] : window.siyuan.languages.color)}</span>
+ <span class="keyboard__slash-icon" style="background-color:${preview.backgroundColor};color:${preview.color}">A</span>
+ <span class="keyboard__slash-text">${customLabel || (builtInStyle ? getBuiltinStyleLabel(builtInStyle) : window.siyuan.languages.color)}</span>
</button>`;
} else {
lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
@@ -487,22 +523,7 @@ 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>
- <button class="keyboard__slash-item" data-type="style1">
- <span class="keyboard__slash-icon" style="color: var(--b3-card-error-color);background-color: var(--b3-card-error-background);">A</span>
- <span class="keyboard__slash-text">${window.siyuan.languages.errorStyle}</span>
- </button>
- <button class="keyboard__slash-item" data-type="style1">
- <span class="keyboard__slash-icon" style="color: var(--b3-card-warning-color);background-color: var(--b3-card-warning-background);">A</span>
- <span class="keyboard__slash-text">${window.siyuan.languages.warningStyle}</span>
- </button>
- <button class="keyboard__slash-item" data-type="style1">
- <span class="keyboard__slash-icon" style="color: var(--b3-card-info-color);background-color: var(--b3-card-info-background);">A</span>
- <span class="keyboard__slash-text">${window.siyuan.languages.infoStyle}</span>
- </button>
- <button class="keyboard__slash-item" data-type="style1">
- <span class="keyboard__slash-icon" style="color: var(--b3-card-success-color);background-color: var(--b3-card-success-background);">A</span>
- <span class="keyboard__slash-text">${window.siyuan.languages.successStyle}</span>
- </button>
+ ${builtinStyleHTML}
${customStyleHTML}
${getManageHTML("style1")}
</div>
@@ -602,6 +623,15 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {
if (pluginHTML) {
pluginHTML = `<div class="keyboard__slash-title"></div><div class="keyboard__slash-block">${pluginHTML}</div>`;
}
+ let builtinStyleHTML = "";
+ (["info", "success", "warning", "error"] as TBuiltinInlineStyleID[]).forEach(id => {
+ if (!isBuiltinInlineStyleVisible("style1", id)) {
+ return;
+ }
+ const style = getBuiltinStyleCSS(id);
+ builtinStyleHTML += getSlashItem(`style${Constants.ZWSP}${style}`,
+ `<div style="${style}" class="keyboard__slash-icon">A</div>`, getBuiltinStyleLabel(id), "true");
+ });
const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;
utilElement.innerHTML = `<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
@@ -660,10 +690,7 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {
</div>
<div class="keyboard__slash-title"></div>
<div class="keyboard__slash-block">
- ${getSlashItem(`style${Constants.ZWSP}color: var(--b3-card-info-color);background-color: var(--b3-card-info-background);`, '<div style="color: var(--b3-card-info-color);background-color: var(--b3-card-info-background);" class="keyboard__slash-icon">A</div>', window.siyuan.languages.infoStyle, "true")}
- ${getSlashItem(`style${Constants.ZWSP}color: var(--b3-card-success-color);background-color: var(--b3-card-success-background);`, '<div style="color: var(--b3-card-success-color);background-color: var(--b3-card-success-background);" class="keyboard__slash-icon">A</div>', window.siyuan.languages.successStyle, "true")}
- ${getSlashItem(`style${Constants.ZWSP}color: var(--b3-card-warning-color);background-color: var(--b3-card-warning-background);`, '<div style="color: var(--b3-card-warning-color);background-color: var(--b3-card-warning-background);" class="keyboard__slash-icon">A</div>', window.siyuan.languages.warningStyle, "true")}
- ${getSlashItem(`style${Constants.ZWSP}color: var(--b3-card-error-color);background-color: var(--b3-card-error-background);`, '<div style="color: var(--b3-card-error-color);background-color: var(--b3-card-error-background);" class="keyboard__slash-icon">A</div>', window.siyuan.languages.errorStyle, "true")}
+ ${builtinStyleHTML}
${getSlashItem(`style${Constants.ZWSP}`, '<div class="keyboard__slash-icon">A</div>', window.siyuan.languages.clearFontStyle, "true")}
</div>${pluginHTML}`;
protyle.hint.bindUploadEvent(protyle, utilElement);
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index a231f276e5..26d49a3f97 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -30,6 +30,22 @@ import {
} from "../../config/entryVisibility/catalog";
import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtime";
import {resolveSlashMenuItems, TSlashMenuItem} from "./slashMenu";
+import {
+ getBuiltinInlineStylePropertyValue,
+ isBuiltinInlineStyleVisible,
+ TBuiltinInlineStyleID,
+} from "../toolbar/inlineStyle";
+
+const slashBuiltinStyleIDs: Partial<Record<string, TBuiltinInlineStyleID>> = {
+ infoStyle: "info",
+ successStyle: "success",
+ warningStyle: "warning",
+ errorStyle: "error",
+};
+
+const getBuiltinStyleCSS = (id: TBuiltinInlineStyleID) =>
+ `color: ${getBuiltinInlineStylePropertyValue(id, "color")};` +
+ `background-color: ${getBuiltinInlineStylePropertyValue(id, "backgroundColor")};`;
const getHotkeyOrMarker = (hotkey: string, marker: string) => {
if (hotkey) {
@@ -356,23 +372,23 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {
}, {
filter: [window.siyuan.languages.infoStyle, "info style", "信息样式", "xinxiyangshi", "xxys"],
id: "infoStyle",
- value: `style${Constants.ZWSP}color: var(--b3-card-info-color);background-color: var(--b3-card-info-background);`,
- html: `<div class="b3-list-item__first"><div style="color: var(--b3-card-info-color);background-color: var(--b3-card-info-background);" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.infoStyle}</span></div>`,
+ value: `style${Constants.ZWSP}${getBuiltinStyleCSS("info")}`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("info")}" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.infoStyle}</span></div>`,
}, {
filter: [window.siyuan.languages.successStyle, "success style", "成功样式", "chenggongyangshi", "cgys"],
id: "successStyle",
- value: `style${Constants.ZWSP}color: var(--b3-card-success-color);background-color: var(--b3-card-success-background);`,
- html: `<div class="b3-list-item__first"><div style="color: var(--b3-card-success-color);background-color: var(--b3-card-success-background);" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.successStyle}</span></div>`,
+ value: `style${Constants.ZWSP}${getBuiltinStyleCSS("success")}`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("success")}" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.successStyle}</span></div>`,
}, {
filter: [window.siyuan.languages.warningStyle, "warning style", "警告样式", "jinggaoyangshi", "jgys"],
id: "warningStyle",
- value: `style${Constants.ZWSP}color: var(--b3-card-warning-color);background-color: var(--b3-card-warning-background);`,
- html: `<div class="b3-list-item__first"><div style="color: var(--b3-card-warning-color);background-color: var(--b3-card-warning-background);" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.warningStyle}</span></div>`,
+ value: `style${Constants.ZWSP}${getBuiltinStyleCSS("warning")}`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("warning")}" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.warningStyle}</span></div>`,
}, {
filter: [window.siyuan.languages.errorStyle, "error style", "错误样式", "cuowuyangshi", "cwys"],
id: "errorStyle",
- value: `style${Constants.ZWSP}color: var(--b3-card-error-color);background-color: var(--b3-card-error-background);`,
- html: `<div class="b3-list-item__first"><div style="color: var(--b3-card-error-color);background-color: var(--b3-card-error-background);" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.errorStyle}</span></div>`,
+ value: `style${Constants.ZWSP}${getBuiltinStyleCSS("error")}`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("error")}" class="color__square color__square--list">A</div><span class="b3-list-item__text">${window.siyuan.languages.errorStyle}</span></div>`,
}, {
filter: [window.siyuan.languages.clearFontStyle, "clear style", "清除样式", "qingchuyangshi", "qcys"],
id: "clearFontStyle",
@@ -414,8 +430,11 @@ export const hintSlash = (key: string, protyle: IProtyle, sourceOrHideConfigured
allList.pop();
}
refreshSlashMenuCatalog(protyle.app.plugins);
- return resolveSlashMenuItems(allList.filter((item) =>
- getEntryCatalogNode(getSlashMenuEntryPath(item.entryKey))), {
+ return resolveSlashMenuItems(allList.filter((item) => {
+ const builtinStyleID = slashBuiltinStyleIDs[item.entryKey];
+ return getEntryCatalogNode(getSlashMenuEntryPath(item.entryKey)) &&
+ (!builtinStyleID || isBuiltinInlineStyleVisible("style1", builtinStyleID));
+ }), {
enabled,
hideConfiguredCreate,
key,
diff --git a/app/src/protyle/render/av/color.test.ts b/app/src/protyle/render/av/color.test.ts
index 4ed6b8c1d4..5571fb53cf 100644
--- a/app/src/protyle/render/av/color.test.ts
+++ b/app/src/protyle/render/av/color.test.ts
@@ -1,4 +1,4 @@
-import {describe, it} from "node:test";
+import {afterEach, describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
getAvailableAVCustomColorIndex,
@@ -8,6 +8,7 @@ import {
getNextAVOptionColor,
normalizeAVColorIndex,
} from "./color";
+import {INLINE_STYLE_EMPTY, setInlineStylesCache} from "../../toolbar/inlineStyle";
const customColor: IAVCustomColor = {
index: 15,
@@ -21,6 +22,10 @@ const customColor: IAVCustomColor = {
},
};
+afterEach(() => {
+ setInlineStylesCache(INLINE_STYLE_EMPTY);
+});
+
describe("AV color indexes", () => {
it("accepts only bounded decimal indexes", () => {
assert.equal(normalizeAVColorIndex("15"), 15);
@@ -33,6 +38,24 @@ describe("AV color indexes", () => {
assert.equal(getNextAVOptionColor(14), "1");
});
+ it("skips hidden built-in colors while keeping the neutral color", () => {
+ setInlineStylesCache({
+ ...INLINE_STYLE_EMPTY,
+ builtin: {
+ ...INLINE_STYLE_EMPTY.builtin,
+ hidden: {
+ ...INLINE_STYLE_EMPTY.builtin.hidden,
+ av: Array.from({length: 13}, (_, index) => index + 1),
+ },
+ },
+ });
+ assert.equal(getNextAVOptionColor(0), "14");
+ assert.equal(getNextAVOptionColor(12), "14");
+ const html = getAVColorGridHTML([], "1", "Manage");
+ assert.doesNotMatch(html, /data-color="1"/);
+ assert.match(html, /data-color="14"/);
+ });
+
it("finds the first available custom index", () => {
assert.equal(getAvailableAVCustomColorIndex([{index: 15}, {index: 17}]), 16);
});
diff --git a/app/src/protyle/render/av/color.ts b/app/src/protyle/render/av/color.ts
index a5af547ac3..ab5a3584c9 100644
--- a/app/src/protyle/render/av/color.ts
+++ b/app/src/protyle/render/av/color.ts
@@ -1,4 +1,5 @@
import {escapeAttr} from "../../../util/escape";
+import {getVisibleBuiltinColorIndexes} from "../../toolbar/inlineStyle";
export const AV_BUILTIN_COLOR_COUNT = 14;
export const AV_CUSTOM_COLOR_MIN = 15;
@@ -56,8 +57,10 @@ export const getAVBackgroundColor = (value: TAVColorReference) => {
return `var(--b3-font-background${index > AV_BUILTIN_COLOR_COUNT ? AV_BUILTIN_COLOR_COUNT : index})`;
};
-export const getNextAVOptionColor = (optionCount: number) =>
- (Math.max(0, optionCount) % AV_BUILTIN_COLOR_COUNT + 1).toString();
+export const getNextAVOptionColor = (optionCount: number) => {
+ const colors = [...getVisibleBuiltinColorIndexes("av"), AV_BUILTIN_COLOR_COUNT];
+ return colors[Math.max(0, optionCount) % colors.length].toString();
+};
export const getAvailableAVCustomColorIndex = (colors: Pick<IAVCustomColor, "index">[]) => {
const usedIndexes = new Set(colors.map(item => item.index));
@@ -83,9 +86,8 @@ export const getAVResolvedColor = (data: IAV | undefined, color: string) => {
export const getAVColorGridHTML = (customColors: IAVCustomColor[], currentColor: string,
manageLabel: string) => {
const currentIndex = normalizeAVColorIndex(currentColor);
- const colors: TAVColorReference[] = Array.from({length: AV_BUILTIN_COLOR_COUNT}, (_, index) => ({
- color: (index + 1).toString(),
- }));
+ const colors: TAVColorReference[] = [...getVisibleBuiltinColorIndexes("av"), AV_BUILTIN_COLOR_COUNT]
+ .map(index => ({color: index.toString()}));
normalizeAVCustomColors(customColors).forEach(item => {
colors.push({
color: item.index.toString(),
diff --git a/app/src/protyle/render/av/colorDialog.ts b/app/src/protyle/render/av/colorDialog.ts
index a02170f6e1..c635f7a066 100644
--- a/app/src/protyle/render/av/colorDialog.ts
+++ b/app/src/protyle/render/av/colorDialog.ts
@@ -12,6 +12,7 @@ import {
getAVCustomColors,
} from "./color";
import {getInlineStyleType, getInlineStylesCache} from "../../toolbar/inlineStyle";
+import {openBuiltinColorDialog} from "../../toolbar/builtinColorDialog";
import * as dayjs from "dayjs";
const cloneCustomColors = (colors: IAVCustomColor[]) => JSON.parse(JSON.stringify(colors)) as IAVCustomColor[];
@@ -31,14 +32,20 @@ export const openAVCustomColorDialog = (options: {
let editingIndex: number | undefined;
let editingColorIndex: number | undefined;
const dialog = new Dialog({
- title: window.siyuan.languages.manageCustomColors,
+ title: window.siyuan.languages.manageColors,
width: isMobile() ? "92vw" : "600px",
content: `<div class="b3-dialog__content" style="max-height:70vh;overflow:auto">
<div data-panel="list">
<div data-type="avCustomColorList" class="b3-list b3-list--background fn__selectnone" style="--file-toggle-width:0px"></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>
+ </div>
</div>
<div data-panel="editor" class="fn__none">
<div class="b3-label b3-label--inner" data-field="colorIndex"></div>
@@ -62,6 +69,7 @@ export const openAVCustomColorDialog = (options: {
const editorPanel = dialog.element.querySelector('[data-panel="editor"]') 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 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;
@@ -82,7 +90,7 @@ export const openAVCustomColorDialog = (options: {
</div>`;
}).join("");
newElement.disabled = draft.length >= AV_CUSTOM_COLOR_LIMIT;
- newElement.style.marginTop = draft.length === 0 ? "0" : "8px";
+ buttonsElement.style.marginTop = draft.length === 0 ? "0" : "8px";
};
const setEditorActionMode = (editing: boolean) => {
@@ -154,6 +162,8 @@ export const openAVCustomColorDialog = (options: {
const index = parseInt(actionElement.dataset.index);
if (action === "new") {
showEditor();
+ } else if (action === "manageBuiltin") {
+ openBuiltinColorDialog("av");
} else if (action === "edit") {
showEditor(index);
} else if (action === "delete") {
diff --git a/app/src/protyle/render/av/kanban/groupMenu.ts b/app/src/protyle/render/av/kanban/groupMenu.ts
index 46f78f4792..612ecc1047 100644
--- a/app/src/protyle/render/av/kanban/groupMenu.ts
+++ b/app/src/protyle/render/av/kanban/groupMenu.ts
@@ -91,7 +91,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.manageCustomColors)}</div>`;
+ getAVCustomColors(data), option.color, window.siyuan.languages.manageColors)}</div>`;
menu.addItem({
type: "empty",
iconHTML: "",
diff --git a/app/src/protyle/render/av/select.ts b/app/src/protyle/render/av/select.ts
index 6dc81c8737..11a297cb63 100644
--- a/app/src/protyle/render/av/select.ts
+++ b/app/src/protyle/render/av/select.ts
@@ -402,7 +402,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.manageCustomColors)}</div>`;
+ getAVCustomColors(data), color, window.siyuan.languages.manageColors)}</div>`;
menu.addItem({
type: "empty",
iconHTML: "",
diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.ts
index 335cd44181..997f096895 100644
--- a/app/src/protyle/toolbar/Font.ts
+++ b/app/src/protyle/toolbar/Font.ts
@@ -10,14 +10,21 @@ import {escapeAttr} from "../../util/escape";
import {
decodeStyle1,
encodeStyle1,
+ filterHiddenRecentInlineStyles,
+ getBuiltinInlineStyleApplication,
+ getBuiltinInlineStyleIDFromValue,
+ getBuiltinInlineStylePreview,
getInlineStyleByValue,
getInlineStyleIDFromValue,
getInlineStylePreview,
getInlineStylesCache,
getInlineStyleType,
getRecentInlineStyleKey,
+ getVisibleBuiltinInlineStyleIDs,
+ isBuiltinInlineStyleVisible,
INLINE_BACKGROUND_COLORS,
INLINE_FONT_COLORS,
+ TBuiltinInlineStyleID,
TInlineStyleType,
} from "./inlineStyle";
import {openInlineStyleDialog} from "./inlineStyleDialog";
@@ -119,13 +126,32 @@ export const convertFontSize = (fontSize: string, unit: "px" | "em", baseFontSiz
export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
onChange?: (type: string, color?: string) => void) => {
let colorHTML = "";
- INLINE_FONT_COLORS.forEach((item) => {
+ 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) => {
+ 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>`;
+ });
let customColorHTML = "";
let customBackgroundHTML = "";
let customStyleHTML = "";
@@ -145,7 +171,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
}
});
const getManageHTML = (type: TInlineStyleType) => window.siyuan.config.readonly || window.siyuan.isPublish ? "" :
- `<button class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.manageCustomColors}" data-action="manageInlineStyle" data-inline-style-type="${type}"><svg class="svg--mid"><use xlink:href="#iconSettings"></use></svg></button>`;
+ `<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>`;
const element = document.createElement("div");
element.classList.add("protyle-font");
@@ -157,7 +183,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
}
});
let lastColorHTML = "";
- const lastFonts = window.siyuan.storage[Constants.LOCAL_FONTSTYLES];
+ const lastFonts = filterHiddenRecentInlineStyles(window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);
if (lastFonts.length > 0) {
lastColorHTML = `<div data-id="lastUsed" class="fn__flex">
${window.siyuan.languages.lastUsed}
@@ -189,9 +215,15 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
lastColorHTML += `<button data-type="${lastFontStatus[0]}" data-value="${lastFontStatus[1]}" class="protyle-font__style ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.fontSize} ${lastFontStatus[1]}">${lastFontStatus[1]}</button>`;
}
break;
- case "style1":
- lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${customLabel || window.siyuan.languages.color + (lastFontStatus[1] ? "" : " " + window.siyuan.languages.default)}" ${lastFontStatus[1] ? `style="background-color:${lastFontStatus[1]};color:${lastFontStatus[2]}"` : ""} data-type="${lastFontStatus[0]}">A</button>`;
+ case "style1": {
+ const builtinStyleID = getBuiltinInlineStyleIDFromValue(item);
+ const preview = builtinStyleID ? getBuiltinInlineStylePreview(builtinStyleID) : {
+ backgroundColor: lastFontStatus[1],
+ color: lastFontStatus[2],
+ };
+ lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${customLabel || (builtinStyleID ? builtinStyleLabels[builtinStyleID] : window.siyuan.languages.color + (lastFontStatus[1] ? "" : " " + window.siyuan.languages.default))}" ${lastFontStatus[1] ? `style="background-color:${preview.backgroundColor};color:${preview.color}"` : ""} data-type="${lastFontStatus[0]}">A</button>`;
break;
+ }
case "clear":
lastColorHTML += `<button style="height: 26px;display: flex;align-items: center;padding: 0 5px;" data-type="${lastFontStatus[0]}" class="protyle-font__style ariaLabel" aria-label="${window.siyuan.languages.clearFontStyle}"><svg class="svg--mid"><use xlink:href="#iconTrashcan"></use></svg></button>`;
break;
@@ -209,10 +241,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>
- <button class="color__square" data-type="style1" style="color: var(--b3-card-error-color);background-color: var(--b3-card-error-background);">A</button>
- <button class="color__square" data-type="style1" style="color: var(--b3-card-warning-color);background-color: var(--b3-card-warning-background);">A</button>
- <button class="color__square" data-type="style1" style="color: var(--b3-card-info-color);background-color: var(--b3-card-info-background);">A</button>
- <button class="color__square" data-type="style1" style="color: var(--b3-card-success-color);background-color: var(--b3-card-success-background);">A</button>
+ ${builtinStyleHTML}
${customStyleHTML}
${getManageHTML("style1")}
</div>
@@ -273,6 +302,8 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
const dataType = target.getAttribute("data-type");
if (target.tagName === "BUTTON") {
if (target.dataset.action === "manageInlineStyle") {
+ closeSubElement(protyle.toolbar);
+ protyle.toolbar.subElement.classList.add("fn__none");
openInlineStyleDialog(target.dataset.inlineStyleType as TInlineStyleType);
} else if (dataType === "style1") {
applyFontStyle(dataType, encodeStyle1(target.style.backgroundColor, target.style.color));
@@ -338,11 +369,13 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: str
window.siyuan.storage[Constants.LOCAL_FONTSTYLES] = localFontStyles;
setStorageVal(Constants.LOCAL_FONTSTYLES, window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);
} else {
- if (localFontStyles.length === 0) {
+ const visibleFontStyles = filterHiddenRecentInlineStyles(localFontStyles);
+ if (visibleFontStyles.length === 0) {
type = "style1";
- color = encodeStyle1("var(--b3-card-error-background)", "var(--b3-card-error-color)");
+ const builtinStyleID = getVisibleBuiltinInlineStyleIDs()[0];
+ color = builtinStyleID ? getBuiltinInlineStyleApplication(builtinStyleID).color : encodeStyle1();
} else {
- const fontStyles = localFontStyles[0].split(Constants.ZWSP);
+ const fontStyles = visibleFontStyles[0].split(Constants.ZWSP);
type = fontStyles.splice(0, 1)[0];
color = fontStyles.join(Constants.ZWSP);
}
diff --git a/app/src/protyle/toolbar/builtinColorDialog.ts b/app/src/protyle/toolbar/builtinColorDialog.ts
new file mode 100644
index 0000000000..cf8f9277be
--- /dev/null
+++ b/app/src/protyle/toolbar/builtinColorDialog.ts
@@ -0,0 +1,325 @@
+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,
+ getBuiltinInlineColor,
+ getBuiltinInlineStyle,
+ getBuiltinInlineStylePropertyValue,
+ getCurrentInlineStyleMode,
+ getInlineStylesCache,
+ IBuiltinInlineColor,
+ IBuiltinInlineStyle,
+ IInlineStyleColors,
+ IInlineStyles,
+ saveInlineStyles,
+ TBuiltinColorType,
+ TBuiltinInlineStyleID,
+ TInlineStyleProperty,
+} from "./inlineStyle";
+
+interface IBuiltinColorDialogEntry {
+ key: number | TBuiltinInlineStyleID;
+ label: string;
+ value?: IBuiltinInlineColor | IBuiltinInlineStyle;
+}
+
+interface IBuiltinColorDialogEditor {
+ entry: IBuiltinColorDialogEntry;
+ element: HTMLElement;
+ editor: ReturnType<typeof bindThemeColorEditor>;
+ fallback: { light: IInlineStyleColors, dark: IInlineStyleColors };
+ overrideElements: Map<TInlineStyleProperty, HTMLInputElement>;
+ showElement: HTMLInputElement;
+}
+
+const cloneInlineStyles = (data = getInlineStylesCache()): IInlineStyles =>
+ JSON.parse(JSON.stringify(data)) as IInlineStyles;
+
+const getTypeLabel = (type: TBuiltinColorType) => {
+ if (type === "color") {
+ return window.siyuan.languages.colorFont;
+ }
+ if (type === "backgroundColor") {
+ return window.siyuan.languages.colorPrimary;
+ }
+ return window.siyuan.languages.color;
+};
+
+const getProperties = (type: TBuiltinColorType): TInlineStyleProperty[] => {
+ if (type === "color") {
+ return ["color"];
+ }
+ if (type === "backgroundColor") {
+ return ["backgroundColor"];
+ }
+ return ["color", "backgroundColor"];
+};
+
+const getEntryLabel = (type: TBuiltinColorType, key: number | TBuiltinInlineStyleID) => {
+ if (type === "style1") {
+ return window.siyuan.languages[`${key}Style`];
+ }
+ return `${getTypeLabel(type)} ${key}`;
+};
+
+const colorToHex = (value: string, fallback: string) => {
+ const normalized = value.trim();
+ if (/^#[0-9a-f]{6}$/i.test(normalized)) {
+ return normalized.toLowerCase();
+ }
+ const match = normalized.match(/^rgba?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)/i);
+ if (!match) {
+ return fallback;
+ }
+ return `#${match.slice(1, 4).map(item => Math.max(0, Math.min(255, Math.round(Number(item))))
+ .toString(16).padStart(2, "0")).join("")}`;
+};
+
+const resolveThemeColor = (value: string, fallback: string) => {
+ const siyuanStyle = document.getElementById("siyuanStyle") as HTMLStyleElement;
+ const disabled = siyuanStyle?.disabled;
+ if (siyuanStyle) {
+ siyuanStyle.disabled = true;
+ }
+ const element = document.createElement("span");
+ element.style.color = value;
+ element.style.position = "fixed";
+ element.style.visibility = "hidden";
+ 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);
+ return {
+ light: {
+ color: resolveThemeColor(getValue("color"), "#000000"),
+ backgroundColor: resolveThemeColor(getValue("backgroundColor"), "#ffffff"),
+ },
+ dark: {
+ color: resolveThemeColor(getValue("color"), "#ffffff"),
+ backgroundColor: resolveThemeColor(getValue("backgroundColor"), "#000000"),
+ },
+ };
+};
+
+const getEditorType = (type: TBuiltinColorType) => type === "av" ? "style1" : type;
+
+const hasOverride = (entry: IBuiltinColorDialogEntry, property: TInlineStyleProperty) =>
+ !!entry.value?.light[property] && !!entry.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>`;
+};
+
+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);
+ });
+};
+
+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";
+};
+
+const setProperty = (target: { light: IInlineStyleColors, dark: IInlineStyleColors },
+ source: { light: IInlineStyleColors, dark: IInlineStyleColors },
+ property: TInlineStyleProperty, enabled: boolean) => {
+ if (enabled) {
+ target.light[property] = source.light[property];
+ target.dark[property] = source.dark[property];
+ } else {
+ delete target.light[property];
+ delete target.dark[property];
+ }
+};
+
+const 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>`,
+ });
+ 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},
+ };
+ 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);
+ });
+ 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 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);
+ };
+
+ dialog.element.addEventListener("click", async event => {
+ const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");
+ if (!actionElement || actionElement.hasAttribute("disabled")) {
+ return;
+ }
+ 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");
+ }
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ });
+};
diff --git a/app/src/protyle/toolbar/inlineStyle.test.ts b/app/src/protyle/toolbar/inlineStyle.test.ts
index 97382442a6..bbaf73ff8e 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} from "./inlineStyle";
+import type {IInlineStyle, IInlineStyleBuiltin} from "./inlineStyle";
let inlineStyle: typeof import("./inlineStyle");
@@ -25,6 +25,17 @@ const combinedStyle: IInlineStyle = {
},
};
+const emptyBuiltin: IInlineStyleBuiltin = {
+ colors: [],
+ styles: [],
+ hidden: {
+ color: [],
+ backgroundColor: [],
+ style1: [],
+ av: [],
+ },
+};
+
describe("normalizeInlineStyles", () => {
it("keeps paired light and dark colors and removes invalid data", () => {
assert.deepEqual(inlineStyle.normalizeInlineStyles({
@@ -46,7 +57,8 @@ describe("normalizeInlineStyles", () => {
dark: {color: "#000000"},
}],
}), {
- version: 1,
+ version: 2,
+ builtin: emptyBuiltin,
styles: [combinedStyle, {
id: "20260821120001-bbcdefg",
name: "Background",
@@ -56,6 +68,64 @@ describe("normalizeInlineStyles", () => {
});
});
+ it("normalizes built-in overrides and hidden entries", () => {
+ assert.deepEqual(inlineStyle.normalizeInlineStyles({
+ version: 2,
+ builtin: {
+ colors: [{
+ index: 2,
+ light: {color: "#AABBCC", backgroundColor: "#123456"},
+ dark: {color: "#001122"},
+ }, {
+ index: 2,
+ light: {color: "#ffffff"},
+ dark: {color: "#000000"},
+ }, {
+ index: 14,
+ light: {color: "#ffffff"},
+ dark: {color: "#000000"},
+ }],
+ styles: [{
+ id: "warning",
+ light: {color: "#FEDCBA", backgroundColor: "#123456"},
+ dark: {color: "#ABCDEF", backgroundColor: "invalid"},
+ }, {
+ id: "unknown",
+ light: {color: "#ffffff"},
+ dark: {color: "#000000"},
+ }],
+ hidden: {
+ color: [3, 1, 3, 0, 14],
+ backgroundColor: [13],
+ style1: ["success", "unknown", "error", "success"],
+ av: [2, 13, 99],
+ },
+ },
+ styles: [],
+ }), {
+ version: 2,
+ builtin: {
+ colors: [{
+ index: 2,
+ light: {color: "#aabbcc"},
+ dark: {color: "#001122"},
+ }],
+ styles: [{
+ id: "warning",
+ light: {color: "#fedcba"},
+ dark: {color: "#abcdef"},
+ }],
+ hidden: {
+ color: [1, 3],
+ backgroundColor: [13],
+ style1: ["error", "success"],
+ av: [2, 13],
+ },
+ },
+ styles: [],
+ });
+ });
+
it("limits names by Unicode code points without splitting surrogate pairs", () => {
const normalized = inlineStyle.normalizeInlineStyles({
version: 1,
@@ -103,13 +173,55 @@ describe("inline style values", () => {
describe("getInlineStylesCSS", () => {
it("generates isolated light and dark variables", () => {
- assert.equal(inlineStyle.getInlineStylesCSS({version: 1, styles: [combinedStyle]}), `:root[data-theme-mode="light"] {
+ assert.equal(inlineStyle.getInlineStylesCSS({version: 2, builtin: emptyBuiltin,
+ styles: [combinedStyle]}), `:root[data-theme-mode="light"] {
--b3-inline-style-20260821120000-abcdefg-color: #112233;
--b3-inline-style-20260821120000-abcdefg-background-color: #ddeeff;
}
:root[data-theme-mode="dark"] {
--b3-inline-style-20260821120000-abcdefg-color: #fefefe;
--b3-inline-style-20260821120000-abcdefg-background-color: #223344;
+}`);
+ });
+
+ it("overrides numbered colors and scopes semantic compatibility variables to content", () => {
+ assert.equal(inlineStyle.getInlineStylesCSS({
+ version: 2,
+ builtin: {
+ colors: [{
+ index: 2,
+ light: {color: "#112233", backgroundColor: "#ddeeff"},
+ dark: {color: "#fefefe", backgroundColor: "#223344"},
+ }],
+ styles: [{
+ id: "error",
+ light: {color: "#330000", backgroundColor: "#ffeeee"},
+ dark: {color: "#ffdddd", backgroundColor: "#440000"},
+ }],
+ hidden: emptyBuiltin.hidden,
+ },
+ styles: [],
+ }), `:root[data-theme-mode="light"] {
+ --b3-font-color2: #112233;
+ --b3-font-background2: #ddeeff;
+ --b3-inline-builtin-error-color: #330000;
+ --b3-inline-builtin-error-background-color: #ffeeee;
+}
+:root[data-theme-mode="light"] .protyle-wysiwyg,
+:root[data-theme-mode="light"] .b3-typography {
+ --b3-card-error-color: var(--b3-inline-builtin-error-color);
+ --b3-card-error-background: var(--b3-inline-builtin-error-background-color);
+}
+:root[data-theme-mode="dark"] {
+ --b3-font-color2: #fefefe;
+ --b3-font-background2: #223344;
+ --b3-inline-builtin-error-color: #ffdddd;
+ --b3-inline-builtin-error-background-color: #440000;
+}
+:root[data-theme-mode="dark"] .protyle-wysiwyg,
+:root[data-theme-mode="dark"] .b3-typography {
+ --b3-card-error-color: var(--b3-inline-builtin-error-color);
+ --b3-card-error-background: var(--b3-inline-builtin-error-background-color);
}`);
});
});
@@ -123,4 +235,51 @@ describe("recent inline styles", () => {
assert.equal(inlineStyle.getInlineStyleIDFromValue(first), combinedStyle.id);
assert.equal(inlineStyle.getRecentInlineStyleKey(first), inlineStyle.getRecentInlineStyleKey(second));
});
+
+ it("filters hidden built-in colors without removing defaults or custom styles", () => {
+ const data = inlineStyle.normalizeInlineStyles({
+ builtin: {
+ hidden: {
+ color: [3],
+ backgroundColor: [4],
+ style1: ["error"],
+ av: [5],
+ },
+ },
+ styles: [combinedStyle],
+ });
+ const custom = "color\u200bvar(--b3-inline-style-20260821120000-abcdefg-color, #112233)";
+ const values = [
+ "color\u200bvar(--b3-font-color3)",
+ "color\u200bvar(--b3-font-color2)",
+ "backgroundColor\u200bvar(--b3-font-background4)",
+ "style1\u200bvar(--b3-card-error-background)\u200bvar(--b3-card-error-color)",
+ "style1\u200bvar(--b3-inline-builtin-warning-background-color, var(--b3-card-warning-background))" +
+ "\u200bvar(--b3-inline-builtin-warning-color, var(--b3-card-warning-color))",
+ "color\u200b",
+ custom,
+ ];
+ assert.deepEqual(inlineStyle.filterHiddenRecentInlineStyles(values, data), [
+ values[1],
+ values[4],
+ values[5],
+ custom,
+ ]);
+ assert.deepEqual(inlineStyle.getVisibleBuiltinColorIndexes("av", data),
+ [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13]);
+ });
+});
+
+describe("built-in semantic styles", () => {
+ it("uses dedicated variables with legacy fallbacks", () => {
+ assert.deepEqual(inlineStyle.getBuiltinInlineStyleApplication("info"), {
+ type: "style1",
+ color: "var(--b3-inline-builtin-info-background-color, var(--b3-card-info-background))" +
+ "\u200bvar(--b3-inline-builtin-info-color, var(--b3-card-info-color))",
+ });
+ assert.deepEqual(inlineStyle.getBuiltinInlineStylePreview("success"), {
+ color: "var(--b3-inline-builtin-success-color, var(--b3-card-success-color))",
+ backgroundColor: "var(--b3-inline-builtin-success-background-color, var(--b3-card-success-background))",
+ });
+ });
});
diff --git a/app/src/protyle/toolbar/inlineStyle.ts b/app/src/protyle/toolbar/inlineStyle.ts
index 520d6e9e7f..7058c25607 100644
--- a/app/src/protyle/toolbar/inlineStyle.ts
+++ b/app/src/protyle/toolbar/inlineStyle.ts
@@ -1,4 +1,5 @@
export type TInlineStyleType = "color" | "backgroundColor" | "style1";
+export type TBuiltinColorType = TInlineStyleType | "av";
export type TInlineStyleMode = "light" | "dark";
export type TInlineStyleProperty = "color" | "backgroundColor";
@@ -14,8 +15,39 @@ export interface IInlineStyle {
dark: IInlineStyleColors;
}
+export const BUILTIN_INLINE_COLOR_COUNT = 13;
+export const BUILTIN_INLINE_STYLE_IDS = ["error", "warning", "info", "success"] as const;
+
+export type TBuiltinInlineStyleID = typeof BUILTIN_INLINE_STYLE_IDS[number];
+
+export interface IBuiltinInlineColor {
+ index: number;
+ light: IInlineStyleColors;
+ dark: IInlineStyleColors;
+}
+
+export interface IBuiltinInlineStyle {
+ id: TBuiltinInlineStyleID;
+ light: IInlineStyleColors;
+ dark: IInlineStyleColors;
+}
+
+export interface IBuiltinInlineStyleHidden {
+ color: number[];
+ backgroundColor: number[];
+ style1: TBuiltinInlineStyleID[];
+ av: number[];
+}
+
+export interface IInlineStyleBuiltin {
+ colors: IBuiltinInlineColor[];
+ styles: IBuiltinInlineStyle[];
+ hidden: IBuiltinInlineStyleHidden;
+}
+
export interface IInlineStyles {
- version: 1;
+ version: 2;
+ builtin: IInlineStyleBuiltin;
styles: IInlineStyle[];
}
@@ -25,7 +57,17 @@ export interface IInlineStyleApplication {
}
export const INLINE_STYLE_EMPTY: IInlineStyles = {
- version: 1,
+ version: 2,
+ builtin: {
+ colors: [],
+ styles: [],
+ hidden: {
+ color: [],
+ backgroundColor: [],
+ style1: [],
+ av: [],
+ },
+ },
styles: [],
};
@@ -34,18 +76,20 @@ export const MAX_INLINE_STYLE_NAME_LENGTH = 64;
export const INLINE_FONT_COLORS = [
"",
- ...Array.from({length: 13}, (_, index) => `var(--b3-font-color${index + 1})`),
+ ...Array.from({length: BUILTIN_INLINE_COLOR_COUNT}, (_, index) => `var(--b3-font-color${index + 1})`),
];
export const INLINE_BACKGROUND_COLORS = [
"",
- ...Array.from({length: 13}, (_, index) => `var(--b3-font-background${index + 1})`),
+ ...Array.from({length: BUILTIN_INLINE_COLOR_COUNT}, (_, index) => `var(--b3-font-background${index + 1})`),
];
const INLINE_STYLE_ID_PATTERN = /^[0-9]{14}-[a-z0-9]{7}$/;
const INLINE_STYLE_COLOR_PATTERN = /^#[0-9A-Fa-f]{6}$/;
const INLINE_STYLE_VARIABLE_PATTERN = /var\(--b3-inline-style-([A-Za-z0-9_-]+?)-(?:background-color|color)(?:\s*,|\))/;
const INLINE_STYLE_SEPARATOR = "\u200b";
+const BUILTIN_FONT_COLOR_VARIABLE_PATTERN = /^var\(--b3-font-color(\d+)\)$/;
+const BUILTIN_BACKGROUND_COLOR_VARIABLE_PATTERN = /^var\(--b3-font-background(\d+)\)$/;
let inlineStylesCache: IInlineStyles | undefined;
let inlineStylesLoadPromise: Promise<IInlineStyles> | undefined;
@@ -94,6 +138,110 @@ const normalizeStyle = (value: unknown): IInlineStyle | undefined => {
};
};
+const normalizePairedColors = (value: unknown) => {
+ if (!value || typeof value !== "object") {
+ return;
+ }
+ const colors = value as { light?: IInlineStyleColors, dark?: IInlineStyleColors };
+ const lightColor = normalizeColor(colors.light?.color);
+ const darkColor = normalizeColor(colors.dark?.color);
+ const lightBackground = normalizeColor(colors.light?.backgroundColor);
+ const darkBackground = normalizeColor(colors.dark?.backgroundColor);
+ const result: { light: IInlineStyleColors, dark: IInlineStyleColors } = {
+ light: {},
+ dark: {},
+ };
+ if (lightColor && darkColor) {
+ result.light.color = lightColor;
+ result.dark.color = darkColor;
+ }
+ if (lightBackground && darkBackground) {
+ result.light.backgroundColor = lightBackground;
+ result.dark.backgroundColor = darkBackground;
+ }
+ if (!result.light.color && !result.light.backgroundColor) {
+ return;
+ }
+ return result;
+};
+
+const normalizeBuiltinColors = (value: unknown) => {
+ const colors: IBuiltinInlineColor[] = [];
+ const indexes = new Set<number>();
+ if (!Array.isArray(value)) {
+ return colors;
+ }
+ value.forEach(item => {
+ if (!item || typeof item !== "object") {
+ return;
+ }
+ const index = Number((item as Partial<IBuiltinInlineColor>).index);
+ const pairedColors = normalizePairedColors(item);
+ if (!Number.isInteger(index) || index < 1 || index > BUILTIN_INLINE_COLOR_COUNT ||
+ indexes.has(index) || !pairedColors) {
+ return;
+ }
+ indexes.add(index);
+ colors.push({index, ...pairedColors});
+ });
+ return colors.sort((a, b) => a.index - b.index);
+};
+
+const normalizeBuiltinStyles = (value: unknown) => {
+ const styles: IBuiltinInlineStyle[] = [];
+ const ids = new Set<TBuiltinInlineStyleID>();
+ if (!Array.isArray(value)) {
+ return styles;
+ }
+ value.forEach(item => {
+ if (!item || typeof item !== "object") {
+ return;
+ }
+ const id = (item as Partial<IBuiltinInlineStyle>).id;
+ const pairedColors = normalizePairedColors(item);
+ if (!BUILTIN_INLINE_STYLE_IDS.includes(id as TBuiltinInlineStyleID) ||
+ ids.has(id as TBuiltinInlineStyleID) || !pairedColors) {
+ return;
+ }
+ ids.add(id as TBuiltinInlineStyleID);
+ styles.push({id: id as TBuiltinInlineStyleID, ...pairedColors});
+ });
+ return styles.sort((a, b) => BUILTIN_INLINE_STYLE_IDS.indexOf(a.id) - BUILTIN_INLINE_STYLE_IDS.indexOf(b.id));
+};
+
+const normalizeHiddenIndexes = (value: unknown) => {
+ 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);
+};
+
+const normalizeHiddenStyleIDs = (value: unknown) => {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+ const ids = new Set(value.filter(item => BUILTIN_INLINE_STYLE_IDS.includes(item as TBuiltinInlineStyleID)) as
+ TBuiltinInlineStyleID[]);
+ return BUILTIN_INLINE_STYLE_IDS.filter(id => ids.has(id));
+};
+
+const normalizeBuiltin = (value: unknown): IInlineStyleBuiltin => {
+ const builtin = value && typeof value === "object" ? value as Partial<IInlineStyleBuiltin> : {};
+ const hidden = builtin.hidden && typeof builtin.hidden === "object" ?
+ builtin.hidden as Partial<IBuiltinInlineStyleHidden> : {};
+ return {
+ colors: normalizeBuiltinColors(builtin.colors),
+ styles: normalizeBuiltinStyles(builtin.styles),
+ hidden: {
+ color: normalizeHiddenIndexes(hidden.color),
+ backgroundColor: normalizeHiddenIndexes(hidden.backgroundColor),
+ style1: normalizeHiddenStyleIDs(hidden.style1),
+ av: normalizeHiddenIndexes(hidden.av),
+ },
+ };
+};
+
export const normalizeInlineStyles = (value: unknown): IInlineStyles => {
const styles: IInlineStyle[] = [];
const ids = new Set<string>();
@@ -110,7 +258,9 @@ export const normalizeInlineStyles = (value: unknown): IInlineStyles => {
});
}
return {
- version: 1,
+ version: 2,
+ builtin: normalizeBuiltin(value && typeof value === "object" ?
+ (value as Partial<IInlineStyles>).builtin : undefined),
styles,
};
};
@@ -249,6 +399,85 @@ export const getInlineStyleByID = (id?: string, data = getInlineStylesCache()) =
export const getInlineStyleByValue = (value?: string, data = getInlineStylesCache()) =>
getInlineStyleByID(getInlineStyleIDFromValue(value), data);
+export const getBuiltinInlineColor = (index: number, data = getInlineStylesCache()) =>
+ data.builtin.colors.find(item => item.index === index);
+
+export const getBuiltinInlineStyle = (id: TBuiltinInlineStyleID, data = getInlineStylesCache()) =>
+ data.builtin.styles.find(item => item.id === id);
+
+export const getBuiltinColorVariableName = (index: number, property: TInlineStyleProperty) =>
+ `--b3-font-${property === "color" ? "color" : "background"}${index}`;
+
+export const getBuiltinColorPropertyValue = (index: number, property: TInlineStyleProperty) =>
+ `var(${getBuiltinColorVariableName(index, property)})`;
+
+export const getBuiltinInlineStyleVariableName = (id: TBuiltinInlineStyleID, property: TInlineStyleProperty) =>
+ `--b3-inline-builtin-${id}-${property === "color" ? "color" : "background-color"}`;
+
+export const getBuiltinInlineStyleLegacyVariableName = (id: TBuiltinInlineStyleID,
+ property: TInlineStyleProperty) =>
+ `--b3-card-${id}-${property === "color" ? "color" : "background"}`;
+
+export const getBuiltinInlineStylePropertyValue = (id: TBuiltinInlineStyleID,
+ property: TInlineStyleProperty) =>
+ `var(${getBuiltinInlineStyleVariableName(id, property)}, ` +
+ `var(${getBuiltinInlineStyleLegacyVariableName(id, property)}))`;
+
+export const getBuiltinInlineStylePreview = (id: TBuiltinInlineStyleID) => ({
+ color: getBuiltinInlineStylePropertyValue(id, "color"),
+ backgroundColor: getBuiltinInlineStylePropertyValue(id, "backgroundColor"),
+});
+
+export const getBuiltinInlineStyleApplication = (id: TBuiltinInlineStyleID): IInlineStyleApplication => ({
+ type: "style1",
+ color: encodeStyle1(getBuiltinInlineStylePropertyValue(id, "backgroundColor"),
+ getBuiltinInlineStylePropertyValue(id, "color")),
+});
+
+export const isBuiltinInlineStyleVisible = (type: TBuiltinColorType, value: number | TBuiltinInlineStyleID,
+ data = getInlineStylesCache()) => {
+ if (type === "style1") {
+ return !BUILTIN_INLINE_STYLE_IDS.includes(value as TBuiltinInlineStyleID) ||
+ !data.builtin.hidden.style1.includes(value as TBuiltinInlineStyleID);
+ }
+ const index = Number(value);
+ return !Number.isInteger(index) || index < 1 || index > BUILTIN_INLINE_COLOR_COUNT ||
+ !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)
+ .filter(index => isBuiltinInlineStyleVisible(type, index, data));
+
+export const getVisibleBuiltinInlineStyleIDs = (data = getInlineStylesCache()) =>
+ BUILTIN_INLINE_STYLE_IDS.filter(id => isBuiltinInlineStyleVisible("style1", id, data));
+
+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;
+};
+
+export const isRecentInlineStyleVisible = (value: string, data = getInlineStylesCache()) => {
+ const [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") {
+ const index = Number(propertyValue?.match(BUILTIN_BACKGROUND_COLOR_VARIABLE_PATTERN)?.[1]);
+ return !index || isBuiltinInlineStyleVisible("backgroundColor", index, data);
+ }
+ if (type === "style1") {
+ const id = getBuiltinInlineStyleIDFromValue(value);
+ return !id || isBuiltinInlineStyleVisible("style1", id, data);
+ }
+ return true;
+};
+
+export const filterHiddenRecentInlineStyles = (values: string[], data = getInlineStylesCache()) =>
+ values.filter(value => isRecentInlineStyleVisible(value, data));
+
export const getRecentInlineStyleKey = (value: string) => {
const id = getInlineStyleIDFromValue(value);
if (!id) {
@@ -261,6 +490,29 @@ export const getInlineStylesCSS = (data = getInlineStylesCache()) => {
const normalized = normalizeInlineStyles(data);
return (["light", "dark"] as TInlineStyleMode[]).map(mode => {
const declarations: string[] = [];
+ const contentDeclarations: string[] = [];
+ normalized.builtin.colors.forEach(color => {
+ if (color[mode].color) {
+ declarations.push(` ${getBuiltinColorVariableName(color.index, "color")}: ${color[mode].color};`);
+ }
+ if (color[mode].backgroundColor) {
+ 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};`);
+ contentDeclarations.push(` ${getBuiltinInlineStyleLegacyVariableName(style.id, "color")}: ` +
+ `var(${getBuiltinInlineStyleVariableName(style.id, "color")});`);
+ }
+ if (style[mode].backgroundColor) {
+ declarations.push(` ${getBuiltinInlineStyleVariableName(style.id, "backgroundColor")}: ` +
+ `${style[mode].backgroundColor};`);
+ contentDeclarations.push(` ${getBuiltinInlineStyleLegacyVariableName(style.id, "backgroundColor")}: ` +
+ `var(${getBuiltinInlineStyleVariableName(style.id, "backgroundColor")});`);
+ }
+ });
normalized.styles.forEach(style => {
if (style[mode].color) {
declarations.push(` ${getInlineStyleVariableName(style.id, "color")}: ${style[mode].color};`);
@@ -269,9 +521,14 @@ export const getInlineStylesCSS = (data = getInlineStylesCache()) => {
declarations.push(` ${getInlineStyleVariableName(style.id, "backgroundColor")}: ${style[mode].backgroundColor};`);
}
});
- if (declarations.length === 0) {
- return "";
+ const blocks: string[] = [];
+ if (declarations.length > 0) {
+ blocks.push(`:root[data-theme-mode="${mode}"] {\n${declarations.join("\n")}\n}`);
+ }
+ if (contentDeclarations.length > 0) {
+ blocks.push(`:root[data-theme-mode="${mode}"] .protyle-wysiwyg,\n` +
+ `:root[data-theme-mode="${mode}"] .b3-typography {\n${contentDeclarations.join("\n")}\n}`);
}
- return `:root[data-theme-mode="${mode}"] {\n${declarations.join("\n")}\n}`;
+ return blocks.join("\n");
}).filter(Boolean).join("\n");
};
diff --git a/app/src/protyle/toolbar/inlineStyleDialog.ts b/app/src/protyle/toolbar/inlineStyleDialog.ts
index aa5f036f05..8276f92fe9 100644
--- a/app/src/protyle/toolbar/inlineStyleDialog.ts
+++ b/app/src/protyle/toolbar/inlineStyleDialog.ts
@@ -16,6 +16,7 @@ import {
saveInlineStyles,
TInlineStyleType,
} from "./inlineStyle";
+import {openBuiltinColorDialog} from "./builtinColorDialog";
const escapeAttribute = (value: string) => escapeAttr(value);
@@ -52,9 +53,15 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun
content: `<div class="b3-dialog__content" style="max-height:70vh;overflow:auto">
<div data-panel="list">
<div data-type="inlineStyleList" class="b3-list b3-list--background fn__selectnone" style="--file-toggle-width:0px"></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>
+ </div>
</div>
<div data-panel="editor" class="fn__none">
<label class="b3-label b3-label--inner fn__flex" style="align-items:center">
@@ -83,6 +90,7 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun
const editorPanel = dialog.element.querySelector('[data-panel="editor"]') 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 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;
@@ -102,7 +110,7 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun
<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("");
newElement.disabled = draft.styles.length >= MAX_INLINE_STYLES;
- newElement.style.marginTop = draft.styles.length === 0 ? "0" : "8px";
+ buttonsElement.style.marginTop = draft.styles.length === 0 ? "0" : "8px";
};
const setEditorActionMode = (editing: boolean) => {
@@ -240,6 +248,8 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun
return;
}
showEditor();
+ } else if (action === "manageBuiltin") {
+ openBuiltinColorDialog(initialType, onChange);
} else if (action === "edit") {
showEditor(index);
} else if (action === "delete") {
@@ -268,7 +278,10 @@ export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroun
saving = true;
actionElement.setAttribute("disabled", "disabled");
try {
- const response = await saveInlineStyles(draft);
+ const response = await saveInlineStyles({
+ ...draft,
+ builtin: cloneInlineStyles().builtin,
+ });
if (response?.code !== 0) {
showMessage(response?.msg || window.siyuan.languages.invalid, 6000, "error");
saving = false;
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
index 2f010a7880..d5d928f1ec 100644
--- a/app/src/protyle/util/tableControl.ts
+++ b/app/src/protyle/util/tableControl.ts
@@ -29,6 +29,7 @@ import {
isDefaultTableColumnWidth,
TABLE_DEFAULT_COLUMN_WIDTH,
} from "./tableColumnWidth";
+import {getVisibleBuiltinColorIndexes} from "../toolbar/inlineStyle";
type TableSelectionMode = "row" | "column" | "cell";
type TableAddControlType = "add-row" | "add-column" | "add-both";
@@ -192,7 +193,8 @@ export const setTableCellStyle = (protyle: IProtyle, node: HTMLElement, cells: H
export const getTableCellBackgroundMenus = (cells: HTMLTableCellElement[],
onChange: (color: string) => void): IMenu[] => {
const backgroundColor = getCommonTableCellStyle(cells, "background-color");
- const colors = ["", ...Array.from({length: 13}, (_, index) => `var(--b3-font-background${index + 1})`)];
+ const colors = ["", ...getVisibleBuiltinColorIndexes("backgroundColor")
+ .map(index => `var(--b3-font-background${index})`)];
const colorHTML = colors.map(color => {
const currentClass = backgroundColor === color ? " color__square--current" : "";
const defaultClass = color ? "" : " ariaLabel";
diff --git a/kernel/api/inline_style.go b/kernel/api/inline_style.go
index d6dba7c757..b673aec9a4 100644
--- a/kernel/api/inline_style.go
+++ b/kernel/api/inline_style.go
@@ -56,26 +56,32 @@ func setInlineStyles(c *gin.Context) {
) {
return
}
- if version != model.InlineStylesVersion {
+ if version != 1 && version != model.InlineStylesVersion {
ret.Code = -1
ret.Msg = "unsupported inline styles version"
return
}
- data, err := gulu.JSON.MarshalJSON(stylesArg)
- if err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ var saved *model.InlineStyles
+ var changed bool
+ var err error
+ if version == 1 {
+ var data []byte
+ if data, err = gulu.JSON.MarshalJSON(stylesArg); err == nil {
+ styles := []*model.InlineStyle{}
+ if err = gulu.JSON.UnmarshalJSON(data, &styles); err == nil {
+ saved, changed, err = model.SetInlineStyles(styles)
+ }
+ }
+ } else {
+ var data []byte
+ if data, err = gulu.JSON.MarshalJSON(arg); err == nil {
+ styles := &model.InlineStyles{}
+ if err = gulu.JSON.UnmarshalJSON(data, styles); err == nil {
+ saved, changed, err = model.SetInlineStylesData(styles)
+ }
+ }
}
- styles := []*model.InlineStyle{}
- if err = gulu.JSON.UnmarshalJSON(data, &styles); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
- }
-
- saved, changed, err := model.SetInlineStyles(styles)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/api/inline_style_test.go b/kernel/api/inline_style_test.go
index b24e340e53..2d7f123c9b 100644
--- a/kernel/api/inline_style_test.go
+++ b/kernel/api/inline_style_test.go
@@ -47,17 +47,32 @@ func TestInlineStylesAPI(t *testing.T) {
t.Fatal(err)
}
if getResponse.Code != 0 || getResponse.Data == nil || getResponse.Data.Version != model.InlineStylesVersion ||
- getResponse.Data.Styles == nil || len(getResponse.Data.Styles) != 0 {
+ getResponse.Data.Styles == nil || len(getResponse.Data.Styles) != 0 || getResponse.Data.Builtin == nil ||
+ getResponse.Data.Builtin.Hidden == nil {
t.Fatalf("unexpected initial inline styles response: %s", getRecorder.Body.String())
}
setRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{
- "version":1,
+ "version":2,
+ "app":"test-app",
"styles":[{
"name":" Accent ",
"light":{"color":"#AABBCC"},
"dark":{"color":"#112233"}
- }]
+ }],
+ "builtin":{
+ "colors":[{
+ "index":2,
+ "light":{"backgroundColor":"#DDEEFF"},
+ "dark":{"backgroundColor":"#445566"}
+ }],
+ "styles":[{
+ "id":"error",
+ "light":{"color":"#AABBCC","backgroundColor":"#DDEEFF"},
+ "dark":{"color":"#112233","backgroundColor":"#445566"}
+ }],
+ "hidden":{"color":[3],"backgroundColor":[4],"style1":["error"],"av":[5]}
+ }
}`)
setResponse := &struct {
Code int `json:"code"`
@@ -68,11 +83,36 @@ func TestInlineStylesAPI(t *testing.T) {
}
if setResponse.Code != 0 || setResponse.Data == nil || len(setResponse.Data.Styles) != 1 ||
setResponse.Data.Styles[0].ID == "" || setResponse.Data.Styles[0].Name != "Accent" ||
- setResponse.Data.Styles[0].Light.Color != "#aabbcc" {
+ setResponse.Data.Styles[0].Light.Color != "#aabbcc" || len(setResponse.Data.Builtin.Colors) != 1 ||
+ setResponse.Data.Builtin.Colors[0].Index != 2 || len(setResponse.Data.Builtin.Styles) != 1 ||
+ len(setResponse.Data.Builtin.Hidden.AV) != 1 {
t.Fatalf("unexpected set inline styles response: %s", setRecorder.Body.String())
}
- futureRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{"version":2,"styles":[]}`)
+ legacyRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{
+ "version":1,
+ "styles":[{
+ "name":"Legacy client",
+ "light":{"color":"#abcdef"},
+ "dark":{"color":"#123456"}
+ }],
+ "builtin":{}
+ }`)
+ legacyResponse := &struct {
+ Code int `json:"code"`
+ Data *model.InlineStyles `json:"data"`
+ }{}
+ if err := json.Unmarshal(legacyRecorder.Body.Bytes(), legacyResponse); err != nil {
+ t.Fatal(err)
+ }
+ if legacyResponse.Code != 0 || legacyResponse.Data == nil || legacyResponse.Data.Version != model.InlineStylesVersion ||
+ len(legacyResponse.Data.Styles) != 1 || legacyResponse.Data.Styles[0].Name != "Legacy client" ||
+ len(legacyResponse.Data.Builtin.Colors) != 1 || len(legacyResponse.Data.Builtin.Styles) != 1 ||
+ len(legacyResponse.Data.Builtin.Hidden.AV) != 1 {
+ t.Fatalf("version 1 update did not preserve builtin colors: %s", legacyRecorder.Body.String())
+ }
+
+ futureRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{"version":3,"styles":[]}`)
if responseCode(t, futureRecorder) != -1 || !strings.Contains(futureRecorder.Body.String(), "unsupported") {
t.Fatalf("future inline styles version was accepted: %s", futureRecorder.Body.String())
}
@@ -80,10 +120,17 @@ func TestInlineStylesAPI(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if len(styles.Styles) != 1 || styles.Styles[0].ID != setResponse.Data.Styles[0].ID {
+ if len(styles.Styles) != 1 || styles.Styles[0].ID != legacyResponse.Data.Styles[0].ID ||
+ len(styles.Builtin.Colors) != 1 {
t.Fatalf("future request overwrote inline styles: %#v", styles)
}
+ invalidBuiltinRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles",
+ `{"version":2,"styles":[],"builtin":{"hidden":{"av":[14]}}}`)
+ if responseCode(t, invalidBuiltinRecorder) != -1 {
+ t.Fatalf("invalid builtin inline styles were accepted: %s", invalidBuiltinRecorder.Body.String())
+ }
+
missingVersionRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{"styles":[]}`)
if responseCode(t, missingVersionRecorder) != -1 || !strings.Contains(missingVersionRecorder.Body.String(), "version") {
t.Fatalf("missing inline styles version was accepted: %s", missingVersionRecorder.Body.String())
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index e26a3eda6e..ff38f4d1c9 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -7707,9 +7707,10 @@ func updateAttributeViewValue(tx *Transaction, attrView *av.AttributeView, keyID
}
type attrViewValueUpdateContext struct {
- keyValues map[string]*av.KeyValues
- blockValues map[string]*av.Value
- values map[string]map[string]*av.Value
+ keyValues map[string]*av.KeyValues
+ blockValues map[string]*av.Value
+ values map[string]map[string]*av.Value
+ availableAVColors []int
}
func newAttrViewValueUpdateContext(attrView *av.AttributeView) *attrViewValueUpdateContext {
@@ -7854,12 +7855,23 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyI
}
// The selection options are inconsistent after pasting data into the database https://github.com/siyuan-note/siyuan/issues/11409
+ var availableColors []int
for _, valOpt := range val.MSelect {
if opt := key.GetOption(valOpt.Content); nil == opt {
// 不存在的选项新建保存
color := attrView.FilterColorValue(valOpt.Color)
if "" == color {
- color = fmt.Sprintf("%d", 1+rand.Intn(14))
+ if nil == availableColors {
+ if nil != context {
+ if nil == context.availableAVColors {
+ context.availableAVColors = getVisibleAVBuiltinColorIndexes()
+ }
+ availableColors = context.availableAVColors
+ } else {
+ availableColors = getVisibleAVBuiltinColorIndexes()
+ }
+ }
+ color = fmt.Sprintf("%d", availableColors[rand.Intn(len(availableColors))])
}
opt = &av.SelectOption{Name: valOpt.Content, Color: color}
key.Options = append(key.Options, opt)
diff --git a/kernel/model/inline_style.go b/kernel/model/inline_style.go
index 84d991ecd7..99c8d73bcd 100644
--- a/kernel/model/inline_style.go
+++ b/kernel/model/inline_style.go
@@ -23,6 +23,7 @@ import (
"os"
"path/filepath"
"regexp"
+ "sort"
"strings"
"sync"
"unicode/utf8"
@@ -34,16 +35,25 @@ import (
)
const (
- InlineStylesVersion = 1
+ InlineStylesVersion = 2
maxInlineStyles = 64
maxInlineStyleNameRunes = 64
maxInlineStylesFileSize = 1024 * 1024
inlineStylesRepoPath = "/storage/inline-styles.json"
+ minBuiltinColorIndex = 1
+ maxBuiltinColorIndex = 13
+ neutralAVColorIndex = 14
)
var (
inlineStylesLock sync.Mutex
inlineStyleColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)
+ builtinStyleOrder = map[string]int{
+ "error": 0,
+ "warning": 1,
+ "info": 2,
+ "success": 3,
+ }
)
type InlineStyleTheme struct {
@@ -58,9 +68,35 @@ type InlineStyle struct {
Dark *InlineStyleTheme `json:"dark"`
}
+type InlineStyleBuiltinColor struct {
+ Index int `json:"index"`
+ Light *InlineStyleTheme `json:"light"`
+ Dark *InlineStyleTheme `json:"dark"`
+}
+
+type InlineStyleBuiltinStyle struct {
+ ID string `json:"id"`
+ Light *InlineStyleTheme `json:"light"`
+ Dark *InlineStyleTheme `json:"dark"`
+}
+
+type InlineStyleBuiltinHidden struct {
+ Color []int `json:"color"`
+ BackgroundColor []int `json:"backgroundColor"`
+ Style1 []string `json:"style1"`
+ AV []int `json:"av"`
+}
+
+type InlineStyleBuiltin struct {
+ Colors []*InlineStyleBuiltinColor `json:"colors"`
+ Styles []*InlineStyleBuiltinStyle `json:"styles"`
+ Hidden *InlineStyleBuiltinHidden `json:"hidden"`
+}
+
type InlineStyles struct {
- Version int `json:"version"`
- Styles []*InlineStyle `json:"styles"`
+ Version int `json:"version"`
+ Styles []*InlineStyle `json:"styles"`
+ Builtin *InlineStyleBuiltin `json:"builtin"`
}
func GetInlineStyles() (ret *InlineStyles, err error) {
@@ -75,16 +111,43 @@ func SetInlineStyles(styles []*InlineStyle) (ret *InlineStyles, changed bool, er
inlineStylesLock.Lock()
defer inlineStylesLock.Unlock()
- dataPath := inlineStylesPath()
+ current, err := loadInlineStyles()
+ if err != nil {
+ return nil, false, err
+ }
+ current.Styles = styles
+ return setInlineStylesData(current)
+}
+
+// SetInlineStylesData 全量保存行级样式和内置颜色配置。
+func SetInlineStylesData(styles *InlineStyles) (ret *InlineStyles, changed bool, err error) {
+ waitForSyncingStorages()
+ inlineStylesLock.Lock()
+ defer inlineStylesLock.Unlock()
+
if _, err = loadInlineStyles(); err != nil {
return nil, false, err
}
+ return setInlineStylesData(styles)
+}
+
+func setInlineStylesData(styles *InlineStyles) (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)
+ }
- normalized, err := normalizeInlineStyles(styles, true)
+ normalizedStyles, err := normalizeInlineStyles(styles.Styles, true)
+ if err != nil {
+ return nil, false, err
+ }
+ normalizedBuiltin, err := normalizeInlineStyleBuiltin(styles.Builtin)
if err != nil {
return nil, false, err
}
- ret = &InlineStyles{Version: InlineStylesVersion, Styles: normalized}
+ ret = &InlineStyles{Version: InlineStylesVersion, Styles: normalizedStyles, Builtin: normalizedBuiltin}
data, err := gulu.JSON.MarshalIndentJSON(ret, "", " ")
if err != nil {
return nil, false, fmt.Errorf("marshal inline styles failed: %w", err)
@@ -93,6 +156,7 @@ func SetInlineStyles(styles []*InlineStyle) (ret *InlineStyles, changed bool, er
return nil, false, fmt.Errorf("inline styles file exceeds the %d byte limit", maxInlineStylesFileSize)
}
+ dataPath := inlineStylesPath()
oldData, readErr := filelock.ReadFile(dataPath)
if readErr != nil && !os.IsNotExist(readErr) {
return nil, false, fmt.Errorf("read inline styles failed: %w", readErr)
@@ -120,7 +184,7 @@ func isInlineStylesRepoPath(filePath string) bool {
}
func loadInlineStyles() (ret *InlineStyles, err error) {
- ret = &InlineStyles{Version: InlineStylesVersion, Styles: []*InlineStyle{}}
+ ret = newEmptyInlineStyles()
data, err := filelock.ReadFile(inlineStylesPath())
if os.IsNotExist(err) {
return ret, nil
@@ -134,16 +198,60 @@ func loadInlineStyles() (ret *InlineStyles, err error) {
if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil {
return nil, fmt.Errorf("unmarshal inline styles failed: %w", err)
}
- if ret.Version != InlineStylesVersion {
+ if ret.Version != 1 && ret.Version != InlineStylesVersion {
return nil, fmt.Errorf("unsupported inline styles version [%d]", ret.Version)
}
ret.Styles, err = normalizeInlineStyles(ret.Styles, false)
if err != nil {
return nil, fmt.Errorf("invalid inline styles data: %w", err)
}
+ ret.Builtin, err = normalizeInlineStyleBuiltin(ret.Builtin)
+ if err != nil {
+ return nil, fmt.Errorf("invalid inline styles data: %w", err)
+ }
+ ret.Version = InlineStylesVersion
return ret, nil
}
+func newEmptyInlineStyles() *InlineStyles {
+ return &InlineStyles{
+ Version: InlineStylesVersion,
+ Styles: []*InlineStyle{},
+ Builtin: newEmptyInlineStyleBuiltin(),
+ }
+}
+
+func newEmptyInlineStyleBuiltin() *InlineStyleBuiltin {
+ return &InlineStyleBuiltin{
+ Colors: []*InlineStyleBuiltinColor{},
+ Styles: []*InlineStyleBuiltinStyle{},
+ Hidden: &InlineStyleBuiltinHidden{
+ Color: []int{},
+ BackgroundColor: []int{},
+ Style1: []string{},
+ AV: []int{},
+ },
+ }
+}
+
+func getVisibleAVBuiltinColorIndexes() []int {
+ styles, err := GetInlineStyles()
+ if err != nil {
+ return []int{neutralAVColorIndex}
+ }
+ hidden := map[int]struct{}{}
+ for _, index := range styles.Builtin.Hidden.AV {
+ hidden[index] = struct{}{}
+ }
+ ret := make([]int, 0, maxBuiltinColorIndex+1)
+ for index := minBuiltinColorIndex; index <= maxBuiltinColorIndex; index++ {
+ if _, ok := hidden[index]; !ok {
+ ret = append(ret, index)
+ }
+ }
+ return append(ret, neutralAVColorIndex)
+}
+
func normalizeInlineStyles(styles []*InlineStyle, generateIDs bool) (ret []*InlineStyle, err error) {
if maxInlineStyles < len(styles) {
return nil, fmt.Errorf("inline styles count exceeds the %d item limit", maxInlineStyles)
@@ -205,6 +313,137 @@ func normalizeInlineStyles(styles []*InlineStyle, generateIDs bool) (ret []*Inli
return ret, nil
}
+func normalizeInlineStyleBuiltin(builtin *InlineStyleBuiltin) (ret *InlineStyleBuiltin, err error) {
+ ret = newEmptyInlineStyleBuiltin()
+ if builtin == nil {
+ return ret, nil
+ }
+
+ colorIndexes := make(map[int]struct{}, len(builtin.Colors))
+ for _, color := range builtin.Colors {
+ if color == nil {
+ return nil, errors.New("builtin color must not be null")
+ }
+ if color.Index < minBuiltinColorIndex || maxBuiltinColorIndex < color.Index {
+ return nil, fmt.Errorf("builtin color index [%d] must be between %d and %d", color.Index,
+ minBuiltinColorIndex, maxBuiltinColorIndex)
+ }
+ if _, exists := colorIndexes[color.Index]; exists {
+ return nil, fmt.Errorf("duplicate builtin color index [%d]", color.Index)
+ }
+ colorIndexes[color.Index] = struct{}{}
+
+ light, dark, err := normalizeInlineStyleThemePair(color.Light, color.Dark, fmt.Sprintf("builtin color [%d]", color.Index))
+ if err != nil {
+ return nil, err
+ }
+ ret.Colors = append(ret.Colors, &InlineStyleBuiltinColor{Index: color.Index, Light: light, Dark: dark})
+ }
+ sort.Slice(ret.Colors, func(i, j int) bool {
+ return ret.Colors[i].Index < ret.Colors[j].Index
+ })
+
+ styleIDs := make(map[string]struct{}, len(builtin.Styles))
+ for _, style := range builtin.Styles {
+ if style == nil {
+ return nil, errors.New("builtin style must not be null")
+ }
+ id := strings.TrimSpace(style.ID)
+ if _, valid := builtinStyleOrder[id]; !valid {
+ return nil, fmt.Errorf("invalid builtin style ID [%s]", id)
+ }
+ if _, exists := styleIDs[id]; exists {
+ return nil, fmt.Errorf("duplicate builtin style ID [%s]", id)
+ }
+ styleIDs[id] = struct{}{}
+
+ light, dark, err := normalizeInlineStyleThemePair(style.Light, style.Dark, "builtin style ["+id+"]")
+ if err != nil {
+ return nil, err
+ }
+ ret.Styles = append(ret.Styles, &InlineStyleBuiltinStyle{ID: id, Light: light, Dark: dark})
+ }
+ sort.Slice(ret.Styles, func(i, j int) bool {
+ return builtinStyleOrder[ret.Styles[i].ID] < builtinStyleOrder[ret.Styles[j].ID]
+ })
+
+ if builtin.Hidden != nil {
+ if ret.Hidden.Color, err = normalizeHiddenBuiltinColorIndexes(builtin.Hidden.Color, "color"); err != nil {
+ return nil, err
+ }
+ if ret.Hidden.BackgroundColor, err = normalizeHiddenBuiltinColorIndexes(builtin.Hidden.BackgroundColor,
+ "backgroundColor"); err != nil {
+ return nil, err
+ }
+ if ret.Hidden.Style1, err = normalizeHiddenBuiltinStyleIDs(builtin.Hidden.Style1); err != nil {
+ return nil, err
+ }
+ if ret.Hidden.AV, err = normalizeHiddenBuiltinColorIndexes(builtin.Hidden.AV, "av"); err != nil {
+ return nil, err
+ }
+ }
+ return ret, nil
+}
+
+func normalizeInlineStyleThemePair(light, dark *InlineStyleTheme, description string) (normalizedLight,
+ normalizedDark *InlineStyleTheme, err error) {
+ if light == nil || dark == nil {
+ return nil, nil, fmt.Errorf("%s must define light and dark themes", description)
+ }
+ if normalizedLight, err = normalizeInlineStyleTheme(light); err != nil {
+ return nil, nil, fmt.Errorf("invalid light theme of %s: %w", description, err)
+ }
+ if normalizedDark, err = normalizeInlineStyleTheme(dark); err != nil {
+ return nil, nil, fmt.Errorf("invalid dark theme of %s: %w", description, err)
+ }
+ lightColor, lightBackground := normalizedLight.Color != "", normalizedLight.BackgroundColor != ""
+ darkColor, darkBackground := normalizedDark.Color != "", normalizedDark.BackgroundColor != ""
+ if !lightColor && !lightBackground {
+ return nil, nil, fmt.Errorf("%s must define color or backgroundColor", description)
+ }
+ if lightColor != darkColor || lightBackground != darkBackground {
+ return nil, nil, fmt.Errorf("%s must use the same fields in light and dark themes", description)
+ }
+ return normalizedLight, normalizedDark, nil
+}
+
+func normalizeHiddenBuiltinColorIndexes(indexes []int, field string) (ret []int, err error) {
+ ret = make([]int, 0, len(indexes))
+ seen := make(map[int]struct{}, len(indexes))
+ for _, index := range indexes {
+ if index < minBuiltinColorIndex || maxBuiltinColorIndex < index {
+ return nil, fmt.Errorf("hidden builtin %s index [%d] must be between %d and %d", field, index,
+ minBuiltinColorIndex, maxBuiltinColorIndex)
+ }
+ if _, exists := seen[index]; exists {
+ continue
+ }
+ seen[index] = struct{}{}
+ ret = append(ret, index)
+ }
+ sort.Ints(ret)
+ return ret, nil
+}
+
+func normalizeHiddenBuiltinStyleIDs(ids []string) (ret []string, err error) {
+ seen := make(map[string]struct{}, len(ids))
+ for _, value := range ids {
+ id := strings.TrimSpace(value)
+ if _, valid := builtinStyleOrder[id]; !valid {
+ return nil, fmt.Errorf("invalid hidden builtin style ID [%s]", id)
+ }
+ if _, exists := seen[id]; exists {
+ continue
+ }
+ seen[id] = struct{}{}
+ ret = append(ret, id)
+ }
+ sort.Slice(ret, func(i, j int) bool {
+ return builtinStyleOrder[ret[i]] < builtinStyleOrder[ret[j]]
+ })
+ return ret, nil
+}
+
func normalizeInlineStyleTheme(theme *InlineStyleTheme) (ret *InlineStyleTheme, err error) {
ret = &InlineStyleTheme{}
if ret.Color, err = normalizeInlineStyleColor(theme.Color); err != nil {
diff --git a/kernel/model/inline_style_test.go b/kernel/model/inline_style_test.go
index 645d0cbd43..f86aee72e8 100644
--- a/kernel/model/inline_style_test.go
+++ b/kernel/model/inline_style_test.go
@@ -18,8 +18,10 @@ package model
import (
"bytes"
+ "encoding/json"
"os"
"path/filepath"
+ "reflect"
"strings"
"testing"
@@ -36,7 +38,11 @@ func TestInlineStylesCRUD(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if styles.Version != InlineStylesVersion || styles.Styles == nil || len(styles.Styles) != 0 {
+ if styles.Version != InlineStylesVersion || styles.Styles == nil || len(styles.Styles) != 0 ||
+ 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 {
t.Fatalf("unexpected empty inline styles: %#v", styles)
}
if _, err = os.Stat(inlineStylesPath()); !os.IsNotExist(err) {
@@ -80,6 +86,148 @@ func TestInlineStylesCRUD(t *testing.T) {
}
}
+func TestInlineStylesBuiltinCRUD(t *testing.T) {
+ setupInlineStylesTest(t)
+
+ saved, changed, err := SetInlineStylesData(&InlineStyles{
+ Version: InlineStylesVersion,
+ Styles: []*InlineStyle{},
+ Builtin: &InlineStyleBuiltin{
+ Colors: []*InlineStyleBuiltinColor{
+ {
+ Index: 13,
+ Light: &InlineStyleTheme{BackgroundColor: " #ABCDEF "},
+ Dark: &InlineStyleTheme{BackgroundColor: "#123456"},
+ },
+ {
+ Index: 2,
+ Light: &InlineStyleTheme{Color: "#AABBCC", BackgroundColor: "#DDEEFF"},
+ Dark: &InlineStyleTheme{Color: "#112233", BackgroundColor: "#445566"},
+ },
+ },
+ Styles: []*InlineStyleBuiltinStyle{
+ {
+ ID: "success",
+ Light: &InlineStyleTheme{Color: "#ABCDEF"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ },
+ {
+ ID: " warning ",
+ Light: &InlineStyleTheme{Color: "#AABBCC", BackgroundColor: "#DDEEFF"},
+ Dark: &InlineStyleTheme{Color: "#112233", BackgroundColor: "#445566"},
+ },
+ },
+ Hidden: &InlineStyleBuiltinHidden{
+ Color: []int{13, 2, 2},
+ BackgroundColor: []int{9, 1},
+ Style1: []string{"success", " warning ", "success"},
+ AV: []int{12, 3, 3},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed || len(saved.Builtin.Colors) != 2 || saved.Builtin.Colors[0].Index != 2 ||
+ saved.Builtin.Colors[1].Index != 13 || saved.Builtin.Colors[0].Light.Color != "#aabbcc" ||
+ len(saved.Builtin.Styles) != 2 || saved.Builtin.Styles[0].ID != "warning" ||
+ saved.Builtin.Styles[1].ID != "success" {
+ t.Fatalf("builtin colors were not normalized: %#v", saved.Builtin)
+ }
+ if !reflect.DeepEqual(saved.Builtin.Hidden.Color, []int{2, 13}) ||
+ !reflect.DeepEqual(saved.Builtin.Hidden.BackgroundColor, []int{1, 9}) ||
+ !reflect.DeepEqual(saved.Builtin.Hidden.Style1, []string{"warning", "success"}) ||
+ !reflect.DeepEqual(saved.Builtin.Hidden.AV, []int{3, 12}) {
+ t.Fatalf("hidden builtin colors were not normalized: %#v", saved.Builtin.Hidden)
+ }
+ if visible := getVisibleAVBuiltinColorIndexes(); !reflect.DeepEqual(visible,
+ []int{1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 13, neutralAVColorIndex}) {
+ t.Fatalf("unexpected visible AV builtin colors: %#v", visible)
+ }
+
+ legacySaved, changed, err := SetInlineStyles([]*InlineStyle{{
+ Name: "Custom",
+ Light: &InlineStyleTheme{Color: "#abcdef"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed || len(legacySaved.Styles) != 1 || !reflect.DeepEqual(legacySaved.Builtin, saved.Builtin) {
+ t.Fatalf("legacy update did not preserve builtin colors: %#v", legacySaved)
+ }
+
+ reset, changed, err := SetInlineStylesData(&InlineStyles{Version: InlineStylesVersion, Styles: legacySaved.Styles})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed || len(reset.Builtin.Colors) != 0 || len(reset.Builtin.Styles) != 0 ||
+ len(reset.Builtin.Hidden.Color) != 0 || len(reset.Builtin.Hidden.BackgroundColor) != 0 ||
+ len(reset.Builtin.Hidden.Style1) != 0 || len(reset.Builtin.Hidden.AV) != 0 {
+ t.Fatalf("missing builtin configuration was not normalized to empty: %#v", reset.Builtin)
+ }
+}
+
+func TestInlineStylesVersion1Migration(t *testing.T) {
+ setupInlineStylesTest(t)
+ legacyData := []byte(`{"version":1,"styles":[{"id":"20260821000000-abcdefg","name":"Legacy","light":{"color":"#abcdef"},"dark":{"color":"#123456"}}]}`)
+ if err := os.MkdirAll(filepath.Dir(inlineStylesPath()), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(inlineStylesPath(), legacyData, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ migrated, err := GetInlineStyles()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if migrated.Version != InlineStylesVersion || len(migrated.Styles) != 1 || migrated.Builtin == nil ||
+ len(migrated.Builtin.Colors) != 0 || migrated.Builtin.Hidden == nil {
+ t.Fatalf("legacy inline styles were not migrated: %#v", migrated)
+ }
+ currentData, err := os.ReadFile(inlineStylesPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(currentData, legacyData) {
+ t.Fatal("loading legacy inline styles rewrote the file")
+ }
+
+ if _, changed, err := SetInlineStyles(migrated.Styles); err != nil || !changed {
+ t.Fatalf("saving migrated inline styles failed: changed=%t, err=%v", changed, err)
+ }
+ var persisted InlineStyles
+ currentData, err = os.ReadFile(inlineStylesPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = json.Unmarshal(currentData, &persisted); err != nil {
+ t.Fatal(err)
+ }
+ if persisted.Version != InlineStylesVersion || persisted.Builtin == nil {
+ t.Fatalf("migrated inline styles were not persisted as version 2: %#v", persisted)
+ }
+}
+
+func TestVisibleAVBuiltinColorIndexesAlwaysKeepsNeutralColor(t *testing.T) {
+ setupInlineStylesTest(t)
+ hidden := make([]int, 0, maxBuiltinColorIndex)
+ for index := minBuiltinColorIndex; index <= maxBuiltinColorIndex; index++ {
+ hidden = append(hidden, index)
+ }
+ if _, _, err := SetInlineStylesData(&InlineStyles{
+ Version: InlineStylesVersion,
+ Styles: []*InlineStyle{},
+ Builtin: &InlineStyleBuiltin{Hidden: &InlineStyleBuiltinHidden{AV: hidden}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if visible := getVisibleAVBuiltinColorIndexes(); !reflect.DeepEqual(visible, []int{neutralAVColorIndex}) {
+ t.Fatalf("unexpected visible AV builtin colors: %#v", visible)
+ }
+}
+
func TestInlineStylesValidation(t *testing.T) {
validID := "20260821000000-abcdefg"
valid := func() *InlineStyle {
@@ -157,13 +305,142 @@ func TestInlineStylesValidation(t *testing.T) {
}
}
+func TestInlineStylesBuiltinValidation(t *testing.T) {
+ valid := func() *InlineStyles {
+ return &InlineStyles{
+ Version: InlineStylesVersion,
+ Styles: []*InlineStyle{},
+ Builtin: &InlineStyleBuiltin{
+ Colors: []*InlineStyleBuiltinColor{{
+ Index: 1,
+ Light: &InlineStyleTheme{Color: "#abcdef"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ }},
+ Styles: []*InlineStyleBuiltinStyle{{
+ ID: "error",
+ Light: &InlineStyleTheme{Color: "#abcdef", BackgroundColor: "#fedcba"},
+ Dark: &InlineStyleTheme{Color: "#123456", BackgroundColor: "#654321"},
+ }},
+ Hidden: &InlineStyleBuiltinHidden{},
+ },
+ }
+ }
+ tests := []struct {
+ name string
+ styles func() *InlineStyles
+ }{
+ {name: "null data", styles: func() *InlineStyles { return nil }},
+ {name: "legacy version", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Version = 1
+ return styles
+ }},
+ {name: "null color", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0] = nil
+ return styles
+ }},
+ {name: "low color index", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0].Index = 0
+ return styles
+ }},
+ {name: "high color index", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0].Index = 14
+ return styles
+ }},
+ {name: "duplicate color index", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors = append(styles.Builtin.Colors, &InlineStyleBuiltinColor{
+ Index: 1,
+ Light: &InlineStyleTheme{BackgroundColor: "#abcdef"},
+ Dark: &InlineStyleTheme{BackgroundColor: "#123456"},
+ })
+ return styles
+ }},
+ {name: "missing color theme", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0].Dark = nil
+ return styles
+ }},
+ {name: "empty color fields", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0].Light = &InlineStyleTheme{}
+ styles.Builtin.Colors[0].Dark = &InlineStyleTheme{}
+ return styles
+ }},
+ {name: "different color fields", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0].Dark = &InlineStyleTheme{BackgroundColor: "#123456"}
+ return styles
+ }},
+ {name: "invalid color value", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Colors[0].Light.Color = "red"
+ return styles
+ }},
+ {name: "null style", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Styles[0] = nil
+ return styles
+ }},
+ {name: "invalid style ID", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Styles[0].ID = "danger"
+ return styles
+ }},
+ {name: "duplicate style ID", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Styles = append(styles.Builtin.Styles, &InlineStyleBuiltinStyle{
+ ID: "error",
+ Light: &InlineStyleTheme{Color: "#abcdef"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ })
+ return styles
+ }},
+ {name: "invalid hidden color", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Hidden.Color = []int{0}
+ return styles
+ }},
+ {name: "invalid hidden background", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Hidden.BackgroundColor = []int{14}
+ return styles
+ }},
+ {name: "invalid hidden style", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Hidden.Style1 = []string{"danger"}
+ return styles
+ }},
+ {name: "invalid hidden av", styles: func() *InlineStyles {
+ styles := valid()
+ styles.Builtin.Hidden.AV = []int{14}
+ return styles
+ }},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ setupInlineStylesTest(t)
+ if _, _, err := SetInlineStylesData(test.styles()); err == nil {
+ t.Fatal("expected builtin validation error")
+ }
+ if _, err := os.Stat(inlineStylesPath()); !os.IsNotExist(err) {
+ t.Fatalf("invalid builtin inline styles were written: %v", err)
+ }
+ })
+ }
+}
+
func TestInlineStylesInvalidFileIsNotOverwritten(t *testing.T) {
tests := []struct {
name string
data []byte
}{
{name: "invalid JSON", data: []byte(`{"version":`)},
- {name: "future version", data: []byte(`{"version":2,"styles":[]}`)},
+ {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: "oversized", data: bytes.Repeat([]byte("x"), maxInlineStylesFileSize+1)},
}
for _, test := range tests {
diff --git a/kernel/model/theme.go b/kernel/model/theme.go
index 5364ece997..6534f6aed0 100644
--- a/kernel/model/theme.go
+++ b/kernel/model/theme.go
@@ -19,6 +19,7 @@ package model
import (
"os"
"path/filepath"
+ "strconv"
"strings"
"github.com/88250/lute/ast"
@@ -71,6 +72,49 @@ func mergeInlineStyleThemeVars(themeStyles map[string]string, styles *InlineStyl
if styles == nil {
return
}
+ if styles.Builtin != nil {
+ for _, color := range styles.Builtin.Colors {
+ if color == nil {
+ continue
+ }
+ theme := color.Light
+ if isDarkMode {
+ theme = color.Dark
+ }
+ if theme == nil {
+ continue
+ }
+ 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.Builtin.Styles {
+ if style == nil {
+ continue
+ }
+ theme := style.Light
+ if isDarkMode {
+ theme = style.Dark
+ }
+ if theme == nil {
+ continue
+ }
+ prefix := "--b3-inline-builtin-" + style.ID
+ legacyPrefix := "--b3-card-" + style.ID
+ if theme.Color != "" {
+ themeStyles[prefix+"-color"] = theme.Color
+ themeStyles[legacyPrefix+"-color"] = theme.Color
+ }
+ if theme.BackgroundColor != "" {
+ themeStyles[prefix+"-background-color"] = theme.BackgroundColor
+ themeStyles[legacyPrefix+"-background"] = theme.BackgroundColor
+ }
+ }
+ }
for _, style := range styles.Styles {
if style == nil {
continue
diff --git a/kernel/model/theme_test.go b/kernel/model/theme_test.go
index 39360d153f..5f3cb23153 100644
--- a/kernel/model/theme_test.go
+++ b/kernel/model/theme_test.go
@@ -57,34 +57,96 @@ func TestResolveCSSVars(t *testing.T) {
}
func TestMergeInlineStyleThemeVars(t *testing.T) {
- styles := &InlineStyles{Version: InlineStylesVersion, Styles: []*InlineStyle{{
- ID: "20260821000000-abcdefg",
- Name: "Combined",
- Light: &InlineStyleTheme{
- Color: "#112233",
- BackgroundColor: "#445566",
+ styles := &InlineStyles{
+ Version: InlineStylesVersion,
+ Styles: []*InlineStyle{{
+ ID: "20260821000000-abcdefg",
+ Name: "Combined",
+ Light: &InlineStyleTheme{
+ Color: "#112233",
+ BackgroundColor: "#445566",
+ },
+ Dark: &InlineStyleTheme{
+ Color: "#aabbcc",
+ BackgroundColor: "#ddeeff",
+ },
+ }},
+ Builtin: &InlineStyleBuiltin{
+ Colors: []*InlineStyleBuiltinColor{{
+ Index: 3,
+ Light: &InlineStyleTheme{Color: "#010203", BackgroundColor: "#040506"},
+ Dark: &InlineStyleTheme{Color: "#070809", BackgroundColor: "#0a0b0c"},
+ }},
+ Styles: []*InlineStyleBuiltinStyle{{
+ ID: "warning",
+ Light: &InlineStyleTheme{Color: "#111213", BackgroundColor: "#141516"},
+ Dark: &InlineStyleTheme{Color: "#171819", BackgroundColor: "#1a1b1c"},
+ }},
},
- Dark: &InlineStyleTheme{
- Color: "#aabbcc",
- BackgroundColor: "#ddeeff",
- },
- }}}
+ }
colorName := "--b3-inline-style-20260821000000-abcdefg-color"
backgroundName := "--b3-inline-style-20260821000000-abcdefg-background-color"
light := map[string]string{colorName: "#000000"}
mergeInlineStyleThemeVars(light, styles, false)
- if light[colorName] != "#112233" || light[backgroundName] != "#445566" {
+ if light[colorName] != "#112233" || light[backgroundName] != "#445566" ||
+ light["--b3-font-color3"] != "#010203" || light["--b3-font-background3"] != "#040506" ||
+ light["--b3-inline-builtin-warning-color"] != "#111213" ||
+ light["--b3-inline-builtin-warning-background-color"] != "#141516" ||
+ light["--b3-card-warning-color"] != "#111213" || light["--b3-card-warning-background"] != "#141516" {
t.Fatalf("unexpected light inline style variables: %#v", light)
}
dark := map[string]string{}
mergeInlineStyleThemeVars(dark, styles, true)
- if dark[colorName] != "#aabbcc" || dark[backgroundName] != "#ddeeff" {
+ if dark[colorName] != "#aabbcc" || dark[backgroundName] != "#ddeeff" ||
+ dark["--b3-font-color3"] != "#070809" || dark["--b3-font-background3"] != "#0a0b0c" ||
+ dark["--b3-inline-builtin-warning-color"] != "#171819" ||
+ dark["--b3-inline-builtin-warning-background-color"] != "#1a1b1c" ||
+ dark["--b3-card-warning-color"] != "#171819" || dark["--b3-card-warning-background"] != "#1a1b1c" {
t.Fatalf("unexpected dark inline style variables: %#v", dark)
}
}
+func TestFillThemeStyleVarUsesBuiltinOverrides(t *testing.T) {
+ setupThemeTest(t, "daylight", `:root {
+ --b3-font-color2: #010101;
+ --b3-card-error-color: #020202;
+ --b3-card-error-background: #030303;
+ }`)
+ Conf.Appearance.Mode = 0
+ Conf.Appearance.ThemeLight = "daylight"
+
+ if _, _, err := SetInlineStylesData(&InlineStyles{
+ Version: InlineStylesVersion,
+ Styles: []*InlineStyle{},
+ Builtin: &InlineStyleBuiltin{
+ Colors: []*InlineStyleBuiltinColor{{
+ Index: 2,
+ Light: &InlineStyleTheme{Color: "#112233"},
+ Dark: &InlineStyleTheme{Color: "#445566"},
+ }},
+ Styles: []*InlineStyleBuiltinStyle{{
+ ID: "error",
+ Light: &InlineStyleTheme{Color: "#aabbcc", BackgroundColor: "#ddeeff"},
+ Dark: &InlineStyleTheme{Color: "#123456", BackgroundColor: "#654321"},
+ }},
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ tree, node := inlineStyleThemeTestTree("color: var(--b3-card-error-color); " +
+ "background-color: var(--b3-card-error-background); border-color: var(--b3-inline-builtin-error-color); " +
+ "text-decoration-color: var(--b3-inline-builtin-error-background-color); " +
+ "outline-color: var(--b3-font-color2);")
+ fillThemeStyleVar(tree)
+ if actual := node.KramdownIAL[0][1]; actual != "color: #aabbcc; background-color: #ddeeff; "+
+ "border-color: #aabbcc; text-decoration-color: #ddeeff; outline-color: #112233;" {
+ t.Fatalf("unexpected builtin inline style export: %s", actual)
+ }
+}
+
func TestFillThemeStyleVarUsesCurrentInlineStyleMode(t *testing.T) {
setupThemeTest(t, "midnight", `:root {}`)
Conf.Appearance.Mode = 1