Skip to content

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

:sparkles: Support custom inline element colors https://github.com/siyuan-note/siyuan/issues/13749

Daniele1793e9de39d
diff --git a/app/src/index.ts b/app/src/index.ts
index 05ee4f636e..e495023953 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -49,7 +49,7 @@ import {Files} from "./layout/dock/Files";
import {Tag} from "./layout/dock/Tag";
import {appearanceConfigApi} from "./config/tabs/appearanceRuntime";
import {renderSnippet} from "./config/util/snippets";
-import {refreshThemeStyle, setBodyHighlight} from "./util/assets";
+import {refreshThemeStyle, reloadInlineStyles, setBodyHighlight} from "./util/assets";
import {reloadSync} from "./util/reloadSync";
import {setTitle} from "./util/processTitle";
import {ensureUILayout} from "./util/ensureUILayout";
@@ -85,6 +85,9 @@ export class App {
case "setAppearance":
appearanceConfigApi.apply(data.data);
break;
+ case "reloadInlineStyles":
+ void reloadInlineStyles();
+ break;
case "setEntryVisibility":
applyEntryVisibility(data.data);
break;
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 75baba83d9..879c3e6e42 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -24,6 +24,19 @@ import {armKeyboardLock, callMobileAppShowKeyboard, canInput, keyboardLockUntil}
import {isNotEditBlock} from "../../protyle/wysiwyg/getBlock";
import {getMirror, getUndoRootID, hasUndoStateMirror, initMirror} from "../../protyle/undo/globalUndo";
import {getMobilePluginToolbarItems} from "./pluginToolbar";
+import {escapeHtml} from "../../util/escape";
+import {
+ encodeStyle1,
+ getInlineStyleByValue,
+ getInlineStyleIDFromValue,
+ getInlineStylePreview,
+ getInlineStylesCache,
+ getInlineStyleType,
+ INLINE_BACKGROUND_COLORS,
+ INLINE_FONT_COLORS,
+ TInlineStyleType,
+} from "../../protyle/toolbar/inlineStyle";
+import {openInlineStyleDialog} from "../../protyle/toolbar/inlineStyleDialog";
import {
getKeyboardHideResult,
getMovingSelectionEndpoint,
@@ -349,25 +362,45 @@ const getSlashItem = (value: string, icon: string, text: string, focus = "false"
export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
let colorHTML = "";
- ["", "var(--b3-font-color1)", "var(--b3-font-color2)", "var(--b3-font-color3)", "var(--b3-font-color4)",
- "var(--b3-font-color5)", "var(--b3-font-color6)", "var(--b3-font-color7)", "var(--b3-font-color8)",
- "var(--b3-font-color9)", "var(--b3-font-color10)", "var(--b3-font-color11)", "var(--b3-font-color12)",
- "var(--b3-font-color13)"].forEach((item, index) => {
+ INLINE_FONT_COLORS.forEach((item, index) => {
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 + 1 : window.siyuan.languages.default}</span>
+ <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${item ? index : window.siyuan.languages.default}</span>
</button>`;
});
let bgHTML = "";
- ["", "var(--b3-font-background1)", "var(--b3-font-background2)", "var(--b3-font-background3)", "var(--b3-font-background4)",
- "var(--b3-font-background5)", "var(--b3-font-background6)", "var(--b3-font-background7)", "var(--b3-font-background8)",
- "var(--b3-font-background9)", "var(--b3-font-background10)", "var(--b3-font-background11)", "var(--b3-font-background12)",
- "var(--b3-font-background13)"].forEach((item, index) => {
+ INLINE_BACKGROUND_COLORS.forEach((item, index) => {
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 + 1 : window.siyuan.languages.default}</span>
+ <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${item ? index : window.siyuan.languages.default}</span>
</button>`;
});
+ let customColorHTML = "";
+ let customBackgroundHTML = "";
+ let customStyleHTML = "";
+ getInlineStylesCache().styles.forEach(style => {
+ const type = getInlineStyleType(style);
+ if (!type) {
+ return;
+ }
+ const preview = getInlineStylePreview(style);
+ const html = `<button class="keyboard__slash-item" data-type="${type}" data-inline-style-id="${style.id}">
+ <span class="keyboard__slash-icon" style="${preview.color ? `color:${preview.color};` : ""}${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}">A</span>
+ <span class="keyboard__slash-text">${escapeHtml(style.name)}</span>
+</button>`;
+ if (type === "color") {
+ customColorHTML += html;
+ } else if (type === "backgroundColor") {
+ customBackgroundHTML += html;
+ } else {
+ customStyleHTML += html;
+ }
+ });
+ 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="#iconAdd"></use></svg>
+ <span class="keyboard__slash-text">${window.siyuan.languages.manage}</span>
+</button>`;
const nodeElements = getFontNodeElements(protyle);
let disableFont = false;
@@ -387,17 +420,21 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
<div data-id="lastUsedWrap" class="keyboard__slash-block">`;
lastFonts.forEach((item: string) => {
const lastFontStatus = item.split(Constants.ZWSP);
+ const inlineStyleID = getInlineStyleIDFromValue(item);
+ const inlineStyle = getInlineStyleByValue(item);
+ const customLabel = inlineStyle ? escapeHtml(inlineStyle.name) :
+ (inlineStyleID ? window.siyuan.languages.custom : "");
switch (lastFontStatus[0]) {
case "color":
lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
<span class="keyboard__slash-icon" ${lastFontStatus[1] ? `style="color:${lastFontStatus[1]}"` : ""} >A</span>
- <span class="keyboard__slash-text">${window.siyuan.languages.colorFont} ${lastFontStatus[1] ? parseInt(lastFontStatus[1].replace("var(--b3-font-color", "")) + 1 : window.siyuan.languages.default}</span>
+ <span class="keyboard__slash-text">${customLabel || window.siyuan.languages.colorFont + " " + (lastFontStatus[1]?.match(/^var\(--b3-font-color(\d+)\)$/)?.[1] || window.siyuan.languages.default)}</span>
</button>`;
break;
case "backgroundColor":
lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
<span class="keyboard__slash-icon" ${lastFontStatus[1] ? `style="background-color:${lastFontStatus[1]}"` : ""}>A</span>
- <span class="keyboard__slash-text">${window.siyuan.languages.colorPrimary} ${lastFontStatus[1] ? parseInt(lastFontStatus[1].replace("var(--b3-font-background", "")) + 1 : window.siyuan.languages.default}</span>
+ <span class="keyboard__slash-text">${customLabel || window.siyuan.languages.colorPrimary + " " + (lastFontStatus[1]?.match(/^var\(--b3-font-background(\d+)\)$/)?.[1] || window.siyuan.languages.default)}</span>
</button>`;
break;
case "style2":
@@ -419,9 +456,10 @@ 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];
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">${window.siyuan.languages[lastFontStatus[2].replace("var(--b3-card-", "").replace("-color)", "") + "Style"]}</span>
+ <span class="keyboard__slash-text">${customLabel || (builtInStyle ? window.siyuan.languages[builtInStyle + "Style"] : window.siyuan.languages.color)}</span>
</button>`;
} else {
lastColorHTML += `<button class="keyboard__slash-item" data-type="${lastFontStatus[0]}">
@@ -464,14 +502,20 @@ export const renderTextMenu = (protyle: IProtyle, toolbarElement: Element) => {
<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>
+ ${customStyleHTML}
+ ${getManageHTML("style1")}
</div>
<div data-id="colorFont" class="keyboard__slash-title">${window.siyuan.languages.colorFont}</div>
<div data-id="colorFontWrap" class="keyboard__slash-block">
${colorHTML}
+ ${customColorHTML}
+ ${getManageHTML("color")}
</div>
<div data-id="colorPrimary" class="keyboard__slash-title">${window.siyuan.languages.colorPrimary}</div>
<div data-id="colorPrimaryWrap" class="keyboard__slash-block">
${bgHTML}
+ ${customBackgroundHTML}
+ ${getManageHTML("backgroundColor")}
</div>
<div data-id="fontStyle" class="keyboard__slash-title">${window.siyuan.languages.fontStyle}</div>
<div data-id="fontStyleWrap" class="keyboard__slash-block">
@@ -1102,6 +1146,14 @@ export const initKeyboardToolbar = () => {
const protyle = getCurrentEditor()?.protyle;
const target = event.target as HTMLElement;
const slashBtnElement = hasClosestByClassName(event.target as HTMLElement, "keyboard__slash-item");
+ if (slashBtnElement && slashBtnElement.dataset.action === "manageInlineStyle") {
+ openInlineStyleDialog(slashBtnElement.dataset.inlineStyleType as TInlineStyleType, () => {
+ renderTextMenu(protyle, toolbarElement);
+ });
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
if (slashBtnElement && !slashBtnElement.getAttribute("data-type")) {
const dataValue = decodeURIComponent(slashBtnElement.getAttribute("data-value"));
if (dataValue === Constants.ZWSP + 3) {
@@ -1136,7 +1188,7 @@ export const initKeyboardToolbar = () => {
const focusRange = !buttonElement.classList.contains("keyboard__slash-item");
if (type === "style1") {
fontEvent(protyle, nodeElements, type,
- itemElement.style.backgroundColor + Constants.ZWSP + itemElement.style.color, focusRange);
+ 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/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index f0693fc9bf..fb4fd59ffe 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -14,6 +14,7 @@ import {redirectToCheckAuth} from "../../util/pathName";
import {reloadSync} from "../../util/reloadSync";
import {activateOnboarding} from "../../onboarding";
import {updateServerAddresses} from "../../config/tabs/accessRuntime";
+import {reloadInlineStyles} from "../../util/assets";
let statusTimeout: number;
const statusElement = document.querySelector("#status") as HTMLElement;
@@ -40,6 +41,9 @@ export const onMessage = (app: App, data: IWebSocketData) => {
case "setAppearance":
window.location.reload();
break;
+ case "reloadInlineStyles":
+ void reloadInlineStyles();
+ break;
case "setSnippet":
window.siyuan.config.snippet = data.data;
renderSnippet();
diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.ts
index 17183df4db..3a6514d158 100644
--- a/app/src/protyle/toolbar/Font.ts
+++ b/app/src/protyle/toolbar/Font.ts
@@ -6,6 +6,21 @@ import {hasClosestBlock, hasClosestByAttribute} from "../util/hasClosest";
import {updateBatchTransaction} from "../wysiwyg/transaction";
import {lineNumberRender} from "../render/highlightRender";
import {closeSubElement} from "./subElementLifecycle";
+import {escapeAttr} from "../../util/escape";
+import {
+ decodeStyle1,
+ encodeStyle1,
+ getInlineStyleByValue,
+ getInlineStyleIDFromValue,
+ getInlineStylePreview,
+ getInlineStylesCache,
+ getInlineStyleType,
+ getRecentInlineStyleKey,
+ INLINE_BACKGROUND_COLORS,
+ INLINE_FONT_COLORS,
+ TInlineStyleType,
+} from "./inlineStyle";
+import {openInlineStyleDialog} from "./inlineStyleDialog";
const MAX_RECENT_FONT_STYLES = 14;
@@ -104,19 +119,33 @@ export const convertFontSize = (fontSize: string, unit: "px" | "em", baseFontSiz
export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
onChange?: (type: string, color?: string) => void) => {
let colorHTML = "";
- ["", "var(--b3-font-color1)", "var(--b3-font-color2)", "var(--b3-font-color3)", "var(--b3-font-color4)",
- "var(--b3-font-color5)", "var(--b3-font-color6)", "var(--b3-font-color7)", "var(--b3-font-color8)",
- "var(--b3-font-color9)", "var(--b3-font-color10)", "var(--b3-font-color11)", "var(--b3-font-color12)",
- "var(--b3-font-color13)"].forEach((item) => {
+ INLINE_FONT_COLORS.forEach((item) => {
colorHTML += `<button ${item ? `class="color__square" style="color:${item}"` : `class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.default}"`} data-type="color">A</button>`;
});
let bgHTML = "";
- ["", "var(--b3-font-background1)", "var(--b3-font-background2)", "var(--b3-font-background3)", "var(--b3-font-background4)",
- "var(--b3-font-background5)", "var(--b3-font-background6)", "var(--b3-font-background7)", "var(--b3-font-background8)",
- "var(--b3-font-background9)", "var(--b3-font-background10)", "var(--b3-font-background11)", "var(--b3-font-background12)",
- "var(--b3-font-background13)"].forEach((item) => {
+ INLINE_BACKGROUND_COLORS.forEach((item) => {
bgHTML += `<button ${item ? `class="color__square" style="background-color:${item}"` : `class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.default}"`} data-type="backgroundColor"></button>`;
});
+ let customColorHTML = "";
+ let customBackgroundHTML = "";
+ let customStyleHTML = "";
+ getInlineStylesCache().styles.forEach(style => {
+ const type = getInlineStyleType(style);
+ if (!type) {
+ return;
+ }
+ const preview = getInlineStylePreview(style);
+ const html = `<button class="color__square ariaLabel" data-position="3south" aria-label="${escapeAttr(style.name)}" data-inline-style-id="${style.id}" data-type="${type}" style="${preview.color ? `color:${preview.color};` : ""}${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}">${type === "backgroundColor" ? "" : "A"}</button>`;
+ if (type === "color") {
+ customColorHTML += html;
+ } else if (type === "backgroundColor") {
+ customBackgroundHTML += html;
+ } else {
+ customStyleHTML += html;
+ }
+ });
+ const getManageHTML = (type: TInlineStyleType) => window.siyuan.config.readonly || window.siyuan.isPublish ? "" :
+ `<button class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.manage}" data-action="manageInlineStyle" data-inline-style-type="${type}"><svg class="svg--mid"><use xlink:href="#iconAdd"></use></svg></button>`;
const element = document.createElement("div");
element.classList.add("protyle-font");
@@ -139,12 +168,15 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
<div data-id="lastUsedWrap" class="fn__flex fn__flex-wrap" style="align-items: center">`;
lastFonts.forEach((item: string) => {
const lastFontStatus = item.split(Constants.ZWSP);
+ const customStyle = getInlineStyleByValue(item);
+ const customLabel = customStyle ? escapeAttr(customStyle.name) :
+ (getInlineStyleIDFromValue(item) ? window.siyuan.languages.custom : "");
switch (lastFontStatus[0]) {
case "color":
- lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.colorFont}${lastFontStatus[1] ? "" : " " + window.siyuan.languages.default}" ${lastFontStatus[1] ? `style="color:${lastFontStatus[1]}"` : ""} data-type="${lastFontStatus[0]}">A</button>`;
+ lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${customLabel || window.siyuan.languages.colorFont + (lastFontStatus[1] ? "" : " " + window.siyuan.languages.default)}" ${lastFontStatus[1] ? `style="color:${lastFontStatus[1]}"` : ""} data-type="${lastFontStatus[0]}">A</button>`;
break;
case "backgroundColor":
- lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.colorPrimary}${lastFontStatus[1] ? "" : " " + window.siyuan.languages.default}" ${lastFontStatus[1] ? `style="background-color:${lastFontStatus[1]}"` : ""} data-type="${lastFontStatus[0]}"></button>`;
+ lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${customLabel || window.siyuan.languages.colorPrimary + (lastFontStatus[1] ? "" : " " + window.siyuan.languages.default)}" ${lastFontStatus[1] ? `style="background-color:${lastFontStatus[1]}"` : ""} data-type="${lastFontStatus[0]}"></button>`;
break;
case "style2":
lastColorHTML += `<button data-type="${lastFontStatus[0]}" class="color__square ariaLabel" data-position="3south" aria-label="${window.siyuan.languages.hollow}" style="-webkit-text-stroke: 0.2px var(--b3-theme-on-background);-webkit-text-fill-color : transparent;">A</button>`;
@@ -158,7 +190,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
}
break;
case "style1":
- lastColorHTML += `<button class="color__square ariaLabel" data-position="3south" aria-label="${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>`;
+ 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>`;
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>`;
@@ -181,18 +213,24 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
<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>
+ ${customStyleHTML}
+ ${getManageHTML("style1")}
</div>
<div class="fn__hr"></div>
<div data-id="colorFont">${window.siyuan.languages.colorFont}</div>
<div class="fn__hr--small"></div>
<div data-id="colorFontWrap" class="fn__flex fn__flex-wrap">
${colorHTML}
+ ${customColorHTML}
+ ${getManageHTML("color")}
</div>
<div class="fn__hr"></div>
<div data-id="colorPrimary">${window.siyuan.languages.colorPrimary}</div>
<div class="fn__hr--small"></div>
<div data-id="colorPrimaryWrap" class="fn__flex fn__flex-wrap">
${bgHTML}
+ ${customBackgroundHTML}
+ ${getManageHTML("backgroundColor")}
</div>
<div class="fn__hr"></div>
<div data-id="fontStyle">${window.siyuan.languages.fontStyle}</div>
@@ -234,8 +272,10 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
while (target && !target.isEqualNode(element)) {
const dataType = target.getAttribute("data-type");
if (target.tagName === "BUTTON") {
- if (dataType === "style1") {
- applyFontStyle(dataType, target.style.backgroundColor + Constants.ZWSP + target.style.color);
+ if (target.dataset.action === "manageInlineStyle") {
+ openInlineStyleDialog(target.dataset.inlineStyleType as TInlineStyleType);
+ } else if (dataType === "style1") {
+ applyFontStyle(dataType, encodeStyle1(target.style.backgroundColor, target.style.color));
} else if (dataType === "fontSize") {
applyFontStyle(dataType, target.getAttribute("data-value"));
} else if (dataType === "backgroundColor") {
@@ -291,14 +331,16 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: str
focusRange = true, onChange?: (type: string, color?: string) => void) => {
let localFontStyles = window.siyuan.storage[Constants.LOCAL_FONTSTYLES];
if (type) {
- localFontStyles = [...new Set([`${type}${Constants.ZWSP}${color}`, ...localFontStyles])]
- .slice(0, MAX_RECENT_FONT_STYLES);
+ const value = `${type}${Constants.ZWSP}${color}`;
+ const recentKey = getRecentInlineStyleKey(value);
+ localFontStyles = [value, ...localFontStyles.filter((item: string) =>
+ getRecentInlineStyleKey(item) !== recentKey)].slice(0, MAX_RECENT_FONT_STYLES);
window.siyuan.storage[Constants.LOCAL_FONTSTYLES] = localFontStyles;
setStorageVal(Constants.LOCAL_FONTSTYLES, window.siyuan.storage[Constants.LOCAL_FONTSTYLES]);
} else {
if (localFontStyles.length === 0) {
type = "style1";
- color = "var(--b3-card-error-color)" + Constants.ZWSP + "var(--b3-card-error-background)";
+ color = encodeStyle1("var(--b3-card-error-background)", "var(--b3-card-error-color)");
} else {
const fontStyles = localFontStyles[0].split(Constants.ZWSP);
type = fontStyles.splice(0, 1)[0];
@@ -320,10 +362,10 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: str
e.style.fontSize = "";
e.style.removeProperty("--b3-parent-background");
} else if (type === "style1") {
- const colorList = color.split(Constants.ZWSP);
- e.style.backgroundColor = colorList[0];
- e.style.color = colorList[1];
- e.style.setProperty("--b3-parent-background", colorList[0]);
+ const style = decodeStyle1(color);
+ e.style.backgroundColor = style.backgroundColor;
+ e.style.color = style.color;
+ e.style.setProperty("--b3-parent-background", style.backgroundColor);
} else if (type === "style2") {
e.style.webkitTextStroke = "0.2px var(--b3-theme-on-background)";
e.style.webkitTextFillColor = "transparent";
@@ -397,10 +439,12 @@ export const setFontStyle = (textElement: HTMLElement, textOption: ITextOption)
case "backgroundColor":
textElement.style.backgroundColor = textOption.color;
break;
- case "style1":
- textElement.style.backgroundColor = textOption.color.split(Constants.ZWSP)[0];
- textElement.style.color = textOption.color.split(Constants.ZWSP)[1];
+ case "style1": {
+ const style = decodeStyle1(textOption.color);
+ textElement.style.backgroundColor = style.backgroundColor;
+ textElement.style.color = style.color;
break;
+ }
case "style2":
textElement.style.webkitTextStroke = "0.2px var(--b3-theme-on-background)";
textElement.style.webkitTextFillColor = "transparent";
@@ -485,8 +529,9 @@ export const hasSameTextStyle = (currentElement: HTMLElement, sideElement: HTMLE
return textObj.color === sideElement.style.backgroundColor;
}
if (textObj.type === "style1") {
- return textObj.color.split(Constants.ZWSP)[0] === sideElement.style.color &&
- textObj.color.split(Constants.ZWSP)[1] === sideElement.style.backgroundColor;
+ const style = decodeStyle1(textObj.color);
+ return style.backgroundColor === sideElement.style.backgroundColor &&
+ style.color === sideElement.style.color;
}
if (textObj.type === "style2") {
return "transparent" === sideElement.style.webkitTextFillColor &&
diff --git a/app/src/protyle/toolbar/inlineStyle.test.ts b/app/src/protyle/toolbar/inlineStyle.test.ts
new file mode 100644
index 0000000000..97382442a6
--- /dev/null
+++ b/app/src/protyle/toolbar/inlineStyle.test.ts
@@ -0,0 +1,126 @@
+import {before, describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import type {IInlineStyle} from "./inlineStyle";
+
+let inlineStyle: typeof import("./inlineStyle");
+
+before(async () => {
+ Object.assign(globalThis, {
+ NODE_ENV: "test",
+ SIYUAN_VERSION: "test",
+ });
+ inlineStyle = await import("./inlineStyle");
+});
+
+const combinedStyle: IInlineStyle = {
+ id: "20260821120000-abcdefg",
+ name: "Combined",
+ light: {
+ color: "#112233",
+ backgroundColor: "#ddeeff",
+ },
+ dark: {
+ color: "#fefefe",
+ backgroundColor: "#223344",
+ },
+};
+
+describe("normalizeInlineStyles", () => {
+ it("keeps paired light and dark colors and removes invalid data", () => {
+ assert.deepEqual(inlineStyle.normalizeInlineStyles({
+ version: 9,
+ styles: [combinedStyle, {
+ id: combinedStyle.id,
+ name: "Duplicate",
+ light: {color: "#ffffff"},
+ dark: {color: "#000000"},
+ }, {
+ id: "20260821120001-bbcdefg",
+ name: " Background ",
+ light: {color: "invalid", backgroundColor: "#AABBCC"},
+ dark: {backgroundColor: "#001122"},
+ }, {
+ id: "invalid-id",
+ name: "Invalid",
+ light: {color: "#ffffff"},
+ dark: {color: "#000000"},
+ }],
+ }), {
+ version: 1,
+ styles: [combinedStyle, {
+ id: "20260821120001-bbcdefg",
+ name: "Background",
+ light: {backgroundColor: "#aabbcc"},
+ dark: {backgroundColor: "#001122"},
+ }],
+ });
+ });
+
+ it("limits names by Unicode code points without splitting surrogate pairs", () => {
+ const normalized = inlineStyle.normalizeInlineStyles({
+ version: 1,
+ styles: [{
+ id: "20260821120002-cbcdefg",
+ name: "😀".repeat(65),
+ light: {color: "#ffffff"},
+ dark: {color: "#000000"},
+ }],
+ });
+ assert.equal([...normalized.styles[0].name].length, 64);
+ assert.equal(normalized.styles[0].name.endsWith("😀"), true);
+ });
+});
+
+describe("inline style values", () => {
+ it("infers the legacy appearance type from available properties", () => {
+ assert.equal(inlineStyle.getInlineStyleType(combinedStyle), "style1");
+ assert.equal(inlineStyle.getInlineStyleType({...combinedStyle, light: {color: "#112233"}, dark: {color: "#ffffff"}}), "color");
+ assert.equal(inlineStyle.getInlineStyleType({
+ ...combinedStyle,
+ light: {backgroundColor: "#ddeeff"},
+ dark: {backgroundColor: "#223344"},
+ }), "backgroundColor");
+ });
+
+ it("encodes combined styles as background then foreground", () => {
+ const encoded = inlineStyle.encodeStyle1("#ddeeff", "#112233");
+ assert.equal(encoded, "#ddeeff\u200b#112233");
+ assert.deepEqual(inlineStyle.decodeStyle1(encoded), {
+ backgroundColor: "#ddeeff",
+ color: "#112233",
+ });
+ });
+
+ it("builds variable references with current-mode fallbacks", () => {
+ assert.deepEqual(inlineStyle.getInlineStyleApplication(combinedStyle, "dark"), {
+ type: "style1",
+ color: "var(--b3-inline-style-20260821120000-abcdefg-background-color, #223344)" +
+ "\u200b" +
+ "var(--b3-inline-style-20260821120000-abcdefg-color, #fefefe)",
+ });
+ });
+});
+
+describe("getInlineStylesCSS", () => {
+ it("generates isolated light and dark variables", () => {
+ assert.equal(inlineStyle.getInlineStylesCSS({version: 1, 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;
+}`);
+ });
+});
+
+describe("recent inline styles", () => {
+ it("extracts a stable preset ID and ignores changing fallbacks", () => {
+ const first = "color\u200b" +
+ "var(--b3-inline-style-20260821120000-abcdefg-color, #112233)";
+ const second = "color\u200b" +
+ "var(--b3-inline-style-20260821120000-abcdefg-color, #445566)";
+ assert.equal(inlineStyle.getInlineStyleIDFromValue(first), combinedStyle.id);
+ assert.equal(inlineStyle.getRecentInlineStyleKey(first), inlineStyle.getRecentInlineStyleKey(second));
+ });
+});
diff --git a/app/src/protyle/toolbar/inlineStyle.ts b/app/src/protyle/toolbar/inlineStyle.ts
new file mode 100644
index 0000000000..520d6e9e7f
--- /dev/null
+++ b/app/src/protyle/toolbar/inlineStyle.ts
@@ -0,0 +1,277 @@
+export type TInlineStyleType = "color" | "backgroundColor" | "style1";
+export type TInlineStyleMode = "light" | "dark";
+export type TInlineStyleProperty = "color" | "backgroundColor";
+
+export interface IInlineStyleColors {
+ color?: string;
+ backgroundColor?: string;
+}
+
+export interface IInlineStyle {
+ id: string;
+ name: string;
+ light: IInlineStyleColors;
+ dark: IInlineStyleColors;
+}
+
+export interface IInlineStyles {
+ version: 1;
+ styles: IInlineStyle[];
+}
+
+export interface IInlineStyleApplication {
+ type: TInlineStyleType;
+ color: string;
+}
+
+export const INLINE_STYLE_EMPTY: IInlineStyles = {
+ version: 1,
+ styles: [],
+};
+
+export const MAX_INLINE_STYLES = 64;
+export const MAX_INLINE_STYLE_NAME_LENGTH = 64;
+
+export const INLINE_FONT_COLORS = [
+ "",
+ ...Array.from({length: 13}, (_, index) => `var(--b3-font-color${index + 1})`),
+];
+
+export const INLINE_BACKGROUND_COLORS = [
+ "",
+ ...Array.from({length: 13}, (_, 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";
+
+let inlineStylesCache: IInlineStyles | undefined;
+let inlineStylesLoadPromise: Promise<IInlineStyles> | undefined;
+let inlineStylesLoadPromiseGeneration = 0;
+let inlineStylesRequestGeneration = 0;
+
+const normalizeColor = (value: unknown) => {
+ if (typeof value !== "string" || !INLINE_STYLE_COLOR_PATTERN.test(value)) {
+ return;
+ }
+ return value.toLowerCase();
+};
+
+const normalizeStyle = (value: unknown): IInlineStyle | undefined => {
+ if (!value || typeof value !== "object") {
+ return;
+ }
+ const style = value as Partial<IInlineStyle>;
+ if (typeof style.id !== "string" || !INLINE_STYLE_ID_PATTERN.test(style.id) ||
+ typeof style.name !== "string" || !style.name.trim()) {
+ return;
+ }
+ const lightColor = normalizeColor(style.light?.color);
+ const darkColor = normalizeColor(style.dark?.color);
+ const lightBackground = normalizeColor(style.light?.backgroundColor);
+ const darkBackground = normalizeColor(style.dark?.backgroundColor);
+ const colors: { light: IInlineStyleColors, dark: IInlineStyleColors } = {
+ light: {},
+ dark: {},
+ };
+ if (lightColor && darkColor) {
+ colors.light.color = lightColor;
+ colors.dark.color = darkColor;
+ }
+ if (lightBackground && darkBackground) {
+ colors.light.backgroundColor = lightBackground;
+ colors.dark.backgroundColor = darkBackground;
+ }
+ if (!colors.light.color && !colors.light.backgroundColor) {
+ return;
+ }
+ return {
+ id: style.id,
+ name: [...style.name.trim()].slice(0, MAX_INLINE_STYLE_NAME_LENGTH).join(""),
+ ...colors,
+ };
+};
+
+export const normalizeInlineStyles = (value: unknown): IInlineStyles => {
+ const styles: IInlineStyle[] = [];
+ const ids = new Set<string>();
+ if (value && typeof value === "object" && Array.isArray((value as Partial<IInlineStyles>).styles)) {
+ (value as Partial<IInlineStyles>).styles.forEach(item => {
+ if (styles.length >= MAX_INLINE_STYLES) {
+ return;
+ }
+ const style = normalizeStyle(item);
+ if (style && !ids.has(style.id)) {
+ ids.add(style.id);
+ styles.push(style);
+ }
+ });
+ }
+ return {
+ version: 1,
+ styles,
+ };
+};
+
+export const setInlineStylesCache = (data: unknown) => {
+ inlineStylesCache = normalizeInlineStyles(data);
+ return inlineStylesCache;
+};
+
+export const getInlineStylesCache = () => inlineStylesCache || INLINE_STYLE_EMPTY;
+
+export const loadInlineStyles = (force = false): Promise<IInlineStyles> => {
+ if (!force && inlineStylesCache) {
+ return Promise.resolve(inlineStylesCache);
+ }
+ if (!force && inlineStylesLoadPromise) {
+ return inlineStylesLoadPromise;
+ }
+ const generation = ++inlineStylesRequestGeneration;
+ inlineStylesLoadPromiseGeneration = generation;
+ const request = (async () => {
+ try {
+ const {fetchSyncPost} = await import("../../util/fetch");
+ const response = await fetchSyncPost("/api/storage/getInlineStyles");
+ if (generation !== inlineStylesRequestGeneration) {
+ return getInlineStylesCache();
+ }
+ if (response?.code !== 0) {
+ return setInlineStylesCache(INLINE_STYLE_EMPTY);
+ }
+ return setInlineStylesCache(response.data);
+ } catch (error) {
+ if (generation !== inlineStylesRequestGeneration) {
+ return getInlineStylesCache();
+ }
+ if (force && inlineStylesCache) {
+ throw error;
+ }
+ return setInlineStylesCache(INLINE_STYLE_EMPTY);
+ } finally {
+ if (inlineStylesLoadPromiseGeneration === generation) {
+ inlineStylesLoadPromise = undefined;
+ inlineStylesLoadPromiseGeneration = 0;
+ }
+ }
+ })();
+ inlineStylesLoadPromise = request;
+ return request;
+};
+
+export const saveInlineStyles = async (data: IInlineStyles) => {
+ const normalized = normalizeInlineStyles(data);
+ const [{Constants}, {fetchSyncPost}] = await Promise.all([
+ import("../../constants"),
+ import("../../util/fetch"),
+ ]);
+ const response = await fetchSyncPost("/api/storage/setInlineStyles", {
+ ...normalized,
+ app: Constants.SIYUAN_APPID,
+ });
+ if (response?.code !== 0) {
+ return response;
+ }
+ inlineStylesRequestGeneration++;
+ setInlineStylesCache(response.data || normalized);
+ return response;
+};
+
+export const getInlineStyleType = (style: IInlineStyle): TInlineStyleType | undefined => {
+ const hasColor = !!style.light.color && !!style.dark.color;
+ const hasBackground = !!style.light.backgroundColor && !!style.dark.backgroundColor;
+ if (hasColor && hasBackground) {
+ return "style1";
+ }
+ if (hasColor) {
+ return "color";
+ }
+ if (hasBackground) {
+ return "backgroundColor";
+ }
+};
+
+export const getCurrentInlineStyleMode = (): TInlineStyleMode =>
+ document.documentElement.getAttribute("data-theme-mode") === "dark" ? "dark" : "light";
+
+export const getInlineStyleVariableName = (id: string, property: TInlineStyleProperty) =>
+ `--b3-inline-style-${id}-${property === "color" ? "color" : "background-color"}`;
+
+export const getInlineStylePropertyValue = (style: IInlineStyle, property: TInlineStyleProperty,
+ mode = getCurrentInlineStyleMode()) => {
+ const fallback = style[mode][property];
+ if (!fallback) {
+ return "";
+ }
+ return `var(${getInlineStyleVariableName(style.id, property)}, ${fallback})`;
+};
+
+export const encodeStyle1 = (backgroundColor = "", color = "") =>
+ backgroundColor + INLINE_STYLE_SEPARATOR + color;
+
+export const decodeStyle1 = (value = "") => {
+ const colors = value.split(INLINE_STYLE_SEPARATOR);
+ return {
+ backgroundColor: colors[0] || "",
+ color: colors[1] || "",
+ };
+};
+
+export const getInlineStyleApplication = (style: IInlineStyle,
+ mode = getCurrentInlineStyleMode()): IInlineStyleApplication | undefined => {
+ const type = getInlineStyleType(style);
+ if (!type) {
+ return;
+ }
+ const color = getInlineStylePropertyValue(style, "color", mode);
+ const backgroundColor = getInlineStylePropertyValue(style, "backgroundColor", mode);
+ return {
+ type,
+ color: type === "style1" ? encodeStyle1(backgroundColor, color) :
+ (type === "color" ? color : backgroundColor),
+ };
+};
+
+export const getInlineStylePreview = (style: IInlineStyle, mode = getCurrentInlineStyleMode(), variables = true) => ({
+ color: style[mode].color ? (variables ? getInlineStylePropertyValue(style, "color", mode) : style[mode].color) : "",
+ backgroundColor: style[mode].backgroundColor ?
+ (variables ? getInlineStylePropertyValue(style, "backgroundColor", mode) : style[mode].backgroundColor) : "",
+});
+
+export const getInlineStyleIDFromValue = (value?: string) =>
+ value?.match(INLINE_STYLE_VARIABLE_PATTERN)?.[1];
+
+export const getInlineStyleByID = (id?: string, data = getInlineStylesCache()) =>
+ id ? data.styles.find(item => item.id === id) : undefined;
+
+export const getInlineStyleByValue = (value?: string, data = getInlineStylesCache()) =>
+ getInlineStyleByID(getInlineStyleIDFromValue(value), data);
+
+export const getRecentInlineStyleKey = (value: string) => {
+ const id = getInlineStyleIDFromValue(value);
+ if (!id) {
+ return value;
+ }
+ return value.split(INLINE_STYLE_SEPARATOR)[0] + INLINE_STYLE_SEPARATOR + id;
+};
+
+export const getInlineStylesCSS = (data = getInlineStylesCache()) => {
+ const normalized = normalizeInlineStyles(data);
+ return (["light", "dark"] as TInlineStyleMode[]).map(mode => {
+ const declarations: string[] = [];
+ normalized.styles.forEach(style => {
+ if (style[mode].color) {
+ declarations.push(` ${getInlineStyleVariableName(style.id, "color")}: ${style[mode].color};`);
+ }
+ if (style[mode].backgroundColor) {
+ declarations.push(` ${getInlineStyleVariableName(style.id, "backgroundColor")}: ${style[mode].backgroundColor};`);
+ }
+ });
+ if (declarations.length === 0) {
+ return "";
+ }
+ return `:root[data-theme-mode="${mode}"] {\n${declarations.join("\n")}\n}`;
+ }).filter(Boolean).join("\n");
+};
diff --git a/app/src/protyle/toolbar/inlineStyleDialog.ts b/app/src/protyle/toolbar/inlineStyleDialog.ts
new file mode 100644
index 0000000000..27b1f1864d
--- /dev/null
+++ b/app/src/protyle/toolbar/inlineStyleDialog.ts
@@ -0,0 +1,314 @@
+import {Dialog} from "../../dialog";
+import {showMessage} from "../../dialog/message";
+import {escapeAttr, escapeHtml} from "../../util/escape";
+import {isMobile} from "../../util/functions";
+import {
+ getCurrentInlineStyleMode,
+ getInlineStylePreview,
+ getInlineStylesCache,
+ getInlineStyleType,
+ IInlineStyle,
+ IInlineStyles,
+ MAX_INLINE_STYLE_NAME_LENGTH,
+ MAX_INLINE_STYLES,
+ saveInlineStyles,
+ TInlineStyleType,
+} from "./inlineStyle";
+
+const escapeAttribute = (value: string) => escapeAttr(value);
+
+const getTypeLabel = (type: TInlineStyleType) => {
+ if (type === "color") {
+ return window.siyuan.languages.colorFont;
+ }
+ if (type === "backgroundColor") {
+ return window.siyuan.languages.colorPrimary;
+ }
+ return window.siyuan.languages.color;
+};
+
+const cloneInlineStyles = (): IInlineStyles => JSON.parse(JSON.stringify(getInlineStylesCache())) as IInlineStyles;
+
+const renderPreviewStyle = (style: IInlineStyle) => {
+ const preview = getInlineStylePreview(style, getCurrentInlineStyleMode(), false);
+ return `${preview.color ? `color:${preview.color};` : ""}` +
+ `${preview.backgroundColor ? `background-color:${preview.backgroundColor};` : ""}`;
+};
+
+export const openInlineStyleDialog = (initialType: TInlineStyleType = "backgroundColor",
+ onChange?: (data: IInlineStyles) => void) => {
+ if (window.siyuan.config.readonly || window.siyuan.isPublish) {
+ return;
+ }
+ const draft = cloneInlineStyles();
+ let editingIndex: number | undefined;
+ let saving = false;
+ const dialog = new Dialog({
+ title: window.siyuan.languages.color,
+ width: isMobile() ? "92vw" : "600px",
+ content: `<div class="b3-dialog__content" style="display:flex;flex-direction:column;gap:12px;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>
+ <button class="b3-button b3-button--outline" data-action="new" type="button" style="margin-top:8px">
+ <svg><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.new}
+ </button>
+ </div>
+ <div data-panel="editor" class="fn__none">
+ <label class="b3-label fn__flex">
+ <span style="min-width:96px">${window.siyuan.languages.name}</span>
+ <input class="b3-text-field fn__flex-1" data-field="name">
+ </label>
+ <label class="b3-label fn__flex">
+ <span style="min-width:96px">${window.siyuan.languages.color}</span>
+ <select class="b3-select fn__flex-1" data-field="type">
+ <option value="color">${window.siyuan.languages.colorFont}</option>
+ <option value="backgroundColor">${window.siyuan.languages.colorPrimary}</option>
+ <option value="style1">${window.siyuan.languages.color}</option>
+ </select>
+ </label>
+ <div class="fn__flex" style="align-items:stretch;gap:12px;flex-wrap:wrap">
+ <div class="b3-label fn__flex-1" style="min-width:200px">
+ <div>${window.siyuan.languages.themeLight}</div>
+ <label class="fn__flex" data-property="color" style="margin-top:8px">
+ <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>
+ <input class="b3-text-field" data-field="lightColor" type="color">
+ </label>
+ <label class="fn__flex" data-property="backgroundColor" style="margin-top:8px">
+ <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>
+ <input class="b3-text-field" data-field="lightBackgroundColor" type="color">
+ </label>
+ </div>
+ <div class="b3-label fn__flex-1" style="min-width:200px">
+ <div>${window.siyuan.languages.themeDark}</div>
+ <label class="fn__flex" data-property="color" style="margin-top:8px">
+ <span class="fn__flex-1">${window.siyuan.languages.colorFont}</span>
+ <input class="b3-text-field" data-field="darkColor" type="color">
+ </label>
+ <label class="fn__flex" data-property="backgroundColor" style="margin-top:8px">
+ <span class="fn__flex-1">${window.siyuan.languages.colorPrimary}</span>
+ <input class="b3-text-field" data-field="darkBackgroundColor" type="color">
+ </label>
+ </div>
+ </div>
+ <div class="fn__flex" style="justify-content:flex-end;margin-top:12px">
+ <button class="b3-button b3-button--cancel" data-action="cancelEdit" type="button">${window.siyuan.languages.cancel}</button>
+ <span class="fn__space"></span>
+ <button class="b3-button b3-button--text" data-action="confirmEdit" type="button">${window.siyuan.languages.confirm}</button>
+ </div>
+ </div>
+</div>
+<div class="b3-dialog__action" data-panel="actions">
+ <button class="b3-button b3-button--cancel" data-action="cancel" type="button">${window.siyuan.languages.cancel}</button>
+ <div class="fn__space"></div>
+ <button class="b3-button b3-button--text" data-action="save" type="button">${window.siyuan.languages.save}</button>
+</div>`,
+ });
+ const listPanel = dialog.element.querySelector('[data-panel="list"]') as HTMLElement;
+ const editorPanel = dialog.element.querySelector('[data-panel="editor"]') as HTMLElement;
+ const actionsPanel = dialog.element.querySelector('[data-panel="actions"]') as HTMLElement;
+ const listElement = dialog.element.querySelector('[data-type="inlineStyleList"]') as HTMLElement;
+ const newElement = dialog.element.querySelector('[data-action="new"]') as HTMLButtonElement;
+ const nameElement = dialog.element.querySelector('[data-field="name"]') as HTMLInputElement;
+ const typeElement = dialog.element.querySelector('[data-field="type"]') as HTMLSelectElement;
+ const lightColorElement = dialog.element.querySelector('[data-field="lightColor"]') as HTMLInputElement;
+ const darkColorElement = dialog.element.querySelector('[data-field="darkColor"]') as HTMLInputElement;
+ const lightBackgroundElement = dialog.element.querySelector('[data-field="lightBackgroundColor"]') as HTMLInputElement;
+ const darkBackgroundElement = dialog.element.querySelector('[data-field="darkBackgroundColor"]') as HTMLInputElement;
+
+ const renderList = () => {
+ listElement.innerHTML = draft.styles.length === 0 ?
+ `<div class="b3-list-item"><span class="b3-list-item__text">${window.siyuan.languages.empty}</span></div>` :
+ draft.styles.map((style, index) => `<div class="b3-list-item b3-list-item--narrow" data-id="${escapeAttribute(style.id)}" data-index="${index}">
+ <span class="b3-list-item__graphic ariaLabel fn__grab" data-drag="true" draggable="true" data-position="north" aria-label="${escapeAttribute(window.siyuan.languages.sort)}"><svg><use xlink:href="#iconDrag"></use></svg></span>
+ <span class="color__square color__square--list" style="${renderPreviewStyle(style)}">A</span>
+ <span class="b3-list-item__text" title="${escapeAttribute(style.name)}">${escapeHtml(style.name)}</span>
+ <span class="b3-list-item__meta">${escapeHtml(getTypeLabel(getInlineStyleType(style) || "color"))}</span>
+ <span class="b3-list-item__action ariaLabel" data-action="edit" data-index="${index}" data-position="north" aria-label="${escapeAttribute(window.siyuan.languages.edit)}"><svg><use xlink:href="#iconEdit"></use></svg></span>
+ <span class="b3-list-item__action b3-list-item__action--warning ariaLabel" data-action="delete" data-index="${index}" data-position="north" aria-label="${escapeAttribute(window.siyuan.languages.delete)}"><svg><use xlink:href="#iconTrashcan"></use></svg></span>
+</div>`).join("");
+ newElement.disabled = draft.styles.length >= MAX_INLINE_STYLES;
+ };
+
+ const updateColorVisibility = () => {
+ const type = typeElement.value as TInlineStyleType;
+ dialog.element.querySelectorAll<HTMLElement>('[data-property="color"]').forEach(item => {
+ item.classList.toggle("fn__none", type === "backgroundColor");
+ });
+ dialog.element.querySelectorAll<HTMLElement>('[data-property="backgroundColor"]').forEach(item => {
+ item.classList.toggle("fn__none", type === "color");
+ });
+ };
+
+ const showList = () => {
+ editingIndex = undefined;
+ editorPanel.classList.add("fn__none");
+ listPanel.classList.remove("fn__none");
+ actionsPanel.classList.remove("fn__none");
+ renderList();
+ };
+
+ const showEditor = (index?: number) => {
+ editingIndex = index ?? -1;
+ const style = typeof index === "number" ? draft.styles[index] : undefined;
+ nameElement.value = style?.name || "";
+ typeElement.value = style ? getInlineStyleType(style) : initialType;
+ typeElement.disabled = !!style;
+ lightColorElement.value = style?.light.color || "#000000";
+ darkColorElement.value = style?.dark.color || "#ffffff";
+ lightBackgroundElement.value = style?.light.backgroundColor || "#fff3cd";
+ darkBackgroundElement.value = style?.dark.backgroundColor || "#554b00";
+ updateColorVisibility();
+ listPanel.classList.add("fn__none");
+ actionsPanel.classList.add("fn__none");
+ editorPanel.classList.remove("fn__none");
+ nameElement.focus();
+ };
+
+ const confirmEditor = () => {
+ const name = nameElement.value.trim();
+ if (!name) {
+ showMessage(window.siyuan.languages.nameEmpty, 6000, "error");
+ nameElement.focus();
+ return;
+ }
+ if ([...name].length > MAX_INLINE_STYLE_NAME_LENGTH) {
+ showMessage(window.siyuan.languages.invalid, 6000, "error");
+ nameElement.focus();
+ return;
+ }
+ const type = typeElement.value as TInlineStyleType;
+ const previous = editingIndex >= 0 ? draft.styles[editingIndex] : undefined;
+ const style: IInlineStyle = {
+ id: previous?.id || Lute.NewNodeID(),
+ name,
+ light: {},
+ dark: {},
+ };
+ if (type !== "backgroundColor") {
+ style.light.color = lightColorElement.value;
+ style.dark.color = darkColorElement.value;
+ }
+ if (type !== "color") {
+ style.light.backgroundColor = lightBackgroundElement.value;
+ style.dark.backgroundColor = darkBackgroundElement.value;
+ }
+ if (previous) {
+ draft.styles[editingIndex] = style;
+ } else {
+ draft.styles.push(style);
+ }
+ showList();
+ };
+
+ let draggingIndex = -1;
+ const clearDragover = () => {
+ listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-index]").forEach(item => {
+ item.classList.remove("dragover__top", "dragover__bottom");
+ });
+ };
+ const clearDragStyles = () => {
+ clearDragover();
+ listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-index]").forEach(item => {
+ item.style.opacity = "";
+ });
+ };
+ listElement.addEventListener("dragstart", (event: DragEvent) => {
+ const handleElement = (event.target as HTMLElement).closest<HTMLElement>('[data-drag="true"]');
+ const itemElement = handleElement?.closest<HTMLElement>(".b3-list-item[data-index]");
+ if (!itemElement) {
+ event.preventDefault();
+ return;
+ }
+ draggingIndex = parseInt(itemElement.dataset.index);
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/plain", itemElement.dataset.index);
+ itemElement.style.opacity = ".38";
+ });
+ listElement.addEventListener("dragover", (event: DragEvent) => {
+ const itemElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item[data-index]");
+ if (!itemElement || draggingIndex < 0) {
+ return;
+ }
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ clearDragover();
+ const rect = itemElement.getBoundingClientRect();
+ itemElement.classList.add(event.clientY < rect.top + rect.height / 2 ? "dragover__top" : "dragover__bottom");
+ });
+ listElement.addEventListener("drop", (event: DragEvent) => {
+ const itemElement = (event.target as HTMLElement).closest<HTMLElement>(".b3-list-item[data-index]");
+ if (!itemElement || draggingIndex < 0) {
+ return;
+ }
+ event.preventDefault();
+ const targetIndex = parseInt(itemElement.dataset.index);
+ const rect = itemElement.getBoundingClientRect();
+ const before = event.clientY < rect.top + rect.height / 2;
+ let insertIndex = targetIndex + (before ? 0 : 1);
+ if (draggingIndex < insertIndex) {
+ insertIndex--;
+ }
+ if (draggingIndex !== insertIndex) {
+ const [style] = draft.styles.splice(draggingIndex, 1);
+ draft.styles.splice(insertIndex, 0, style);
+ renderList();
+ }
+ draggingIndex = -1;
+ clearDragStyles();
+ });
+ listElement.addEventListener("dragend", () => {
+ draggingIndex = -1;
+ clearDragStyles();
+ });
+
+ typeElement.addEventListener("change", updateColorVisibility);
+ 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;
+ const index = parseInt(actionElement.dataset.index);
+ if (action === "new") {
+ if (draft.styles.length >= MAX_INLINE_STYLES) {
+ showMessage(window.siyuan.languages.invalid, 6000, "error");
+ return;
+ }
+ showEditor();
+ } else if (action === "edit") {
+ showEditor(index);
+ } else if (action === "delete") {
+ draft.styles.splice(index, 1);
+ renderList();
+ } else if (action === "cancelEdit") {
+ showList();
+ } else if (action === "confirmEdit") {
+ confirmEditor();
+ } else if (action === "cancel") {
+ dialog.destroy();
+ } else if (action === "save" && !saving) {
+ saving = true;
+ actionElement.setAttribute("disabled", "disabled");
+ try {
+ const response = await saveInlineStyles(draft);
+ if (response?.code !== 0) {
+ showMessage(response?.msg || window.siyuan.languages.invalid, 6000, "error");
+ saving = false;
+ actionElement.removeAttribute("disabled");
+ return;
+ }
+ const data = getInlineStylesCache();
+ onChange?.(data);
+ 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();
+ });
+ renderList();
+};
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index ae5d2bc217..1507a3bd6a 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -23,6 +23,10 @@ import {getBackend, getFrontend} from "./functions";
import {getWorkspaceName} from "./processTitle";
import {ensureSelectedCustomFont} from "./customFont";
import {isCurrentThemeSupported, shouldUnloadThemeScript} from "./themeCompatibility";
+import {
+ getInlineStylesCSS,
+ loadInlineStyles
+} from "../protyle/toolbar/inlineStyle";
let headingNumberMeasurementRefreshTimer: number;
const DEJAVU_EMOJI_PRESENTATION_UNICODE_RANGE = "U+25fd-25fe, U+2614-2615, U+2648-2653, U+267f, U+2693, U+26a1, " +
@@ -270,6 +274,14 @@ export const initAssets = () => {
};
export const setInlineStyle = async (set = true, servePath = "../../../") => {
+ let inlineStylesCSS = "";
+ try {
+ const inlineStyles = await loadInlineStyles();
+ inlineStylesCSS = getInlineStylesCSS(inlineStyles);
+ } catch (error) {
+ console.error("load inline styles error: " + error);
+ inlineStylesCSS = getInlineStylesCSS();
+ }
if (set) {
await ensureSelectedCustomFont(window.siyuan.config.editor.fontFamily, window.siyuan.config.editor.fontWeight);
}
@@ -360,6 +372,7 @@ export const setInlineStyle = async (set = true, servePath = "../../../") => {
if ("ontouchend" in document) {
style += "\n.b3-menu .b3-menu__action {opacity: 0.68;}";
}
+ style += inlineStylesCSS ? "\n" + inlineStylesCSS : "";
if (set) {
const siyuanStyle = document.getElementById("siyuanStyle");
if (siyuanStyle) {
@@ -371,6 +384,15 @@ export const setInlineStyle = async (set = true, servePath = "../../../") => {
return style;
};
+export const reloadInlineStyles = async () => {
+ try {
+ await loadInlineStyles(true);
+ } catch (error) {
+ console.error("reload inline styles error: " + error);
+ }
+ await setInlineStyle();
+};
+
export const setMode = (modeElementValue: number) => {
/// #if !MOBILE
let mode = modeElementValue;
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index de67a2749f..e65e82ba01 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -27,7 +27,7 @@ import {hideAllElements} from "../protyle/ui/hideElements";
import {reloadEmoji} from "../emoji";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
import {renderSnippet} from "../config/util/snippets";
-import {refreshThemeStyle, setBodyHighlight} from "../util/assets";
+import {refreshThemeStyle, reloadInlineStyles, setBodyHighlight} from "../util/assets";
import {reloadSync} from "../util/reloadSync";
import {setTitle} from "../util/processTitle";
import {ensureUILayout} from "../util/ensureUILayout";
@@ -59,6 +59,9 @@ class App {
case "setAppearance":
appearanceConfigApi.apply(data.data);
break;
+ case "reloadInlineStyles":
+ void reloadInlineStyles();
+ break;
case "setEntryVisibility":
applyEntryVisibility(data.data);
break;
diff --git a/kernel/api/inline_style.go b/kernel/api/inline_style.go
new file mode 100644
index 0000000000..d6dba7c757
--- /dev/null
+++ b/kernel/api/inline_style.go
@@ -0,0 +1,91 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "net/http"
+
+ "github.com/88250/gulu"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func getInlineStyles(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ styles, err := model.GetInlineStyles()
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ ret.Data = styles
+}
+
+func setInlineStyles(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+ var stylesArg []any
+ var version float64
+ var app string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("version", &version, true, false),
+ util.BindJsonArg("styles", &stylesArg, true, false),
+ util.BindJsonArg("app", &app, false, false),
+ ) {
+ return
+ }
+ if 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
+ }
+ 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()
+ return
+ }
+ ret.Data = saved
+ if changed {
+ evt := util.NewCmdResult("reloadInlineStyles", 0, util.PushModeBroadcastMainExcludeSelfApp)
+ evt.AppId = app
+ util.PushEvent(evt)
+ util.ReloadPublishServiceSessions()
+ }
+}
diff --git a/kernel/api/inline_style_test.go b/kernel/api/inline_style_test.go
new file mode 100644
index 0000000000..b24e340e53
--- /dev/null
+++ b/kernel/api/inline_style_test.go
@@ -0,0 +1,135 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestInlineStylesAPI(t *testing.T) {
+ setupInlineStylesAPITest(t)
+ gin.SetMode(gin.TestMode)
+
+ engine := gin.New()
+ engine.POST("/api/storage/getInlineStyles", getInlineStyles)
+ engine.POST("/api/storage/setInlineStyles", setInlineStyles)
+
+ getRecorder := performInlineStylesRequest(engine, "/api/storage/getInlineStyles", "")
+ getResponse := &struct {
+ Code int `json:"code"`
+ Data *model.InlineStyles `json:"data"`
+ }{}
+ if err := json.Unmarshal(getRecorder.Body.Bytes(), getResponse); err != nil {
+ t.Fatal(err)
+ }
+ if getResponse.Code != 0 || getResponse.Data == nil || getResponse.Data.Version != model.InlineStylesVersion ||
+ getResponse.Data.Styles == nil || len(getResponse.Data.Styles) != 0 {
+ t.Fatalf("unexpected initial inline styles response: %s", getRecorder.Body.String())
+ }
+
+ setRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{
+ "version":1,
+ "styles":[{
+ "name":" Accent ",
+ "light":{"color":"#AABBCC"},
+ "dark":{"color":"#112233"}
+ }]
+ }`)
+ setResponse := &struct {
+ Code int `json:"code"`
+ Data *model.InlineStyles `json:"data"`
+ }{}
+ if err := json.Unmarshal(setRecorder.Body.Bytes(), setResponse); err != nil {
+ t.Fatal(err)
+ }
+ 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" {
+ t.Fatalf("unexpected set inline styles response: %s", setRecorder.Body.String())
+ }
+
+ futureRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{"version":2,"styles":[]}`)
+ if responseCode(t, futureRecorder) != -1 || !strings.Contains(futureRecorder.Body.String(), "unsupported") {
+ t.Fatalf("future inline styles version was accepted: %s", futureRecorder.Body.String())
+ }
+ styles, err := model.GetInlineStyles()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(styles.Styles) != 1 || styles.Styles[0].ID != setResponse.Data.Styles[0].ID {
+ t.Fatalf("future request overwrote inline styles: %#v", styles)
+ }
+
+ 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())
+ }
+}
+
+func TestInlineStylesAPIPermissions(t *testing.T) {
+ setupInlineStylesAPITest(t)
+ gin.SetMode(gin.TestMode)
+
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, model.RoleReader)
+ c.Next()
+ })
+ ServeAPI(engine)
+
+ getRecorder := performInlineStylesRequest(engine, "/api/storage/getInlineStyles", "")
+ if getRecorder.Code != http.StatusOK || responseCode(t, getRecorder) != 0 {
+ t.Fatalf("reader cannot get inline styles: %s", getRecorder.Body.String())
+ }
+ setRecorder := performInlineStylesRequest(engine, "/api/storage/setInlineStyles", `{"version":1,"styles":[]}`)
+ if setRecorder.Code != http.StatusForbidden {
+ t.Fatalf("reader changed inline styles: status=%d, body=%s", setRecorder.Code, setRecorder.Body.String())
+ }
+}
+
+func performInlineStylesRequest(engine *gin.Engine, path, body string) *httptest.ResponseRecorder {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
+ if body != "" {
+ request.Header.Set("Content-Type", "application/json")
+ }
+ engine.ServeHTTP(recorder, request)
+ return recorder
+}
+
+func setupInlineStylesAPITest(t *testing.T) {
+ t.Helper()
+ oldDataDir, oldConf, oldReadOnly := util.DataDir, model.Conf, util.ReadOnly
+ util.DataDir, model.Conf, util.ReadOnly = t.TempDir(), model.NewAppConf(), false
+ model.Conf.Sync = conf.NewSync()
+ t.Cleanup(func() {
+ util.DataDir, model.Conf, util.ReadOnly = oldDataDir, oldConf, oldReadOnly
+ })
+ if err := os.MkdirAll(util.DataDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index c2c02184d3..a1e7b7aa57 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -108,6 +108,8 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/storage/setLocalStorageVals", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setLocalStorageVals)
ginServer.Handle("POST", "/api/storage/removeLocalStorageVal", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeLocalStorageVal)
ginServer.Handle("POST", "/api/storage/removeLocalStorageVals", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeLocalStorageVals)
+ ginServer.Handle("POST", "/api/storage/getInlineStyles", model.CheckAuth, getInlineStyles)
+ ginServer.Handle("POST", "/api/storage/setInlineStyles", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setInlineStyles)
ginServer.Handle("POST", "/api/storage/getCriteria", model.CheckAuth, getCriteria)
ginServer.Handle("POST", "/api/storage/setCriterion", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setCriterion)
ginServer.Handle("POST", "/api/storage/removeCriterion", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeCriterion)
diff --git a/kernel/model/inline_style.go b/kernel/model/inline_style.go
new file mode 100644
index 0000000000..84d991ecd7
--- /dev/null
+++ b/kernel/model/inline_style.go
@@ -0,0 +1,228 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "unicode/utf8"
+
+ "github.com/88250/gulu"
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ InlineStylesVersion = 1
+ maxInlineStyles = 64
+ maxInlineStyleNameRunes = 64
+ maxInlineStylesFileSize = 1024 * 1024
+ inlineStylesRepoPath = "/storage/inline-styles.json"
+)
+
+var (
+ inlineStylesLock sync.Mutex
+ inlineStyleColorPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)
+)
+
+type InlineStyleTheme struct {
+ Color string `json:"color,omitempty"`
+ BackgroundColor string `json:"backgroundColor,omitempty"`
+}
+
+type InlineStyle struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Light *InlineStyleTheme `json:"light"`
+ Dark *InlineStyleTheme `json:"dark"`
+}
+
+type InlineStyles struct {
+ Version int `json:"version"`
+ Styles []*InlineStyle `json:"styles"`
+}
+
+func GetInlineStyles() (ret *InlineStyles, err error) {
+ waitForSyncingStorages()
+ inlineStylesLock.Lock()
+ defer inlineStylesLock.Unlock()
+ return loadInlineStyles()
+}
+
+func SetInlineStyles(styles []*InlineStyle) (ret *InlineStyles, changed bool, err error) {
+ waitForSyncingStorages()
+ inlineStylesLock.Lock()
+ defer inlineStylesLock.Unlock()
+
+ dataPath := inlineStylesPath()
+ if _, err = loadInlineStyles(); err != nil {
+ return nil, false, err
+ }
+
+ normalized, err := normalizeInlineStyles(styles, true)
+ if err != nil {
+ return nil, false, err
+ }
+ ret = &InlineStyles{Version: InlineStylesVersion, Styles: normalized}
+ data, err := gulu.JSON.MarshalIndentJSON(ret, "", " ")
+ if err != nil {
+ return nil, false, fmt.Errorf("marshal inline styles failed: %w", err)
+ }
+ if maxInlineStylesFileSize < len(data) {
+ return nil, false, fmt.Errorf("inline styles file exceeds the %d byte limit", maxInlineStylesFileSize)
+ }
+
+ oldData, readErr := filelock.ReadFile(dataPath)
+ if readErr != nil && !os.IsNotExist(readErr) {
+ return nil, false, fmt.Errorf("read inline styles failed: %w", readErr)
+ }
+ if bytes.Equal(oldData, data) {
+ return ret, false, nil
+ }
+
+ if err = os.MkdirAll(filepath.Dir(dataPath), 0755); err != nil {
+ return nil, false, fmt.Errorf("create inline styles directory failed: %w", err)
+ }
+ if err = filelock.WriteFile(dataPath, data); err != nil {
+ return nil, false, fmt.Errorf("write inline styles failed: %w", err)
+ }
+ IncSync()
+ return ret, true, nil
+}
+
+func inlineStylesPath() string {
+ return filepath.Join(util.DataDir, "storage", "inline-styles.json")
+}
+
+func isInlineStylesRepoPath(filePath string) bool {
+ return filePath == inlineStylesRepoPath
+}
+
+func loadInlineStyles() (ret *InlineStyles, err error) {
+ ret = &InlineStyles{Version: InlineStylesVersion, Styles: []*InlineStyle{}}
+ data, err := filelock.ReadFile(inlineStylesPath())
+ if os.IsNotExist(err) {
+ return ret, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("read inline styles failed: %w", err)
+ }
+ if maxInlineStylesFileSize < len(data) {
+ return nil, fmt.Errorf("inline styles file exceeds the %d byte limit", maxInlineStylesFileSize)
+ }
+ if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil {
+ return nil, fmt.Errorf("unmarshal inline styles failed: %w", err)
+ }
+ if 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)
+ }
+ return ret, nil
+}
+
+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)
+ }
+ ret = make([]*InlineStyle, 0, len(styles))
+ ids := make(map[string]struct{}, len(styles))
+ for _, style := range styles {
+ if style == nil {
+ return nil, errors.New("inline style must not be null")
+ }
+
+ id := strings.TrimSpace(style.ID)
+ if id == "" && generateIDs {
+ for {
+ id = ast.NewNodeID()
+ if _, exists := ids[id]; !exists {
+ break
+ }
+ }
+ }
+ if !ast.IsNodeIDPattern(id) {
+ return nil, fmt.Errorf("invalid inline style ID [%s]", id)
+ }
+ if _, exists := ids[id]; exists {
+ return nil, fmt.Errorf("duplicate inline style ID [%s]", id)
+ }
+ ids[id] = struct{}{}
+
+ name := strings.TrimSpace(style.Name)
+ if name == "" {
+ return nil, errors.New("inline style name must not be empty")
+ }
+ if maxInlineStyleNameRunes < utf8.RuneCountInString(name) {
+ return nil, fmt.Errorf("inline style name exceeds the %d character limit", maxInlineStyleNameRunes)
+ }
+ if style.Light == nil || style.Dark == nil {
+ return nil, fmt.Errorf("inline style [%s] must define light and dark themes", id)
+ }
+
+ light, err := normalizeInlineStyleTheme(style.Light)
+ if err != nil {
+ return nil, fmt.Errorf("invalid light theme of inline style [%s]: %w", id, err)
+ }
+ dark, err := normalizeInlineStyleTheme(style.Dark)
+ if err != nil {
+ return nil, fmt.Errorf("invalid dark theme of inline style [%s]: %w", id, err)
+ }
+ lightColor, lightBackground := light.Color != "", light.BackgroundColor != ""
+ darkColor, darkBackground := dark.Color != "", dark.BackgroundColor != ""
+ if !lightColor && !lightBackground {
+ return nil, fmt.Errorf("inline style [%s] must define color or backgroundColor", id)
+ }
+ if lightColor != darkColor || lightBackground != darkBackground {
+ return nil, fmt.Errorf("inline style [%s] must use the same fields in light and dark themes", id)
+ }
+
+ ret = append(ret, &InlineStyle{ID: id, Name: name, Light: light, Dark: dark})
+ }
+ return ret, nil
+}
+
+func normalizeInlineStyleTheme(theme *InlineStyleTheme) (ret *InlineStyleTheme, err error) {
+ ret = &InlineStyleTheme{}
+ if ret.Color, err = normalizeInlineStyleColor(theme.Color); err != nil {
+ return nil, fmt.Errorf("invalid color: %w", err)
+ }
+ if ret.BackgroundColor, err = normalizeInlineStyleColor(theme.BackgroundColor); err != nil {
+ return nil, fmt.Errorf("invalid backgroundColor: %w", err)
+ }
+ return ret, nil
+}
+
+func normalizeInlineStyleColor(color string) (ret string, err error) {
+ ret = strings.ToLower(strings.TrimSpace(color))
+ if ret == "" {
+ return ret, nil
+ }
+ if !inlineStyleColorPattern.MatchString(ret) {
+ return "", fmt.Errorf("color [%s] must use #RRGGBB format", color)
+ }
+ return ret, nil
+}
diff --git a/kernel/model/inline_style_test.go b/kernel/model/inline_style_test.go
new file mode 100644
index 0000000000..645d0cbd43
--- /dev/null
+++ b/kernel/model/inline_style_test.go
@@ -0,0 +1,227 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ ignore "github.com/sabhiram/go-gitignore"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestInlineStylesCRUD(t *testing.T) {
+ setupInlineStylesTest(t)
+
+ styles, err := GetInlineStyles()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if styles.Version != InlineStylesVersion || styles.Styles == nil || len(styles.Styles) != 0 {
+ t.Fatalf("unexpected empty inline styles: %#v", styles)
+ }
+ if _, err = os.Stat(inlineStylesPath()); !os.IsNotExist(err) {
+ t.Fatalf("get created inline styles file: %v", err)
+ }
+
+ saved, changed, err := SetInlineStyles([]*InlineStyle{
+ {
+ Name: " Combined ",
+ Light: &InlineStyleTheme{Color: " #AABBCC ", BackgroundColor: "#DDEEFF"},
+ Dark: &InlineStyleTheme{Color: "#112233", BackgroundColor: "#445566"},
+ },
+ {
+ ID: "20260821000000-abcdefg",
+ Name: "Background",
+ Light: &InlineStyleTheme{BackgroundColor: "#ABCDEF"},
+ Dark: &InlineStyleTheme{BackgroundColor: "#123456"},
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed || len(saved.Styles) != 2 || !ast.IsNodeIDPattern(saved.Styles[0].ID) {
+ t.Fatalf("unexpected saved inline styles: %#v", saved)
+ }
+ if saved.Styles[0].Name != "Combined" || saved.Styles[0].Light.Color != "#aabbcc" ||
+ saved.Styles[0].Light.BackgroundColor != "#ddeeff" || saved.Styles[1].Light.BackgroundColor != "#abcdef" {
+ t.Fatalf("inline styles were not normalized: %#v", saved)
+ }
+
+ loaded, err := GetInlineStyles()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(loaded.Styles) != 2 || loaded.Styles[0].ID != saved.Styles[0].ID ||
+ loaded.Styles[1].ID != saved.Styles[1].ID {
+ t.Fatalf("inline style order or IDs changed: %#v", loaded)
+ }
+ if _, changed, err = SetInlineStyles(loaded.Styles); err != nil || changed {
+ t.Fatalf("unchanged inline styles were rewritten: changed=%t, err=%v", changed, err)
+ }
+}
+
+func TestInlineStylesValidation(t *testing.T) {
+ validID := "20260821000000-abcdefg"
+ valid := func() *InlineStyle {
+ return &InlineStyle{
+ ID: validID,
+ Name: "Valid",
+ Light: &InlineStyleTheme{Color: "#abcdef"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ }
+ }
+ tests := []struct {
+ name string
+ styles func() []*InlineStyle
+ }{
+ {name: "null style", styles: func() []*InlineStyle { return []*InlineStyle{nil} }},
+ {name: "invalid ID", styles: func() []*InlineStyle {
+ style := valid()
+ style.ID = "invalid"
+ return []*InlineStyle{style}
+ }},
+ {name: "duplicate ID", styles: func() []*InlineStyle { return []*InlineStyle{valid(), valid()} }},
+ {name: "empty name", styles: func() []*InlineStyle {
+ style := valid()
+ style.Name = " "
+ return []*InlineStyle{style}
+ }},
+ {name: "long name", styles: func() []*InlineStyle {
+ style := valid()
+ style.Name = strings.Repeat("界", maxInlineStyleNameRunes+1)
+ return []*InlineStyle{style}
+ }},
+ {name: "missing theme", styles: func() []*InlineStyle {
+ style := valid()
+ style.Dark = nil
+ return []*InlineStyle{style}
+ }},
+ {name: "empty fields", styles: func() []*InlineStyle {
+ style := valid()
+ style.Light = &InlineStyleTheme{}
+ style.Dark = &InlineStyleTheme{}
+ return []*InlineStyle{style}
+ }},
+ {name: "different fields", styles: func() []*InlineStyle {
+ style := valid()
+ style.Dark = &InlineStyleTheme{BackgroundColor: "#123456"}
+ return []*InlineStyle{style}
+ }},
+ {name: "invalid color", styles: func() []*InlineStyle {
+ style := valid()
+ style.Light.Color = "#abc"
+ return []*InlineStyle{style}
+ }},
+ {name: "too many styles", styles: func() []*InlineStyle {
+ styles := make([]*InlineStyle, maxInlineStyles+1)
+ for i := range styles {
+ styles[i] = &InlineStyle{
+ Name: "Style",
+ Light: &InlineStyleTheme{Color: "#abcdef"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ }
+ }
+ return styles
+ }},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ setupInlineStylesTest(t)
+ if _, _, err := SetInlineStyles(test.styles()); err == nil {
+ t.Fatal("expected validation error")
+ }
+ if _, err := os.Stat(inlineStylesPath()); !os.IsNotExist(err) {
+ t.Fatalf("invalid 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: "oversized", data: bytes.Repeat([]byte("x"), maxInlineStylesFileSize+1)},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ setupInlineStylesTest(t)
+ if err := os.MkdirAll(filepath.Dir(inlineStylesPath()), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(inlineStylesPath(), test.data, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := GetInlineStyles(); err == nil {
+ t.Fatal("expected invalid inline styles error")
+ }
+ if _, _, err := SetInlineStyles([]*InlineStyle{{
+ Name: "Replacement",
+ Light: &InlineStyleTheme{Color: "#abcdef"},
+ Dark: &InlineStyleTheme{Color: "#123456"},
+ }}); err == nil {
+ t.Fatal("expected replacement to be rejected")
+ }
+ current, err := os.ReadFile(inlineStylesPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(current, test.data) {
+ t.Fatal("invalid inline styles file was overwritten")
+ }
+ })
+ }
+}
+
+func TestInlineStylesRepoPath(t *testing.T) {
+ setupInlineStylesTest(t)
+ if !isInlineStylesRepoPath("/storage/inline-styles.json") {
+ t.Fatal("inline styles repository path was not recognized")
+ }
+ for _, filePath := range []string{
+ "storage/inline-styles.json",
+ "/storage/inline-styles.json.bak",
+ "/storage/nested/inline-styles.json",
+ } {
+ if isInlineStylesRepoPath(filePath) {
+ t.Fatalf("unexpected inline styles repository path match: %s", filePath)
+ }
+ }
+ if ignore.CompileIgnoreLines(getSyncIgnoreLines()...).MatchesPath(inlineStylesRepoPath) {
+ t.Fatal("inline styles file is ignored by data synchronization")
+ }
+}
+
+func setupInlineStylesTest(t *testing.T) {
+ t.Helper()
+ oldDataDir, oldConf := util.DataDir, Conf
+ util.DataDir, Conf = t.TempDir(), NewAppConf()
+ Conf.Sync = conf.NewSync()
+ t.Cleanup(func() {
+ util.DataDir, Conf = oldDataDir, oldConf
+ })
+}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 1930ac8d86..e4a9ccfad4 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -2304,7 +2304,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
var upserts, removes []string
var upsertTrees int
// 可能需要重新加载部分功能
- var needReloadFlashcard, needReloadOcrTexts, needReloadPlugin, needReloadSnippet bool
+ var needReloadFlashcard, needReloadInlineStyles, needReloadOcrTexts, needReloadPlugin, needReloadSnippet bool
reloadPluginSet := hashset.New() // 插件代码变更 data/plugins/
dataChangePluginSet := hashset.New() // 插件存储数据变更 data/storage/petal/
needUnindexBoxes, needIndexBoxes := map[string]bool{}, map[string]bool{}
@@ -2366,6 +2366,10 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
needReloadSnippet = true
}
+ if isInlineStylesRepoPath(file.Path) {
+ needReloadInlineStyles = true
+ }
+
if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
cache.RemoveAVData(strings.TrimSuffix(filepath.Base(file.Path), ".json"))
}
@@ -2441,6 +2445,10 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
needReloadSnippet = true
}
+ if isInlineStylesRepoPath(file.Path) {
+ needReloadInlineStyles = true
+ }
+
if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
cache.RemoveAVData(strings.TrimSuffix(filepath.Base(file.Path), ".json"))
}
@@ -2479,6 +2487,10 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
syncingFiles = sync.Map{}
syncingStorages.Store(false)
+ if needReloadInlineStyles && !exit {
+ util.BroadcastByType("main", "reloadInlineStyles", 0, "", nil)
+ util.ReloadPublishServiceSessions()
+ }
removedEncryptedBox := false
for boxID := range removedBoxConfs {
if IsEncryptedBox(boxID) || removedBoxCryptoBackups[boxID] {
diff --git a/kernel/model/theme.go b/kernel/model/theme.go
index 6d0872856b..5364ece997 100644
--- a/kernel/model/theme.go
+++ b/kernel/model/theme.go
@@ -17,34 +17,37 @@
package model
import (
- "bytes"
"os"
"path/filepath"
"strings"
- "github.com/88250/gulu"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
- "github.com/gorilla/css/scanner"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/util"
"github.com/vanng822/css"
)
+const maxCSSVarResolveDepth = 64
+
// 将文档中的 CSS 变量替换为具体的主题样式值
func fillThemeStyleVar(tree *parse.Tree) {
if nil == tree || nil == tree.Root {
return
}
+ isDarkMode := 1 == Conf.Appearance.Mode
var themeStyles map[string]string
- if 1 == Conf.Appearance.Mode {
+ if isDarkMode {
themeStyles = getThemeStyleVar(Conf.Appearance.ThemeDark, true)
} else {
themeStyles = getThemeStyleVar(Conf.Appearance.ThemeLight, false)
}
- if 1 > len(themeStyles) {
- return
+ inlineStyles, err := GetInlineStyles()
+ if err != nil {
+ logging.LogErrorf("load inline styles for theme variables failed: %s", err)
+ } else {
+ mergeInlineStyleThemeVars(themeStyles, inlineStyles, isDarkMode)
}
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -58,103 +61,239 @@ func fillThemeStyleVar(tree *parse.Tree) {
continue
}
- styleSheet := css.Parse(ial[1])
- buf := bytes.Buffer{}
- for _, r := range styleSheet.GetCSSRuleList() {
- styles := getStyleVarName(r.Style.Selector)
- for style, name := range styles {
- buf.WriteString(style)
- buf.WriteString(": ")
-
- // 解析嵌套的 CSS 变量
- value := resolveNestedCSSVar(themeStyles, name)
-
- if "" == value {
- // 回退为原始 var() 形式
- buf.WriteString("var(")
- buf.WriteString(name)
- buf.WriteString(")")
- } else {
- buf.WriteString(value)
- }
- buf.WriteString("; ")
- }
- }
- if 0 < buf.Len() {
- ial[1] = strings.TrimSpace(buf.String())
- }
+ ial[1] = resolveCSSVars(ial[1], themeStyles)
}
return ast.WalkContinue
})
}
-// 递归解析嵌套的 CSS 变量
-func resolveNestedCSSVar(themeStyles map[string]string, varName string) string {
- visited := make(map[string]bool) // 循环引用检测
- maxDepth := 10 // 防止无限嵌套
-
- currentName := varName
- for range maxDepth {
- if visited[currentName] {
- return ""
+func mergeInlineStyleThemeVars(themeStyles map[string]string, styles *InlineStyles, isDarkMode bool) {
+ if styles == nil {
+ return
+ }
+ for _, style := range styles.Styles {
+ if style == nil {
+ continue
}
- visited[currentName] = true
-
- value, exists := themeStyles[currentName]
- if !exists {
- return ""
+ theme := style.Light
+ if isDarkMode {
+ theme = style.Dark
+ }
+ if theme == nil {
+ continue
}
+ prefix := "--b3-inline-style-" + style.ID
+ if theme.Color != "" {
+ themeStyles[prefix+"-color"] = theme.Color
+ }
+ if theme.BackgroundColor != "" {
+ themeStyles[prefix+"-background-color"] = theme.BackgroundColor
+ }
+ }
+}
- // 如果不包含嵌套变量,直接返回最终值
- if !strings.Contains(value, "var(") {
- return value
+func resolveCSSVars(value string, variables map[string]string) string {
+ ret, _ := resolveCSSVarsValue(value, variables, map[string]bool{}, 0)
+ return ret
+}
+
+func resolveCSSVarsValue(value string, variables map[string]string, resolving map[string]bool, depth int) (ret string, valid bool) {
+ if maxCSSVarResolveDepth < depth {
+ return value, false
+ }
+
+ var builder strings.Builder
+ valid = true
+ position := 0
+ for position < len(value) {
+ start := findNextCSSVar(value, position)
+ if start < 0 {
+ builder.WriteString(value[position:])
+ break
+ }
+ builder.WriteString(value[position:start])
+ end, ok := findCSSFunctionEnd(value, start+3)
+ if !ok {
+ builder.WriteString(value[start:])
+ valid = false
+ break
}
- // 提取嵌套变量名:var(--variable-name) -> --variable-name
- nestedVarName := gulu.Str.SubStringBetween(value, "(", ")")
- if "" == nestedVarName {
- return value
+ original := value[start : end+1]
+ name, fallback, hasFallback := splitCSSVarArguments(value[start+4 : end])
+ resolved, ok := resolveCSSVar(name, fallback, hasFallback, original, variables, resolving, depth+1)
+ builder.WriteString(resolved)
+ if !ok {
+ valid = false
}
+ position = end + 1
+ }
+ return builder.String(), valid
+}
- currentName = nestedVarName
+func resolveCSSVar(name, fallback string, hasFallback bool, original string, variables map[string]string,
+ resolving map[string]bool, depth int) (ret string, valid bool) {
+ name = normalizeCSSVarName(name)
+ if strings.HasPrefix(name, "--") && !resolving[name] {
+ if value, exists := variables[name]; exists {
+ resolving[name] = true
+ resolved, ok := resolveCSSVarsValue(value, variables, resolving, depth)
+ delete(resolving, name)
+ if ok {
+ return resolved, true
+ }
+ }
}
- return ""
+ if hasFallback {
+ resolved, ok := resolveCSSVarsValue(strings.TrimSpace(fallback), variables, resolving, depth)
+ if ok {
+ return resolved, true
+ }
+ }
+ return original, false
}
-// 从 CSS 选择器值中解析出样式属性和对应的 CSS 变量名
-func getStyleVarName(value *css.CSSValue) (ret map[string]string) {
- ret = map[string]string{}
-
- var start, end int
- var style, name string
- for i, t := range value.Tokens {
- // 获取样式属性名
- if scanner.TokenIdent == t.Type && 0 == start {
- style = strings.TrimSpace(t.Value)
+func findNextCSSVar(value string, start int) int {
+ var quote byte
+ for i := start; i < len(value); i++ {
+ if quote != 0 {
+ if value[i] == '\\' {
+ i++
+ continue
+ }
+ if value[i] == quote {
+ quote = 0
+ }
+ continue
+ }
+ if value[i] == '\'' || value[i] == '"' {
+ quote = value[i]
continue
}
+ if i+1 < len(value) && value[i] == '/' && value[i+1] == '*' {
+ if commentEnd := strings.Index(value[i+2:], "*/"); commentEnd >= 0 {
+ i += commentEnd + 3
+ continue
+ }
+ return -1
+ }
+ if i+4 <= len(value) && strings.EqualFold(value[i:i+4], "var(") &&
+ (i == 0 || !isCSSIdentifierByte(value[i-1])) {
+ return i
+ }
+ }
+ return -1
+}
- if scanner.TokenFunction == t.Type && "var(" == t.Value {
- start = i
+func findCSSFunctionEnd(value string, openParen int) (ret int, ok bool) {
+ if openParen >= len(value) || value[openParen] != '(' {
+ return 0, false
+ }
+ depth := 0
+ var quote byte
+ for i := openParen; i < len(value); i++ {
+ if quote != 0 {
+ if value[i] == '\\' {
+ i++
+ continue
+ }
+ if value[i] == quote {
+ quote = 0
+ }
continue
}
- if scanner.TokenChar == t.Type && ")" == t.Value {
- end = i
+ if value[i] == '\'' || value[i] == '"' {
+ quote = value[i]
+ continue
+ }
+ if i+1 < len(value) && value[i] == '/' && value[i+1] == '*' {
+ if commentEnd := strings.Index(value[i+2:], "*/"); commentEnd >= 0 {
+ i += commentEnd + 3
+ continue
+ }
+ return 0, false
+ }
+ switch value[i] {
+ case '(':
+ depth++
+ case ')':
+ depth--
+ if depth == 0 {
+ return i, true
+ }
+ }
+ }
+ return 0, false
+}
- // 提取 var() 中的变量名
- if 0 < start && 0 < end {
- for _, tt := range value.Tokens[start+1 : end] {
- name += tt.Value
- }
- name = strings.TrimSpace(name)
+func splitCSSVarArguments(value string) (name, fallback string, hasFallback bool) {
+ depth := 0
+ var quote byte
+ for i := 0; i < len(value); i++ {
+ if quote != 0 {
+ if value[i] == '\\' {
+ i++
+ continue
+ }
+ if value[i] == quote {
+ quote = 0
+ }
+ continue
+ }
+ if value[i] == '\'' || value[i] == '"' {
+ quote = value[i]
+ continue
+ }
+ if i+1 < len(value) && value[i] == '/' && value[i+1] == '*' {
+ commentEnd := strings.Index(value[i+2:], "*/")
+ if commentEnd < 0 {
+ return value, "", false
+ }
+ i += commentEnd + 3
+ continue
+ }
+ switch value[i] {
+ case '(':
+ depth++
+ case ')':
+ if 0 < depth {
+ depth--
+ }
+ case ',':
+ if depth == 0 {
+ return value[:i], value[i+1:], true
}
- start, end = 0, 0
- ret[style] = name
- style, name = "", ""
}
}
- return
+ return value, "", false
+}
+
+func normalizeCSSVarName(value string) string {
+ var builder strings.Builder
+ position := 0
+ for position < len(value) {
+ commentStart := strings.Index(value[position:], "/*")
+ if commentStart < 0 {
+ builder.WriteString(value[position:])
+ break
+ }
+ commentStart += position
+ builder.WriteString(value[position:commentStart])
+ commentEnd := strings.Index(value[commentStart+2:], "*/")
+ if commentEnd < 0 {
+ builder.WriteString(value[commentStart:])
+ break
+ }
+ builder.WriteByte(' ')
+ position = commentStart + commentEnd + 4
+ }
+ return strings.TrimSpace(builder.String())
+}
+
+func isCSSIdentifierByte(value byte) bool {
+ return value == '-' || value == '_' || '0' <= value && value <= '9' ||
+ 'a' <= value && value <= 'z' || 'A' <= value && value <= 'Z'
}
// 获取主题的样式变量映射表
diff --git a/kernel/model/theme_test.go b/kernel/model/theme_test.go
new file mode 100644
index 0000000000..39360d153f
--- /dev/null
+++ b/kernel/model/theme_test.go
@@ -0,0 +1,158 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestResolveCSSVars(t *testing.T) {
+ variables := map[string]string{
+ "--primary": "#112233",
+ "--nested": "var(--primary)",
+ "--cycle-a": "var(--cycle-b)",
+ "--cycle-b": "var(--cycle-a)",
+ "--with-fall": "var(--missing, #445566)",
+ }
+ input := `font-size: 18px; color: var(--nested); background-color: var(--missing, var(--with-fall, #778899)); ` +
+ `border-color: var(--cycle-a, #abcdef); outline-color: var(--unknown); content: "var(--primary)"; ` +
+ `box-shadow: 0 0 1px var(--missing-shadow, rgba(1, 2, 3, 0.5));`
+ expected := `font-size: 18px; color: #112233; background-color: #445566; border-color: #abcdef; ` +
+ `outline-color: var(--unknown); content: "var(--primary)"; box-shadow: 0 0 1px rgba(1, 2, 3, 0.5);`
+ if actual := resolveCSSVars(input, variables); actual != expected {
+ t.Fatalf("unexpected resolved CSS:\n%s\nwant:\n%s", actual, expected)
+ }
+
+ if actual := resolveCSSVars("color: var(--cycle-a);", variables); actual != "color: var(--cycle-a);" {
+ t.Fatalf("cycle without fallback was changed: %s", actual)
+ }
+ if actual := resolveCSSVars("color: var(--missing,);", variables); actual != "color: ;" {
+ t.Fatalf("empty fallback was not resolved: %s", actual)
+ }
+ commented := "color: var(--primary/**/, #000000); background-color: var(--primary /*,*/, #000000);"
+ if actual := resolveCSSVars(commented, variables); actual != "color: #112233; background-color: #112233;" {
+ t.Fatalf("comments in var arguments were not handled: %s", actual)
+ }
+}
+
+func TestMergeInlineStyleThemeVars(t *testing.T) {
+ styles := &InlineStyles{Version: InlineStylesVersion, Styles: []*InlineStyle{{
+ ID: "20260821000000-abcdefg",
+ Name: "Combined",
+ Light: &InlineStyleTheme{
+ Color: "#112233",
+ BackgroundColor: "#445566",
+ },
+ 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" {
+ t.Fatalf("unexpected light inline style variables: %#v", light)
+ }
+
+ dark := map[string]string{}
+ mergeInlineStyleThemeVars(dark, styles, true)
+ if dark[colorName] != "#aabbcc" || dark[backgroundName] != "#ddeeff" {
+ t.Fatalf("unexpected dark inline style variables: %#v", dark)
+ }
+}
+
+func TestFillThemeStyleVarUsesCurrentInlineStyleMode(t *testing.T) {
+ setupThemeTest(t, "midnight", `:root {}`)
+ Conf.Appearance.Mode = 1
+ Conf.Appearance.ThemeDark = "midnight"
+
+ const id = "20260821000000-abcdefg"
+ if _, _, err := SetInlineStyles([]*InlineStyle{{
+ ID: id,
+ Name: "Foreground",
+ Light: &InlineStyleTheme{Color: "#112233"},
+ Dark: &InlineStyleTheme{Color: "#aabbcc"},
+ }}); err != nil {
+ t.Fatal(err)
+ }
+
+ style := "font-size: 18px; color: var(--b3-inline-style-" + id + "-color, #445566);"
+ tree, node := inlineStyleThemeTestTree(style)
+ fillThemeStyleVar(tree)
+ if actual := node.KramdownIAL[0][1]; actual != "font-size: 18px; color: #aabbcc;" {
+ t.Fatalf("unexpected Word inline style: %s", actual)
+ }
+}
+
+func TestFillThemeStyleVarFallsBackForInvalidInlineStyles(t *testing.T) {
+ setupThemeTest(t, "daylight", `:root { --theme-background: #112233; }`)
+ Conf.Appearance.Mode = 0
+ Conf.Appearance.ThemeLight = "daylight"
+
+ if err := os.MkdirAll(filepath.Dir(inlineStylesPath()), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(inlineStylesPath(), []byte(`{"version":`), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ tree, node := inlineStyleThemeTestTree("font-size: 18px; color: var(--missing, #abcdef); " +
+ "background-color: var(--theme-background);")
+ fillThemeStyleVar(tree)
+ if actual := node.KramdownIAL[0][1]; actual != "font-size: 18px; color: #abcdef; background-color: #112233;" {
+ t.Fatalf("invalid inline styles affected Word fallback: %s", actual)
+ }
+}
+
+func inlineStyleThemeTestTree(style string) (tree *parse.Tree, node *ast.Node) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ node = &ast.Node{Type: ast.NodeParagraph, KramdownIAL: [][]string{{"style", style}}}
+ root.AppendChild(node)
+ return &parse.Tree{Root: root}, node
+}
+
+func setupThemeTest(t *testing.T, theme, css string) {
+ t.Helper()
+ oldDataDir, oldThemesPath, oldConf := util.DataDir, util.ThemesPath, Conf
+ tempDir := t.TempDir()
+ util.DataDir = filepath.Join(tempDir, "data")
+ util.ThemesPath = filepath.Join(tempDir, "themes")
+ Conf = NewAppConf()
+ Conf.Appearance = conf.NewAppearance()
+ Conf.Sync = conf.NewSync()
+ t.Cleanup(func() {
+ util.DataDir, util.ThemesPath, Conf = oldDataDir, oldThemesPath, oldConf
+ })
+
+ themeDir := filepath.Join(util.ThemesPath, theme)
+ if err := os.MkdirAll(themeDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(themeDir, "theme.css"), []byte(css), 0644); err != nil {
+ t.Fatal(err)
+ }
+}