♻️ refactor(ui): 重构 UI 渲染系统并优化资源管理 (#2094)

* ♻️ refactor(ui): 重构 UI 渲染系统并优化资源管理

- 【重构】重构 `RendererService` 架构,解耦模板引擎、主题管理与截图引擎
- 【重构】重构 `ui` 模块,采用组件注册机制与数据模型驱动,移除旧版 `builders`
- 【功能】新增 UI 热重载模式,支持在不重启的情况下实时预览 HTML/CSS 修改
- 【功能】增强启动项资源检查,支持基于 `resources.spec` 的版本校验与自动更新
- 【优化】统一内置插件的 UI 渲染逻辑,迁移至新的 `ui.table`、`ui.markdown` 等工厂接口
- 【优化】优化日志脱敏工具,支持自动折叠调试输出中冗长的样式标签
- 【优化】引入 `AssetResolutionService`,完善皮肤、组件、主题间的多级资源回退机制
- 【优化】新增组件生命周期钩子 `prepare`,支持渲染前的异步数据预处理

* 🚨 auto fix by pre-commit hooks

---------

Co-authored-by: webjoin111 <455457521@qq.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Rumio
2026-02-06 20:13:40 +08:00
committed by GitHub
co-authored by webjoin111 pre-commit-ci[bot]
parent bc8e1659ae
commit 5e30694663
77 changed files with 3035 additions and 3258 deletions
+28
View File
@@ -1,3 +1,5 @@
from collections.abc import Callable
import random
import re
from typing import overload
@@ -5,6 +7,7 @@ from nonebot.adapters import Bot
from nonebot_plugin_uninfo import Session, SupportScope, Uninfo, get_interface
from zhenxun.configs.config import BotConfig
from zhenxun.configs.path_config import THEMES_PATH
from zhenxun.models.group_console import GroupConsole
from zhenxun.services.cache.runtime_cache import (
BanMemoryCache,
@@ -95,6 +98,31 @@ class CommonUtils:
elif isinstance(data, list):
return "".join(cls.format(item) for item in data)
@staticmethod
def get_random_asset_factory(sub_path: str) -> Callable[[], str | None]:
"""
创建一个从指定 assets 子目录随机选取资源的工厂函数。
用于 Pydantic 模型的 default_factory。
参数:
sub_path: 相对于 themes/default/assets/ 的子路径,例如 "ui/zhenxun/down"
"""
def _factory() -> str | None:
target_dir = THEMES_PATH / "default" / "assets" / sub_path
if not target_dir.exists():
return None
images = [
f.name
for f in target_dir.iterdir()
if f.is_file()
and f.suffix.lower() in [".png", ".jpg", ".jpeg", ".webp"]
]
return f"{sub_path}/{random.choice(images)}" if images else None
return _factory
class SqlUtils:
@classmethod
+11 -8
View File
@@ -3,7 +3,7 @@ from pathlib import Path
import random
from zhenxun import ui
from zhenxun.ui.builders import charts as chart_builders
from zhenxun.ui.models.charts import EChartsData
from .models import Barh
@@ -21,11 +21,14 @@ class ChartUtils:
if BACKGROUND_PATH.exists()
else None
)
items = list(zip(data.category_data, data.data))
builder = chart_builders.bar_chart(
title=data.title, items=items, direction="horizontal"
)
if background_image_name:
builder.set_background_image(background_image_name)
return await ui.render(builder.build())
items = list(zip(data.category_data, data.data))
chart_data = EChartsData.bar_chart(
title=data.title,
items=items, # type: ignore
direction="horizontal",
background_image=background_image_name,
)
return await ui.render(chart_data)
+25 -1
View File
@@ -46,6 +46,7 @@ def _sanitize_ui_html(html_string: str) -> str:
"""
专门用于净化UI渲染调试HTML的函数。
它会查找所有内联的base64数据(如字体、图片)并将其截断。
同时会折叠冗长的样式标签,避免主题 CSS 在日志中撑爆。
"""
if not isinstance(html_string, str):
return html_string
@@ -57,7 +58,30 @@ def _sanitize_ui_html(html_string: str) -> str:
original_len = len(match.group(0)) - len(prefix)
return f"{prefix}[...base64_omitted_len={original_len}...]"
return pattern.sub(replacer, html_string)
html_string = pattern.sub(replacer, html_string)
pattern_style = re.compile(
r"(<style[^>]*>)(.*?)(</style>)", re.DOTALL | re.IGNORECASE
)
def replacer_style(match):
start_tag, content, end_tag = match.group(1), match.group(2), match.group(3)
keywords = [
"Base Styles - Assembled by Jinja2",
"Utility Classes",
"@layer reset, base, components, utilities;",
]
if len(content) > 600 or any(keyword in content for keyword in keywords):
excerpt = (
f"\n /* [theme.css.jinja content hidden for brevity - "
f"{len(content)} chars] */\n"
)
return f"{start_tag}{excerpt}{end_tag}"
return match.group(0)
return pattern_style.sub(replacer_style, html_string)
def _sanitize_nonebot_message(message: Message) -> Message:
@@ -436,6 +436,14 @@ class ZhenxunRepoManagerClass:
branch: 分支名称
force: 是否强制更新
"""
critical_dir = self.config.RESOURCE_PATH / "themes" / "default"
if not critical_dir.exists() or not any(critical_dir.iterdir()):
logger.warning(
f"检测到关键资源目录 {critical_dir} 缺失或为空,将开启强制修复模式。",
LOG_COMMAND,
)
force = True
if await check_git():
await self.resources_git_update(source, branch, force)
logger.debug("使用git更新资源文件!", LOG_COMMAND)
+4 -3
View File
@@ -6,6 +6,7 @@ from abc import ABC, abstractmethod
from pathlib import Path
import aiofiles
from anyio import Path as AsyncPath
from zhenxun.services.log import logger
@@ -258,10 +259,10 @@ class BaseRepoManager(ABC):
repo_url = prepare_repo_url(repo_url)
# 检查本地目录是否存在
if not local_path.exists():
if not await AsyncPath(local_path).exists():
# 如果不存在,则克隆仓库
logger.info(f"克隆仓库 {repo_url} 到 {local_path}", LOG_COMMAND)
success, stdout, stderr = await run_git_command(
success, _stdout, stderr = await run_git_command(
f"clone -b {branch} {repo_url} {local_path}"
)
if not success:
@@ -396,7 +397,7 @@ class BaseRepoManager(ABC):
result.new_version = new_version.strip()
# 如果版本相同,则无需更新
if old_version.strip() == new_version.strip():
if old_version.strip() == new_version.strip() and not force:
logger.info(
f"仓库 {repo_url} 已是最新版本: {new_version.strip()}", LOG_COMMAND
)