feat: sync dashboard theme to plugin pages and prevent flash on load#8377
Merged
0 commit merged intoMay 28, 2026
Merged
Conversation
Contributor
There was a problem hiding this comment.
Code Review
This pull request introduces light and dark theme adaptation for AstrBot plugin pages, allowing the theme state to sync automatically. It updates the bridge SDK, backend routes, frontend views, and documentation, and adds corresponding tests. Feedback on the changes suggests using a case-insensitive regular expression to search for the <head> tag in the HTML rewriter to prevent duplicate tag injection when dealing with uppercase tags or tags with attributes.
Contributor
There was a problem hiding this comment.
Hey - I've found 2 issues, and left some high level feedback:
- The
isDarkgetter incustomizer.tshardcodesPurpleThemeDark, which will break if additional dark themes are introduced; consider deriving darkness from a more generic rule (e.g., amodefield or a naming convention likeendsWith('Dark')). - When
uiThemechanges you only resend context to the iframe, but the iframesrc(andtheme=query param) is not updated, so server-side HTML/asset rendering remains on the original theme; consider updatingiframeSrc(or reloading the iframe) on theme toggle so server-side theme hints stay in sync with the live context.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The `isDark` getter in `customizer.ts` hardcodes `PurpleThemeDark`, which will break if additional dark themes are introduced; consider deriving darkness from a more generic rule (e.g., a `mode` field or a naming convention like `endsWith('Dark')`).
- When `uiTheme` changes you only resend context to the iframe, but the iframe `src` (and `theme=` query param) is not updated, so server-side HTML/asset rendering remains on the original theme; consider updating `iframeSrc` (or reloading the iframe) on theme toggle so server-side theme hints stay in sync with the live context.
## Individual Comments
### Comment 1
<location path="astrbot/dashboard/routes/plugin.py" line_range="608-609" />
<code_context>
+ color_scheme_meta = (
+ f'<meta name="color-scheme" content="{theme}">'
+ )
+ if "<head>" in rewritten_html:
+ rewritten_html = rewritten_html.replace(
+ "<head>",
+ f"<head>\n {color_scheme_meta}",
</code_context>
<issue_to_address>
**issue (bug_risk):** Head-tag detection is case- and format-sensitive and can cause duplicate <head> insertion.
This plain-string `"<head>"` check will miss variants like `<head>\n`, `<head >`, or different casing, so the later `<html>` branch may inject a second `<head>` even when one already exists. Use a case‑insensitive regex such as `re.search(r"<head\b[^>]*>", rewritten_html, re.IGNORECASE)` to detect and reuse the existing `<head>` tag rather than creating a new one.
</issue_to_address>
### Comment 2
<location path="astrbot/dashboard/routes/plugin.py" line_range="280" />
<code_context>
self._get_by_path(locale_data, f"pages.{page_name}.title") or page_name
)
+ theme = request.args.get("theme", "").strip()
+
return {
</code_context>
<issue_to_address>
**issue (complexity):** Consider extracting shared theme parsing and HTML mutation into dedicated helpers to keep the main route logic simpler and more maintainable.
You can reduce the added complexity by centralizing theme handling and encapsulating the HTML mutation logic.
### 1. Centralize theme parsing/validation
The `request.args.get("theme", "").strip()` + `theme in ("dark", "light")` logic now appears in multiple places. Extract it into a helper to keep the rules in one place and simplify call sites.
```python
def _get_request_theme() -> str | None:
theme = request.args.get("theme", "").strip()
return theme if theme in ("dark", "light") else None
```
Use it where you need `isDark`:
```python
# before
theme = request.args.get("theme", "").strip()
return {
...
"i18n": plugin_i18n,
"isDark": theme == "dark",
}
# after
theme = _get_request_theme()
return {
...
"i18n": plugin_i18n,
"isDark": theme == "dark" if theme else False,
}
```
And in `_prepare_plugin_page_query_params`:
```python
def _prepare_plugin_page_query_params(... ) -> dict[str, str] | None:
params: dict[str, str] = {}
asset_token = request.args.get("asset_token", "").strip()
if not asset_token:
asset_token = self._issue_plugin_page_asset_token(plugin_name, page_name) or ""
if asset_token:
params["asset_token"] = asset_token
theme = _get_request_theme()
if theme:
params["theme"] = theme
return params or None
```
### 2. Extract and simplify HTML theme application
The inline block that mutates `rewritten_html` is doing several regex/string operations with nested conditionals. Moving this into a focused helper makes the main flow easier to follow and gives you one place to reason about the behavior.
```python
def _apply_theme_to_html(html: str, theme: str) -> str:
# add data-theme to <html ...>
html = re.sub(
r"(<html\b[^>]*?)>",
rf'\1 data-theme="{theme}">',
html,
count=1,
flags=re.IGNORECASE,
)
color_scheme_meta = f'<meta name="color-scheme" content="{theme}">'
# ensure <head> gets the meta tag (create <head> if missing)
if "<head>" in html:
return html.replace(
"<head>",
f"<head>\n {color_scheme_meta}",
1,
)
return re.sub(
r"(<html\b[^>]*?>)",
rf"\1\n <head>\n {color_scheme_meta}\n </head>",
html,
count=1,
flags=re.IGNORECASE,
)
```
Then the main HTML rewriting logic becomes:
```python
rewritten_html = _HTML_ASSET_ATTR_RE.sub(replace_attr, html_text)
theme = (extra_query_params or {}).get("theme") or _get_request_theme()
if theme:
rewritten_html = _apply_theme_to_html(rewritten_html, theme)
```
This keeps the existing behavior (validated theme, `data-theme` on `<html>`, `color-scheme` meta in `<head>` or newly created `<head>`) but:
- removes duplicated theme validation logic;
- isolates all HTML/regex manipulation in one helper;
- simplifies the main function to a straightforward “if theme: apply theme”.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
5 tasks
e960c14
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Plugin pages embedded via iframe had no awareness of the dashboard's light/dark theme state, causing two problems:
This PR adds an end-to-end theme sync mechanism so plugin pages automatically match the dashboard theme on load and react to live theme switching, with the initial theme applied server-side to eliminate flash.
Modifications / 改动点
Backend (plugin.py): Added theme query parameter propagation through the plugin page asset pipeline. The _get_plugin_page_initial_context now includes isDark. The HTML rewriter injects data-theme on and a tag server-side to prevent initial flash.
Bridge SDK (plugin_page_bridge.js): applyContext() now sets data-theme on document.documentElement when context includes isDark, enabling live theme switching.
Frontend (PluginPagePage.vue): Appends &theme=dark/light to iframe URL and includes isDark in postMessage context. Watches uiTheme to re-send context on theme toggle.
Store (customizer.ts): Added isDark getter.
Tests: Added tests for isDark in bridge SDK initial context (dark/light/absent/invalid params) and theme propagation in rewritten HTML (data-theme, color-scheme meta).
Docs: Added light/dark theme adaptation section to plugin-pages guide (zh + en).
This is NOT a breaking change. / 这不是一个破坏性变更。
Screenshots or Test Results / 运行截图或测试结果
Testing on the
astrbot_plugin_livingmemoryplugin showed that switching between light and dark themes using AstrBot's built-in theme switching function resulted in the Livingmemory WebUI switching themes accordingly. Furthermore, the WebUI could be switched back to the opposite theme without affecting the display of the AstrBot WebUI.The current default behavior is to maintain the same light/dark theme as the AstrBot WebUI when entering the plugin's WebUI.
Checklist / 检查清单
😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
/ 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
/ 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in
requirements.txtandpyproject.toml./ 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到
requirements.txt和pyproject.toml文件相应位置。😮 My changes do not introduce malicious code.
/ 我的更改没有引入恶意代码。
Summary by Sourcery
Synchronize the dashboard’s light/dark theme with plugin pages and eliminate initial theme flash for iframe-embedded plugin UIs.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: