Skip to content

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

:sparkles: Support global default fonts for dynamic icons https://github.com/siyuan-note/siyuan/issues/19941

Daniel75999ee563e8
diff --git a/app/src/config/tabs/appearanceRuntime.test.ts b/app/src/config/tabs/appearanceRuntime.test.ts
index 3f664fa5c1..358cb1e83f 100644
--- a/app/src/config/tabs/appearanceRuntime.test.ts
+++ b/app/src/config/tabs/appearanceRuntime.test.ts
@@ -8,16 +8,20 @@ import {ModuleKind, transpileModule} from "typescript";
const {parse} = require("ifdef-loader/preprocessor");
for (const mobile of [true, false]) {
- for (const change of ["gradient", "duplicate", "theme", "initial"] as const) {
+ for (const change of ["gradient", "duplicate", "theme", "initial", "font", "font-reset"] as const) {
test(`appearance updates preserve gradient controls without skipping theme initialization (${change}, mobile=${mobile})`, async () => {
const source = readFileSync(resolve(process.cwd(), "src/config/tabs/appearanceRuntime.ts"), "utf8");
const processed = parse(source, {MOBILE: mobile, BROWSER: true}, false, true);
const code = transpileModule(processed, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;
- const appearance = {lang: "en_US", mode: 0, bodyGradient: {mode: "auto"}};
+ const appearance = {
+ lang: "en_US", mode: 0, bodyGradient: {mode: "auto"},
+ globalFontFamilies: change === "font-reset" ? [{family: "Arial", weight: 700}] : [],
+ };
const next = change === "initial" ? appearance : {
...appearance,
mode: change === "theme" ? 1 : 0,
bodyGradient: {mode: change === "duplicate" ? "auto" : "custom"},
+ globalFontFamilies: change === "font" ? [{family: "Arial", weight: 700}] : [],
};
const siyuan = {config: {appearance}};
const calls: string[] = [];
@@ -49,6 +53,7 @@ for (const mobile of [true, false]) {
assert.equal(calls.includes("setBodyHighlight"), updatesInPlace);
assert.equal(calls.includes("loadAssets"), !updatesInPlace);
assert.equal(calls.includes("remountOpenSettingTab"), !updatesInPlace && !mobile);
+ assert.equal(calls.includes("refreshDynamicIcons"), change === "font" || change === "font-reset");
});
}
}
diff --git a/app/src/config/tabs/appearanceRuntime.ts b/app/src/config/tabs/appearanceRuntime.ts
index 78ffae5b67..7b0816b53e 100644
--- a/app/src/config/tabs/appearanceRuntime.ts
+++ b/app/src/config/tabs/appearanceRuntime.ts
@@ -21,6 +21,7 @@ import {getCurrentThemeName, isCurrentThemeSupported, shouldUnloadThemeScript} f
import {remountOpenSettingTab} from "../setting/mount";
import {createConfigNamespaceApi} from "../util/namespaceApi";
import {syncBodyGradient} from "./bodyGradient";
+import {refreshDynamicIcons} from "../../emoji/dynamicIcon";
/** 主题模式下拉框初值:合并 mode / modeOS */
export const appearanceThemeModeValue = (): number =>
@@ -116,6 +117,7 @@ const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppear
if (JSON.stringify(data.globalFontFamilies) !== JSON.stringify(prevAppearance.globalFontFamilies)) {
await setInlineStyle();
refreshHeadingNumberMeasurements();
+ refreshDynamicIcons();
}
/// #if !MOBILE
void remountOpenSettingTab("appearance");
diff --git a/app/src/emoji/dynamicIcon.test.ts b/app/src/emoji/dynamicIcon.test.ts
new file mode 100644
index 0000000000..ae0829c510
--- /dev/null
+++ b/app/src/emoji/dynamicIcon.test.ts
@@ -0,0 +1,46 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {getDynamicIconValue, refreshDynamicIcons} from "./dynamicIcon";
+
+test("font refresh reloads only local dynamic icons and preserves saved values", () => {
+ assert.equal(getDynamicIconValue("api/icon/getDynamicIcon?_fontRefresh=old"), "api/icon/getDynamicIcon");
+ const sources = [
+ "api/icon/getDynamicIcon?type=8&content=%E6%97%A5&id=target",
+ "/api/icon/getDynamicIcon?type=1&date=&_fontRefresh=old",
+ "http://localhost/api/icon/getDynamicIcon?type=2",
+ "https://example.com/api/icon/getDynamicIcon?type=1",
+ "/emojis/custom.svg",
+ "http://[invalid",
+ ];
+ const images = sources.map(src => ({
+ src,
+ getAttribute: () => src,
+ setAttribute(name: string, value: string) {
+ assert.equal(name, "src");
+ this.src = value;
+ },
+ }));
+ const originalDocument = Object.getOwnPropertyDescriptor(globalThis, "document");
+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ Object.defineProperty(globalThis, "document", {configurable: true, value: {
+ baseURI: "http://localhost/", querySelectorAll: () => images,
+ }});
+ Object.defineProperty(globalThis, "window", {configurable: true, value: {location: {origin: "http://localhost"}}});
+ try {
+ refreshDynamicIcons();
+ for (let i = 0; i < 3; i++) {
+ assert.match(images[i].src, /[?&]_fontRefresh=\d+$/);
+ assert.equal(new URL(images[i].src, "http://localhost").searchParams.getAll("_fontRefresh").length, 1);
+ assert.equal(getDynamicIconValue(images[i].src), getDynamicIconValue(sources[i]));
+ }
+ assert.deepEqual(images.slice(3).map(image => image.src), sources.slice(3));
+ } finally {
+ for (const [name, descriptor] of [["document", originalDocument], ["window", originalWindow]] as const) {
+ if (descriptor) {
+ Object.defineProperty(globalThis, name, descriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, name);
+ }
+ }
+ }
+});
diff --git a/app/src/emoji/dynamicIcon.ts b/app/src/emoji/dynamicIcon.ts
new file mode 100644
index 0000000000..85712c3de1
--- /dev/null
+++ b/app/src/emoji/dynamicIcon.ts
@@ -0,0 +1,31 @@
+const FONT_REFRESH_PARAM = "_fontRefresh";
+
+export const getDynamicIconValue = (src: string): string => {
+ const [path, query = ""] = src.split("?", 2);
+ const params = new URLSearchParams(query);
+ if (!params.has(FONT_REFRESH_PARAM)) {
+ return src;
+ }
+ params.delete(FONT_REFRESH_PARAM);
+ const value = params.toString();
+ return value ? `${path}?${value}` : path;
+};
+
+export const refreshDynamicIcons = () => {
+ const revision = Date.now().toString();
+ document.querySelectorAll<HTMLImageElement>("img[src]").forEach(image => {
+ const src = image.getAttribute("src");
+ let url: URL;
+ try {
+ url = new URL(src, document.baseURI);
+ } catch {
+ return;
+ }
+ if (url.origin !== window.location.origin || !url.pathname.endsWith("/api/icon/getDynamicIcon")) {
+ return;
+ }
+ // 刷新标记仅用于重新请求图片,选择图标时移除,不写入图标属性。
+ const value = getDynamicIconValue(src);
+ image.setAttribute("src", `${value}${value.includes("?") ? "&" : "?"}${FONT_REFRESH_PARAM}=${revision}`);
+ });
+};
diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.ts
index df6b3e8769..8f170dd746 100644
--- a/app/src/emoji/index.ts
+++ b/app/src/emoji/index.ts
@@ -40,6 +40,7 @@ import {getFileTreeIconHTML, updateFileTreeItemIcon} from "./fileTreeIcon";
import {bindBottomSheetDialog} from "../mobile/util/bindBottomSheetDialog";
import {activeBlur} from "../mobile/util/keyboardToolbar";
import {bindEmojiSheetSelection} from "../mobile/util/bindEmojiSheetSelection";
+import {getDynamicIconValue} from "./dynamicIcon";
export {unicode2Emoji};
@@ -1457,7 +1458,7 @@ export const openEmojiPanel = (
unicode = target.getAttribute("data-unicode");
dialog.destroy();
} else if (target.classList.contains("emoji__dynamic-item")) {
- unicode = target.getAttribute("src");
+ unicode = getDynamicIconValue(target.getAttribute("src"));
dialog.destroy();
} else {
// 随机
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 2fe196bc0f..d8c4127e7e 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -304,7 +304,7 @@ declare namespace Config {
light: {color: string; opacity: number};
dark: {color: string; opacity: number};
};
- /** 全局默认字体,按优先级从高到低排列 */
+ /** 全局默认字体,按优先级从高到低排列;动态图标也使用此列表和首选字重,字体由客户端解析 */
globalFontFamilies: IEditor["fontFamilies"];
/**
* Close button behavior
diff --git a/kernel/api/icon.go b/kernel/api/icon.go
index a6dd1dc6a8..5e0dee0d89 100644
--- a/kernel/api/icon.go
+++ b/kernel/api/icon.go
@@ -28,6 +28,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -179,6 +180,12 @@ var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Con
svg = generateTypeOneSVG(color, dateInfo)
}
+ var fonts []*conf.EditorFont
+ if nil != model.Conf.Appearance {
+ fonts = model.Conf.Appearance.GlobalFontFamilies
+ }
+ svg = applyDynamicIconFont(svg, fonts)
+
if !model.Conf.Editor.AllowSVGScript {
var err error
svg, err = util.SanitizeSVG(svg)
@@ -197,6 +204,36 @@ var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Con
return apicontract.SuccessBinary("image/svg+xml", []byte(svg))
})
+// applyDynamicIconFont 将全局字体和首选字重应用到 SVG 根节点,供所有文本继承。
+func applyDynamicIconFont(svg string, fonts []*conf.EditorFont) string {
+ const fallback = "-apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'"
+ families := make([]string, 0, len(fonts)+1)
+ weight := 400
+ for _, font := range fonts {
+ if nil == font || "" == font.Family {
+ continue
+ }
+ if 0 == len(families) && 1 <= font.Weight && font.Weight <= 1000 {
+ weight = font.Weight
+ }
+ // 字体名称作为 CSS 字符串编码,再对整个属性进行 XML 转义。
+ var family strings.Builder
+ family.WriteByte('"')
+ for _, char := range font.Family {
+ if '\\' == char || '"' == char || char < 0x20 || 0x7f == char {
+ fmt.Fprintf(&family, "\\%x ", char)
+ } else {
+ family.WriteRune(char)
+ }
+ }
+ family.WriteByte('"')
+ families = append(families, family.String())
+ }
+ families = append(families, fallback)
+ attributes := fmt.Sprintf(`<svg font-family="%s" font-weight="%d" `, html.EscapeString(strings.Join(families, ", ")), weight)
+ return strings.Replace(svg, "<svg ", attributes, 1)
+}
+
// dynamicIconContentAccessable 判断调用方是否可读取动态图标模板内容所引用的块。
// 管理员与编辑者拥有工作区读权限,只读角色则需要通过发布访问控制(禁用、密码与加密笔记本门禁)。
func dynamicIconContentAccessable(c *gin.Context, id string) bool {
@@ -351,10 +388,10 @@ func generateTypeOneSVG(color string, dateInfo map[string]any) string {
<svg id="dynamic_icon_type1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M512,447.5c0,32-25,57-57,57H57c-32,0-57-25-57-57V120.5c0-31,25-57,57-57h398c32,0,57,26,57,57v327Z" style="fill: #ecf2f7;"/>
<path d="M39,0h434c21.52,0,39,17.48,39,39v146H0V39C0,17.48,17.48,0,39,0Z" style="fill: %s;"/>
- <text transform="translate(22 146.5)" style="fill: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 100px;">%s</text>
- <text x="50%%" y="392.5" style="fill: #66757f; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 240px; text-anchor: middle">%d</text>
- <text x="50%%" y="472.5" style="fill: #66757f; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 64px; text-anchor: middle">%s</text>
- <text transform="translate(331.03 148.44)" style="fill: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 71.18px;">%d</text>
+ <text transform="translate(22 146.5)" style="fill: #fff; font-size: 100px;">%s</text>
+ <text x="50%%" y="392.5" style="fill: #66757f; font-size: 240px; text-anchor: middle">%d</text>
+ <text x="50%%" y="472.5" style="fill: #66757f; font-size: 64px; text-anchor: middle">%s</text>
+ <text transform="translate(331.03 148.44)" style="fill: #fff; font-size: 71.18px;">%d</text>
</svg>
`, colorScheme.Primary, dateInfo["month"], dateInfo["day"], dateInfo["weekday"], dateInfo["year"])
}
@@ -367,9 +404,9 @@ func generateTypeTwoSVG(color string, dateInfo map[string]any) string {
<svg id="dynamic_icon_type2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M512,447.5c0,32-25,57-57,57H57c-32,0-57-25-57-57V120.5c0-31,25-57,57-57h398c32,0,57,26,57,57v327Z" style="fill: #ecf2f7;"/>
<path d="M39,0h434c21.52,0,39,17.48,39,39v146H0V39C0,17.48,17.48,0,39,0Z" style="fill: %s;"/>
- <text transform="translate(22 146.5)" style="fill: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 100px;">%s</text>
- <text x="50%%" y="420.5" style="fill: #66757f; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 256px;text-anchor: middle">%d</text>
- <text transform="translate(331.03 148.44)" style="fill: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 71.18px;">%d</text>
+ <text transform="translate(22 146.5)" style="fill: #fff; font-size: 100px;">%s</text>
+ <text x="50%%" y="420.5" style="fill: #66757f; font-size: 256px;text-anchor: middle">%d</text>
+ <text transform="translate(331.03 148.44)" style="fill: #fff; font-size: 71.18px;">%d</text>
</svg>
`, colorScheme.Primary, dateInfo["month"], dateInfo["day"], dateInfo["year"])
}
@@ -390,8 +427,8 @@ func generateTypeThreeSVG(color string, dateInfo map[string]any) string {
<circle cx="382.5" cy="135" r="14"/>
<circle cx="382.5" cy="93" r="14"/>
</g>
- <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%d</text>
- <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%s</text>
+ <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; ">%d</text>
+ <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%s</text>
</svg>
`, colorScheme.Primary, colorScheme.Secondary, dateInfo["year"], dateInfo["month"])
}
@@ -412,7 +449,7 @@ func generateTypeFourSVG(color string, dateInfo map[string]any) string {
<circle cx="382.5" cy="135" r="14"/>
<circle cx="382.5" cy="93" r="14"/>
</g>
- <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%d</text>
+ <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%d</text>
</svg>
`, colorScheme.Primary, colorScheme.Secondary, dateInfo["year"])
}
@@ -433,8 +470,8 @@ func generateTypeFiveSVG(color string, dateInfo map[string]any) string {
<circle cx="382.5" cy="135" r="14"/>
<circle cx="382.5" cy="93" r="14"/>
</g>
- <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%d</text>
- <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%s</text>
+ <text transform="translate(22 146.5)" style="fill: #fff;font-size: 120px; ">%d</text>
+ <text x="50%%" y="410.5" style="fill: #66757f;font-size: 200px;text-anchor: middle;">%s</text>
</svg>
`, colorScheme.Primary, colorScheme.Secondary, dateInfo["isoYear"], dateInfo["week"])
}
@@ -488,7 +525,7 @@ func generateTypeSixSVG(color string, lang string, weekdayType string, dateInfo
<circle cx="382.5" cy="113.5" r="14"/>
<circle cx="382.5" cy="71.5" r="14"/>
</g>
- <text id="weekday" x="50%%" y="65%%" style="fill: %s; font-size: %.2fpx; text-anchor: middle; dominant-baseline:middle; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei';">%s</text>
+ <text id="weekday" x="50%%" y="65%%" style="fill: %s; font-size: %.2fpx; text-anchor: middle; dominant-baseline:middle;">%s</text>
</svg>`, colorScheme.Primary, colorScheme.Secondary, colorScheme.Primary, fontSize, weekday)
}
@@ -557,11 +594,11 @@ func generateTypeSevenSVG(color string, lang string, dateInfo map[string]any) st
<svg id="dynamic_icon_type7" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path id="bottom" d="M512,447.5c0,32-25,57-57,57H57c-32,0-57-25-57-57V120.5c0-31,25-57,57-57h398c32,0,57,26,57,57v327Z" style="fill: #ecf2f7;"/>
<path id="top" d="M39,0h434c21.52,0,39,17.48,39,39v146H0V39C0,17.48,17.48,0,39,0Z" style="fill: %s;"/>
- <text id="year" transform="translate(46.1 78.92)" style="fill: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 60px;">%d</text>
- <text id="day" transform="translate(43.58 148.44)" style="fill: #fff; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 60px;">%s</text>
- <text id="passStr" transform="translate(400 148.44)" style="fill: #fff; text-anchor: middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; font-size: 71.18px;">%s</text>
- <text id="diffDays" x="50%%" y="65%%" style="font-size: %.0fpx; fill: #66757f; text-anchor: middle; dominant-baseline:middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%s</text>
- <text id="dayStr" x="50%%" y="472.5" style="font-size: 64px; text-anchor: middle; fill: #66757f; font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei';">%s</text>
+ <text id="year" transform="translate(46.1 78.92)" style="fill: #fff; font-size: 60px;">%d</text>
+ <text id="day" transform="translate(43.58 148.44)" style="fill: #fff; font-size: 60px;">%s</text>
+ <text id="passStr" transform="translate(400 148.44)" style="fill: #fff; text-anchor: middle;font-size: 71.18px;">%s</text>
+ <text id="diffDays" x="50%%" y="65%%" style="font-size: %.0fpx; fill: #66757f; text-anchor: middle; dominant-baseline:middle;">%s</text>
+ <text id="dayStr" x="50%%" y="472.5" style="font-size: 64px; text-anchor: middle; fill: #66757f;">%s</text>
</svg>`, colorScheme.Primary, dateInfo["year"], dateInfo["date"], tipText, fontSize, diffDaysText, dayStr)
}
@@ -618,7 +655,7 @@ func generateTypeEightSVG(color, content string) string {
return fmt.Sprintf(`
<svg id="dynamic_icon_type8" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M39,0h434c20.97,0,38,17.03,38,38v412c0,33.11-26.89,60-60,60H60c-32.56,0-59-26.44-59-59V38C1,17.03,18.03,0,39,0Z" style="fill: %s;"/>
- <text x="50%%" y="55%%" dy="%s" style="font-size: %.2fpx; fill: #fff; text-anchor: middle; dominant-baseline:middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%s</text>
+ <text x="50%%" y="55%%" dy="%s" style="font-size: %.2fpx; fill: #fff; text-anchor: middle; dominant-baseline:middle;">%s</text>
</svg>
`, colorScheme.Primary, dy, fontSize, escapedContent)
}
diff --git a/kernel/api/icon_test.go b/kernel/api/icon_test.go
index e63d5cb5fd..c41f2c04cc 100644
--- a/kernel/api/icon_test.go
+++ b/kernel/api/icon_test.go
@@ -9,6 +9,8 @@
package api
import (
+ "encoding/xml"
+ "fmt"
"net/http"
"net/http/httptest"
"strings"
@@ -19,6 +21,65 @@ import (
"github.com/siyuan-note/siyuan/kernel/model"
)
+func TestAPIContractDynamicIconGlobalFonts(t *testing.T) {
+ oldConf := model.Conf
+ model.Conf = model.NewAppConf()
+ model.Conf.Editor = conf.NewEditor()
+ model.Conf.Appearance = conf.NewAppearance()
+ t.Cleanup(func() { model.Conf = oldConf })
+ const fallback = "-apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'"
+ for _, test := range []struct {
+ name string
+ fonts []*conf.EditorFont
+ family string
+ weight string
+ }{
+ {"default", nil, fallback, "400"},
+ {"ordered", []*conf.EditorFont{{Family: "Arial", Weight: 700}, {Family: "思源黑体", Weight: 300}}, `"Arial", "思源黑体", ` + fallback, "700"},
+ {"invalid", []*conf.EditorFont{nil, {Family: ""}, {Family: "Arial", Weight: 1001}}, `"Arial", ` + fallback, "400"},
+ {"escaped", []*conf.EditorFont{{Family: "A\"\\\n<&';font-weight:1", Weight: 500}}, `"A\22 \5c \a <&';font-weight:1", ` + fallback, "500"},
+ } {
+ for _, allowScript := range []bool{false, true} {
+ for iconType := 1; iconType <= 8; iconType++ {
+ t.Run(fmt.Sprintf("%s/type%d/script%t", test.name, iconType, allowScript), func(t *testing.T) {
+ model.Conf.Appearance.GlobalFontFamilies = test.fonts
+ model.Conf.Editor.AllowSVGScript = allowScript
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/icon/getDynamicIcon?type=%d&content=Text&date=2026-09-29&lang=en", iconType), nil)
+ getDynamicIcon(context)
+ requireAPIContract(t, http.MethodGet, "/api/icon/getDynamicIcon", recorder)
+ var svg struct {
+ XMLName xml.Name `xml:"svg"`
+ Family string `xml:"font-family,attr"`
+ Weight string `xml:"font-weight,attr"`
+ Texts []struct {
+ Style string `xml:"style,attr"`
+ } `xml:"text"`
+ }
+ if err := xml.Unmarshal(recorder.Body.Bytes(), &svg); err != nil {
+ t.Fatal(err)
+ }
+ if svg.Family != test.family || svg.Weight != test.weight {
+ t.Fatalf("unexpected font: %q / %q", svg.Family, svg.Weight)
+ }
+ if len(svg.Texts) == 0 {
+ t.Fatal("missing icon text")
+ }
+ for _, text := range svg.Texts {
+ if strings.Contains(text.Style, "font-family") || strings.Contains(text.Style, "font-weight") {
+ t.Fatalf("text overrides inherited font: %s", text.Style)
+ }
+ }
+ if recorder.Header().Get("Cache-Control") != "no-cache" || recorder.Header().Get("Vary") != "Cookie" {
+ t.Fatal("dynamic icon cache headers changed")
+ }
+ })
+ }
+ }
+ }
+}
+
func TestGenerateTypeEightSVGEscapesContent(t *testing.T) {
content := `</text><desc><style><script>alert(1)</script></style></desc><text>`
output := generateTypeEightSVG("red", content)
diff --git a/kernel/apicontract/icon.go b/kernel/apicontract/icon.go
index 8c6601393c..3e22e59182 100644
--- a/kernel/apicontract/icon.go
+++ b/kernel/apicontract/icon.go
@@ -1,5 +1,7 @@
package apicontract
+// DynamicIconRequest 生成动态图标 SVG,字体按全局默认字体的优先顺序回退,并使用首选字体的字重。
+// 未配置全局字体时使用内置字体列表;字体由客户端解析,不嵌入字体文件,缺失字体时继续回退。
type DynamicIconRequest struct {
Type string `json:"type" api:"optional"`
Color string `json:"color" api:"optional"`