Skip to content

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

:recycle: Use original theme variables for built-in inline styles https://github.com/siyuan-note/siyuan/issues/19625

Daniel15947bf19294
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 702ba6db53..b95fdca842 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -33,6 +33,7 @@ import {
filterHiddenRecentInlineStyles,
getBuiltinInlineStyleIDFromValue,
getBuiltinInlineStylePreview,
+ getBuiltinInlineStyleApplication,
getBuiltinInlineStylePropertyValue,
getInlineStyleByID,
getInlineStyleByValue,
@@ -471,7 +472,7 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
</button>`;
}
const preview = getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID);
- return `<button class="keyboard__slash-item" data-type="style1">
+ return `<button class="keyboard__slash-item" data-type="style1" data-builtin-style-id="${key}">
<span class="keyboard__slash-icon" style="color:${preview.color};background-color:${preview.backgroundColor};">A</span>
<span class="keyboard__slash-text">${getBuiltinStyleLabel(key as TBuiltinInlineStyleID)}</span>
</button>`;
@@ -562,7 +563,7 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
backgroundColor: lastFontStatus[1],
color: lastFontStatus[2],
};
- lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
+ lastColorHTML += `<button class="keyboard__slash-item" data-builtin-style-id="${builtInStyle || ""}" data-type="${lastFontStatus[0]}">
<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>`;
@@ -724,8 +725,10 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {
return;
}
const style = getBuiltinStyleCSS(id);
+ const preview = getBuiltinInlineStylePreview(id);
builtinStyleHTML += getSlashItem(`style${Constants.ZWSP}${style}`,
- `<div style="${style}" class="keyboard__slash-icon">A</div>`, getBuiltinStyleLabel(id), "true");
+ `<div style="color:${preview.color};background-color:${preview.backgroundColor};" 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>
@@ -1600,8 +1603,10 @@ export const initKeyboardToolbar = () => {
const itemElement = buttonElement.firstElementChild as HTMLElement;
const focusRange = !buttonElement.classList.contains("keyboard__slash-item");
if (type === "style1") {
+ const builtinID = buttonElement.dataset.builtinStyleId as TBuiltinInlineStyleID;
fontEvent(protyle, nodeElements, type,
- encodeStyle1(itemElement.style.backgroundColor, itemElement.style.color), focusRange);
+ builtinID ? getBuiltinInlineStyleApplication(builtinID).color :
+ encodeStyle1(itemElement.style.backgroundColor, itemElement.style.color), focusRange);
} else if (type === "fontSize") {
fontEvent(protyle, nodeElements, type, itemElement.textContent.trim(), focusRange);
} else if (type === "backgroundColor") {
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index 54113b05d0..d76b9c608d 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -39,6 +39,7 @@ import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtim
import {resolveSlashMenuItems, TSlashMenuItem} from "./slashMenu";
import {
getBuiltinInlineStylePropertyValue,
+ getBuiltinInlineStylePreview,
isBuiltinInlineStyleVisible,
TBuiltinInlineStyleID,
} from "../toolbar/inlineStyle";
@@ -62,9 +63,13 @@ const slashBuiltinStyleIDs: Partial<Record<string, TBuiltinInlineStyleID>> = {
errorStyle: "error",
};
-const getBuiltinStyleCSS = (id: TBuiltinInlineStyleID) =>
- `color: ${getBuiltinInlineStylePropertyValue(id, "color")};` +
- `background-color: ${getBuiltinInlineStylePropertyValue(id, "backgroundColor")};`;
+const getBuiltinStyleCSS = (id: TBuiltinInlineStyleID, preview = false) => {
+ const colors = preview ? getBuiltinInlineStylePreview(id) : {
+ color: getBuiltinInlineStylePropertyValue(id, "color"),
+ backgroundColor: getBuiltinInlineStylePropertyValue(id, "backgroundColor"),
+ };
+ return `color: ${colors.color};background-color: ${colors.backgroundColor};`;
+};
const getHotkeyOrMarker = (hotkey: string, marker: string) => {
if (hotkey) {
@@ -397,22 +402,22 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {
filter: [window.siyuan.languages.infoStyle, "info style", "信息样式", "xinxiyangshi", "xxys"],
id: "infoStyle",
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>`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("info", true)}" 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}${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>`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("success", true)}" 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}${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>`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("warning", true)}" 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}${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>`,
+ html: `<div class="b3-list-item__first"><div style="${getBuiltinStyleCSS("error", true)}" 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",
diff --git a/app/src/protyle/render/av/richText.test.ts b/app/src/protyle/render/av/richText.test.ts
index 54b27ebd0d..9231847392 100644
--- a/app/src/protyle/render/av/richText.test.ts
+++ b/app/src/protyle/render/av/richText.test.ts
@@ -394,6 +394,16 @@ describe("attribute view text source compatibility", () => {
});
it("keeps only supported inline color declarations", () => {
+ for (const id of ["error", "warning", "info", "success"]) {
+ const style = `color: var(--b3-card-${id}-color); background-color: var(--b3-card-${id}-background);`;
+ assert.equal(sanitizeAVRichTextInlineStyle(style), style);
+ assert.equal(sanitizeAVRichTextInlineStyle(`color: var(--b3-card-${id}-background);`), "");
+ assert.equal(sanitizeAVRichTextInlineStyle(`background-color: var(--b3-card-${id}-color);`), "");
+ }
+ for (const value of ["var(--b3-card-danger-color)", "var(--b3-card-info-color, red)",
+ "var(--b3-inline-builtin-info-color, var(--b3-card-error-color))"]) {
+ assert.equal(sanitizeAVRichTextInlineStyle(`color: ${value};`), "");
+ }
assert.equal(sanitizeAVRichTextInlineStyle(
"background-color: var(--b3-font-background8); color:var(--b3-font-color2);"
), "color: var(--b3-font-color2); background-color: var(--b3-font-background8);");
diff --git a/app/src/protyle/render/av/richTextValue.ts b/app/src/protyle/render/av/richTextValue.ts
index c362b6edd8..51e06bf588 100644
--- a/app/src/protyle/render/av/richTextValue.ts
+++ b/app/src/protyle/render/av/richTextValue.ts
@@ -723,6 +723,10 @@ const normalizeAVRichTextInlineStyleValue = (property: AVRichTextStyleProperty,
return "";
}
+ const themeStyle = value.match(/^var\(--b3-card-(error|warning|info|success)-(color|background)\)$/);
+ if (themeStyle) {
+ return themeStyle[2] === (property === "color" ? "color" : "background") ? value : "";
+ }
const builtinStyle = value.match(
/^var\(--b3-inline-builtin-(error|warning|info|success)-(color|background-color),\s*var\(--b3-card-(error|warning|info|success)-(color|background)\)\)$/
);
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index ce2e9e4ba7..d6757f0f8a 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -12,7 +12,8 @@ import {openLink} from "../../../editor/openLink";
import {matchHotKey} from "../../util/hotKey";
import {setFullscreen} from "../../breadcrumb/action";
import {
- getBuiltinColorPropertyValue, getBuiltinInlineStylePreview, getInlineStyleByID, getInlineStylePreview, getInlineStylePropertyValue,
+ getBuiltinColorPropertyValue, getBuiltinInlineStylePreview, getBuiltinInlineStylePropertyValue,
+ getInlineStyleByID, getInlineStylePreview, getInlineStylePropertyValue,
getInlineStylesCache, getVisibleOrderedStyleKeys, isBuiltinOrderKey,
TBuiltinInlineStyleID,
} from "../../toolbar/inlineStyle";
@@ -148,7 +149,9 @@ class ListMindmapController {
return getVisibleOrderedStyleKeys("style1", data).map(key => {
if (isBuiltinOrderKey("style1", key)) {
return {label: window.siyuan.languages[`${key}Style`],
- ...getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID)};
+ color: getBuiltinInlineStylePropertyValue(key as TBuiltinInlineStyleID, "color"),
+ backgroundColor: getBuiltinInlineStylePropertyValue(key as TBuiltinInlineStyleID, "backgroundColor"),
+ preview: getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID)};
}
const style = getInlineStyleByID(key, data);
return {label: style.name, ...getInlineStylePreview(style)};
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index 5df0cb3ebf..3439cae5b6 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -302,7 +302,8 @@ const browserCases = async (sourceCode: string, css: string) => {
host, model,
labels: new Proxy({}, {get: (_target, key) => String(key)}),
colors: () => [{label: "Appearance background", value: "var(--b3-font-background1)"}],
- nodeColors: () => [{label: "Appearance combined", color: "var(--b3-font-color1)", backgroundColor: "var(--b3-font-background1)"}],
+ nodeColors: () => [{label: "Appearance combined", color: "var(--b3-font-color1)",
+ backgroundColor: "var(--b3-font-background1)", preview: {color: "#112233", backgroundColor: "#ddeeff"}}],
onFullscreen: (enter: boolean) => fullscreenChanges.push(enter),
onEdit: (id: string) => edits.push(id),
finishEdit: () => finishAllowed,
@@ -552,6 +553,8 @@ const browserCases = async (sourceCode: string, css: string) => {
const nodeColorButton = nodePalette.querySelector<HTMLButtonElement>('[aria-label="Appearance combined"]');
check.equal(nodeColorButton.textContent, "A");
check.equal(nodeColorButton.classList.contains("color__square"), true);
+ check.equal(getComputedStyle(nodeColorButton).color, "rgb(17, 34, 51)");
+ check.equal(getComputedStyle(nodeColorButton).backgroundColor, "rgb(221, 238, 255)");
nodeColorButton.click();
check.deepEqual(nodeStyles[nodeStyles.length - 1], [beta, {textColor: "var(--b3-font-color1)", backgroundColor: "var(--b3-font-background1)"}]);
host.style.setProperty("--b3-font-color1", "#123456");
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index 70710ee4e6..c42c6aeb18 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -20,7 +20,10 @@ export interface ListMindmapViewOptions {
cdn?: string;
onOpenLink?: (href: string, event: MouseEvent) => void;
colors?: () => {label: string, value: string}[];
- nodeColors?: () => {label: string, color: string, backgroundColor: string}[];
+ nodeColors?: () => {
+ label: string, color: string, backgroundColor: string,
+ preview?: {color: string, backgroundColor: string},
+ }[];
onManageNodeColors?: () => void;
onManageLineColors?: () => void;
onFullscreen?: (enter: boolean, button: HTMLButtonElement) => void;
@@ -1310,7 +1313,10 @@ export class ListMindmapView {
const nodePalette = createElement("div", "fn__flex");
nodePalette.setAttribute("role", "group");
nodePalette.setAttribute("aria-label", this.label("color"));
- [{label: this.label("default"), color: "", backgroundColor: ""}, ...(this.options.nodeColors?.() || [])].forEach(item => {
+ const nodeColors: ReturnType<NonNullable<ListMindmapViewOptions["nodeColors"]>> = [
+ {label: this.label("default"), color: "", backgroundColor: ""}, ...(this.options.nodeColors?.() || []),
+ ];
+ nodeColors.forEach(item => {
const button = this.makeButton("color", "iconFont", () => change({
textColor: item.color, backgroundColor: item.backgroundColor,
}));
@@ -1319,8 +1325,8 @@ export class ListMindmapView {
button.textContent = "A";
button.setAttribute("aria-label", item.label);
button.setAttribute("aria-pressed", String(selected));
- button.style.color = item.color;
- button.style.backgroundColor = item.backgroundColor;
+ button.style.color = item.preview?.color ?? item.color;
+ button.style.backgroundColor = item.preview?.backgroundColor ?? item.backgroundColor;
nodePalette.append(button);
});
if (this.options.onManageNodeColors) {
diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.ts
index ba56a684cd..edb1d4662c 100644
--- a/app/src/protyle/toolbar/Font.ts
+++ b/app/src/protyle/toolbar/Font.ts
@@ -184,7 +184,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
}
const preview = getBuiltinInlineStylePreview(key as TBuiltinInlineStyleID);
return "<button class=\"color__square ariaLabel\" data-position=\"3south\" data-type=\"style1\" " +
- `aria-label="${builtinStyleLabels[key as TBuiltinInlineStyleID]}" style="color:${preview.color};` +
+ `data-builtin-style-id="${key}" aria-label="${builtinStyleLabels[key as TBuiltinInlineStyleID]}" style="color:${preview.color};` +
`background-color:${preview.backgroundColor};">A</button>`;
}
const style = getInlineStyleByID(key, data);
@@ -256,7 +256,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
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>`;
+ 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-builtin-style-id="${builtinStyleID || ""}" data-type="${lastFontStatus[0]}">A</button>`;
break;
}
case "clear":
@@ -394,7 +394,9 @@ ${showInlineDirection ? `<div class="fn__hr"></div>
protyle.toolbar.element.classList.add("fn__none");
openInlineStyleDialog(target.dataset.inlineStyleType as TInlineStyleType);
} else if (dataType === "style1") {
- applyFontStyle(dataType, encodeStyle1(target.style.backgroundColor, target.style.color));
+ const builtinID = target.dataset.builtinStyleId as TBuiltinInlineStyleID;
+ applyFontStyle(dataType, builtinID ? getBuiltinInlineStyleApplication(builtinID).color :
+ encodeStyle1(target.style.backgroundColor, target.style.color));
closeSelectionToolbarAppearance();
} else if (dataType === "fontSize") {
applyFontStyle(dataType, target.getAttribute("data-value"));
diff --git a/app/src/protyle/toolbar/inlineStyle.test.ts b/app/src/protyle/toolbar/inlineStyle.test.ts
index b561358fcc..83d9edd1f3 100644
--- a/app/src/protyle/toolbar/inlineStyle.test.ts
+++ b/app/src/protyle/toolbar/inlineStyle.test.ts
@@ -1,9 +1,76 @@
import {before, describe, it} from "node:test";
import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, rmSync, writeFileSync} from "node:fs";
+import {tmpdir} from "node:os";
+import * as path from "node:path";
+import {promisify} from "node:util";
import type {IInlineStyle, IInlineStyleBuiltin, IInlineStyleOrder} from "./inlineStyle";
let inlineStyle: typeof import("./inlineStyle");
+it("renders both formats with content overrides while preserving interface colors", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 30000,
+}, async () => {
+ const data = inlineStyle.normalizeInlineStyles({version: 2, styles: [], builtin: {
+ colors: [], hidden: {}, styles: [{id: "info",
+ light: {color: "#112233", backgroundColor: "#ddeeff"},
+ dark: {color: "#445566", backgroundColor: "#778899"}}],
+ }});
+ const html = `<style>:root {--b3-card-info-color: #010203; --b3-card-info-background: #040506;}</style>
+<style id="siyuanStyle">${inlineStyle.getInlineStylesCSS(data)}</style>
+<button id="interface" style="color:var(--b3-card-info-color);background-color:var(--b3-card-info-background)">UI</button>` +
+ ["protyle-wysiwyg", "b3-typography"].map(className => `<div class="${className}">` +
+ [
+ "color:var(--b3-card-info-color);background-color:var(--b3-card-info-background)",
+ "color:var(--b3-inline-builtin-info-color, var(--b3-card-info-color));" +
+ "background-color:var(--b3-inline-builtin-info-background-color, var(--b3-card-info-background))",
+ ].map(style => `<span class="content" style="${style}">A</span>`).join("") + "</div>").join("");
+ const cases = () => {
+ const check = (element: Element, color: string, background: string) => {
+ const style = getComputedStyle(element);
+ if (style.color !== color || style.backgroundColor !== background) {
+ throw new Error(`${element.outerHTML}: ${style.color}, ${style.backgroundColor}`);
+ }
+ };
+ for (const mode of ["light", "dark"]) {
+ document.documentElement.setAttribute("data-theme-mode", mode);
+ document.querySelectorAll(".content").forEach(element => check(element,
+ mode === "light" ? "rgb(17, 34, 51)" : "rgb(68, 85, 102)",
+ mode === "light" ? "rgb(221, 238, 255)" : "rgb(119, 136, 153)"));
+ check(document.getElementById("interface"), "rgb(1, 2, 3)", "rgb(4, 5, 6)");
+ }
+ (document.getElementById("siyuanStyle") as HTMLStyleElement).disabled = true;
+ document.querySelectorAll(".content").forEach(element => check(element, "rgb(1, 2, 3)", "rgb(4, 5, 6)"));
+ };
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-inline-style-test-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.commandLine.appendSwitch("disable-gpu");
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, webPreferences: {offscreen: true}});
+ try {
+ await win.loadURL("data:text/html," + encodeURIComponent(${JSON.stringify(html)}));
+ await win.webContents.executeJavaScript(${JSON.stringify(`const __name = value => value; (${cases.toString()})()`)});
+ win.destroy();
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ win.destroy();
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron") as unknown as string, [script], {env, timeout: 25000, windowsHide: true});
+ } finally {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
+
before(async () => {
Object.assign(globalThis, {
NODE_ENV: "test",
@@ -238,7 +305,7 @@ describe("getInlineStylesCSS", () => {
}`);
});
- it("overrides numbered colors and scopes semantic compatibility variables to content", () => {
+ it("overrides numbered colors and scopes semantic theme variables to content", () => {
assert.equal(inlineStyle.getInlineStylesCSS({
version: 2,
builtin: {
@@ -258,29 +325,33 @@ describe("getInlineStylesCSS", () => {
}), `: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);
+ --b3-card-error-color: #330000;
+ --b3-card-error-background: #ffeeee;
}
: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);
+ --b3-card-error-color: #ffdddd;
+ --b3-card-error-background: #440000;
}`);
});
});
describe("recent inline styles", () => {
+ it("deduplicates old and new built-in expressions", () => {
+ const current = "style1\u200b" + inlineStyle.getBuiltinInlineStyleApplication("info").color;
+ const previous = "style1\u200bvar(--b3-inline-builtin-info-background-color, var(--b3-card-info-background))" +
+ "\u200bvar(--b3-inline-builtin-info-color, var(--b3-card-info-color))";
+ assert.equal(inlineStyle.getRecentInlineStyleKey(previous), inlineStyle.getRecentInlineStyleKey(current));
+ assert.notEqual(inlineStyle.getRecentInlineStyleKey(current),
+ inlineStyle.getRecentInlineStyleKey("style1\u200b" + inlineStyle.getBuiltinInlineStyleApplication("error").color));
+ });
it("extracts a stable preset ID and ignores changing fallbacks", () => {
const first = "color\u200b" +
"var(--b3-inline-style-20260821120000-abcdefg-color, #112233)";
@@ -342,15 +413,31 @@ describe("recent inline styles", () => {
});
describe("built-in semantic styles", () => {
- it("uses dedicated variables with legacy fallbacks", () => {
+ it("previews each mode independently without persisting literal colors", () => {
+ const data = inlineStyle.normalizeInlineStyles({version: 2, styles: [], builtin: {
+ ...emptyBuiltin,
+ styles: [{id: "info", light: {color: "#112233"}, dark: {color: "#ddeeff"}}],
+ }});
+ assert.deepEqual(inlineStyle.getBuiltinInlineStylePreview("info", "light", data), {
+ color: "#112233", backgroundColor: "var(--b3-card-info-background)",
+ });
+ assert.deepEqual(inlineStyle.getBuiltinInlineStylePreview("info", "dark", data), {
+ color: "#ddeeff", backgroundColor: "var(--b3-card-info-background)",
+ });
+ assert.equal(inlineStyle.getBuiltinInlineStyleApplication("info").color,
+ "var(--b3-card-info-background)\u200bvar(--b3-card-info-color)");
+ assert.equal(inlineStyle.getBuiltinInlineStylePreview("info", "light").color,
+ "var(--b3-card-info-color)");
+ });
+ it("writes original theme variables without overrides", () => {
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))",
+ color: "var(--b3-card-info-background)" +
+ "\u200bvar(--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))",
+ assert.deepEqual(inlineStyle.getBuiltinInlineStylePreview("success", "light"), {
+ color: "var(--b3-card-success-color)",
+ backgroundColor: "var(--b3-card-success-background)",
});
});
});
diff --git a/app/src/protyle/toolbar/inlineStyle.ts b/app/src/protyle/toolbar/inlineStyle.ts
index 450df477d0..4b38e79790 100644
--- a/app/src/protyle/toolbar/inlineStyle.ts
+++ b/app/src/protyle/toolbar/inlineStyle.ts
@@ -601,21 +601,20 @@ export const getBuiltinColorPropertyValue = (index: number, property: TInlineSty
`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)}))`;
+ `var(${getBuiltinInlineStyleVariableName(id, property)})`;
-export const getBuiltinInlineStylePreview = (id: TBuiltinInlineStyleID) => ({
- color: getBuiltinInlineStylePropertyValue(id, "color"),
- backgroundColor: getBuiltinInlineStylePropertyValue(id, "backgroundColor"),
-});
+export const getBuiltinInlineStylePreview = (id: TBuiltinInlineStyleID,
+ mode = getCurrentInlineStyleMode(), data = getInlineStylesCache()) => {
+ const colors = getBuiltinInlineStyle(id, data)?.[mode];
+ return {
+ color: colors?.color || getBuiltinInlineStylePropertyValue(id, "color"),
+ backgroundColor: colors?.backgroundColor || getBuiltinInlineStylePropertyValue(id, "backgroundColor"),
+ };
+};
export const getBuiltinInlineStyleApplication = (id: TBuiltinInlineStyleID): IInlineStyleApplication => ({
type: "style1",
@@ -692,6 +691,10 @@ export const filterHiddenRecentInlineStyles = (values: string[], data = getInlin
values.filter(value => isRecentInlineStyleVisible(value, data));
export const getRecentInlineStyleKey = (value: string) => {
+ const builtinID = value.startsWith("style1" + INLINE_STYLE_SEPARATOR) && getBuiltinInlineStyleIDFromValue(value);
+ if (builtinID) {
+ return "style1" + INLINE_STYLE_SEPARATOR + builtinID;
+ }
const id = getInlineStyleIDFromValue(value);
if (!id) {
return value;
@@ -720,15 +723,11 @@ export const getInlineStylesCSS = (data: unknown = getInlineStylesCache()) => {
});
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")});`);
+ contentDeclarations.push(` ${getBuiltinInlineStyleVariableName(style.id, "color")}: ${style[mode].color};`);
}
if (style[mode].backgroundColor) {
- declarations.push(` ${getBuiltinInlineStyleVariableName(style.id, "backgroundColor")}: ` +
+ contentDeclarations.push(` ${getBuiltinInlineStyleVariableName(style.id, "backgroundColor")}: ` +
`${style[mode].backgroundColor};`);
- contentDeclarations.push(` ${getBuiltinInlineStyleLegacyVariableName(style.id, "backgroundColor")}: ` +
- `var(${getBuiltinInlineStyleVariableName(style.id, "backgroundColor")});`);
}
});
normalized.styles.forEach(style => {
diff --git a/kernel/av/value.go b/kernel/av/value.go
index 141640aa70..c7ade76f93 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -1270,6 +1270,9 @@ func normalizeValueTextRichBuiltinStyleValue(property, value string) (ret string
if "background-color" == property {
valueSuffix, legacySuffix = "background-color", "background"
}
+ if match := valueTextRichBuiltinThemeStylePattern.FindStringSubmatch(value); len(match) == 3 {
+ return value, match[2] == legacySuffix
+ }
match := valueTextRichBuiltinStylePattern.FindStringSubmatch(value)
if 5 != len(match) || match[1] != match[3] || match[2] != valueSuffix || match[4] != legacySuffix {
return "", false
@@ -1362,8 +1365,9 @@ var valueTextRichStylePropertyOrder = []string{
}
var (
- valueTextRichBuiltinPalettePattern = regexp.MustCompile(`^var\(--b3-font-(color|background)(\d+)\)$`)
- valueTextRichBuiltinStylePattern = regexp.MustCompile(
+ valueTextRichBuiltinThemeStylePattern = regexp.MustCompile(`^var\(--b3-card-(error|warning|info|success)-(color|background)\)$`)
+ valueTextRichBuiltinPalettePattern = regexp.MustCompile(`^var\(--b3-font-(color|background)(\d+)\)$`)
+ valueTextRichBuiltinStylePattern = regexp.MustCompile(
`^var\(--b3-inline-builtin-(error|warning|info|success)-(color|background-color),\s*` +
`var\(--b3-card-(error|warning|info|success)-(color|background)\)\)$`,
)
diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.go
index a4385aa80e..9b3ea9a3fc 100644
--- a/kernel/av/value_text_test.go
+++ b/kernel/av/value_text_test.go
@@ -297,6 +297,9 @@ func TestValueTextRichTextMarkStyleIALWhitelist(t *testing.T) {
content string
style string
}{
+ {`<span data-type="text strong" style="color: var(--b3-card-error-color); ` +
+ `background-color: var(--b3-card-warning-background);">builtin theme</span>`,
+ "color: var(--b3-card-error-color); background-color: var(--b3-card-warning-background);"},
{`<span data-type="text" style="color: var(--b3-font-color1);">foreground</span>`,
"color: var(--b3-font-color1);"},
{`<span data-type="text" style="color: var(--b3-font-color01);">normalized foreground</span>`,
@@ -410,6 +413,11 @@ func TestValueTextRichTextMarkStyleIALWhitelist(t *testing.T) {
`<span data-type="text" style="color: var(--b3-font-color8); background-image: url(javascript:alert(1));">URL</span>`,
`<span data-type="text" style="color: var(--b3-font-color8); color: var(--b3-font-color9);">duplicate</span>`,
`<span data-type="text" style="color: var(--b3-inline-builtin-danger-color, var(--b3-card-danger-color));">unknown builtin</span>`,
+ `<span data-type="text" style="color: var(--b3-card-danger-color);">unknown theme</span>`,
+ `<span data-type="text" style="color: var(--b3-card-info-background);">wrong theme property</span>`,
+ `<span data-type="text" style="background-color: var(--b3-card-info-color);">wrong theme background</span>`,
+ `<span data-type="text" style="color: var(--b3-card-info-color, red);">unexpected fallback</span>`,
+ `<span data-type="text" style="color: var(--b3-inline-builtin-info-color, var(--b3-card-error-color));">mismatched fallback</span>`,
`<span data-type="text" style="color: var(--b3-inline-style-invalid-color, #112233);">invalid ID</span>`,
`<span data-type="text" style="color: var(--b3-inline-style-20240101000000-abcdefg-color, url(javascript:alert(1)));">custom URL</span>`,
`<span data-type="text" custom-foo="bar" style="color: var(--b3-font-color8);">custom attribute</span>`,
diff --git a/kernel/model/theme_test.go b/kernel/model/theme_test.go
index 2b90d03baa..1b9bfb12a3 100644
--- a/kernel/model/theme_test.go
+++ b/kernel/model/theme_test.go
@@ -145,6 +145,24 @@ func TestFillThemeStyleVarUsesBuiltinOverrides(t *testing.T) {
"border-color: #aabbcc; text-decoration-color: #ddeeff; outline-color: #112233;" {
t.Fatalf("unexpected builtin inline style export: %s", actual)
}
+ for _, mode := range []int{0, 1} {
+ Conf.Appearance.Mode = mode
+ for _, source := range []string{
+ "color: var(--b3-card-error-color); background-color: var(--b3-card-error-background);",
+ "color: var(--b3-inline-builtin-error-color, var(--b3-card-error-color)); " +
+ "background-color: var(--b3-inline-builtin-error-background-color, var(--b3-card-error-background));",
+ } {
+ tree, node = inlineStyleThemeTestTree(source)
+ fillThemeStyleVar(tree)
+ expected := "color: #aabbcc; background-color: #ddeeff;"
+ if mode == 1 {
+ expected = "color: #123456; background-color: #654321;"
+ }
+ if actual := node.KramdownIAL[0][1]; actual != expected {
+ t.Fatalf("mode %d export of %q: %s", mode, source, actual)
+ }
+ }
+ }
}
func TestFillThemeStyleVarUsesCurrentInlineStyleMode(t *testing.T) {