Skip to content

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

:sparkles: Support theme frontend compatibility https://github.com/siyuan-note/siyuan/issues/13855

Daniel9a3eb0e8c366
diff --git a/app/src/config/tabs/appearanceRuntime.ts b/app/src/config/tabs/appearanceRuntime.ts
index 99a3fd9d48..d0ae0b8d57 100644
--- a/app/src/config/tabs/appearanceRuntime.ts
+++ b/app/src/config/tabs/appearanceRuntime.ts
@@ -6,7 +6,9 @@ import {exportLayout} from "../../layout/util";
import {syncHideToolbarLayout, updateBarModeIcon} from "../../layout/topBar";
/// #endif
import {fetchPost} from "../../util/fetch";
-import {loadAssets} from "../../util/assets";
+import {loadAssets, unloadThemeScript} from "../../util/assets";
+import {getFrontend} from "../../util/functions";
+import {shouldUnloadThemeScript} from "../../util/themeCompatibility";
import {remountOpenSettingTab} from "../setting/mount";
import {createConfigNamespaceApi} from "../util/namespaceApi";
@@ -48,38 +50,21 @@ const applyAppearanceConfig = async (data: Config.IAppearance) => {
return;
}
- if (window.siyuan.config.appearance.themeJS) {
- if (data.mode !== window.siyuan.config.appearance.mode ||
- (data.mode === window.siyuan.config.appearance.mode && (
- (data.mode === 0 && window.siyuan.config.appearance.themeLight !== data.themeLight) ||
- (data.mode === 1 && window.siyuan.config.appearance.themeDark !== data.themeDark))
- )
- ) {
- if (window.destroyTheme) {
- try {
- await window.destroyTheme();
- window.destroyTheme = undefined;
- document.getElementById("themeScript").remove();
- } catch (e) {
- console.error("destroyTheme error: " + e);
- }
- } else {
- /// #if MOBILE
- void reloadUI();
- /// #else
- void exportLayout({
- errorExit: false,
- cb() {
- window.location.reload();
- },
- });
- /// #endif
- return;
- }
- }
+ const prevAppearance = window.siyuan.config.appearance;
+ if (shouldUnloadThemeScript(prevAppearance, data, getFrontend()) && !await unloadThemeScript()) {
+ /// #if MOBILE
+ void reloadUI();
+ /// #else
+ void exportLayout({
+ errorExit: false,
+ cb() {
+ window.location.reload();
+ },
+ });
+ /// #endif
+ return;
}
- const prevAppearance = window.siyuan.config.appearance;
window.siyuan.config.appearance = data;
document.getElementById("status")?.classList.toggle("fn__none", data.hideStatusBar);
diff --git a/app/src/index.ts b/app/src/index.ts
index 13a60f896d..2f37c79dd0 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -48,7 +48,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 {setBodyHighlight} from "./util/assets";
+import {refreshThemeStyle, setBodyHighlight} from "./util/assets";
import {reloadSync} from "./util/reloadSync";
import {setTitle} from "./util/processTitle";
import {ensureUILayout} from "./util/ensureUILayout";
@@ -219,11 +219,7 @@ export class App {
progressBackgroundTask(data.data.tasks);
break;
case "refreshtheme":
- if ((window.siyuan.config.appearance.mode === 1 && window.siyuan.config.appearance.themeDark !== "midnight") || (window.siyuan.config.appearance.mode === 0 && window.siyuan.config.appearance.themeLight !== "daylight")) {
- (document.getElementById("themeStyle") as HTMLLinkElement).href = data.data.theme;
- } else {
- (document.getElementById("themeDefaultStyle") as HTMLLinkElement).href = data.data.theme;
- }
+ refreshThemeStyle(data.data.theme);
break;
case "openFileById":
openFileById({app: this, id: data.data.id, action: [Constants.CB_GET_FOCUS]});
diff --git a/app/src/protyle/util/addScript.ts b/app/src/protyle/util/addScript.ts
index f88263c215..47dfdb9c1a 100644
--- a/app/src/protyle/util/addScript.ts
+++ b/app/src/protyle/util/addScript.ts
@@ -40,5 +40,9 @@ export const addScript = (path: string, id: string) => {
scriptElement.id = id;
resolve(true);
};
+ scriptElement.onerror = () => {
+ scriptElement.remove();
+ resolve(false);
+ };
});
};
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 2d4cb0c0ec..3bfa28c0df 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -300,11 +300,11 @@ declare namespace Config {
/**
* List of installed light themes
*/
- lightThemes: { label: string; name: string }[];
+ lightThemes: IAppearanceTheme[];
/**
* List of installed dark themes
*/
- darkThemes: { label: string; name: string }[];
+ darkThemes: IAppearanceTheme[];
/**
* The current theme mode
* - `0`: Light theme
@@ -336,6 +336,12 @@ declare namespace Config {
entryVisibility: IEntryVisibility;
}
+ export interface IAppearanceTheme {
+ label: string;
+ name: string;
+ frontends?: string[];
+ }
+
export type TEntryVisibilityBase = "simple" | "full";
export interface IEntryVisibilityProfile {
diff --git a/app/src/util/assets.ts b/app/src/util/assets.ts
index ec96af99ba..ae5d2bc217 100644
--- a/app/src/util/assets.ts
+++ b/app/src/util/assets.ts
@@ -22,6 +22,7 @@ import {setCodeTheme} from "../protyle/render/util";
import {getBackend, getFrontend} from "./functions";
import {getWorkspaceName} from "./processTitle";
import {ensureSelectedCustomFont} from "./customFont";
+import {isCurrentThemeSupported, shouldUnloadThemeScript} from "./themeCompatibility";
let headingNumberMeasurementRefreshTimer: number;
const DEJAVU_EMOJI_PRESENTATION_UNICODE_RANGE = "U+25fd-25fe, U+2614-2615, U+2648-2653, U+267f, U+2693, U+26a1, " +
@@ -44,6 +45,49 @@ const scheduleHeadingNumberMeasurementRefresh = (styleElements: HTMLLinkElement[
schedule(styleElements.length > 0 ? Constants.TIMEOUT_LOAD : 0);
};
+const getThemeScriptElements = () => Array.from(document.querySelectorAll<HTMLScriptElement>(
+ "script[src*='/appearance/themes/'][src*='/theme.js']"
+));
+
+const removeThemeScriptElements = () => {
+ getThemeScriptElements().forEach((item) => item.remove());
+};
+
+export const unloadThemeScript = async () => {
+ const themeScriptElement = document.getElementById("themeScript");
+ const themeScriptElements = getThemeScriptElements();
+ if (!themeScriptElement && !window.destroyTheme) {
+ themeScriptElements.forEach((item) => item.remove());
+ return true;
+ }
+ if (!window.destroyTheme) {
+ return false;
+ }
+ try {
+ await window.destroyTheme();
+ window.destroyTheme = undefined;
+ themeScriptElement?.remove();
+ removeThemeScriptElements();
+ return true;
+ } catch (error) {
+ console.error("destroyTheme error: " + error);
+ return false;
+ }
+};
+
+export const refreshThemeStyle = (themeAddress: string) => {
+ const appearance = window.siyuan.config.appearance;
+ if (!isCurrentThemeSupported(appearance, getFrontend())) {
+ return;
+ }
+ const isCustomTheme = (appearance.mode === 1 && appearance.themeDark !== "midnight") ||
+ (appearance.mode === 0 && appearance.themeLight !== "daylight");
+ const styleElement = document.getElementById(isCustomTheme ? "themeStyle" : "themeDefaultStyle") as HTMLLinkElement;
+ if (styleElement) {
+ styleElement.href = themeAddress;
+ }
+};
+
export const loadAssets = (data: Config.IAppearance) => {
const changedThemeStyleElements: HTMLLinkElement[] = [];
let themeStylesChanged = false;
@@ -86,7 +130,9 @@ export const loadAssets = (data: Config.IAppearance) => {
themeStylesChanged = true;
}
const styleElement = document.getElementById("themeStyle");
- if ((data.mode === 1 && data.themeDark !== "midnight") || (data.mode === 0 && data.themeLight !== "daylight")) {
+ const themeSupported = isCurrentThemeSupported(data, getFrontend());
+ if (themeSupported && ((data.mode === 1 && data.themeDark !== "midnight") ||
+ (data.mode === 0 && data.themeLight !== "daylight"))) {
const themeAddress = `/appearance/themes/${data.mode === 1 ? data.themeDark : data.themeLight}/theme.css?v=${data.themeVer}`;
if (styleElement) {
if (!styleElement.getAttribute("href").startsWith(themeAddress)) {
@@ -135,14 +181,13 @@ export const loadAssets = (data: Config.IAppearance) => {
/// #endif
setCodeTheme();
- const themeScriptElement = document.getElementById("themeScript");
const themeScriptAddress = `/appearance/themes/${data.mode === 1 ? data.themeDark : data.themeLight}/theme.js?v=${data.themeVer}`;
- if (themeScriptElement) {
- if (!themeScriptElement.getAttribute("src").startsWith(themeScriptAddress)) {
- themeScriptElement.remove();
- addScript(themeScriptAddress, "themeScript");
- }
- } else {
+ const themeScriptURL = new URL(themeScriptAddress, window.location.href).href;
+ const themeScriptElements = getThemeScriptElements();
+ if (!data.themeJS || !themeSupported) {
+ removeThemeScriptElements();
+ } else if (!themeScriptElements.some((item) => item.src === themeScriptURL)) {
+ removeThemeScriptElements();
addScript(themeScriptAddress, "themeScript");
}
@@ -203,31 +248,23 @@ export const initAssets = () => {
fetchPost("/api/system/setAppearanceMode", {
mode: OSTheme === "light" ? 0 : 1
}, async response => {
- if (window.siyuan.config.appearance.themeJS) {
- if (window.destroyTheme) {
- try {
- await window.destroyTheme();
- window.destroyTheme = undefined;
- document.getElementById("themeScript").remove();
- } catch (e) {
- console.error("destroyTheme error: " + e);
- }
- } else {
- /// #if !MOBILE
- exportLayout({
- cb() {
- window.location.reload();
- },
- errorExit: false,
- });
- /// #else
- window.location.reload();
- /// #endif
- return;
- }
+ const nextAppearance = response.data.appearance as Config.IAppearance;
+ if (shouldUnloadThemeScript(window.siyuan.config.appearance, nextAppearance, getFrontend()) &&
+ !await unloadThemeScript()) {
+ /// #if !MOBILE
+ exportLayout({
+ cb() {
+ window.location.reload();
+ },
+ errorExit: false,
+ });
+ /// #else
+ window.location.reload();
+ /// #endif
+ return;
}
- window.siyuan.config.appearance = response.data.appearance;
- loadAssets(response.data.appearance);
+ window.siyuan.config.appearance = nextAppearance;
+ loadAssets(nextAppearance);
});
});
};
diff --git a/app/src/util/themeCompatibility.test.ts b/app/src/util/themeCompatibility.test.ts
new file mode 100644
index 0000000000..ae95da5eed
--- /dev/null
+++ b/app/src/util/themeCompatibility.test.ts
@@ -0,0 +1,89 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ getCurrentAppearanceTheme,
+ isCurrentThemeSupported,
+ isThemeFrontendSupported,
+ shouldUnloadThemeScript
+} from "./themeCompatibility";
+
+const appearance = (overrides: Partial<Config.IAppearance> = {}) => ({
+ mode: 0,
+ themeLight: "light-theme",
+ themeDark: "dark-theme",
+ themeVer: "1.0.0",
+ themeJS: true,
+ lightThemes: [{name: "light-theme", label: "Light", frontends: ["desktop"]}],
+ darkThemes: [{name: "dark-theme", label: "Dark", frontends: ["mobile"]}],
+ ...overrides,
+} as Config.IAppearance);
+
+describe("theme frontend compatibility", () => {
+ it("treats missing, empty, and all frontends as supported", () => {
+ assert.equal(isThemeFrontendSupported(undefined, "mobile"), true);
+ assert.equal(isThemeFrontendSupported(null, "mobile"), true);
+ assert.equal(isThemeFrontendSupported([], "mobile"), true);
+ assert.equal(isThemeFrontendSupported(["all"], "mobile"), true);
+ });
+
+ it("matches frontends exactly", () => {
+ assert.equal(isThemeFrontendSupported(["desktop"], "desktop"), true);
+ assert.equal(isThemeFrontendSupported(["desktop"], "browser-desktop"), false);
+ assert.equal(isThemeFrontendSupported(["browser-desktop"], "browser-desktop"), true);
+ });
+
+ it("selects the theme for the current appearance mode", () => {
+ assert.equal(getCurrentAppearanceTheme(appearance())?.name, "light-theme");
+ assert.equal(getCurrentAppearanceTheme(appearance({mode: 1}))?.name, "dark-theme");
+ });
+
+ it("falls back to supported when theme metadata is unavailable", () => {
+ assert.equal(isCurrentThemeSupported(appearance({lightThemes: []}), "mobile"), true);
+ });
+
+ it("uses each mode's frontend declaration", () => {
+ assert.equal(isCurrentThemeSupported(appearance(), "desktop"), true);
+ assert.equal(isCurrentThemeSupported(appearance(), "mobile"), false);
+ assert.equal(isCurrentThemeSupported(appearance({mode: 1}), "mobile"), true);
+ });
+});
+
+describe("theme script lifecycle", () => {
+ it("unloads when the active theme identity changes", () => {
+ assert.equal(shouldUnloadThemeScript(appearance(), appearance({mode: 1}), "desktop"), true);
+ assert.equal(shouldUnloadThemeScript(appearance(), appearance({themeLight: "other"}), "desktop"), true);
+ assert.equal(shouldUnloadThemeScript(appearance(), appearance({themeVer: "2.0.0"}), "desktop"), true);
+ });
+
+ it("unloads when the next theme has no script or is incompatible", () => {
+ assert.equal(shouldUnloadThemeScript(appearance(), appearance({themeJS: false}), "desktop"), true);
+ const previous = appearance({
+ lightThemes: [{name: "light-theme", label: "Light", frontends: ["mobile"]}],
+ });
+ assert.equal(shouldUnloadThemeScript(previous, appearance(), "mobile"), true);
+ });
+
+ it("keeps a compatible unchanged script", () => {
+ assert.equal(shouldUnloadThemeScript(appearance(), appearance(), "desktop"), false);
+ });
+
+ it("does not unload when the previous theme script was not loaded", () => {
+ assert.equal(shouldUnloadThemeScript(
+ appearance({themeJS: false}),
+ appearance({mode: 1}),
+ "desktop",
+ ), false);
+ assert.equal(shouldUnloadThemeScript(
+ appearance(),
+ appearance({mode: 1}),
+ "mobile",
+ ), false);
+ });
+
+ it("loads a newly compatible unchanged script without unloading", () => {
+ const previous = appearance({
+ lightThemes: [{name: "light-theme", label: "Light", frontends: ["mobile"]}],
+ });
+ assert.equal(shouldUnloadThemeScript(previous, appearance(), "desktop"), false);
+ });
+});
diff --git a/app/src/util/themeCompatibility.ts b/app/src/util/themeCompatibility.ts
new file mode 100644
index 0000000000..267171ebf2
--- /dev/null
+++ b/app/src/util/themeCompatibility.ts
@@ -0,0 +1,36 @@
+export const isThemeFrontendSupported = (
+ frontends: string[] | null | undefined,
+ frontend: string,
+) => {
+ if (!frontends?.length || frontends.includes("all")) {
+ return true;
+ }
+ return frontends.includes(frontend);
+};
+
+export const getCurrentAppearanceTheme = (appearance: Config.IAppearance) => {
+ const themeName = appearance.mode === 1 ? appearance.themeDark : appearance.themeLight;
+ const themes = appearance.mode === 1 ? appearance.darkThemes : appearance.lightThemes;
+ return themes?.find((item) => item.name === themeName);
+};
+
+export const getCurrentThemeName = (appearance: Config.IAppearance) => {
+ return appearance.mode === 1 ? appearance.themeDark : appearance.themeLight;
+};
+
+export const isCurrentThemeSupported = (appearance: Config.IAppearance, frontend: string) => {
+ return isThemeFrontendSupported(getCurrentAppearanceTheme(appearance)?.frontends, frontend);
+};
+
+export const shouldUnloadThemeScript = (
+ previous: Config.IAppearance,
+ next: Config.IAppearance,
+ frontend: string,
+) => {
+ const previousThemeScriptLoaded = previous.themeJS && isCurrentThemeSupported(previous, frontend);
+ return previousThemeScriptLoaded && (previous.mode !== next.mode ||
+ getCurrentThemeName(previous) !== getCurrentThemeName(next) ||
+ previous.themeVer !== next.themeVer ||
+ !next.themeJS ||
+ !isCurrentThemeSupported(next, frontend));
+};
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index fb0bbd7dc5..701cd201bd 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 {setBodyHighlight} from "../util/assets";
+import {refreshThemeStyle, setBodyHighlight} from "../util/assets";
import {reloadSync} from "../util/reloadSync";
import {setTitle} from "../util/processTitle";
import {ensureUILayout} from "../util/ensureUILayout";
@@ -166,11 +166,7 @@ class App {
progressBackgroundTask(data.data.tasks);
break;
case "refreshtheme":
- if ((window.siyuan.config.appearance.mode === 1 && window.siyuan.config.appearance.themeDark !== "midnight") || (window.siyuan.config.appearance.mode === 0 && window.siyuan.config.appearance.themeLight !== "daylight")) {
- (document.getElementById("themeStyle") as HTMLLinkElement).href = data.data.theme;
- } else {
- (document.getElementById("themeDefaultStyle") as HTMLLinkElement).href = data.data.theme;
- }
+ refreshThemeStyle(data.data.theme);
break;
case "openFileById":
openFileById({app: this, id: data.data.id, action: [Constants.CB_GET_FOCUS]});
diff --git a/kernel/api/system.go b/kernel/api/system.go
index 6907ec56c9..07d06878ab 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -1114,11 +1114,7 @@ func setAppearanceMode(c *gin.Context) {
mode := int(arg["mode"].(float64))
model.Conf.Appearance.Mode = mode
- if 0 == mode {
- model.Conf.Appearance.ThemeJS = gulu.File.IsExist(filepath.Join(util.ThemesPath, model.Conf.Appearance.ThemeLight, "theme.js"))
- } else {
- model.Conf.Appearance.ThemeJS = gulu.File.IsExist(filepath.Join(util.ThemesPath, model.Conf.Appearance.ThemeDark, "theme.js"))
- }
+ model.LoadThemes()
model.Conf.Save()
ret.Data = map[string]any{
diff --git a/kernel/conf/appearance.go b/kernel/conf/appearance.go
index c019465b93..92d18348f1 100644
--- a/kernel/conf/appearance.go
+++ b/kernel/conf/appearance.go
@@ -132,8 +132,9 @@ func NormalizeEntryVisibility(entryVisibility *EntryVisibility, fallback string)
}
type AppearanceTheme struct {
- Name string `json:"name"` // daylight
- Label string `json:"label"` // i18n display name
+ Name string `json:"name"` // daylight
+ Label string `json:"label"` // i18n display name
+ Frontends []string `json:"frontends,omitempty"` // 支持的前端
}
type AppearanceIcon struct {
diff --git a/kernel/model/appearance.go b/kernel/model/appearance.go
index 60056c2dec..79029ad9f8 100644
--- a/kernel/model/appearance.go
+++ b/kernel/model/appearance.go
@@ -165,7 +165,7 @@ func LoadThemes() {
modes = *themeConf.Modes
}
for _, mode := range modes {
- t := &conf.AppearanceTheme{Name: name}
+ t := &conf.AppearanceTheme{Name: name, Frontends: themeConf.Frontends}
if isBuiltInTheme(name) {
t.Label = name + Conf.Language(281)
} else {