sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)

This commit is contained in:
gozeros committed 2026-10-21 14:51:31 +08:00
1 parent 4f7f07504a
commit 8bc8b0e082
1651 files changed
+278599 -11416

No files matched your search

@@ -0,0 +1,61 @@
# Web App 站点模板(templates/web-app-template)
DeerFlow「Web App 产物模式」的站点脚手架:智能体在沙箱里 `scaffold` 本模板到
`outputs/<site>/`,改 `site.json`、写 `src/pages/*.tsx`、放数据到 `public/`,
再由 `scripts/build_site.py build` 用**预置依赖**执行 vite build 产出 `dist/`,
经平台签名静态托管在「站点预览」工作台(前端路由 `#/sites/{threadId}/{siteName}`)打开。
## 目录约定
- `site.json` — 站点清单:`title` / `description` / `nav[]`(页面导航顺序)/
`map`(可选底图:`tilesUrl` XYZ 模板或 `pmtiles` 单文件;都留空 = 无底图纯 GeoJSON 模式,离线可用)
- `src/pages/**/*.tsx` — 每个文件即一个页面,文件名(去扩展名)即路由(`overview.tsx` → `/#/overview`),自动注册
- `src/components/` — 内置组件:`AppShell`(导航壳)、`FlowCanvas`(@xyflow/react 交互流程图)、
`GeoMap`(MapLibre 地图)、`ChartPanel`(ECharts)、`MermaidBlock`(Mermaid 静态图)
- `public/` — GeoJSON / 数据文件,页面内 `fetch("./data.geojson")` 相对加载
- `scripts/build_site.py` — 构建 CLI(check / scaffold / build / status,输出单行 JSON)
## 依赖预置与开启步骤(关键:默认完全关闭,离线环境不跑 npm install)
`node_modules/` 已 gitignore,**永远不要提交,也永远不要在沙箱里安装**:
- **开发机**:`make webapp-template`(即在本目录 `pnpm install && pnpm build`)一次性生成;
- **离线发版**:`deerflow-offline-deployment` 仓库的构建脚本需在有网的 CI 上执行
`pnpm install --frozen-lockfile`(或 `npm ci`),把整个 `node_modules/` 随镜像预置到
`/app/backend/templates/web-app-template/node_modules`。
构建脚本会用 symlink(Linux)/ junction(Windows `mklink /J`,免管理员)把预置依赖
链进各站点目录,多站点共享、零拷贝。
**开启功能 = config.yaml 里同时放开两处注释**(缺一不可):
1. `sandbox.mounts` 里的模板挂载条目(沙箱技能经 `/mnt/web-app-template` 探测;
2. 文件末尾的 `web_app:` 段,`enabled: true`(开平台 API 与前端入口)。
`build_site.py check` 在宿主侧会读取 config.yaml 的 `web_app.enabled`(可用 env
`DEERFLOW_WEBAPP_ENABLED` / `DEERFLOW_WEBAPP_CONFIG` 覆盖);沙箱内读不到配置文件,
"挂载即视为开"——所以挂载条目就是沙箱侧的开关。改挂载后需重启网关(provider 单例
启动时读取;uvicorn --reload 模式改任一 `app/` 下文件即可触发热重启)。
未开启或依赖未预置时整条链路**优雅降级**:capability 探测返回不可用,技能第 0 步
回退单页 HTML 产出,前端入口按钮不渲染,现有功能零影响。
## 构建链路速查
```bash
python scripts/build_site.py check # 能力探测(模板/依赖/node)
python scripts/build_site.py scaffold outputs/my-site # 脚手架(排除 node_modules/dist/scripts)
python scripts/build_site.py build outputs/my-site # 链接预置依赖 + vite build → dist/
python scripts/build_site.py status outputs/my-site # dist 状态 + 最近构建结果
```
环境变量:`DEERFLOW_WEBAPP_TEMPLATE`(模板目录)、`DEERFLOW_WEBAPP_NODE`(node 路径)、
`DEERFLOW_WEBAPP_TIMEOUT`(构建超时秒数,默认 180)。
## 模板自身的构建约束
- `vite.config.ts` 固定 `base: "./"`(嵌套托管路径下资源自适应)与 `target: "es2018"`
(兼容 chrome100 老内核,与主前端基线一致);不要改这两个配置。
- 样式是纯 CSS + design tokens(`src/styles.css`),**不引入 Tailwind**(oklch 在老内核失效)。
- HashRouter:静态托管无需服务端 SPA fallback。
- 不新增 npm 依赖;只用已内置库(react / react-router-dom / @xyflow/react / maplibre-gl /
echarts / mermaid / pmtiles)。
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>站点</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>
@@ -0,0 +1,28 @@
{
"name": "web-app-template",
"private": true,
"version": "1.0.0",
"type": "module",
"description": "DeerFlow Web App 产物模板:多页面站点(React Router)+ 流程图 + 地图",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"@xyflow/react": "^12.10.0",
"echarts": "^6.1.0",
"maplibre-gl": "^6.9.0",
"mermaid": "^11.15.0",
"pmtiles": "^4.3.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.9.4"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "~5.8.2",
"vite": "^6.0.0"
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,53 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { "name": "北京", "description": "示例点位:华北区域中心" },
"geometry": { "type": "Point", "coordinates": [116.407, 39.904] }
},
{
"type": "Feature",
"properties": { "name": "上海", "description": "示例点位:华东区域中心" },
"geometry": { "type": "Point", "coordinates": [121.473, 31.23] }
},
{
"type": "Feature",
"properties": { "name": "广州", "description": "示例点位:华南区域中心" },
"geometry": { "type": "Point", "coordinates": [113.264, 23.129] }
},
{
"type": "Feature",
"properties": { "name": "成都", "description": "示例点位:西南区域中心" },
"geometry": { "type": "Point", "coordinates": [104.066, 30.572] }
},
{
"type": "Feature",
"properties": { "name": "示例轨迹线" },
"geometry": {
"type": "LineString",
"coordinates": [
[116.407, 39.904],
[113.264, 23.129],
[104.066, 30.572]
]
}
},
{
"type": "Feature",
"properties": { "name": "示例区域面" },
"geometry": {
"type": "Polygon",
"coordinates": [
[
[118.0, 30.0],
[122.0, 30.0],
[122.0, 33.0],
[118.0, 33.0],
[118.0, 30.0]
]
]
}
}
]
}
@@ -0,0 +1,371 @@
#!/usr/bin/env python3
"""DeerFlow Web App 产物构建脚本(纯标准库,可在沙箱与宿主两侧运行)。
子命令:
check 能力探测:模板 / node_modules / node 二进制是否就绪(技能第 0 步调用)
scaffold 从模板脚手架一个新站点目录(排除 node_modules、dist 等运行产物)
build 链接预置 node_modules 并执行 vite build,产出 dist/
status 查询站点构建状态(dist 信息 + 最近一次构建结果)
所有输出都是单行 JSON(stdout),失败时 exit code != 0 且 JSON 里带完整原因,
供智能体自修复或前端展示。
环境变量:
DEERFLOW_WEBAPP_TEMPLATE 模板目录(默认:脚本所在目录的上一级)
DEERFLOW_WEBAPP_NODE node 可执行文件(默认:PATH 上的 node)
DEERFLOW_WEBAPP_TIMEOUT 构建超时秒数(默认 180)
"""
from __future__ import annotations
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
DEFAULT_TIMEOUT = 180
SITE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
IGNORE_ON_SCAFFOLD = shutil.ignore_patterns(
"node_modules", "dist", "scripts", ".build-result.json", ".git", "*.log"
)
def _emit(payload: dict, ok: bool) -> int:
payload["ok"] = ok
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception: # noqa: BLE001 - 老版本 Python 没有 reconfigure
pass
print(json.dumps(payload, ensure_ascii=False))
return 0 if ok else 1
def _template_dir() -> Path:
env_dir = os.environ.get("DEERFLOW_WEBAPP_TEMPLATE")
if env_dir:
return Path(env_dir).resolve()
# 沙箱内也常挂载到 /mnt/web-app-template
mounted = Path("/mnt/web-app-template")
if mounted.is_dir() and (mounted / "scripts" / "build_site.py").exists():
return mounted
return Path(__file__).resolve().parent.parent
def _find_node() -> str | None:
env_node = os.environ.get("DEERFLOW_WEBAPP_NODE")
if env_node and Path(env_node).exists():
return env_node
which = shutil.which("node")
if which:
return which
candidates = (
["/usr/bin/node", "/usr/local/bin/node"]
if platform.system() != "Windows"
else [
r"C:\Program Files\nodejs\node.exe",
r"C:\Program Files (x86)\nodejs\node.exe",
]
)
for c in candidates:
if Path(c).exists():
return c
return None
def _resolve_site_dir(raw: str) -> Path:
"""站点目录解析:相对路径(相对 cwd)、/mnt/user-data 前缀(沙箱视图)、
或 LocalSandbox 已改写为宿主绝对路径的形态(须位于 user-data/outputs 之下)。
拒绝目录穿越与越界绝对路径。
"""
if not raw or ".." in Path(raw).parts or "\x00" in raw:
raise ValueError(f"非法站点目录: {raw!r}")
p = Path(raw)
if p.is_absolute():
norm = str(p.resolve()).replace("\\", "/")
if norm.startswith("/mnt/user-data") or norm.startswith("/mnt/acp-workspace"):
return p
# LocalSandbox 会把命令里的 /mnt/user-data/... 改写成宿主绝对路径;
# 只接受位于 user-data/outputs 目录树内的改写结果
marker = "/user-data/outputs/"
idx = norm.find(marker)
if idx > 0:
user_data_root = Path(norm[: idx + len("/user-data")])
if user_data_root.is_dir():
return Path(norm)
raise ValueError(f"绝对路径须位于 user-data/outputs 之下: {raw!r}")
return (Path.cwd() / p).resolve()
def _validate_site_name(name: str) -> None:
if not SITE_NAME_RE.match(name):
raise ValueError(
f"站点目录名只允许字母数字开头,含 [A-Za-z0-9._-]: {name!r}"
)
def _read_build_result(site_dir: Path) -> dict | None:
f = site_dir / ".build-result.json"
if not f.exists():
return None
try:
return json.loads(f.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return None
def _dist_info(site_dir: Path) -> dict:
dist = site_dir / "dist"
if not dist.is_dir():
return {"exists": False}
files = [p for p in dist.rglob("*") if p.is_file()]
latest = max((p.stat().st_mtime for p in files), default=None)
return {
"exists": True,
"file_count": len(files),
"total_bytes": sum(p.stat().st_size for p in files),
"mtime": latest,
}
def _web_app_enabled_from_config() -> tuple[bool, str]:
"""读取 config.yaml 的 ``web_app.enabled``(宿主侧生效;沙箱内读不到配置时视为开启)。
优先级:env ``DEERFLOW_WEBAPP_ENABLED`` > ``DEERFLOW_WEBAPP_CONFIG`` 指定的
config.yaml > 模板目录向上查找的 config.yaml。沙箱内模板挂载在
/mnt/web-app-template(向上找不到 config.yaml),此时回退 True —— 沙箱侧的
开关由「平台是否挂载模板」表达(config.yaml sandbox.mounts 注释即关闭)。
"""
env_flag = os.environ.get("DEERFLOW_WEBAPP_ENABLED", "").strip().lower()
if env_flag in ("1", "true", "yes", "on"):
return True, "env DEERFLOW_WEBAPP_ENABLED"
if env_flag in ("0", "false", "no", "off"):
return False, "env DEERFLOW_WEBAPP_ENABLED"
config_candidates: list[Path] = []
env_config = os.environ.get("DEERFLOW_WEBAPP_CONFIG", "").strip()
if env_config:
config_candidates.append(Path(env_config))
else:
# 宿主侧布局:<backend>/templates/web-app-template/scripts/ → <backend>/config.yaml
config_candidates.append(Path(__file__).resolve().parents[3] / "config.yaml")
for config_path in config_candidates:
if not config_path.is_file():
continue
try:
lines = config_path.read_text(encoding="utf-8").splitlines()
except OSError:
continue
in_section = False
for line in lines:
stripped = line.split("#", 1)[0].rstrip()
if not stripped or stripped.lstrip().startswith("-"):
continue
indent = len(stripped) - len(stripped.lstrip())
if not stripped.startswith(" ") and stripped.endswith(":"):
in_section = stripped[:-1].strip() == "web_app"
continue
if in_section and indent >= 2:
key, _, value = stripped.strip().partition(":")
if key.strip() == "enabled":
return value.strip().lower() in ("1", "true", "yes", "on"), str(config_path)
# 配置文件存在但没有 web_app 段 → 与平台 pydantic 默认一致:False
return False, str(config_path)
# 沙箱视图:向上找不到 config.yaml(模板挂在 /mnt/web-app-template),
# 开关由「平台是否挂载模板」表达 → 视为开启
return True, "config not found (sandbox view: mount presence decides)"
def cmd_check(_args: list[str]) -> int:
template = _template_dir()
node = _find_node()
vite_bin = template / "node_modules" / "vite" / "bin" / "vite.js"
enabled, enabled_source = _web_app_enabled_from_config()
checks = {
"enabled": (enabled, enabled_source),
"template": (template.is_dir() and (template / "site.json").exists(), str(template)),
"node_modules": (vite_bin.exists(), str(vite_bin)),
"node": (node is not None, node or ""),
}
available = all(ok for ok, _ in checks.values())
return _emit(
{
"available": available,
"template_dir": str(template),
"node_bin": node or "",
"checks": {k: {"ok": ok, "detail": detail} for k, (ok, detail) in checks.items()},
},
ok=True, # check 本身永远成功,可用性看 available 字段
)
def cmd_scaffold(args: list[str]) -> int:
if len(args) != 1:
return _emit({"error": "用法: build_site.py scaffold <站点目录>"}, ok=False)
try:
site_dir = _resolve_site_dir(args[0])
_validate_site_name(site_dir.name)
template = _template_dir()
if not (template / "site.json").exists():
return _emit({"error": f"模板不存在或不完整: {template}"}, ok=False)
if not site_dir.exists():
site_dir.mkdir(parents=True, exist_ok=True)
shutil.copytree(template, site_dir, dirs_exist_ok=True, ignore=IGNORE_ON_SCAFFOLD)
if not (site_dir / "site.json").exists():
return _emit({"error": "脚手架后缺少 site.json,模板不完整"}, ok=False)
return _emit({"site_dir": str(site_dir), "scaffolded": True}, ok=True)
except Exception as exc: # noqa: BLE001
return _emit({"error": f"scaffold 失败: {exc}"}, ok=False)
def _link_node_modules(site_dir: Path, template: Path) -> str:
"""把模板的 node_modules 链接进站点目录(符号链接 → Windows junction → 整拷贝兜底)。
注意:Python 3.8+ 的 shutil.rmtree 遇到 junction 只解除链接不穿透删除,
因此清理失效链接时对宿主模板是安全的。
"""
target = template / "node_modules"
link = site_dir / "node_modules"
def _valid(p: Path) -> bool:
return (p / "vite" / "bin" / "vite.js").exists()
if link.exists() or link.is_symlink():
if _valid(link):
return "reused"
try:
if link.is_symlink() or link.is_file():
link.unlink()
else:
shutil.rmtree(link, ignore_errors=True)
except OSError:
pass
try:
os.symlink(target, link, target_is_directory=True)
if _valid(link):
return "symlink"
link.unlink()
except (OSError, NotImplementedError):
pass
if platform.system() == "Windows":
try:
proc = subprocess.run(
["cmd", "/c", "mklink", "/J", str(link), str(target)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
)
if proc.returncode == 0 and _valid(link):
return "junction"
except Exception: # noqa: BLE001
pass
shutil.copytree(target, link, dirs_exist_ok=True)
return "copied"
def cmd_build(args: list[str]) -> int:
if len(args) != 1:
return _emit({"error": "用法: build_site.py build <站点目录>"}, ok=False)
started = time.time()
try:
site_dir = _resolve_site_dir(args[0])
if not (site_dir / "site.json").exists():
return _emit(
{"error": f"站点目录缺少 site.json(不是 Web App 站点): {site_dir}"}, ok=False
)
template = _template_dir()
node = _find_node()
if node is None:
return _emit({"error": "找不到 node 可执行文件(PATH 或 DEERFLOW_WEBAPP_NODE)"}, ok=False)
vite_bin = template / "node_modules" / "vite" / "bin" / "vite.js"
if not vite_bin.exists():
return _emit(
{"error": f"模板依赖未预置(缺 {vite_bin}),离线部署需先执行 node_modules 预置"}, ok=False
)
link_mode = _link_node_modules(site_dir, template)
timeout = int(os.environ.get("DEERFLOW_WEBAPP_TIMEOUT", str(DEFAULT_TIMEOUT)))
env = dict(os.environ)
env["NODE_ENV"] = "production"
proc = subprocess.run(
[node, str(vite_bin), "build"],
cwd=str(site_dir),
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
env=env,
)
duration_ms = int((time.time() - started) * 1000)
result = {
"site_dir": str(site_dir),
"success": proc.returncode == 0,
"duration_ms": duration_ms,
"node_modules": link_mode,
"stdout_tail": proc.stdout[-8000:],
"stderr_tail": proc.stderr[-8000:],
"finished_at": time.time(),
}
if proc.returncode != 0:
result["error"] = f"vite build 退出码 {proc.returncode},详见 stderr_tail"
result["dist"] = _dist_info(site_dir)
(site_dir / ".build-result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8"
)
return _emit(result, ok=proc.returncode == 0)
except subprocess.TimeoutExpired:
result = {
"site_dir": args[0] if args else "",
"success": False,
"error": f"构建超时(>{os.environ.get('DEERFLOW_WEBAPP_TIMEOUT', DEFAULT_TIMEOUT)}s)已终止",
"duration_ms": int((time.time() - started) * 1000),
"finished_at": time.time(),
}
try:
(Path(args[0]) / ".build-result.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8"
)
except Exception: # noqa: BLE001
pass
return _emit(result, ok=False)
except Exception as exc: # noqa: BLE001
return _emit({"error": f"build 失败: {exc}"}, ok=False)
def cmd_status(args: list[str]) -> int:
if len(args) != 1:
return _emit({"error": "用法: build_site.py status <站点目录>"}, ok=False)
try:
site_dir = _resolve_site_dir(args[0])
return _emit(
{
"site_dir": str(site_dir),
"exists": site_dir.is_dir(),
"has_site_json": (site_dir / "site.json").exists(),
"dist": _dist_info(site_dir),
"last_build": _read_build_result(site_dir),
},
ok=True,
)
except Exception as exc: # noqa: BLE001
return _emit({"error": f"status 失败: {exc}"}, ok=False)
def main() -> int:
commands = {"check": cmd_check, "scaffold": cmd_scaffold, "build": cmd_build, "status": cmd_status}
if len(sys.argv) < 2 or sys.argv[1] not in commands:
return _emit(
{"error": "用法: build_site.py <check|scaffold|build|status> [站点目录]"}, ok=False
)
return commands[sys.argv[1]](sys.argv[2:])
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,15 @@
{
"title": "示例站点",
"description": "基于 DeerFlow Web App 模板生成的多页面站点",
"nav": [
{ "page": "overview", "label": "总览" },
{ "page": "process", "label": "流程图" },
{ "page": "map", "label": "地图" }
],
"map": {
"tilesUrl": "",
"tilesType": "raster",
"pmtiles": "",
"attribution": ""
}
}
@@ -0,0 +1,134 @@
/* AppShell 布局样式(与全局 styles.css 的 tokens 配合) */
.app-shell {
display: flex;
min-height: 100vh;
}
.app-sidebar {
width: 232px;
flex-shrink: 0;
background: #171c2b;
color: #c6cddd;
display: flex;
flex-direction: column;
padding: 18px 12px;
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
}
.app-brand {
display: flex;
gap: 10px;
align-items: center;
padding: 4px 8px 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
margin-bottom: 12px;
}
.app-brand-mark {
width: 38px;
height: 38px;
border-radius: 10px;
background: linear-gradient(135deg, #3b6bff, #21c8b7);
color: #fff;
font-size: 17px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.app-brand-title {
color: #fff;
font-weight: 600;
font-size: 15px;
line-height: 1.3;
word-break: break-all;
}
.app-brand-desc {
font-size: 11px;
color: #7e8799;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.app-nav {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
}
.app-nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 12px;
border-radius: 8px;
color: #aab3c5;
font-size: 14px;
transition: background 0.15s ease, color 0.15s ease;
}
.app-nav-item:hover {
background: rgba(255, 255, 255, 0.06);
color: #fff;
text-decoration: none;
}
.app-nav-item--active {
background: rgba(59, 107, 255, 0.18);
color: #fff;
}
.app-nav-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
opacity: 0.55;
flex-shrink: 0;
}
.app-sidebar-footer {
font-size: 11px;
color: #5a6478;
text-align: center;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.app-main {
flex: 1;
min-width: 0;
}
@media (max-width: 760px) {
.app-shell {
flex-direction: column;
}
.app-sidebar {
width: 100%;
height: auto;
position: static;
padding: 10px 12px;
}
.app-nav {
flex-direction: row;
overflow-x: auto;
}
.app-brand-desc,
.app-sidebar-footer {
display: none;
}
}
@@ -0,0 +1,50 @@
import { useEffect } from "react";
import { NavLink, Outlet } from "react-router-dom";
import { siteConfig } from "@/lib/site-config";
import "./AppShell.css";
/**
* 站点外壳:左侧导航(数据来自 site.json 的 nav)+ 内容区。
* site.json 里新增 nav 项即可出现在导航中。
*/
export default function AppShell() {
useEffect(() => {
document.title = siteConfig.title;
}, []);
return (
<div className="app-shell">
<aside className="app-sidebar">
<div className="app-brand">
<div className="app-brand-mark">{siteConfig.title.slice(0, 1) || "站"}</div>
<div className="app-brand-text">
<div className="app-brand-title">{siteConfig.title}</div>
{siteConfig.description ? (
<div className="app-brand-desc">{siteConfig.description}</div>
) : null}
</div>
</div>
<nav className="app-nav">
{siteConfig.nav.map((item) => (
<NavLink
key={item.page}
to={`/${item.page}`}
className={({ isActive }) =>
isActive ? "app-nav-item app-nav-item--active" : "app-nav-item"
}
>
<span className="app-nav-dot" />
{item.label}
</NavLink>
))}
</nav>
<div className="app-sidebar-footer">DeerFlow Web App</div>
</aside>
<main className="app-main">
<Outlet />
</main>
</div>
);
}
@@ -0,0 +1,43 @@
import { useEffect, useRef } from "react";
import * as echarts from "echarts";
/**
* 图表组件(基于 ECharts):传入任意 ECharts option 即可渲染,自动响应容器尺寸变化。
* 常用图型:bar / line / pie / scatter / radar,option 写法参考 ECharts 官方文档。
*/
export default function ChartPanel({
option,
height = 340,
}: {
option: echarts.EChartsOption;
height?: number;
}) {
const containerRef = useRef<HTMLDivElement | null>(null);
const chartRef = useRef<echarts.ECharts | null>(null);
useEffect(() => {
if (!containerRef.current) return;
const chart = echarts.init(containerRef.current);
chartRef.current = chart;
const observer = new ResizeObserver(() => chart.resize());
observer.observe(containerRef.current);
return () => {
observer.disconnect();
chart.dispose();
chartRef.current = null;
};
}, []);
useEffect(() => {
chartRef.current?.setOption(option, true);
}, [option]);
return (
<div
ref={containerRef}
style={{ width: "100%", height }}
role="img"
aria-label="ECharts 图表"
/>
);
}
@@ -0,0 +1,13 @@
@import "@xyflow/react/dist/style.css";
.flow-canvas {
width: 100%;
border: 1px solid var(--c-border, #e3e8ef);
border-radius: var(--radius-lg, 14px);
background: #fbfcfe;
overflow: hidden;
}
.flow-canvas .react-flow__node {
font-family: inherit;
}
@@ -0,0 +1,172 @@
import { useMemo } from "react";
import {
Background,
Controls,
MarkerType,
MiniMap,
ReactFlow,
} from "@xyflow/react";
import type { Edge, Node } from "@xyflow/react";
import "./FlowCanvas.css";
/**
* 可交互流程图(基于 @xyflow/react):支持拖拽、缩放、小地图。
*
* 数据格式(与 DeerFlow flow-json 对齐,edges 两套字段名都接受):
* {
* direction: "TB" | "LR",
* nodes: [{ id: "n1", label: "开始", type?: "start|end|stage|process|decision|risk|deliverable" }],
* edges: [{ source: "n1", target: "n2", label?: "是" }]
* }
*/
export interface FlowNodeData {
id: string;
label: string;
type?: string;
}
export interface FlowEdgeData {
source: string;
target: string;
label?: string;
from?: string;
to?: string;
}
export interface FlowData {
direction?: "TB" | "LR";
nodes: FlowNodeData[];
edges: FlowEdgeData[];
}
const NODE_COLORS: Record<string, { bg: string; border: string; color: string }> = {
start: { bg: "#e8f7ef", border: "#17895a", color: "#116a45" },
end: { bg: "#e8f7ef", border: "#17895a", color: "#116a45" },
stage: { bg: "#e9efff", border: "#2f5cff", color: "#1f44bd" },
process: { bg: "#f0f3f8", border: "#8a93a6", color: "#1c2333" },
task: { bg: "#f0f3f8", border: "#8a93a6", color: "#1c2333" },
decision: { bg: "#fff6e5", border: "#b97509", color: "#8f5c07" },
risk: { bg: "#fdecec", border: "#d64545", color: "#b03535" },
deliverable: { bg: "#eef6ff", border: "#0d7cd6", color: "#0b61a8" },
role: { bg: "#f3efff", border: "#7353d4", color: "#5a3fb4" },
};
const DEFAULT_NODE_COLOR = { bg: "#f0f3f8", border: "#8a93a6", color: "#1c2333" };
/** 最长路径分层 + 同层顺序排布的简易自动布局 */
function layoutFlow(data: FlowData): { nodes: Node[]; edges: Edge[] } {
const vertical = (data.direction ?? "TB") === "TB";
const nodeIds = new Set(data.nodes.map((n) => n.id));
const normalizedEdges: { id: string; source: string; target: string; label?: string }[] = [];
const outgoing = new Map<string, string[]>();
const indegree = new Map<string, number>();
for (const n of data.nodes) {
indegree.set(n.id, 0);
outgoing.set(n.id, []);
}
let edgeSeq = 0;
for (const e of data.edges) {
const source = e.source ?? e.from ?? "";
const target = e.target ?? e.to ?? "";
if (!nodeIds.has(source) || !nodeIds.has(target) || source === target) continue;
normalizedEdges.push({ id: `e${edgeSeq++}`, source, target, label: e.label });
outgoing.get(source)!.push(target);
indegree.set(target, (indegree.get(target) ?? 0) + 1);
}
// Kahn 拓扑排序求层号(取最长路径)
const layer = new Map<string, number>();
const queue: string[] = [];
for (const [id, deg] of indegree) {
if (deg === 0) {
queue.push(id);
layer.set(id, 0);
}
}
let guard = 0;
const limit = nodeIds.size * (nodeIds.size + 1);
while (queue.length > 0 && guard++ < limit) {
const id = queue.shift()!;
const layerNo = layer.get(id) ?? 0;
for (const next of outgoing.get(id) ?? []) {
layer.set(next, Math.max(layer.get(next) ?? 0, layerNo + 1));
const deg = (indegree.get(next) ?? 1) - 1;
indegree.set(next, deg);
if (deg === 0) queue.push(next);
}
}
// 环上节点兜底:未分层的放第 0 层
for (const n of data.nodes) if (!layer.has(n.id)) layer.set(n.id, 0);
const byLayer = new Map<number, string[]>();
for (const n of data.nodes) {
const l = layer.get(n.id) ?? 0;
if (!byLayer.has(l)) byLayer.set(l, []);
byLayer.get(l)!.push(n.id);
}
const GAP_MAIN = 130;
const GAP_CROSS = 210;
const nodes: Node[] = data.nodes.map((n) => {
const l = layer.get(n.id) ?? 0;
const siblings = byLayer.get(l) ?? [];
const index = siblings.indexOf(n.id);
const offset = index - (siblings.length - 1) / 2;
const colors = NODE_COLORS[n.type ?? ""] ?? DEFAULT_NODE_COLOR;
return {
id: n.id,
position: vertical
? { x: offset * GAP_CROSS, y: l * GAP_MAIN }
: { x: l * GAP_CROSS, y: offset * GAP_MAIN },
data: { label: n.label },
style: {
background: colors.bg,
border: `1.5px solid ${colors.border}`,
color: colors.color,
borderRadius: 8,
padding: "8px 14px",
fontSize: 13,
fontWeight: 500,
width: "auto",
},
};
});
const edges: Edge[] = normalizedEdges.map((e) => ({
id: e.id,
source: e.source,
target: e.target,
label: e.label,
type: "smoothstep",
style: { stroke: "#9aa5ba", strokeWidth: 1.6 },
labelStyle: { fontSize: 11, fill: "#5a6478" },
labelBgStyle: { fill: "#ffffff" },
markerEnd: { type: MarkerType.ArrowClosed, color: "#9aa5ba" },
}));
return { nodes, edges };
}
export default function FlowCanvas({ data, height = 460 }: { data: FlowData; height?: number }) {
const { nodes, edges } = useMemo(() => layoutFlow(data), [data]);
return (
<div className="flow-canvas" style={{ height }}>
<ReactFlow
nodes={nodes}
edges={edges}
fitView
minZoom={0.2}
maxZoom={2}
proOptions={{ hideAttribution: true }}
nodesConnectable={false}
defaultEdgeOptions={{ type: "smoothstep" }}
>
<Background color="#dfe5ee" gap={18} />
<Controls showInteractive={false} />
{nodes.length > 12 ? <MiniMap pannable zoomable /> : null}
</ReactFlow>
</div>
);
}
@@ -0,0 +1,52 @@
.geomap-wrap {
position: relative;
width: 100%;
border: 1px solid var(--c-border, #e3e8ef);
border-radius: var(--radius-lg, 14px);
overflow: hidden;
background: #eef2f7;
}
.geomap-container {
width: 100%;
height: 100%;
}
.geomap-marker {
background: #2f5cff;
color: #fff;
font-size: 12px;
font-weight: 500;
padding: 3px 10px;
border-radius: 999px;
border: 2px solid #ffffff;
box-shadow: 0 2px 8px rgba(16, 24, 40, 0.25);
white-space: nowrap;
cursor: default;
}
.geomap-popover-title {
font-weight: 600;
font-size: 13px;
margin-bottom: 2px;
}
.geomap-popover-desc {
font-size: 12px;
color: #5a6478;
max-width: 220px;
}
.geomap-tiles-warn {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
background: #fff6e5;
color: #8f5c07;
border: 1px solid #e8c98a;
font-size: 12px;
padding: 4px 12px;
border-radius: 999px;
z-index: 5;
}
@@ -0,0 +1,268 @@
import { useEffect, useRef, useState } from "react";
import {
Map as MaplibreMap,
Marker,
NavigationControl,
Popup,
addProtocol,
} from "maplibre-gl";
import type { StyleSpecification } from "maplibre-gl";
import { siteConfig } from "@/lib/site-config";
import "maplibre-gl/dist/maplibre-gl.css";
import "./GeoMap.css";
/**
* 地图组件(基于 MapLibre GL JS):
* - 默认「无底图模式」:纯背景 + GeoJSON 点/线/面图层,离线环境开箱即用;
* - site.json 的 map.tilesUrl 配置 XYZ 瓦片(如内网 GeoServer),map.pmtiles 配 PMTiles 单文件底图;
* - 地图数据通过 data(GeoJSON FeatureCollection)传入,点要素以 HTML 气泡呈现(properties.name / description)。
*/
export interface GeoMapProps {
/** GeoJSON FeatureCollection */
data: GeoJSON.FeatureCollection;
height?: number;
/** 初始视野中心 [lng, lat],缺省按数据 fitBounds */
center?: [number, number];
zoom?: number;
/** 额外专题图层:GeoJSON 数据 + 线/面渲染样式 */
layers?: Array<{
id: string;
data: GeoJSON.FeatureCollection;
type: "line" | "fill";
color?: string;
width?: number;
opacity?: number;
}>;
}
let pmtilesProtocolReady = false;
function buildStyle(): StyleSpecification {
const mapCfg = siteConfig.map ?? {};
const style: StyleSpecification = {
version: 8,
sources: {},
layers: [
{
id: "background",
type: "background",
paint: { "background-color": "#eef2f7" },
},
],
};
if (mapCfg.pmtiles) {
// PMTiles 单文件底图(部署方预置的离线底图)。矢量底图需要按底图内容
// 补充具体图层样式,这里仅建立数据源,常用作栅格 PMTiles。
style.sources["pmtiles-base"] = {
type: "raster",
tiles: [`pmtiles://${mapCfg.pmtiles}/{z}/{x}/{y}`],
tileSize: 256,
attribution: mapCfg.attribution ?? "",
};
style.layers.push({
id: "pmtiles-base",
type: "raster",
source: "pmtiles-base",
paint: { "raster-opacity": 1 },
});
} else if (mapCfg.tilesUrl) {
style.sources["tile-base"] = {
type: "raster",
tiles: [mapCfg.tilesUrl],
tileSize: 256,
attribution: mapCfg.attribution ?? "",
};
style.layers.push({
id: "tile-base",
type: "raster",
source: "tile-base",
paint: { "raster-opacity": 1 },
});
}
return style;
}
function collectBounds(fc: GeoJSON.FeatureCollection): [number, number][] {
const points: [number, number][] = [];
for (const f of fc.features ?? []) {
const g = f.geometry;
if (!g) continue;
if (g.type === "Point") {
points.push(g.coordinates as [number, number]);
} else if (g.type === "LineString" || g.type === "MultiLineString") {
const lines =
g.type === "LineString" ? [g.coordinates as number[][]] : (g.coordinates as number[][][]);
for (const line of lines) for (const c of line) points.push([c[0], c[1]]);
} else if (g.type === "Polygon" || g.type === "MultiPolygon") {
const polys =
g.type === "Polygon" ? [g.coordinates as number[][][]] : (g.coordinates as number[][][][]);
for (const poly of polys) for (const ring of poly) for (const c of ring) points.push([c[0], c[1]]);
}
}
return points;
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
export default function GeoMap({ data, height = 480, center, zoom = 4, layers }: GeoMapProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const mapRef = useRef<MaplibreMap | null>(null);
const [tilesFailed, setTilesFailed] = useState(false);
useEffect(() => {
if (!containerRef.current) return;
let cancelled = false;
let map: MaplibreMap | null = null;
const boot = async () => {
const mapCfg = siteConfig.map ?? {};
if (mapCfg.pmtiles && !pmtilesProtocolReady) {
try {
const { Protocol } = await import("pmtiles");
const protocol = new Protocol();
addProtocol("pmtiles", protocol.tile as unknown as never);
pmtilesProtocolReady = true;
} catch (err) {
console.warn("[GeoMap] PMTiles 协议注册失败,回退无底图模式", err);
}
}
if (cancelled || !containerRef.current) return;
map = new MaplibreMap({
container: containerRef.current,
style: buildStyle(),
center: center ?? [105, 35],
zoom,
});
mapRef.current = map;
map.addControl(new NavigationControl({ showCompass: false }), "top-right");
if (mapCfg.tilesUrl || mapCfg.pmtiles) {
map.on("tileerror", () => setTilesFailed(true));
map.on("sourcedata", (e) => {
if ((e.sourceId === "tile-base" || e.sourceId === "pmtiles-base") && e.isSourceLoaded) {
setTilesFailed(false);
}
});
}
map.on("load", () => {
if (cancelled || !data?.features?.length) return;
map!.addSource("site-data", { type: "geojson", data });
const hasPoly = data.features.some(
(f) => f.geometry?.type === "Polygon" || f.geometry?.type === "MultiPolygon",
);
const hasLine = data.features.some(
(f) => f.geometry?.type === "LineString" || f.geometry?.type === "MultiLineString",
);
if (hasPoly) {
map!.addLayer({
id: "site-data-fill",
type: "fill",
source: "site-data",
filter: ["in", ["geometry-type"], ["literal", ["Polygon", "MultiPolygon"]]],
paint: { "fill-color": "#3b6bff", "fill-opacity": 0.14 },
});
map!.addLayer({
id: "site-data-outline",
type: "line",
source: "site-data",
filter: ["in", ["geometry-type"], ["literal", ["Polygon", "MultiPolygon"]]],
paint: { "line-color": "#2f5cff", "line-width": 1.6 },
});
}
if (hasLine) {
map!.addLayer({
id: "site-data-line",
type: "line",
source: "site-data",
filter: ["in", ["geometry-type"], ["literal", ["LineString", "MultiLineString"]]],
paint: { "line-color": "#17895a", "line-width": 2.4 },
});
}
for (const f of data.features) {
if (f.geometry?.type !== "Point") continue;
const coord = f.geometry.coordinates as [number, number];
const name = (f.properties?.name ?? f.properties?.label ?? "").toString() || "未命名地点";
const el = document.createElement("div");
el.className = "geomap-marker";
el.textContent = name;
const marker = new Marker({ element: el }).setLngLat(coord).addTo(map!);
if (f.properties?.description) {
marker.setPopup(
new Popup({ offset: 14, closeButton: false }).setHTML(
`<div class="geomap-popover-title">${escapeHtml(name)}</div>` +
`<div class="geomap-popover-desc">${escapeHtml(
f.properties.description.toString(),
)}</div>`,
),
);
}
}
for (const layer of layers ?? []) {
map!.addSource(layer.id, { type: "geojson", data: layer.data });
map!.addLayer(
layer.type === "fill"
? {
id: `${layer.id}-fill`,
type: "fill",
source: layer.id,
paint: {
"fill-color": layer.color ?? "#d64545",
"fill-opacity": layer.opacity ?? 0.18,
},
}
: {
id: `${layer.id}-line`,
type: "line",
source: layer.id,
paint: {
"line-color": layer.color ?? "#d64545",
"line-width": layer.width ?? 2,
"line-opacity": layer.opacity ?? 1,
},
},
);
}
if (!center) {
const points = collectBounds(data);
if (points.length > 0) {
const lngs = points.map((p) => p[0]);
const lats = points.map((p) => p[1]);
map!.fitBounds(
[
[Math.min(...lngs), Math.min(...lats)],
[Math.max(...lngs), Math.max(...lats)],
],
{ padding: 60, maxZoom: 12, duration: 0 },
);
}
}
});
};
void boot();
return () => {
cancelled = true;
map?.remove();
mapRef.current = null;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(data), center, zoom]);
return (
<div className="geomap-wrap" style={{ height }}>
<div ref={containerRef} className="geomap-container" />
{tilesFailed ? (
<div className="geomap-tiles-warn">底图瓦片加载失败(离线环境可忽略,仅影响底图显示)</div>
) : null}
</div>
);
}
@@ -0,0 +1,44 @@
import { useEffect, useRef, useState } from "react";
import "./mermaid.css";
/**
* 静态流程图组件(基于 Mermaid):传入 Mermaid 文本(flowchart TD / sequenceDiagram 等)
* 渲染为 SVG,适合报告、方案图等快速生成的场景;需要拖拽交互的流程图请用 FlowCanvas。
*/
export default function MermaidBlock({ source }: { source: string }) {
const containerRef = useRef<HTMLDivElement | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
const render = async () => {
try {
const mermaid = (await import("mermaid")).default;
mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "neutral" });
const { svg } = await mermaid.render(`mermaid-${Math.random().toString(36).slice(2)}`, source);
if (!cancelled && containerRef.current) {
containerRef.current.innerHTML = svg;
setError(null);
}
} catch (err) {
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
}
};
void render();
return () => {
cancelled = true;
};
}, [source]);
if (error) {
return (
<div className="mermaid-error">
<p>Mermaid 图渲染失败</p>
<pre>{source}</pre>
<p className="muted">{error}</p>
</div>
);
}
return <div ref={containerRef} className="mermaid-block" />;
}
@@ -0,0 +1,32 @@
.mermaid-block {
background: #fbfcfe;
border: 1px solid var(--c-border, #e3e8ef);
border-radius: var(--radius-lg, 14px);
padding: 18px;
overflow-x: auto;
display: flex;
justify-content: center;
}
.mermaid-block svg {
max-width: 100%;
height: auto;
}
.mermaid-error {
border: 1px solid #f0c1c1;
background: #fdf3f3;
border-radius: var(--radius, 10px);
padding: 14px 16px;
color: #b03535;
font-size: 13px;
}
.mermaid-error pre {
font-family: var(--font-mono, monospace);
font-size: 12px;
white-space: pre-wrap;
background: rgba(255, 255, 255, 0.6);
padding: 8px 10px;
border-radius: 6px;
}
@@ -0,0 +1,53 @@
import rawSiteConfig from "../../site.json";
export interface SiteNavItem {
/** 页面文件名(不含扩展名),对应路由 /#/<page> */
page: string;
/** 导航显示名 */
label: string;
}
export interface SiteMapConfig {
/** XYZ 瓦片地址模板(含 {x}/{y}/{z}),如内网 GeoServer;留空则使用无底图模式 */
tilesUrl?: string;
/** 瓦片类型,默认 raster */
tilesType?: "raster" | "vector";
/** PMTiles 单文件地址(相对站点根的路径或绝对 URL),优先于 tilesUrl */
pmtiles?: string;
/** 底图版权说明 */
attribution?: string;
}
export interface SiteConfig {
title: string;
description?: string;
nav: SiteNavItem[];
map?: SiteMapConfig;
}
function coerceConfig(raw: unknown): SiteConfig {
const obj = (raw ?? {}) as Record<string, unknown>;
const nav = Array.isArray(obj.nav)
? obj.nav
.filter((item): item is Record<string, unknown> => !!item && typeof item === "object")
.map((item) => ({
page: String(item.page ?? "").trim(),
label: String(item.label ?? item.page ?? "").trim(),
}))
.filter((item) => item.page.length > 0)
: [];
const mapObj = (obj.map ?? {}) as Record<string, unknown>;
return {
title: String(obj.title ?? "站点"),
description: obj.description ? String(obj.description) : undefined,
nav,
map: {
tilesUrl: mapObj.tilesUrl ? String(mapObj.tilesUrl) : "",
tilesType: mapObj.tilesType === "vector" ? "vector" : "raster",
pmtiles: mapObj.pmtiles ? String(mapObj.pmtiles) : "",
attribution: mapObj.attribution ? String(mapObj.attribution) : "",
},
};
}
export const siteConfig: SiteConfig = coerceConfig(rawSiteConfig);
@@ -0,0 +1,67 @@
import { StrictMode, Suspense, lazy } from "react";
import type { ComponentType } from "react";
import { createRoot } from "react-dom/client";
import { HashRouter, Navigate, Route, Routes } from "react-router-dom";
import AppShell from "@/components/AppShell";
import { siteConfig } from "@/lib/site-config";
import "@/styles.css";
/**
* 自动路由注册:src/pages/ 下每个 .tsx 文件就是一个页面,
* 文件名(去掉扩展名,支持子目录)即路由路径,例如:
* src/pages/overview.tsx → /#/overview
* src/pages/report/detail.tsx → /#/report/detail
* 生成页面时只需新增文件,无需改动本文件。
*/
const pageModules = import.meta.glob("./pages/**/*.tsx");
const pageRoutes = Object.entries(pageModules).map(([file, loader]) => {
const routePath = file.replace(/^\.\//, "").replace(/\.tsx$/, "");
const LazyPage = lazy(loader as () => Promise<{ default: ComponentType }>);
return {
path: `/${routePath}`,
element: (
<Suspense fallback={<PageLoading />}>
<LazyPage />
</Suspense>
),
};
});
const firstPage =
siteConfig.nav.find((item) => item.page)?.page ??
(pageRoutes[0] ? pageRoutes[0].path.slice(1) : "");
function PageLoading() {
return (
<div className="page-loading" role="status">
页面加载中…
</div>
);
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<HashRouter>
<Routes>
<Route element={<AppShell />}>
<Route index element={<Navigate to={`/${firstPage}`} replace />} />
{pageRoutes.map((r) => (
<Route key={r.path} path={r.path} element={r.element} />
))}
<Route
path="*"
element={
<div className="page-loading">
<p>页面不存在</p>
<a href={`#/${firstPage}`}>返回首页</a>
</div>
}
/>
</Route>
</Routes>
</HashRouter>
</StrictMode>,
);
@@ -0,0 +1,51 @@
import { useEffect, useState } from "react";
import GeoMap from "@/components/GeoMap";
import type { GeoMapProps } from "@/components/GeoMap";
/**
* 地图页示例:GeoJSON 数据放 public/ 目录(构建时原样拷贝到 dist/),
* 页面里用 fetch("./<文件名>") 相对路径加载。
* 地图默认无底图(离线可用);在 site.json 的 map 段配置 tilesUrl / pmtiles 可加底图。
*/
export default function MapPage() {
const [data, setData] = useState<GeoMapProps["data"] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
fetch("./data.geojson")
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<GeoMapProps["data"]>;
})
.then((json) => {
if (!cancelled) setData(json);
})
.catch((err) => {
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
});
return () => {
cancelled = true;
};
}, []);
return (
<div className="page">
<header className="page-header">
<h1 className="page-title">地图</h1>
<p className="page-subtitle">空间分布可视化(点 / 线 / 面)。</p>
</header>
<section className="card">
{error ? (
<p className="card-body">数据加载失败:{error}</p>
) : data ? (
<GeoMap data={data} height={520} />
) : (
<p className="card-body">地图数据加载中…</p>
)}
</section>
</div>
);
}
@@ -0,0 +1,102 @@
import { Link } from "react-router-dom";
import ChartPanel from "@/components/ChartPanel";
/**
* 总览页示例:统计卡片 + 图表 + 页面入口。
* 新增页面:在 src/pages/ 下新建 .tsx 文件,并在 site.json 的 nav 里加一项即可。
*/
export default function OverviewPage() {
const stats = [
{ label: "覆盖区域", value: "12", unit: "个" },
{ label: "重点项目", value: "36", unit: "个" },
{ label: "数据总量", value: "1,204", unit: "条" },
{ label: "本月新增", value: "+86", unit: "条", trend: "up" as const },
];
return (
<div className="page">
<header className="page-header">
<h1 className="page-title">总览</h1>
<p className="page-subtitle">站点数据概览与快速入口。</p>
</header>
<section className="grid grid-4" style={{ marginBottom: 20 }}>
{stats.map((s) => (
<div className="stat" key={s.label}>
<div
className={
"stat-value " + (s.trend === "up" ? "stat-up" : s.trend === "down" ? "stat-down" : "")
}
>
{s.value}
<span className="stat-label" style={{ display: "inline" }}> {s.unit}</span>
</div>
<div className="stat-label">{s.label}</div>
</div>
))}
</section>
<section className="grid grid-2" style={{ marginBottom: 20 }}>
<div className="card">
<h2 className="card-title">月度趋势</h2>
<ChartPanel
option={{
tooltip: { trigger: "axis" },
grid: { left: 40, right: 16, top: 24, bottom: 28 },
xAxis: { type: "category", data: ["1月", "2月", "3月", "4月", "5月", "6月"] },
yAxis: { type: "value" },
series: [
{
type: "line",
smooth: true,
data: [120, 182, 161, 204, 232, 287],
areaStyle: { opacity: 0.12 },
itemStyle: { color: "#2f5cff" },
},
],
}}
/>
</div>
<div className="card">
<h2 className="card-title">类别占比</h2>
<ChartPanel
option={{
tooltip: { trigger: "item" },
legend: { bottom: 0 },
series: [
{
type: "pie",
radius: ["42%", "68%"],
center: ["50%", "46%"],
data: [
{ value: 42, name: "类别 A" },
{ value: 28, name: "类别 B" },
{ value: 20, name: "类别 C" },
{ value: 10, name: "其他" },
],
},
],
}}
/>
</div>
</section>
<section className="card">
<h2 className="card-title">快速入口</h2>
<div className="grid grid-2">
<div>
<p className="card-body">
查看业务流程?前往 <Link to="/process">流程图页</Link>。
</p>
</div>
<div>
<p className="card-body">
查看空间分布?前往 <Link to="/map">地图页</Link>。
</p>
</div>
</div>
</section>
</div>
);
}
@@ -0,0 +1,51 @@
import FlowCanvas from "@/components/FlowCanvas";
import type { FlowData } from "@/components/FlowCanvas";
import MermaidBlock from "@/components/MermaidBlock";
/**
* 流程图页示例:FlowCanvas(可拖拽/缩放的交互流程图)+ MermaidBlock(静态图)。
*/
const flowData: FlowData = {
direction: "TB",
nodes: [
{ id: "n1", label: "开始", type: "start" },
{ id: "n2", label: "数据收集", type: "stage" },
{ id: "n3", label: "清洗与校验", type: "process" },
{ id: "n4", label: "质量达标?", type: "decision" },
{ id: "n5", label: "分析建模", type: "stage" },
{ id: "n6", label: "报告产出", type: "deliverable" },
{ id: "n7", label: "异常处理", type: "risk" },
{ id: "n8", label: "结束", type: "end" },
],
edges: [
{ source: "n1", target: "n2" },
{ source: "n2", target: "n3" },
{ source: "n3", target: "n4" },
{ source: "n4", target: "n5", label: "是" },
{ source: "n4", target: "n7", label: "否" },
{ source: "n7", target: "n3", label: "重新处理" },
{ source: "n5", target: "n6" },
{ source: "n6", target: "n8" },
],
};
export default function ProcessPage() {
return (
<div className="page">
<header className="page-header">
<h1 className="page-title">流程图</h1>
<p className="page-subtitle">交互式流程图(可拖拽节点、缩放画布)与静态示意图。</p>
</header>
<section className="card" style={{ marginBottom: 20 }}>
<h2 className="card-title">业务主流程</h2>
<FlowCanvas data={flowData} height={480} />
</section>
<section className="card">
<h2 className="card-title">静态示意图(Mermaid)</h2>
<MermaidBlock source={"flowchart LR\n A[需求输入] --> B{评审}\n B -->|通过| C[排期开发]\n B -->|驳回| A"} />
</section>
</div>
);
}
@@ -0,0 +1,250 @@
/*
* 站点全局基础样式:纯 CSS + design tokens(不依赖 Tailwind,兼容旧内核浏览器,
* 颜色只用 #hex/rgb(),避免 oklch 等新语法)。
* 页面可以直接使用 .card / .grid / .stat / .btn 等既有类快速搭建版式,
* 也可以在各自页面里写 scoped 样式覆盖。
*/
:root {
--c-bg: #f5f7fa;
--c-surface: #ffffff;
--c-surface-2: #f0f3f8;
--c-border: #e3e8ef;
--c-text: #1c2333;
--c-text-2: #5a6478;
--c-text-3: #8a93a6;
--c-primary: #2f5cff;
--c-primary-weak: rgba(47, 92, 255, 0.1);
--c-success: #17895a;
--c-warning: #b97509;
--c-danger: #d64545;
--radius: 10px;
--radius-lg: 14px;
--shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 4px 16px rgba(16, 24, 40, 0.06);
--font-sans: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, -apple-system, sans-serif;
--font-mono: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
body {
font-family: var(--font-sans);
background: var(--c-bg);
color: var(--c-text);
font-size: 14px;
line-height: 1.6;
-webkit-font-smoothing: antialiased;
}
a {
color: var(--c-primary);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* ---------- 布局原语 ---------- */
.page {
max-width: 1100px;
margin: 0 auto;
padding: 24px 28px 48px;
}
.page-header {
margin-bottom: 20px;
}
.page-title {
font-size: 22px;
font-weight: 700;
margin: 0 0 6px;
}
.page-subtitle {
color: var(--c-text-2);
margin: 0;
}
.grid {
display: grid;
gap: 16px;
}
.grid-2 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.grid-3 {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.grid-4 {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
@media (max-width: 900px) {
.grid-3,
.grid-4 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 620px) {
.grid-2,
.grid-3,
.grid-4 {
grid-template-columns: minmax(0, 1fr);
}
}
/* ---------- 卡片与统计 ---------- */
.card {
background: var(--c-surface);
border: 1px solid var(--c-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow);
padding: 18px 20px;
}
.card-title {
font-size: 15px;
font-weight: 600;
margin: 0 0 12px;
}
.card-body {
color: var(--c-text-2);
}
.stat {
background: var(--c-surface);
border: 1px solid var(--c-border);
border-radius: var(--radius);
padding: 14px 16px;
}
.stat-value {
font-size: 26px;
font-weight: 700;
line-height: 1.2;
}
.stat-label {
color: var(--c-text-3);
font-size: 12px;
margin-top: 4px;
}
.stat-up {
color: var(--c-success);
}
.stat-down {
color: var(--c-danger);
}
/* ---------- 标签与徽章 ---------- */
.badge {
display: inline-block;
padding: 2px 10px;
border-radius: 999px;
font-size: 12px;
background: var(--c-surface-2);
color: var(--c-text-2);
border: 1px solid var(--c-border);
}
.badge-primary {
background: var(--c-primary-weak);
color: var(--c-primary);
border-color: rgba(47, 92, 255, 0.25);
}
/* ---------- 按钮 ---------- */
.btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 16px;
border-radius: 8px;
border: 1px solid var(--c-border);
background: var(--c-surface);
color: var(--c-text);
font-size: 14px;
cursor: pointer;
transition: all 0.15s ease;
}
.btn:hover {
border-color: var(--c-primary);
color: var(--c-primary);
}
.btn-primary {
background: var(--c-primary);
border-color: var(--c-primary);
color: #fff;
}
.btn-primary:hover {
background: #2450e0;
color: #fff;
}
/* ---------- 表格 ---------- */
.table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.table th,
.table td {
text-align: left;
padding: 9px 12px;
border-bottom: 1px solid var(--c-border);
}
.table th {
color: var(--c-text-3);
font-weight: 500;
background: var(--c-surface-2);
}
.table tr:last-child td {
border-bottom: none;
}
/* ---------- 其他 ---------- */
.page-loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 50vh;
color: var(--c-text-3);
}
.muted {
color: var(--c-text-3);
}
.mono {
font-family: var(--font-mono);
}
.divider {
border: none;
border-top: 1px solid var(--c-border);
margin: 16px 0;
}
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2018",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowImportingTsExtensions": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src", "site.json"]
}
@@ -0,0 +1,24 @@
import { fileURLToPath, URL } from "node:url";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
// 站点会被静态托管在嵌套路径下(/api/public/site-preview/{token}/),
// 因此必须用相对基准 base: "./",让 assets 引用随宿主路径自适应。
export default defineConfig({
base: "./",
plugins: [react()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
build: {
// 兼容 chrome100 一类的旧内核浏览器(与 DeerFlow 前端构建基线一致)
target: "es2018",
outDir: "dist",
emptyOutDir: true,
// 生成的站点普遍很小,关闭分块警告
chunkSizeWarningLimit: 4096,
},
});