Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1dd2921674 | ||
|
|
d30f7d08c5 | ||
|
|
5bdb55f3f1 | ||
|
|
fbecf30513 | ||
|
|
19d5ac0fee |
@@ -1,139 +0,0 @@
|
||||
---
|
||||
description: 审查当前工作区未提交代码中的垃圾代码,并在不影响逻辑的前提下自动清理
|
||||
argument-hint: 可选:指定要检查的文件或目录(默认检查所有未提交修改)
|
||||
allowed-tools: ["Read", "Edit", "Bash", "Grep", "Glob"]
|
||||
---
|
||||
|
||||
# /cleanup — 垃圾代码审查与清理
|
||||
|
||||
分析当前工作区(git diff)中的未提交代码,找出并修复常见垃圾代码,**不得改变任何运行逻辑**。
|
||||
|
||||
## 检查范围
|
||||
|
||||
若 `$ARGUMENTS` 非空,则只检查指定文件/目录;否则检查所有未提交修改(`git diff HEAD`)。
|
||||
|
||||
## 节省上下文规则
|
||||
|
||||
优先用确定性的 CLI 检查缩小范围,不要一上来把完整文件或大 diff 读入上下文:
|
||||
|
||||
```bash
|
||||
git diff --name-only HEAD
|
||||
git diff --unified=0 HEAD -- <path>
|
||||
git diff --check
|
||||
rg -n "TODO|FIXME|console\.log|debugger|print\(" <changed-paths>
|
||||
```
|
||||
|
||||
只有 focused diff 不足以安全判断或修改时,才读取完整文件。
|
||||
|
||||
## 审查清单
|
||||
|
||||
按优先级检查以下问题(只报告在本次 diff 中**新增或修改**的代码里存在的问题):
|
||||
|
||||
### 1. 重复逻辑 (Duplicate Logic)
|
||||
- 完全相同或高度相似的代码块在多处出现
|
||||
- 同一函数/方法被多个地方各自实现,已有公共版本未被复用
|
||||
- 相同的 DOM 查询、正则、模板字符串在同一文件重复
|
||||
|
||||
### 2. Magic Numbers / Magic Strings
|
||||
- 裸数字直接参与计算(如偏移量、时间、尺寸、阈值),没有命名常量
|
||||
- 硬编码字符串(如 id 名、状态值、URL 片段)散落在逻辑中
|
||||
- 例外:`0`, `1`, `-1`, `100`, `""` 等语义明确的惯用值不算
|
||||
|
||||
### 3. 命名问题
|
||||
- 含义不明的缩写变量(如 `or_`, `tmp2`, `x2`)
|
||||
- 命名与实际用途不符
|
||||
- 同一概念在不同地方用不同名字表达
|
||||
|
||||
### 4. 死代码 / 无效代码
|
||||
- 注释掉的旧代码块(3行以上)
|
||||
- 声明后从未使用的变量/参数/导入
|
||||
- 永远不会执行的条件分支
|
||||
|
||||
### 5. 代码风格问题
|
||||
- 尾部空白字符(trailing whitespace)
|
||||
- 同一文件内风格不一致(如混用单双引号、缩进不统一)
|
||||
- 空行使用不一致(连续多个空行等)
|
||||
|
||||
### 6. 其他常见问题
|
||||
- 私有辅助函数应被 export 但没有,导致调用方重复实现
|
||||
- 类型/接口重复定义
|
||||
- 过于冗长的条件表达式可以简化(不改逻辑)
|
||||
|
||||
## 执行步骤
|
||||
|
||||
### Step 1 — 获取待检查文件列表
|
||||
|
||||
```bash
|
||||
# 无参数时:获取所有未提交修改
|
||||
git diff HEAD --name-only
|
||||
|
||||
# 有参数时:用 $ARGUMENTS 过滤
|
||||
```
|
||||
|
||||
### Step 2 — 逐文件阅读并分析
|
||||
|
||||
先从 focused diff 开始:
|
||||
|
||||
```bash
|
||||
git diff --unified=0 HEAD -- <file>
|
||||
```
|
||||
|
||||
用 `rg`、`git diff --check`、编译器或 linter 输出确认确定性问题。只有需要上下文时才用 Read 读取完整文件。对照审查清单,记录每个问题:文件名、行号、问题类型、建议修复方式。
|
||||
|
||||
### Step 3 — 报告问题清单
|
||||
|
||||
在修改前,先以列表形式输出所有发现的问题:
|
||||
|
||||
```
|
||||
发现 N 个问题:
|
||||
|
||||
[文件] js/foo.js
|
||||
· L34, L78: 重复逻辑 — 两处都实现了相同的 DOM 查询,可提取到 getPanel()
|
||||
· L91: Magic number — 硬编码 14 作为偏移量,应命名为 TOOLTIP_OFFSET
|
||||
|
||||
[文件] js/bar.js
|
||||
· L12: 命名问题 — 变量 `or_` 语义不明,应命名为 outerR/outerG/outerB
|
||||
...
|
||||
```
|
||||
|
||||
如果没有发现问题,直接输出"未发现垃圾代码,当前代码质量良好。"并停止。
|
||||
|
||||
### Step 4 — 执行修复
|
||||
|
||||
对每个问题,使用 Edit 工具进行**最小化修改**:
|
||||
|
||||
- **重复逻辑**:提取为共享常量/函数,更新所有调用点
|
||||
- **Magic number**:在文件顶部或逻辑附近声明 `const NAME = value`,替换所有引用
|
||||
- **命名问题**:重命名变量,更新所有使用处
|
||||
- **死代码**:直接删除
|
||||
- **尾部空白/风格**:修正
|
||||
- **未 export 的函数**:添加 `export`,在调用方改为导入(不重复实现)
|
||||
|
||||
**修复原则:**
|
||||
- 只改在审查清单中发现的问题,不做额外优化
|
||||
- 每次 Edit 只修改确实有问题的行,保持 diff 最小
|
||||
- 改完后用 `grep` 验证旧的坏代码已消失
|
||||
- 优先做精确补丁;只有仓库已有对应格式化流程时,才运行格式化工具
|
||||
|
||||
### Step 5 — 输出总结
|
||||
|
||||
```
|
||||
清理完成:
|
||||
|
||||
修复了 N 个问题:
|
||||
✓ earth.js — 提取重复 vertexShader 为 ATMOS_VERTEX_SHADER 常量
|
||||
✓ main.js — 提取 TOOLTIP_CURSOR_OFFSET = 14(4处引用)
|
||||
✓ controls.js — export updateLayerButtonState,移除 main.js 中的重复实现
|
||||
...
|
||||
|
||||
未修改的问题(需人工确认):
|
||||
! foo.js L45 — 注释代码块较长,建议手动确认是否可删除
|
||||
```
|
||||
|
||||
## 约束
|
||||
|
||||
- **禁止**改变函数签名、接口定义、导出 API(除非问题正是私有函数应被 export)
|
||||
- **禁止**添加新功能、新抽象、新参数
|
||||
- **禁止**修改注释内容(只删除注释掉的死代码)
|
||||
- **禁止**修改测试文件逻辑
|
||||
- 如果一个 Magic number 的语义不完全确定,**跳过**,在总结中标记为"需人工确认"
|
||||
@@ -1,104 +0,0 @@
|
||||
---
|
||||
description: Create or update repository documentation from current code changes
|
||||
argument-hint: Optional: topic to document, or leave empty to infer from git diff
|
||||
allowed-tools: ["Read", "Edit", "Write", "Bash", "Glob", "Grep"]
|
||||
---
|
||||
|
||||
# /docs — Documentation Workflow
|
||||
|
||||
## Goal
|
||||
|
||||
Create or update documentation that explains why a change exists, how it behaves, and what maintainers need to know. Keep this command generic. Repository-specific coverage rules live in the repository and must be loaded separately.
|
||||
|
||||
## Repository Rules
|
||||
|
||||
Before deciding scope, check whether the repository has a documentation rules file:
|
||||
|
||||
```bash
|
||||
test -f docs/documentation-coverage-rules.md && sed -n '1,240p' docs/documentation-coverage-rules.md
|
||||
```
|
||||
|
||||
If it exists, apply it as the project-specific coverage checklist. If it does not exist, continue with the generic workflow below.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1 — Understand The Change
|
||||
|
||||
```bash
|
||||
git diff HEAD --stat
|
||||
git diff HEAD --name-only
|
||||
git log --oneline -10
|
||||
rg --files docs
|
||||
```
|
||||
|
||||
If `$ARGUMENTS` specifies a topic, focus on that topic. Otherwise infer the documentation topic from the changed files. Do not read the full repository diff by default; inspect focused files only:
|
||||
|
||||
```bash
|
||||
git diff HEAD -- <path>
|
||||
rg -n "class |def |function |export |router|@router|interface |type " <path>
|
||||
```
|
||||
|
||||
### Step 2 — Decide Scope
|
||||
|
||||
- Prefer updating an existing relevant document over creating a duplicate.
|
||||
- Use one document for one coherent topic.
|
||||
- Split documents only when the change crosses meaningful domains.
|
||||
- Keep filenames lowercase and hyphenated.
|
||||
- Apply the repository-specific rules file before writing.
|
||||
|
||||
#### Document Audience Routing (Planet)
|
||||
|
||||
In this repository, classify the action's performer before picking a target file:
|
||||
|
||||
- Browser/UI end user → `docs/technical/{zh,en}/manual.md` or `quickstart.md`.
|
||||
- Shell / Docker / log paths / `planet.sh` / SMTP fallbacks / port forwarding → `docs/technical/{zh,en}/ops-runbook.md` (or an existing `ops-*.md`).
|
||||
- Second-party developers → existing `*-context.md` / `backend-*.md` / `earth-*.md` files.
|
||||
|
||||
Never put shell commands, log paths, or Docker operations into `manual.md` / `quickstart.md`. Never put UI button labels or screenshots into `ops-*.md`. When the same action has both a UI and a CLI path, write each in its own home and cross-link them with one sentence.
|
||||
|
||||
For ambiguous or large documentation changes, briefly state the intended doc plan before editing. For clear small changes, proceed directly.
|
||||
|
||||
### Step 3 — Write
|
||||
|
||||
Explain:
|
||||
|
||||
- Background/problem: what was wrong or missing before.
|
||||
- Core design decisions and rationale.
|
||||
- Operational or user-facing impact.
|
||||
- Relevant code paths, only when useful for future maintainers.
|
||||
|
||||
Style:
|
||||
|
||||
- Follow the repository’s existing language and heading conventions.
|
||||
- Use fenced code blocks with language tags.
|
||||
- Prefer tables for comparisons or parameter lists.
|
||||
- Keep snippets concise and relevant.
|
||||
- For UI labels, chart labels, feature names, datasource names, and other terms that may become mixed Chinese/English copy, check `docs/technical/{zh,en}/naming-glossary.md` and use the documented display name. If a confusing term is missing, update the glossary in both languages as part of the docs change.
|
||||
|
||||
### Step 4 — Verify
|
||||
|
||||
- Read the completed docs once for clarity and stale statements.
|
||||
- Verify referenced paths exist with `test -e` or `rg --files`.
|
||||
- Run applicable checks from `docs/documentation-coverage-rules.md`.
|
||||
- Check Markdown links use readable user-facing titles unless repository rules allow otherwise.
|
||||
|
||||
### Step 5 — Report
|
||||
|
||||
Summarize changed docs and verification:
|
||||
|
||||
```md
|
||||
Updated:
|
||||
- path/to/doc.md — what changed
|
||||
|
||||
Verified:
|
||||
- checks that passed
|
||||
- checks that could not be run, if any
|
||||
```
|
||||
|
||||
## Hard Constraints
|
||||
|
||||
- Do not leave placeholder docs.
|
||||
- Do not duplicate bilingual files byte-for-byte.
|
||||
- Do not reference PR numbers, issue numbers, or the current conversation unless explicitly requested.
|
||||
- Do not write changelog-style lists without the reasoning and tradeoffs behind the change.
|
||||
- Keep docs maintainable and concise.
|
||||
@@ -1,93 +0,0 @@
|
||||
---
|
||||
description: 用 goal-driven 方法推动一个复杂任务持续执行,直到明确成功标准被满足
|
||||
argument-hint: 建议填写任务目标;若同时给出成功标准更好
|
||||
allowed-tools: ["Read", "Edit", "Bash", "Grep", "Glob"]
|
||||
---
|
||||
|
||||
# /goal-driven — 目标驱动执行模式
|
||||
|
||||
使用 `lidangzzz/goal-driven` 的核心思想来推进复杂任务:先固定目标与成功标准,再持续执行和反复验收,直到标准真正满足。
|
||||
|
||||
适用场景:
|
||||
|
||||
- 长周期实现任务
|
||||
- 高复杂度工程任务
|
||||
- 可被明确验收的研究、实现、迁移、验证类工作
|
||||
|
||||
不适用场景:
|
||||
|
||||
- 纯脑暴
|
||||
- 无法定义成功标准的模糊任务
|
||||
- 很小的一次性修改
|
||||
|
||||
## 输入要求
|
||||
|
||||
若 `$ARGUMENTS` 只包含目标,没有成功标准,先补全一版可执行的成功标准再开始。
|
||||
|
||||
启动时先输出:
|
||||
|
||||
```md
|
||||
Goal
|
||||
- ...
|
||||
|
||||
Criteria for success
|
||||
- ...
|
||||
|
||||
Plan
|
||||
1. ...
|
||||
2. ...
|
||||
3. ...
|
||||
|
||||
Verification
|
||||
- ...
|
||||
```
|
||||
|
||||
## 执行规则
|
||||
|
||||
1. 先把任务固化为两个核心块:
|
||||
- `Goal`
|
||||
- `Criteria for success`
|
||||
|
||||
2. 成功标准必须尽量客观,可验证,可落地。
|
||||
优先写成:
|
||||
- 需要交付什么
|
||||
- 需要通过哪些测试或验证
|
||||
- 如何判断结果真的完成
|
||||
|
||||
3. 进入持续执行循环:
|
||||
- 完成一个阶段
|
||||
- 检查当前结果是否满足成功标准
|
||||
- 若未满足,明确剩余差距并继续推进
|
||||
|
||||
4. 任何“完成了”“差不多了”“已实现”之类的结论,都必须经过验证,不能直接接受。
|
||||
|
||||
5. 如果验证失败:
|
||||
- 明确指出哪条成功标准没满足
|
||||
- 继续工作,不要把阶段性进展误判为完成
|
||||
|
||||
6. 只有在以下情况之一才能停止:
|
||||
- 成功标准已满足
|
||||
- 用户明确要求停止
|
||||
|
||||
## 执行风格
|
||||
|
||||
- 重证据,轻口头判断
|
||||
- 优先使用确定性工具证据:`rg`、`git diff --stat`、`git diff -- <path>`、测试、构建、lint、`curl`、数据库查询等能直接证明成功标准的方式
|
||||
- 不把大段命令输出粘进回复;保留在工具调用里,回复只总结关键证据
|
||||
- 重验收,轻自我感觉
|
||||
- 优先用测试、日志、产物、对比结果来证明完成
|
||||
- 对长期任务保持“未达标就继续”的节奏
|
||||
|
||||
## 简版模板
|
||||
|
||||
```md
|
||||
Goal: [[[[[在此填写最终目标]]]]]
|
||||
|
||||
Criteria for success: [[[[[在此填写成功标准]]]]]
|
||||
|
||||
循环执行:
|
||||
1. 推进任务
|
||||
2. 检查是否满足成功标准
|
||||
3. 若未满足,继续工作
|
||||
4. 直到满足标准或用户明确停止
|
||||
```
|
||||
@@ -1,160 +0,0 @@
|
||||
---
|
||||
description: 发版工作流:根据变更类型决定版本号,更新所有版本文件和 changelog,运行验证,commit 并 push
|
||||
argument-hint: 可选:feature | bugfix | 或直接描述本次发布内容
|
||||
allowed-tools: ["Read", "Edit", "Bash", "Glob", "Grep"]
|
||||
---
|
||||
|
||||
# /release — Planet 发版工作流
|
||||
|
||||
## 版本号规则
|
||||
|
||||
| 变更类型 | 版本跳动 | 适用场景 |
|
||||
|---------|---------|---------|
|
||||
| `feature` | `+0.1.0` | 纯新功能,无 bugfix |
|
||||
| `improvement` | `+0.0.1` | UI 调整、小功能增强、bugfix 混合,或以 UI/体验改进为主的迭代 |
|
||||
| `bugfix` | `+0.0.1` | 纯 bug 修复,无新功能 |
|
||||
| `docs` / `maintenance` / `refactor` | 默认不发版,除非用户明确要求 |
|
||||
|
||||
意图混合时以用户明确描述为准;bugfix + 小 feature 混合默认判定为 `improvement`(`+0.0.1`)。
|
||||
|
||||
## 必须同步更新的文件
|
||||
|
||||
使用 `git rev-parse --show-toplevel` 获取仓库根目录,以下路径均相对于根目录:
|
||||
|
||||
- `VERSION`
|
||||
- `frontend/package.json`(`"version"` 字段)
|
||||
- `pyproject.toml`(`version =` 字段)
|
||||
- `uv.lock`(**不要手动编辑**,通过 `uv lock` 重新生成)
|
||||
- `docs/CHANGELOG.md`
|
||||
- `docs/version-history.md`
|
||||
|
||||
## 节省上下文规则
|
||||
|
||||
发版判断应以确定性 CLI 证据为主,优先使用紧凑命令和定点读取:
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
git diff --stat HEAD
|
||||
git diff --name-only HEAD
|
||||
rg -n "version|^## |^Released:|当前开发版本|current" VERSION frontend/package.json pyproject.toml docs/CHANGELOG.md docs/version-history.md
|
||||
```
|
||||
|
||||
除非需要判断某个代码变更是否属于本次发版,否则不要读取完整 diff。
|
||||
|
||||
## 执行步骤
|
||||
|
||||
### Step 1 — 环境检查
|
||||
|
||||
```bash
|
||||
git branch --show-current # 确认在 dev 分支
|
||||
git status --short # 检查是否有无关的未暂存修改
|
||||
cat VERSION # 读取当前版本
|
||||
```
|
||||
|
||||
若当前**不在 `dev` 分支**,停下来告知用户,不要继续。
|
||||
|
||||
若存在无关的未暂存修改,列出并询问用户是否一并提交,或先 stash。
|
||||
|
||||
### Step 2 — 确定发版类型与新版本号
|
||||
|
||||
- 若 `$ARGUMENTS` 提供了明确类型(`feature` / `bugfix`),直接使用
|
||||
- 否则根据 `git diff --stat HEAD`、`git diff --name-only HEAD`、必要的 focused diff 和 `git log` 推断
|
||||
- 计算新版本号(例:`0.26.2` → bugfix → `0.26.3`)
|
||||
- **先输出发版计划供用户确认**:
|
||||
|
||||
```
|
||||
发版计划:
|
||||
类型:bugfix
|
||||
版本:0.26.2 → 0.26.3
|
||||
分支:dev
|
||||
将更新:VERSION, frontend/package.json, pyproject.toml, uv.lock, CHANGELOG.md, version-history.md
|
||||
```
|
||||
|
||||
### Step 3 — 更新版本号文件
|
||||
|
||||
按顺序更新(每步用 Edit 工具,精确替换,不要重写整个文件):
|
||||
|
||||
1. `VERSION` — 直接替换全部内容为新版本号
|
||||
2. `frontend/package.json` — 替换 `"version": "x.x.x"` 行
|
||||
3. `pyproject.toml` — 替换 `version = "x.x.x"` 行
|
||||
4. 运行 `uv lock` 重新生成 `uv.lock`(在仓库根目录下执行)
|
||||
|
||||
### Step 4 — 更新 CHANGELOG.md
|
||||
|
||||
在文件顶部插入新条目,格式:
|
||||
|
||||
```markdown
|
||||
## [x.x.x] — YYYY-MM-DD
|
||||
|
||||
### ✨ Features / 🐛 Fixes / 🔧 Improvements
|
||||
- ...(只列高信号条目,最多 5 条)
|
||||
- ...
|
||||
|
||||
---
|
||||
```
|
||||
|
||||
日期使用 `date +%Y-%m-%d` 获取今天的日期。
|
||||
|
||||
### Step 5 — 更新 docs/version-history.md
|
||||
|
||||
- 更新文件头部的"当前开发版本"字段
|
||||
- 在时间线表格顶部插入新行:`| vx.x.x | YYYY-MM-DD | 一句话摘要 |`
|
||||
|
||||
### Step 6 — 验证
|
||||
|
||||
针对本次变更范围做最小验证:
|
||||
|
||||
- Python 文件有修改:先用 `git diff --name-only HEAD -- '*.py'` 列出,再运行 `python3 -m py_compile <changed_files>`
|
||||
- Frontend 文件有修改:先用 `git diff --name-only HEAD -- frontend` 判断范围,再运行项目标准检查(若无则跳过并说明)
|
||||
- 版本号一致性检查:用 grep 确认 VERSION、package.json、pyproject.toml 中的版本号完全一致
|
||||
|
||||
```bash
|
||||
cat VERSION
|
||||
rg -n "\"version\":|^version =|version = " frontend/package.json pyproject.toml uv.lock
|
||||
```
|
||||
|
||||
### Step 7 — 提交前预览
|
||||
|
||||
展示将要提交的文件列表:
|
||||
|
||||
```bash
|
||||
git diff --stat HEAD
|
||||
```
|
||||
|
||||
再次确认所有必须文件都在变更列表中,**不包含**非预期文件(如调试文件、.env 等)。
|
||||
|
||||
### Step 8 — Commit & Push(用户确认后)
|
||||
|
||||
```bash
|
||||
git add VERSION frontend/package.json pyproject.toml uv.lock docs/CHANGELOG.md docs/version-history.md
|
||||
# 若有代码变更也一并 stage
|
||||
git add <code_files>
|
||||
|
||||
git commit -m "release: bump version to x.x.x"
|
||||
git tag vx.x.x
|
||||
git push origin dev
|
||||
git push origin vx.x.x
|
||||
```
|
||||
|
||||
commit message 固定格式:`release: bump version to x.x.x`
|
||||
|
||||
### Step 9 — 完成确认
|
||||
|
||||
输出摘要:
|
||||
|
||||
```
|
||||
✓ 版本号已更新:0.26.2 → 0.26.3
|
||||
✓ CHANGELOG 已更新
|
||||
✓ version-history 已更新
|
||||
✓ uv.lock 已重新生成
|
||||
✓ 验证通过
|
||||
✓ commit: release: bump version to 0.26.3
|
||||
✓ tag: v0.26.3
|
||||
✓ 已 push 到 origin/dev
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
- `uv.lock` 只能通过 `uv lock` 生成,绝不手动编辑
|
||||
- 发版 commit 只包含版本文件 + 本次功能代码,不混入无关改动
|
||||
- 若环境中 `uv` 不可用,说明原因并跳过 lockfile 更新,提醒用户手动运行
|
||||
BIN
.codex/screenshots/earth-i18n-current-page.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
.codex/screenshots/earth-i18n-hd-texture-status.png
Normal file
|
After Width: | Height: | Size: 4.4 KiB |
BIN
.codex/screenshots/i18n-admin-data-sidebar.png
Normal file
|
After Width: | Height: | Size: 109 KiB |
BIN
.codex/screenshots/i18n-ai-tool-calls.png
Normal file
|
After Width: | Height: | Size: 124 KiB |
BIN
.codex/screenshots/i18n-earth-brand-config.png
Normal file
|
After Width: | Height: | Size: 170 KiB |
BIN
.codex/screenshots/i18n-earth-hud-brand.png
Normal file
|
After Width: | Height: | Size: 772 KiB |
BIN
.codex/screenshots/i18n-settings-notifications.png
Normal file
|
After Width: | Height: | Size: 95 KiB |
BIN
.codex/screenshots/i18n-settings-system.png
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
.codex/screenshots/sidebar-left-align.png
Normal file
|
After Width: | Height: | Size: 28 KiB |
145
AGENTS.md
@@ -1,28 +1,41 @@
|
||||
# Planet Agent Entry Point
|
||||
# AGENTS.md
|
||||
|
||||
This is the compatibility entry point for coding agents. The older root
|
||||
`agents.md` file remains authoritative for repository-specific agent behavior;
|
||||
do not delete or replace it.
|
||||
**Planet agent harness. Defines behavior for coding agents working in this repository.**
|
||||
|
||||
## Read First
|
||||
---
|
||||
|
||||
## Harness Compatibility
|
||||
|
||||
This file is the single authoritative agent guide for the Planet repository.
|
||||
The older lowercase `agents.md` entry has been merged here so coding agents and
|
||||
harness tools use one source of truth.
|
||||
|
||||
### Source Of Truth
|
||||
|
||||
- `rules.md` is the mandatory repository rule source. Always load `core`,
|
||||
`security`, and `workflow`; load only task-relevant modules after that.
|
||||
- `AGENTS.md` defines the local agent operating mode and evidence gates.
|
||||
- `project_context.md` is background, not a rule source. Prefer newer
|
||||
implementation docs when it disagrees with current code.
|
||||
- `.codex/skills/` is the active specialized workflow layer for cleanup, docs,
|
||||
goal-driven work, and release.
|
||||
- Do not duplicate long workflow text across harness files. Durable constraints
|
||||
belong in `rules.md`; task procedures belong in skills or scripts.
|
||||
|
||||
Read these files before changing code:
|
||||
|
||||
1. `rules.md` - mandatory repository rules. Always load `core`, `security`, and
|
||||
`workflow`; load `docs`, `frontend`, `backend`, `earth`, `ai`, or `release`
|
||||
when the task touches those areas.
|
||||
2. `agents.md` - existing agent role, communication, and workflow guidance.
|
||||
3. `project_context.md` - static project background. Prefer newer implementation
|
||||
docs when this context disagrees with current code.
|
||||
4. `README.md` - current architecture, startup, and toolchain summary.
|
||||
5. `docs/HARNESS.md` - harness workflow, conflict policy, and validation tiers.
|
||||
6. `CODEMAP.md` - codebase entry points, ownership boundaries, and deeper docs.
|
||||
1. `rules.md`
|
||||
2. `AGENTS.md`
|
||||
3. `project_context.md`
|
||||
4. `README.md`
|
||||
5. `docs/HARNESS.md`
|
||||
6. `CODEMAP.md`
|
||||
|
||||
For documentation work, also read `docs/documentation-coverage-rules.md`.
|
||||
|
||||
## Start Safely
|
||||
### Start Safely
|
||||
|
||||
Before editing:
|
||||
Before broad edits:
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
@@ -40,7 +53,7 @@ git diff --unified=0 HEAD -- <path>
|
||||
|
||||
Preserve user changes already present in the worktree.
|
||||
|
||||
## Validation
|
||||
### Validation
|
||||
|
||||
Fast local harness validation:
|
||||
|
||||
@@ -54,28 +67,114 @@ Full local validation:
|
||||
scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
`validate.sh` includes the quick check and the frontend Bun build. Docker image
|
||||
smoke builds are intentionally opt-in:
|
||||
`validate.sh` includes quick checks, frontend Bun build, and frontend smoke
|
||||
unless disabled by its documented environment flags. Docker image smoke builds
|
||||
are intentionally opt-in:
|
||||
|
||||
```bash
|
||||
PLANET_HARNESS_DOCKER_SMOKE=1 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
## High-Risk Areas
|
||||
Harness scripts resolve `bun`, `uv`, and optional delivery tools from the
|
||||
current non-interactive environment first. If a tool is missing there, they ask
|
||||
the user's login interactive shell instead of assuming a specific dotfile.
|
||||
|
||||
### High-Risk Areas
|
||||
|
||||
- `planet.sh` owns local lifecycle, ports, WSL/LAN behavior, and destructive
|
||||
`destroy` cleanup.
|
||||
- Frontend package management is Bun-only. Do not use npm, pnpm, or yarn.
|
||||
- Frontend changes must satisfy `scripts/harness/frontend-rules-check.sh`; use
|
||||
rendered smoke evidence for public pages, auth guards, authenticated admin
|
||||
route/section availability, safe navigation/search/tab interactions, mobile
|
||||
layout, and 125% / 150% zoom, not only a build.
|
||||
- Admin or Docs layout changes must load `rules.md` `uiux` and preserve the
|
||||
one-screen (`一屏` / `首屏`) height chain: route roots use `height: 100%`,
|
||||
intermediate wrappers keep `min-height: 0`, and only the intended child owns
|
||||
scrolling.
|
||||
- `aiprovider` is a protocol/provider adapter; keep business prompts and product
|
||||
workflows in the backend.
|
||||
- Earth rendering depends on layer order, depth behavior, picking, and
|
||||
performance-sensitive Three.js code.
|
||||
- Secrets belong in environment files or configured settings stores, never in
|
||||
committed files.
|
||||
- Backend service code must use structured logging instead of `print()` or
|
||||
debugger calls; `scripts/harness/backend-rules-check.sh` enforces this.
|
||||
|
||||
## Conflict Policy
|
||||
### Conflict Policy
|
||||
|
||||
Existing project rules and workflows win. If new harness guidance conflicts with
|
||||
`rules.md`, `agents.md`, current docs, scripts, or CI, keep the existing behavior
|
||||
and document the compatibility note in `docs/harness-audit.md` or
|
||||
`rules.md`, `AGENTS.md`, current docs, scripts, or CI, keep the existing
|
||||
behavior and document the compatibility note in `docs/harness-audit.md` or
|
||||
`docs/HARNESS.md`.
|
||||
|
||||
---
|
||||
|
||||
## Operating Mode
|
||||
|
||||
- Default to acting directly when the user gives a clear task.
|
||||
- Ask before acting only when the missing decision is risky, cannot be
|
||||
discovered from repository context, and no conservative assumption is safe.
|
||||
- Read relevant files before editing.
|
||||
- Prefer focused CLI evidence: `rg`, `git diff --stat`, `git diff --name-only`,
|
||||
focused file reads, tests, builds, linters, and harness scripts.
|
||||
- Keep changes scoped to the requested area. Do not mix cleanup, feature work,
|
||||
release work, and documentation unless the task requires it.
|
||||
|
||||
---
|
||||
|
||||
## Evidence Gates
|
||||
|
||||
- Visual inputs are blocking evidence. If the user provides a screenshot, image,
|
||||
mock, browser capture, or visual reference, obtain evidence from the artifact
|
||||
before interpreting intent or editing code.
|
||||
- Path resolution is part of the task. If the path cannot be opened, first try
|
||||
reasonable local equivalents such as WSL/Windows path conversion,
|
||||
workspace-relative lookup, absolute paths, and attached-file locations.
|
||||
- Never guess from prompt text, filenames, previous context, logs, OCR, or
|
||||
memory when a visual artifact was provided but cannot be accessed.
|
||||
- OCR is acceptable evidence for text-only visual questions or non-multimodal
|
||||
environments; state that OCR was used as the fallback. Layout, color, spacing,
|
||||
pixel, and rendering issues need real visual inspection or a clear limitation
|
||||
note.
|
||||
- If a visual artifact still cannot be inspected, say so and pause that
|
||||
visual-dependent part of the work.
|
||||
- Claims of completion need evidence: a relevant test, build, lint, screenshot,
|
||||
diff, direct file check, or harness result.
|
||||
- For UI and rendering changes, verify the rendered result when local tooling
|
||||
allows it.
|
||||
|
||||
---
|
||||
|
||||
## Communication
|
||||
|
||||
- Match the user's language. Use Chinese for Chinese requests unless the user
|
||||
asks otherwise.
|
||||
- Keep updates short and specific: what is being inspected, edited, or verified.
|
||||
- Final responses should summarize changed files and verification, with blockers
|
||||
stated plainly.
|
||||
- Use file references with line numbers when explaining code or review findings.
|
||||
|
||||
---
|
||||
|
||||
## Quality Bar
|
||||
|
||||
- Prefer existing project patterns over new abstractions.
|
||||
- Remove stale branches, mocks, compatibility paths, and duplicated helpers once
|
||||
a stable path exists.
|
||||
- Centralize prompts, constants, defaults, and shared request/response handling.
|
||||
- Do not add secrets, generated runtime output, or local environment files.
|
||||
- Frontend commands use Bun only. Do not use `npm`, `pnpm`, or `yarn`.
|
||||
- Run the smallest relevant verification for the changed scope and report
|
||||
anything skipped.
|
||||
|
||||
---
|
||||
|
||||
## Prohibited
|
||||
|
||||
- Do not skip visual evidence handling when a visual artifact was provided.
|
||||
- Do not preserve obsolete harness files just because they already exist.
|
||||
- Do not invent behavior not present in code, docs, or verified external
|
||||
sources.
|
||||
- Do not rewrite unrelated files during cleanup.
|
||||
- Do not mark a task complete without checking concrete success criteria.
|
||||
|
||||
22
CODEMAP.md
@@ -41,11 +41,18 @@ are the source of detail for specific subsystems.
|
||||
offsets, picking behavior, legend semantics, and performance constraints.
|
||||
- `planet.sh` owns local environment bootstrap and service lifecycle. Prefer
|
||||
wrapping it from harness scripts instead of duplicating its internals.
|
||||
- Harness scripts source `scripts/harness/lib.sh` so agent shells that cannot
|
||||
see `bun` or `uv` in non-interactive `PATH` can still resolve the user's login
|
||||
interactive command path without hardcoding `.zshrc`.
|
||||
|
||||
## Validation Commands
|
||||
|
||||
```bash
|
||||
scripts/harness/doctor.sh
|
||||
scripts/harness/security-check.sh
|
||||
scripts/harness/backend-rules-check.sh
|
||||
scripts/harness/frontend-rules-check.sh
|
||||
scripts/harness/docs-consistency-check.sh
|
||||
scripts/harness/quick-check.sh
|
||||
scripts/harness/validate.sh
|
||||
./planet.sh health
|
||||
@@ -60,8 +67,17 @@ uv run --frozen --group dev --project .. python -m pytest -s tests/test_api.py t
|
||||
cd frontend
|
||||
bun install --frozen-lockfile
|
||||
bun run build
|
||||
PLANET_FRONTEND_SMOKE_URL=http://127.0.0.1:4173 bun ../scripts/harness/frontend-smoke.mjs
|
||||
```
|
||||
|
||||
The frontend smoke covers public routes, unauthenticated admin guards,
|
||||
login-error handling, the Earth iframe entry, and authenticated `super_admin`
|
||||
admin route/section rendering with mocked API data. Authenticated admin checks
|
||||
run on desktop, mobile, and 125% / 150% zoom; desktop and mobile passes also
|
||||
check for accidental global horizontal overflow. A second smoke layer exercises
|
||||
safe desktop/mobile navigation, admin search, section tab switching, dialog
|
||||
opening, and non-destructive shortcut links.
|
||||
|
||||
Optional delivery smoke, when Docker and Helm are available:
|
||||
|
||||
```bash
|
||||
@@ -84,9 +100,9 @@ PLANET_HARNESS_DOCKER_SMOKE=1 scripts/harness/validate.sh
|
||||
|
||||
## Known Sharp Edges
|
||||
|
||||
- `project_context.md` includes older roadmap-era assumptions such as Celery,
|
||||
Kafka, TimescaleDB, MinIO, and UE5 being part of the active local stack. Treat
|
||||
it as background unless current README/docs/code confirm the same behavior.
|
||||
- `project_context.md` is static background for agents. It now labels future
|
||||
stack directions separately, but current code and technical docs still win
|
||||
when details diverge.
|
||||
- README now describes Web Earth, React admin, FastAPI, and `aiprovider` as the
|
||||
active local development shape.
|
||||
- Local `destroy` is intentionally destructive for Planet-owned Docker and build
|
||||
|
||||
@@ -83,7 +83,7 @@
|
||||
| 组件 | 用途 |
|
||||
|------|------|
|
||||
| React 18 | UI 框架 |
|
||||
| Ant Design Pro | 管理后台组件 |
|
||||
| Tactile UI / Radix primitives / lucide-react | 管理后台组件、基础交互与图标 |
|
||||
| Axios | HTTP 客户端 |
|
||||
| Socket.io-client | WebSocket 客户端 |
|
||||
| ECharts | 统计图表 |
|
||||
|
||||
248
agents.md
@@ -1,248 +0,0 @@
|
||||
# agents.md
|
||||
|
||||
**AI Agent 角色设定。定义 AI 如何行为、沟通和工作。**
|
||||
|
||||
---
|
||||
|
||||
## Harness Compatibility
|
||||
|
||||
Common agent tools should start at `AGENTS.md`. This file remains the existing
|
||||
behavior guide and must not be replaced by harness docs. For safe repository
|
||||
orientation, use:
|
||||
|
||||
- `rules.md` for mandatory project rules
|
||||
- `project_context.md` for static background
|
||||
- `docs/HARNESS.md` for validation tiers and conflict policy
|
||||
- `CODEMAP.md` for subsystem entry points and ownership boundaries
|
||||
- `docs/harness-audit.md` for the latest harness compatibility notes
|
||||
|
||||
Existing project rules and workflows stay authoritative when they conflict with
|
||||
new harness guidance.
|
||||
|
||||
---
|
||||
|
||||
## Identity
|
||||
|
||||
You are **opencode**, an AI coding assistant specialized in enterprise-level systems.
|
||||
|
||||
You are working on the **智能星球计划 (Intelligent Planet Plan)** - a situational awareness system for data-centric competition featuring:
|
||||
- Python FastAPI backend
|
||||
- React Admin dashboard
|
||||
- Unreal Engine 5 3D visualization
|
||||
- Multi-source data collection
|
||||
- Polarized 3D large display (4K, 120Hz)
|
||||
|
||||
---
|
||||
|
||||
## Communication Style
|
||||
|
||||
### Tone
|
||||
- **Professional but concise**
|
||||
- Technical accuracy with clarity
|
||||
- No unnecessary verbosity
|
||||
- Use code comments sparingly (explain **why**, not **what**)
|
||||
|
||||
### When Responding
|
||||
1. **Answer directly** - 1-3 sentences for simple questions
|
||||
2. **Use code blocks** for all code snippets
|
||||
3. **Include file:line_number** references when discussing code
|
||||
4. **Never** start with "I am an AI assistant" or similar phrases
|
||||
5. **Never** add unnecessary preambles/postambles
|
||||
|
||||
### Examples
|
||||
|
||||
**Good:**
|
||||
```
|
||||
GPU clusters are stored in `backend/app/services/collectors/top500.py:45`.
|
||||
```
|
||||
|
||||
**Bad:**
|
||||
```
|
||||
Based on the information you provided, I can see that the GPU clusters are stored in the top500.py file at line 45. Let me explain more about this...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Operational Mode
|
||||
|
||||
### Plan Mode (default for complex tasks)
|
||||
- Analyze requirements
|
||||
- Propose architecture
|
||||
- Confirm with user before execution
|
||||
- **DO NOT** write code until approved
|
||||
|
||||
### Build Mode (after user approval)
|
||||
- Execute the approved plan
|
||||
- Write code, run commands
|
||||
- Verify results
|
||||
- Report completion concisely
|
||||
|
||||
### Read-Only Mode
|
||||
- Analyze code
|
||||
- Explain functionality
|
||||
- Answer questions
|
||||
- **DO NOT** modify files
|
||||
|
||||
---
|
||||
|
||||
## Decision Framework
|
||||
|
||||
### When to Ask Before Acting
|
||||
- Unclear requirements
|
||||
- Multiple implementation approaches
|
||||
- Architecture changes
|
||||
- Dependency additions
|
||||
- Anything that could break existing functionality
|
||||
|
||||
### When to Act Directly
|
||||
- Clear, approved requirements
|
||||
- Routine tasks (linting, formatting, running tests)
|
||||
- Following established patterns
|
||||
- Fixing obvious bugs
|
||||
|
||||
### When to Refuse
|
||||
- Malicious code requests
|
||||
- Security violations (secrets, credentials)
|
||||
- Anything that violates `rules.md`
|
||||
|
||||
---
|
||||
|
||||
## Working Principles
|
||||
|
||||
### 1. First Understand, Then Act
|
||||
- Read relevant files before editing
|
||||
- Understand existing patterns and conventions
|
||||
- Follow the code style in the codebase
|
||||
- Match the project's technology choices
|
||||
|
||||
### 2. Incremental Progress
|
||||
- Break large tasks into smaller PRs
|
||||
- Complete one feature before starting the next
|
||||
- Run tests after each significant change
|
||||
- Commit frequently with clear messages
|
||||
|
||||
### 3. Quality First
|
||||
- Write tests for new functionality
|
||||
- Run linters before committing
|
||||
- Fix warnings, don't ignore them
|
||||
- Document non-obvious decisions
|
||||
|
||||
### 4. Communication Clarity
|
||||
- Use precise technical language
|
||||
- Show relevant code, not explanations
|
||||
- Report errors with context
|
||||
- Confirm understanding of requirements
|
||||
|
||||
---
|
||||
|
||||
## Code Review Checklist
|
||||
|
||||
Before marking a task complete:
|
||||
|
||||
- [ ] Code follows `rules.md` style guidelines
|
||||
- [ ] Type hints are correct and complete
|
||||
- [ ] Error handling is proper (no silent failures)
|
||||
- [ ] Tests pass locally
|
||||
- [ ] Linting passes
|
||||
- [ ] No TODO comments left behind
|
||||
- [ ] Documentation updated if needed
|
||||
- [ ] Commit message is clear
|
||||
|
||||
---
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### Feature Development
|
||||
```
|
||||
1. Understand requirements
|
||||
2. Check existing patterns in codebase
|
||||
3. Design solution (brief mental model)
|
||||
4. Write code following rules.md
|
||||
5. Write/run tests
|
||||
6. Lint and format
|
||||
7. Commit with clear message
|
||||
8. Report completion
|
||||
```
|
||||
|
||||
### Bug Fix
|
||||
```
|
||||
1. Reproduce the bug (write failing test)
|
||||
2. Locate the source
|
||||
3. Fix the issue
|
||||
4. Verify test passes
|
||||
5. Check for regressions
|
||||
6. Commit fix
|
||||
```
|
||||
|
||||
### Refactoring
|
||||
```
|
||||
1. Understand current behavior
|
||||
2. Design target state
|
||||
3. Make incremental changes
|
||||
4. Preserve tests
|
||||
5. Verify functionality
|
||||
6. Clean up dead code
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Special Considerations
|
||||
|
||||
### WebSocket Services
|
||||
- Implement heartbeat mechanism (30-second intervals)
|
||||
- Handle disconnection gracefully
|
||||
- Include camera position in control frames
|
||||
- Support both update and full sync modes
|
||||
|
||||
### Data Collectors
|
||||
- Inherit from BaseCollector
|
||||
- Implement fetch() and transform() methods
|
||||
- Support incremental updates
|
||||
- Handle API changes gracefully
|
||||
|
||||
### UE5 Integration
|
||||
- Communicate via WebSocket
|
||||
- Send data frames at configurable intervals (default 5 min)
|
||||
- Support auto-cruise and manual modes
|
||||
- Optimize for 4K@120Hz rendering
|
||||
|
||||
### Multi-User Security
|
||||
- JWT tokens with 15-minute expiration
|
||||
- Redis token blacklist for logout
|
||||
- Role-based access control (RBAC)
|
||||
- Audit logging for all actions
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
### When Writing Code
|
||||
```python
|
||||
# File: backend/app/services/collectors/top500.py
|
||||
from typing import List, Dict
|
||||
|
||||
class TOP500Collector:
|
||||
async def fetch(self) -> List[Dict]:
|
||||
...
|
||||
```
|
||||
|
||||
### When Explaining
|
||||
- Use concise paragraphs
|
||||
- Include code references
|
||||
- No conversational filler
|
||||
|
||||
### When Reporting Progress
|
||||
- What was done
|
||||
- What remains
|
||||
- Any blockers
|
||||
- Next action
|
||||
|
||||
---
|
||||
|
||||
## Remember
|
||||
|
||||
1. **Rules are hard constraints** - follow `rules.md` absolutely
|
||||
2. **Context provides understanding** - use `project_context.md` for background
|
||||
3. **Role defines behavior** - follow `agents.md` for how to work
|
||||
4. **Quality over speed** - Enterprise systems require precision
|
||||
5. **Communicate clearly** - Precision in, precision out
|
||||
@@ -11,17 +11,20 @@ To get higher limits, set PEERINGDB_API_KEY environment variable.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from typing import Dict, Any, List
|
||||
from datetime import UTC, datetime
|
||||
import os
|
||||
from typing import Any, Dict, List
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.services.collectors.base import HTTPCollector
|
||||
|
||||
|
||||
# PeeringDB API key - read from environment variable
|
||||
PEERINGDB_API_KEY = os.environ.get("PEERINGDB_API_KEY", "")
|
||||
logger = get_logger(__name__, service="collector")
|
||||
|
||||
|
||||
class PeeringDBIXPCollector(HTTPCollector):
|
||||
@@ -39,6 +42,7 @@ class PeeringDBIXPCollector(HTTPCollector):
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (Python/collector)",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
base = self._resolved_url or self.base_url
|
||||
@@ -61,7 +65,11 @@ class PeeringDBIXPCollector(HTTPCollector):
|
||||
if response.status_code == 429:
|
||||
# Rate limited - wait and retry with exponential backoff
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
@@ -72,13 +80,21 @@ class PeeringDBIXPCollector(HTTPCollector):
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
raise
|
||||
|
||||
print(f"Warning: PeeringDB collection failed after {max_retries} retries: {last_error}")
|
||||
logger.warning_event(
|
||||
"PeeringDB collection failed after retries",
|
||||
event="collector.peeringdb.retries_exhausted",
|
||||
context={"max_retries": max_retries, "last_error": last_error},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
@@ -146,6 +162,7 @@ class PeeringDBNetworkCollector(HTTPCollector):
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (Python/collector)",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
base = self._resolved_url or self.base_url
|
||||
@@ -167,7 +184,11 @@ class PeeringDBNetworkCollector(HTTPCollector):
|
||||
|
||||
if response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
@@ -178,13 +199,21 @@ class PeeringDBNetworkCollector(HTTPCollector):
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
raise
|
||||
|
||||
print(f"Warning: PeeringDB collection failed after {max_retries} retries: {last_error}")
|
||||
logger.warning_event(
|
||||
"PeeringDB collection failed after retries",
|
||||
event="collector.peeringdb.retries_exhausted",
|
||||
context={"max_retries": max_retries, "last_error": last_error},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
@@ -254,6 +283,7 @@ class PeeringDBFacilityCollector(HTTPCollector):
|
||||
"User-Agent": "Planet-Intelligence-System/1.0 (Python/collector)",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
base = self._resolved_url or self.base_url
|
||||
@@ -275,7 +305,11 @@ class PeeringDBFacilityCollector(HTTPCollector):
|
||||
|
||||
if response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
@@ -286,13 +320,21 @@ class PeeringDBFacilityCollector(HTTPCollector):
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 429:
|
||||
delay = base_delay * (2**attempt)
|
||||
print(f"PeeringDB rate limited, waiting {delay}s before retry...")
|
||||
logger.warning_event(
|
||||
"PeeringDB rate limited; retrying after delay",
|
||||
event="collector.peeringdb.rate_limited",
|
||||
context={"delay_seconds": delay, "attempt": attempt + 1},
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
last_error = "Rate limited"
|
||||
continue
|
||||
raise
|
||||
|
||||
print(f"Warning: PeeringDB collection failed after {max_retries} retries: {last_error}")
|
||||
logger.warning_event(
|
||||
"PeeringDB collection failed after retries",
|
||||
event="collector.peeringdb.retries_exhausted",
|
||||
context={"max_retries": max_retries, "last_error": last_error},
|
||||
)
|
||||
return {}
|
||||
|
||||
async def fetch(self) -> List[Dict[str, Any]]:
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
"""Space-Track TLE Collector
|
||||
"""Space-Track TLE Collector.
|
||||
|
||||
Collects satellite TLE (Two-Line Element) data from Space-Track.org.
|
||||
API documentation: https://www.space-track.org/documentation
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Dict, Any, List
|
||||
import httpx
|
||||
from typing import Any, Dict, List
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from app.services.collectors.base import BaseCollector
|
||||
import httpx
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.logging import get_logger
|
||||
from app.core.satellite_tle import build_tle_lines_from_elements
|
||||
from app.services.collectors.base import BaseCollector
|
||||
|
||||
|
||||
logger = get_logger(__name__, service="collector")
|
||||
|
||||
|
||||
class SpaceTrackTLECollector(BaseCollector):
|
||||
@@ -53,10 +57,16 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
password = settings.SPACETRACK_PASSWORD
|
||||
|
||||
if not username or not password:
|
||||
print("SPACETRACK: No credentials configured, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track credentials are not configured; using sample data",
|
||||
event="collector.spacetrack.credentials_missing",
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
print(f"SPACETRACK: Attempting to fetch TLE data with username: {username}")
|
||||
logger.info_event(
|
||||
"Space-Track TLE fetch started",
|
||||
event="collector.spacetrack.fetch.start",
|
||||
)
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
@@ -78,11 +88,17 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
print(f"SPACETRACK: Login response status: {login_response.status_code}")
|
||||
print(f"SPACETRACK: Login response URL: {login_response.url}")
|
||||
logger.info_event(
|
||||
"Space-Track login response received",
|
||||
event="collector.spacetrack.login.response",
|
||||
context={"status_code": login_response.status_code},
|
||||
)
|
||||
|
||||
if login_response.status_code == 403:
|
||||
print("SPACETRACK: Trying alternate login method...")
|
||||
logger.warning_event(
|
||||
"Space-Track login returned forbidden; trying alternate method",
|
||||
event="collector.spacetrack.login.forbidden",
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=120.0,
|
||||
@@ -90,11 +106,6 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
) as alt_client:
|
||||
await alt_client.get(f"{self.site_root}/")
|
||||
|
||||
form_data = {
|
||||
"username": username,
|
||||
"password": password,
|
||||
"query": "class/gp/NORAD_CAT_ID/25544/format/json",
|
||||
}
|
||||
alt_login = await alt_client.post(
|
||||
self.login_url,
|
||||
data={
|
||||
@@ -102,77 +113,59 @@ class SpaceTrackTLECollector(BaseCollector):
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
print(f"SPACETRACK: Alt login status: {alt_login.status_code}")
|
||||
logger.info_event(
|
||||
"Space-Track alternate login response received",
|
||||
event="collector.spacetrack.alt_login.response",
|
||||
context={"status_code": alt_login.status_code},
|
||||
)
|
||||
|
||||
if alt_login.status_code == 200:
|
||||
tle_response = await alt_client.get(self.probe_url)
|
||||
if tle_response.status_code == 200:
|
||||
data = tle_response.json()
|
||||
print(f"SPACETRACK: Received {len(data)} records via alt method")
|
||||
logger.info_event(
|
||||
"Space-Track alternate query completed",
|
||||
event="collector.spacetrack.alt_query.completed",
|
||||
context={"record_count": len(data)},
|
||||
)
|
||||
return data
|
||||
|
||||
if login_response.status_code != 200:
|
||||
print(f"SPACETRACK: Login failed, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track login failed; using sample data",
|
||||
event="collector.spacetrack.login.failed",
|
||||
context={"status_code": login_response.status_code},
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
tle_response = await client.get(self.probe_url)
|
||||
print(f"SPACETRACK: TLE query status: {tle_response.status_code}")
|
||||
|
||||
if tle_response.status_code != 200:
|
||||
print(f"SPACETRACK: Query failed, using sample data")
|
||||
return self._get_sample_data()
|
||||
|
||||
data = tle_response.json()
|
||||
print(f"SPACETRACK: Received {len(data)} records")
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"SPACETRACK: Error - {e}, using sample data")
|
||||
return self._get_sample_data()
|
||||
|
||||
print(f"SPACETRACK: Attempting to fetch TLE data with username: {username}")
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=120.0,
|
||||
follow_redirects=True,
|
||||
headers={
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Accept": "application/json, text/html, */*",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
},
|
||||
) as client:
|
||||
# First, visit the main page to get any cookies
|
||||
await client.get(f"{self.site_root}/")
|
||||
|
||||
# Login to get session cookie
|
||||
login_response = await client.post(
|
||||
self.login_url,
|
||||
data={
|
||||
"identity": username,
|
||||
"password": password,
|
||||
},
|
||||
logger.info_event(
|
||||
"Space-Track TLE query response received",
|
||||
event="collector.spacetrack.query.response",
|
||||
context={"status_code": tle_response.status_code},
|
||||
)
|
||||
print(f"SPACETRACK: Login response status: {login_response.status_code}")
|
||||
print(f"SPACETRACK: Login response URL: {login_response.url}")
|
||||
print(f"SPACETRACK: Login response body: {login_response.text[:500]}")
|
||||
|
||||
if login_response.status_code != 200:
|
||||
print(f"SPACETRACK: Login failed, using sample data")
|
||||
return self._get_sample_data()
|
||||
|
||||
# Query for TLE data (get first 1000 satellites)
|
||||
tle_response = await client.get(self.query_url)
|
||||
print(f"SPACETRACK: TLE query status: {tle_response.status_code}")
|
||||
|
||||
if tle_response.status_code != 200:
|
||||
print(f"SPACETRACK: Query failed, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track TLE query failed; using sample data",
|
||||
event="collector.spacetrack.query.failed",
|
||||
context={"status_code": tle_response.status_code},
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
data = tle_response.json()
|
||||
print(f"SPACETRACK: Received {len(data)} records")
|
||||
logger.info_event(
|
||||
"Space-Track TLE fetch completed",
|
||||
event="collector.spacetrack.fetch.completed",
|
||||
context={"record_count": len(data)},
|
||||
)
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"SPACETRACK: Error - {e}, using sample data")
|
||||
logger.warning_event(
|
||||
"Space-Track TLE fetch failed; using sample data",
|
||||
event="collector.spacetrack.fetch.failed",
|
||||
context={"error": str(e)},
|
||||
)
|
||||
return self._get_sample_data()
|
||||
|
||||
def transform(self, raw_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
|
||||
@@ -45,7 +45,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
|
||||
DocsMetadata("earth-bgp-context.md", "earth-bgp-context", "docs_developer", "Earth", 14, "BGP 态势上下文", "BGP Context"),
|
||||
DocsMetadata("earth-interactable-usage.md", "earth-interactable-usage", "docs_developer", "Earth", 16, "智能星球可交互图标接入", "Intelligent Planet Interactable Usage"),
|
||||
DocsMetadata("earth-interactable-clustering.md", "earth-interactable-clustering", "docs_developer", "Earth", 17, "智能星球可交互图标聚类策略", "Intelligent Planet Interactable Clustering"),
|
||||
DocsMetadata("earth-toolbar-overlay-coordination.md", "earth-toolbar-overlay-coordination", "docs_developer", "Earth", 17, "智能星球工具栏与浮层协同", "Intelligent Planet Toolbar and Overlay Coordination"),
|
||||
DocsMetadata("earth-toolbar-overlay-coordination.md", "earth-toolbar-overlay-coordination", "docs_developer", "Earth", 18, "智能星球工具栏与浮层协同", "Intelligent Planet Toolbar and Overlay Coordination"),
|
||||
DocsMetadata("earth-news-sources.md", "earth-news-sources", "docs_developer", "Earth", 19, "智能星球新闻源配置", "Intelligent Planet News Source Configuration"),
|
||||
DocsMetadata("frontend-admin-frontend-context.md", "frontend-admin-frontend-context", "docs_developer", "Frontend", 20, "控制台前端结构", "Admin Frontend Context"),
|
||||
DocsMetadata("frontend-layout-guidelines.md", "frontend-layout-guidelines", "docs_developer", "Frontend", 21, "前端布局指南", "Frontend Layout Guidelines"),
|
||||
@@ -56,7 +56,7 @@ DOCS_METADATA: tuple[DocsMetadata, ...] = (
|
||||
DocsMetadata("backend-datasources-api-performance.md", "backend-datasources-api-performance", "docs_developer", "Backend", 33, "数据源 API 性能", "Datasource API Performance"),
|
||||
DocsMetadata("data-job-earth-sync-architecture.md", "data-job-earth-sync-architecture", "docs_developer", "Backend", 34, "数据作业与 Outbox 技术架构", "Data Jobs and Outbox Architecture"),
|
||||
DocsMetadata("backend-enum-contracts.md", "backend-enum-contracts", "docs_developer", "Backend", 35, "后端枚举与字符串兼容契约", "Backend Enum and String Compatibility Contract"),
|
||||
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 36, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
|
||||
DocsMetadata("location-pipeline-development.md", "location-pipeline-development", "docs_developer", "Backend", 35, "通用位置估算管线开发说明", "Shared Location Resolution Pipeline Development Guide"),
|
||||
DocsMetadata("earth-news-live-streams-collector-format.md", "earth-news-live-streams-collector-format", "docs_developer", "Backend", 36, "新闻直播采集格式", "News Live Streams Collector Format"),
|
||||
DocsMetadata("docs-gatekeeper-development.md", "docs-gatekeeper-development", "docs_developer", "Backend", 37, "Docs Gatekeeper 开发说明", "Docs Gatekeeper Development Guide"),
|
||||
DocsMetadata("agents-aiprovider.md", "agents-aiprovider", "docs_developer", "Agents", 40, "AI Provider 指南", "AI Provider Guide"),
|
||||
|
||||
@@ -865,9 +865,9 @@ def _get_locale_text(
|
||||
if isinstance(fallback, dict):
|
||||
value = _coerce_str(fallback.get(key))
|
||||
if value:
|
||||
if locale == "en-US" and _contains_cjk_text(value):
|
||||
return ""
|
||||
return value
|
||||
if locale == "en-US" and _is_chinese_language(item.content_language):
|
||||
return item.title if key == "title" else item.summary
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
@@ -384,7 +384,14 @@ def test_parse_chinese_rss_marks_source_language_and_keeps_zh_localization():
|
||||
assert items[0].content_language == "zh-CN"
|
||||
assert items[0].localizations["zh-CN"]["title"] == "中国电商平台发布季度增长数据"
|
||||
assert payload_zh["display_title"] == "中国电商平台发布季度增长数据"
|
||||
assert payload_en["display_title"] == "中国电商平台发布季度增长数据"
|
||||
assert payload_en["display_title"] == ""
|
||||
|
||||
items[0].localizations["en-US"] = {
|
||||
"title": "Chinese e-commerce platform reports quarterly growth",
|
||||
"summary": "The platform said cross-border orders rose year over year.",
|
||||
}
|
||||
payload_en_ready = _serialize_item(items[0], active_region="global", locale="en-US")
|
||||
assert payload_en_ready["display_title"] == "Chinese e-commerce platform reports quarterly growth"
|
||||
|
||||
|
||||
def test_default_news_sources_include_business_and_ecommerce_sources():
|
||||
|
||||
@@ -8,6 +8,93 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [0.74.2] — 2026-07-01
|
||||
|
||||
Released: 2026-07-01
|
||||
|
||||
### Highlights
|
||||
- 收敛 agent harness 到 `rules.md`、`AGENTS.md`、`docs/HARNESS.md` 和 `.codex/skills/`,删除重复维护的旧 Claude command 入口。
|
||||
- 强化视觉证据规则:截图或视觉引用路径打不开时必须先处理 WSL/Windows 路径、相对路径和附件位置,而不是跳过后猜测。
|
||||
- 明确 OCR 可作为文本类视觉证据或非多模态环境 fallback,同时要求布局、颜色、像素和渲染类问题保留真实视觉验证或明确限制说明。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- `AGENTS.md` 替换旧 opencode/默认 Plan Mode 内容,保留最新单一入口和 harness 验证说明。
|
||||
- `rules.md` 与 `docs/HARNESS.md` 同步 Visual Evidence Gate,补齐路径解析、访问失败报告和 OCR fallback 边界。
|
||||
- 删除 `.claude/commands/*` 中与 `.codex/skills/*` 重复的旧 cleanup/docs/goal-driven/release 入口,并更新文档受众计划中的旧路径引用。
|
||||
|
||||
---
|
||||
|
||||
## [0.74.1] — 2026-06-30
|
||||
|
||||
Released: 2026-06-30
|
||||
|
||||
### Highlights
|
||||
- 将 `/earth-content` 的品牌标识上传收敛到 `Logo 地址` 与 `标题图地址` 字段内,移除旧的全局“选择资产/上传”工具栏。
|
||||
- 新增字段级图片拖拽反馈,拖到对应字段时直接提示将图片复制为 Logo 或标题图。
|
||||
- 对齐品牌上传按钮到现有 Tactile UI primary 按钮样式,并同步中英文使用手册、快速开始和控制台上下文文档。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- `BrandAssetInput` 支持字段内选择文件、拖拽上传、单字段 loading 和上传后回写草稿 URL。
|
||||
- `FieldGrid` 支持按字段注入自定义输入控件,同时复用统一草稿提交路径。
|
||||
- 品牌上传拖拽态改为低饱和 tactile 配色,上传按钮保持蓝色轻立体样式,容器内上下/右侧留白对齐为 3px。
|
||||
- 补齐品牌上传相关 legacy UI 英文翻译、术语对照和用户文档。
|
||||
|
||||
---
|
||||
|
||||
## [0.74.0] — 2026-06-30
|
||||
|
||||
Released: 2026-06-30
|
||||
|
||||
### Highlights
|
||||
- 扩展统一 i18n 到 Web Earth、控制台、认证页和公开 Docs 的更多动态入口,减少英文界面中文残留。
|
||||
- 强化 Earth HUD 的通知胶囊、品牌栏、语言 switch、图例、tooltip、详情卡、新闻和 TV 文案展示,避免英文态裁切或错位。
|
||||
- 将容易遗漏的 i18n 入口和视觉回归加入 harness,让 smoke 覆盖通知位置、内容宽度、语言切换状态和动态文案。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 Earth runtime i18n 入口,统一高清材质、启动状态、错误提示和图层状态文案来源。
|
||||
- 补齐国家名、属性名、卫星 legend、详情页 tooltip、新闻/TV 默认文案和 API 错误提示的英文翻译与回退。
|
||||
- 更新控制台与 Earth 布局规则,保留 brand 尺寸语义,同时让标题、副标题和通知胶囊按内容完整显示。
|
||||
- 扩展 frontend smoke 与 harness 文档,固化一屏高度链、i18n 动态入口、胶囊/tag overflow 和截图证据要求。
|
||||
- 更新 Earth 新闻本地化服务与测试,确保英文界面新闻内容不再回退中文 UI 文案。
|
||||
|
||||
---
|
||||
|
||||
## [0.73.0] — 2026-06-29
|
||||
|
||||
Released: 2026-06-29
|
||||
|
||||
### Highlights
|
||||
- 新增前端统一 i18n 基础设施,让认证页、Docs UI、控制台外壳、导航、搜索和核心共享组件共用 `zh-CN` / `en-US` 语言状态。
|
||||
- 控制台侧边栏偏好面板接入语言与主题切换,并修复一屏高度链、账号区、状态指示器和英文态文案裁切问题。
|
||||
- 扩展 harness 与 smoke 覆盖,确保 admin shell 高度、移动/缩放布局、语言切换、搜索、Docs 和核心控制台交互在发布前被验证。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 `frontend/src/i18n/`,用 `i18next` / `react-i18next` 维护资源、locale 映射、Docs 兼容和过渡期 legacy UI 翻译桥。
|
||||
- 将 AdminLayout、route manifest、admin search、Auth、DataTable、Dialog、Toast、MarkdownRenderer 和 Users 页迁移到统一翻译资源。
|
||||
- 补齐 Planet Content、Collected Data、System Logs、Datasources、Settings 和 Collection Management 等英文态残留翻译,并覆盖动态计数字符串。
|
||||
- 改进控制台侧边栏账号区、语言 switch、状态 pill 自适应宽度和 admin shell overflow ownership,避免首屏溢出和状态词裁切。
|
||||
- 更新 i18n 计划、控制台前端上下文、harness 文档和规则,记录语言迁移边界、状态指示器布局约束和一屏验证要求。
|
||||
|
||||
---
|
||||
|
||||
## [0.72.0] — 2026-06-29
|
||||
|
||||
Released: 2026-06-29
|
||||
|
||||
### Highlights
|
||||
- 将 agent 入口收敛到单一 `AGENTS.md`,并让 harness 明确阻止小写入口再次分叉。
|
||||
- 新增完整本地 harness 验证层,覆盖 backend/frontend/docs/security 静态规则、前端 build 和 Playwright 路由/交互 smoke。
|
||||
- 扩展 Earth News 与控制台 smoke,确保新闻源测试、新增取消、手动新闻组创建、桌面/移动菜单和 zoom 布局都在发布前验证。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 `scripts/harness/*` 规则检查、doctor、validate 和前端 smoke 脚本,并将未跟踪 harness 设施纳入发布。
|
||||
- 清理 SpaceTrack 与 PeeringDB collector 的 stdout/debug 输出,改用结构化日志并移除 SpaceTrack 不可达重复 fetch 路径。
|
||||
- 强化控制台布局、auth 表单、Docs 页面、Earth shell 和 Earth toolbar 的响应式与无障碍细节。
|
||||
- 同步 README、CODEMAP、HARNESS、harness audit、用户手册、快速开始和开发者文档,明确当前 Web Earth / React admin / FastAPI / aiprovider 边界。
|
||||
- 将 backend、frontend、docs 和 Earth News 检查纳入 `scripts/harness/quick-check.sh` 与 `scripts/harness/validate.sh` 的稳定验证面。
|
||||
|
||||
---
|
||||
|
||||
## [0.71.1] — 2026-06-26
|
||||
|
||||
Released: 2026-06-26
|
||||
|
||||
153
docs/HARNESS.md
@@ -9,7 +9,7 @@ or release workflows.
|
||||
Existing project rules are authoritative:
|
||||
|
||||
1. `rules.md`
|
||||
2. `agents.md`
|
||||
2. `AGENTS.md`
|
||||
3. Current implementation docs under `docs/technical/`
|
||||
4. Existing scripts, especially `planet.sh`
|
||||
5. Existing Gitea workflow files under `.gitea/workflows/`
|
||||
@@ -18,6 +18,17 @@ When harness guidance conflicts with any of the above, keep the existing rule,
|
||||
do not overwrite the existing workflow, and add a compatibility note here or in
|
||||
`docs/harness-audit.md`.
|
||||
|
||||
For frontend or documentation audits, also read the Rules Coverage Evidence
|
||||
section in `docs/harness-audit.md`. It maps `rules.md` clauses to the current
|
||||
static checks, Playwright smoke coverage, and remaining manual review areas, so
|
||||
an agent can distinguish a proved harness pass from a rule that still needs
|
||||
human-quality inspection.
|
||||
|
||||
When the user describes work with product words rather than module names, use
|
||||
the `rules.md` **Agent Discovery Index** before deciding which modules to load.
|
||||
It maps Chinese phrases such as `一屏`, `高度没控住`, `文档`, `数据源`,
|
||||
`地球`, `模型供应商`, and `发版` to the required rule modules.
|
||||
|
||||
## Starting Work
|
||||
|
||||
Recommended startup flow:
|
||||
@@ -71,8 +82,12 @@ git diff --unified=0 HEAD -- <path>
|
||||
| Tier | Command | What It Does |
|
||||
| --- | --- | --- |
|
||||
| Doctor | `scripts/harness/doctor.sh` | Checks required files, required tools, optional delivery tools, and forbidden frontend lockfiles. |
|
||||
| Quick | `scripts/harness/quick-check.sh` | Runs doctor, whitespace diff check, shell syntax checks, and CI backend smoke tests. |
|
||||
| Full | `scripts/harness/validate.sh` | Runs quick check, frontend Bun install/build, optional Helm checks, and opt-in Docker image smoke builds. |
|
||||
| Security | `scripts/harness/security-check.sh` | Checks that environment/private-key files are not tracked and scans for high-confidence committed secret tokens. |
|
||||
| Backend Rules | `scripts/harness/backend-rules-check.sh` | Checks backend app Python for direct `print()`, `breakpoint()`, and `pdb.set_trace()` debug calls so service code uses structured logging. |
|
||||
| Frontend Rules | `scripts/harness/frontend-rules-check.sh` | Checks Bun-only scripts, admin route manifest coherence, literal internal route links, admin search route targets, frontend debug output, native button safety, icon-button accessibility, no nested Cards, no AntD/Space layout primitives, ConnectionTestInput usage, admin/docs shell height-chain sizing, same-category style owner warnings, viewport-scaled font sizes, zero letter spacing, and high-signal UI rule warnings. |
|
||||
| Docs Consistency | `scripts/harness/docs-consistency-check.sh` | Checks frontend Docs metadata against backend Gatekeeper metadata, public Docs registration, full technical-doc bilingual file pairs, public doc links, readable link titles, language-scoped technical links, README/project-context admin stack drift, supported credential collector contracts, manual console route coverage against the actual admin manifest, documented UI route drift, documented `?section=` deep-link validity against the actual admin section config in technical docs and active plan docs, and the harness rules-coverage notes. |
|
||||
| Quick | `scripts/harness/quick-check.sh` | Runs doctor, whitespace diff check, shell syntax checks, security scan, backend/frontend/doc consistency checks, and CI backend smoke tests. |
|
||||
| Full | `scripts/harness/validate.sh` | Runs quick check, frontend Bun install/build, Playwright route smoke, optional Helm checks, and opt-in Docker image smoke builds. |
|
||||
|
||||
Docker image smoke builds are expensive and are off by default:
|
||||
|
||||
@@ -80,6 +95,106 @@ Docker image smoke builds are expensive and are off by default:
|
||||
PLANET_HARNESS_DOCKER_SMOKE=1 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
Frontend Playwright smoke runs by default in full validation after the frontend
|
||||
build. It starts a local Vite preview and checks the `/` to Earth redirect,
|
||||
public pages, unknown-route login fallback, protected admin route login
|
||||
fallback, authenticated unknown-route fallback to `/admin`, Docs loading with
|
||||
mocked API content, Docs detail page
|
||||
language/theme/search interactions, every Docs catalog slug exposed by the
|
||||
frontend/backend metadata, the Earth iframe entry point, login error handling,
|
||||
register + email verification, password reset, standalone email verification,
|
||||
and authenticated `super_admin` rendering for every admin route plus core
|
||||
`section` deep links derived from the actual admin route and section config.
|
||||
Authenticated admin
|
||||
checks run at desktop size, mobile size, and 125% / 150% zoom; desktop and
|
||||
mobile passes also fail on global horizontal overflow so table/detail panels
|
||||
must keep overflow ownership inside their own scroll regions. To enforce the
|
||||
existing `rules.md` `uiux` one-screen workspace rule, admin shell pages have a
|
||||
hard rendered check: the shell must resolve to the viewport height through the
|
||||
root 100% height chain, `#root`/document/body must not gain vertical overflow,
|
||||
and the desktop sidebar account/preferences area must remain inside the first
|
||||
viewport while the nav owns any excess scrolling. The smoke also
|
||||
derives the sidebar menu from the actual admin route manifest and clicks every
|
||||
visible `super_admin` menu entry on both desktop and mobile viewports, then
|
||||
exercises safe interaction paths for admin search, section tabs, the AI settings
|
||||
shortcut, logs view switching, user dialog opening, and data distribution toggles.
|
||||
It also exercises Earth News source testing, add/cancel source draft behavior,
|
||||
and manual news group creation against mocked `/earth/news-*` APIs.
|
||||
Documented AI and collector
|
||||
deep links such as `/ai?section=integrations`, `/ai?section=playground`, and
|
||||
`/collection-management?section=collector_credentials` are part of the rendered
|
||||
smoke surface:
|
||||
|
||||
```bash
|
||||
PLANET_HARNESS_FRONTEND_SMOKE=0 scripts/harness/validate.sh
|
||||
PLANET_HARNESS_FRONTEND_SMOKE_PORT=4174 scripts/harness/validate.sh
|
||||
```
|
||||
|
||||
### Visual Evidence And Style Consistency
|
||||
|
||||
- Treat user-provided screenshots and images as primary visual evidence. If a
|
||||
screenshot contradicts written text, inspect the image first and explicitly
|
||||
call out the mismatch before deciding what to change.
|
||||
- Path resolution is part of visual evidence handling. If a referenced
|
||||
screenshot path cannot be opened, try reasonable local equivalents first:
|
||||
WSL/Windows path conversion, workspace-relative paths, absolute paths, current
|
||||
thread attachments, repository files, and obvious local attachment/download
|
||||
locations.
|
||||
- If the image still cannot be found or opened, report the exact path/access
|
||||
blocker instead of guessing. Do not infer image content from the filename, alt
|
||||
text, surrounding prose, logs, or memory.
|
||||
- OCR is acceptable evidence for text-only questions or non-multimodal
|
||||
environments; state when OCR was the fallback. Layout, color, spacing, pixel,
|
||||
and rendering issues still require a real visual inspection or an explicit
|
||||
"could not verify visually" note.
|
||||
- Same-category UI surfaces must use one visual system per product area. Badges,
|
||||
chips, pills, tags, status labels, small buttons, cards, panels, and toolbar
|
||||
controls should reuse the shared component, shared token, or established CSS
|
||||
owner for that area instead of introducing a page-local lookalike.
|
||||
- `scripts/harness/frontend-rules-check.sh` warns when semantic
|
||||
`badge` / `chip` / `pill` / `tag` / `status` selectors appear outside the
|
||||
approved React and Earth CSS owner files. A warning means the reviewer should
|
||||
either move the style into the shared owner or document why this is a genuinely
|
||||
new visual family.
|
||||
|
||||
### Earth I18n Harness Rules
|
||||
|
||||
Earth i18n work must validate rendered behavior, not only static text lookup.
|
||||
Agents often miss dynamic strings that are created after initial page load, so
|
||||
the smoke treats these as first-class i18n surfaces:
|
||||
|
||||
- **Visible text and attributes**: translated checks must include `innerText`
|
||||
plus `title`, `aria-label`, `placeholder`, and `alt`. Tooltips and icon-only
|
||||
buttons are user-facing copy, not implementation details.
|
||||
- **Dynamic detail cards**: info cards opened from Earth markers, cruise cards,
|
||||
BGP markers, compute centers, vessels, and news must render field labels,
|
||||
status values, source tags, action buttons, and disabled/tooltips in the active
|
||||
language.
|
||||
- **English content safety**: English mode must not fall back to Chinese news
|
||||
titles, summaries, feed names, measure words, or generic status labels. If no
|
||||
English localization exists, hide the item or use a neutral English fallback.
|
||||
- **Brand assets**: locale switching must update both text and image assets.
|
||||
The default Earth HUD brand uses `title-zh.png` for Chinese and `title-en.png`
|
||||
for English while keeping the same top-left layout and logo position.
|
||||
- **Controls and state**: switch/segmented-control visuals must follow the real
|
||||
checked/pressed state after both direct clicks and programmatic panel changes.
|
||||
A control is not valid if the state changes but the thumb, active pill, or
|
||||
`aria-*` state stays stale.
|
||||
- **Runtime copy entrypoints**: dynamic status, loading, startup, and error copy
|
||||
must enter through `earthMessage(...)` plus the centralized
|
||||
`EARTH_MESSAGE_TEMPLATES` map. Do not hide direct strings behind
|
||||
`showStatusMessage`, `queueStatusMessage`, `showGestureStatusMessage`,
|
||||
`showError`, `setLoadingMessage`, `resolveStartupMessage`, `startupMessage`,
|
||||
or `earth:status` events.
|
||||
- **Capsules and tags**: pills, tags, chips, badges, and small buttons must not
|
||||
overflow their panel. Prefer a slightly wider owning panel for important
|
||||
status information; otherwise use `min-width: 0`, wrapping, or ellipsis with a
|
||||
translated tooltip.
|
||||
|
||||
Current frontend smoke explicitly covers the Earth English locale flow: brand
|
||||
image swap, settings language controls, panel switch visual sync, English news
|
||||
filtering, English detail-card text and tooltips, and TV default/source labels.
|
||||
|
||||
## Environment Requirements
|
||||
|
||||
Required for normal development:
|
||||
@@ -89,6 +204,12 @@ Required for normal development:
|
||||
- `bun` for frontend dependency and build execution
|
||||
- Python resolved by `uv` from the root `pyproject.toml`
|
||||
|
||||
Harness command lookup first checks the current non-interactive `PATH`. If a
|
||||
required tool is not visible there, `scripts/harness/lib.sh` asks the user's
|
||||
login interactive shell (`$SHELL`, then `zsh`, then `bash`) for the command
|
||||
path. This avoids hardcoding a dotfile while still covering agent environments
|
||||
that do not inherit the user's normal shell setup.
|
||||
|
||||
Required for full local stack operation:
|
||||
|
||||
- Docker and Docker Compose
|
||||
@@ -121,6 +242,14 @@ No automatic hooks are installed in this phase. Manual reminders:
|
||||
|
||||
- Run `scripts/harness/quick-check.sh` before handing off small changes.
|
||||
- Run `scripts/harness/validate.sh` before larger cross-subsystem changes.
|
||||
- Run `scripts/harness/security-check.sh` after touching config, auth,
|
||||
credentials, docs examples, or generated fixtures.
|
||||
- Run `scripts/harness/backend-rules-check.sh` after backend service edits to
|
||||
catch direct stdout/debugger calls before they reach runtime logs.
|
||||
- Run `scripts/harness/frontend-rules-check.sh` after frontend edits to expose
|
||||
route, package-manager, debug-output, and UI rule warnings.
|
||||
- Run `scripts/harness/docs-consistency-check.sh` after docs edits or feature
|
||||
route changes.
|
||||
- Add focused tests before modifying backend service behavior or frontend
|
||||
workflows.
|
||||
- For docs changes, run the checks listed in
|
||||
@@ -136,6 +265,9 @@ No automatic hooks are installed in this phase. Manual reminders:
|
||||
4. Make the smallest behavior-preserving or feature-scoped change.
|
||||
5. Run `scripts/harness/quick-check.sh` or a narrower documented command.
|
||||
6. Update relevant docs when behavior, workflow, or operations change.
|
||||
7. For rendered frontend changes, verify the affected route with Playwright or
|
||||
the full harness smoke, because `bun run build` alone does not prove page
|
||||
usability.
|
||||
|
||||
### Bug Fix
|
||||
|
||||
@@ -149,7 +281,8 @@ No automatic hooks are installed in this phase. Manual reminders:
|
||||
|
||||
1. Read `docs/documentation-coverage-rules.md`.
|
||||
2. Route docs by audience: UI users, operations, or second-party developers.
|
||||
3. Keep Chinese and English public docs consistent when a public doc pair exists.
|
||||
3. Keep Chinese and English technical docs paired by filename; public Docs also
|
||||
need matching frontend/backend metadata when exposed in the product Docs UI.
|
||||
4. Run the repository-specific docs checks that match the changed files.
|
||||
|
||||
### Release Or Delivery Change
|
||||
@@ -161,7 +294,15 @@ release process.
|
||||
## Implementation Notes
|
||||
|
||||
- `docs/harness-audit.md` records the discovery pass that led to this harness.
|
||||
- `AGENTS.md` is a compatibility entry point for tools that expect the uppercase
|
||||
filename. The existing `agents.md` file remains in place.
|
||||
- `AGENTS.md` is the single authoritative agent guide. The older lowercase
|
||||
`agents.md` entry has been merged into it and should remain absent.
|
||||
- `CODEMAP.md` is intentionally high level; deeper subsystem docs stay in
|
||||
`docs/technical/{zh,en}/`.
|
||||
- `scripts/harness/frontend-smoke.mjs` is a lightweight route/section smoke
|
||||
with mocked API data. It proves route shells, auth guards, and primary admin
|
||||
sections render, but it is not a replacement for feature-specific browser QA
|
||||
against a real backend.
|
||||
- Frontend smoke prints phase-level progress by default. Use
|
||||
`PLANET_FRONTEND_SMOKE_PROGRESS=verbose` to print each route/menu/doc item
|
||||
when diagnosing a slow or failing smoke run, or set it to `0` to suppress
|
||||
progress lines.
|
||||
|
||||
@@ -25,12 +25,11 @@ compatibility note, not a replacement for existing rules or architecture docs.
|
||||
|
||||
| File | Status | Notes |
|
||||
| --- | --- | --- |
|
||||
| `agents.md` | Present | Existing root agent behavior guide. It references `rules.md` and `project_context.md`. |
|
||||
| `AGENTS.md` | Present | Single authoritative agent behavior guide. It references `rules.md`, `project_context.md`, harness validation, and high-risk areas. |
|
||||
| `rules.md` | Present | Mandatory modular rules. Always load `core`, `security`, and `workflow`; load topic modules as needed. |
|
||||
| `project_context.md` | Present | Static context. Some roadmap-era stack details are older than the current README/docs. |
|
||||
| `.claude/commands/*.md` | Present | Existing command docs for cleanup, docs, goal-driven, and release workflows. |
|
||||
| `.codex/skills/*.md` | Present | Existing local skills for cleanup, docs, goal-driven, and release. |
|
||||
| `AGENTS.md` | Added by harness | Compatibility entry point that points to existing rules and harness docs. |
|
||||
|
||||
## Existing CI Gates
|
||||
|
||||
@@ -69,13 +68,12 @@ The repository uses `.gitea/workflows/`, not `.github/workflows/`.
|
||||
|
||||
## Missing Or Unclear Areas
|
||||
|
||||
- README previously listed `AGENTS.md` in the project tree while only lowercase
|
||||
`agents.md` existed. The harness adds uppercase `AGENTS.md` as a compatibility
|
||||
wrapper and preserves `agents.md`.
|
||||
- `project_context.md` includes older roadmap assumptions such as Celery, Kafka,
|
||||
TimescaleDB, MinIO, and UE5 as active stack elements. The current README and
|
||||
technical docs describe Web Earth, React admin, FastAPI, PostgreSQL/Redis, and
|
||||
`aiprovider` as the active local development shape.
|
||||
- The older lowercase `agents.md` entry has been merged into uppercase
|
||||
`AGENTS.md` so coding agents and harness tools use one source of truth.
|
||||
- `project_context.md` originally included older roadmap assumptions such as
|
||||
Celery, Kafka, TimescaleDB, MinIO, and UE5 as active stack elements. The
|
||||
harness pass updated it to separate active stack facts from future directions;
|
||||
current code and technical docs still remain authoritative when details drift.
|
||||
- No safe automatic hook system was already configured. This phase documents
|
||||
manual reminders instead of adding hooks.
|
||||
- `.github/workflows/` is absent by design; CI is under `.gitea/workflows/`.
|
||||
@@ -84,19 +82,80 @@ The repository uses `.gitea/workflows/`, not `.github/workflows/`.
|
||||
|
||||
| Conflict Or Tension | Resolution |
|
||||
| --- | --- |
|
||||
| Prompt suggested `AGENTS.md`; repository already had `agents.md`. | Added a minimal uppercase compatibility entry and preserved the existing lowercase guide. |
|
||||
| Prompt suggested `AGENTS.md`; repository already had `agents.md`. | Merged the lowercase guide into uppercase `AGENTS.md`; harness doctor now requires `AGENTS.md` and keeps `agents.md` absent to prevent split authority. |
|
||||
| Harness validation could duplicate CI. | Added wrapper scripts that call existing commands and mirror current CI gates where practical. |
|
||||
| Full Docker smoke builds are expensive locally. | Kept them opt-in with `PLANET_HARNESS_DOCKER_SMOKE=1`. |
|
||||
| Internal harness docs could clutter public Docs UI. | Kept `docs/HARNESS.md` and `docs/harness-audit.md` as repository docs, not product Docs entries. |
|
||||
| Existing frontend toolchain is Bun-only. | Harness scripts and docs use Bun only and flag npm/pnpm/yarn lockfiles as failures. |
|
||||
| Agents often miss user-installed Bun or uv in non-interactive shells. | Added `scripts/harness/lib.sh` to resolve tools from current `PATH` first and then the user's login interactive shell without hardcoding a dotfile. |
|
||||
| Always-loaded security rules had no standalone harness gate. | Added `scripts/harness/security-check.sh` to block tracked `.env` / key files and scan for high-confidence committed private keys or provider tokens; quick-check now runs it. |
|
||||
| Build success does not prove frontend page usability. | Added static frontend rules/doc checks and a Playwright route smoke for public pages, protected admin fallback, Docs loading and detail interactions, Earth iframe entry, login/register/verification/password-reset interactions, authenticated admin route/section rendering with mocked API data across desktop, mobile, and 125% / 150% zoom, plus manifest-derived desktop/mobile menu navigation and safe search/tab/dialog/Earth News interactions. |
|
||||
| Route fallback behavior can regress even when every named page renders. | Extended the frontend smoke to verify `/` redirects to Earth, unauthenticated unknown routes show the login page, and authenticated unknown routes navigate back to `/admin`. |
|
||||
| Frontend smoke route lists can drift from `AdminRoutes` and resource-page sections. | Updated the smoke to derive protected route checks and authenticated section deep-link checks from `AdminRoutes.tsx` and `PlainResourcePages.tsx`, including redirect-only `/alerts`. |
|
||||
| Docs smoke mocks can drift from the product Docs catalog. | Updated the frontend smoke to derive mocked Docs catalog/content from `frontend/src/pages/Docs/docs-content.ts` plus backend Gatekeeper access metadata, then open every Chinese Docs catalog slug. |
|
||||
| User manuals can miss a real console menu entry after route changes. | Added a docs consistency check that compares the manual console overview tables with `frontend/src/admin/routes/manifest.tsx`; fixed the missing `/docs` row in both user manuals. |
|
||||
| Rendered pages can still contain broken internal shortcuts. | Added literal internal route-link checks and an interaction smoke for the AI settings shortcut; this caught and fixed a stale `/admin/settings` link that should point to `/settings`. |
|
||||
| Global search entries can drift because their route targets live in data objects rather than JSX links. | Added a frontend rules check that validates every admin search `routePath` against the actual frontend route set. |
|
||||
| Responsive styling fixes can satisfy one viewport by breaking the no-viewport-font rule. | Added a frontend rules failure for `font-size` values that use viewport or container query width units, and replaced public auth shell `vw` font sizing with fixed desktop/mobile sizes. |
|
||||
| Typography polish can accidentally reintroduce squeezed non-zero letter spacing. | Normalized active frontend `letter-spacing` values to `0` and made the frontend rules check fail non-zero `letter-spacing` / `letterSpacing` declarations, with only inherit/default-zero forms allowed. |
|
||||
| Native buttons can accidentally submit forms or keep controls clickable while loading after a props-spread reorder. | Added a frontend rules failure for TSX `<button>` elements without explicit `type` and for buttons whose `disabled` state can be overridden by a later props spread; fixed the data distribution buttons and auth button disabled ordering. |
|
||||
| Admin/docs shell layouts can reintroduce brittle viewport sizing after a responsive fix. | Changed the admin and Docs route shells to use the existing `html/body/#root` 100% height chain, and added a frontend rules failure for exact `100vh` / `100vw` shell sizing in those CSS files. |
|
||||
| Compact workspaces can drift back into card-in-card layouts or implicit AntD `Space` wrappers. | Added frontend rules failures for nested `Card` components, AntD imports, and `<Space>` layout primitives in active frontend source. |
|
||||
| Connection-test controls can drift back into detached toolbar buttons. | Added a shared `ConnectionTestInput` suffix pattern for AI Provider and WebSearch Base URL fields, disabled WebSearch configuration/test controls when the tool is off, and made the frontend rules check fail detached AI/WebSearch connection-test buttons. |
|
||||
| Same-category UI styles can fragment into page-local lookalikes. | Added same-category style owner warnings for semantic `badge`, `chip`, `pill`, `tag`, and `status` CSS selectors outside the approved shared React and Earth CSS owner files. |
|
||||
| Visual fixes can go wrong when agents guess from missing screenshot paths. | Documented screenshots and images as primary visual evidence: if the path is not available, agents must search alternate attachment/local locations or report the blocker instead of inferring image content. |
|
||||
| Public docs can reference stale admin section URLs. | Added docs consistency validation for documented `?section=` links and rendered smoke coverage for documented AI / collector deep links. |
|
||||
| Active plan docs can preserve old admin deep-link assumptions after the technical docs are corrected. | Extended docs consistency checks to active `docs/plans/*.md` files for stale admin tab-query terms and actual `?section=` validity; corrected the docs audience split plan to current section routes. |
|
||||
| Top-level README can drift from the actual frontend stack while technical docs stay current. | Updated README from Ant Design Pro to Tactile UI / Radix primitives / lucide-react and added README stale admin-stack terms to docs consistency checks. |
|
||||
| Agent background context can reintroduce inactive stack assumptions. | Updated `project_context.md` and the root agent guide to label current stack facts versus future directions, then added exact stale-stack patterns for them to docs consistency checks. |
|
||||
| Docs `?section=` validation can drift if the harness owns its own route/section table. | Changed the docs consistency check to derive section keys from `AdminRoutes.tsx` and `PlainResourcePages.tsx` resource configs before validating documented deep links. |
|
||||
| Public Docs can drift between frontend catalog metadata and backend Gatekeeper authorization metadata. | Added a docs consistency check that compares filename, slug, group, order, and bilingual titles across both metadata sources; aligned existing order drift for toolbar overlay and location pipeline docs. |
|
||||
| Non-public technical docs can silently become Chinese-only or English-only. | Added a full `docs/technical/{zh,en}` filename-pair check so every technical Markdown file has a same-named counterpart before docs consistency passes. |
|
||||
| Credentialed collector docs can drift from backend support wiring. | Added docs consistency validation for every built-in collector marked `requires_credentials=true` and `credential_status=supported`: it must have a provider, default credential guide, supported connectivity provider, frontend credential UI/guidance, a regression test, and zh/en connectivity documentation. |
|
||||
| Backend collectors can leak debug output or credential-adjacent context through stdout. | Replaced SpaceTrack and PeeringDB collector `print()` calls with structured logger events, removed unreachable duplicate SpaceTrack fetch code, and added `scripts/harness/backend-rules-check.sh` to block future backend app `print()`, `breakpoint()`, or `pdb.set_trace()` calls. |
|
||||
|
||||
## Rules Coverage Evidence
|
||||
|
||||
This matrix records how the current harness checks the `rules.md` modules that
|
||||
matter for this frontend and documentation pass. "Automated" means the listed
|
||||
command fails when the rule regresses. "Smoke" means the rendered product route
|
||||
or interaction is opened with Playwright. "Manual" means the rule is still a
|
||||
judgment call and must be inspected during review.
|
||||
|
||||
Before using this matrix, start from `rules.md`'s **Agent Discovery Index** when
|
||||
the user describes work with Chinese/product terms instead of module names. The
|
||||
index is the routing layer; this table is the coverage/evidence layer.
|
||||
|
||||
| `rules.md` Area | Rule Surface | Harness Evidence | Remaining Review |
|
||||
| --- | --- | --- | --- |
|
||||
| `core` | Remove stale transitional paths, duplicated helpers, and naming drift after large changes. | `scripts/harness/docs-consistency-check.sh` blocks known stale stack terms, old `?tab=` links, public Docs metadata drift, and README/project context drift. `scripts/harness/frontend-rules-check.sh` blocks repeated detached AI/WebSearch connection-test buttons by requiring `ConnectionTestInput`. | Naming quality, function size, and whether a new abstraction is worth keeping remain manual review items. |
|
||||
| `core` | Keep one source of truth for route, Docs, and section state. | Frontend route, admin manifest, admin search targets, Docs catalog metadata, backend Gatekeeper metadata, manual route tables, and documented `?section=` links are all parsed from source and compared by `frontend-rules-check.sh`, `docs-consistency-check.sh`, and `frontend-smoke.mjs`. | Business-state ownership inside feature components still needs focused review when behavior changes. |
|
||||
| `security` | Do not commit secrets, tracked env files, private keys, or exposed tokens. | `scripts/harness/security-check.sh` fails on tracked `.env` / private-key files and high-confidence provider tokens. `backend-rules-check.sh` blocks backend stdout/debugger calls, and `frontend-rules-check.sh` fails frontend console output that includes token material. | Whether a newly added setting should be masked or stored server-side still requires feature-specific review. |
|
||||
| `workflow` | Frontend package management must stay Bun-only. | `scripts/harness/doctor.sh` and `frontend-rules-check.sh` fail forbidden frontend lockfiles and `npm` / `pnpm` / `yarn` script usage. `validate.sh` uses Bun for install, build, preview, and smoke. | New dependency legitimacy and maintenance quality are manual unless a dependency is actually added. |
|
||||
| `workflow` | Agents should find `bun` and `uv` even when non-interactive `PATH` is incomplete. | `scripts/harness/lib.sh` checks the current `PATH`, then asks `$SHELL`, `zsh`, and `bash` login interactive shells for the command path without hardcoding a dotfile. `doctor.sh`, `quick-check.sh`, and `validate.sh` all source it. | System package installation remains outside harness scope and should be reported instead of auto-fixed. |
|
||||
| `docs` | Keep public Docs whitelist-driven and synchronized with backend authorization metadata. | `docs-consistency-check.sh` compares frontend Docs metadata against backend Gatekeeper metadata, verifies files exist for both languages, checks public link titles, and blocks missing zh/en technical doc pairs. `frontend-smoke.mjs` opens every Chinese Docs catalog slug plus detail/search/language/theme interactions. | Quality of prose, examples, and whether a doc should be public are still editorial review items. |
|
||||
| `docs` | User manuals must match real console routes and deep links. | `docs-consistency-check.sh` compares manual console tables with `frontend/src/admin/routes/manifest.tsx` and validates documented `?section=` links from actual `AdminRoutes.tsx` plus `PlainResourcePages.tsx` section config. | Screenshots and UI-copy nuance are not exhaustively validated. |
|
||||
| `uiux` | Admin pages are compact single-screen workspaces with explicit overflow ownership. | `frontend-rules-check.sh` fails missing admin shell height-chain declarations (`.admin-theme-root`, `.admin`, `.admin__sider`, `.admin__nav-scroll`, `.admin__account`, `.admin__content`, `.admin__content-inner`), warns on suspicious `overflow: hidden`, and blocks exact `100vh` / `100vw` shell sizing in admin/Docs CSS. `frontend-smoke.mjs` checks every admin route at desktop/mobile and verifies `.admin` equals viewport height, `#root`/document/body have no vertical overflow, and desktop sidebar account/preferences stay in the first viewport. Zoom passes still cover 125% / 150% rendering. | Visual density, hierarchy, and whether a scroll owner feels ergonomic remain manual QA. |
|
||||
| `uiux` | Controls use expected patterns and accessible icon buttons. | `frontend-rules-check.sh` blocks icon `Button` without `aria-label` and `title`, native `<button>` without explicit `type`, nested Cards, AntD imports, `<Space>`, and detached connection-test buttons. Smoke exercises search, tabs, dialogs, data toggles, and connection-test actions. | Native buttons with visible text are not treated as icon-only by static checks; semantics still need review when adding custom controls. |
|
||||
| `uiux` | Same-category visual surfaces should use one style system per product area. | `frontend-rules-check.sh` warns when semantic `badge`, `chip`, `pill`, `tag`, or `status` selectors appear outside approved shared React and Earth CSS owner files. `docs/HARNESS.md` also makes screenshots/images primary evidence for visual fixes and forbids guessing when an image path is unavailable. | Final visual cohesion across screenshots still needs human/Playwright review, especially for page-specific cards, panels, and toolbar controls that static selector checks cannot classify perfectly. |
|
||||
| `uiux` | Text should fit, avoid viewport-scaled font sizes, and keep letter spacing at zero. | `frontend-rules-check.sh` fails viewport/container-width font-size units and non-zero `letter-spacing` / `letterSpacing`. `frontend-smoke.mjs` checks rendered routes for global overflow across desktop/mobile. | Per-element text clipping without page-level overflow is not exhaustively detected and needs visual review for changed screens. |
|
||||
| `frontend` | Keep shared behavior in reusable components and existing project patterns. | `frontend-rules-check.sh` enforces shared `ConnectionTestInput`, route/link/search consistency, no debug output, native button safety, Tactile/Radix/lucide direction instead of AntD/Space, and whitelist-driven public Docs. `bun x tsc --noEmit` and `bun run build` verify TypeScript/build health. | Broad casts, inline styles, and overflow issues are warnings when context may be legitimate; review changed lines before accepting them. |
|
||||
| `frontend` | Responsive adaptations must preserve the primary action path. | `frontend-smoke.mjs` clicks every visible admin menu entry on desktop and mobile, opens protected routes unauthenticated and authenticated, verifies root/unknown route fallback, and exercises core auth flows. | Deep feature workflows beyond smoke data, such as destructive or long-running actions, require targeted tests before behavior changes. |
|
||||
| `earth` | Earth render work needs real rendering checks. | Full smoke opens `/earth` and verifies the `3D Earth` iframe entry point. Earth News settings routes are included through the admin manifest/menu smoke, mocked `/earth/news-*` API responses, source test, add/cancel source draft, and manual news group creation checks. The broader Earth-specific layer/depth rules remain in `rules.md` and Earth docs. | The harness still does not claim full 3D layer visual verification; layer-depth and picking changes need targeted browser/canvas QA. |
|
||||
|
||||
## Harness Files Added
|
||||
|
||||
| File | Purpose |
|
||||
| --- | --- |
|
||||
| `AGENTS.md` | Compatibility agent entry point. |
|
||||
| `AGENTS.md` | Single authoritative agent guide and coding-agent entry point. |
|
||||
| `docs/HARNESS.md` | Harness workflow, validation tiers, conflict policy, and manual reminders. |
|
||||
| `CODEMAP.md` | High-level codebase map and validation references. |
|
||||
| `scripts/harness/lib.sh` | Shared command lookup and run helpers. |
|
||||
| `scripts/harness/doctor.sh` | Environment and repository-shape check. |
|
||||
| `scripts/harness/security-check.sh` | High-confidence secret and tracked environment/key file check. |
|
||||
| `scripts/harness/backend-rules-check.sh` | Backend app debug-call guard for direct stdout/debugger usage. |
|
||||
| `scripts/harness/frontend-rules-check.sh` | Bun-only, route manifest, literal internal link, admin-search route target, debug-output, native-button safety, icon-button accessibility, Card nesting, AntD/Space avoidance, ConnectionTestInput, admin shell one-screen height-chain declarations, admin/docs shell viewport sizing, same-category style owner warnings, viewport-font, zero-letter-spacing, and UI rules static check. |
|
||||
| `scripts/harness/docs-consistency-check.sh` | Frontend/backend Docs metadata alignment, public Docs metadata, full technical-doc bilingual pair, link-title, language-scoped technical link, supported credential collector contracts, manual console route coverage, documented route, admin-config-derived section deep-link consistency, and harness rules-coverage note check. |
|
||||
| `scripts/harness/frontend-smoke.mjs` | Playwright route, Docs detail/language/theme/search interaction, public auth form interaction, desktop/mobile/zoom rendering, admin shell one-screen/overflow checks, safe admin navigation/search/tab/dialog/Earth News interactions, and authenticated admin route/section smoke for the built frontend preview. |
|
||||
| `scripts/harness/quick-check.sh` | Fast deterministic local validation. |
|
||||
| `scripts/harness/validate.sh` | Full local validation wrapper with optional delivery smoke. |
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
当前重点入口:
|
||||
|
||||
- [控制台 i18n 接入计划](/home/ray/dev/linkong/planet/docs/plans/admin-console-i18n-plan.md)
|
||||
- [Earth Mobile Drawer UI Plan](/home/ray/dev/linkong/planet/docs/plans/earth-mobile-drawer-ui-plan.md)
|
||||
- [Earth Compute Center BGP Style Plan](/home/ray/dev/linkong/planet/docs/plans/earth-compute-center-bgp-style-plan.md)
|
||||
- [Earth Renderer Architecture Separation Plan](/home/ray/dev/linkong/planet/docs/plans/earth-renderer-architecture-separation-plan.md)
|
||||
|
||||
62
docs/plans/admin-console-i18n-plan.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# 控制台 i18n 接入计划
|
||||
|
||||
**状态**:基础设施已落地,大型业务页迁移继续进行
|
||||
**创建日期**:2026-06-29
|
||||
**核心目标**:把 Docs 已有的中英文文档能力提升为前端统一 i18n 体系,让未登录认证页、Docs UI、控制台外壳、导航、搜索和核心工作台文案共用同一个语言状态。
|
||||
|
||||
## 背景
|
||||
|
||||
Docs 站点已经有 `zh` / `en` 文档目录、Gatekeeper 权限和 `/api/v1/docs/{lang}/{slug}` 内容接口,但语言状态只保存在 `docs-lang`,不影响控制台。控制台页面、搜索索引、toast、dialog、表格和认证页仍以中文硬编码为主,导致用户切到英文文档后,控制台仍是中文。
|
||||
|
||||
本计划把前端语言偏好收敛到 `planet-locale`,默认 `zh-CN`,支持 `en-US`。Docs 继续使用后端现有 `zh` / `en` 文档接口,通过前端映射与全局 locale 对齐。
|
||||
|
||||
## 设计决策
|
||||
|
||||
- 使用 `i18next` 和 `react-i18next` 作为统一 i18n 层,避免长期维护自研插值、hook 和资源加载逻辑。
|
||||
- 前端统一语言枚举为 `zh-CN` / `en-US`;Docs 请求继续转换为 `zh` / `en`,新闻接口继续使用已有 `zh-CN` / `en-US` 口径。
|
||||
- 语言偏好首版只保存在浏览器 `localStorage`,不新增后端用户设置字段。
|
||||
- `docs-lang` 保留为兼容读取和写入项,让已访问过 Docs 的浏览器能平滑迁移。
|
||||
- 静态路由、导航、搜索目标和通用组件使用显式翻译 key;大型业务页在迁移期间通过 legacy UI 翻译桥补足常见硬编码文案。
|
||||
|
||||
## 分期
|
||||
|
||||
### P1:统一语言基础设施
|
||||
|
||||
- 在 `frontend/src/i18n/` 下维护 locale 类型、资源、初始化和 `useLocale()`。
|
||||
- 在 `frontend/src/main.tsx` 里初始化 i18n,并同步 `document.documentElement.lang`。
|
||||
- 在认证页和控制台侧边栏偏好面板提供语言切换入口。
|
||||
|
||||
### P2:高复用界面迁移
|
||||
|
||||
- 迁移 Docs UI、AdminLayout、route manifest、admin search、Auth、DataTable、Dialog、Toast 和 MarkdownRenderer。
|
||||
- 搜索索引按当前语言展示,同时保留中英文关键词以免降低可发现性。
|
||||
- 用户管理页作为独立业务页示范,迁移表头、按钮、toast、校验提示、角色和 Gatekeeper 标签。
|
||||
|
||||
当前已完成统一 `planet-locale`、Docs 兼容映射、认证页和控制台外壳语言入口、共享组件 key 化,以及 legacy UI 翻译桥。后续工作集中在把大型业务页从过渡桥迁移到显式 key。
|
||||
|
||||
### P3:大型业务页收敛
|
||||
|
||||
- 分批把 Dashboard、DataList、Logs 和 PlainResourcePages 的配置块改为显式翻译 key。
|
||||
- 过渡期保留 legacy UI 翻译桥,只处理 admin/auth 容器里的精确静态文本和属性。
|
||||
- 业务数据、日志原文、API 字段名、provider id、命令和 Markdown 正文不走 legacy 翻译桥。
|
||||
|
||||
### P4:移除过渡桥
|
||||
|
||||
- 当 `rg -n "[\\p{Han}]" frontend/src/admin frontend/src/pages frontend/src/components` 只剩业务数据示例、中文文档标题或必须保留的中文品牌词时,删除 legacy UI 翻译桥。
|
||||
- 增加 key 完整性检查,确保 `zh-CN` 和 `en-US` 资源结构一致。
|
||||
|
||||
## 验证
|
||||
|
||||
- `cd frontend && bun run build`
|
||||
- `scripts/harness/frontend-rules-check.sh`
|
||||
- `scripts/harness/docs-consistency-check.sh`
|
||||
- `scripts/harness/quick-check.sh`
|
||||
- 前端 smoke 需要覆盖登录页、Docs、Admin 侧边栏语言切换、侧边栏和搜索结果在中英文下渲染。
|
||||
|
||||
## 相关文件
|
||||
|
||||
- `frontend/src/i18n/`:统一 locale、资源和过渡桥。
|
||||
- `frontend/src/pages/Docs/Docs.tsx`:Docs 语言状态改为读取全局 locale。
|
||||
- `frontend/src/admin/components/layout/AdminLayout.tsx`:控制台侧边栏语言切换、导航和搜索文案。
|
||||
- `frontend/src/admin/search/indexers.ts`:Admin 搜索目标本地化。
|
||||
- `docs/technical/{zh,en}/frontend-admin-frontend-context.md`:当前实现上下文。
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
**状态**:待实施
|
||||
**创建日期**:2026-05-12
|
||||
**核心目标**:把 `docs/technical/{zh,en}/manual.md` 拆成"纯客户视角"的使用手册,把 `planet.sh`、日志、LAN、故障排查这类运维内容迁到独立 `ops-runbook.md`,并把分层规则写进 `documentation-coverage-rules.md` 和 `.claude/commands/docs.md`,让以后写文档时自动按受众归档。
|
||||
**校正日期**:2026-06-26,控制台深链已从旧 tab 查询口径更新为当前 `?section=` 口径。
|
||||
**核心目标**:把 `docs/technical/{zh,en}/manual.md` 拆成"纯客户视角"的使用手册,把 `planet.sh`、日志、LAN、故障排查这类运维内容迁到独立 `ops-runbook.md`,并把分层规则写进 `documentation-coverage-rules.md` 和 `.codex/skills/docs/SKILL.md`,让以后写文档时自动按受众归档。
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -31,12 +32,12 @@
|
||||
3. **登录与找回密码** — 登录页、忘记密码流程
|
||||
4. **账户设置** — 修改密码、修改邮箱(需重新验证)、查看权限组、登出
|
||||
5. **Console 总览** — 左侧菜单结构、各路由用途
|
||||
6. **配置数据采集器** — `/collection-management?tab=collector_credentials`:选择 collector、连接测试、保存凭证;BarentsWatch / AISStream 两个典型例子
|
||||
7. **配置 AI 凭证** — `/ai?tab=providers`:默认 provider、模型、Base URL、API Key、本地代理;工具 tab(WebSearch、OCR)
|
||||
6. **配置数据采集器** — `/collection-management?section=collector_credentials`:选择 collector、连接测试、保存凭证;BarentsWatch / AISStream 两个典型例子
|
||||
7. **配置 AI 凭证** — `/ai?section=integrations`:默认 provider、模型、Base URL、API Key、本地代理;工具 section(WebSearch、OCR)位于 `/ai?section=tools`
|
||||
8. **系统设置** — `/settings` 其他子 tab(系统设置、电视直播源、SMTP 邮件)
|
||||
9. **用户管理(管理员)** — `/users`:创建、删除、改角色、Gatekeeper 权限组
|
||||
10. **数据探索** — `/datasources`、`/data`、`/bgp`、`/alerts/*`
|
||||
11. **AI 测试台** — `/ai?tab=playground`
|
||||
11. **AI 测试台** — `/ai?section=playground`
|
||||
12. **Earth 公开页面** — 现 manual.md 的 Earth 章节原样保留(图层、图例、搜索、位置候选、设置、视角、动捕、巡航、移动端)
|
||||
13. **Docs 文档站** — 当前 Docs 章节保留(权限组说明)
|
||||
|
||||
@@ -48,7 +49,7 @@
|
||||
|
||||
- 打开管理员给你的 URL
|
||||
- 注册账号 + 邮箱验证
|
||||
- 登录后第一次做什么(建议先到 `/collection-management?tab=collector_credentials` 配一个 collector,再到 `/ai` 配模型)
|
||||
- 登录后第一次做什么(建议先到 `/collection-management?section=collector_credentials` 配一个 collector,再到 `/ai?section=integrations` 配模型)
|
||||
- 看 Earth
|
||||
|
||||
部署/开发的 quickstart 内容并入 `ops-runbook.md` 的"首次部署"小节,**不**再单独出 `ops-quickstart.md`,避免新增维护点。
|
||||
@@ -79,7 +80,7 @@
|
||||
> - 新增客户可见 UI 流 → 同时更新 `manual.md` zh+en 与 `docs-content.ts`
|
||||
> - 新增 ops 命令或脚本 → 只更新 `ops-runbook.md` zh+en
|
||||
|
||||
## .claude/commands/docs.md 增量
|
||||
## `.codex/skills/docs/SKILL.md` 增量
|
||||
|
||||
在 "Step 2 — Decide Scope" 后插一段:
|
||||
|
||||
@@ -99,7 +100,7 @@
|
||||
- `docs/technical/zh/quickstart.md` & `en/quickstart.md` — 重写
|
||||
- `docs/technical/zh/ops-runbook.md` & `en/ops-runbook.md` *(新)*
|
||||
- `docs/documentation-coverage-rules.md` — 加受众分层段
|
||||
- `.claude/commands/docs.md` — 加 Document Audience Routing 段
|
||||
- `.codex/skills/docs/SKILL.md` — 加 Document Audience Routing 段
|
||||
- `frontend/src/pages/Docs/docs-content.ts` — 注册 `ops-runbook` 到 `DOCS_METADATA`(`docs_admin` 组)
|
||||
|
||||
## 依赖
|
||||
|
||||
@@ -8,7 +8,7 @@ The console now separates the "data source catalog" from "collector configuratio
|
||||
- Lists all data sources, including built-in and custom sources.
|
||||
- Clicking a name only opens an information drawer.
|
||||
- Focuses on status, manual collection, and running collection tasks.
|
||||
- `/collection-management?tab=collector_credentials`
|
||||
- `/collection-management?section=collector_credentials`
|
||||
- Displays as "Collectors".
|
||||
- Owns endpoint, headers, base parameters, and credentials.
|
||||
- Every collector exposes a connection button for health checks.
|
||||
|
||||
@@ -75,7 +75,11 @@ This is currently the most critical UI control entry point for the Earth fronten
|
||||
|
||||
Earth settings are now grouped by `data-settings-tab` and `data-settings-tab-panel`. Desktop and mobile share the same category semantics: Runtime, Display, Panels, Motion, Shortcuts, and System. When adding a setting, first choose its category, then add the DOM, persistence field, and restore logic; do not keep growing one long undifferentiated panel.
|
||||
|
||||
The news category selector in Display reuses the same chip-selector pattern as Cruise Modules. It only filters news categories for the current browser on the Earth frontend. It does not toggle layers, basemap, boundaries, TV, data points, BGP, vessels, satellites, or compute centers; those remain owned by the layer panel, media panel, and admin configuration. `controls.js` persists only `shared.newsCategoryFilters` and broadcasts `earth:news-category-filters-change`; `news.js` sends the selected categories to `/api/v1/news/earth-feed?categories=...&locale=zh-CN`, so Web and UE clients share the same backend category filtering path.
|
||||
Earth runs inside an independent iframe / static application, so it cannot directly reuse React Admin's `react-i18next` context. `public/earth` uses its own [i18n.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/i18n.js) runtime to read and write the global `planet-locale`, while keeping the legacy `docs-lang` in sync. This keeps Docs, the console, and Earth on the same language preference. The language switch belongs in the Settings `System` tab, and desktop/mobile both use the same `data-earth-locale` buttons; do not put language selection into layer, display, or runtime-mode settings.
|
||||
|
||||
The news category selector in Display reuses the same chip-selector pattern as Cruise Modules. It only filters news categories for the current browser on the Earth frontend. It does not toggle layers, basemap, boundaries, TV, data points, BGP, vessels, satellites, or compute centers; those remain owned by the layer panel, media panel, and admin configuration. `controls.js` persists only `shared.newsCategoryFilters` and broadcasts `earth:news-category-filters-change`; `news.js` sends the selected categories and current locale to `/api/v1/news/earth-feed?categories=...&locale=...`, so Web and UE clients share the same backend category filtering path.
|
||||
|
||||
In English mode, Earth news must render only English title/summary text. Chinese source items without `en-US` localization are filtered from the visible cards/ticker/cruise until the backend enrichment finishes, and source/feed labels fall back to English-safe names instead of rendering Chinese labels.
|
||||
|
||||
The news panel, ticker, and news cruise must consume `items` / `cruise_items` from the same `/api/v1/news/earth-feed` response instead of keeping separate regional caches. `news.js` builds a refresh request key from region, category, source, and limit; only concurrent requests with the same key reuse the promise, and stale responses from an older region are dropped by token. Source filtering is also region-scoped: when the user moves from Asia Pacific to Europe or another region, source IDs saved for the old region must not be appended to the next fetch. After the new payload arrives, the saved source list is intersected with the available `sources`; if the intersection is empty, the current region falls back to all available sources. This keeps the ticker, panel, and cruise cards aligned after region switches.
|
||||
|
||||
@@ -242,6 +246,8 @@ Earth settings are stored in `localStorage`. The key is typically a namespaced s
|
||||
|
||||
Settings that affect visual layers and surface interaction (terrain opacity, day/night mode, satellite display style, satellite idle breathing, real satellite altitude, track display, hover tooltip mode, etc.) are read during initialization and applied immediately.
|
||||
|
||||
Language preference is the exception: Earth language is not a private `planet.earth.settings.v2` field. It shares `planet-locale` with Docs/Admin. When language changes, `i18n.js` updates `document.documentElement.lang`, translates static and dynamically inserted DOM, synchronizes language button state, and passes the current locale to news requests. The news module refreshes after a language change so an English UI does not reuse a Chinese news payload.
|
||||
|
||||
The surface hover tooltip preference is persisted by `controls.js` as `shared.surfaceHoverInfoMode`, while `main.js` composes the actual tooltip in the globe-surface hover branch. `Country` shows country details only when a country polygon is hit and stays silent over ocean; `Position` shows latitude, longitude, and sampled terrain elevation and clears country-boundary hover; `Full` shows country + position on land and position over ocean.
|
||||
|
||||
The real satellite altitude preference is persisted by `controls.js`, while the rendering state lives in `satellites.js`. When enabled, the real radius from SGP4 is compressed logarithmically into the current Earth visual radius range. When disabled, satellite dots, trails, and predicted orbits all return to the legacy same-sphere display. Toggling this setting must refresh satellite positions and clear trail buffers so a trail never mixes both height models. `maxRealAltitudeOffset = 25` is a visual cap tuned for the current camera and `earthRadius = 100`: GEO / MEO remain clearly higher than LEO, but the highest orbits stay within about 25% beyond the globe radius so selection targets, red trails, and the globe do not feel disconnected.
|
||||
@@ -352,7 +358,7 @@ For future Earth changes:
|
||||
|
||||
The Earth frontend and the console frontend are not the same UI system:
|
||||
|
||||
- Console frontend: React + Ant Design workbench
|
||||
- Console frontend: React + Tactile UI / Radix primitives / lucide workbench
|
||||
- Earth frontend: native HUD + Three.js display under `public/earth`
|
||||
|
||||
Therefore:
|
||||
|
||||
@@ -144,6 +144,8 @@ The Web Earth client and UE client both consume `GET /api/v1/news/earth-feed`. T
|
||||
- `categories`: comma-separated news category keys, for example `business,ecommerce`. Omit it when all categories are selected.
|
||||
- `locale`: display locale, currently `zh-CN` or `en-US`, defaulting to `zh-CN`. Chinese RSS items are stored as Chinese source content and enriched with `en-US`; English RSS items are enriched with `zh-CN`.
|
||||
|
||||
For `locale=en-US`, the API must not fall back to Chinese source title/summary. If a Chinese source item has not yet received an `en-US` localization, `display_title` and `display_summary` stay empty so the Earth client can show an English pending/empty state instead of mixing languages.
|
||||
|
||||
Examples:
|
||||
|
||||
```http
|
||||
|
||||
@@ -98,6 +98,8 @@ Admin status labels should use [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
`StatusText` is an indicator-light pill: the pill background and border stay on the component base color, while only the dot and text use the status color. `Badge` does not carry the indicator-light meaning, so it may use a light same-tone background and border for stronger hierarchy.
|
||||
|
||||
Status indicators must show the full state word. In lists, hierarchy groups, and detail headers, the title/description area should shrink or wrap while the status pill keeps content-sized width and does not get compressed by flex/grid layout; do not truncate state words such as `Configured` or `Available` just to save horizontal space.
|
||||
|
||||
| Tone | Color variable | Meaning | Examples |
|
||||
| --- | --- | --- | --- |
|
||||
| `success` | `--an-success` | available, successful, connected, enabled | log source `Available`, collection `Success` |
|
||||
@@ -155,7 +157,6 @@ Purpose:
|
||||
Current usage:
|
||||
|
||||
- Admin data sources, collected data, collection management, logs, alerts, and BGP pages
|
||||
- Old AntD legacy pages continue using shared scrolling behavior through compatibility wrappers
|
||||
|
||||
### 3. `TableScrollRegion`
|
||||
|
||||
@@ -217,7 +218,31 @@ Current constraints:
|
||||
- Prefer CSS variable overrides for colors instead of hard-coding theme colors in feature components
|
||||
- Best for a small set of mutually exclusive choices; do not use it as a long list, navigation menu, or select replacement
|
||||
|
||||
### 6. `MarkdownRenderer`
|
||||
### 6. Console i18n
|
||||
|
||||
Files:
|
||||
|
||||
- [i18n/index.ts](/home/ray/dev/linkong/planet/frontend/src/i18n/index.ts)
|
||||
- [i18n/locale.ts](/home/ray/dev/linkong/planet/frontend/src/i18n/locale.ts)
|
||||
- [i18n/resources.ts](/home/ray/dev/linkong/planet/frontend/src/i18n/resources.ts)
|
||||
- [LegacyI18nBridge.tsx](/home/ray/dev/linkong/planet/frontend/src/i18n/LegacyI18nBridge.tsx)
|
||||
|
||||
Purpose:
|
||||
|
||||
- Share one `zh-CN` / `en-US` language state across the console, auth pages, and Docs UI
|
||||
- Store the language preference in `planet-locale` while keeping compatibility with the old `docs-lang`
|
||||
- Keep Docs API requests mapped to the backend's existing `zh` / `en` document interface
|
||||
- Provide language switchers in the console sidebar preferences panel and auth panel
|
||||
|
||||
Current constraints:
|
||||
|
||||
- New console copy should be added to `resources.ts`, then consumed with `useTranslation()` or `useLocale()`
|
||||
- Routes, menus, search indexes, and shared components must use explicit translation keys
|
||||
- `LegacyI18nBridge` is transitional and only handles exact static text and attributes inside admin/auth containers
|
||||
- Business data, raw logs, API field names, provider ids, commands, and Markdown body content are not translated by the legacy bridge
|
||||
- Future large-page migrations should shrink the legacy dictionary rather than grow it
|
||||
|
||||
### 7. `MarkdownRenderer`
|
||||
|
||||
File:
|
||||
|
||||
@@ -275,17 +300,16 @@ File:
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- `/ai` now owns LLM Provider, AI Tool configuration, and the testbench instead of nesting them under `/settings`
|
||||
- The `模型供应商` tab manages default provider, model, base URL, provider key, local `aiprovider` proxy, and connection test; provider and model fields use editable comboboxes so users can manually enter new providers/models if the models.dev catalog stops updating
|
||||
- The `工具` tab first selects a tool from a dropdown menu, then renders that tool's configuration; it currently includes WebSearch and OCR
|
||||
- `/ai` now owns LLM Provider, AI Tool configuration, and Playground instead of nesting them under `/settings`
|
||||
- The `模型供应商` section manages default provider, model, base URL, provider key, local `aiprovider` proxy, and connection test; provider and model fields use editable comboboxes so users can manually enter new providers/models if the models.dev catalog stops updating
|
||||
- The `工具调用` section first selects a tool from a dropdown menu, then renders that tool's configuration; it currently includes WebSearch and OCR
|
||||
- WebSearch configuration includes provider, search key, base URL, timeout, result count, and advanced provider options
|
||||
- OCR configuration includes provider, Base URL, API key, model/engine, languages, timeout, file-size limit, and output format
|
||||
- The `测试台` tab embeds the former Playground real session, preset prompts, and AI Provider status debugging
|
||||
- The page reuses the Settings single-screen tabs, panel card, and internal scrolling style
|
||||
- The `Playground` section embeds the former Playground real session, preset prompts, and AI Provider status debugging
|
||||
- The page reuses the Settings single-screen section, panel card, and internal scrolling style
|
||||
- AI Provider and WebSearch connection tests use `ConnectionTestInput`, with the connector icon fixed at the end of the Base URL input; when WebSearch is disabled, every configuration field and the test entry point are greyed out except the switch
|
||||
|
||||
Legacy `/settings?tab=ai` should redirect to `/ai?tab=providers`.
|
||||
Legacy `/playground` should redirect to `/ai?tab=playground`.
|
||||
AI configuration no longer lives under `/settings`; `/playground` should redirect to `/ai?section=playground`.
|
||||
|
||||
### 3. Business Data Gateway
|
||||
|
||||
@@ -342,11 +366,11 @@ Current page boundary:
|
||||
- Endpoint, headers, and config are displayed here, not edited.
|
||||
- Credential-bearing collectors point users to `Collection Management -> Collectors`.
|
||||
|
||||
Keep this boundary: do not put custom datasource editing, built-in endpoint overrides, or credential forms back into `/datasources`. Those configuration entry points live at `/collection-management?tab=collector_credentials`.
|
||||
Keep this boundary: do not put custom datasource editing, built-in endpoint overrides, or credential forms back into `/datasources`. Those configuration entry points live at `/collection-management?section=collector_credentials`.
|
||||
|
||||
### Collectors Page
|
||||
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) has three route modes: `/settings` for System Settings, `/earth-content` for Earth Content, and `/collection-management` for Collection Management. The `collector_credentials` tab is shown as `Collectors` under `/collection-management`.
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) has three route modes: `/settings` for System Settings, `/earth-content` for Earth Content, and `/collection-management` for Collection Management. The `collector_credentials` section is shown as `Collectors` under `/collection-management`.
|
||||
|
||||
The `System Display` section under `/settings` includes the `Demo Mode` switch. When enabled, Earth OOBE ignores existing current collected data and the local `browse first` temporary skip state, then opens the initialization guide directly. This switch is only for demos and acceptance checks; it does not change datasources, collection queues, or Earth content resources.
|
||||
|
||||
@@ -363,6 +387,7 @@ Current boundary:
|
||||
`/earth-content` reuses the same single-screen tab container from [Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx), but its ownership is separate from System Settings:
|
||||
|
||||
- `TV Livestream` owns the Earth media-panel source configuration.
|
||||
- `Branding` owns Earth HUD brand assets. `Logo URL` and `Title Image URL` use inline upload controls inside the fields; the upload buttons keep the primary `TactileButton` style, and dropping an image onto the matching field shows a low-saturation drag reaction instead of the old global asset-picker toolbar.
|
||||
- `Boundary Precision` owns the Earth static boundary asset state: provider, low-precision fallback, high-precision manifest/PMTiles, source JSON, and build action.
|
||||
- `Base Map`, `Layer Resources`, `3D Assets`, and `News Anchor Strategy` are placeholders only. They show module status and do not invent fake APIs or fake data.
|
||||
|
||||
@@ -391,6 +416,7 @@ These principles have been repeatedly validated in the project:
|
||||
4. Do not use `overflow: hidden` to mask structural issues
|
||||
5. Do not compress the main work area to make summary cards show completely
|
||||
6. Custom scrollbars must be floating overlays; they must not squeeze content width
|
||||
7. The Admin shell relies on the root `height: 100%` chain and should not use exact `100vh` sizing at the workspace root
|
||||
|
||||
For detailed experience, see:
|
||||
|
||||
@@ -411,7 +437,7 @@ Do not write local CSS patches first, then retrofit the structure.
|
||||
|
||||
The console frontend and the Earth frontend are not the same system:
|
||||
|
||||
- Console frontend: React + Ant Design workbench
|
||||
- Console frontend: React + Tactile UI / Radix primitives / lucide workbench
|
||||
- Earth frontend: independent native HUD system under `public/earth`
|
||||
|
||||
Therefore:
|
||||
|
||||
@@ -210,6 +210,11 @@ Inspection order:
|
||||
3. Does the real scroll node explicitly use `overflow: auto`?
|
||||
4. Have intermediate wrapper layers silently changed layout semantics?
|
||||
|
||||
The current Admin and Docs root shells rely on the `html` / `body` / `#root`
|
||||
`height: 100%` chain. Do not reintroduce exact `100vh` / `100vw` sizing on
|
||||
these embedded workspace shells; modals, overlays, and narrow-screen safety
|
||||
boundaries may still use `calc(100vh - ...)` as a maximum-size constraint.
|
||||
|
||||
### 5. UI State and Display State Out of Sync
|
||||
|
||||
Repeated in Earth-related changes:
|
||||
|
||||
@@ -22,7 +22,7 @@ URLs below use the local default `http://localhost:3000`. Replace the prefix wit
|
||||
1. Open `http://localhost:3000/login` and click "Register" under the form.
|
||||
2. On `/register`, fill in:
|
||||
- **Username**: 3–50 characters, used to log in
|
||||
- **Email**: receives the verification code; editable later in account settings
|
||||
- **Email**: receives the verification code; in the current version, ask an administrator to maintain email changes in user management
|
||||
- **Password**: at least 8 characters
|
||||
3. After submission you are taken to the verify page. A 6-digit code is sent to your email. It expires in 10 minutes.
|
||||
4. Enter the code and click "Verify and Sign In". On success the system stores a session and sends you to the console.
|
||||
@@ -52,23 +52,23 @@ If you see "Email not verified", the page automatically redirects to `/verify-em
|
||||
3. After receiving the code, enter it together with a new password (≥ 8 characters) and click "Reset Password".
|
||||
4. The system sends you back to `/login` — sign in with the new password.
|
||||
|
||||
## Account Settings
|
||||
## Account Area And Sign Out
|
||||
|
||||
Click your username at the top-right of the console to open account settings:
|
||||
The account area at the bottom of the console sidebar shows the current username, version, and theme control. The current version does not include a signed-in self-service account settings page:
|
||||
|
||||
- Change password: enter current password + new password
|
||||
- Change email: the system sends a verification code to the new address; the change applies only after verification
|
||||
- View Gatekeeper groups: lists current groups (`docs_user` / `docs_developer` / `docs_admin`)
|
||||
- Log out: clears the current session
|
||||
- Use `/forgot-password` for password reset through email verification
|
||||
- Administrators maintain email, role, and Gatekeeper groups at `/users`
|
||||
- The sign-out icon in the account area clears the current session and returns to the login page
|
||||
|
||||
## Console Overview
|
||||
|
||||
The console at `http://localhost:3000/admin` is built with React + Ant Design. The left menu is organized by work domain.
|
||||
The console at `http://localhost:3000/admin` is built with React plus Tactile UI / Radix primitives and lucide icons. The left menu is organized by work domain.
|
||||
|
||||
| Page | Route | Purpose |
|
||||
| --- | --- | --- |
|
||||
| Dashboard | `/admin` | System overview |
|
||||
| Earth | `/earth` | Open the public Earth page |
|
||||
| Docs | `/docs` | Open the docs site and show documents allowed by Gatekeeper permissions |
|
||||
| Datasources | `/datasources` | Source directory and collection triggers |
|
||||
| Collected Data | `/data` | Data already ingested |
|
||||
| BGP | `/bgp` | BGP situational view |
|
||||
@@ -86,7 +86,7 @@ Menu items hide automatically when you lack permission. If a menu is missing, ch
|
||||
|
||||
## Configure Data Collectors
|
||||
|
||||
`/collection-management?tab=collector_credentials` is the "Collectors" page. It manages connection configuration for every collector, not just credentials. Legacy `/settings?tab=collector_credentials` redirects here; the datasource directory remains at `/datasources`.
|
||||
`/collection-management?section=collector_credentials` is the "Collectors" page. It manages connection configuration for every collector, not just credentials; the datasource directory remains at `/datasources`.
|
||||
|
||||
Steps:
|
||||
|
||||
@@ -127,7 +127,7 @@ The default guide follows the BarentsWatch official tutorial and reminds you to
|
||||
|
||||
Steps:
|
||||
|
||||
1. Open `/collection-management?tab=collector_credentials` and select `AISStream Realtime Vessels : aisstream_vessels`
|
||||
1. Open `/collection-management?section=collector_credentials` and select `AISStream Realtime Vessels : aisstream_vessels`
|
||||
2. Fill the AISStream API Key
|
||||
3. Keep the default endpoint `wss://stream.aisstream.io/v0/stream`
|
||||
4. Click the plug icon to test; confirm it reports `Reachable`
|
||||
@@ -141,11 +141,12 @@ Steps:
|
||||
|
||||
## Configure AI Credentials
|
||||
|
||||
`/ai?tab=providers` is the AI management entry. Three key sub-tabs:
|
||||
`/ai?section=integrations` is the AI management entry. Key sections:
|
||||
|
||||
- `Model Providers`: default LLM provider, model, base URL, API key, local `aiprovider` proxy, connection test
|
||||
- `Tools`: a dropdown for specific tools — currently WebSearch and OCR
|
||||
- `Tool Calls`: a dropdown for specific tools — currently WebSearch and OCR
|
||||
- `Prompts`: a task dropdown for news localization, alert analysis, BGP briefs, and other LLM tasks. Operators can edit the prompt or reset it to the default
|
||||
- `Playground`: real session, preset request, and AI Provider status debugging
|
||||
|
||||
### Model Providers
|
||||
|
||||
@@ -170,7 +171,7 @@ The plug icon at the end of the Base URL input runs a connection test. A passing
|
||||
|
||||
After selecting a task, the page shows the effective prompt, whether it is customized, the shipped default version, and a reset button. Saving affects only that task. Reset restores the default prompt from the current release package. Business facts, context, and output schemas are still assembled by the backend for each task.
|
||||
|
||||
The legacy link `/settings?tab=ai` redirects to `/ai?tab=providers`.
|
||||
AI configuration no longer lives in System Settings; `/playground` redirects to `/ai?section=playground`.
|
||||
|
||||
## Datasources and Task Logs
|
||||
|
||||
@@ -191,7 +192,7 @@ TV livestreams and boundary precision moved to `/earth-content`; collectors and
|
||||
|
||||
`/earth-content` is under the console's Operations and Configuration group and owns resources used by the Earth frontend:
|
||||
|
||||
- **Brand Assets**: manages the logo, title image, title text, subtitle, and description used by the Earth HUD. Uploaded images are saved as Earth brand assets and read by the Earth page immediately.
|
||||
- **Brand Assets**: manages the logo, title image, title text, subtitle, and description used by the Earth HUD. The `Logo URL` and `Title Image URL` fields each include their own Upload button, and image files can be dropped directly onto the matching field. After upload, the field receives the new asset URL; save the brand configuration to make the Earth page use it.
|
||||
- **About**: manages the About card shown in Earth settings, including logo, kicker, title, version, description, and metadata.
|
||||
- **TV Livestream**: manages sources shown in the Earth media panel.
|
||||
- **News Content**: browses news grouped by RSS source and manual group. RSS items remain read-only; manual groups support create, JSON import, edit, delete, and reprocess.
|
||||
@@ -245,7 +246,7 @@ To let a regular user read developer or operations docs, add `docs_developer` or
|
||||
|
||||
## AI Testbench
|
||||
|
||||
`/ai?tab=playground` is for real-pipeline debugging:
|
||||
`/ai?section=playground` is for real-pipeline debugging:
|
||||
|
||||
- Pick the active provider
|
||||
- Run preset requests or custom prompts
|
||||
|
||||
@@ -28,6 +28,9 @@ This document standardizes terms used across Intelligent Planet, the console, ba
|
||||
| AI Provider | AI Provider | Service name |
|
||||
| tool | 工具 | Web Search, OCR, and similar integrations |
|
||||
| Playground | Playground | Interactive debugging entry |
|
||||
| branding | 品牌标识 | Earth HUD brand configuration section under `/earth-content` |
|
||||
| brand assets | 品牌资源 | Logo, title image, and related HUD copy assets |
|
||||
| title image | 标题图 | Earth HUD title image |
|
||||
|
||||
## Data Types
|
||||
|
||||
|
||||
@@ -32,11 +32,12 @@ The default role is `viewer`: you can sign in but only see public pages. For col
|
||||
|
||||
After landing on the `/admin` dashboard, here's a recommended walk-through:
|
||||
|
||||
1. `/collection-management?tab=collector_credentials`: pick a collector and click the plug icon to test connectivity. Free collectors (e.g. open BGP) usually work right away; credential-bearing ones like `AISStream` or `BarentsWatch` need an API key / client secret first
|
||||
2. `/ai?tab=providers`: fill an LLM provider (e.g. `minimax` / `openai`), model, base URL, API key, and click the plug at the end of the base URL to test. WebSearch / OCR tools are optional
|
||||
3. `/datasources` or `/data`: check whether collectors have produced data. Use `/datasources -> Built-in Sources` for finite collectors: with no rows selected, click `Trigger All`; after selecting rows, the primary button becomes `Trigger Selected N`. The top-right queue button shows progress. Use `/datasources -> Realtime Sources` for AISStream / WebSocket health and counters
|
||||
4. `/alerts/system`: verify system alerts look right
|
||||
5. `/users` (super_admin only): open accounts for teammates or adjust their groups
|
||||
1. `/collection-management?section=collector_credentials`: pick a collector and click the plug icon to test connectivity. Free collectors (e.g. open BGP) usually work right away; credential-bearing ones like `AISStream` or `BarentsWatch` need an API key / client secret first
|
||||
2. `/ai?section=integrations`: fill an LLM provider (e.g. `minimax` / `openai`), model, base URL, API key, and click the plug at the end of the base URL to test. WebSearch / OCR tools are optional
|
||||
3. `/earth-content?section=brand`: maintain the Earth HUD logo and title image in Branding. The Upload button inside each URL field opens a file picker, and image files can also be dropped directly onto the matching field. Save the brand configuration after upload
|
||||
4. `/datasources` or `/data`: check whether collectors have produced data. Use `/datasources -> Built-in Sources` for finite collectors: with no rows selected, click `Trigger All`; after selecting rows, the primary button becomes `Trigger Selected N`. The top-right queue button shows progress. Use `/datasources -> Realtime Sources` for AISStream / WebSocket health and counters
|
||||
5. `/alerts/system`: verify system alerts look right
|
||||
6. `/users` (super_admin only): open accounts for teammates or adjust their groups
|
||||
|
||||
## 4. Open Earth
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
- 展示所有数据源,包括内置和自定义。
|
||||
- 点击名称只打开信息抽屉。
|
||||
- 负责查看状态、触发采集和查看采集中任务。
|
||||
- `/collection-management?tab=collector_credentials`
|
||||
- `/collection-management?section=collector_credentials`
|
||||
- 显示为“采集器”。
|
||||
- 负责 endpoint、请求头、基础参数和凭证配置。
|
||||
- 所有采集器都提供连接按钮,用于健康检查。
|
||||
|
||||
@@ -75,7 +75,11 @@ Earth 收到 `/ws` 的 `earth_updates` 时只把它当作刷新提示,真实
|
||||
|
||||
Earth 设置面板现在按 `data-settings-tab` 和 `data-settings-tab-panel` 分类组织。桌面端和移动端使用同一组分类语义:运行、显示、面板、动捕、快捷键、系统。新增设置项时应先判断它属于哪个分类,再补 DOM、持久化字段和恢复逻辑;不要把所有控件继续堆到一个长面板里。
|
||||
|
||||
`显示` 分类里的新闻类型选择复用巡航模块的 chip 选择器形态,只控制星球端当前浏览器的新闻分类显示。它不会打开或关闭图层、底图、边界、TV、数据点、BGP、船舶、卫星或算力中心;这些仍由图层面板、媒体面板和控制台配置各自负责。`controls.js` 只持久化 `shared.newsCategoryFilters` 并广播 `earth:news-category-filters-change`,`news.js` 会把选中的类型拼到 `/api/v1/news/earth-feed?categories=...&locale=zh-CN`,让 Web 和 UE 走同一套后端类型过滤。
|
||||
Earth 运行在独立 iframe / 静态应用里,不能直接复用 React Admin 的 `react-i18next` 上下文。`public/earth` 自己通过 [i18n.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/i18n.js) 读取并写回全局 `planet-locale`,同时同步旧的 `docs-lang`,这样 Docs、控制台和 Earth 的语言偏好保持一致。语言切换控件属于设置里的 `系统` tab,桌面和移动端都使用同一组 `data-earth-locale` 按钮;不要把语言选择塞进图层、显示或运行模式设置里。
|
||||
|
||||
`显示` 分类里的新闻类型选择复用巡航模块的 chip 选择器形态,只控制星球端当前浏览器的新闻分类显示。它不会打开或关闭图层、底图、边界、TV、数据点、BGP、船舶、卫星或算力中心;这些仍由图层面板、媒体面板和控制台配置各自负责。`controls.js` 只持久化 `shared.newsCategoryFilters` 并广播 `earth:news-category-filters-change`,`news.js` 会把选中的类型和当前 locale 拼到 `/api/v1/news/earth-feed?categories=...&locale=...`,让 Web 和 UE 走同一套后端类型过滤。
|
||||
|
||||
英文模式下,Earth 新闻只能渲染英文标题和摘要。中文来源新闻如果还没有 `en-US` 本地化,会先从可见卡片、滚动条和巡航中隐藏,直到后端增强完成;来源和 feed 标签也必须回退到英文安全名称,避免英文界面混入中文标签。
|
||||
|
||||
新闻面板、滚动条和新闻巡航必须消费同一次 `/api/v1/news/earth-feed` 响应里的 `items` / `cruise_items`,不能各自缓存区域状态。`news.js` 的刷新请求以区域、类型、来源和数量生成 request key;只有 key 相同的并发请求才复用 promise,旧区域请求返回时会被 token 丢弃。来源过滤也必须按区域作用域处理:当用户从亚太切到欧洲等其它区域时,旧区域保存的来源 ID 不允许继续拼到下一次 fetch 里;拿到新 payload 后再与 `sources` 列表做交集,若没有交集则回退到当前区域所有可用来源。这样滚动条、面板和巡航才会在区域切换后展示同一批新闻。
|
||||
|
||||
@@ -457,6 +461,8 @@ Earth 设置面板当前由 [controls.js](/home/ray/dev/linkong/planet/frontend/
|
||||
|
||||
也就是说,Earth 设置不是一次性 UI 状态了,而是本地设备级偏好。后续如果再加入新的设置项,应优先接入同一条持久化链,而不是各自散着写 `localStorage`。
|
||||
|
||||
语言偏好例外:Earth 语言不是 `planet.earth.settings.v2` 的私有字段,而是与 Docs/Admin 共用 `planet-locale`。切换语言时,`i18n.js` 会更新 `document.documentElement.lang`、翻译静态和动态插入的 DOM、同步语言按钮状态,并向新闻请求传递当前 locale;新闻模块在语言变化后会重新刷新,避免英文界面复用中文新闻 payload。
|
||||
|
||||
地表 hover 提示由 `controls.js` 持久化为 `shared.surfaceHoverInfoMode`,实际 tooltip 在 `main.js` 的地表 hover 分支组合。`国家` 模式只在命中国家时显示国家信息,海洋区域不显示地表 tooltip;`位置` 模式只显示纬度、经度和地形采样海拔,并清除国家边界 hover;`完整` 模式在陆地显示国家 + 位置,在海洋显示位置。
|
||||
|
||||
卫星真实高度开关由 `controls.js` 持久化,实际渲染状态在 `satellites.js`。开启时,SGP4 得到的真实半径会按对数压缩到当前 Earth 视觉半径范围;关闭时,卫星点、轨迹和预测轨道都回到旧版同层球面。切换时必须刷新卫星位置并清理轨迹缓存,避免同一条轨迹混入两个高度模型。`maxRealAltitudeOffset = 25` 是当前相机和 `earthRadius = 100` 下的视觉上限:它让 GEO / MEO 比 LEO 明显更高,但把最高轨道控制在地球半径外约 25%,避免选择点、红色轨迹和主体地球之间出现过大的空场。
|
||||
|
||||
@@ -144,6 +144,8 @@ JSON 导入首版只支持数组:
|
||||
- `categories`:逗号分隔的新闻类型 key,例如 `business,ecommerce`。全选时可以不传。
|
||||
- `locale`:展示语言,支持 `zh-CN` 和 `en-US`,默认 `zh-CN`。中文 RSS 会以中文原文入库,并由后台补 `en-US`;英文 RSS 则由后台补 `zh-CN`。
|
||||
|
||||
当 `locale=en-US` 时,接口不能回退展示中文原文标题或摘要。中文来源新闻尚未生成 `en-US` 本地化时,`display_title` 和 `display_summary` 保持为空,由 Earth 前端展示英文待处理或空态,避免英文界面混入中文新闻内容。
|
||||
|
||||
示例:
|
||||
|
||||
```http
|
||||
|
||||
@@ -98,6 +98,8 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
`StatusText` 是带圆点的指示灯:胶囊背景和边框保持组件原色,只让圆点和文字变成状态色。`Badge` 不带指示灯语义,可以使用同 tone 的浅色背景和边框强化信息层级。
|
||||
|
||||
状态指示器必须完整显示状态词。列表、树形组和详情栏里的状态列应让标题/描述区域收缩或换行,状态 pill 本身使用内容自适应宽度并禁止被 flex/grid 挤压;不要为了紧凑把 `Configured` / `Available` 这类状态裁成省略号。
|
||||
|
||||
| Tone | 颜色变量 | 语义 | 示例 |
|
||||
| --- | --- | --- | --- |
|
||||
| `success` | `--an-success` | 可用、成功、已连接、已启用 | 日志源 `可用`、采集 `成功` |
|
||||
@@ -216,7 +218,31 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
- 颜色优先通过 CSS 变量覆盖,避免在业务组件里硬编码主题色
|
||||
- 适合少量互斥选项,不适合用作长列表、导航菜单或表单下拉
|
||||
|
||||
### 6. `MarkdownRenderer`
|
||||
### 6. 控制台 i18n
|
||||
|
||||
文件:
|
||||
|
||||
- [i18n/index.ts](/home/ray/dev/linkong/planet/frontend/src/i18n/index.ts)
|
||||
- [i18n/locale.ts](/home/ray/dev/linkong/planet/frontend/src/i18n/locale.ts)
|
||||
- [i18n/resources.ts](/home/ray/dev/linkong/planet/frontend/src/i18n/resources.ts)
|
||||
- [LegacyI18nBridge.tsx](/home/ray/dev/linkong/planet/frontend/src/i18n/LegacyI18nBridge.tsx)
|
||||
|
||||
用途:
|
||||
|
||||
- 控制台、认证页和 Docs UI 共用 `zh-CN` / `en-US` 语言状态
|
||||
- 语言偏好保存在 `planet-locale`,同时兼容旧的 `docs-lang`
|
||||
- Docs 请求仍映射到后端现有 `zh` / `en` 文档接口
|
||||
- 控制台侧边栏偏好面板和认证页面板提供语言切换入口
|
||||
|
||||
当前约束:
|
||||
|
||||
- 新增控制台文案优先写入 `resources.ts`,组件使用 `useTranslation()` 或 `useLocale()`
|
||||
- 路由、菜单、搜索索引和通用组件必须使用显式翻译 key
|
||||
- `LegacyI18nBridge` 只作为过渡层,负责 admin/auth 容器内未迁移的精确静态文本和属性
|
||||
- 业务数据、日志原文、API 字段名、provider id、命令和 Markdown 正文不走 legacy 翻译桥
|
||||
- 后续迁移大型业务页时应减少 legacy 字典,而不是继续扩大它
|
||||
|
||||
### 7. `MarkdownRenderer`
|
||||
|
||||
文件:
|
||||
|
||||
@@ -274,17 +300,16 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
职责:
|
||||
|
||||
- `/ai` 独立承载 LLM Provider、AI Tool 配置和测试台,不再放在 `/settings` 的系统配置 tabs 中
|
||||
- `模型供应商` tab 管理默认 provider、模型、base URL、provider key、本地 `aiprovider` 代理和连接测试;provider 和模型输入使用可输入组合框,models.dev 目录停更时用户仍可手动填新 provider/model
|
||||
- `工具` tab 先通过下拉菜单选择工具,再管理对应配置;当前包含 WebSearch 和 OCR
|
||||
- `/ai` 独立承载 LLM Provider、AI Tool 配置和 Playground,不再放在 `/settings` 的系统配置分区中
|
||||
- `模型供应商` 分区管理默认 provider、模型、base URL、provider key、本地 `aiprovider` 代理和连接测试;provider 和模型输入使用可输入组合框,models.dev 目录停更时用户仍可手动填新 provider/model
|
||||
- `工具调用` 分区先通过下拉菜单选择工具,再管理对应配置;当前包含 WebSearch 和 OCR
|
||||
- WebSearch 配置包含 provider、搜索 key、base URL、超时、结果数和高级 provider 参数
|
||||
- OCR 配置包含 provider、Base URL、API Key、模型/engine、语言、超时、文件大小上限和输出格式
|
||||
- `测试台` tab 嵌入原 Playground 的真实会话、预设请求和 AI Provider 状态调试
|
||||
- 页面复用 Settings 的单屏 tabs、panel card 和内部滚动样式
|
||||
- `Playground` 分区嵌入原 Playground 的真实会话、预设请求和 AI Provider 状态调试
|
||||
- 页面复用 Settings 的单屏分区、panel card 和内部滚动样式
|
||||
- AI Provider / WebSearch 的连接测试使用 `ConnectionTestInput`,连接器图标固定在 Base URL 输入框末端;WebSearch 未启用时,除开关外的配置项和测试入口都置灰
|
||||
|
||||
旧的 `/settings?tab=ai` 应跳转到 `/ai?tab=providers`。
|
||||
旧的 `/playground` 应跳转到 `/ai?tab=playground`。
|
||||
AI 配置不再挂在 `/settings` 下;`/playground` 应跳转到 `/ai?section=playground`。
|
||||
|
||||
### 3. 业务数据网关
|
||||
|
||||
@@ -342,7 +367,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
- endpoint、headers、config 只展示,不在这里编辑。
|
||||
- 需要凭证的采集器提示用户到“采集管理 -> 采集器”维护。
|
||||
|
||||
这个边界很重要:后续不要把自定义数据源编辑、内置 endpoint 覆盖或凭证表单再塞回 `/datasources`。这些配置入口统一放在 `/collection-management?tab=collector_credentials`。
|
||||
这个边界很重要:后续不要把自定义数据源编辑、内置 endpoint 覆盖或凭证表单再塞回 `/datasources`。这些配置入口统一放在 `/collection-management?section=collector_credentials`。
|
||||
|
||||
页面顶部的总进度区域新增 `采集中 N` 标签:
|
||||
|
||||
@@ -355,7 +380,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
|
||||
### 采集器设置页
|
||||
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 会按路由进入三种模式:`/settings` 是系统设置,`/earth-content` 是智能星球内容,`/collection-management` 是采集管理。`collector_credentials` tab 当前在 `/collection-management` 下显示为“采集器”。
|
||||
[Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 会按路由进入三种模式:`/settings` 是系统设置,`/earth-content` 是智能星球内容,`/collection-management` 是采集管理。`collector_credentials` section 当前在 `/collection-management` 下显示为“采集器”。
|
||||
|
||||
`/settings` 的“系统显示”分区包含 `演示模式` 开关。开启后,智能星球的 OOBE 会忽略“已有当前采集数据”和本地“先浏览”临时跳过状态,直接展示初始化引导;该开关仅用于演示/验收流程,不改变数据源、采集队列或智能星球内容资源配置。
|
||||
|
||||
@@ -368,7 +393,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
- 不需要凭证的采集器只显示基础配置:endpoint、默认 endpoint、请求头、timeout、retry。
|
||||
- `BarentsWatch AIS` 使用专用凭证表单。
|
||||
|
||||
连接图标使用内联 `PlugConnectIcon`,视觉语义来自 Tabler `plug-connected`。后续如果控制台重写图标体系,应迁移到 Tabler Icons,而不是继续使用 Ant Design 刷新图标表达连接。
|
||||
连接测试入口使用现有 `Button icon="test"` 图标语义。后续如果控制台重写图标体系,应迁移到现有 lucide / Tactile UI 图标体系,而不是用普通刷新图标表达连接。
|
||||
|
||||
`Client Secret` 的表单语义:
|
||||
|
||||
@@ -393,6 +418,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
`/earth-content` 复用 [Settings.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 的单屏 tab 容器,但页面责任与系统设置分离:
|
||||
|
||||
- `电视直播` 迁移原直播源配置,继续管理 Earth 媒体面板内容源。
|
||||
- `品牌标识` 管理 Earth HUD 的品牌资源。`Logo 地址` 与 `标题图地址` 使用字段内上传控件,上传按钮保持 `TactileButton` 的 primary 样式;图片拖到对应字段时显示低饱和拖拽反应,避免回到旧的全局“选择资产/上传”工具栏。
|
||||
- `国界精度` 管理 Earth 静态国界资产:provider 状态、低精 fallback、高精 manifest/PMTiles、源配置 JSON 和构建动作。
|
||||
- `地球底图`、`图层资源`、`三维素材`、`新闻锚点策略` 是占位页,只显示模块待接入,不造假接口或假数据。
|
||||
|
||||
@@ -421,6 +447,7 @@ Admin 的状态标签统一走 [StatusText](/home/ray/dev/linkong/planet/fronten
|
||||
4. 不要用 `overflow: hidden` 掩盖结构问题
|
||||
5. 不要为了摘要卡完整显示去压缩主工作区
|
||||
6. 自定义滚动条必须是浮层,不得挤压内容宽度
|
||||
7. Admin shell 依赖 root `height: 100%` 高度链,不在根工作区重新写精确 `100vh`
|
||||
|
||||
详细经验见:
|
||||
|
||||
|
||||
@@ -210,6 +210,10 @@
|
||||
3. 真正滚动节点是否明确 `overflow: auto`
|
||||
4. 中间包装层是否偷偷改了布局语义
|
||||
|
||||
当前 Admin 和 Docs 根 shell 依赖 `html` / `body` / `#root` 的 `height: 100%`
|
||||
链路。不要在这些嵌入式工作区根容器上重新写精确 `100vh` / `100vw`;
|
||||
弹窗、浮层和窄屏安全边界可以继续使用 `calc(100vh - ...)` 作为最大尺寸约束。
|
||||
|
||||
### 5. UI 状态和显示状态不同步
|
||||
|
||||
Earth 相关改动里反复出现:
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
1. 打开 `http://localhost:3000/login`,点击表单下方"注册账户"。
|
||||
2. 在 `/register` 填写:
|
||||
- **用户名**:3–50 位字符,登录时使用
|
||||
- **邮箱**:用于接收验证码,可在账户设置中修改
|
||||
- **邮箱**:用于接收验证码;当前版本如需修改邮箱,请联系管理员在用户管理中维护
|
||||
- **密码**:至少 8 位
|
||||
3. 提交后会跳到验证页,已将 6 位验证码发到你的邮箱。10 分钟内有效。
|
||||
4. 输入验证码,点击"验证并登录"。验证通过后系统会自动写入登录态并跳到控制台。
|
||||
@@ -52,23 +52,23 @@
|
||||
3. 收到验证码后,在下一步填入验证码 + 新密码(至少 8 位),点击"重置密码"。
|
||||
4. 系统会跳回 `/login`,用新密码登录即可。
|
||||
|
||||
## 账户设置
|
||||
## 账户区与退出
|
||||
|
||||
控制台右上角点击你的用户名进入账户设置,可以:
|
||||
控制台左侧底部的账户区会显示当前用户名、版本号和主题切换。当前版本还没有登录后的自助账户设置页:
|
||||
|
||||
- 修改密码:输入当前密码 + 新密码
|
||||
- 修改邮箱:输入新邮箱后系统会发验证码到新地址,验证通过后才生效
|
||||
- 查看权限组:列出你目前拥有的 Gatekeeper 权限组(`docs_user` / `docs_developer` / `docs_admin`)
|
||||
- 登出:清除当前会话
|
||||
- 忘记密码或需要重置密码时,使用 `/forgot-password` 邮件验证码流程
|
||||
- 邮箱、角色和 Gatekeeper 权限组由管理员在 `/users` 维护
|
||||
- 点击账户区的退出图标会清除当前会话并返回登录页
|
||||
|
||||
## 控制台总览
|
||||
|
||||
控制台 `http://localhost:3000/admin` 使用 React + Ant Design,左侧菜单按工作域组织。
|
||||
控制台 `http://localhost:3000/admin` 使用 React + Tactile UI / Radix 基础组件和 lucide 图标,左侧菜单按工作域组织。
|
||||
|
||||
| 页面 | 路由 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| 仪表盘 | `/admin` | 系统概览 |
|
||||
| 智能星球 | `/earth` | 跳到公开智能星球页面 |
|
||||
| 文档 | `/docs` | 打开文档站并按 Gatekeeper 权限查看可见文档 |
|
||||
| 数据源 | `/datasources` | 数据源目录、触发采集 |
|
||||
| 采集数据 | `/data` | 已落库的数据 |
|
||||
| BGP 观测 | `/bgp` | BGP 专题观测 |
|
||||
@@ -86,7 +86,7 @@
|
||||
|
||||
## 配置数据采集器
|
||||
|
||||
`/collection-management?tab=collector_credentials` 是"采集器"页。这里统一维护所有采集器的连接配置,不仅是凭证。旧链接 `/settings?tab=collector_credentials` 会自动跳转到这个入口;数据源目录仍保留在 `/datasources`。
|
||||
`/collection-management?section=collector_credentials` 是"采集器"页。这里统一维护所有采集器的连接配置,不仅是凭证;数据源目录仍保留在 `/datasources`。
|
||||
|
||||
操作步骤:
|
||||
|
||||
@@ -130,7 +130,7 @@
|
||||
|
||||
操作步骤:
|
||||
|
||||
1. `/collection-management?tab=collector_credentials` 选择 `AISStream 实时船舶 : aisstream_vessels`
|
||||
1. `/collection-management?section=collector_credentials` 选择 `AISStream 实时船舶 : aisstream_vessels`
|
||||
2. 在 `AISStream 凭证` 填入 API Key
|
||||
3. Endpoint 保持默认 `wss://stream.aisstream.io/v0/stream`
|
||||
4. 点击插头图标进行连接测试,确认显示 `可用`
|
||||
@@ -144,11 +144,12 @@
|
||||
|
||||
## 配置 AI 凭证
|
||||
|
||||
`/ai?tab=providers` 是 AI 模型管理入口。包含三个核心子 tab:
|
||||
`/ai?section=integrations` 是 AI 模型管理入口。主要分区包括:
|
||||
|
||||
- `模型供应商`:默认 LLM provider、模型、Base URL、API Key、本地 `aiprovider` 代理和连接测试
|
||||
- `工具`:通过下拉菜单选择具体工具,当前支持 WebSearch 和 OCR
|
||||
- `工具调用`:通过下拉菜单选择具体工具,当前支持 WebSearch 和 OCR
|
||||
- `提示词`:通过功能入口下拉菜单选择新闻汉化、告警研判、BGP 简报等 LLM 任务,手动调整提示词或重置为缺省
|
||||
- `Playground`:真实会话、预设请求和 AI Provider 状态调试
|
||||
|
||||
### 模型供应商
|
||||
|
||||
@@ -173,7 +174,7 @@ Base URL 输入框尾端的插头图标会触发连接测试。测试通过会
|
||||
|
||||
选择功能入口后,页面会显示当前提示词、是否已自定义、缺省版本和重置按钮。保存只影响该功能入口;重置会恢复当前发布包中的缺省提示词。业务事实、上下文和输出 schema 仍由后端按功能入口自动传入。
|
||||
|
||||
旧链接 `/settings?tab=ai` 会跳到 `/ai?tab=providers`。
|
||||
旧的 AI 配置入口不再放在系统设置里;`/playground` 会跳到 `/ai?section=playground`。
|
||||
|
||||
## 系统设置
|
||||
|
||||
@@ -190,7 +191,7 @@ Base URL 输入框尾端的插头图标会触发连接测试。测试通过会
|
||||
|
||||
`/earth-content` 位于控制台“运维与配置”下,面向智能星球前端体验资源:
|
||||
|
||||
- **品牌资源**:维护智能星球 HUD 使用的 logo、标题图、标题文本、副标题和描述;上传的图片会保存为智能星球品牌资产并立即供智能星球页面读取。
|
||||
- **品牌资源**:维护智能星球 HUD 使用的 logo、标题图、标题文本、副标题和描述。`Logo 地址` 和 `标题图地址` 字段内各有独立的“上传”按钮,也可以把图片直接拖到对应字段;上传成功后字段会写入新的资产地址,保存品牌配置后供智能星球页面读取。
|
||||
- **关于**:维护智能星球设置面板里的关于卡片,包括 logo、眉标、标题、版本、描述和元信息。
|
||||
- **电视直播**:维护智能星球媒体面板里的直播源。
|
||||
- **新闻内容**:按 RSS 来源和手动新闻组查看新闻。RSS 新闻保持只读;手动新闻组可以新增、批量导入 JSON、编辑、删除和重新处理。
|
||||
@@ -244,7 +245,7 @@ Base URL 输入框尾端的插头图标会触发连接测试。测试通过会
|
||||
|
||||
## AI 测试台
|
||||
|
||||
`/ai?tab=playground` 用于真实分析链路调试。可以:
|
||||
`/ai?section=playground` 用于真实分析链路调试。可以:
|
||||
|
||||
- 选择当前 provider
|
||||
- 用预设请求或自定义 prompt 触发分析
|
||||
|
||||
@@ -28,6 +28,9 @@
|
||||
| AI Provider | AI Provider | 服务名,保留英文 |
|
||||
| tool | 工具 | Web Search、OCR 等工具配置 |
|
||||
| Playground | Playground | 交互调试入口,保留英文 |
|
||||
| branding | 品牌标识 | `/earth-content` 中的 Earth HUD 品牌配置分区 |
|
||||
| brand assets | 品牌资源 | Logo、标题图和相关 HUD 文案资源 |
|
||||
| title image | 标题图 | Earth HUD 标题图片,不写作“标题图片地址”以外的混合名 |
|
||||
|
||||
## 数据类型
|
||||
|
||||
|
||||
@@ -32,11 +32,12 @@
|
||||
|
||||
进入 `/admin` 仪表盘后,建议按这个顺序熟悉控制台:
|
||||
|
||||
1. `/collection-management?tab=collector_credentials`:选一个采集器,点插头图标做连接测试。免费 collector(开源 BGP 等)通常直接可用;像 `AISStream`、`BarentsWatch` 这类需要凭证的,需要先填 API Key/Client Secret
|
||||
2. `/ai?tab=providers`:填一个 LLM provider(例如 `minimax` / `openai`)、模型名、Base URL、API Key,点 Base URL 末端的插头测试连接。WebSearch / OCR 工具可选
|
||||
3. `/datasources` 或 `/data`:看采集器是否已经产出数据。有限采集器看 `/datasources -> 内置源`,不勾选时点“触发全部”,勾选后主按钮会变成“触发已选 N”;右上角队列按钮可查看进度。AISStream / WebSocket 长连接看 `/datasources -> 实时源` 的健康状态和计数
|
||||
4. `/alerts/system`:看系统告警是否正常
|
||||
5. `/users`(仅 `super_admin`):根据需要给同事开账号或调权限组
|
||||
1. `/collection-management?section=collector_credentials`:选一个采集器,点插头图标做连接测试。免费 collector(开源 BGP 等)通常直接可用;像 `AISStream`、`BarentsWatch` 这类需要凭证的,需要先填 API Key/Client Secret
|
||||
2. `/ai?section=integrations`:填一个 LLM provider(例如 `minimax` / `openai`)、模型名、Base URL、API Key,点 Base URL 末端的插头测试连接。WebSearch / OCR 工具可选
|
||||
3. `/earth-content?section=brand`:在“品牌标识”里维护智能星球的 Logo 和标题图;对应地址字段内的“上传”按钮支持选择文件,也支持把图片直接拖到字段上,保存后会应用到智能星球 HUD
|
||||
4. `/datasources` 或 `/data`:看采集器是否已经产出数据。有限采集器看 `/datasources -> 内置源`,不勾选时点“触发全部”,勾选后主按钮会变成“触发已选 N”;右上角队列按钮可查看进度。AISStream / WebSocket 长连接看 `/datasources -> 实时源` 的健康状态和计数
|
||||
5. `/alerts/system`:看系统告警是否正常
|
||||
6. `/users`(仅 `super_admin`):根据需要给同事开账号或调权限组
|
||||
|
||||
## 4. 打开智能星球
|
||||
|
||||
|
||||
@@ -16,12 +16,17 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.71.1`
|
||||
- `dev` 当前开发分支历史推导到:`0.74.2`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `0.74.2` | bugfix | `dev` | `pending` | 收敛 agent harness 到根规则和 Codex skills,删除旧 Claude command 重复入口,并强化视觉证据路径解析与 OCR fallback 规则 |
|
||||
| `0.74.1` | improvement | `dev` | `pending` | 将品牌标识上传收敛到 Logo/标题图字段内,新增字段级拖拽反馈和 Tactile UI primary 上传按钮,并同步中英文使用文档 |
|
||||
| `0.74.0` | feature | `dev` | `pending` | 扩展统一 i18n 到 Web Earth 动态入口、控制台/API 错误和公开页面,修复 Earth 通知胶囊、语言 switch、品牌栏、legend、tooltip、新闻/TV 英文态裁切与中文残留,并加入 harness 回归覆盖 |
|
||||
| `0.73.0` | feature | `dev` | `pending` | 新增前端统一 i18n、控制台语言/主题偏好入口、英文态 legacy 过渡翻译和 admin 一屏/状态指示器布局验证 |
|
||||
| `0.72.0` | feature | `dev` | `pending` | 新增完整 agent harness、单一 AGENTS 入口、Earth News smoke 覆盖和 collector 结构化日志清理,并同步控制台/Earth/Docs 响应式维护文档 |
|
||||
| `0.71.1` | bugfix | `dev` | `pending` | 修复 Earth 新闻区域切换、滚动条/面板/巡航一致性和新闻精修队列饿死问题,并补充 agent harness 与双语维护文档 |
|
||||
| `0.71.0` | feature | `dev` | `pending` | Motion Agent 升级为 Web/UE 共用双向控制与真实识别服务,新增 Earth 手动新闻工作流、来源多样化,并完善启动/测试 harness 与双语文档 |
|
||||
| `0.70.0` | feature | `dev` | `pending` | 新增后端枚举契约治理、Earth 新闻分类/Breaking 链路和船只当前状态快照,清理错误视口刷新逻辑并同步双语文档 |
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"dayjs": "^1.11.10",
|
||||
"echarts": "^6.0.0",
|
||||
"i18next": "26.3.3",
|
||||
"lucide-react": "^1.16.0",
|
||||
"mermaid": "^11.15.0",
|
||||
"pbf": "^4.0.1",
|
||||
@@ -29,6 +30,7 @@
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hook-form": "^7.76.0",
|
||||
"react-i18next": "17.0.8",
|
||||
"react-resizable": "^3.1.3",
|
||||
"react-router-dom": "^6.21.0",
|
||||
"simplex-noise": "^4.0.1",
|
||||
@@ -84,6 +86,8 @@
|
||||
|
||||
"@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw=="],
|
||||
|
||||
"@babel/runtime": ["@babel/runtime@7.29.7", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],
|
||||
|
||||
"@babel/template": ["@babel/template@7.28.6", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ=="],
|
||||
|
||||
"@babel/traverse": ["@babel/traverse@7.29.0", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/types": "^7.29.0", "debug": "^4.3.1" } }, "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA=="],
|
||||
@@ -556,6 +560,10 @@
|
||||
|
||||
"hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
||||
|
||||
"html-parse-stringify": ["html-parse-stringify@3.0.1", "", { "dependencies": { "void-elements": "3.1.0" } }, "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg=="],
|
||||
|
||||
"i18next": ["i18next@26.3.3", "", { "peerDependencies": { "typescript": "^5 || ^6" }, "optionalPeers": ["typescript"] }, "sha512-aYVegyBdXSO93CMMihvr47jI7GHSOcIahMpJX+qzUXDzW4xDJf2uenIA+45vDU+YhiVdcfsql70AC9RVdMNrHg=="],
|
||||
|
||||
"iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
|
||||
|
||||
"import-meta-resolve": ["import-meta-resolve@4.2.0", "", {}, "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg=="],
|
||||
@@ -632,6 +640,8 @@
|
||||
|
||||
"react-hook-form": ["react-hook-form@7.76.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17 || ^18 || ^19" } }, "sha512-eKtLGgFeSgkHqQD8J59AMZ9a4uD1D83iSIzt4YlTGD7liDen5rrjcUO1rVIGd9yC1gofryjtHbv+4ny4hkLWlw=="],
|
||||
|
||||
"react-i18next": ["react-i18next@17.0.8", "", { "dependencies": { "@babel/runtime": "^7.29.2", "html-parse-stringify": "^3.0.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "i18next": ">= 26.2.0", "react": ">= 16.8.0", "typescript": "^5 || ^6" }, "optionalPeers": ["typescript"] }, "sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw=="],
|
||||
|
||||
"react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
|
||||
|
||||
"react-refresh": ["react-refresh@0.17.0", "", {}, "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ=="],
|
||||
@@ -702,6 +712,8 @@
|
||||
|
||||
"vite": ["vite@5.4.21", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": "bin/vite.js" }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="],
|
||||
|
||||
"void-elements": ["void-elements@3.1.0", "", {}, "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w=="],
|
||||
|
||||
"ws": ["ws@8.18.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],
|
||||
|
||||
"xmlhttprequest-ssl": ["xmlhttprequest-ssl@2.1.2", "", {}, "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ=="],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.71.1",
|
||||
"version": "0.74.2",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
@@ -20,6 +20,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"dayjs": "^1.11.10",
|
||||
"echarts": "^6.0.0",
|
||||
"i18next": "26.3.3",
|
||||
"lucide-react": "^1.16.0",
|
||||
"mermaid": "^11.15.0",
|
||||
"pbf": "^4.0.1",
|
||||
@@ -28,6 +29,7 @@
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hook-form": "^7.76.0",
|
||||
"react-i18next": "17.0.8",
|
||||
"react-resizable": "^3.1.3",
|
||||
"react-router-dom": "^6.21.0",
|
||||
"simplex-noise": "^4.0.1",
|
||||
|
||||
@@ -1157,15 +1157,18 @@
|
||||
|
||||
.earth-mobile-tv-overview-tags {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 1px;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.earth-mobile-tv-overview-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 20px;
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
@@ -1173,8 +1176,9 @@
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--hud-text);
|
||||
font-size: 0.62rem;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
line-height: 1.15;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.earth-mobile-tv-overview-tag--status {
|
||||
@@ -1817,11 +1821,15 @@
|
||||
.earth-mobile-settings-pill {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--hud-text-soft);
|
||||
padding: 10px 14px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.earth-mobile-settings-pill.is-active {
|
||||
@@ -1835,6 +1843,9 @@
|
||||
}
|
||||
|
||||
.earth-mobile-settings-chip {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
border: 1px solid rgba(212, 227, 244, 0.12);
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
@@ -1844,6 +1855,9 @@
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.18s ease,
|
||||
@@ -1900,11 +1914,13 @@
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
|
||||
.earth-mobile-settings-switch input:checked + .earth-mobile-settings-switch-track {
|
||||
.earth-mobile-settings-switch input:checked + .earth-mobile-settings-switch-track,
|
||||
.earth-mobile-settings-switch.is-checked .earth-mobile-settings-switch-track {
|
||||
background: rgba(122, 180, 255, 0.34);
|
||||
}
|
||||
|
||||
.earth-mobile-settings-switch input:checked + .earth-mobile-settings-switch-track::after {
|
||||
.earth-mobile-settings-switch input:checked + .earth-mobile-settings-switch-track::after,
|
||||
.earth-mobile-settings-switch.is-checked .earth-mobile-settings-switch-track::after {
|
||||
transform: translate(16px, -50%);
|
||||
}
|
||||
|
||||
@@ -2145,10 +2161,10 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
.earth-status-message,
|
||||
.earth-error-message {
|
||||
position: absolute;
|
||||
top: calc(var(--hud-offset) + calc(2px * var(--hud-scale)));
|
||||
top: calc(var(--hud-offset) + calc(44px * var(--hud-scale)));
|
||||
left: min(
|
||||
calc(var(--hud-offset) + calc(340px * var(--hud-scale)) + calc(12px * var(--hud-scale))),
|
||||
calc(100vw - min(calc(440px * var(--hud-scale)), 74vw) - var(--hud-offset))
|
||||
calc(100vw - min(calc(620px * var(--hud-scale)), 82vw) - var(--hud-offset))
|
||||
);
|
||||
transform: translateY(-18px);
|
||||
display: none;
|
||||
@@ -2172,8 +2188,8 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
text-align: left;
|
||||
min-width: min(calc(160px * var(--hud-scale)), 58vw);
|
||||
max-width: min(calc(440px * var(--hud-scale)), 74vw);
|
||||
min-width: 0;
|
||||
max-width: min(calc(620px * var(--hud-scale)), 82vw);
|
||||
color: var(--hud-text);
|
||||
opacity: 0;
|
||||
transition:
|
||||
@@ -2236,6 +2252,7 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Loading: three-dot sequential pulse */
|
||||
@@ -2869,6 +2886,7 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
.earth-settings-segmented-btn {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--hud-text-soft);
|
||||
@@ -2878,6 +2896,9 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
font-size: calc(0.7rem * var(--hud-scale));
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 0.18s ease,
|
||||
@@ -2979,6 +3000,9 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
}
|
||||
|
||||
.earth-settings-chip {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
border: 1px solid rgba(212, 227, 244, 0.1);
|
||||
border-radius: 999px;
|
||||
background:
|
||||
@@ -2990,6 +3014,9 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
font-size: calc(0.7rem * var(--hud-scale));
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.18s ease,
|
||||
@@ -3253,12 +3280,18 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: calc(38px * var(--hud-scale));
|
||||
height: calc(22px * var(--hud-scale));
|
||||
flex: 0 0 auto;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.earth-settings-switch input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.earth-settings-switch-track {
|
||||
@@ -3285,12 +3318,14 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
|
||||
.earth-settings-switch input:checked + .earth-settings-switch-track {
|
||||
.earth-settings-switch input:checked + .earth-settings-switch-track,
|
||||
.earth-settings-switch.is-checked .earth-settings-switch-track {
|
||||
background: linear-gradient(180deg, rgba(143, 185, 255, 0.72), rgba(104, 147, 221, 0.78));
|
||||
border-color: rgba(223, 236, 252, 0.28);
|
||||
}
|
||||
|
||||
.earth-settings-switch input:checked + .earth-settings-switch-track::after {
|
||||
.earth-settings-switch input:checked + .earth-settings-switch-track::after,
|
||||
.earth-settings-switch.is-checked .earth-settings-switch-track::after {
|
||||
transform: translate(calc(16px * var(--hud-scale)), -50%);
|
||||
}
|
||||
|
||||
|
||||
@@ -145,6 +145,22 @@
|
||||
.hud-panel-brand .earth-brand--en .earth-brand__subtitle,
|
||||
.hud-panel-brand .earth-brand--en .earth-brand__description {
|
||||
font-family: "Roboto Condensed", "Arial Narrow", "Trebuchet MS", "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
white-space: normal;
|
||||
word-break: normal;
|
||||
overflow-wrap: normal;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.hud-panel-brand .earth-brand--en .earth-brand__subtitle {
|
||||
font-size: calc(0.58rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.hud-panel-brand .earth-brand--en .earth-brand__description {
|
||||
font-size: calc(0.5rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
/* ── Info detail panel (floating, positioned near click by JS) ── */
|
||||
@@ -152,7 +168,7 @@
|
||||
.hud-panel-info {
|
||||
position: absolute;
|
||||
z-index: 50;
|
||||
width: min(calc(300px * var(--hud-scale)), calc(100vw - 32px));
|
||||
width: min(calc(340px * var(--hud-scale)), calc(100vw - 32px));
|
||||
border-radius: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
@@ -349,12 +365,17 @@
|
||||
}
|
||||
|
||||
.info-card-label {
|
||||
min-width: 0;
|
||||
max-width: 42%;
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.68rem * var(--hud-scale));
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
transition: color 0.18s ease;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
@@ -365,17 +386,35 @@
|
||||
}
|
||||
|
||||
.info-card-value {
|
||||
min-width: 0;
|
||||
color: var(--hud-text);
|
||||
font-weight: 600;
|
||||
font-size: calc(0.82rem * var(--hud-scale));
|
||||
line-height: 1.45;
|
||||
text-align: right;
|
||||
max-width: calc(180px * var(--hud-scale));
|
||||
max-width: calc(220px * var(--hud-scale));
|
||||
word-break: break-word;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
|
||||
.info-card-source-tag {
|
||||
display: inline-flex;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
margin-left: calc(4px * var(--hud-scale));
|
||||
padding: 0 calc(5px * var(--hud-scale));
|
||||
border: 1px solid rgba(214, 229, 245, 0.14);
|
||||
border-radius: 999px;
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.64rem * var(--hud-scale));
|
||||
line-height: 1.35;
|
||||
vertical-align: middle;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Type-specific header accent colors */
|
||||
.info-card.cable .info-card-header {
|
||||
background: rgba(255, 200, 0, 0.12);
|
||||
@@ -681,15 +720,25 @@
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.info-card-compute-candidate-precision {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 44%;
|
||||
color: #cfe1ff;
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.info-card-compute-candidate-preview {
|
||||
position: relative;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: calc(96px * var(--hud-scale));
|
||||
background: transparent;
|
||||
color: #c9dcff;
|
||||
border: 1px solid rgba(214, 229, 245, 0.18);
|
||||
@@ -697,6 +746,9 @@
|
||||
cursor: pointer;
|
||||
padding: 2px 6px;
|
||||
font-size: calc(0.68rem * var(--hud-scale));
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.info-card-compute-candidate-preview:hover {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
/* Lives inside .earth-left-column — narrower than brand panel intentionally */
|
||||
border-radius: 0;
|
||||
padding: 0;
|
||||
width: calc(260px * var(--hud-scale));
|
||||
width: calc(276px * var(--hud-scale));
|
||||
z-index: 10;
|
||||
overflow: hidden;
|
||||
margin-top: calc(12px * var(--hud-scale));
|
||||
@@ -184,7 +184,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(8px * var(--hud-scale));
|
||||
padding: calc(9px * var(--hud-scale)) calc(10px * var(--hud-scale));
|
||||
padding: calc(9px * var(--hud-scale)) calc(12px * var(--hud-scale));
|
||||
border-bottom: 1px solid var(--hud-line);
|
||||
transition: background 0.14s ease;
|
||||
min-height: calc(56px * var(--hud-scale));
|
||||
@@ -241,6 +241,9 @@
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
line-height: 1.2;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ── Toggle switch ────────────────────────────────────────────── */
|
||||
@@ -329,12 +332,13 @@
|
||||
appearance: none;
|
||||
position: absolute;
|
||||
top: calc(4px * var(--hud-scale));
|
||||
left: calc(19px * var(--hud-scale));
|
||||
left: calc(21px * var(--hud-scale));
|
||||
z-index: 2;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: calc(16px * var(--hud-scale));
|
||||
max-width: calc(38px * var(--hud-scale));
|
||||
height: calc(16px * var(--hud-scale));
|
||||
padding: 0 calc(4px * var(--hud-scale));
|
||||
border: 1px solid rgba(255, 226, 186, 0.62);
|
||||
@@ -348,6 +352,9 @@
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
filter 0.16s ease,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
left: var(--hud-offset);
|
||||
border-radius: 0;
|
||||
padding: 0;
|
||||
width: min(calc(200px * var(--hud-scale)), calc(100vw - 32px));
|
||||
width: min(calc(280px * var(--hud-scale)), calc(100vw - 32px));
|
||||
z-index: 10;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -51,14 +51,17 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: calc(3px * var(--hud-scale)) calc(7px * var(--hud-scale));
|
||||
border-radius: calc(4px * var(--hud-scale));
|
||||
border: 1px solid rgba(120, 180, 255, 0.2);
|
||||
background: rgba(120, 180, 255, 0.12);
|
||||
color: var(--hud-accent-strong);
|
||||
font-size: calc(0.68rem * var(--hud-scale));
|
||||
letter-spacing: 0.08em;
|
||||
letter-spacing: 0.02em;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* ── Bar action buttons ───────────────────────────────────────── */
|
||||
@@ -92,6 +95,7 @@
|
||||
.legend-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
padding: calc(4px * var(--hud-scale)) 0;
|
||||
overflow-y: auto;
|
||||
max-height: calc(220px * var(--hud-scale));
|
||||
@@ -110,6 +114,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(8px * var(--hud-scale));
|
||||
min-width: 0;
|
||||
padding: calc(5px * var(--hud-scale)) calc(10px * var(--hud-scale));
|
||||
}
|
||||
|
||||
@@ -135,6 +140,9 @@
|
||||
}
|
||||
|
||||
.legend-label {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
color: var(--hud-text);
|
||||
font-size: calc(0.78rem * var(--hud-scale));
|
||||
font-weight: 400;
|
||||
@@ -142,6 +150,7 @@
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
/* ── Layout-expanded ──────────────────────────────────────────── */
|
||||
@@ -156,7 +165,7 @@
|
||||
position: fixed;
|
||||
left: 8px;
|
||||
bottom: calc(84px + var(--safe-bottom));
|
||||
width: min(172px, calc(100vw - 16px));
|
||||
width: min(208px, calc(100vw - 16px));
|
||||
z-index: 205;
|
||||
}
|
||||
|
||||
|
||||
@@ -306,6 +306,8 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: calc(6px * var(--hud-scale));
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: calc(30px * var(--hud-scale));
|
||||
border: 1px solid rgba(201, 225, 247, 0.1);
|
||||
border-radius: calc(12px * var(--hud-scale));
|
||||
@@ -330,6 +332,11 @@
|
||||
}
|
||||
|
||||
.news-filter-pill strong {
|
||||
min-width: 0;
|
||||
max-width: calc(160px * var(--hud-scale));
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--hud-accent-strong);
|
||||
font-size: calc(0.7rem * var(--hud-scale));
|
||||
font-weight: 700;
|
||||
@@ -391,6 +398,8 @@
|
||||
}
|
||||
|
||||
.news-filter-chip {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
border: 1px solid rgba(201, 225, 247, 0.12);
|
||||
border-radius: calc(14px * var(--hud-scale));
|
||||
padding: calc(7px * var(--hud-scale)) calc(10px * var(--hud-scale));
|
||||
@@ -398,6 +407,10 @@
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
font: inherit;
|
||||
font-size: calc(0.74rem * var(--hud-scale));
|
||||
line-height: 1.25;
|
||||
text-align: center;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@@ -539,6 +552,7 @@
|
||||
|
||||
.news-story-meta {
|
||||
justify-content: space-between;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.news-story-tags {
|
||||
@@ -549,6 +563,7 @@
|
||||
.news-story-time,
|
||||
.news-story-origin,
|
||||
.news-story-tag {
|
||||
min-width: 0;
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.66rem * var(--hud-scale));
|
||||
}
|
||||
@@ -563,6 +578,7 @@
|
||||
|
||||
.news-story-origin {
|
||||
color: rgba(188, 212, 238, 0.56);
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -582,9 +598,13 @@
|
||||
}
|
||||
|
||||
.news-story-tag {
|
||||
max-width: 100%;
|
||||
border-radius: 999px;
|
||||
padding: calc(3px * var(--hud-scale)) calc(7px * var(--hud-scale));
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
line-height: 1.25;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.news-story-tag--breaking {
|
||||
|
||||
@@ -254,19 +254,31 @@
|
||||
.earth-toolbar-btn .icon,
|
||||
.earth-toolbar-hub-btn .material-symbols-rounded {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
z-index: 4;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.earth-toolbar-btn .icon {
|
||||
.earth-toolbar-btn .icon,
|
||||
.earth-toolbar-hub-btn .material-symbols-rounded,
|
||||
.earth-zoom-btn > span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: transform 0.16s ease, opacity 0.16s ease;
|
||||
color: rgba(243, 244, 246, 0.9);
|
||||
text-shadow: 0 1.5px 3px rgba(0, 0, 0, 0.5);
|
||||
transition:
|
||||
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
color 0.3s ease,
|
||||
opacity 0.16s ease;
|
||||
backface-visibility: hidden;
|
||||
-webkit-backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.earth-zoom-btn > span {
|
||||
position: relative;
|
||||
z-index: 4;
|
||||
}
|
||||
|
||||
.earth-toolbar-btn .material-symbols-rounded,
|
||||
.earth-toolbar-hub-btn .material-symbols-rounded {
|
||||
font-size: calc(21px * var(--toolbar-scale));
|
||||
@@ -299,22 +311,34 @@
|
||||
--btn-scale: 1;
|
||||
--press-offset: 0px;
|
||||
--float-offset: 0px;
|
||||
--mouse-x: 0.5;
|
||||
--mouse-y: 0.5;
|
||||
--toolbar-atmosphere-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.25);
|
||||
--toolbar-atmosphere-hover: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.55);
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
transform-style: preserve-3d;
|
||||
transform-origin: center center;
|
||||
will-change: transform, box-shadow;
|
||||
z-index: 2;
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
border: none;
|
||||
outline: none;
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.085), transparent 38%),
|
||||
rgba(255, 255, 255, var(--toolbar-glass-opacity));
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.16) 0%,
|
||||
rgba(255, 255, 255, 0.02) 40%,
|
||||
rgba(15, 23, 42, 0.35) 75%,
|
||||
rgba(3, 7, 18, 0.85) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 8px 28px rgba(0, 0, 0, 0.38),
|
||||
inset 0 1.5px 2px rgba(255, 255, 255, 0.22),
|
||||
inset 0 -1.5px 2px rgba(0, 0, 0, 0.28);
|
||||
backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(108%) brightness(0.92);
|
||||
-webkit-backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(108%) brightness(0.92);
|
||||
0 8px 24px -4px rgba(0, 0, 0, 0.65),
|
||||
inset 0 0 1.5px 1.2px rgba(255, 255, 255, 0.15),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.45),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.03),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.06);
|
||||
backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(130%);
|
||||
-webkit-backdrop-filter: blur(var(--toolbar-glass-blur, 16px)) saturate(130%);
|
||||
|
||||
transform:
|
||||
translate3d(
|
||||
@@ -325,121 +349,182 @@
|
||||
scale(var(--btn-scale));
|
||||
|
||||
transition:
|
||||
transform 0.22s ease,
|
||||
box-shadow 0.22s ease,
|
||||
background 0.22s ease,
|
||||
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
box-shadow 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
background 0.4s cubic-bezier(0.16, 1, 0.3, 1),
|
||||
opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.liquid-glass-surface::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
top: 4%;
|
||||
left: 15%;
|
||||
width: 70%;
|
||||
height: 32%;
|
||||
border-radius: 50% 50% 45% 45% / 65% 65% 35% 35%;
|
||||
background:
|
||||
radial-gradient(circle at 32% 20%, rgba(255, 255, 255, 0.13), transparent 34%),
|
||||
radial-gradient(circle at 54% 54%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.035), transparent 58%);
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
rgba(255, 255, 255, 0.38) 0%,
|
||||
rgba(255, 255, 255, 0.1) 50%,
|
||||
rgba(255, 255, 255, 0) 100%
|
||||
);
|
||||
filter: blur(0.4px);
|
||||
opacity: 1;
|
||||
pointer-events: none;
|
||||
transform: translate3d(calc(var(--elastic-x) * 0.08), calc(var(--elastic-y) * 0.08), 0);
|
||||
transition: opacity 0.18s ease, transform 0.18s ease;
|
||||
transform:
|
||||
translate(
|
||||
calc((var(--mouse-x, 0.5) - 0.5) * 5px),
|
||||
calc((var(--mouse-y, 0.5) - 0.5) * 3px)
|
||||
);
|
||||
transform-origin: top center;
|
||||
transition: transform 0.25s ease-out;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.liquid-glass-surface::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
bottom: -10%;
|
||||
left: 12%;
|
||||
width: 76%;
|
||||
height: 35%;
|
||||
border-radius: 50%;
|
||||
background:
|
||||
radial-gradient(circle at 50% 50%, transparent 58%, rgba(0, 0, 0, 0.1) 100%);
|
||||
box-shadow:
|
||||
inset 0 0 0 0.5px rgba(255, 255, 255, 0.06);
|
||||
opacity: 1;
|
||||
radial-gradient(
|
||||
ellipse at bottom,
|
||||
var(--toolbar-atmosphere-color) 0%,
|
||||
rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.02) 70%,
|
||||
rgba(0, 0, 0, 0) 100%
|
||||
);
|
||||
filter: blur(1px);
|
||||
opacity: 0.9;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.18s ease, box-shadow 0.18s ease;
|
||||
transform:
|
||||
translate(
|
||||
calc((var(--mouse-x, 0.5) - 0.5) * -3px),
|
||||
calc((var(--mouse-y, 0.5) - 0.5) * -2px)
|
||||
);
|
||||
transition:
|
||||
transform 0.25s ease-out,
|
||||
opacity 0.3s ease;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.earth-toolbar-hub-btn.liquid-glass-surface {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.095), transparent 40%),
|
||||
rgba(255, 255, 255, 0.07);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.18) 0%,
|
||||
rgba(255, 255, 255, 0.025) 42%,
|
||||
rgba(15, 23, 42, 0.32) 74%,
|
||||
rgba(3, 7, 18, 0.82) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 9px 30px rgba(0, 0, 0, 0.4),
|
||||
inset 0 1.5px 2px rgba(255, 255, 255, 0.24),
|
||||
inset 0 -1.5px 2px rgba(0, 0, 0, 0.3);
|
||||
0 9px 26px -4px rgba(0, 0, 0, 0.68),
|
||||
inset 0 0 1.8px 1.3px rgba(255, 255, 255, 0.17),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.5),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.04),
|
||||
inset 0 7px 13px rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover {
|
||||
--btn-scale: 1.03;
|
||||
--press-offset: -1px;
|
||||
--btn-scale: 1.05;
|
||||
--press-offset: -3px;
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.14), transparent 40%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.12), transparent 62%),
|
||||
rgba(255, 255, 255, 0.085);
|
||||
border-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.42);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.22) 0%,
|
||||
rgba(255, 255, 255, 0.04) 40%,
|
||||
rgba(15, 23, 42, 0.25) 75%,
|
||||
rgba(3, 7, 18, 0.8) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 40px rgba(0, 0, 0, 0.44),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.36),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover::before {
|
||||
opacity: 1;
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.2), transparent 36%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.14), transparent 62%);
|
||||
transform: translate3d(calc(var(--elastic-x) * 0.08), calc(var(--elastic-y) * 0.08 - 1px), 0);
|
||||
0 14px 28px -6px rgba(0, 0, 0, 0.8),
|
||||
0 0 15px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 1.8px 1.2px rgba(255, 255, 255, 0.22),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.65),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.04),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover::after {
|
||||
opacity: 1;
|
||||
box-shadow:
|
||||
inset 0 0 0 0.75px rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.16);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:hover .icon,
|
||||
.earth-toolbar-hub-btn.liquid-glass-surface:hover > .material-symbols-rounded,
|
||||
.earth-zoom-btn.liquid-glass-surface:hover > span {
|
||||
color: #ffffff;
|
||||
transform: scale(1.06);
|
||||
}
|
||||
|
||||
.liquid-glass-surface:active,
|
||||
.liquid-glass-surface.is-pressed {
|
||||
--btn-scale: 0.94;
|
||||
--press-offset: 3px;
|
||||
--btn-scale: 0.95;
|
||||
--press-offset: -1px;
|
||||
transition: transform 0.1s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
box-shadow:
|
||||
0 4px 14px rgba(0, 0, 0, 0.28),
|
||||
inset 0 1px 2px rgba(255, 255, 255, 0.18),
|
||||
inset 0 -1px 3px rgba(0, 0, 0, 0.34);
|
||||
0 5px 12px -3px rgba(0, 0, 0, 0.9),
|
||||
0 0 8px -2px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 1.5px 1.2px rgba(255, 255, 255, 0.18),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.55),
|
||||
inset 0 -1px 4px rgba(255, 255, 255, 0.01);
|
||||
}
|
||||
|
||||
.liquid-glass-surface.active {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.14), transparent 40%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.13), transparent 62%),
|
||||
rgba(255, 255, 255, 0.09);
|
||||
border-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.42);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.24) 0%,
|
||||
rgba(255, 255, 255, 0.045) 40%,
|
||||
rgba(15, 23, 42, 0.24) 75%,
|
||||
rgba(3, 7, 18, 0.78) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 40px rgba(0, 0, 0, 0.46),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.38),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.2);
|
||||
0 13px 28px -6px rgba(0, 0, 0, 0.78),
|
||||
0 0 16px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 1.9px 1.25px rgba(255, 255, 255, 0.24),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.66),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.04),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.11);
|
||||
}
|
||||
|
||||
.liquid-glass-surface.active:hover {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.16), transparent 40%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.17), transparent 64%),
|
||||
rgba(255, 255, 255, 0.1);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.28) 0%,
|
||||
rgba(255, 255, 255, 0.055) 40%,
|
||||
rgba(15, 23, 42, 0.22) 75%,
|
||||
rgba(3, 7, 18, 0.76) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 42px rgba(0, 0, 0, 0.48),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.42),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.18);
|
||||
0 15px 30px -6px rgba(0, 0, 0, 0.82),
|
||||
0 0 18px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 2px 1.25px rgba(255, 255, 255, 0.27),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.7),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.05),
|
||||
inset 0 6px 12px rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.earth-toolbar-cluster.is-expanded .earth-toolbar-hub-btn.liquid-glass-surface {
|
||||
background:
|
||||
radial-gradient(circle at 32% 22%, rgba(255, 255, 255, 0.15), transparent 42%),
|
||||
radial-gradient(circle at 52% 52%, rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.15), transparent 64%),
|
||||
rgba(255, 255, 255, 0.095);
|
||||
border-color: rgba(var(--toolbar-light-rgb, 91, 186, 255), 0.44);
|
||||
radial-gradient(
|
||||
circle at 35% 30%,
|
||||
rgba(255, 255, 255, 0.24) 0%,
|
||||
rgba(255, 255, 255, 0.045) 40%,
|
||||
rgba(15, 23, 42, 0.24) 75%,
|
||||
rgba(3, 7, 18, 0.78) 100%
|
||||
);
|
||||
box-shadow:
|
||||
0 12px 42px rgba(0, 0, 0, 0.48),
|
||||
inset 0 1.5px 3px rgba(255, 255, 255, 0.4),
|
||||
inset 0 -1.5px 3px rgba(0, 0, 0, 0.18);
|
||||
0 14px 30px -6px rgba(0, 0, 0, 0.82),
|
||||
0 0 17px -1px var(--toolbar-atmosphere-hover),
|
||||
inset 0 0 2px 1.25px rgba(255, 255, 255, 0.26),
|
||||
inset 0 1px 0.5px 0.2px rgba(255, 255, 255, 0.68),
|
||||
inset 0 -3px 8px rgba(255, 255, 255, 0.05),
|
||||
inset 0 7px 13px rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.earth-rotate-toggle .icon-play,
|
||||
|
||||
@@ -154,7 +154,9 @@
|
||||
}
|
||||
|
||||
.tv-panel-tag {
|
||||
flex: 0 0 auto;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
border: 1px solid rgba(137, 179, 217, 0.22);
|
||||
border-radius: calc(999px * var(--hud-scale));
|
||||
background: rgba(108, 153, 192, 0.12);
|
||||
@@ -164,6 +166,8 @@
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
letter-spacing: 0.04em;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.tv-panel-tag--status {
|
||||
|
||||
@@ -1211,6 +1211,16 @@
|
||||
</div>
|
||||
<div class="earth-mobile-settings-group" data-settings-tab-panel="system" hidden>
|
||||
<div class="earth-mobile-settings-title">系统</div>
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">星球语言</span>
|
||||
<span class="earth-mobile-settings-subtitle">同步 Docs 和控制台语言偏好</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented" role="group" aria-label="星球语言">
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-earth-locale="zh-CN" aria-pressed="true">中文</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-earth-locale="en-US" aria-pressed="false">English</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-actions">
|
||||
<button id="mobile-settings-reset" class="earth-mobile-action-btn earth-mobile-action-btn--ghost" type="button">重置设置</button>
|
||||
<a class="earth-mobile-action-btn" href="/admin" target="_blank" rel="noreferrer noopener">打开控制台</a>
|
||||
@@ -1769,6 +1779,16 @@
|
||||
<section class="earth-settings-section" data-settings-tab-panel="system" hidden>
|
||||
<div class="earth-settings-section-title">系统</div>
|
||||
<div class="earth-settings-list">
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">星球语言</span>
|
||||
<span class="earth-settings-item-subtitle">同步 Docs 和控制台语言偏好</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="星球语言">
|
||||
<button type="button" class="earth-settings-segmented-btn is-active" data-earth-locale="zh-CN" aria-pressed="true">中文</button>
|
||||
<button type="button" class="earth-settings-segmented-btn" data-earth-locale="en-US" aria-pressed="false">English</button>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
class="earth-settings-item earth-settings-link"
|
||||
href="/admin"
|
||||
|
||||
@@ -17,11 +17,25 @@ const BRANDS = {
|
||||
logoSrc: "/earth/assets/brand/earth-logo.png",
|
||||
titleSrc: "/earth/assets/brand/title-en.png",
|
||||
titleText: "Intelligent Planet Program",
|
||||
subtitle: "Physical-Universe Holography",
|
||||
description: "Satellites · Cables · Compute Infra",
|
||||
subtitle: "Reality Layer Situational Awareness System",
|
||||
description: "Satellites · Subsea Cables · Compute Infrastructure",
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_BRAND_TITLE_BY_VARIANT = {
|
||||
zh: BRANDS.zh.titleSrc,
|
||||
en: BRANDS.en.titleSrc,
|
||||
};
|
||||
|
||||
const LOCALIZED_FIELD_NAMES = {
|
||||
ariaLabel: ["aria_label", "ariaLabel"],
|
||||
titleAlt: ["title_alt", "titleAlt"],
|
||||
titleSrc: ["title_src", "titleSrc"],
|
||||
titleText: ["title_text", "titleText"],
|
||||
subtitle: ["subtitle"],
|
||||
description: ["description"],
|
||||
};
|
||||
|
||||
export function getDefaultBrandConfig(variant = DEFAULT_BRAND_LANGUAGE) {
|
||||
return BRANDS[variant] ?? BRANDS[DEFAULT_BRAND_LANGUAGE];
|
||||
}
|
||||
@@ -35,18 +49,65 @@ function escapeHtml(value = "") {
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function hasCjkText(value = "") {
|
||||
return /[\u3400-\u9fff]/.test(String(value ?? ""));
|
||||
}
|
||||
|
||||
function readConfigValue(config, keys = []) {
|
||||
for (const key of keys) {
|
||||
if (config[key] !== undefined && config[key] !== null && config[key] !== "") {
|
||||
return config[key];
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readLocalizedConfigValue(config, fieldName, variant, fallback) {
|
||||
const keys = LOCALIZED_FIELD_NAMES[fieldName] || [fieldName];
|
||||
const localeSuffix = variant === "en" ? "en" : "zh";
|
||||
const localeKeys = keys.flatMap((key) => [
|
||||
`${key}_${localeSuffix}`,
|
||||
`${key}${localeSuffix.charAt(0).toUpperCase()}${localeSuffix.slice(1)}`,
|
||||
]);
|
||||
const localized = readConfigValue(config, localeKeys);
|
||||
if (localized !== undefined) return localized;
|
||||
const generic = readConfigValue(config, keys);
|
||||
return generic ?? fallback;
|
||||
}
|
||||
|
||||
function normalizeBrandConfig(config = {}, variant = DEFAULT_BRAND_LANGUAGE) {
|
||||
const defaults = getDefaultBrandConfig(variant);
|
||||
const sourceTitleSrc = readLocalizedConfigValue(config, "titleSrc", variant, undefined);
|
||||
const normalized = {
|
||||
...defaults,
|
||||
...config,
|
||||
ariaLabel: config.aria_label ?? config.ariaLabel ?? defaults.ariaLabel,
|
||||
titleAlt: config.title_alt ?? config.titleAlt ?? defaults.titleAlt,
|
||||
ariaLabel: readLocalizedConfigValue(config, "ariaLabel", variant, defaults.ariaLabel),
|
||||
titleAlt: readLocalizedConfigValue(config, "titleAlt", variant, defaults.titleAlt),
|
||||
logoSrc: config.logo_src ?? config.logoSrc ?? defaults.logoSrc,
|
||||
titleSrc: config.title_src ?? config.titleSrc ?? defaults.titleSrc,
|
||||
titleText: config.title_text ?? config.titleText ?? defaults.titleText,
|
||||
titleSrc: sourceTitleSrc ?? defaults.titleSrc,
|
||||
titleText: readLocalizedConfigValue(config, "titleText", variant, defaults.titleText),
|
||||
subtitle: readLocalizedConfigValue(config, "subtitle", variant, defaults.subtitle),
|
||||
description: readLocalizedConfigValue(config, "description", variant, defaults.description),
|
||||
};
|
||||
|
||||
if (
|
||||
variant === "en" &&
|
||||
(
|
||||
!sourceTitleSrc ||
|
||||
sourceTitleSrc === DEFAULT_BRAND_TITLE_BY_VARIANT.zh ||
|
||||
hasCjkText(normalized.titleText) ||
|
||||
hasCjkText(normalized.titleAlt) ||
|
||||
hasCjkText(normalized.ariaLabel)
|
||||
)
|
||||
) {
|
||||
normalized.titleSrc = DEFAULT_BRAND_TITLE_BY_VARIANT.en;
|
||||
normalized.titleAlt = defaults.titleAlt;
|
||||
normalized.titleText = defaults.titleText;
|
||||
normalized.ariaLabel = defaults.ariaLabel;
|
||||
normalized.subtitle = defaults.subtitle;
|
||||
normalized.description = defaults.description;
|
||||
}
|
||||
|
||||
if (!normalized.titleText) normalized.titleText = defaults.titleText;
|
||||
if (!normalized.ariaLabel) normalized.ariaLabel = normalized.titleText;
|
||||
if (!normalized.titleAlt) normalized.titleAlt = normalized.titleText;
|
||||
|
||||
@@ -13,6 +13,7 @@ import { getSurfaceMarkerCameraScale, latLonToVector3 } from "./utils.js";
|
||||
import { setEarthStatValue, updateEarthStats, showStatusMessage } from "./ui.js";
|
||||
import { showInfoCard } from "./info-card.js";
|
||||
import { setLegendItems, setLegendMode } from "./legend.js";
|
||||
import { earthMessage } from "./i18n.js";
|
||||
|
||||
export let cableLines = [];
|
||||
export let landingPoints = [];
|
||||
@@ -324,7 +325,7 @@ export function clearCableData(earthObj = null) {
|
||||
export async function loadGeoJSONFromPath(scene, earthObj, options = {}) {
|
||||
const { silent = false } = options;
|
||||
if (!silent) {
|
||||
showStatusMessage("正在加载电缆数据...", "warning");
|
||||
showStatusMessage(earthMessage("loading.cableData"), "warning");
|
||||
}
|
||||
|
||||
const response = await fetch(PATHS.cablesApi, { cache: "no-store" });
|
||||
@@ -423,7 +424,7 @@ export async function loadGeoJSONFromPath(scene, earthObj, options = {}) {
|
||||
});
|
||||
|
||||
if (!silent) {
|
||||
showStatusMessage(`成功加载 ${cableLines.length} 条电缆`, "success");
|
||||
showStatusMessage(earthMessage("status.loadedCables", { count: cableLines.length }), "success");
|
||||
}
|
||||
return cableLines.length;
|
||||
}
|
||||
@@ -512,7 +513,7 @@ export async function loadLandingPoints(scene, earthObj, options = {}) {
|
||||
setEarthStatValue("landing-point-count", `${validCount}个`);
|
||||
|
||||
if (!silent) {
|
||||
showStatusMessage(`成功加载 ${validCount} 个登陆点`, "success");
|
||||
showStatusMessage(earthMessage("status.loadedLandingPoints", { count: validCount }), "success");
|
||||
}
|
||||
return validCount;
|
||||
}
|
||||
@@ -532,7 +533,7 @@ export function handleCableClick(cable) {
|
||||
rfs: data.rfs,
|
||||
});
|
||||
|
||||
showStatusMessage(`已锁定: ${data.name}`, "info");
|
||||
showStatusMessage(earthMessage("status.locked", { name: data.name }), "info");
|
||||
}
|
||||
|
||||
export function clearCableSelection() {
|
||||
|
||||
198
frontend/public/earth/js/controls.js
vendored
@@ -109,6 +109,7 @@ import {
|
||||
setLayerButtonState,
|
||||
updateLayerButtonState,
|
||||
} from "./layer-button-state.js";
|
||||
import { earthMessage, translateText } from "./i18n.js";
|
||||
import {
|
||||
DEFAULT_MOTION_PROVIDER,
|
||||
MOTION_GESTURES,
|
||||
@@ -428,12 +429,12 @@ function getShortcutForAction(actionId) {
|
||||
|
||||
function getAutoRotateShortcutStatusMessage(isActive) {
|
||||
if (rotationMode === ROTATION_MODE.CRUISE) {
|
||||
return isActive ? "巡航已恢复" : "巡航已暂停";
|
||||
return earthMessage("status.runtimePaused", { label: "巡航", active: isActive });
|
||||
}
|
||||
if (rotationMode === ROTATION_MODE.MOTION) {
|
||||
return isActive ? "动捕已恢复" : "动捕已暂停";
|
||||
return earthMessage("status.runtimePaused", { label: "动捕", active: isActive });
|
||||
}
|
||||
return isActive ? "旋转已恢复" : "旋转已暂停";
|
||||
return earthMessage("status.runtimePaused", { label: "旋转", active: isActive });
|
||||
}
|
||||
|
||||
function getShortcutOwnerByBinding(binding, { excludeActionId = null } = {}) {
|
||||
@@ -731,7 +732,7 @@ function toggleLayoutExpandedFromShortcut() {
|
||||
const container = document.getElementById("container");
|
||||
if (!(container instanceof HTMLElement)) return;
|
||||
const expanded = toggleLayoutExpanded(container);
|
||||
showStatusMessage(expanded ? "布局已最大化" : "布局已恢复", "info");
|
||||
showStatusMessage(earthMessage("status.layoutExpanded", { expanded }), "info");
|
||||
}
|
||||
|
||||
async function toggleLayerFromShortcut(layerId) {
|
||||
@@ -739,11 +740,17 @@ async function toggleLayerFromShortcut(layerId) {
|
||||
if (!definition) return;
|
||||
const button = getLayerButton(layerId);
|
||||
if (button?.disabled || button?.classList.contains("is-disabled")) {
|
||||
showStatusMessage(`${definition.label}当前不可用`, "warning");
|
||||
showStatusMessage(earthMessage("status.layerUnavailable", { layer: definition.label }), "warning");
|
||||
return;
|
||||
}
|
||||
await definition.setVisible(!definition.getVisible());
|
||||
showStatusMessage(`${definition.label}${definition.getVisible() ? "已显示" : "已隐藏"}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.layerVisibility", {
|
||||
layer: definition.label,
|
||||
visible: definition.getVisible(),
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
|
||||
function executeKeyboardShortcut(actionId, event = null) {
|
||||
@@ -1378,7 +1385,7 @@ function getZoomResetTooltipText(zoom) {
|
||||
}
|
||||
|
||||
function getZoomResetStatusMessage(zoom) {
|
||||
return `缩放已重置到${formatZoomPercent(zoom)}`;
|
||||
return earthMessage("status.zoomReset", { zoom: formatZoomPercent(zoom) });
|
||||
}
|
||||
|
||||
function normalizeAutoRotationSpeed(value) {
|
||||
@@ -2090,7 +2097,7 @@ export function setEarthNewsCategoryEnabled(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(Boolean(enabled) ? "新闻类型已显示" : "新闻类型已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "新闻类型", visible: Boolean(enabled) }), "info");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -2147,7 +2154,13 @@ export function setCruiseModules(nextModules, { persist = true, suppressStatus =
|
||||
|
||||
if (!suppressStatus) {
|
||||
const labels = normalizedModules.map((moduleId) => CRUISE_MODULE_LABELS[moduleId] || moduleId);
|
||||
showStatusMessage(`巡航模块已切换为:${labels.join(" + ")}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.modulesChanged", {
|
||||
label: "巡航模块",
|
||||
value: labels.map((label) => translateText(label)).join(" + "),
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
|
||||
return normalizedModules;
|
||||
@@ -2178,7 +2191,7 @@ export function setCruiseQueueMode(
|
||||
: normalizedMode === CRUISE_QUEUE_MODES.RANDOM
|
||||
? "随机"
|
||||
: "默认";
|
||||
showStatusMessage(`巡航队列已切换为:${label}`, "info");
|
||||
showStatusMessage(earthMessage("status.valueChanged", { label: "巡航队列", value: label }), "info");
|
||||
}
|
||||
|
||||
return normalizedMode;
|
||||
@@ -2203,7 +2216,7 @@ export function setCruiseRegionOrder(
|
||||
|
||||
if (persist) persistEarthSettings();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("巡航大区顺序已更新", "info");
|
||||
showStatusMessage(earthMessage("status.updated", { label: "巡航大区顺序" }), "info");
|
||||
}
|
||||
|
||||
return normalizedOrder;
|
||||
@@ -2237,7 +2250,7 @@ export function setSatelliteDisplayStyle(
|
||||
normalizedStyle === SATELLITE_DISPLAY_STYLES.GROUND_FOOTPRINT
|
||||
? "真实地表覆盖"
|
||||
: "自身发光";
|
||||
showStatusMessage(`卫星显示风格已切换为:${nextLabel}`, "info");
|
||||
showStatusMessage(earthMessage("status.valueChanged", { label: "卫星显示风格", value: nextLabel }), "info");
|
||||
}
|
||||
|
||||
return normalizedStyle;
|
||||
@@ -2256,7 +2269,7 @@ export function setSatelliteIdleBreathingEnabled(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(enabled ? "卫星呼吸闪烁已开启" : "卫星呼吸闪烁已关闭", "info");
|
||||
showStatusMessage(earthMessage("status.booleanSetting", { label: "卫星呼吸闪烁", enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -2275,7 +2288,9 @@ export function setSatelliteRealAltitudeEnabled(
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(
|
||||
enabled ? "卫星真实高度已开启" : "卫星已切换为旧版同层高度",
|
||||
enabled
|
||||
? earthMessage("status.booleanSetting", { label: "卫星真实高度", enabled })
|
||||
: earthMessage("status.valueChanged", { label: "卫星", value: "旧版同层高度" }),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
@@ -2295,7 +2310,7 @@ export function setInteractableCompactDotsEnabled(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(enabled ? "低缩放彩色圆点已开启" : "低缩放彩色圆点已关闭", "info");
|
||||
showStatusMessage(earthMessage("status.booleanSetting", { label: "低缩放彩色圆点", enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -2330,7 +2345,7 @@ export function setSurfaceHoverInfoMode(
|
||||
: normalizedMode === SURFACE_HOVER_INFO_MODES.POSITION
|
||||
? "位置"
|
||||
: "完整";
|
||||
showStatusMessage(`悬停提示已切换为:${label}`, "info");
|
||||
showStatusMessage(earthMessage("status.valueChanged", { label: "悬停提示", value: label }), "info");
|
||||
}
|
||||
|
||||
return normalizedMode;
|
||||
@@ -2508,12 +2523,13 @@ export function setMotionDebugEnabled(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus && changed) {
|
||||
const message = motionDebugEnabled
|
||||
? rotationMode === ROTATION_MODE.MOTION
|
||||
? "动捕调试模式已开启"
|
||||
: "动捕调试模式将在下次进入动捕时开启"
|
||||
: "动捕调试模式已关闭";
|
||||
showStatusMessage(message, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.motionDebugMode", {
|
||||
enabled: motionDebugEnabled,
|
||||
pending: rotationMode !== ROTATION_MODE.MOTION,
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
return motionDebugEnabled;
|
||||
}
|
||||
@@ -2537,12 +2553,7 @@ export function setMotionProvider(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus && changed) {
|
||||
showStatusMessage(
|
||||
motionProvider === "motion_agent"
|
||||
? "动捕输入源已切换为 Motion Agent"
|
||||
: "动捕输入源已切换为浏览器摄像头",
|
||||
"info",
|
||||
);
|
||||
showStatusMessage(earthMessage("status.motionProvider", { provider: motionProvider }), "info");
|
||||
}
|
||||
return motionProvider;
|
||||
}
|
||||
@@ -2566,10 +2577,7 @@ export function setMotionDebugSkeletonOnly(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus && changed) {
|
||||
showStatusMessage(
|
||||
motionDebugSkeletonOnly ? "动捕调试已切换为只显示骨骼" : "动捕调试已显示实时画面",
|
||||
"info",
|
||||
);
|
||||
showStatusMessage(earthMessage("status.motionDebugView", { skeletonOnly: motionDebugSkeletonOnly }), "info");
|
||||
}
|
||||
return motionDebugSkeletonOnly;
|
||||
}
|
||||
@@ -2597,7 +2605,7 @@ export function setMotionEnabledGestures(
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus && changed) {
|
||||
showStatusMessage("动捕识别动作已更新", "info");
|
||||
showStatusMessage(earthMessage("status.motionGesturesUpdated"), "info");
|
||||
}
|
||||
return getMotionEnabledGestures();
|
||||
}
|
||||
@@ -2626,7 +2634,7 @@ function resetEarthSettings() {
|
||||
}
|
||||
}
|
||||
void applyEarthSettings(defaults).then(() => {
|
||||
showStatusMessage("Earth 设置已重置", "info");
|
||||
showStatusMessage(earthMessage("status.settingsReset"), "info");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2638,7 +2646,7 @@ async function setTerrainEnabled(button, enabled, { persist = true, silent = fal
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage("地形已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "真实地形", visible: false }), "info");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -2651,7 +2659,7 @@ async function setTerrainEnabled(button, enabled, { persist = true, silent = fal
|
||||
statusText: "加载中",
|
||||
});
|
||||
if (!silent) {
|
||||
showStatusMessage("正在加载真实地形数据...", "info");
|
||||
showStatusMessage(earthMessage("loading.realTerrainData"), "info");
|
||||
}
|
||||
await ensureTerrainReady();
|
||||
}
|
||||
@@ -2661,7 +2669,7 @@ async function setTerrainEnabled(button, enabled, { persist = true, silent = fal
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage("真实地形已显示", "success");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "真实地形", visible: true }), "success");
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
@@ -2670,7 +2678,7 @@ async function setTerrainEnabled(button, enabled, { persist = true, silent = fal
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage("真实地形暂时不可用", "error");
|
||||
showStatusMessage(earthMessage("status.terrainUnavailable"), "error");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -2688,7 +2696,7 @@ async function setSatellitesLayerEnabled(button, enabled, { persist = true, sile
|
||||
}
|
||||
await setSatellitesEnabled(enabled, { suppressStatus: silent, suppressLoadingUi: silent });
|
||||
if (!enabled && !silent) {
|
||||
showStatusMessage("卫星已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "卫星", visible: false }), "info");
|
||||
} else if (enabled) {
|
||||
setEarthStatValue("satellite-count", `${getSatelliteCount()} 颗`);
|
||||
}
|
||||
@@ -2718,7 +2726,7 @@ function setGridLinesLayerEnabled(button, enabled, { persist = true, silent = fa
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage(enabled ? "经纬线已显示" : "经纬线已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "经纬线", visible: enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -2806,7 +2814,7 @@ function setBGPLayerEnabled(button, enabled, { persist = true, silent = false }
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage(enabled ? "BGP观测已显示" : "BGP观测已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "BGP观测", visible: enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -2822,7 +2830,7 @@ function setComputeCentersLayerEnabled(button, enabled, { persist = true, silent
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage(enabled ? "算力中心已显示" : "算力中心已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "算力中心", visible: enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -2891,7 +2899,7 @@ function setTrailsDisplayEnabled(enabled, { persist = true, silent = false } = {
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
showStatusMessage(enabled ? "轨迹已显示" : "轨迹已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "轨迹", visible: enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -3001,7 +3009,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupMode: "preload",
|
||||
startupAlwaysLoad: true,
|
||||
startupLabel: "海陆基座",
|
||||
startupMessage: "正在加载海陆基座...",
|
||||
startupMessage: earthMessage("startup.landOceanBase"),
|
||||
getVisible: () => getShowCountryBoundaries(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setCountryBoundariesLayerEnabled(getLayerButton("countryBoundaries"), visible, options),
|
||||
@@ -3018,7 +3026,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupPriority: 30,
|
||||
startupMode: "visible",
|
||||
startupLabel: "高清材质",
|
||||
startupMessage: "正在启用高清材质...",
|
||||
startupMessage: earthMessage("startup.hdTexture"),
|
||||
getVisible: () => getHighResTextureEnabled(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setHighResTextureLayerEnabled(getLayerButton("earthHighResTexture"), visible, options),
|
||||
@@ -3053,8 +3061,8 @@ function getBuiltinLayerDefinitions() {
|
||||
startupMode: "visible",
|
||||
startupLabel: "海缆",
|
||||
startupMessage: {
|
||||
prepare: "正在加载登陆点...",
|
||||
load: "正在加载海缆...",
|
||||
prepare: earthMessage("startup.landingPoints"),
|
||||
load: earthMessage("startup.cables"),
|
||||
},
|
||||
getVisible: () => getShowCables(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
@@ -3072,7 +3080,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupPriority: 60,
|
||||
startupMode: "preload",
|
||||
startupLabel: "算力中心",
|
||||
startupMessage: "正在加载算力中心...",
|
||||
startupMessage: earthMessage("startup.computeCenters"),
|
||||
getVisible: () => getShowComputeCenters(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setComputeCentersLayerEnabled(getLayerButton("computeCenters"), visible, options),
|
||||
@@ -3089,7 +3097,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupPriority: 70,
|
||||
startupMode: "preload",
|
||||
startupLabel: "BGP态势",
|
||||
startupMessage: "正在加载BGP态势...",
|
||||
startupMessage: earthMessage("startup.bgp"),
|
||||
getVisible: () => getShowBGP(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setBGPLayerEnabled(getLayerButton("bgp"), visible, options),
|
||||
@@ -3106,7 +3114,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupPriority: 65,
|
||||
startupMode: "visible",
|
||||
startupLabel: "船只",
|
||||
startupMessage: "正在加载船只...",
|
||||
startupMessage: earthMessage("startup.vessels"),
|
||||
getVisible: () => getVesselsEnabled(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setVesselsLayerEnabled(getLayerButton("vessels"), visible, options),
|
||||
@@ -3123,7 +3131,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupPriority: 80,
|
||||
startupMode: "visible",
|
||||
startupLabel: "卫星",
|
||||
startupMessage: "正在加载卫星...",
|
||||
startupMessage: earthMessage("startup.satellites"),
|
||||
getVisible: () => getSatellitesEnabled(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setSatellitesLayerEnabled(getLayerButton("satellites"), visible, options),
|
||||
@@ -3140,7 +3148,7 @@ function getBuiltinLayerDefinitions() {
|
||||
startupPriority: null,
|
||||
startupMode: "visible",
|
||||
startupLabel: "地形",
|
||||
startupMessage: "正在渲染地形...",
|
||||
startupMessage: earthMessage("startup.terrain"),
|
||||
statusTarget: "terrain-status",
|
||||
getVisible: () => showTerrain,
|
||||
setVisible: (visible, options = {}) =>
|
||||
@@ -3345,7 +3353,10 @@ export function showZoomStatusCapsule({ force = false, zoom = null } = {}) {
|
||||
const currentZoom = Number.isFinite(Number(zoom))
|
||||
? clampEarthZoomLevel(zoom)
|
||||
: syncZoomLevelFromCamera(activeCamera);
|
||||
showGestureStatusMessage(`缩放 ${Math.round(currentZoom * 100)}%`, "info");
|
||||
showGestureStatusMessage(
|
||||
earthMessage("status.zoomPercent", { percent: Math.round(currentZoom * 100) }),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
|
||||
function cancelSettingsSheetAnimation() {
|
||||
@@ -3602,10 +3613,17 @@ function syncSettingsToggle(panelId, visible) {
|
||||
inputs.forEach((input) => {
|
||||
if (input instanceof HTMLInputElement) {
|
||||
input.checked = visible;
|
||||
syncSettingsSwitchVisual(input, visible);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function syncSettingsSwitchVisual(input, visible = input?.checked === true) {
|
||||
if (!(input instanceof HTMLInputElement)) return;
|
||||
const switchShell = input.closest(".earth-settings-switch, .earth-mobile-settings-switch");
|
||||
switchShell?.classList.toggle("is-checked", Boolean(visible));
|
||||
}
|
||||
|
||||
function syncAllHudPanelToggles() {
|
||||
HUD_PANEL_IDS.forEach((panelId) => {
|
||||
const panel = document.getElementById(panelId);
|
||||
@@ -3775,12 +3793,15 @@ function startBoundaryBuildPolling() {
|
||||
setHighPrecisionBoundariesEnabled(true);
|
||||
await reloadCountryBoundaries({ suppressStatus: true });
|
||||
await refreshBoundaryPrecisionStatus().catch(() => {});
|
||||
showStatusMessage("高精国界已下载并应用", "info");
|
||||
showStatusMessage(earthMessage("status.boundaryDownloaded"), "info");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
stopBoundaryBuildPolling();
|
||||
showStatusMessage(`高清国界进度读取失败:${error.message || error}`, "warning");
|
||||
showStatusMessage(
|
||||
earthMessage("status.failure", { label: "高清国界进度读取失败", error: error.message || error }),
|
||||
"warning",
|
||||
);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
@@ -3791,7 +3812,7 @@ async function startBoundaryPrecisionBuild() {
|
||||
});
|
||||
boundaryBuildAttemptedThisSession = true;
|
||||
await fetchBoundaryPrecisionJson("/api/v1/earth/boundaries/build", { method: "POST", body: "{}" });
|
||||
showStatusMessage("高精国界构建已启动", "info");
|
||||
showStatusMessage(earthMessage("status.boundaryBuildStarted"), "info");
|
||||
startBoundaryBuildPolling();
|
||||
}
|
||||
|
||||
@@ -3806,7 +3827,10 @@ async function setupBoundaryPrecisionControls() {
|
||||
}
|
||||
} catch (error) {
|
||||
renderBoundaryPrecisionStatus({});
|
||||
showStatusMessage(`高清国界状态读取失败:${error.message || error}`, "warning");
|
||||
showStatusMessage(
|
||||
earthMessage("status.failure", { label: "高清国界状态读取失败", error: error.message || error }),
|
||||
"warning",
|
||||
);
|
||||
}
|
||||
|
||||
els.buildButtons.forEach((buildButton) => {
|
||||
@@ -3820,14 +3844,17 @@ async function setupBoundaryPrecisionControls() {
|
||||
if (getHighPrecisionBoundariesEnabled()) return;
|
||||
setHighPrecisionBoundariesEnabled(true);
|
||||
await reloadCountryBoundaries({ suppressStatus: true });
|
||||
showStatusMessage("已切换到高精国界", "info");
|
||||
showStatusMessage(earthMessage("status.boundaryPrecision", { high: true }), "info");
|
||||
await refreshBoundaryPrecisionStatus().catch(() => {});
|
||||
return;
|
||||
}
|
||||
await startBoundaryPrecisionBuild();
|
||||
} catch (error) {
|
||||
await refreshBoundaryPrecisionStatus().catch(() => {});
|
||||
showStatusMessage(`高精国界切换失败:${error.message || error}`, "warning");
|
||||
showStatusMessage(
|
||||
earthMessage("status.failure", { label: "高精国界切换失败", error: error.message || error }),
|
||||
"warning",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3838,7 +3865,10 @@ async function setupBoundaryPrecisionControls() {
|
||||
await startBoundaryPrecisionBuild();
|
||||
} catch (error) {
|
||||
await refreshBoundaryPrecisionStatus().catch(() => {});
|
||||
showStatusMessage(`高精国界重建启动失败:${error.message || error}`, "warning");
|
||||
showStatusMessage(
|
||||
earthMessage("status.failure", { label: "高精国界重建启动失败", error: error.message || error }),
|
||||
"warning",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3849,10 +3879,13 @@ async function setupBoundaryPrecisionControls() {
|
||||
if (!getHighPrecisionBoundariesEnabled()) return;
|
||||
setHighPrecisionBoundariesEnabled(false);
|
||||
await reloadCountryBoundaries({ suppressStatus: true });
|
||||
showStatusMessage("已切换到低精国界", "info");
|
||||
showStatusMessage(earthMessage("status.boundaryPrecision", { high: false }), "info");
|
||||
await refreshBoundaryPrecisionStatus().catch(() => {});
|
||||
} catch (error) {
|
||||
showStatusMessage(`低精国界切换失败:${error.message || error}`, "warning");
|
||||
showStatusMessage(
|
||||
earthMessage("status.failure", { label: "低精国界切换失败", error: error.message || error }),
|
||||
"warning",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4043,7 +4076,7 @@ function setShortcutBinding(actionId, binding, { persist = true } = {}) {
|
||||
if (!normalizedBinding) return false;
|
||||
const owner = getShortcutOwnerByBinding(normalizedBinding, { excludeActionId: actionId });
|
||||
if (owner) {
|
||||
showStatusMessage(`快捷键已被「${owner.label}」使用`, "warning");
|
||||
showStatusMessage(earthMessage("status.shortcutConflict", { owner: owner.label }), "warning");
|
||||
return false;
|
||||
}
|
||||
const nextShortcuts = normalizeKeyboardShortcuts(keyboardShortcuts);
|
||||
@@ -4083,7 +4116,7 @@ function setShortcutEnabled(actionId, enabled, { persist = true } = {}) {
|
||||
if (enabled) {
|
||||
const owner = getShortcutOwnerByBinding(currentShortcut.binding, { excludeActionId: actionId });
|
||||
if (owner) {
|
||||
showStatusMessage(`快捷键已被「${owner.label}」使用`, "warning");
|
||||
showStatusMessage(earthMessage("status.shortcutConflict", { owner: owner.label }), "warning");
|
||||
renderShortcutSettings();
|
||||
return false;
|
||||
}
|
||||
@@ -4110,7 +4143,7 @@ function resetAllShortcutBindings() {
|
||||
capturingShortcutActionId = null;
|
||||
renderShortcutSettings();
|
||||
persistEarthSettings();
|
||||
showStatusMessage("快捷键已恢复默认", "info");
|
||||
showStatusMessage(earthMessage("status.shortcutsReset"), "info");
|
||||
}
|
||||
|
||||
function moveCruiseRegionInOrder(region, targetRegion) {
|
||||
@@ -4270,11 +4303,15 @@ function setupSettingsControls() {
|
||||
|
||||
const toggleInputs = document.querySelectorAll("[data-settings-panel]");
|
||||
toggleInputs.forEach((input) => {
|
||||
if (input instanceof HTMLInputElement) {
|
||||
syncSettingsSwitchVisual(input);
|
||||
}
|
||||
bindListener(input, "change", (event) => {
|
||||
const target = event.currentTarget;
|
||||
if (!(target instanceof HTMLInputElement)) return;
|
||||
const panelId = target.dataset.settingsPanel;
|
||||
if (!panelId) return;
|
||||
syncSettingsSwitchVisual(target, target.checked);
|
||||
setHudPanelVisibility(panelId, target.checked);
|
||||
});
|
||||
});
|
||||
@@ -5247,7 +5284,10 @@ function setupRotateControls(camera) {
|
||||
: rotationMode === ROTATION_MODE.MOTION
|
||||
? "动捕"
|
||||
: "自动旋转";
|
||||
showStatusMessage(isRotating ? `${label}已开启` : `${label}已暂停`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.runtimePaused", { label, active: isRotating }),
|
||||
"info",
|
||||
);
|
||||
});
|
||||
|
||||
updateRotateUI();
|
||||
@@ -5518,7 +5558,7 @@ function setupTerrainControls() {
|
||||
|
||||
bindListener(layoutBtn, "click", () => {
|
||||
const expanded = toggleLayoutExpanded(container);
|
||||
showStatusMessage(expanded ? "布局已最大化" : "布局已恢复", "info");
|
||||
showStatusMessage(earthMessage("status.layoutExpanded", { expanded }), "info");
|
||||
});
|
||||
|
||||
const mediaVisible =
|
||||
@@ -5552,7 +5592,13 @@ function setupKeyboardControls() {
|
||||
if (!nextBinding) return;
|
||||
if (setShortcutBinding(capturingShortcutActionId, nextBinding)) {
|
||||
const definition = KEYBOARD_SHORTCUT_DEFINITION_BY_ID.get(capturingShortcutActionId);
|
||||
showStatusMessage(`${definition?.label || "快捷键"}已设置为 ${getShortcutDisplayLabel(nextBinding)}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.shortcutSet", {
|
||||
label: definition?.label || "快捷键",
|
||||
binding: getShortcutDisplayLabel(nextBinding),
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
capturingShortcutActionId = null;
|
||||
syncShortcutCaptureUi();
|
||||
}
|
||||
@@ -5600,6 +5646,8 @@ function setupLiquidGlassInteractions() {
|
||||
surface.style.setProperty("--tilt-y", "0deg");
|
||||
surface.style.setProperty("--panel-tilt-x", "0deg");
|
||||
surface.style.setProperty("--panel-tilt-y", "0deg");
|
||||
surface.style.setProperty("--mouse-x", "0.5");
|
||||
surface.style.setProperty("--mouse-y", "0.5");
|
||||
surface.style.setProperty("--dock-scale", "1");
|
||||
surface.style.setProperty("--dock-lift", "0px");
|
||||
surface.style.setProperty("--dock-shift-x", "0px");
|
||||
@@ -5616,13 +5664,15 @@ function setupLiquidGlassInteractions() {
|
||||
|
||||
surfaces.forEach((surface) => {
|
||||
resetSurface(surface);
|
||||
const isToolbarSurface = Boolean(surface.closest(".earth-toolbar-items"));
|
||||
const isToolbarSurface = Boolean(surface.closest(".earth-toolbar"));
|
||||
const isPanelSurface = surface.classList.contains("hud-panel");
|
||||
|
||||
bindListener(surface, "pointermove", (event) => {
|
||||
const rect = surface.getBoundingClientRect();
|
||||
const px = (event.clientX - rect.left) / rect.width;
|
||||
const py = (event.clientY - rect.top) / rect.height;
|
||||
surface.style.setProperty("--mouse-x", `${px.toFixed(3)}`);
|
||||
surface.style.setProperty("--mouse-y", `${py.toFixed(3)}`);
|
||||
if (isPanelSurface) {
|
||||
const panelTiltX = (0.5 - py) * 5;
|
||||
const panelTiltY = (px - 0.5) * 6;
|
||||
@@ -6008,9 +6058,9 @@ function updateRotateUI() {
|
||||
? "动捕"
|
||||
: "自动旋转";
|
||||
if (tooltip) {
|
||||
tooltip.textContent = autoRotate ? `暂停${activeLabel}` : `开始${activeLabel}`;
|
||||
tooltip.textContent = translateText(autoRotate ? `暂停${activeLabel}` : `开始${activeLabel}`);
|
||||
}
|
||||
btn.title = `${getRotationModeLabel()} · ${activeLabel}`;
|
||||
btn.title = translateText(`${getRotationModeLabel()} · ${activeLabel}`);
|
||||
}
|
||||
|
||||
syncRotationModeButtons();
|
||||
@@ -6052,7 +6102,7 @@ export function setAutoRotationSpeed(value, { persist = true, suppressStatus = f
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (changed && !suppressStatus) {
|
||||
showStatusMessage(`旋转转速已设为 ${formatAutoRotationSpeed(normalizedSpeed)}`, "info");
|
||||
showStatusMessage(earthMessage("status.rotateSpeed", { speed: formatAutoRotationSpeed(normalizedSpeed) }), "info");
|
||||
}
|
||||
return normalizedSpeed;
|
||||
}
|
||||
@@ -6075,7 +6125,7 @@ export function setRotationMode(nextMode, { persist = true, suppressStatus = fal
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (changed && !suppressStatus) {
|
||||
showStatusMessage(`已切换到${getRotationModeLabel(normalizedMode)}`, "info");
|
||||
showStatusMessage(earthMessage("status.switchedTo", { label: getRotationModeLabel(normalizedMode) }), "info");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6147,7 +6197,7 @@ export function focusEarthView(camera, options = {}) {
|
||||
earthObj.rotation.y = nextRotation.y;
|
||||
earthObj.rotation.z = nextRotation.z;
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("视角已重置", "info");
|
||||
showStatusMessage(earthMessage("status.viewReset"), "info");
|
||||
}
|
||||
resolve();
|
||||
},
|
||||
|
||||
1641
frontend/public/earth/js/i18n.js
Normal file
@@ -1,5 +1,12 @@
|
||||
// info-card.js - Unified info card module
|
||||
import { showStatusMessage } from './ui.js';
|
||||
import {
|
||||
earthMessage,
|
||||
getEarthLocale,
|
||||
hasCjkText,
|
||||
localizeCountryName,
|
||||
translateText,
|
||||
} from './i18n.js';
|
||||
import {
|
||||
getNewsDisplaySummary,
|
||||
getNewsDisplayTitle,
|
||||
@@ -85,8 +92,8 @@ function clearLocationCollectState(contextOrKey) {
|
||||
}
|
||||
|
||||
function getWebSearchDisabledTitle(capability = computeCenterLocationCapability) {
|
||||
if (!capability) return '正在检查 WebSearch 状态,稍候即可定位。';
|
||||
return capability.reason || 'WebSearch 未开启,无法进行事实核查定位。';
|
||||
if (!capability) return infoText('正在检查 WebSearch 状态,稍候即可定位。');
|
||||
return infoText(capability.reason || 'WebSearch 未开启,无法进行事实核查定位。');
|
||||
}
|
||||
|
||||
function isComputeCenterLocationBlocked() {
|
||||
@@ -134,7 +141,7 @@ function setLocationButtonLoading(button, loading, label) {
|
||||
button.classList.toggle('is-loading', Boolean(loading));
|
||||
button.toggleAttribute('aria-busy', Boolean(loading));
|
||||
if (label) {
|
||||
button.dataset.loadingLabel = label;
|
||||
button.dataset.loadingLabel = infoText(label);
|
||||
}
|
||||
updateComputeCenterLocationCapabilityDom();
|
||||
}
|
||||
@@ -188,14 +195,27 @@ function formatInfoCardValue(field, rawValue) {
|
||||
if (IDENTIFIER_FIELD_KEYS.has(field.key)) {
|
||||
value = String(value);
|
||||
} else if (typeof value === 'number') {
|
||||
value = value.toLocaleString();
|
||||
value = value.toLocaleString(getEarthLocale());
|
||||
}
|
||||
if (field.key === 'country') {
|
||||
value = localizeCountryName(value) || value;
|
||||
}
|
||||
if (field.unit && value !== '-') {
|
||||
value = value + ' ' + field.unit;
|
||||
value = value + ' ' + translateText(field.unit);
|
||||
} else if (typeof value === 'string') {
|
||||
value = translateText(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function infoText(value, fallback = '') {
|
||||
const translated = translateText(value);
|
||||
if (getEarthLocale() === 'en-US' && hasCjkText(translated) && fallback) {
|
||||
return fallback;
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
|
||||
function escapeInfoCardHtml(value) {
|
||||
return String(value ?? '').replace(/[&<>"']/g, (char) => ({
|
||||
'&': '&',
|
||||
@@ -299,18 +319,18 @@ function renderNewsCardContent(content, data) {
|
||||
const metaHtml = metaItems.length
|
||||
? `<div class="info-card-news-meta-grid">${metaItems.map(([label, value]) => `
|
||||
<div class="info-card-news-meta-item">
|
||||
<span>${escapeInfoCardHtml(label)}</span>
|
||||
<span>${escapeInfoCardHtml(infoText(label))}</span>
|
||||
<strong>${escapeInfoCardHtml(value)}</strong>
|
||||
</div>
|
||||
`).join('')}</div>`
|
||||
: '';
|
||||
content.innerHTML = `
|
||||
<div class="info-card-news-layout">
|
||||
<div class="info-card-news-kicker">新闻信号</div>
|
||||
<div class="info-card-news-kicker">${escapeInfoCardHtml(infoText('新闻信号'))}</div>
|
||||
<div class="info-card-news-title">${escapeInfoCardHtml(title)}</div>
|
||||
${metaHtml}
|
||||
<div class="info-card-news-summary-shell">
|
||||
<div class="info-card-news-summary-label">概要</div>
|
||||
<div class="info-card-news-summary-label">${escapeInfoCardHtml(infoText('概要'))}</div>
|
||||
<div class="info-card-news-summary" data-news-summary></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -332,18 +352,18 @@ function renderMobileNewsCardContent(content, data) {
|
||||
const metaHtml = metaItems.length
|
||||
? `<div class="info-card-news-meta-grid info-card-news-meta-grid--mobile">${metaItems.map(([label, value]) => `
|
||||
<div class="info-card-news-meta-item">
|
||||
<span>${escapeInfoCardHtml(label)}</span>
|
||||
<span>${escapeInfoCardHtml(infoText(label))}</span>
|
||||
<strong>${escapeInfoCardHtml(value)}</strong>
|
||||
</div>
|
||||
`).join('')}</div>`
|
||||
: '';
|
||||
content.innerHTML = `
|
||||
<div class="earth-mobile-news-detail">
|
||||
<div class="earth-mobile-news-detail-kicker">新闻信号</div>
|
||||
<div class="earth-mobile-news-detail-kicker">${escapeInfoCardHtml(infoText('新闻信号'))}</div>
|
||||
<div class="earth-mobile-news-detail-title">${escapeInfoCardHtml(title)}</div>
|
||||
${metaHtml}
|
||||
<div class="earth-mobile-news-detail-summary-shell">
|
||||
<div class="earth-mobile-news-detail-summary-label">概要</div>
|
||||
<div class="earth-mobile-news-detail-summary-label">${escapeInfoCardHtml(infoText('概要'))}</div>
|
||||
<div class="earth-mobile-news-detail-summary" data-news-summary></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -371,7 +391,7 @@ function renderMobileDetailContent(type, config, data) {
|
||||
const value = formatInfoCardValue(field, data[field.key]);
|
||||
html += `
|
||||
<div class="earth-mobile-detail-row">
|
||||
<span class="earth-mobile-detail-row-label">${field.label}</span>
|
||||
<span class="earth-mobile-detail-row-label">${escapeInfoCardHtml(infoText(field.label))}</span>
|
||||
<span class="earth-mobile-detail-row-value">${value}</span>
|
||||
</div>
|
||||
`;
|
||||
@@ -428,7 +448,7 @@ function renderDefaultCardContent(content, config, data) {
|
||||
const sourceLabel = getFieldSourceLabel(data, field.key);
|
||||
html += `
|
||||
<div class="info-card-property">
|
||||
<span class="info-card-label">${field.label}</span>
|
||||
<span class="info-card-label">${escapeInfoCardHtml(infoText(field.label))}</span>
|
||||
<span class="info-card-value">${value}${sourceLabel}</span>
|
||||
</div>
|
||||
`;
|
||||
@@ -519,8 +539,8 @@ function buildLocationCollectContext(config, data) {
|
||||
|
||||
function renderLocationCollectSection(context) {
|
||||
const buttonLabel = context.needsConfirmation
|
||||
? '重新自动采集坐标'
|
||||
: '自动采集坐标候选';
|
||||
? infoText('重新自动采集坐标')
|
||||
: infoText('自动采集坐标候选');
|
||||
const cacheKey = getLocationCollectCacheKey(context);
|
||||
const cached = getLocationCollectState(cacheKey);
|
||||
ensureComputeCenterLocationCapability();
|
||||
@@ -559,7 +579,7 @@ function hydrateLocationCollectRoot(root, state) {
|
||||
const statusEl = root.querySelector('[data-collect-status], [data-unresolved-status]');
|
||||
const candidatesEl = root.querySelector('[data-collect-candidates], [data-unresolved-candidates]');
|
||||
const button = root.querySelector('[data-collect-action="run"], [data-unresolved-collect]');
|
||||
if (statusEl) statusEl.textContent = state?.statusText || '';
|
||||
if (statusEl) statusEl.textContent = infoText(state?.statusText || '');
|
||||
if (candidatesEl) candidatesEl.innerHTML = renderCachedCollectCandidates(state);
|
||||
if (button instanceof HTMLButtonElement) {
|
||||
button.classList.toggle('is-loading', state?.loading === true);
|
||||
@@ -654,15 +674,15 @@ function ensureCandidateActionBindings(rootOrChild, context) {
|
||||
if (typeof actionContext.save !== 'function') return;
|
||||
const statusEl = root.querySelector('[data-collect-status], [data-unresolved-status]');
|
||||
button.disabled = true;
|
||||
if (statusEl) statusEl.textContent = '正在保存所选坐标...';
|
||||
if (statusEl) statusEl.textContent = infoText('正在保存所选坐标...');
|
||||
try {
|
||||
const saveResult = await actionContext.save(candidate);
|
||||
setLocationCollectState(actionContext, {
|
||||
loading: false,
|
||||
statusText: '坐标已保存',
|
||||
statusText: infoText('坐标已保存'),
|
||||
candidates: [],
|
||||
});
|
||||
if (statusEl) statusEl.textContent = '坐标已保存';
|
||||
if (statusEl) statusEl.textContent = infoText('坐标已保存');
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('earth:compute-center-location-saved', {
|
||||
detail: {
|
||||
@@ -685,7 +705,7 @@ function ensureCandidateActionBindings(rootOrChild, context) {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('save compute-center location failed', error);
|
||||
if (statusEl) statusEl.textContent = `保存失败:${error?.message || error}`;
|
||||
if (statusEl) statusEl.textContent = infoText(`保存失败:${error?.message || error}`);
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -695,14 +715,14 @@ function formatLocationCollectFailure(result) {
|
||||
const regularReason = result?.failure_reason || '常规来源没有可用坐标候选';
|
||||
const llmReason = result?.llm_failure_reason;
|
||||
if (llmReason) {
|
||||
return `常规来源无结果;LLM 兜底未生成可用候选:${llmReason}`;
|
||||
return infoText(`常规来源无结果;LLM 兜底未生成可用候选:${llmReason}`);
|
||||
}
|
||||
const attempted = Array.isArray(result?.attempted_queries) ? result.attempted_queries : [];
|
||||
const attemptedLlm = attempted.some((query) => String(query || '').startsWith('llm_factcheck:'));
|
||||
if (attemptedLlm) {
|
||||
return `常规来源无结果;LLM 兜底已尝试但没有返回可用候选。${regularReason}`;
|
||||
return infoText(`常规来源无结果;LLM 兜底已尝试但没有返回可用候选。${regularReason}`);
|
||||
}
|
||||
return regularReason;
|
||||
return infoText(regularReason);
|
||||
}
|
||||
|
||||
function bindLocationCollectControls(content, context) {
|
||||
@@ -728,7 +748,7 @@ function bindLocationCollectControls(content, context) {
|
||||
setLocationButtonLoading(button, true, '正在定位');
|
||||
setLocationCollectState(context, {
|
||||
loading: true,
|
||||
statusText: '正在采集坐标候选...',
|
||||
statusText: infoText('正在采集坐标候选...'),
|
||||
candidates: [],
|
||||
});
|
||||
try {
|
||||
@@ -736,7 +756,7 @@ function bindLocationCollectControls(content, context) {
|
||||
if (!result?.success) {
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `未能采集到坐标:${formatLocationCollectFailure(result)}`,
|
||||
statusText: infoText(`未能采集到坐标:${formatLocationCollectFailure(result)}`),
|
||||
candidates: [],
|
||||
result,
|
||||
});
|
||||
@@ -745,7 +765,7 @@ function bindLocationCollectControls(content, context) {
|
||||
const candidates = Array.isArray(result.candidates) ? result.candidates : [];
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `共找到 ${candidates.length} 个候选位置`,
|
||||
statusText: infoText(`共找到 ${candidates.length} 个候选位置`),
|
||||
candidates,
|
||||
result,
|
||||
});
|
||||
@@ -753,7 +773,7 @@ function bindLocationCollectControls(content, context) {
|
||||
console.error('collect-location failed', error);
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `采集失败:${error?.message || error}`,
|
||||
statusText: infoText(`采集失败:${error?.message || error}`),
|
||||
candidates: [],
|
||||
});
|
||||
} finally {
|
||||
@@ -773,22 +793,22 @@ function renderCollectCandidateRow(candidate, isBest, index) {
|
||||
? `${Math.round(Number(candidate.confidence) * 100)}%`
|
||||
: '-';
|
||||
const safeIndex = Number.isFinite(Number(index)) ? Number(index) : 0;
|
||||
const name = escapeInfoCardHtml(candidate.matched_location_name || candidate.display_name || '候选');
|
||||
const name = escapeInfoCardHtml(candidate.matched_location_name || candidate.display_name || infoText('候选'));
|
||||
const sourceLabel = escapeInfoCardHtml(candidate.source || '');
|
||||
return `
|
||||
<div class="info-card-compute-candidate ${isBest ? 'is-best' : ''}">
|
||||
<div class="info-card-compute-candidate-line">
|
||||
<span class="info-card-compute-candidate-name">${name}</span>
|
||||
<span class="info-card-compute-candidate-precision">${escapeInfoCardHtml(precisionLabel)}</span>
|
||||
<span class="info-card-compute-candidate-precision">${escapeInfoCardHtml(infoText(precisionLabel))}</span>
|
||||
</div>
|
||||
<div class="info-card-compute-candidate-line">
|
||||
<span class="info-card-compute-candidate-source">${sourceLabel}</span>
|
||||
<span class="info-card-compute-candidate-confidence">置信 ${escapeInfoCardHtml(confidence)}</span>
|
||||
<span class="info-card-compute-candidate-confidence">${escapeInfoCardHtml(infoText(`置信 ${confidence}`))}</span>
|
||||
</div>
|
||||
<div class="info-card-compute-candidate-line">
|
||||
<span class="info-card-compute-candidate-coords">${Number(candidate.latitude).toFixed(4)}, ${Number(candidate.longitude).toFixed(4)}</span>
|
||||
<button type="button" class="info-card-compute-candidate-preview" data-preview-candidate data-candidate-index="${safeIndex}">预览</button>
|
||||
<button type="button" class="info-card-compute-candidate-preview" data-save-candidate data-candidate-index="${safeIndex}">保存</button>
|
||||
<button type="button" class="info-card-compute-candidate-preview" data-preview-candidate data-candidate-index="${safeIndex}">${escapeInfoCardHtml(infoText('预览'))}</button>
|
||||
<button type="button" class="info-card-compute-candidate-preview" data-save-candidate data-candidate-index="${safeIndex}">${escapeInfoCardHtml(infoText('保存'))}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -803,7 +823,7 @@ function getUnresolvedComputeCenterContext(item) {
|
||||
entityId: item?.source_id || item?.id || '',
|
||||
sourceId: item?.source_id || item?.id || '',
|
||||
recordId: item?.id || item?.record_id || '',
|
||||
name: item?.name || item?.title || '未命名算力中心',
|
||||
name: item?.name || item?.title || infoText('未命名算力中心'),
|
||||
site_type: item?.site_type || metadata.site_type || '',
|
||||
operator: item?.operator || item?.vendor || metadata.operator || '',
|
||||
site: item?.site || metadata.site || metadata.organization || '',
|
||||
@@ -821,7 +841,7 @@ function renderComputeCenterUnresolvedContent(content, data) {
|
||||
if (!items.length) {
|
||||
content.innerHTML = `
|
||||
<div class="info-card-unresolved-empty">
|
||||
当前没有待定位算力中心
|
||||
${escapeInfoCardHtml(infoText('当前没有待定位算力中心'))}
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
@@ -835,7 +855,7 @@ function renderComputeCenterUnresolvedContent(content, data) {
|
||||
const cached = getLocationCollectState(cacheKey);
|
||||
const meta = [context.site || context.operator, context.city, context.country]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || '缺少可用地址字段';
|
||||
.join(' · ') || infoText('缺少可用地址字段');
|
||||
return `
|
||||
<div class="info-card-unresolved-item" data-unresolved-item data-collect-cache-key="${escapeInfoCardHtml(cacheKey)}">
|
||||
<div class="info-card-unresolved-main">
|
||||
@@ -847,10 +867,10 @@ function renderComputeCenterUnresolvedContent(content, data) {
|
||||
<button type="button" class="info-card-compute-candidate-preview"
|
||||
data-unresolved-collect
|
||||
data-requires-web-search="true"
|
||||
data-ready-title="采集坐标候选"
|
||||
title="${escapeInfoCardHtml(blocked ? disabledTitle : '采集坐标候选')}"
|
||||
data-ready-title="${escapeInfoCardHtml(infoText('采集坐标候选'))}"
|
||||
title="${escapeInfoCardHtml(blocked ? disabledTitle : infoText('采集坐标候选'))}"
|
||||
${blocked ? 'disabled aria-disabled="true"' : ''}
|
||||
data-context-json="${contextJson}">采集</button>
|
||||
data-context-json="${contextJson}">${escapeInfoCardHtml(getEarthLocale() === 'en-US' ? 'Collect' : '采集')}</button>
|
||||
</div>
|
||||
<div class="info-card-compute-collect-status" data-unresolved-status>${escapeInfoCardHtml(cached?.statusText || '')}</div>
|
||||
<div class="info-card-compute-collect-candidates" data-unresolved-candidates>
|
||||
@@ -863,14 +883,14 @@ function renderComputeCenterUnresolvedContent(content, data) {
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="info-card-unresolved-summary">
|
||||
<span data-unresolved-summary-text>${items.length} 个算力中心没有可信坐标</span>
|
||||
<span data-unresolved-summary-text>${escapeInfoCardHtml(infoText(`${items.length} 个算力中心没有可信坐标`))}</span>
|
||||
<button type="button" class="info-card-compute-candidate-preview info-card-unresolved-adopt"
|
||||
data-unresolved-adopt-all
|
||||
data-requires-web-search="true"
|
||||
data-ready-title="一键定位并采用最高置信候选"
|
||||
title="${escapeInfoCardHtml(blocked ? disabledTitle : '一键定位并采用最高置信候选')}"
|
||||
data-ready-title="${escapeInfoCardHtml(infoText('一键定位并采用最高置信候选'))}"
|
||||
title="${escapeInfoCardHtml(blocked ? disabledTitle : infoText('一键定位并采用最高置信候选'))}"
|
||||
${blocked ? 'disabled aria-disabled="true"' : ''}>
|
||||
一键定位
|
||||
${escapeInfoCardHtml(infoText('一键定位'))}
|
||||
</button>
|
||||
</div>
|
||||
<div class="info-card-compute-collect-status" data-unresolved-batch-status>${escapeInfoCardHtml(computeCenterUnresolvedBatchState.statusText || '')}</div>
|
||||
@@ -888,8 +908,8 @@ function updateUnresolvedSummary(content) {
|
||||
const summaryText = content.querySelector('[data-unresolved-summary-text]');
|
||||
if (summaryText) {
|
||||
summaryText.textContent = remainingCount > 0
|
||||
? `${remainingCount} 个算力中心没有可信坐标`
|
||||
: '当前没有待定位算力中心';
|
||||
? infoText(`${remainingCount} 个算力中心没有可信坐标`)
|
||||
: infoText('当前没有待定位算力中心');
|
||||
}
|
||||
const adoptAllButton = content.querySelector('[data-unresolved-adopt-all]');
|
||||
if (adoptAllButton instanceof HTMLButtonElement) {
|
||||
@@ -948,7 +968,7 @@ async function collectUnresolvedComputeCenterCandidates(context, options = {}) {
|
||||
async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel = '') {
|
||||
setLocationCollectState(context, {
|
||||
loading: true,
|
||||
statusText: progressLabel || '正在一键定位并采用最高置信候选...',
|
||||
statusText: infoText(progressLabel || '正在一键定位并采用最高置信候选...'),
|
||||
candidates: [],
|
||||
});
|
||||
const { mod, result, candidates } = await collectUnresolvedComputeCenterCandidates(
|
||||
@@ -958,7 +978,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
|
||||
if (!result?.success) {
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `未找到可采用候选:${formatLocationCollectFailure(result)}`,
|
||||
statusText: infoText(`未找到可采用候选:${formatLocationCollectFailure(result)}`),
|
||||
candidates: [],
|
||||
result,
|
||||
});
|
||||
@@ -966,7 +986,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
|
||||
}
|
||||
setLocationCollectState(context, {
|
||||
loading: true,
|
||||
statusText: `找到 ${candidates.length} 个候选,正在保存最高置信位置...`,
|
||||
statusText: infoText(`找到 ${candidates.length} 个候选,正在保存最高置信位置...`),
|
||||
candidates,
|
||||
result,
|
||||
});
|
||||
@@ -974,7 +994,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
|
||||
if (!bestCandidate) {
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: '未找到包含有效经纬度的候选',
|
||||
statusText: infoText('未找到包含有效经纬度的候选'),
|
||||
candidates,
|
||||
result,
|
||||
});
|
||||
@@ -983,7 +1003,7 @@ async function saveBestUnresolvedComputeCenterCandidate(context, progressLabel =
|
||||
const saveResult = await mod.saveComputeCenterLocation(context.sourceId, bestCandidate, context);
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: '坐标已保存,等待图层刷新',
|
||||
statusText: infoText('坐标已保存,等待图层刷新'),
|
||||
candidates,
|
||||
result,
|
||||
savedCandidate: bestCandidate,
|
||||
@@ -1052,7 +1072,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
setLocationButtonLoading(button, true, '正在定位');
|
||||
setLocationCollectState(context, {
|
||||
loading: true,
|
||||
statusText: '正在采集坐标候选...',
|
||||
statusText: infoText('正在采集坐标候选...'),
|
||||
candidates: [],
|
||||
});
|
||||
try {
|
||||
@@ -1060,7 +1080,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
if (!result?.success) {
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `未能采集到坐标:${formatLocationCollectFailure(result)}`,
|
||||
statusText: infoText(`未能采集到坐标:${formatLocationCollectFailure(result)}`),
|
||||
candidates: [],
|
||||
result,
|
||||
});
|
||||
@@ -1068,7 +1088,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
}
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `共找到 ${candidates.length} 个候选位置`,
|
||||
statusText: infoText(`共找到 ${candidates.length} 个候选位置`),
|
||||
candidates,
|
||||
result,
|
||||
});
|
||||
@@ -1084,7 +1104,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
console.error('collect unresolved compute-center location failed', error);
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `采集失败:${error?.message || error}`,
|
||||
statusText: infoText(`采集失败:${error?.message || error}`),
|
||||
candidates: [],
|
||||
});
|
||||
} finally {
|
||||
@@ -1127,7 +1147,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
processed: 0,
|
||||
saved: 0,
|
||||
missed: 0,
|
||||
statusText: `一键定位进行中 0/${pendingItems.length}...`,
|
||||
statusText: infoText(`一键定位进行中 0/${pendingItems.length}...`),
|
||||
});
|
||||
|
||||
let savedCount = 0;
|
||||
@@ -1136,7 +1156,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
for (const [index, { itemRoot, context }] of pendingItems.entries()) {
|
||||
const itemStatusEl = itemRoot.querySelector('[data-unresolved-status]');
|
||||
itemRoot.classList.add('is-locating');
|
||||
const progressText = `正在定位并采用最高置信候选 ${index + 1}/${pendingItems.length}...`;
|
||||
const progressText = infoText(`正在定位并采用最高置信候选 ${index + 1}/${pendingItems.length}...`);
|
||||
setUnresolvedBatchState({
|
||||
statusText: progressText,
|
||||
processed: index,
|
||||
@@ -1147,7 +1167,7 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
try {
|
||||
const saveOutcome = await saveBestUnresolvedComputeCenterCandidate(context, progressText);
|
||||
if (!saveOutcome.saved) {
|
||||
if (itemStatusEl) itemStatusEl.textContent = getLocationCollectState(context)?.statusText || '未找到可采用候选';
|
||||
if (itemStatusEl) itemStatusEl.textContent = getLocationCollectState(context)?.statusText || infoText('未找到可采用候选');
|
||||
missedCount += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -1157,11 +1177,11 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
console.error('adopt unresolved compute-center location failed', error);
|
||||
setLocationCollectState(context, {
|
||||
loading: false,
|
||||
statusText: `一键定位失败:${error?.message || error}`,
|
||||
statusText: infoText(`一键定位失败:${error?.message || error}`),
|
||||
candidates: [],
|
||||
});
|
||||
if (itemStatusEl) {
|
||||
itemStatusEl.textContent = `一键采用失败:${error?.message || error}`;
|
||||
itemStatusEl.textContent = infoText(`一键采用失败:${error?.message || error}`);
|
||||
}
|
||||
missedCount += 1;
|
||||
} finally {
|
||||
@@ -1170,14 +1190,14 @@ function bindComputeCenterUnresolvedControls(content) {
|
||||
processed: index + 1,
|
||||
saved: savedCount,
|
||||
missed: missedCount,
|
||||
statusText: `一键定位进行中 ${index + 1}/${pendingItems.length},已保存 ${savedCount} 个${missedCount ? `,失败 ${missedCount} 个` : ''}`,
|
||||
statusText: infoText(`一键定位进行中 ${index + 1}/${pendingItems.length},已保存 ${savedCount} 个${missedCount ? `,失败 ${missedCount} 个` : ''}`),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const finalStatus = savedCount > 0
|
||||
? `已定位并采用 ${savedCount} 个最高置信候选${missedCount ? `,${missedCount} 个仍需手动处理` : ''}`
|
||||
: `${missedCount} 个都没有可自动采用的候选,需要手动处理`;
|
||||
? infoText(`已定位并采用 ${savedCount} 个最高置信候选${missedCount ? `,${missedCount} 个仍需手动处理` : ''}`)
|
||||
: infoText(`${missedCount} 个都没有可自动采用的候选,需要手动处理`);
|
||||
if (statusEl) statusEl.textContent = finalStatus;
|
||||
setUnresolvedBatchState({
|
||||
running: false,
|
||||
@@ -1213,7 +1233,7 @@ function getFieldSourceLabel(data, fieldKey) {
|
||||
if (!sources || typeof sources !== 'object') return '';
|
||||
const source = sources[fieldKey];
|
||||
if (!source) return '';
|
||||
return ` <span class="info-card-source-tag" title="字段来源">${source}</span>`;
|
||||
return ` <span class="info-card-source-tag" title="${escapeInfoCardHtml(infoText('字段来源'))}">${escapeInfoCardHtml(infoText(source))}</span>`;
|
||||
}
|
||||
|
||||
function renderVesselEnrichmentSection(enrichment) {
|
||||
@@ -1223,8 +1243,8 @@ function renderVesselEnrichmentSection(enrichment) {
|
||||
if (!profile && !media) {
|
||||
return `
|
||||
<div class="info-card-enrichment info-card-enrichment--empty">
|
||||
<div class="info-card-enrichment-title">船舶资料</div>
|
||||
<div class="info-card-enrichment-status">资料缓存中</div>
|
||||
<div class="info-card-enrichment-title">${escapeInfoCardHtml(infoText('船舶资料'))}</div>
|
||||
<div class="info-card-enrichment-status">${escapeInfoCardHtml(infoText('资料缓存中'))}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -1244,11 +1264,11 @@ function renderVesselEnrichmentSection(enrichment) {
|
||||
inner += renderEnrichmentMeta('媒体', media);
|
||||
}
|
||||
if (!inner) {
|
||||
inner = '<div class="info-card-enrichment-status">资料缓存中</div>';
|
||||
inner = `<div class="info-card-enrichment-status">${escapeInfoCardHtml(infoText('资料缓存中'))}</div>`;
|
||||
}
|
||||
return `
|
||||
<div class="info-card-enrichment">
|
||||
<div class="info-card-enrichment-title">船舶资料</div>
|
||||
<div class="info-card-enrichment-title">${escapeInfoCardHtml(infoText('船舶资料'))}</div>
|
||||
${inner}
|
||||
</div>
|
||||
`;
|
||||
@@ -1261,8 +1281,8 @@ function renderEnrichmentPayloadRows(payload) {
|
||||
if (typeof value === 'object') continue;
|
||||
rows += `
|
||||
<div class="info-card-property">
|
||||
<span class="info-card-label">${key}</span>
|
||||
<span class="info-card-value">${String(value)}</span>
|
||||
<span class="info-card-label">${escapeInfoCardHtml(infoText(key))}</span>
|
||||
<span class="info-card-value">${escapeInfoCardHtml(infoText(String(value)))}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -1271,45 +1291,45 @@ function renderEnrichmentPayloadRows(payload) {
|
||||
|
||||
function renderEnrichmentMeta(label, record) {
|
||||
const parts = [];
|
||||
if (record.source) parts.push(`来源 ${record.source}`);
|
||||
if (record.fetched_at) parts.push(`更新 ${record.fetched_at}`);
|
||||
if (record.source) parts.push(infoText(`来源 ${record.source}`));
|
||||
if (record.fetched_at) parts.push(infoText(`更新 ${record.fetched_at}`));
|
||||
if (record.confidence !== null && record.confidence !== undefined) {
|
||||
parts.push(`置信 ${Number(record.confidence).toFixed(2)}`);
|
||||
parts.push(infoText(`置信 ${Number(record.confidence).toFixed(2)}`));
|
||||
}
|
||||
if (!parts.length) return '';
|
||||
return `<div class="info-card-enrichment-meta">${label}:${parts.join(' · ')}</div>`;
|
||||
return `<div class="info-card-enrichment-meta">${escapeInfoCardHtml(infoText(label))}: ${escapeInfoCardHtml(parts.join(' · '))}</div>`;
|
||||
}
|
||||
|
||||
// ── Mobile popup ─────────────────────────────────────────────
|
||||
|
||||
function getMobilePopupTitle(type, data) {
|
||||
switch (type) {
|
||||
case 'cable': return data.name || '海缆';
|
||||
case 'landing_point': return data.name || '登陆点';
|
||||
case 'satellite': return data.name || '卫星';
|
||||
case 'bgp': return data.anomaly_type || 'BGP事件';
|
||||
case 'cable': return data.name || infoText('海缆');
|
||||
case 'landing_point': return data.name || infoText('登陆点');
|
||||
case 'satellite': return data.name || infoText('卫星');
|
||||
case 'bgp': return data.anomaly_type || infoText('BGP事件');
|
||||
case 'news': return getNewsCardTitle(data);
|
||||
case 'bgp_collector': return data.collector || 'BGP观测站';
|
||||
case 'compute_center_unresolved': return '待定位算力中心';
|
||||
case 'supercomputer': return data.name || '超算';
|
||||
case 'gpu_cluster': return data.name || 'GPU集群';
|
||||
case 'vessel': return data.name || '船只';
|
||||
default: return '详情';
|
||||
case 'bgp_collector': return data.collector || infoText('BGP观测站');
|
||||
case 'compute_center_unresolved': return infoText('待定位算力中心');
|
||||
case 'supercomputer': return data.name || infoText('超算');
|
||||
case 'gpu_cluster': return data.name || infoText('GPU集群');
|
||||
case 'vessel': return data.name || infoText('船只');
|
||||
default: return infoText('详情');
|
||||
}
|
||||
}
|
||||
|
||||
function getMobilePopupSubtitle(type, data) {
|
||||
switch (type) {
|
||||
case 'cable': return data.owner || data.status || '海缆';
|
||||
case 'landing_point': return data.country || '登陆点';
|
||||
case 'satellite': return data.norad_id ? `NORAD ${data.norad_id}` : '卫星';
|
||||
case 'bgp': return data.severity || 'BGP路由异常';
|
||||
case 'news': return getNewsCardSummaryPreview(data, 30) || '态势新闻';
|
||||
case 'bgp_collector': return data.location || 'BGP观测站';
|
||||
case 'compute_center_unresolved': return `${data?.totalCount || 0} 个待定位`;
|
||||
case 'supercomputer': return data.country || '超级计算机';
|
||||
case 'gpu_cluster': return data.country || 'GPU集群';
|
||||
case 'vessel': return data.vessel_type || 'AIS 船只';
|
||||
case 'cable': return infoText(data.owner || data.status || '海缆');
|
||||
case 'landing_point': return localizeCountryName(data.country) || infoText('登陆点');
|
||||
case 'satellite': return data.norad_id ? `NORAD ${data.norad_id}` : infoText('卫星');
|
||||
case 'bgp': return infoText(data.severity || 'BGP路由异常');
|
||||
case 'news': return getNewsCardSummaryPreview(data, 30) || infoText('态势新闻');
|
||||
case 'bgp_collector': return data.location || infoText('BGP观测站');
|
||||
case 'compute_center_unresolved': return infoText(`${data?.totalCount || 0} 个待定位`);
|
||||
case 'supercomputer': return localizeCountryName(data.country) || infoText('超级计算机');
|
||||
case 'gpu_cluster': return localizeCountryName(data.country) || infoText('GPU集群');
|
||||
case 'vessel': return data.vessel_type || infoText('AIS 船只');
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
@@ -1809,8 +1829,8 @@ function mountCard() {
|
||||
<div id="info-card" class="info-card">
|
||||
<div class="info-card-header hud-panel-drag-handle">
|
||||
<span class="info-card-icon" id="info-card-icon">🛰️</span>
|
||||
<h3 id="info-card-title">详情</h3>
|
||||
<button class="info-card-close hud-panel-close" type="button" aria-label="关闭详情">
|
||||
<h3 id="info-card-title">${escapeInfoCardHtml(infoText('详情'))}</h3>
|
||||
<button class="info-card-close hud-panel-close" type="button" aria-label="${escapeInfoCardHtml(infoText('关闭详情'))}">
|
||||
<span class="material-symbols-rounded">close</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -1850,16 +1870,19 @@ function mountCard() {
|
||||
const value = valueEl?.textContent?.trim();
|
||||
|
||||
if (!value || value === '-') {
|
||||
showStatusMessage('无可复制内容', 'warning');
|
||||
showStatusMessage(earthMessage("status.copyEmpty"), 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
showStatusMessage(`已复制${label.textContent}:${value}`, 'success');
|
||||
showStatusMessage(
|
||||
earthMessage("status.copyValue", { label: label.textContent, value }),
|
||||
'success',
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Copy failed:', error);
|
||||
showStatusMessage('复制失败', 'error');
|
||||
showStatusMessage(earthMessage("status.copyFailed"), 'error');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1885,7 +1908,7 @@ function positionPanel(panel, x, y, options = {}) {
|
||||
const scale = parseFloat(
|
||||
getComputedStyle(document.documentElement).getPropertyValue('--hud-scale')
|
||||
) || 1;
|
||||
const estW = Math.min(300 * scale, vpW - 32);
|
||||
const estW = Math.min(340 * scale, vpW - 32);
|
||||
const estH = Math.min(420 * scale, vpH * 0.7);
|
||||
|
||||
if (options.absolute === true) {
|
||||
@@ -2000,11 +2023,11 @@ export function showInfoCard(type, data, options = {}) {
|
||||
if (title) {
|
||||
title.textContent = type === 'news'
|
||||
? getNewsCardTitle(data)
|
||||
: config.title;
|
||||
: infoText(config.title);
|
||||
}
|
||||
if (typeLabel) {
|
||||
typeLabel.textContent = type === 'news'
|
||||
? '新闻信号'
|
||||
? infoText('新闻信号')
|
||||
: type.replaceAll('_', ' ');
|
||||
}
|
||||
|
||||
@@ -2041,7 +2064,7 @@ export function showInfoCard(type, data, options = {}) {
|
||||
icon.textContent = config.icon;
|
||||
title.textContent = type === 'news'
|
||||
? getNewsCardTitle(data)
|
||||
: config.title;
|
||||
: infoText(config.title);
|
||||
|
||||
if (type === 'news') {
|
||||
renderNewsCardContent(content, data);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { translateText } from "./i18n.js";
|
||||
|
||||
export function setButtonTooltip(button, text) {
|
||||
const translatedText = translateText(text);
|
||||
if (button instanceof HTMLElement) {
|
||||
button.title = text;
|
||||
button.title = translatedText;
|
||||
}
|
||||
const tooltip = button?.querySelector(".earth-toolbar-tooltip");
|
||||
if (tooltip) {
|
||||
tooltip.textContent = text;
|
||||
tooltip.textContent = translatedText;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
loadCountryBoundaries,
|
||||
toggleCountryBoundaries,
|
||||
} from "./country-boundaries.js";
|
||||
import { earthMessage } from "./i18n.js";
|
||||
|
||||
/**
|
||||
* Layer startup task registry.
|
||||
@@ -101,7 +102,7 @@ function registerVesselStartupTask() {
|
||||
if (!context.getShowVessels()) return;
|
||||
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载船只..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.vessels")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -125,7 +126,7 @@ function registerCableStartupTask() {
|
||||
if (!context.isCablesEnabled()) return;
|
||||
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "prepare", "正在加载登陆点..."),
|
||||
resolveStartupMessage(layer, "prepare", earthMessage("startup.landingPoints")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -137,7 +138,7 @@ function registerCableStartupTask() {
|
||||
await context.yieldFrame(16);
|
||||
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载海缆..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.cables")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -161,7 +162,7 @@ function registerSatelliteStartupTask() {
|
||||
if (!context.isSatellitesEnabled()) return;
|
||||
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载卫星..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.satellites")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -200,7 +201,7 @@ function registerSatelliteStartupTask() {
|
||||
function registerBGPStartupTask() {
|
||||
registerLayerStartupTask("bgp", (context) => async (layer) => {
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载BGP态势..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.bgp")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -223,7 +224,7 @@ function registerEarthTextureStartupTask() {
|
||||
if (!context.isEarthTextureVisible()) return;
|
||||
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载地球纹理..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.hdTexture")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -241,7 +242,7 @@ function registerCloudStartupTask() {
|
||||
if (!context.isCloudsEnabled()) return;
|
||||
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载大气云图..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.clouds")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -257,7 +258,7 @@ function registerCloudStartupTask() {
|
||||
function registerCountryBoundaryStartupTask() {
|
||||
registerLayerStartupTask("countryBoundaries", (context) => async (layer) => {
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载海陆基座..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.landOceanBase")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
@@ -283,7 +284,7 @@ function registerCountryBoundaryStartupTask() {
|
||||
function registerComputeCenterStartupTask() {
|
||||
registerLayerStartupTask("computeCenters", (context) => async (layer) => {
|
||||
context.setLoadingMessage(
|
||||
resolveStartupMessage(layer, "load", "正在加载算力中心..."),
|
||||
resolveStartupMessage(layer, "load", earthMessage("startup.computeCenters")),
|
||||
);
|
||||
await context.yieldFrame(12);
|
||||
try {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { createHUDPanel } from "./hud-panels.js";
|
||||
import { getEarthLocale, translateText } from "./i18n.js";
|
||||
|
||||
const LEGEND_MODES = {
|
||||
cables: { title: "海缆" },
|
||||
satellites: { title: "卫星" },
|
||||
cables: { title: "海缆", compactTitleEn: "Cables" },
|
||||
satellites: { title: "卫星", compactTitleEn: "Orbits" },
|
||||
countryBoundaries: { title: "国界" },
|
||||
computeCenters: { title: "算力" },
|
||||
vessels: { title: "船只" },
|
||||
@@ -11,6 +12,7 @@ const LEGEND_MODES = {
|
||||
|
||||
let currentLegendMode = "cables";
|
||||
let legendPanel = null;
|
||||
let legendLocaleListenerBound = false;
|
||||
let legendItemsByMode = {
|
||||
cables: [],
|
||||
satellites: [],
|
||||
@@ -40,6 +42,14 @@ export function initLegend() {
|
||||
});
|
||||
}
|
||||
|
||||
if (!legendLocaleListenerBound) {
|
||||
legendLocaleListenerBound = true;
|
||||
window.addEventListener("earth:locale-change", () => {
|
||||
syncCurrentLabel(currentLegendMode);
|
||||
renderLegend(currentLegendMode);
|
||||
});
|
||||
}
|
||||
|
||||
syncCurrentLabel(currentLegendMode);
|
||||
renderLegend(currentLegendMode);
|
||||
}
|
||||
@@ -68,24 +78,38 @@ export function setLegendItems(mode, items) {
|
||||
}
|
||||
|
||||
function syncCurrentLabel(mode) {
|
||||
const nextLabel = LEGEND_MODES[mode]?.title || LEGEND_MODES.cables.title;
|
||||
const nextLabel = getLegendModeTitle(mode);
|
||||
[document.getElementById("legend-current-label"), document.getElementById("mobile-situation-legend-mode")]
|
||||
.forEach((labelEl) => {
|
||||
if (labelEl) {
|
||||
labelEl.textContent = nextLabel;
|
||||
const translatedLabel = getEarthLocale() === "en-US" ? nextLabel : translateText(nextLabel);
|
||||
labelEl.textContent = translatedLabel;
|
||||
labelEl.dataset.i18nOriginalTitle = translatedLabel;
|
||||
labelEl.title = translatedLabel;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getLegendModeTitle(mode) {
|
||||
const definition = LEGEND_MODES[mode] || LEGEND_MODES.cables;
|
||||
if (getEarthLocale() === "en-US" && definition.compactTitleEn) {
|
||||
return definition.compactTitleEn;
|
||||
}
|
||||
return definition.title;
|
||||
}
|
||||
|
||||
function renderLegend(mode) {
|
||||
const items = legendItemsByMode[mode] || [];
|
||||
const html = items
|
||||
.map(
|
||||
(item) => `
|
||||
(item) => {
|
||||
const label = escapeLegendHtml(translateText(item.label));
|
||||
return `
|
||||
<div class="legend-item">
|
||||
<span class="legend-dot legend-dot--${item.shape || "dot"}" style="background:${item.color}; color:${item.color}"></span>
|
||||
<span class="legend-label">${item.label}</span>
|
||||
</div>`,
|
||||
<span class="legend-label" title="${label}">${label}</span>
|
||||
</div>`;
|
||||
},
|
||||
)
|
||||
.join("");
|
||||
|
||||
@@ -99,3 +123,12 @@ function renderLegend(mode) {
|
||||
mobileList.innerHTML = html;
|
||||
}
|
||||
}
|
||||
|
||||
function escapeLegendHtml(value) {
|
||||
return String(value ?? "")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import * as THREE from "three";
|
||||
|
||||
import {
|
||||
earthMessage,
|
||||
getEarthLocale,
|
||||
initEarthI18n,
|
||||
localizeCountryName,
|
||||
onEarthLocaleChange,
|
||||
translateText,
|
||||
} from "./i18n.js";
|
||||
import {
|
||||
CONFIG,
|
||||
CRUISE_MODULES,
|
||||
@@ -304,6 +312,12 @@ import {
|
||||
setMotionDebugPanelVisible,
|
||||
} from "./motion-debug-panel.js";
|
||||
|
||||
initEarthI18n();
|
||||
window.addEventListener("earth:status", (event) => {
|
||||
const message = event.detail?.message;
|
||||
if (message) showStatusMessage(message, event.detail?.type || "info");
|
||||
});
|
||||
|
||||
const EARTH_RADIUS_KM = 6371;
|
||||
const EARTH_GRAVITATIONAL_PARAMETER_KM3_S2 = 398600.4418;
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
@@ -343,6 +357,7 @@ let earthTexture = null;
|
||||
let animationFrameId = null;
|
||||
let initialized = false;
|
||||
let destroyed = false;
|
||||
let runtimeBrandConfig = null;
|
||||
let isDataLoading = false;
|
||||
let currentLoadToken = 0;
|
||||
let cablesEnabled = true;
|
||||
@@ -357,6 +372,21 @@ let calloutConnector = null;
|
||||
let cruiseBGPAdapter = null;
|
||||
let cruiseNewsAdapter = null;
|
||||
let cruiseSequencer = null;
|
||||
|
||||
function getEarthBrandLanguage() {
|
||||
return getEarthLocale() === "en-US" ? "en" : (HUD_CONFIG.brandLanguage || "zh");
|
||||
}
|
||||
|
||||
function getLocalizedBrandConfig(config = null) {
|
||||
if (config && typeof config === "object") {
|
||||
return { ...config, variant: config.variant || getEarthBrandLanguage() };
|
||||
}
|
||||
return getEarthBrandLanguage();
|
||||
}
|
||||
|
||||
function remountEarthBrand() {
|
||||
mountBrand(document.getElementById("brand-root"), getLocalizedBrandConfig(runtimeBrandConfig));
|
||||
}
|
||||
let cruiseRandomQueueSignature = "";
|
||||
let cruiseRandomQueueItems = [];
|
||||
let earthUpdatesSocket = null;
|
||||
@@ -419,6 +449,21 @@ const VESSEL_POINTER_RADIUS_PX = 22;
|
||||
const INTERACTABLE_POINTER_RADIUS_PX = 24;
|
||||
const MOTION_FOCUS_RADIUS_PX = 180;
|
||||
const MOTION_FOCUS_REFRESH_MS = 350;
|
||||
|
||||
function isEnglishEarthLocale() {
|
||||
return getEarthLocale() === "en-US";
|
||||
}
|
||||
|
||||
function formatUnresolvedComputeTitle(count) {
|
||||
return isEnglishEarthLocale()
|
||||
? `${count} compute centers pending location`
|
||||
: `${count} 个算力中心待定位`;
|
||||
}
|
||||
|
||||
function formatUnresolvedComputeSuffix(count) {
|
||||
if (count <= 0) return "";
|
||||
return isEnglishEarthLocale() ? ` (${count} pending location)` : `(${count} 个待定位)`;
|
||||
}
|
||||
const MOTION_MARKER_ANCHOR_SIZE_PX = 24;
|
||||
const MOTION_SATELLITE_ANCHOR_SIZE_PX = 18;
|
||||
const MOTION_CABLE_ANCHOR_SIZE_PX = 14;
|
||||
@@ -881,7 +926,9 @@ function getPrimaryClusterHit(...intersectionGroups) {
|
||||
|
||||
function getClusterBriefHtml(hit) {
|
||||
const count = Number(hit?.clusterCount || hit?.clusterMarkers?.length || 0);
|
||||
return `<strong>共 ${count} 个对象</strong><br><span>放大后可查看单个图标</span>`;
|
||||
const title = isEnglishEarthLocale() ? `${count} objects` : `共 ${count} 个对象`;
|
||||
const hint = isEnglishEarthLocale() ? "Zoom in to inspect individual markers" : "放大后可查看单个图标";
|
||||
return `<strong>${title}</strong><br><span>${hint}</span>`;
|
||||
}
|
||||
|
||||
function getPrimaryBGPHoverTarget(bgpAnomalyIntersects, bgpCollectorIntersects) {
|
||||
@@ -1336,7 +1383,7 @@ async function applyMotionSharedCruiseFocus(direction = "next") {
|
||||
|
||||
const presented = await sequencer.presentSpecificItem(targetItem, { interrupt: true });
|
||||
if (presented) {
|
||||
showStatusMessage("动捕: 已切换巡航目标", "info");
|
||||
showStatusMessage(earthMessage("status.motionCruiseTargetSwitched"), "info");
|
||||
}
|
||||
return Boolean(presented);
|
||||
}
|
||||
@@ -1465,7 +1512,10 @@ export async function applyMotionFocus(direction = "next") {
|
||||
refreshMotionFocusCandidates({ force: true });
|
||||
if (motionFocusCandidates.length === 0) {
|
||||
const layer = getCurrentMotionFocusLayer();
|
||||
showStatusMessage(layer ? `动捕: ${layer.label}当前视野没有可选目标` : "动捕: 当前没有可用图层", "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.motionNoTarget", { layer: layer?.label || "" }),
|
||||
"info",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const delta = direction === "prev" ? -1 : 1;
|
||||
@@ -1473,7 +1523,10 @@ export async function applyMotionFocus(direction = "next") {
|
||||
const candidate = motionFocusCandidates[motionFocusIndex];
|
||||
applyMotionFocusVisual(candidate);
|
||||
await presentMotionCandidate(candidate);
|
||||
showStatusMessage(`动捕: 已切换到${getMotionCandidateLabel(candidate)}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.motionSwitchedTo", { label: getMotionCandidateLabel(candidate) }),
|
||||
"info",
|
||||
);
|
||||
return true;
|
||||
} finally {
|
||||
releaseGate();
|
||||
@@ -1486,7 +1539,7 @@ export async function applyMotionLayerSwitch(direction = "next") {
|
||||
try {
|
||||
const layers = getVisibleMotionLayerDefinitions();
|
||||
if (layers.length === 0) {
|
||||
showStatusMessage("动捕: 当前没有可切换的可见图层", "info");
|
||||
showStatusMessage(earthMessage("status.motionNoVisibleLayer"), "info");
|
||||
return false;
|
||||
}
|
||||
const currentIndex = layers.findIndex((layer) => layer.id === motionFocusLayerId);
|
||||
@@ -1505,7 +1558,10 @@ export async function applyMotionLayerSwitch(direction = "next") {
|
||||
if (candidate) {
|
||||
await presentMotionCandidate(candidate);
|
||||
}
|
||||
showStatusMessage(`动捕: 已切换到${nextLayer.label}图层`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.motionSwitchedTo", { label: nextLayer.label, layer: true }),
|
||||
"info",
|
||||
);
|
||||
return true;
|
||||
} finally {
|
||||
releaseGate();
|
||||
@@ -1673,7 +1729,10 @@ function confirmMotionCandidate(candidate, { showMotionStatus = true } = {}) {
|
||||
});
|
||||
window.dispatchEvent(new CustomEvent("earth:open-details-tab"));
|
||||
if (showMotionStatus) {
|
||||
showStatusMessage(`动捕: 已确认${getMotionCandidateLabel(candidate)}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.motionConfirmed", { label: getMotionCandidateLabel(candidate) }),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1693,7 +1752,7 @@ function showCableInfo(cable, coords) {
|
||||
function getCableBriefHtml(cable) {
|
||||
const name = cable.userData.name || "未知海缆";
|
||||
const status = cable.userData.status || "";
|
||||
return `<strong>${name}</strong>${status ? `<br>${status}` : ""}`;
|
||||
return `<strong>${translateText(name)}</strong>${status ? `<br>${translateText(status)}` : ""}`;
|
||||
}
|
||||
|
||||
function showSatelliteInfo(props, coords) {
|
||||
@@ -1822,7 +1881,7 @@ function showVesselInfo(marker, coords) {
|
||||
status: formatVesselStatus(marker.userData?.nav_status),
|
||||
length: marker.userData?.length ?? "-",
|
||||
received_at: marker.userData?.received_at
|
||||
? new Date(marker.userData.received_at).toLocaleString("zh-CN", { hour12: false })
|
||||
? new Date(marker.userData.received_at).toLocaleString(getEarthLocale(), { hour12: false })
|
||||
: "-",
|
||||
}, coords);
|
||||
}
|
||||
@@ -1846,31 +1905,31 @@ function getEarthInteractableBriefHtml(marker) {
|
||||
const ud = marker?.userData || {};
|
||||
const name = ud.label || ud.name || "交互点";
|
||||
const kind = ud.kind || "数据点";
|
||||
return `<strong>${name}</strong><br>${kind}`;
|
||||
return `<strong>${translateText(name)}</strong><br>${translateText(kind)}`;
|
||||
}
|
||||
|
||||
function getVesselBriefHtml(marker) {
|
||||
const name = marker.userData?.name || `MMSI ${marker.userData?.mmsi}`;
|
||||
const speed = marker.userData?.sog ?? "-";
|
||||
const vesselType = marker.userData?.vessel_type_display || marker.userData?.vessel_type_name || "Vessel";
|
||||
return `<strong>${name}</strong><br>${vesselType} · ${speed} kn`;
|
||||
return `<strong>${translateText(name)}</strong><br>${translateText(vesselType)} · ${speed} kn`;
|
||||
}
|
||||
|
||||
function getComputeCenterBriefHtml(marker) {
|
||||
const name = marker.userData?.name || "算力中心";
|
||||
const type = formatComputeCenterTypeLabel(marker.userData?.site_type);
|
||||
const location = [marker.userData?.city, marker.userData?.country]
|
||||
const location = [marker.userData?.city, localizeCountryName(marker.userData?.country)]
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
const precision = marker.userData?.is_estimated ? " · 估算位置" : "";
|
||||
return `<strong>${name}</strong><br>${type}${location ? ` · ${location}` : ""}${precision}`;
|
||||
const precision = marker.userData?.is_estimated ? ` · ${translateText("估算位置")}` : "";
|
||||
return `<strong>${translateText(name)}</strong><br>${translateText(type)}${location ? ` · ${location}` : ""}${precision}`;
|
||||
}
|
||||
|
||||
function getCountryBoundaryBriefHtml(country) {
|
||||
const name = country?.nameZh || country?.name || "未知国家";
|
||||
const name = localizeCountryName(country) || translateText("未知国家");
|
||||
const code = country?.isoA3 || country?.isoA2 || "-";
|
||||
const continent = country?.continent || "-";
|
||||
return `<strong>${name}</strong><br>ISO: ${code}<br>大洲: ${continent}`;
|
||||
const continent = translateText(country?.continent || "-");
|
||||
return `<strong>${name}</strong><br>ISO: ${code}<br>${translateText("大洲")}: ${continent}`;
|
||||
}
|
||||
|
||||
function getSurfacePositionBriefHtml(coords) {
|
||||
@@ -1880,7 +1939,7 @@ function getSurfacePositionBriefHtml(coords) {
|
||||
? `${(elevMeters / 1000).toFixed(2)} km`
|
||||
: `${Math.round(elevMeters)} m`
|
||||
: "—";
|
||||
return `纬度: ${coords.lat}°<br>经度: ${coords.lon}°<br>海拔: ${elevText}`;
|
||||
return `${translateText("纬度")}: ${coords.lat}°<br>${translateText("经度")}: ${coords.lon}°<br>${translateText("海拔")}: ${elevText}`;
|
||||
}
|
||||
|
||||
function showBGPInfo(marker, coords) {
|
||||
@@ -1920,7 +1979,9 @@ function showBGPInfo(marker, coords) {
|
||||
),
|
||||
prefix:
|
||||
Array.isArray(marker.userData.prefixes) && marker.userData.prefixes.length > 1
|
||||
? `${marker.userData.prefixes[0]} 等${marker.userData.prefixes.length}个`
|
||||
? isEnglishEarthLocale()
|
||||
? `${marker.userData.prefixes[0]} + ${marker.userData.prefixes.length - 1}`
|
||||
: `${marker.userData.prefixes[0]} 等${marker.userData.prefixes.length}个`
|
||||
: marker.userData.prefix,
|
||||
as_path_display:
|
||||
Array.isArray(marker.userData.as_path) && marker.userData.as_path.length > 0
|
||||
@@ -1932,7 +1993,9 @@ function showBGPInfo(marker, coords) {
|
||||
: marker.userData.origin_asn,
|
||||
new_origin_asn:
|
||||
Array.isArray(marker.userData.affected_asns) && marker.userData.affected_asns.length > 3
|
||||
? `共${marker.userData.affected_asns.length}个ASN`
|
||||
? isEnglishEarthLocale()
|
||||
? `${marker.userData.affected_asns.length} ASNs`
|
||||
: `共${marker.userData.affected_asns.length}个ASN`
|
||||
: marker.userData.new_origin_asn,
|
||||
confidence: formatBGPConfidence(marker.userData.confidence),
|
||||
collector: marker.userData.collector,
|
||||
@@ -1941,7 +2004,9 @@ function showBGPInfo(marker, coords) {
|
||||
related_cables: relatedCables,
|
||||
related_satellites:
|
||||
marker.userData.related_satellite_count > 0
|
||||
? `${marker.userData.related_satellite_count}颗事件附近卫星`
|
||||
? isEnglishEarthLocale()
|
||||
? `${marker.userData.related_satellite_count} nearby event satellites`
|
||||
: `${marker.userData.related_satellite_count}颗事件附近卫星`
|
||||
: "-",
|
||||
location:
|
||||
marker.userData.location ||
|
||||
@@ -1983,7 +2048,8 @@ function showBGPCollectorInfo(marker, coords) {
|
||||
function getBGPCollectorBriefHtml(marker) {
|
||||
const name = marker.userData.collector || "观测站";
|
||||
const count = marker.userData.anomaly_count ?? 0;
|
||||
return `<strong>${name}</strong><br>${count} 条事件`;
|
||||
const eventText = isEnglishEarthLocale() ? `${count} events` : `${count} 条事件`;
|
||||
return `<strong>${translateText(name)}</strong><br>${eventText}`;
|
||||
}
|
||||
|
||||
function getSearchCardCoords() {
|
||||
@@ -2157,7 +2223,10 @@ async function focusSearchLandingPoint(point) {
|
||||
});
|
||||
applyLandingPointVisualState(relatedCableNames, relatedCableNames.length === 0, camera);
|
||||
showLandingPointInfo(point, getSearchCardCoords());
|
||||
showStatusMessage(`已定位登陆点:${point.userData?.name || "未知登陆点"}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.located", { target: "登陆点", name: point.userData?.name || "未知登陆点" }),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
|
||||
async function focusSearchSatellite(index) {
|
||||
@@ -2191,7 +2260,13 @@ async function focusSearchSatellite(index) {
|
||||
}
|
||||
}
|
||||
showSatelliteInfo(sat.properties, getSearchCardCoords());
|
||||
showStatusMessage(`已定位卫星:${sat.properties.name || sat.properties.norad_cat_id || "未知卫星"}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.located", {
|
||||
target: "卫星",
|
||||
name: sat.properties.name || sat.properties.norad_cat_id || "未知卫星",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
|
||||
async function focusSearchBGPMarker(marker) {
|
||||
@@ -2215,7 +2290,13 @@ async function focusSearchBGPMarker(marker) {
|
||||
showBGPEventOverlay(marker, earth);
|
||||
applyBGPEventSatelliteHighlights(marker);
|
||||
showBGPInfo(marker, getSearchCardCoords());
|
||||
showStatusMessage(`已定位 BGP 事件:${marker.userData?.collector || "未知观测站"}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.located", {
|
||||
target: "BGP 事件",
|
||||
name: marker.userData?.collector || "未知观测站",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2225,7 +2306,13 @@ async function focusSearchBGPMarker(marker) {
|
||||
lockedObjectType = "bgp_collector";
|
||||
showBGPCollectorCoverageOverlay(marker, earth);
|
||||
showBGPCollectorInfo(marker, getSearchCardCoords());
|
||||
showStatusMessage(`已定位观测站:${marker.userData?.collector || "未知观测站"}`, "info");
|
||||
showStatusMessage(
|
||||
earthMessage("status.located", {
|
||||
target: "观测站",
|
||||
name: marker.userData?.collector || "未知观测站",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2247,7 +2334,10 @@ async function focusSearchComputeCenter(marker) {
|
||||
lockedObjectType = "compute_center";
|
||||
showComputeCenterInfo(marker, getSearchCardCoords());
|
||||
showStatusMessage(
|
||||
`已定位算力中心:${marker.userData?.name || "未知节点"}`,
|
||||
earthMessage("status.located", {
|
||||
target: "算力中心",
|
||||
name: marker.userData?.name || "未知节点",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
@@ -2310,7 +2400,7 @@ async function spawnComputeCenterAfterLocationSave(detail = {}) {
|
||||
lockedObject = result.marker;
|
||||
lockedObjectType = "compute_center";
|
||||
}
|
||||
showStatusMessage("算力中心坐标已保存", "success");
|
||||
showStatusMessage(earthMessage("status.computeCoordinatesSaved"), "success");
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -2336,7 +2426,10 @@ async function focusSearchVessel(marker) {
|
||||
console.warn("船只轨迹加载失败:", error);
|
||||
});
|
||||
showStatusMessage(
|
||||
`已定位船只:${marker.userData?.name || marker.userData?.mmsi || "未知船只"}`,
|
||||
earthMessage("status.located", {
|
||||
target: "船只",
|
||||
name: marker.userData?.name || marker.userData?.mmsi || "未知船只",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
@@ -2645,16 +2738,16 @@ async function loadEarthStatsSummary({
|
||||
function updateComputeCenterHud(computeCenterResult) {
|
||||
const computeBtn = document.getElementById("toggle-compute-centers");
|
||||
const unresolvedCount = Number(computeCenterResult?.unresolvedCount) || 0;
|
||||
const unresolvedTooltip =
|
||||
unresolvedCount > 0 ? `(${unresolvedCount} 个待定位)` : "";
|
||||
const unresolvedTooltip = formatUnresolvedComputeSuffix(unresolvedCount);
|
||||
|
||||
if (computeBtn) {
|
||||
const tooltip = getShowComputeCenters()
|
||||
? `隐藏算力中心${unresolvedTooltip}`
|
||||
: `显示算力中心${unresolvedTooltip}`;
|
||||
setLayerButtonState(computeBtn, {
|
||||
active: getShowComputeCenters(),
|
||||
loading: false,
|
||||
tooltip: getShowComputeCenters()
|
||||
? `隐藏算力中心${unresolvedTooltip}`
|
||||
: `显示算力中心${unresolvedTooltip}`,
|
||||
tooltip: translateText(tooltip),
|
||||
});
|
||||
updateComputeCenterUnresolvedBadge(computeBtn, unresolvedCount);
|
||||
}
|
||||
@@ -2690,8 +2783,12 @@ function updateComputeCenterUnresolvedBadge(computeBtn, unresolvedCount) {
|
||||
|
||||
computeBtn.dataset.unresolvedCount = String(count);
|
||||
badge.textContent = count > 99 ? "99+" : String(count);
|
||||
badge.title = `${count} 个算力中心待定位`;
|
||||
badge.setAttribute("aria-label", `${count} 个算力中心待定位,点击查看`);
|
||||
const title = formatUnresolvedComputeTitle(count);
|
||||
badge.title = title;
|
||||
badge.setAttribute(
|
||||
"aria-label",
|
||||
isEnglishEarthLocale() ? `${title}, click to view` : `${title},点击查看`,
|
||||
);
|
||||
}
|
||||
|
||||
function syncComputeCenterUnresolvedCount(unresolvedCount) {
|
||||
@@ -2773,12 +2870,12 @@ function prepareToolInfoCard(type) {
|
||||
|
||||
if (hadCruisePresentation || restoreCruise) {
|
||||
stopCruiseMode({ preserveCard: false });
|
||||
showStatusMessage("已暂停巡航,正在打开候选列表", "info");
|
||||
showStatusMessage(earthMessage("status.cruisePausedOpenCandidates"), "info");
|
||||
} else if (hadMotionPresentation) {
|
||||
presentationController?.dismiss?.("tool_card_open");
|
||||
motionCruiseSequencer?.stop?.();
|
||||
motionSharedCruiseSequencer?.stop?.();
|
||||
showStatusMessage("已暂停动捕目标展示,正在打开候选列表", "info");
|
||||
showStatusMessage(earthMessage("status.motionPausedOpenCandidates"), "info");
|
||||
}
|
||||
|
||||
activeToolInfoCard = {
|
||||
@@ -2809,7 +2906,7 @@ function resumeCruiseAfterToolInfoCard(context) {
|
||||
return;
|
||||
}
|
||||
|
||||
showStatusMessage("候选列表已关闭,巡航已恢复", "info");
|
||||
showStatusMessage(earthMessage("status.candidatesClosedCruiseResumed"), "info");
|
||||
ensureCruisePolling();
|
||||
syncCruiseModuleKnownEventIds()
|
||||
.catch((error) => {
|
||||
@@ -3522,12 +3619,12 @@ function handleCruiseQueueSettingsChange() {
|
||||
|
||||
function handleCruiseNextCardShortcut() {
|
||||
if (!isCruiseModeActive()) {
|
||||
showStatusMessage("切换到巡航模式后可切换卡片", "info");
|
||||
showStatusMessage(earthMessage("status.cruiseModeRequired"), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!getAutoRotate()) {
|
||||
showStatusMessage("巡航已暂停,按空格恢复", "info");
|
||||
showStatusMessage(earthMessage("status.cruisePausedSpace"), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3770,12 +3867,7 @@ function getSatellitePointerIntersections(event) {
|
||||
|
||||
function buildLoadErrorMessage(errors) {
|
||||
if (errors.length === 0) return "";
|
||||
return errors
|
||||
.map(
|
||||
({ label, reason }) =>
|
||||
`${label}加载失败: ${reason?.message || String(reason)}`,
|
||||
)
|
||||
.join(";");
|
||||
return earthMessage("status.loadFailedList", { items: errors });
|
||||
}
|
||||
|
||||
function updateSatelliteToggleUi(enabled, satelliteCount = getSatelliteCount()) {
|
||||
@@ -4128,15 +4220,30 @@ export function init() {
|
||||
destroyed = false;
|
||||
initialized = true;
|
||||
updateHudScale();
|
||||
const brandRoot = document.getElementById("brand-root");
|
||||
mountBrand(brandRoot, HUD_CONFIG.brandLanguage);
|
||||
remountEarthBrand();
|
||||
fetchEarthBrandConfig()
|
||||
.then((brandConfig) => {
|
||||
mountBrand(brandRoot, brandConfig);
|
||||
runtimeBrandConfig = brandConfig;
|
||||
remountEarthBrand();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("Earth brand config unavailable, using defaults.", error);
|
||||
});
|
||||
cleanupFns.push(onEarthLocaleChange(() => {
|
||||
remountEarthBrand();
|
||||
updateCableToggleUi(getShowCables());
|
||||
updateSatelliteToggleUi(getShowSatellites());
|
||||
updateComputeCenterHud({
|
||||
totalCount: getComputeCenterCount(),
|
||||
unresolvedCount: getUnresolvedComputeCenters().length,
|
||||
});
|
||||
updateVesselToggleUi(getShowVessels());
|
||||
updateBGPHud({
|
||||
totalCount: getBGPCount(),
|
||||
collectorCount: getBGPCollectorCount(),
|
||||
});
|
||||
updateStatsSummary();
|
||||
}));
|
||||
initTVPanel();
|
||||
initEarthAbout();
|
||||
initEarthOobe();
|
||||
@@ -4280,7 +4387,7 @@ export function applyMotionRotate(axisOrDirection, directionOrIntensity = 1, may
|
||||
up: "向上旋转",
|
||||
down: "向下旋转",
|
||||
}[direction] || "旋转";
|
||||
showStatusMessage(`动捕: ${label}`, "info");
|
||||
showStatusMessage(earthMessage("status.motionPrefix", { text: label }), "info");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -4309,10 +4416,10 @@ export function applyMotionConfirm() {
|
||||
}
|
||||
if (lockedObject || lockedSatellite) {
|
||||
window.dispatchEvent(new CustomEvent("earth:open-details-tab"));
|
||||
showStatusMessage("动捕: 已确认当前目标", "info");
|
||||
showStatusMessage(earthMessage("status.motionConfirmCurrent"), "info");
|
||||
return true;
|
||||
}
|
||||
showStatusMessage("动捕: 请先选择目标", "info");
|
||||
showStatusMessage(earthMessage("status.motionSelectTargetFirst"), "info");
|
||||
return false;
|
||||
} finally {
|
||||
releaseGate();
|
||||
@@ -4783,7 +4890,7 @@ async function loadData() {
|
||||
clearSatelliteData();
|
||||
clearCountryBoundaryHover();
|
||||
|
||||
setLoadingMessage("正在初始化...");
|
||||
setLoadingMessage(earthMessage("loading.initializing"));
|
||||
setLoading(true);
|
||||
await yieldFrame(18);
|
||||
if (loadToken !== currentLoadToken) { isDataLoading = false; return; }
|
||||
@@ -4860,7 +4967,7 @@ async function loadData() {
|
||||
const terrainMessage = resolveStartupMessage(
|
||||
terrainLayer,
|
||||
"load",
|
||||
"正在渲染地形...",
|
||||
earthMessage("startup.terrain"),
|
||||
);
|
||||
setLoadingMessage(terrainMessage);
|
||||
await yieldFrame(24);
|
||||
@@ -4891,7 +4998,7 @@ async function loadData() {
|
||||
queueStatusMessage(errorMessage, "error");
|
||||
} else {
|
||||
hideError();
|
||||
queueStatusMessage("数据已加载", "success");
|
||||
queueStatusMessage(earthMessage("status.dataLoaded"), "success");
|
||||
}
|
||||
|
||||
applyDeferredLayerVisibilitySettings()
|
||||
@@ -4935,13 +5042,13 @@ export async function setCablesEnabled(
|
||||
clearSelectionAndInfo();
|
||||
disableCables();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("线缆已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "线缆", visible: false }), "info");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!suppressLoadingUi) {
|
||||
setLoadingMessage("正在加载线缆数据...");
|
||||
setLoadingMessage(earthMessage("loading.cableData"));
|
||||
setLoading(true);
|
||||
hideError();
|
||||
}
|
||||
@@ -4949,19 +5056,20 @@ export async function setCablesEnabled(
|
||||
try {
|
||||
const cableCount = await ensureCablesEnabled();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("线缆已显示", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "线缆", visible: true }), "info");
|
||||
}
|
||||
return cableCount;
|
||||
} catch (error) {
|
||||
cablesEnabled = false;
|
||||
clearCableData(getEarth());
|
||||
updateCableToggleUi(false);
|
||||
const message = `线缆加载失败: ${error?.message || String(error)}`;
|
||||
const reason = error?.message || String(error);
|
||||
const message = earthMessage("status.layerLoadFailed", { layer: "线缆", error: reason });
|
||||
void reportEarthClientLog({
|
||||
level: "error",
|
||||
category: "layer-toggle",
|
||||
module: "cables",
|
||||
message,
|
||||
message: `线缆加载失败: ${reason}`,
|
||||
detail: error,
|
||||
});
|
||||
if (!suppressLoadingUi) {
|
||||
@@ -4986,7 +5094,7 @@ export async function setCountryBoundariesEnabled(
|
||||
toggleCountryBoundaries(false);
|
||||
clearCountryBoundaryHover();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("国界已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "国界", visible: false }), "info");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -5002,18 +5110,19 @@ export async function setCountryBoundariesEnabled(
|
||||
setLegendItems("countryBoundaries", getCountryBoundaryLegendItems());
|
||||
refreshLegend();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("国界已显示", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "国界", visible: true }), "info");
|
||||
}
|
||||
return countryCount;
|
||||
} catch (error) {
|
||||
toggleCountryBoundaries(false);
|
||||
clearCountryBoundaryHover();
|
||||
const message = `国界加载失败: ${error?.message || String(error)}`;
|
||||
const reason = error?.message || String(error);
|
||||
const message = earthMessage("status.layerLoadFailed", { layer: "国界", error: reason });
|
||||
void reportEarthClientLog({
|
||||
level: "error",
|
||||
category: "layer-toggle",
|
||||
module: "country-boundaries",
|
||||
message,
|
||||
message: `国界加载失败: ${reason}`,
|
||||
detail: error,
|
||||
});
|
||||
if (!suppressStatus) {
|
||||
@@ -5082,7 +5191,7 @@ export async function setHighResTextureEnabled(enabled, { suppressStatus = false
|
||||
}
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(enabled ? "高清材质已启用" : "高清材质已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerEnabled", { layer: "高清材质", enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -5103,7 +5212,7 @@ export async function setAtmosphereCloudsEnabled(enabled, { suppressStatus = fal
|
||||
}
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(enabled ? "大气云图已显示" : "大气云图已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "大气云图", visible: enabled }), "info");
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
@@ -5128,7 +5237,7 @@ export async function setSatellitesEnabled(
|
||||
}
|
||||
|
||||
if (!suppressLoadingUi) {
|
||||
setLoadingMessage("正在加载卫星数据...");
|
||||
setLoadingMessage(earthMessage("loading.satelliteData"));
|
||||
setLoading(true);
|
||||
hideError();
|
||||
}
|
||||
@@ -5136,19 +5245,20 @@ export async function setSatellitesEnabled(
|
||||
try {
|
||||
const satelliteCount = await ensureSatellitesEnabled();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("卫星已显示", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "卫星", visible: true }), "info");
|
||||
}
|
||||
return satelliteCount;
|
||||
} catch (error) {
|
||||
satellitesEnabled = false;
|
||||
resetSatelliteState();
|
||||
updateSatelliteToggleUi(false, 0);
|
||||
const message = `卫星加载失败: ${error?.message || String(error)}`;
|
||||
const reason = error?.message || String(error);
|
||||
const message = earthMessage("status.layerLoadFailed", { layer: "卫星", error: reason });
|
||||
void reportEarthClientLog({
|
||||
level: "error",
|
||||
category: "layer-toggle",
|
||||
module: "satellites",
|
||||
message,
|
||||
message: `卫星加载失败: ${reason}`,
|
||||
detail: error,
|
||||
});
|
||||
if (!suppressLoadingUi) {
|
||||
@@ -5178,13 +5288,13 @@ export async function setVesselsEnabled(
|
||||
clearSelectionAndInfo();
|
||||
disableVessels();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("船只已隐藏", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "船只", visible: false }), "info");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!suppressLoadingUi) {
|
||||
setLoadingMessage("正在加载船只数据...");
|
||||
setLoadingMessage(earthMessage("loading.vesselData"));
|
||||
setLoading(true);
|
||||
hideError();
|
||||
}
|
||||
@@ -5192,19 +5302,20 @@ export async function setVesselsEnabled(
|
||||
try {
|
||||
const vesselCount = await ensureVesselsEnabled();
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage("船只已显示", "info");
|
||||
showStatusMessage(earthMessage("status.layerVisibility", { layer: "船只", visible: true }), "info");
|
||||
}
|
||||
return vesselCount;
|
||||
} catch (error) {
|
||||
vesselsEnabled = false;
|
||||
clearVesselData(getEarth());
|
||||
updateVesselToggleUi(false, 0);
|
||||
const message = `船只加载失败: ${error?.message || String(error)}`;
|
||||
const reason = error?.message || String(error);
|
||||
const message = earthMessage("status.layerLoadFailed", { layer: "船只", error: reason });
|
||||
void reportEarthClientLog({
|
||||
level: "error",
|
||||
category: "layer-toggle",
|
||||
module: "vessels",
|
||||
message,
|
||||
message: `船只加载失败: ${reason}`,
|
||||
detail: error,
|
||||
});
|
||||
if (!suppressLoadingUi) {
|
||||
@@ -5258,13 +5369,13 @@ function setupEventListeners() {
|
||||
// for the user-visible confirmation.
|
||||
return refreshComputeCentersAfterLocationSave()
|
||||
.then(() => {
|
||||
showStatusMessage("算力中心坐标已保存", "success");
|
||||
showStatusMessage(earthMessage("status.computeCoordinatesSaved"), "success");
|
||||
})
|
||||
.catch((error) => {
|
||||
// Swallow refresh failure: the save itself succeeded, so we
|
||||
// must not surface this as a save failure.
|
||||
console.warn("后台校准算力中心图层失败:", error);
|
||||
showStatusMessage("坐标已保存,地图稍后同步", "info");
|
||||
showStatusMessage(earthMessage("status.coordinatesSavedLater"), "info");
|
||||
});
|
||||
}
|
||||
// Optimistic marker is on screen; reconcile in the background.
|
||||
@@ -5275,10 +5386,10 @@ function setupEventListeners() {
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("即时生成算力中心交互物件失败,改用后台刷新:", error);
|
||||
showStatusMessage("坐标已保存,正在同步地图...", "info");
|
||||
showStatusMessage(earthMessage("status.coordinatesSavedSyncing"), "info");
|
||||
refreshComputeCentersAfterLocationSave()
|
||||
.then(() => {
|
||||
showStatusMessage("算力中心坐标已保存", "success");
|
||||
showStatusMessage(earthMessage("status.computeCoordinatesSaved"), "success");
|
||||
})
|
||||
.catch((refreshError) => {
|
||||
console.warn("后台校准算力中心图层失败:", refreshError);
|
||||
@@ -5945,7 +6056,11 @@ function onClick(event) {
|
||||
const incidentSummary = getBGPInfrastructureSummary(clickedMarker);
|
||||
showBGPInfo(clickedMarker, { x: event.clientX, y: event.clientY });
|
||||
showStatusMessage(
|
||||
`已选择BGP事件: ${clickedMarker.userData.collector} · ${incidentSummary.regionCount}个区域 / ${incidentSummary.cableCount}条相关海缆`,
|
||||
earthMessage("status.bgpSelected", {
|
||||
collector: clickedMarker.userData.collector,
|
||||
regionCount: incidentSummary.regionCount,
|
||||
cableCount: incidentSummary.cableCount,
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
return;
|
||||
@@ -5969,7 +6084,7 @@ function onClick(event) {
|
||||
clickedMarker.userData.related_satellite_count = 0;
|
||||
showBGPCollectorInfo(clickedMarker, { x: event.clientX, y: event.clientY });
|
||||
showStatusMessage(
|
||||
`已选择观测站: ${clickedMarker.userData.collector}`,
|
||||
earthMessage("status.selected", { target: "观测站", name: clickedMarker.userData.collector }),
|
||||
"info",
|
||||
);
|
||||
return;
|
||||
@@ -5986,7 +6101,10 @@ function onClick(event) {
|
||||
setAutoRotate(false);
|
||||
showComputeCenterInfo(clickedMarker, { x: event.clientX, y: event.clientY });
|
||||
showStatusMessage(
|
||||
`已选择算力中心: ${clickedMarker.userData?.name || "未知节点"}`,
|
||||
earthMessage("status.selected", {
|
||||
target: "算力中心",
|
||||
name: clickedMarker.userData?.name || "未知节点",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
return;
|
||||
@@ -6006,7 +6124,10 @@ function onClick(event) {
|
||||
console.warn("船只轨迹加载失败:", error);
|
||||
});
|
||||
showStatusMessage(
|
||||
`已选择船只: ${clickedMarker.userData?.name || clickedMarker.userData?.mmsi}`,
|
||||
earthMessage("status.selected", {
|
||||
target: "船只",
|
||||
name: clickedMarker.userData?.name || clickedMarker.userData?.mmsi,
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
return;
|
||||
@@ -6021,7 +6142,10 @@ function onClick(event) {
|
||||
distancePxSq: 0,
|
||||
}, { showMotionStatus: false })) {
|
||||
showStatusMessage(
|
||||
`已选择交互点: ${clickedMarker.userData?.label || clickedMarker.userData?.name || clickedMarker.userData?.id || "未知目标"}`,
|
||||
earthMessage("status.selected", {
|
||||
target: "交互点",
|
||||
name: clickedMarker.userData?.label || clickedMarker.userData?.name || clickedMarker.userData?.id || "未知目标",
|
||||
}),
|
||||
"info",
|
||||
);
|
||||
}
|
||||
@@ -6079,7 +6203,7 @@ function onClick(event) {
|
||||
screen: { x: event.clientX, y: event.clientY },
|
||||
distancePxSq: 0,
|
||||
}, { showMotionStatus: false });
|
||||
showStatusMessage("已选择: " + sat.properties.name, "info");
|
||||
showStatusMessage(earthMessage("status.selected", { name: sat.properties.name }), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as THREE from "three";
|
||||
import { CONFIG, CONNECTOR_CONFIG, CRUISE_CONFIG } from "./constants.js";
|
||||
import { showInfoCard, hideInfoCard } from "./info-card.js";
|
||||
import { latLonToVector3 } from "./utils.js";
|
||||
import { formatLocaleDateTime, getEarthLocale, hasCjkText } from "./i18n.js";
|
||||
import {
|
||||
createConnectorPath,
|
||||
resolveConnectorAnchor,
|
||||
@@ -20,8 +21,9 @@ import {
|
||||
getNewsFetchChannelLabel,
|
||||
getNewsFeedLabel,
|
||||
getNewsLocationSourceLabel,
|
||||
getNewsRegionLabel,
|
||||
getNewsRegionDisplayLabel,
|
||||
getNewsSourceTypeLabel,
|
||||
getNewsSourceNameLabel,
|
||||
} from "./news-locale.js";
|
||||
|
||||
const CRUISE_PRESENTATION_HIDE_MS = 220;
|
||||
@@ -38,10 +40,10 @@ function getItemTimestamp(item) {
|
||||
}
|
||||
|
||||
function formatPublishedAt(rawValue) {
|
||||
if (!rawValue) return "刚刚同步";
|
||||
if (!rawValue) return getEarthLocale() === "en-US" ? "Just synced" : "刚刚同步";
|
||||
const parsed = new Date(rawValue);
|
||||
if (Number.isNaN(parsed.getTime())) return "刚刚同步";
|
||||
return parsed.toLocaleString("zh-CN", {
|
||||
if (Number.isNaN(parsed.getTime())) return getEarthLocale() === "en-US" ? "Just synced" : "刚刚同步";
|
||||
return formatLocaleDateTime(parsed, {
|
||||
hour12: false,
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
@@ -94,6 +96,10 @@ function mapNewsItemToCruiseEvent(item) {
|
||||
|
||||
const rawFeedName = item.feed_name || "";
|
||||
const sourceType = item.source_type || (String(rawFeedName).startsWith("Global Monitor /") ? "aggregated" : "rss");
|
||||
const regionLabel = getNewsRegionDisplayLabel(item.region, item.display_region);
|
||||
const locationLabel = getEarthLocale() === "en-US" && hasCjkText(item.location_label)
|
||||
? regionLabel
|
||||
: item.location_label || regionLabel;
|
||||
|
||||
return {
|
||||
id: `news:${item.id}`,
|
||||
@@ -101,21 +107,21 @@ function mapNewsItemToCruiseEvent(item) {
|
||||
type: "news",
|
||||
title: getNewsDisplayTitle(item),
|
||||
summary: getNewsDisplaySummary(item),
|
||||
source: item.source || "",
|
||||
source: getNewsSourceNameLabel({ id: item.source_id, name: item.source || "" }),
|
||||
feedName: getNewsFeedLabel(rawFeedName),
|
||||
rawFeedName,
|
||||
feedSourceTypeLabel: getNewsSourceTypeLabel(sourceType),
|
||||
fetchChannelLabel: getNewsFetchChannelLabel(rawFeedName, sourceType),
|
||||
categoryLabel: getNewsCategoryLabel(item.category),
|
||||
region: item.region || "global",
|
||||
regionLabel: item.display_region || getNewsRegionLabel(item.region),
|
||||
regionLabel,
|
||||
url: item.url || "",
|
||||
publishedAt: item.published_at || null,
|
||||
publishedAtDisplay: formatPublishedAt(item.published_at),
|
||||
latitude,
|
||||
longitude,
|
||||
locationLabel: item.location_label || item.display_region || getNewsRegionLabel(item.region),
|
||||
sourceLocationLabel: item.location_label || item.display_region || getNewsRegionLabel(item.region),
|
||||
locationLabel,
|
||||
sourceLocationLabel: locationLabel,
|
||||
targetLocationConfidence: item.location_meta?.target?.confidence ?? null,
|
||||
targetLocationSource: item.location_source || "",
|
||||
targetLocationSourceLabel: getNewsLocationSourceLabel(item.location_source),
|
||||
|
||||
@@ -1,182 +1,414 @@
|
||||
const DEFAULT_LOCALE = "zh-CN";
|
||||
import { getEarthLocale, hasCjkText, normalizeLocale } from "./i18n.js";
|
||||
|
||||
const REGION_LABELS = {
|
||||
americas: "美洲",
|
||||
europe: "欧洲",
|
||||
"middle-east-africa": "中东与非洲",
|
||||
"asia-pacific": "亚太",
|
||||
global: "全球",
|
||||
"zh-CN": {
|
||||
americas: "美洲",
|
||||
europe: "欧洲",
|
||||
"middle-east-africa": "中东与非洲",
|
||||
"asia-pacific": "亚太",
|
||||
global: "全球",
|
||||
},
|
||||
"en-US": {
|
||||
americas: "Americas",
|
||||
europe: "Europe",
|
||||
"middle-east-africa": "Middle East & Africa",
|
||||
"asia-pacific": "Asia Pacific",
|
||||
global: "Global",
|
||||
},
|
||||
};
|
||||
|
||||
const FEED_LABELS = {
|
||||
"Global Monitor / World": "区域监测",
|
||||
"Global Monitor / Americas": "区域监测",
|
||||
"Global Monitor / Europe": "区域监测",
|
||||
"Global Monitor / MEA": "区域监测",
|
||||
"Global Monitor / APAC": "区域监测",
|
||||
"zh-CN": {
|
||||
"Global Monitor / World": "区域监测",
|
||||
"Global Monitor / Americas": "区域监测",
|
||||
"Global Monitor / Europe": "区域监测",
|
||||
"Global Monitor / MEA": "区域监测",
|
||||
"Global Monitor / APAC": "区域监测",
|
||||
},
|
||||
"en-US": {
|
||||
"Global Monitor / World": "Regional Monitor",
|
||||
"Global Monitor / Americas": "Regional Monitor",
|
||||
"Global Monitor / Europe": "Regional Monitor",
|
||||
"Global Monitor / MEA": "Regional Monitor",
|
||||
"Global Monitor / APAC": "Regional Monitor",
|
||||
},
|
||||
};
|
||||
|
||||
const CATEGORY_LABELS = {
|
||||
politics: "政治",
|
||||
business: "商业",
|
||||
ecommerce: "电商",
|
||||
finance: "金融",
|
||||
sports: "体育",
|
||||
technology: "科技",
|
||||
military: "军事",
|
||||
disaster: "灾害",
|
||||
energy: "能源",
|
||||
society: "社会",
|
||||
culture: "文化",
|
||||
other: "其他",
|
||||
"zh-CN": {
|
||||
politics: "政治",
|
||||
business: "商业",
|
||||
ecommerce: "电商",
|
||||
finance: "金融",
|
||||
sports: "体育",
|
||||
technology: "科技",
|
||||
military: "军事",
|
||||
disaster: "灾害",
|
||||
energy: "能源",
|
||||
society: "社会",
|
||||
culture: "文化",
|
||||
other: "其他",
|
||||
},
|
||||
"en-US": {
|
||||
politics: "Politics",
|
||||
business: "Business",
|
||||
ecommerce: "E-commerce",
|
||||
finance: "Finance",
|
||||
sports: "Sports",
|
||||
technology: "Technology",
|
||||
military: "Military",
|
||||
disaster: "Disaster",
|
||||
energy: "Energy",
|
||||
society: "Society",
|
||||
culture: "Culture",
|
||||
other: "Other",
|
||||
},
|
||||
};
|
||||
|
||||
const BREAKING_LEVEL_LABELS = {
|
||||
watch: "关注",
|
||||
breaking: "突发",
|
||||
critical: "严重突发",
|
||||
"zh-CN": {
|
||||
watch: "关注",
|
||||
breaking: "突发",
|
||||
critical: "严重突发",
|
||||
},
|
||||
"en-US": {
|
||||
watch: "Watch",
|
||||
breaking: "Breaking",
|
||||
critical: "Critical",
|
||||
},
|
||||
};
|
||||
|
||||
const BREAKING_SCOPE_LABELS = {
|
||||
regional: "区域",
|
||||
global: "全球",
|
||||
"zh-CN": {
|
||||
regional: "区域",
|
||||
global: "全球",
|
||||
},
|
||||
"en-US": {
|
||||
regional: "Regional",
|
||||
global: "Global",
|
||||
},
|
||||
};
|
||||
|
||||
const SOURCE_TYPE_LABELS = {
|
||||
rss: "RSS",
|
||||
atom: "Atom",
|
||||
aggregated: "Aggregated",
|
||||
manual: "手动添加",
|
||||
reference: "Reference",
|
||||
"zh-CN": {
|
||||
rss: "RSS",
|
||||
atom: "Atom",
|
||||
aggregated: "Aggregated",
|
||||
manual: "手动添加",
|
||||
reference: "Reference",
|
||||
},
|
||||
"en-US": {
|
||||
rss: "RSS",
|
||||
atom: "Atom",
|
||||
aggregated: "Aggregated",
|
||||
manual: "Manual",
|
||||
reference: "Reference",
|
||||
},
|
||||
};
|
||||
|
||||
const LOCATION_SOURCE_LABELS = {
|
||||
region_anchor: "区域锚点",
|
||||
ai_inferred_target: "AI 推断位置",
|
||||
headline_location_hint: "标题位置线索",
|
||||
headline_country_hint: "标题国家线索",
|
||||
"zh-CN": {
|
||||
region_anchor: "区域锚点",
|
||||
ai_inferred_target: "AI 推断位置",
|
||||
headline_location_hint: "标题位置线索",
|
||||
headline_country_hint: "标题国家线索",
|
||||
},
|
||||
"en-US": {
|
||||
region_anchor: "Region Anchor",
|
||||
ai_inferred_target: "AI-inferred Location",
|
||||
headline_location_hint: "Headline Location Hint",
|
||||
headline_country_hint: "Headline Country Hint",
|
||||
},
|
||||
};
|
||||
|
||||
const ENRICHMENT_STATUS_LABELS = {
|
||||
pending: "待增强",
|
||||
queued: "增强排队中",
|
||||
attempted: "增强中",
|
||||
success: "已汉化",
|
||||
content_only: "已汉化",
|
||||
location_only: "位置已增强",
|
||||
unavailable: "AI 未配置",
|
||||
provider_error: "增强失败",
|
||||
parse_error: "增强解析失败",
|
||||
no_result: "暂无增强结果",
|
||||
"zh-CN": {
|
||||
pending: "待增强",
|
||||
queued: "增强排队中",
|
||||
attempted: "增强中",
|
||||
success: "已汉化",
|
||||
content_only: "已汉化",
|
||||
location_only: "位置已增强",
|
||||
unavailable: "AI 未配置",
|
||||
provider_error: "增强失败",
|
||||
parse_error: "增强解析失败",
|
||||
no_result: "暂无增强结果",
|
||||
},
|
||||
"en-US": {
|
||||
pending: "Pending",
|
||||
queued: "Queued",
|
||||
attempted: "Enhancing",
|
||||
success: "Localized",
|
||||
content_only: "Localized",
|
||||
location_only: "Location Enhanced",
|
||||
unavailable: "AI Unconfigured",
|
||||
provider_error: "Enhancement Failed",
|
||||
parse_error: "Parse Failed",
|
||||
no_result: "No Enhancement",
|
||||
},
|
||||
};
|
||||
|
||||
const SOURCE_NAME_LABELS = {
|
||||
"en-US": {
|
||||
"36氪": "36Kr",
|
||||
"亿邦动力": "Ebrun",
|
||||
"商务数据中心": "MOFCOM Data Center",
|
||||
"商务部电商动态": "MOFCOM E-Commerce",
|
||||
"国家统计局数据发布": "National Bureau of Statistics",
|
||||
"电商物流指数": "China E-Commerce Logistics Index",
|
||||
},
|
||||
};
|
||||
|
||||
const SOURCE_ID_LABELS = {
|
||||
"en-US": {
|
||||
"36kr": "36Kr",
|
||||
ebrun: "Ebrun",
|
||||
"mofcom-data": "MOFCOM Data Center",
|
||||
"mofcom-ecommerce": "MOFCOM E-Commerce",
|
||||
"stats-china-online-retail": "National Bureau of Statistics",
|
||||
"china-ecommerce-logistics-index": "China E-Commerce Logistics Index",
|
||||
},
|
||||
};
|
||||
|
||||
const FEED_NAME_LABELS = {
|
||||
"en-US": {
|
||||
"综合资讯": "General",
|
||||
"文章资讯": "Articles",
|
||||
"最新快讯": "Newsflash",
|
||||
"动态内容": "Updates",
|
||||
"零售": "Retail",
|
||||
"服务": "Services",
|
||||
"数据": "Data",
|
||||
"政策": "Policy",
|
||||
"数据发布": "Data Releases",
|
||||
},
|
||||
};
|
||||
|
||||
const TITLE_PLACEHOLDERS = {
|
||||
queued: "新闻汉化排队中",
|
||||
attempted: "新闻汉化中",
|
||||
provider_error: "新闻汉化失败,正在重试",
|
||||
parse_error: "新闻解析失败,正在重试",
|
||||
unavailable: "等待 AI 配置",
|
||||
no_result: "新闻汉化待重试",
|
||||
location_only: "新闻汉化待重试",
|
||||
"zh-CN": {
|
||||
queued: "新闻汉化排队中",
|
||||
attempted: "新闻汉化中",
|
||||
provider_error: "新闻汉化失败,正在重试",
|
||||
parse_error: "新闻解析失败,正在重试",
|
||||
unavailable: "等待 AI 配置",
|
||||
no_result: "新闻汉化待重试",
|
||||
location_only: "新闻汉化待重试",
|
||||
},
|
||||
"en-US": {
|
||||
queued: "English translation queued",
|
||||
attempted: "English translation in progress",
|
||||
provider_error: "English translation retrying",
|
||||
parse_error: "English translation retrying",
|
||||
unavailable: "Waiting for AI configuration",
|
||||
no_result: "English translation pending",
|
||||
location_only: "English translation pending",
|
||||
},
|
||||
};
|
||||
|
||||
const SUMMARY_PLACEHOLDERS = {
|
||||
queued: "中文概要正在生成,请稍后刷新。",
|
||||
attempted: "中文概要正在生成,请稍后刷新。",
|
||||
provider_error: "中文概要生成失败,系统会重新提交增强任务。",
|
||||
parse_error: "中文概要解析失败,系统会重新提交增强任务。",
|
||||
unavailable: "AI 服务配置完成后将生成中文概要。",
|
||||
no_result: "中文概要暂未生成,系统会继续重试。",
|
||||
location_only: "已完成位置增强,中文概要将继续重试。",
|
||||
"zh-CN": {
|
||||
queued: "中文概要正在生成,请稍后刷新。",
|
||||
attempted: "中文概要正在生成,请稍后刷新。",
|
||||
provider_error: "中文概要生成失败,系统会重新提交增强任务。",
|
||||
parse_error: "中文概要解析失败,系统会重新提交增强任务。",
|
||||
unavailable: "AI 服务配置完成后将生成中文概要。",
|
||||
no_result: "中文概要暂未生成,系统会继续重试。",
|
||||
location_only: "已完成位置增强,中文概要将继续重试。",
|
||||
},
|
||||
"en-US": {
|
||||
queued: "English summary is being generated. Refresh shortly.",
|
||||
attempted: "English summary is being generated. Refresh shortly.",
|
||||
provider_error: "English summary generation failed and will be retried.",
|
||||
parse_error: "English summary parsing failed and will be retried.",
|
||||
unavailable: "English summary will be generated after AI is configured.",
|
||||
no_result: "English summary is pending and will be retried.",
|
||||
location_only: "Location is ready; English summary is still pending.",
|
||||
},
|
||||
};
|
||||
|
||||
function normalizeText(value) {
|
||||
return String(value ?? "").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function getLocalization(item, locale = DEFAULT_LOCALE) {
|
||||
function getLocale(locale = getEarthLocale()) {
|
||||
return normalizeLocale(locale);
|
||||
}
|
||||
|
||||
function getLabels(table, locale = getEarthLocale()) {
|
||||
const normalizedLocale = getLocale(locale);
|
||||
return table[normalizedLocale] || table["zh-CN"] || {};
|
||||
}
|
||||
|
||||
function isEnglishLocale(locale = getEarthLocale()) {
|
||||
return getLocale(locale) === "en-US";
|
||||
}
|
||||
|
||||
function isEnglishContent(item) {
|
||||
const language = String(item?.content_language || "").toLowerCase();
|
||||
return language === "en" || language.startsWith("en-") || language.startsWith("en_");
|
||||
}
|
||||
|
||||
function getPlaceholder(table, status, locale = getEarthLocale(), fallbackKey = "no_result") {
|
||||
const labels = getLabels(table, locale);
|
||||
return labels[status] || labels[fallbackKey] || "";
|
||||
}
|
||||
|
||||
function safeEnglishText(value) {
|
||||
const text = normalizeText(value);
|
||||
return text && !hasCjkText(text) ? text : "";
|
||||
}
|
||||
|
||||
function sourceIdFallback(id) {
|
||||
const value = normalizeText(id);
|
||||
if (!value) return "";
|
||||
return value
|
||||
.replace(/[-_]+/g, " ")
|
||||
.replace(/\b\w/g, (letter) => letter.toUpperCase());
|
||||
}
|
||||
|
||||
function getLocalization(item, locale = getEarthLocale()) {
|
||||
const localizations = item?.localizations;
|
||||
const localized = localizations && typeof localizations === "object"
|
||||
? localizations[locale]
|
||||
? localizations[getLocale(locale)]
|
||||
: null;
|
||||
return localized && typeof localized === "object" ? localized : {};
|
||||
}
|
||||
|
||||
export function getNewsDisplayTitle(item, locale = DEFAULT_LOCALE) {
|
||||
export function getNewsDisplayTitle(item, locale = getEarthLocale()) {
|
||||
const normalizedLocale = getLocale(locale);
|
||||
const localized = getLocalization(item, locale).title;
|
||||
if (localized || item?.display_title) {
|
||||
if (normalizedLocale === "zh-CN" && (item?.display_title || localized)) {
|
||||
return normalizeText(item?.display_title || localized);
|
||||
}
|
||||
if (normalizedLocale === "en-US") {
|
||||
return safeEnglishText(localized)
|
||||
|| safeEnglishText(item?.display_title)
|
||||
|| (isEnglishContent(item) ? safeEnglishText(item?.title) : "")
|
||||
|| getPlaceholder(TITLE_PLACEHOLDERS, item?.enrichment_status, locale);
|
||||
}
|
||||
if (localized) {
|
||||
return normalizeText(localized);
|
||||
}
|
||||
if (item?.title) {
|
||||
return normalizeText(item.title);
|
||||
}
|
||||
return normalizeText(
|
||||
TITLE_PLACEHOLDERS[item?.enrichment_status]
|
||||
|| "新闻汉化中",
|
||||
);
|
||||
return normalizeText(getPlaceholder(TITLE_PLACEHOLDERS, item?.enrichment_status, locale, "attempted"));
|
||||
}
|
||||
|
||||
export function getNewsDisplaySummary(item, locale = DEFAULT_LOCALE) {
|
||||
export function getNewsDisplaySummary(item, locale = getEarthLocale()) {
|
||||
const normalizedLocale = getLocale(locale);
|
||||
const localized = getLocalization(item, locale).summary;
|
||||
if (localized || item?.display_summary) {
|
||||
if (normalizedLocale === "zh-CN" && (item?.display_summary || localized)) {
|
||||
return normalizeText(item?.display_summary || localized);
|
||||
}
|
||||
if (normalizedLocale === "en-US") {
|
||||
return safeEnglishText(localized)
|
||||
|| safeEnglishText(item?.display_summary)
|
||||
|| (isEnglishContent(item) ? safeEnglishText(item?.summary) : "")
|
||||
|| getPlaceholder(SUMMARY_PLACEHOLDERS, item?.enrichment_status, locale);
|
||||
}
|
||||
if (localized) {
|
||||
return normalizeText(localized);
|
||||
}
|
||||
if (item?.summary) {
|
||||
return normalizeText(item.summary);
|
||||
}
|
||||
return normalizeText(
|
||||
SUMMARY_PLACEHOLDERS[item?.enrichment_status]
|
||||
|| "中文概要生成中,请稍后刷新。",
|
||||
);
|
||||
return normalizeText(getPlaceholder(SUMMARY_PLACEHOLDERS, item?.enrichment_status, locale, "attempted"));
|
||||
}
|
||||
|
||||
export function isNewsContentReady(item, locale = DEFAULT_LOCALE) {
|
||||
export function isNewsContentReady(item, locale = getEarthLocale()) {
|
||||
const localized = getLocalization(item, locale);
|
||||
const title = normalizeText(item?.display_title || localized.title || item?.title);
|
||||
const summary = normalizeText(item?.display_summary || localized.summary || item?.summary);
|
||||
const normalizedLocale = getLocale(locale);
|
||||
if (normalizedLocale === "en-US") {
|
||||
const title = safeEnglishText(localized.title)
|
||||
|| safeEnglishText(item?.display_title)
|
||||
|| (isEnglishContent(item) ? safeEnglishText(item?.title) : "");
|
||||
const summary = safeEnglishText(localized.summary)
|
||||
|| safeEnglishText(item?.display_summary)
|
||||
|| (isEnglishContent(item) ? safeEnglishText(item?.summary) : "");
|
||||
return Boolean(title && summary);
|
||||
}
|
||||
const title = normalizeText(
|
||||
item?.display_title || localized.title || item?.title,
|
||||
);
|
||||
const summary = normalizeText(
|
||||
item?.display_summary || localized.summary || item?.summary,
|
||||
);
|
||||
return Boolean(title && summary);
|
||||
}
|
||||
|
||||
export function getNewsRegionLabel(region, fallback = "") {
|
||||
return REGION_LABELS[region] || fallback || region || REGION_LABELS.global;
|
||||
export function getNewsRegionLabel(region, fallback = "", locale = getEarthLocale()) {
|
||||
const labels = getLabels(REGION_LABELS, locale);
|
||||
return labels[region] || fallback || region || labels.global;
|
||||
}
|
||||
|
||||
export function getNewsFeedLabel(feedName) {
|
||||
return FEED_LABELS[feedName] || feedName || "聚合源";
|
||||
export function getNewsFeedLabel(feedName, locale = getEarthLocale()) {
|
||||
const normalizedLocale = getLocale(locale);
|
||||
const mappedFeed = getLabels(FEED_NAME_LABELS, locale)[feedName];
|
||||
if (mappedFeed) return mappedFeed;
|
||||
if (normalizedLocale === "en-US" && hasCjkText(feedName)) return "News Feed";
|
||||
return getLabels(FEED_LABELS, locale)[feedName]
|
||||
|| feedName
|
||||
|| (normalizedLocale === "en-US" ? "Aggregated Source" : "聚合源");
|
||||
}
|
||||
|
||||
export function getNewsCategoryLabel(category) {
|
||||
return CATEGORY_LABELS[category] || category || CATEGORY_LABELS.other;
|
||||
export function getNewsCategoryLabel(category, locale = getEarthLocale()) {
|
||||
const labels = getLabels(CATEGORY_LABELS, locale);
|
||||
return labels[category] || category || labels.other;
|
||||
}
|
||||
|
||||
export function getNewsBreakingLabel(level, scope = "regional") {
|
||||
export function getNewsBreakingLabel(level, scope = "regional", locale = getEarthLocale()) {
|
||||
const normalizedLevel = normalizeText(level).toLowerCase();
|
||||
if (!normalizedLevel || normalizedLevel === "none") return "";
|
||||
const levelLabel = BREAKING_LEVEL_LABELS[normalizedLevel] || level;
|
||||
const scopeLabel = BREAKING_SCOPE_LABELS[normalizeText(scope).toLowerCase()] || BREAKING_SCOPE_LABELS.regional;
|
||||
return `${scopeLabel}${levelLabel}`;
|
||||
const levelLabels = getLabels(BREAKING_LEVEL_LABELS, locale);
|
||||
const scopeLabels = getLabels(BREAKING_SCOPE_LABELS, locale);
|
||||
const levelLabel = levelLabels[normalizedLevel] || level;
|
||||
const scopeLabel = scopeLabels[normalizeText(scope).toLowerCase()] || scopeLabels.regional;
|
||||
return getLocale(locale) === "en-US" ? `${scopeLabel} ${levelLabel}` : `${scopeLabel}${levelLabel}`;
|
||||
}
|
||||
|
||||
export function getNewsSourceTypeLabel(sourceType) {
|
||||
export function getNewsSourceTypeLabel(sourceType, locale = getEarthLocale()) {
|
||||
const normalized = normalizeText(sourceType).toLowerCase();
|
||||
return SOURCE_TYPE_LABELS[normalized] || sourceType || "RSS";
|
||||
return getLabels(SOURCE_TYPE_LABELS, locale)[normalized] || sourceType || "RSS";
|
||||
}
|
||||
|
||||
export function getNewsSourceNameLabel(sourceOrName, locale = getEarthLocale()) {
|
||||
const normalizedLocale = getLocale(locale);
|
||||
const source = sourceOrName && typeof sourceOrName === "object" ? sourceOrName : null;
|
||||
const name = normalizeText(source ? source.name : sourceOrName);
|
||||
if (normalizedLocale !== "en-US") return name;
|
||||
const id = normalizeText(source?.id || source?.source_id);
|
||||
return getLabels(SOURCE_ID_LABELS, locale)[id]
|
||||
|| getLabels(SOURCE_NAME_LABELS, locale)[name]
|
||||
|| safeEnglishText(name)
|
||||
|| sourceIdFallback(id)
|
||||
|| "News Source";
|
||||
}
|
||||
|
||||
export function getNewsRegionDisplayLabel(region, fallback = "", locale = getEarthLocale()) {
|
||||
return getNewsRegionLabel(region, isEnglishLocale(locale) ? "" : fallback, locale);
|
||||
}
|
||||
|
||||
export function isRegionalMonitorFeed(feedName) {
|
||||
return Object.prototype.hasOwnProperty.call(FEED_LABELS, feedName);
|
||||
return Object.values(FEED_LABELS).some((labels) =>
|
||||
Object.prototype.hasOwnProperty.call(labels, feedName),
|
||||
);
|
||||
}
|
||||
|
||||
export function getNewsFetchChannelLabel(feedName, sourceType = "") {
|
||||
const normalized = normalizeText(sourceType).toLowerCase();
|
||||
if (isRegionalMonitorFeed(feedName) || normalized === "aggregated") return "区域监测";
|
||||
if (normalized === "manual") return "手动添加";
|
||||
if (normalized === "atom") return "单源 Atom";
|
||||
if (normalized === "reference") return "配置保留";
|
||||
return "单源 RSS";
|
||||
const english = getEarthLocale() === "en-US";
|
||||
if (isRegionalMonitorFeed(feedName) || normalized === "aggregated") return english ? "Regional Monitor" : "区域监测";
|
||||
if (normalized === "manual") return english ? "Manual" : "手动添加";
|
||||
if (normalized === "atom") return english ? "Single-source Atom" : "单源 Atom";
|
||||
if (normalized === "reference") return english ? "Reserved" : "配置保留";
|
||||
return english ? "Single-source RSS" : "单源 RSS";
|
||||
}
|
||||
|
||||
export function getNewsLocationSourceLabel(source) {
|
||||
return LOCATION_SOURCE_LABELS[source] || source || "位置来源";
|
||||
export function getNewsLocationSourceLabel(source, locale = getEarthLocale()) {
|
||||
return getLabels(LOCATION_SOURCE_LABELS, locale)[source]
|
||||
|| source
|
||||
|| (getLocale(locale) === "en-US" ? "Location Source" : "位置来源");
|
||||
}
|
||||
|
||||
export function getNewsEnrichmentStatusLabel(statusOrItem) {
|
||||
@@ -184,9 +416,11 @@ export function getNewsEnrichmentStatusLabel(statusOrItem) {
|
||||
const status = item ? item.enrichment_status : statusOrItem;
|
||||
const language = String(item?.content_language || "").toLowerCase();
|
||||
if (language.startsWith("zh") && status !== "success" && status !== "content_only") {
|
||||
if (status === "queued" || status === "attempted") return "英文补译中";
|
||||
if (status === "provider_error" || status === "parse_error" || status === "no_result") return "中文原文";
|
||||
return "中文原文";
|
||||
if (status === "queued" || status === "attempted") return getEarthLocale() === "en-US" ? "English Translation Pending" : "英文补译中";
|
||||
if (status === "provider_error" || status === "parse_error" || status === "no_result") return getEarthLocale() === "en-US" ? "Chinese Original" : "中文原文";
|
||||
return getEarthLocale() === "en-US" ? "Chinese Original" : "中文原文";
|
||||
}
|
||||
return ENRICHMENT_STATUS_LABELS[status] || status || "增强状态";
|
||||
return getLabels(ENRICHMENT_STATUS_LABELS)[status]
|
||||
|| status
|
||||
|| (getEarthLocale() === "en-US" ? "Enhancement Status" : "增强状态");
|
||||
}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { showStatusMessage } from "./ui.js";
|
||||
import {
|
||||
applyEarthI18n,
|
||||
earthMessage,
|
||||
getEarthLocale,
|
||||
onEarthLocaleChange,
|
||||
translateText,
|
||||
} from "./i18n.js";
|
||||
import {
|
||||
getNewsDisplaySummary,
|
||||
getNewsDisplayTitle,
|
||||
@@ -6,8 +13,11 @@ import {
|
||||
getNewsBreakingLabel,
|
||||
getNewsEnrichmentStatusLabel,
|
||||
getNewsFetchChannelLabel,
|
||||
getNewsFeedLabel,
|
||||
getNewsRegionLabel,
|
||||
getNewsRegionDisplayLabel,
|
||||
getNewsSourceTypeLabel,
|
||||
getNewsSourceNameLabel,
|
||||
isNewsContentReady,
|
||||
} from "./news-locale.js";
|
||||
import {
|
||||
@@ -129,17 +139,18 @@ function formatCoord(value, positiveLabel, negativeLabel) {
|
||||
}
|
||||
|
||||
function formatRelativeTime(raw) {
|
||||
if (!raw) return "刚刚同步";
|
||||
const english = getEarthLocale() === "en-US";
|
||||
if (!raw) return english ? "Just synced" : "刚刚同步";
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return "刚刚同步";
|
||||
if (Number.isNaN(date.getTime())) return english ? "Just synced" : "刚刚同步";
|
||||
|
||||
const diff = Date.now() - date.getTime();
|
||||
const minutes = Math.max(1, Math.round(diff / 60000));
|
||||
if (minutes < 60) return `${minutes} 分钟前`;
|
||||
if (minutes < 60) return english ? `${minutes}m ago` : `${minutes} 分钟前`;
|
||||
const hours = Math.round(minutes / 60);
|
||||
if (hours < 24) return `${hours} 小时前`;
|
||||
if (hours < 24) return english ? `${hours}h ago` : `${hours} 小时前`;
|
||||
const days = Math.round(hours / 24);
|
||||
return `${days} 天前`;
|
||||
return english ? `${days}d ago` : `${days} 天前`;
|
||||
}
|
||||
|
||||
export function updateNewsToggleUI(visible) {
|
||||
@@ -371,7 +382,7 @@ function escapeNewsHtml(value) {
|
||||
|
||||
function getDisplayableNewsItems(items) {
|
||||
return Array.isArray(items)
|
||||
? items.filter(isNewsContentReady)
|
||||
? items.filter((item) => isNewsContentReady(item))
|
||||
: [];
|
||||
}
|
||||
|
||||
@@ -430,25 +441,30 @@ function normalizeNewsSourceType(value) {
|
||||
|
||||
function getNewsSourceDescriptor(item, sourcesByName, sourcesById) {
|
||||
const feedName = String(item?.feed_name || "").trim();
|
||||
const sourceName = String(item?.source || feedName || "NEWS").trim();
|
||||
const rawSourceName = String(item?.source || feedName || "NEWS").trim();
|
||||
const sourceId = String(item?.source_id || "").trim();
|
||||
const sourceConfig = sourcesById.get(sourceId) || sourcesByName.get(feedName) || null;
|
||||
const sourceType = normalizeNewsSourceType(item?.source_type || sourceConfig?.source_type)
|
||||
|| (feedName.startsWith("Global Monitor /") ? "aggregated" : "rss");
|
||||
const sourceTypeLabel = getNewsSourceTypeLabel(sourceType);
|
||||
const channelLabel = getNewsFetchChannelLabel(feedName, sourceType);
|
||||
const sourceGroupName = String(sourceConfig?.name || "").trim();
|
||||
const sourceName = getNewsSourceNameLabel(
|
||||
sourceConfig || { id: sourceId, name: rawSourceName },
|
||||
);
|
||||
const feedLabel = getNewsFetchChannelLabel(feedName, sourceType);
|
||||
const sourceGroupName = sourceConfig ? getNewsSourceNameLabel(sourceConfig) : "";
|
||||
const originLabel = sourceGroupName
|
||||
? `${sourceGroupName} · ${channelLabel}`
|
||||
: feedName && feedName !== sourceName
|
||||
? `${feedName} · ${sourceTypeLabel}`
|
||||
? `${feedLabel} · ${sourceTypeLabel}`
|
||||
: `${channelLabel} · ${sourceTypeLabel}`;
|
||||
const english = getEarthLocale() === "en-US";
|
||||
const tooltip = [
|
||||
`媒体来源:${sourceName}`,
|
||||
sourceGroupName ? `来源组:${sourceGroupName}` : "",
|
||||
feedName ? `RSS 来源:${feedName}` : "",
|
||||
`源类型:${sourceTypeLabel}`,
|
||||
`抓取通道:${channelLabel}`,
|
||||
`${english ? "Media source" : "媒体来源"}: ${sourceName}`,
|
||||
sourceGroupName ? `${english ? "Source group" : "来源组"}: ${sourceGroupName}` : "",
|
||||
feedName ? `${english ? "RSS feed" : "RSS 来源"}: ${getNewsFeedNameForTooltip(feedName)}` : "",
|
||||
`${english ? "Source type" : "源类型"}: ${sourceTypeLabel}`,
|
||||
`${english ? "Fetch channel" : "抓取通道"}: ${channelLabel}`,
|
||||
].filter(Boolean).join("\n");
|
||||
return {
|
||||
sourceName,
|
||||
@@ -461,6 +477,43 @@ function getNewsSourceDescriptor(item, sourcesByName, sourcesById) {
|
||||
};
|
||||
}
|
||||
|
||||
function getNewsFeedNameForTooltip(feedName) {
|
||||
return getEarthLocale() === "en-US"
|
||||
? getNewsFeedLabel(feedName)
|
||||
: feedName;
|
||||
}
|
||||
|
||||
function getFocusRegionText(focus = {}) {
|
||||
return getNewsRegionDisplayLabel(focus.region, focus.display_region);
|
||||
}
|
||||
|
||||
function getFocusLabelText(focus = {}) {
|
||||
if (getEarthLocale() === "en-US") {
|
||||
return getNewsRegionDisplayLabel(focus.region, focus.label);
|
||||
}
|
||||
return focus.label || "全球焦点";
|
||||
}
|
||||
|
||||
function formatNewsSourceCount(enabledCount, totalCount) {
|
||||
if (getEarthLocale() === "en-US") return `${enabledCount || totalCount} / ${totalCount} sources`;
|
||||
return `${enabledCount || totalCount} / ${totalCount} 路来源`;
|
||||
}
|
||||
|
||||
function formatNewsStatus({ displayCount, totalCount, stale, hasErrors }) {
|
||||
if (getEarthLocale() === "en-US") {
|
||||
if (displayCount !== totalCount) return `Showing ${displayCount} / ${totalCount} stories`;
|
||||
if (stale) return `Showing the latest available news cache, ${totalCount} stories`;
|
||||
return hasErrors
|
||||
? `Aggregated ${totalCount} stories; some sources are unavailable`
|
||||
: `Aggregated ${totalCount} situation stories`;
|
||||
}
|
||||
if (displayCount !== totalCount) return `展示 ${displayCount} / ${totalCount} 条态势新闻`;
|
||||
if (stale) return `当前显示最近一次可用新闻缓存,共 ${totalCount} 条`;
|
||||
return hasErrors
|
||||
? `已聚合 ${totalCount} 条,部分源不可用`
|
||||
: `已聚合 ${totalCount} 条态势新闻`;
|
||||
}
|
||||
|
||||
function getEnabledNewsCategoryKeys(filters = activeNewsCategoryFilters) {
|
||||
if (!filters || typeof filters !== "object") return [...NEWS_CATEGORY_KEYS].sort();
|
||||
return Object.entries(filters)
|
||||
@@ -548,10 +601,10 @@ function setNewsSourceFilters(enabledIds, { persist = true } = {}) {
|
||||
}
|
||||
|
||||
function summarizeSelection(enabledCount, totalCount) {
|
||||
if (totalCount <= 0) return "暂无";
|
||||
if (enabledCount <= 0) return "未选";
|
||||
if (enabledCount === totalCount) return "全部";
|
||||
return `${enabledCount} 项`;
|
||||
if (totalCount <= 0) return translateText("暂无");
|
||||
if (enabledCount <= 0) return translateText("未选");
|
||||
if (enabledCount === totalCount) return translateText("全部");
|
||||
return translateText(`${enabledCount} 项`);
|
||||
}
|
||||
|
||||
function syncFilterSummaries(nextPayload = payload) {
|
||||
@@ -567,10 +620,12 @@ function syncFilterSummaries(nextPayload = payload) {
|
||||
});
|
||||
document.querySelectorAll('[data-news-filter-summary="limit"]').forEach((el) => {
|
||||
const total = Array.isArray(nextPayload?.items) ? nextPayload.items.length : 0;
|
||||
el.textContent = newsFullListMode ? "全部" : `${Math.min(NEWS_SUMMARY_LIMIT, total || NEWS_SUMMARY_LIMIT)} 条`;
|
||||
el.textContent = newsFullListMode
|
||||
? translateText("全部")
|
||||
: translateText(`${Math.min(NEWS_SUMMARY_LIMIT, total || NEWS_SUMMARY_LIMIT)} 条`);
|
||||
});
|
||||
document.querySelectorAll("[data-news-view-mode-label]").forEach((el) => {
|
||||
el.textContent = newsFullListMode ? "返回摘要" : "查看全部";
|
||||
el.textContent = translateText(newsFullListMode ? "返回摘要" : "查看全部");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -601,7 +656,9 @@ function renderCategoryFilterChips() {
|
||||
function renderSourceFilterChips() {
|
||||
const sources = Array.isArray(payload?.sources) ? payload.sources : [];
|
||||
const enabled = new Set(getEnabledNewsSourceIds());
|
||||
if (!sources.length) return `<span class="news-filter-popover__hint">暂无可筛选来源。</span>`;
|
||||
if (!sources.length) {
|
||||
return `<span class="news-filter-popover__hint">${escapeNewsHtml(translateText("暂无可筛选来源。"))}</span>`;
|
||||
}
|
||||
return sources
|
||||
.map((source) => {
|
||||
const id = String(source?.id || "").trim();
|
||||
@@ -613,15 +670,15 @@ function renderSourceFilterChips() {
|
||||
type="button"
|
||||
data-news-source-toggle="${escapeNewsHtml(id)}"
|
||||
aria-pressed="${active ? "true" : "false"}"
|
||||
>${escapeNewsHtml(source?.name || id)}</button>
|
||||
>${escapeNewsHtml(getNewsSourceNameLabel(source || { id }))}</button>
|
||||
`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
function renderFilterPopover(kind) {
|
||||
const title = kind === "source" ? "新闻来源" : "新闻类型";
|
||||
const hint = kind === "source" ? "按大来源筛选,不影响后台抓取。" : "按新闻内容分类筛选。";
|
||||
const title = translateText(kind === "source" ? "新闻来源" : "新闻类型");
|
||||
const hint = translateText(kind === "source" ? "按大来源筛选,不影响后台抓取。" : "按新闻内容分类筛选。");
|
||||
const content = kind === "source" ? renderSourceFilterChips() : renderCategoryFilterChips();
|
||||
|
||||
activeFilterPopover = kind;
|
||||
@@ -675,19 +732,19 @@ function renderTicker(nextPayload) {
|
||||
const focus = nextPayload?.focus || {};
|
||||
|
||||
if (tickerRegion instanceof HTMLElement) {
|
||||
tickerRegion.textContent = focus.display_region || getNewsRegionLabel(focus.region);
|
||||
tickerRegion.textContent = getFocusRegionText(focus);
|
||||
tickerRegion.style.color = focus.accent || "";
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
tickerTrack.textContent = "正在准备全球态势新闻...";
|
||||
tickerTrack.textContent = translateText("正在准备全球态势新闻...");
|
||||
tickerTrack.style.removeProperty("--news-ticker-duration");
|
||||
return;
|
||||
}
|
||||
|
||||
const visibleItems = getDisplayableNewsItems(items).slice(0, 6);
|
||||
if (visibleItems.length === 0) {
|
||||
tickerTrack.textContent = "当前新闻类型没有可显示新闻...";
|
||||
tickerTrack.textContent = translateText("当前新闻类型没有可显示新闻...");
|
||||
tickerTrack.style.removeProperty("--news-ticker-duration");
|
||||
return;
|
||||
}
|
||||
@@ -695,7 +752,10 @@ function renderTicker(nextPayload) {
|
||||
tickerTrack.innerHTML = tickerItems
|
||||
.map((item) => `
|
||||
<span class="earth-news-ticker__item" data-news-id="${escapeTickerText(item.id || "")}">
|
||||
<span class="earth-news-ticker__source">${escapeTickerText(item.source || item.feed_name || "NEWS")}</span>
|
||||
<span class="earth-news-ticker__source">${escapeTickerText(getNewsSourceNameLabel({
|
||||
id: item.source_id,
|
||||
name: item.source || item.feed_name || "NEWS",
|
||||
}))}</span>
|
||||
<span>${escapeTickerText(getNewsDisplaySummary(item))}</span>
|
||||
</span>
|
||||
`)
|
||||
@@ -711,7 +771,7 @@ function renderEmptyState(message) {
|
||||
empty.textContent = message;
|
||||
}
|
||||
if (status) {
|
||||
status.textContent = "等待聚合新闻源";
|
||||
status.textContent = translateText("等待聚合新闻源");
|
||||
}
|
||||
if (openBtn) openBtn.disabled = true;
|
||||
renderTicker({ items: [], focus: payload?.focus || { region: "global" } });
|
||||
@@ -762,7 +822,7 @@ function renderPayload(nextPayload) {
|
||||
}
|
||||
|
||||
if (regionChip) {
|
||||
regionChip.textContent = focus.display_region || getNewsRegionLabel(focus.region);
|
||||
regionChip.textContent = getFocusRegionText(focus);
|
||||
regionChip.style.setProperty("--news-accent", focus.accent || "#d6e6ff");
|
||||
}
|
||||
|
||||
@@ -772,25 +832,22 @@ function renderPayload(nextPayload) {
|
||||
return;
|
||||
}
|
||||
|
||||
focusLabel.textContent = focus.label || "全球焦点";
|
||||
focusLabel.textContent = getFocusLabelText(focus);
|
||||
|
||||
if (typeof focus.lat === "number" && typeof focus.lon === "number") {
|
||||
focusCoords.textContent = `${formatCoord(focus.lat, "N", "S")} · ${formatCoord(focus.lon, "E", "W")}`;
|
||||
} else {
|
||||
focusCoords.textContent = "跟随当前视角自动聚焦";
|
||||
focusCoords.textContent = translateText("跟随当前视角自动聚焦");
|
||||
}
|
||||
|
||||
const enabledSourceCount = getEnabledNewsSourceIds(nextPayload).length;
|
||||
sourceCount.textContent = `${enabledSourceCount || sources.length} / ${sources.length} 路来源`;
|
||||
if (displayItems.length !== items.length) {
|
||||
status.textContent = `展示 ${displayItems.length} / ${items.length} 条态势新闻`;
|
||||
} else if (nextPayload?.stale) {
|
||||
status.textContent = `当前显示最近一次可用新闻缓存,共 ${items.length} 条`;
|
||||
} else {
|
||||
status.textContent = nextPayload?.errors?.length
|
||||
? `已聚合 ${items.length} 条,部分源不可用`
|
||||
: `已聚合 ${items.length} 条态势新闻`;
|
||||
}
|
||||
sourceCount.textContent = formatNewsSourceCount(enabledSourceCount, sources.length);
|
||||
status.textContent = formatNewsStatus({
|
||||
displayCount: displayItems.length,
|
||||
totalCount: items.length,
|
||||
stale: Boolean(nextPayload?.stale),
|
||||
hasErrors: Boolean(nextPayload?.errors?.length),
|
||||
});
|
||||
|
||||
if (feedAnchor) {
|
||||
const matchedSource = sources.find((source) => source.region === focus.region) || sources[0];
|
||||
@@ -806,8 +863,8 @@ function renderPayload(nextPayload) {
|
||||
if (empty) {
|
||||
empty.hidden = false;
|
||||
empty.textContent = items.length === 0
|
||||
? "当前未拉到可用新闻,请稍后刷新或切换视角区域。"
|
||||
: "当前新闻类型没有可显示新闻。";
|
||||
? translateText("当前未拉到可用新闻,请稍后刷新或切换视角区域。")
|
||||
: translateText("当前新闻类型没有可显示新闻。");
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -827,7 +884,7 @@ function renderPayload(nextPayload) {
|
||||
const title = getNewsDisplayTitle(item);
|
||||
const summaryText = getNewsDisplaySummary(item);
|
||||
const leadText = summaryText || title;
|
||||
const regionLabel = item.display_region || getNewsRegionLabel(item.region);
|
||||
const regionLabel = getNewsRegionDisplayLabel(item.region, item.display_region);
|
||||
const categoryLabel = getNewsCategoryLabel(item.category);
|
||||
const statusLabel = getNewsEnrichmentStatusLabel(item);
|
||||
const breakingLabel = getNewsBreakingLabel(breakingLevel, breakingScope);
|
||||
@@ -962,17 +1019,24 @@ async function fetchNews(lat, lon, context = {}) {
|
||||
const categorySignature = context.categorySignature ?? getNewsCategorySignature();
|
||||
const sourceSignature = context.sourceSignature ?? getNewsSourceSignatureForFetch(lat, lon);
|
||||
if (categorySignature === "__none__" || sourceSignature === "__none__") {
|
||||
const locale = getEarthLocale();
|
||||
return {
|
||||
...(payload || {}),
|
||||
generated_at: new Date().toISOString(),
|
||||
focus: payload?.focus || { lat, lon, region: "global", label: "全球焦点", display_region: "全球" },
|
||||
focus: payload?.focus || {
|
||||
lat,
|
||||
lon,
|
||||
region: "global",
|
||||
label: translateText("全球焦点"),
|
||||
display_region: getNewsRegionLabel("global"),
|
||||
},
|
||||
sources: payload?.sources || [],
|
||||
filters: {
|
||||
region: payload?.focus?.region || "global",
|
||||
categories: categorySignature === "__none__" ? [] : getEnabledNewsCategoryKeys(),
|
||||
sources: sourceSignature === "__none__" ? [] : getEnabledNewsSourceIds(),
|
||||
limit: getNewsLimit(),
|
||||
locale: "zh-CN",
|
||||
locale,
|
||||
},
|
||||
items: [],
|
||||
cruise_items: [],
|
||||
@@ -986,7 +1050,7 @@ async function fetchNews(lat, lon, context = {}) {
|
||||
if (categorySignature) url.searchParams.set("categories", categorySignature);
|
||||
if (sourceSignature) url.searchParams.set("sources", sourceSignature);
|
||||
url.searchParams.set("limit", String(getNewsLimit()));
|
||||
url.searchParams.set("locale", "zh-CN");
|
||||
url.searchParams.set("locale", getEarthLocale());
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
@@ -1011,6 +1075,7 @@ async function refreshNews(lat, lon, { silent = false } = {}) {
|
||||
categorySignature,
|
||||
sourceSignature,
|
||||
getNewsLimit(),
|
||||
getEarthLocale(),
|
||||
].join("|");
|
||||
|
||||
if (refreshPromise && refreshRequestKey === requestKey) return refreshPromise;
|
||||
@@ -1034,9 +1099,10 @@ async function refreshNews(lat, lon, { silent = false } = {}) {
|
||||
if (Array.isArray(nextPayload?.items) && nextPayload.items.length === 0) {
|
||||
const { status } = getElements();
|
||||
if (status) {
|
||||
status.textContent = "当前区域暂无可用新闻,已完成一次聚合尝试";
|
||||
status.textContent = translateText("当前区域暂无可用新闻,已完成一次聚合尝试");
|
||||
}
|
||||
}
|
||||
applyEarthI18n();
|
||||
return nextPayload;
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -1045,12 +1111,12 @@ async function refreshNews(lat, lon, { silent = false } = {}) {
|
||||
}
|
||||
console.error("加载 Earth RSS 新闻失败:", error);
|
||||
const message = error?.name === "AbortError"
|
||||
? "新闻聚合请求超时,请稍后重试"
|
||||
: `新闻聚合暂时不可用: ${error?.message || "未知错误"}`;
|
||||
? translateText("新闻聚合请求超时,请稍后重试")
|
||||
: `${translateText("新闻聚合暂时不可用")}: ${error?.message || (getEarthLocale() === "en-US" ? "Unknown error" : "未知错误")}`;
|
||||
if (!payload) {
|
||||
renderEmptyState(message);
|
||||
} else if (!silent) {
|
||||
showStatusMessage("态势新闻同步失败", "error");
|
||||
showStatusMessage(earthMessage("status.newsSyncFailed"), "error");
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
@@ -1185,7 +1251,7 @@ export function initNewsPanel() {
|
||||
initialized = true;
|
||||
|
||||
updateNewsToggleUI(true);
|
||||
renderEmptyState("正在准备全球态势新闻聚合源...");
|
||||
renderEmptyState(translateText("正在准备全球态势新闻聚合源..."));
|
||||
|
||||
const { ticker, hudCloseBtn } = getElements();
|
||||
ticker?.addEventListener("click", (event) => {
|
||||
@@ -1252,6 +1318,13 @@ export function initNewsPanel() {
|
||||
lastFetchAt = 0;
|
||||
refreshNews(lastFocus?.lat, lastFocus?.lon, { silent: true }).catch(() => {});
|
||||
});
|
||||
onEarthLocaleChange(() => {
|
||||
syncFilterSummaries();
|
||||
if (activeFilterPopover) renderFilterPopover(activeFilterPopover);
|
||||
lastFetchAt = 0;
|
||||
refreshRequestKey = "";
|
||||
refreshNews(lastFocus?.lat, lastFocus?.lon, { silent: true }).catch(() => {});
|
||||
});
|
||||
setupNewsHudResize();
|
||||
connectNewsRealtime();
|
||||
|
||||
@@ -1260,9 +1333,9 @@ export function initNewsPanel() {
|
||||
refreshBtn?.addEventListener("click", async () => {
|
||||
try {
|
||||
await refreshNews(lastFocus?.lat, lastFocus?.lon);
|
||||
showStatusMessage("态势新闻已刷新", "info");
|
||||
showStatusMessage(earthMessage("status.newsRefresh", { ok: true }), "info");
|
||||
} catch {
|
||||
showStatusMessage("态势新闻刷新失败", "error");
|
||||
showStatusMessage(earthMessage("status.newsRefresh", { ok: false }), "error");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import Hls from "hls.js";
|
||||
import { showStatusMessage } from "./ui.js";
|
||||
import { createHUDPanel } from "./hud-panels.js";
|
||||
import {
|
||||
earthMessage,
|
||||
formatLocaleDateTime,
|
||||
getEarthLocale,
|
||||
hasCjkText,
|
||||
onEarthLocaleChange,
|
||||
translateText,
|
||||
} from "./i18n.js";
|
||||
|
||||
// Naming convention:
|
||||
// - #media-panel is the outer HUD shell, responsible for drag/resize/show-hide
|
||||
@@ -63,6 +71,59 @@ const HLS_SOURCE_FAILURE_DETAILS = new Set([
|
||||
"fragLoadTimeOut",
|
||||
]);
|
||||
|
||||
const TV_SOURCE_TYPE_LABELS = {
|
||||
hls: "HLS",
|
||||
video: "Video",
|
||||
iframe: "Web",
|
||||
external: "External",
|
||||
youtube: "YouTube",
|
||||
};
|
||||
|
||||
function isEnglishLocale() {
|
||||
return getEarthLocale() === "en-US";
|
||||
}
|
||||
|
||||
function titleCaseIdentifier(value) {
|
||||
return String(value || "")
|
||||
.replace(/[-_]+/g, " ")
|
||||
.replace(/\b\w/g, (letter) => letter.toUpperCase())
|
||||
.trim();
|
||||
}
|
||||
|
||||
function safeTVText(value, fallback = "") {
|
||||
const text = String(value ?? "").trim();
|
||||
if (!text) return fallback;
|
||||
if (isEnglishLocale() && hasCjkText(text)) return fallback;
|
||||
return text;
|
||||
}
|
||||
|
||||
function getTVSourceName(source) {
|
||||
if (!source) return translateText("暂无可用频道");
|
||||
return safeTVText(
|
||||
source.name,
|
||||
titleCaseIdentifier(source.id) || "Live Channel",
|
||||
);
|
||||
}
|
||||
|
||||
function getTVSourceTypeLabel(sourceType) {
|
||||
const normalized = String(sourceType || "").trim().toLowerCase();
|
||||
return TV_SOURCE_TYPE_LABELS[normalized] || safeTVText(sourceType, translateText("频道"));
|
||||
}
|
||||
|
||||
function getTVSourceField(value, fallback = "") {
|
||||
return safeTVText(value, fallback);
|
||||
}
|
||||
|
||||
function getTVCollectorLabel(value) {
|
||||
const collector = getTVSourceField(value, "Collector");
|
||||
return `${translateText("采集")}: ${collector}`;
|
||||
}
|
||||
|
||||
function getTVNotes(source) {
|
||||
if (!source?.notes) return translateText("支持后台配置默认源与采集器补充源。");
|
||||
return safeTVText(source.notes, translateText("配置于控制台"));
|
||||
}
|
||||
|
||||
function isVideoActuallyPlaying(video) {
|
||||
return (
|
||||
video instanceof HTMLVideoElement
|
||||
@@ -157,9 +218,9 @@ function syncMetaToggleState(collapsed) {
|
||||
desktopToggle.setAttribute("aria-expanded", collapsed ? "false" : "true");
|
||||
desktopToggle.setAttribute(
|
||||
"aria-label",
|
||||
collapsed ? "展开新闻直播内容" : "折叠新闻直播内容",
|
||||
translateText(collapsed ? "展开新闻直播内容" : "折叠新闻直播内容"),
|
||||
);
|
||||
desktopToggle.title = collapsed ? "展开新闻直播内容" : "折叠新闻直播内容";
|
||||
desktopToggle.title = translateText(collapsed ? "展开新闻直播内容" : "折叠新闻直播内容");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,11 +389,11 @@ function updateToggleButton(visible) {
|
||||
icon.textContent = "live_tv";
|
||||
}
|
||||
const title = visible ? "关闭 Live 新闻" : "打开 Live 新闻";
|
||||
toggleBtn.title = title;
|
||||
toggleBtn.setAttribute("aria-label", title);
|
||||
toggleBtn.title = translateText(title);
|
||||
toggleBtn.setAttribute("aria-label", translateText(title));
|
||||
const tooltip = toggleBtn.querySelector(".earth-toolbar-tooltip");
|
||||
if (tooltip) {
|
||||
tooltip.textContent = title;
|
||||
tooltip.textContent = translateText(title);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -628,30 +689,30 @@ function syncMobileOverviewSummary(source) {
|
||||
const summary = document.getElementById("mobile-tv-overview-summary");
|
||||
const tags = document.getElementById("mobile-tv-overview-tags");
|
||||
if (headline instanceof HTMLElement) {
|
||||
headline.textContent = source?.name || "暂无可用频道";
|
||||
headline.textContent = getTVSourceName(source);
|
||||
}
|
||||
if (summary instanceof HTMLElement) {
|
||||
if (!source) {
|
||||
summary.textContent = "点击查看当前频道来源、目录和补充说明";
|
||||
summary.textContent = translateText("点击查看当前频道来源、目录和补充说明");
|
||||
} else {
|
||||
const parts = [
|
||||
source.provider,
|
||||
source.region,
|
||||
source.language,
|
||||
getTVSourceField(source.provider),
|
||||
getTVSourceField(source.region),
|
||||
getTVSourceField(source.language),
|
||||
].filter(Boolean);
|
||||
summary.textContent = parts.length
|
||||
? parts.join(" · ")
|
||||
: "点击查看完整频道信息";
|
||||
: translateText("点击查看完整频道信息");
|
||||
}
|
||||
}
|
||||
if (tags instanceof HTMLElement) {
|
||||
const tagValues = source
|
||||
? [
|
||||
{ label: source.source_type || "频道", kind: "status" },
|
||||
source.collector_source ? { label: `采集:${source.collector_source}`, kind: "" } : { label: "内置源", kind: "" },
|
||||
source.region ? { label: source.region, kind: "" } : null,
|
||||
{ label: getTVSourceTypeLabel(source.source_type), kind: "status" },
|
||||
source.collector_source ? { label: getTVCollectorLabel(source.collector_source), kind: "" } : { label: translateText("内置源"), kind: "" },
|
||||
source.region ? { label: getTVSourceField(source.region, "Global"), kind: "" } : null,
|
||||
].filter(Boolean).slice(0, 3)
|
||||
: [{ label: "待加载", kind: "status" }];
|
||||
: [{ label: translateText("待加载"), kind: "status" }];
|
||||
tags.replaceChildren(
|
||||
...tagValues.map(({ label, kind }) => {
|
||||
const chip = document.createElement("span");
|
||||
@@ -727,7 +788,7 @@ function getCurrentSource() {
|
||||
function setPanelMessage(message) {
|
||||
const { status } = getElements();
|
||||
if (status) {
|
||||
status.textContent = message || TV_STATUS_MESSAGE.idle;
|
||||
status.textContent = translateText(message || TV_STATUS_MESSAGE.idle);
|
||||
if (status.id === "tv-source-status") {
|
||||
const normalized = message || TV_STATUS_MESSAGE.idle;
|
||||
status.classList.toggle(
|
||||
@@ -762,7 +823,7 @@ function resetVideo(video) {
|
||||
function showEmptyState(empty, message) {
|
||||
if (!(empty instanceof HTMLElement)) return;
|
||||
empty.hidden = false;
|
||||
empty.textContent = message;
|
||||
empty.textContent = translateText(message);
|
||||
}
|
||||
|
||||
function hideEmptyState(empty) {
|
||||
@@ -797,11 +858,11 @@ function renderSourceOptions() {
|
||||
const fragment = document.createDocumentFragment();
|
||||
|
||||
sources.forEach((source) => {
|
||||
const defaultMark = source.id === tvPayload?.default_source_id ? " · 默认" : "";
|
||||
const defaultMark = source.id === tvPayload?.default_source_id ? ` · ${translateText("默认")}` : "";
|
||||
const failMark = failedSourceIds.has(source.id) ? " ⚠" : "";
|
||||
const option = document.createElement("option");
|
||||
option.value = source.id;
|
||||
option.textContent = `${source.name}${defaultMark}${failMark}`;
|
||||
option.textContent = `${getTVSourceName(source)}${defaultMark}${failMark}`;
|
||||
fragment.appendChild(option);
|
||||
});
|
||||
|
||||
@@ -820,27 +881,37 @@ function renderSource(source) {
|
||||
const isExternalOnly = Boolean(source) && !embeddedUrl && !videoUrl && Boolean(externalUrl);
|
||||
|
||||
if (title) {
|
||||
title.textContent = source?.name || "暂无可用频道";
|
||||
title.textContent = getTVSourceName(source);
|
||||
}
|
||||
if (origin instanceof HTMLElement) {
|
||||
origin.textContent = source?.collector_source ? "采集" : source ? "内置" : "待加载";
|
||||
origin.title = source?.collector_source ? `采集源:${source.collector_source}` : source ? "内置源" : "待加载";
|
||||
origin.textContent = source?.collector_source ? translateText("采集") : source ? translateText("内置") : translateText("待加载");
|
||||
origin.title = source?.collector_source ? `${translateText("采集源")}: ${getTVSourceField(source.collector_source, "Collector")}` : source ? translateText("内置源") : translateText("待加载");
|
||||
}
|
||||
if (meta) {
|
||||
meta.textContent = source
|
||||
? `${source.provider} · ${source.region} · ${source.language} · ${source.source_type}`
|
||||
: "当前未配置可播放新闻直播源";
|
||||
const metaParts = source
|
||||
? [
|
||||
getTVSourceField(source.provider),
|
||||
getTVSourceField(source.region),
|
||||
getTVSourceField(source.language),
|
||||
getTVSourceTypeLabel(source.source_type),
|
||||
].filter(Boolean)
|
||||
: [];
|
||||
meta.textContent = metaParts.length
|
||||
? metaParts.join(" · ")
|
||||
: translateText("当前未配置可播放新闻直播源");
|
||||
}
|
||||
if (catalog) {
|
||||
const sourceCount = tvPayload?.source_count || tvPayload?.sources?.length || 0;
|
||||
const latestUpdatedAt = tvPayload?.latest_updated_at || tvPayload?.generated_at || "";
|
||||
const latestLabel = latestUpdatedAt
|
||||
? `最近同步 ${new Date(latestUpdatedAt).toLocaleString("zh-CN", { hour12: false })}`
|
||||
: "尚未同步";
|
||||
catalog.textContent = `共 ${sourceCount} 个频道 · ${latestLabel}`;
|
||||
? `${translateText("最近同步")} ${formatLocaleDateTime(latestUpdatedAt)}`
|
||||
: translateText("尚未同步");
|
||||
catalog.textContent = isEnglishLocale()
|
||||
? `${sourceCount} channels · ${latestLabel}`
|
||||
: `共 ${sourceCount} 个频道 · ${latestLabel}`;
|
||||
}
|
||||
if (notes) {
|
||||
notes.textContent = source?.notes || "支持后台配置默认源与采集器补充源。";
|
||||
notes.textContent = getTVNotes(source);
|
||||
}
|
||||
syncMobileOverviewSummary(source);
|
||||
|
||||
@@ -954,8 +1025,8 @@ export function initTVPanel() {
|
||||
collapseBtn: metaToggle,
|
||||
bodyCollapsedClass: "is-collapsed",
|
||||
preferredDirection: "up",
|
||||
expandLabel: "展开新闻直播信息",
|
||||
collapseLabel: "折叠新闻直播信息",
|
||||
expandLabel: translateText("展开新闻直播信息"),
|
||||
collapseLabel: translateText("折叠新闻直播信息"),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -965,6 +1036,12 @@ export function initTVPanel() {
|
||||
|
||||
updateToggleButton(mediaPanel?.isVisible() ?? !panel?.classList.contains("hud-panel-hidden"));
|
||||
syncSettingsToggle(mediaPanel?.isVisible() ?? !panel?.classList.contains("hud-panel-hidden"));
|
||||
onEarthLocaleChange(() => {
|
||||
syncMetaToggleState(isMetaCollapsed());
|
||||
updateToggleButton(mediaPanel?.isVisible() ?? !panel?.classList.contains("hud-panel-hidden"));
|
||||
if (tvPayload) renderPanel();
|
||||
else renderSource(null);
|
||||
});
|
||||
|
||||
toggleBtn?.addEventListener("click", async (event) => {
|
||||
event.preventDefault();
|
||||
@@ -973,12 +1050,12 @@ export function initTVPanel() {
|
||||
if (!currentlyVisible) {
|
||||
setPanelVisible(true);
|
||||
await ensureTVPanelReady();
|
||||
showStatusMessage("Live 新闻窗口已打开", "info");
|
||||
showStatusMessage(earthMessage("status.newsPanel", { open: true }), "info");
|
||||
return;
|
||||
}
|
||||
|
||||
setPanelVisible(false);
|
||||
showStatusMessage("Live 新闻窗口已关闭", "info");
|
||||
showStatusMessage(earthMessage("status.newsPanel", { open: false }), "info");
|
||||
});
|
||||
|
||||
[select, document.getElementById("mobile-tv-source-select"), document.getElementById("tv-source-select")]
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
// ui.js - UI update functions
|
||||
|
||||
import {
|
||||
applyEarthI18n,
|
||||
earthMessage,
|
||||
formatEarthMessage,
|
||||
getEarthLocale,
|
||||
onEarthLocaleChange,
|
||||
translateText,
|
||||
} from "./i18n.js";
|
||||
|
||||
let statusTimeoutId = null;
|
||||
let statusHideTimeoutId = null;
|
||||
const STATUS_BASE_CLASS = "earth-status-message";
|
||||
@@ -27,14 +36,30 @@ function getEarthStatTargets(statKey) {
|
||||
);
|
||||
}
|
||||
|
||||
function formatEarthStatValue(value) {
|
||||
return translateText(value);
|
||||
}
|
||||
|
||||
function syncEarthStatElement(element) {
|
||||
if (!(element instanceof HTMLElement)) return;
|
||||
const sourceValue = element.dataset.earthStatSourceValue;
|
||||
if (sourceValue === undefined) return;
|
||||
element.textContent = formatEarthStatValue(sourceValue);
|
||||
}
|
||||
|
||||
export function setEarthStatValue(statKey, value) {
|
||||
getEarthStatTargets(statKey).forEach((element) => {
|
||||
if (element instanceof HTMLElement) {
|
||||
element.textContent = value;
|
||||
element.dataset.earthStatSourceValue = String(value ?? "");
|
||||
syncEarthStatElement(element);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onEarthLocaleChange(() => {
|
||||
document.querySelectorAll("[data-earth-stat-source-value]").forEach(syncEarthStatElement);
|
||||
});
|
||||
|
||||
function setElementDisplay(element, visible, displayValue = "block") {
|
||||
if (!element) return;
|
||||
element.style.display = visible ? displayValue : "none";
|
||||
@@ -82,7 +107,7 @@ function buildStatusContent(statusEl, message, type) {
|
||||
|
||||
const text = document.createElement("span");
|
||||
text.className = "earth-status-text";
|
||||
text.textContent = message;
|
||||
text.textContent = formatEarthMessage(message);
|
||||
|
||||
statusEl.appendChild(indicator);
|
||||
statusEl.appendChild(text);
|
||||
@@ -92,23 +117,20 @@ function getStatusSidePlacement(statusEl) {
|
||||
if (!(statusEl instanceof HTMLElement)) return false;
|
||||
if (document.querySelector(".layout-mode-mobile")) return false;
|
||||
|
||||
const ticker = document.getElementById("desktop-news-ticker");
|
||||
const brand = document.getElementById("brand-panel");
|
||||
if (!(ticker instanceof HTMLElement) || !(brand instanceof HTMLElement)) return false;
|
||||
if (ticker.classList.contains("is-hidden") || ticker.offsetParent === null) return false;
|
||||
if (!(brand instanceof HTMLElement)) return false;
|
||||
|
||||
const tickerRect = ticker.getBoundingClientRect();
|
||||
const brandRect = brand.getBoundingClientRect();
|
||||
const statusWidth = Math.ceil(statusEl.getBoundingClientRect().width || statusEl.scrollWidth || 0);
|
||||
if (!statusWidth || !tickerRect.width || !brandRect.width) return false;
|
||||
if (!statusWidth || !brandRect.width) return false;
|
||||
|
||||
const rootStyle = getComputedStyle(document.documentElement);
|
||||
const hudScale = Number.parseFloat(rootStyle.getPropertyValue("--hud-scale")) || 1;
|
||||
const requiredGap = Math.max(10, Math.round(12 * hudScale));
|
||||
const availableWidth = tickerRect.left - brandRect.right - requiredGap * 2;
|
||||
const left = Math.round(brandRect.right + requiredGap);
|
||||
const availableWidth = window.innerWidth - left - requiredGap;
|
||||
return {
|
||||
shouldStack: availableWidth < statusWidth,
|
||||
left: Math.round(brandRect.right + requiredGap),
|
||||
left,
|
||||
maxWidth: Math.max(160, Math.floor(availableWidth)),
|
||||
};
|
||||
}
|
||||
@@ -122,9 +144,8 @@ function syncStatusPlacement(statusEl) {
|
||||
return;
|
||||
}
|
||||
const placement = getStatusSidePlacement(statusEl);
|
||||
const shouldStack = !placement || placement.shouldStack;
|
||||
statusEl.classList.toggle(STATUS_TICKER_STACK_CLASS, shouldStack);
|
||||
if (!placement || shouldStack) {
|
||||
statusEl.classList.remove(STATUS_TICKER_STACK_CLASS);
|
||||
if (!placement) {
|
||||
statusEl.style.left = "";
|
||||
statusEl.style.maxWidth = "";
|
||||
return;
|
||||
@@ -134,10 +155,12 @@ function syncStatusPlacement(statusEl) {
|
||||
}
|
||||
|
||||
function syncVisibleStatusPlacement() {
|
||||
const statusEl = getElement("status-message");
|
||||
if (statusEl?.classList.contains("visible")) {
|
||||
syncStatusPlacement(statusEl);
|
||||
}
|
||||
["status-message", "error-message"].forEach((id) => {
|
||||
const el = getElement(id);
|
||||
if (el?.classList.contains("visible")) {
|
||||
syncStatusPlacement(el);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildPersistentErrorContent(errorEl, message) {
|
||||
@@ -237,7 +260,9 @@ export function updateCoordinatesDisplay(lat, lon, alt = 0) {
|
||||
if (longitudeEl) longitudeEl.textContent = lon.toFixed(2) + "°";
|
||||
if (latitudeEl) latitudeEl.textContent = lat.toFixed(2) + "°";
|
||||
if (mouseCoordsEl) {
|
||||
mouseCoordsEl.textContent = `鼠标: ${lat.toFixed(2)}°, ${lon.toFixed(2)}°`;
|
||||
mouseCoordsEl.textContent = getEarthLocale() === "en-US"
|
||||
? `Mouse: ${lat.toFixed(2)}°, ${lon.toFixed(2)}°`
|
||||
: `鼠标: ${lat.toFixed(2)}°, ${lon.toFixed(2)}°`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,7 +278,11 @@ export function updateZoomDisplay(zoomLevel, distance) {
|
||||
const label = `${percent}%`;
|
||||
zoomValueEl.textContent = label;
|
||||
}
|
||||
if (zoomLevelEl) zoomLevelEl.textContent = "缩放: " + percent + "%";
|
||||
if (zoomLevelEl) {
|
||||
zoomLevelEl.textContent = getEarthLocale() === "en-US"
|
||||
? `Zoom: ${percent}%`
|
||||
: `缩放: ${percent}%`;
|
||||
}
|
||||
if (slider) slider.value = zoomLevel;
|
||||
if (cameraDistanceEl) cameraDistanceEl.textContent = distance + " km";
|
||||
}
|
||||
@@ -276,7 +305,14 @@ export function updateEarthStats(stats) {
|
||||
setEarthStatValue("bgp-collector-count", String(stats.bgpCollectorCount || 0));
|
||||
}
|
||||
if (has("bgpStatusSummary")) setEarthStatValue("bgp-status-summary", stats.bgpStatusSummary || "-");
|
||||
if (has("terrainOn")) setEarthStatValue("terrain-status", stats.terrainOn ? "开启" : "关闭");
|
||||
if (has("terrainOn")) {
|
||||
setEarthStatValue(
|
||||
"terrain-status",
|
||||
getEarthLocale() === "en-US"
|
||||
? (stats.terrainOn ? "On" : "Off")
|
||||
: (stats.terrainOn ? "开启" : "关闭"),
|
||||
);
|
||||
}
|
||||
if (has("textureQuality")) setEarthStatValue("texture-quality", stats.textureQuality || "8K 卫星图");
|
||||
}
|
||||
|
||||
@@ -292,7 +328,7 @@ export function setLoading(loading) {
|
||||
clearLoadingWidthLock(statusEl);
|
||||
buildStatusContent(
|
||||
statusEl,
|
||||
pendingLoadingMessage || "正在加载...",
|
||||
pendingLoadingMessage || earthMessage("loading.default"),
|
||||
"loading",
|
||||
);
|
||||
pendingLoadingMessage = "";
|
||||
@@ -331,7 +367,7 @@ export function setLoadingMessage(title) {
|
||||
}
|
||||
const textEl = statusEl.querySelector(".earth-status-text");
|
||||
if (textEl) {
|
||||
textEl.textContent = title;
|
||||
textEl.textContent = formatEarthMessage(title);
|
||||
requestAnimationFrame(() => {
|
||||
updateLoadingWidthLock(statusEl);
|
||||
syncStatusPlacement(statusEl);
|
||||
@@ -344,6 +380,7 @@ export function showTooltip(x, y, content) {
|
||||
const tooltip = getElement("tooltip");
|
||||
if (!tooltip) return;
|
||||
tooltip.innerHTML = content;
|
||||
applyEarthI18n(tooltip);
|
||||
tooltip.style.left = x + "px";
|
||||
tooltip.style.top = y + "px";
|
||||
setElementDisplay(tooltip, true);
|
||||
@@ -364,6 +401,7 @@ export function showError(message) {
|
||||
buildPersistentErrorContent(errorEl, message);
|
||||
errorEl.className = `${STATUS_BASE_CLASS} earth-error-message error`;
|
||||
setElementDisplay(errorEl, true, "inline-flex");
|
||||
syncStatusPlacement(errorEl);
|
||||
errorEl.offsetHeight;
|
||||
errorEl.classList.add("visible");
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Suspense, lazy } from 'react'
|
||||
import { Suspense, lazy, useEffect } from 'react'
|
||||
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Routes, Route, Navigate, useLocation } from 'react-router-dom'
|
||||
|
||||
import { useAuthStore } from './stores/auth'
|
||||
import Login from './pages/Login/Login'
|
||||
import { AdminErrorBoundary } from './admin/components/AdminErrorBoundary'
|
||||
import LegacyI18nBridge from './i18n/LegacyI18nBridge'
|
||||
|
||||
const Register = lazy(() => import('./pages/Register/Register'))
|
||||
const VerifyEmail = lazy(() => import('./pages/VerifyEmail/VerifyEmail'))
|
||||
@@ -26,35 +28,43 @@ function isPublicPath(pathname: string) {
|
||||
}
|
||||
|
||||
function App() {
|
||||
const { t } = useTranslation()
|
||||
const { token } = useAuthStore()
|
||||
const { pathname } = useLocation()
|
||||
const isPublicRoute = isPublicPath(pathname)
|
||||
|
||||
useEffect(() => {
|
||||
document.title = t('app.title')
|
||||
}, [t])
|
||||
|
||||
if (!token && !isPublicRoute) {
|
||||
return <Login />
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
fallback={(
|
||||
<div className="app-route-loading">
|
||||
<div className="app-route-loading__spinner" aria-label="正在加载" />
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/verify-email" element={<VerifyEmail />} />
|
||||
<Route path="/forgot-password" element={<ForgotPassword />} />
|
||||
<Route path={ROOT_ROUTE} element={<Navigate to={EARTH_ROUTE} replace />} />
|
||||
<Route path={EARTH_ROUTE} element={<Earth />} />
|
||||
<Route path={DOCS_ROUTE} element={<Docs />} />
|
||||
<Route path={DOCS_ROUTE_PATTERN} element={<Docs />} />
|
||||
<Route path="/playground" element={<Navigate to="/ai?section=playground" replace />} />
|
||||
<Route path="/*" element={<AdminErrorBoundary><AdminRoutes /></AdminErrorBoundary>} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
<>
|
||||
<LegacyI18nBridge />
|
||||
<Suspense
|
||||
fallback={(
|
||||
<div className="app-route-loading">
|
||||
<div className="app-route-loading__spinner" aria-label={t('app.routeLoading')} />
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/verify-email" element={<VerifyEmail />} />
|
||||
<Route path="/forgot-password" element={<ForgotPassword />} />
|
||||
<Route path={ROOT_ROUTE} element={<Navigate to={EARTH_ROUTE} replace />} />
|
||||
<Route path={EARTH_ROUTE} element={<Earth />} />
|
||||
<Route path={DOCS_ROUTE} element={<Docs />} />
|
||||
<Route path={DOCS_ROUTE_PATTERN} element={<Docs />} />
|
||||
<Route path="/playground" element={<Navigate to="/ai?section=playground" replace />} />
|
||||
<Route path="/*" element={<AdminErrorBoundary><AdminRoutes /></AdminErrorBoundary>} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '@tanstack/react-table'
|
||||
import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import TableScrollRegion from '../../../components/Scrollbar/TableScrollRegion'
|
||||
import { Button } from '../ui/button'
|
||||
|
||||
@@ -37,11 +38,12 @@ export function DataTable<TData>({
|
||||
getRowClassName,
|
||||
selection,
|
||||
loading = false,
|
||||
emptyText = '暂无数据',
|
||||
emptyText,
|
||||
className = '',
|
||||
footer,
|
||||
onRowClick,
|
||||
}: DataTableProps<TData>) {
|
||||
const { t } = useTranslation()
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
const memoizedColumns = useMemo(() => columns, [columns])
|
||||
|
||||
@@ -74,7 +76,7 @@ export function DataTable<TData>({
|
||||
<th className="an-data-table__selection-cell">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="选择当前可见数据"
|
||||
aria-label={t('common.selectVisibleRows')}
|
||||
checked={allVisibleSelected}
|
||||
disabled={!visibleSelectableIds.length}
|
||||
ref={(element) => {
|
||||
@@ -114,7 +116,7 @@ export function DataTable<TData>({
|
||||
<td colSpan={columnCount}>
|
||||
<div className="an-data-table__state">
|
||||
<span className="an-spinner" />
|
||||
加载中
|
||||
{t('common.loading')}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -131,7 +133,7 @@ export function DataTable<TData>({
|
||||
<td className="an-data-table__selection-cell">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={selection.getCheckboxLabel?.(row.original) || '选择行'}
|
||||
aria-label={selection.getCheckboxLabel?.(row.original) || t('common.selectRow')}
|
||||
checked={selection.selectedRowIds.has(row.id)}
|
||||
disabled={selection.isRowSelectable ? !selection.isRowSelectable(row.original) : false}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
@@ -149,7 +151,7 @@ export function DataTable<TData>({
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={columnCount}>
|
||||
<div className="an-data-table__state">{emptyText}</div>
|
||||
<div className="an-data-table__state">{emptyText || t('common.noData')}</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
@@ -173,18 +175,19 @@ export function DataTablePager({
|
||||
total: number
|
||||
onPageChange: (page: number) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize))
|
||||
return (
|
||||
<div className="an-data-table__pager">
|
||||
<span>
|
||||
第 {page} / {totalPages} 页,共 {total.toLocaleString()} 条
|
||||
{t('common.page', { page, totalPages, total: total.toLocaleString() })}
|
||||
</span>
|
||||
<div className="an-data-table__pager-actions">
|
||||
<Button size="sm" variant="subtle" disabled={page <= 1} onClick={() => onPageChange(page - 1)}>
|
||||
上一页
|
||||
{t('common.previousPage')}
|
||||
</Button>
|
||||
<Button size="sm" variant="subtle" disabled={page >= totalPages} onClick={() => onPageChange(page + 1)}>
|
||||
下一页
|
||||
{t('common.nextPage')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import {
|
||||
ChevronDown,
|
||||
Languages,
|
||||
LogOut,
|
||||
Menu,
|
||||
Moon,
|
||||
Monitor,
|
||||
Search,
|
||||
Settings,
|
||||
Sun,
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
import { type FocusEvent, type KeyboardEvent, type ReactNode, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import packageJson from '../../../../package.json'
|
||||
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
|
||||
import SegmentedControl from '../../../components/SegmentedControl/SegmentedControl'
|
||||
import { localeOptions, useLocale, type SupportedLocale } from '../../../i18n/locale'
|
||||
import { useAuthStore } from '../../../stores/auth'
|
||||
import { useAdminTheme, type AdminThemeMode } from '../../design/theme'
|
||||
import { cn } from '../../utils'
|
||||
@@ -28,6 +32,8 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const adminSearch = useAdminSearch()
|
||||
const { t } = useTranslation()
|
||||
const { locale, setLocale } = useLocale()
|
||||
const { user, logout } = useAuthStore()
|
||||
const { mode, setMode } = useAdminTheme()
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
@@ -35,25 +41,39 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
const [openKeys, setOpenKeys] = useState<string[]>(cachedOpenKeys)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [preferencesOpen, setPreferencesOpen] = useState(false)
|
||||
const [highlightedSearchIndex, setHighlightedSearchIndex] = useState(0)
|
||||
const menuViewportRef = useRef<HTMLDivElement>(null)
|
||||
const searchInputRef = useRef<HTMLInputElement>(null)
|
||||
const isSuperAdmin = user?.role === 'super_admin'
|
||||
const username = user?.username || '-'
|
||||
const userInitial = username.trim().charAt(0).toUpperCase() || '?'
|
||||
const preferencesLabel = preferencesOpen ? t('admin.collapsePreferences') : t('admin.expandPreferences')
|
||||
const visibleRoutes = useMemo(() => getVisibleAdminRoutes(isSuperAdmin), [isSuperAdmin])
|
||||
const navGroups = useMemo(() => {
|
||||
return adminRouteGroups.map((group) => ({
|
||||
...group,
|
||||
children: visibleRoutes.filter((route) => route.group === group.key),
|
||||
label: t(group.labelKey),
|
||||
children: visibleRoutes
|
||||
.filter((route) => route.group === group.key)
|
||||
.map((route) => ({ ...route, label: t(route.labelKey) })),
|
||||
})).filter((group) => group.children.length > 0)
|
||||
}, [visibleRoutes])
|
||||
}, [t, visibleRoutes])
|
||||
const selectedKey = location.pathname === '/admin/' ? '/admin' : location.pathname.replace(/\/$/, '')
|
||||
const activeRoute = visibleRoutes.find((route) => route.path === selectedKey)
|
||||
const activeRouteLabel = activeRoute ? t(activeRoute.labelKey) : ''
|
||||
const searchResults = useMemo(() => adminSearch.search(searchQuery), [adminSearch, searchQuery])
|
||||
const themeOptions = useMemo(() => [
|
||||
{ value: 'light' as const, label: '浅色', title: '浅色', icon: <Sun /> },
|
||||
{ value: 'system' as const, label: '系统', title: '跟随系统', icon: <Monitor /> },
|
||||
{ value: 'dark' as const, label: '深色', title: '深色', icon: <Moon /> },
|
||||
], [])
|
||||
{ value: 'light' as const, label: t('common.themeLight'), title: t('common.themeLight'), icon: <Sun /> },
|
||||
{ value: 'system' as const, label: t('common.themeSystem'), title: t('common.themeFollowSystem'), icon: <Monitor /> },
|
||||
{ value: 'dark' as const, label: t('common.themeDark'), title: t('common.themeDark'), icon: <Moon /> },
|
||||
], [t])
|
||||
const languageOptions = useMemo(() => localeOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: t(option.labelKey),
|
||||
title: t(option.titleKey),
|
||||
icon: <Languages />,
|
||||
})), [t])
|
||||
|
||||
const updateOpenKeys = (nextKeys: string[]) => {
|
||||
cachedOpenKeys = nextKeys
|
||||
@@ -116,14 +136,15 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
event.stopPropagation()
|
||||
setCollapsed((value) => !value)
|
||||
}}
|
||||
aria-label={collapsed ? '展开菜单' : '折叠菜单'}
|
||||
title={collapsed ? t('admin.expandMenu') : t('admin.collapseMenu')}
|
||||
aria-label={collapsed ? t('admin.expandMenu') : t('admin.collapseMenu')}
|
||||
>
|
||||
{collapsed ? <Menu size={18} /> : <X size={18} />}
|
||||
</Button>
|
||||
{!collapsed ? (
|
||||
<div className="admin__brand-copy">
|
||||
<span className="admin__brand-text">智能星球</span>
|
||||
<span className="admin__brand-subtitle">控制台</span>
|
||||
<span className="admin__brand-text">{t('admin.brandTitle')}</span>
|
||||
<span className="admin__brand-subtitle">{t('admin.brandSubtitle')}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -185,36 +206,61 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
{!collapsed ? (
|
||||
<div className="admin__account">
|
||||
<div className="admin__account-row">
|
||||
<div>
|
||||
<strong>Hi, {user?.username || '-'}</strong>
|
||||
<div className="admin__account-row admin__account-row--primary">
|
||||
<div className="admin__account-profile">
|
||||
<span className="admin__account-avatar" aria-hidden="true">{userInitial}</span>
|
||||
<div>
|
||||
<strong>{t('admin.greeting', { name: username })}</strong>
|
||||
<span>{t('admin.version')} v{packageJson.version}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin__account-actions">
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className={cn('admin__account-preferences', preferencesOpen && 'is-active')}
|
||||
onClick={() => setPreferencesOpen((value) => !value)}
|
||||
title={preferencesLabel}
|
||||
aria-label={preferencesLabel}
|
||||
aria-expanded={preferencesOpen}
|
||||
>
|
||||
<Settings size={15} />
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="admin__account-logout"
|
||||
onClick={() => {
|
||||
logout()
|
||||
navigate('/login')
|
||||
}}
|
||||
title={t('admin.logout')}
|
||||
aria-label={t('admin.logout')}
|
||||
>
|
||||
<LogOut size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="admin__account-logout"
|
||||
onClick={() => {
|
||||
logout()
|
||||
navigate('/login')
|
||||
}}
|
||||
aria-label="退出登录"
|
||||
title="退出登录"
|
||||
>
|
||||
<LogOut size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="admin__account-row">
|
||||
<span>版本号</span>
|
||||
<strong>v{packageJson.version}</strong>
|
||||
<div className={cn('admin__preferences-drawer', preferencesOpen && 'is-open')} aria-hidden={!preferencesOpen}>
|
||||
<div className="admin__preferences-panel">
|
||||
<SegmentedControl<SupportedLocale>
|
||||
ariaLabel={t('admin.languageControl')}
|
||||
className="admin__language-control admin__language-control--sider"
|
||||
options={languageOptions}
|
||||
scale={0.86}
|
||||
value={locale}
|
||||
onChange={setLocale}
|
||||
/>
|
||||
<SegmentedControl<AdminThemeMode>
|
||||
ariaLabel={t('admin.themeControl')}
|
||||
className="admin__theme-control admin__theme-control--sider"
|
||||
options={themeOptions}
|
||||
scale={0.86}
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<SegmentedControl<AdminThemeMode>
|
||||
ariaLabel="控制台主题"
|
||||
className="admin__theme-control admin__theme-control--sider"
|
||||
options={themeOptions}
|
||||
scale={0.72}
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
@@ -249,22 +295,22 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
{mobileNavOpen ? (
|
||||
<div className="admin__mobile-nav">
|
||||
<div className="admin__mobile-nav-panel">{nav}</div>
|
||||
<button className="admin__mobile-nav-backdrop" type="button" aria-label="关闭导航" onClick={() => setMobileNavOpen(false)} />
|
||||
<button className="admin__mobile-nav-backdrop" type="button" aria-label={t('admin.closeNav')} onClick={() => setMobileNavOpen(false)} />
|
||||
</div>
|
||||
) : null}
|
||||
<main className="admin__content">
|
||||
<header className="admin__topbar">
|
||||
<Button size="icon" variant="ghost" className="admin__mobile-menu" onClick={() => setMobileNavOpen(true)} aria-label="打开导航">
|
||||
<Button size="icon" variant="ghost" className="admin__mobile-menu" onClick={() => setMobileNavOpen(true)} aria-label={t('admin.openNav')} title={t('admin.openNav')}>
|
||||
<Menu size={18} />
|
||||
</Button>
|
||||
<div className="admin__search" onBlur={handleSearchBlur}>
|
||||
<Search className="admin__search-icon" size={16} />
|
||||
<input
|
||||
ref={searchInputRef}
|
||||
aria-label="搜索功能、配置和文字"
|
||||
aria-label={t('admin.search.label')}
|
||||
autoComplete="off"
|
||||
value={searchQuery}
|
||||
placeholder={activeRoute ? `搜索功能、配置和文字,当前:${activeRoute.label}` : '搜索功能、配置和文字'}
|
||||
placeholder={activeRouteLabel ? `${t('admin.search.placeholder')},${t('admin.search.current', { label: activeRouteLabel })}` : t('admin.search.placeholder')}
|
||||
onChange={(event) => {
|
||||
setSearchQuery(event.target.value)
|
||||
setSearchOpen(true)
|
||||
@@ -274,7 +320,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
/>
|
||||
{searchOpen ? (
|
||||
<div className="admin__search-results" role="listbox" aria-label="Admin 搜索结果">
|
||||
<div className="admin__search-results" role="listbox" aria-label={t('admin.search.results')}>
|
||||
{searchResults.length > 0 ? searchResults.map((target, index) => {
|
||||
const ResultIcon = target.icon || Search
|
||||
return (
|
||||
@@ -296,7 +342,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
||||
</button>
|
||||
)
|
||||
}) : (
|
||||
<div className="admin__search-empty">{adminSearch.loading ? '正在加载搜索索引…' : '没有找到匹配内容'}</div>
|
||||
<div className="admin__search-empty">{adminSearch.loading ? t('admin.search.loading') : t('admin.search.empty')}</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog'
|
||||
import { X } from 'lucide-react'
|
||||
import { type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
|
||||
import { Button } from './button'
|
||||
|
||||
@@ -15,6 +16,8 @@ interface DialogProps {
|
||||
}
|
||||
|
||||
export function Dialog({ open, onOpenChange, title, description, children, footer, width }: DialogProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
|
||||
<DialogPrimitive.Portal>
|
||||
@@ -30,7 +33,7 @@ export function Dialog({ open, onOpenChange, title, description, children, foote
|
||||
) : null}
|
||||
</div>
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button size="icon" variant="ghost" aria-label="关闭">
|
||||
<Button size="icon" variant="ghost" aria-label={t('common.close')} title={t('common.close')}>
|
||||
<X size={16} />
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
@@ -60,12 +63,16 @@ export function ConfirmDialog({
|
||||
onOpenChange,
|
||||
title,
|
||||
description,
|
||||
confirmLabel = '确认',
|
||||
cancelLabel = '取消',
|
||||
confirmLabel,
|
||||
cancelLabel,
|
||||
danger = false,
|
||||
loading = false,
|
||||
onConfirm,
|
||||
}: ConfirmDialogProps) {
|
||||
const { t } = useTranslation()
|
||||
const resolvedCancelLabel = cancelLabel || t('common.cancel')
|
||||
const resolvedConfirmLabel = confirmLabel || t('common.confirm')
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
@@ -76,15 +83,15 @@ export function ConfirmDialog({
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="subtle" onClick={() => onOpenChange(false)} disabled={loading}>
|
||||
{cancelLabel}
|
||||
{resolvedCancelLabel}
|
||||
</Button>
|
||||
<Button variant={danger ? 'danger' : 'primary'} onClick={onConfirm} loading={loading}>
|
||||
{confirmLabel}
|
||||
{resolvedConfirmLabel}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<span className="sr-only">{description || '请确认本次操作。'}</span>
|
||||
<span className="sr-only">{description || t('common.confirm')}</span>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as ToastPrimitive from '@radix-ui/react-toast'
|
||||
import { X } from 'lucide-react'
|
||||
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type ToastTone = 'default' | 'success' | 'error'
|
||||
|
||||
@@ -18,6 +19,7 @@ interface ToastContextValue {
|
||||
const ToastContext = createContext<ToastContextValue | null>(null)
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const { t } = useTranslation()
|
||||
const [items, setItems] = useState<ToastItem[]>([])
|
||||
|
||||
const toast = useCallback((item: Omit<ToastItem, 'id' | 'tone'> & { tone?: ToastTone }) => {
|
||||
@@ -46,7 +48,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
{item.description}
|
||||
</ToastPrimitive.Description>
|
||||
) : null}
|
||||
<ToastPrimitive.Close className="an-toast__close" aria-label="关闭通知">
|
||||
<ToastPrimitive.Close className="an-toast__close" aria-label={t('common.close')} title={t('common.close')}>
|
||||
<X size={14} />
|
||||
</ToastPrimitive.Close>
|
||||
</ToastPrimitive.Root>
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { useWebSocket } from '../../hooks/useWebSocket'
|
||||
import { describeApiError, describeApiValue } from '../../i18n/api-errors'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import { formatDateTimeZhCN } from '../../utils/datetime'
|
||||
import { AdminLayout } from '../components/layout/AdminLayout'
|
||||
@@ -148,14 +149,14 @@ function DashboardContent() {
|
||||
setRestartTaskId(res.data.task_id)
|
||||
setRestartStartedAt(Date.now())
|
||||
setRestartStage('waiting_for_shutdown')
|
||||
setRestartMessage(res.data.message || '已发送重启指令,正在等待服务进入重启流程。')
|
||||
setRestartMessage(describeApiValue(res.data.message, '已发送重启指令,正在等待服务进入重启流程。'))
|
||||
setRestartLogs((current) => [...current, `任务已创建: ${res.data.task_id}`])
|
||||
} catch (restartError: unknown) {
|
||||
const err = restartError as { response?: { data?: { detail?: string } } }
|
||||
const restartFailureMessage = describeApiError(restartError, '提交重启任务失败')
|
||||
setRestartStage('failed')
|
||||
setRestartMessage(err.response?.data?.detail || '提交重启任务失败')
|
||||
setRestartMessage(restartFailureMessage)
|
||||
setRestartLogs((current) => [...current, '提交重启任务失败'])
|
||||
toast({ tone: 'error', title: '提交失败', description: err.response?.data?.detail || '提交重启任务失败' })
|
||||
toast({ tone: 'error', title: '提交失败', description: restartFailureMessage })
|
||||
} finally {
|
||||
setRestartSubmitting(false)
|
||||
}
|
||||
@@ -191,7 +192,7 @@ function DashboardContent() {
|
||||
try {
|
||||
const taskRes = await axios.get<RestartTask>(`/api/v1/system/restart-tasks/${restartTaskId}`, { timeout: 1500 })
|
||||
const task = taskRes.data
|
||||
if (!cancelled && task?.message) setRestartMessage(task.message)
|
||||
if (!cancelled && task?.message) setRestartMessage(describeApiValue(task.message, '重启任务正在执行'))
|
||||
if (!cancelled && restartAction !== 'restart-system') {
|
||||
const logsRes = await axios.get<RestartTaskLogs>(`/api/v1/system/restart-tasks/${restartTaskId}/logs`, { timeout: 1500 })
|
||||
if (logsRes.data.lines.length > 0) setRestartLogs(logsRes.data.lines.slice(-8))
|
||||
@@ -204,7 +205,7 @@ function DashboardContent() {
|
||||
}
|
||||
if (!cancelled && (task.status === 'failed' || task.status === 'timeout')) {
|
||||
setRestartStage(task.status === 'timeout' ? 'timeout' : 'failed')
|
||||
setRestartMessage(task.message || '重启任务失败')
|
||||
setRestartMessage(describeApiValue(task.message, '重启任务失败'))
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -410,8 +410,8 @@ export default function DataList() {
|
||||
<CardHeader>
|
||||
<CardTitle>数据概览</CardTitle>
|
||||
<div className="an-segmented">
|
||||
<button className={distributionDimension === 'source' ? 'is-active' : ''} onClick={() => setDistributionDimension('source')}>按数据源</button>
|
||||
<button className={distributionDimension === 'type' ? 'is-active' : ''} onClick={() => setDistributionDimension('type')}>按类型</button>
|
||||
<button type="button" className={distributionDimension === 'source' ? 'is-active' : ''} onClick={() => setDistributionDimension('source')}>按数据源</button>
|
||||
<button type="button" className={distributionDimension === 'type' ? 'is-active' : ''} onClick={() => setDistributionDimension('type')}>按类型</button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import { useWebSocket } from '../../hooks/useWebSocket'
|
||||
import { describeApiError } from '../../i18n/api-errors'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import { AdminLayout } from '../components/layout/AdminLayout'
|
||||
import { Badge } from '../components/ui/badge'
|
||||
@@ -168,9 +169,7 @@ function statusLabel(status: string) {
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown, fallback: string) {
|
||||
if (!axios.isAxiosError(error)) return fallback
|
||||
const detail = error.response?.data?.detail
|
||||
return typeof detail === 'string' ? detail : fallback
|
||||
return describeApiError(error, fallback)
|
||||
}
|
||||
|
||||
function formatDateTime(value?: string | null) {
|
||||
|
||||
@@ -4,7 +4,9 @@ import axios from 'axios'
|
||||
import { Edit, Plus, Search, Trash2, X } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { z } from 'zod'
|
||||
import { describeApiError } from '../../i18n/api-errors'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import { DataTable } from '../components/data-table/DataTable'
|
||||
import { AdminLayout } from '../components/layout/AdminLayout'
|
||||
@@ -25,28 +27,17 @@ interface User {
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const userSchema = z.object({
|
||||
username: z.string().min(1, '请输入用户名'),
|
||||
email: z.string().email('请输入有效邮箱'),
|
||||
password: z.string().optional(),
|
||||
role: z.string().min(1, '请选择角色'),
|
||||
gatekeeper_groups: z.array(z.string()).optional(),
|
||||
})
|
||||
interface UserFormValues {
|
||||
username: string
|
||||
email: string
|
||||
password?: string
|
||||
role: string
|
||||
gatekeeper_groups?: string[]
|
||||
}
|
||||
|
||||
type UserFormValues = z.infer<typeof userSchema>
|
||||
const roleValues = ['super_admin', 'admin', 'operator', 'viewer'] as const
|
||||
|
||||
const roleOptions = [
|
||||
{ value: 'super_admin', label: '超级管理员' },
|
||||
{ value: 'admin', label: '管理员' },
|
||||
{ value: 'operator', label: '操作员' },
|
||||
{ value: 'viewer', label: '只读用户' },
|
||||
]
|
||||
|
||||
const gatekeeperOptions = [
|
||||
{ value: 'docs_user', label: '文档:用户文档' },
|
||||
{ value: 'docs_developer', label: '文档:开发文档' },
|
||||
{ value: 'docs_admin', label: '文档:管理/运维文档' },
|
||||
]
|
||||
const gatekeeperValues = ['docs_user', 'docs_developer', 'docs_admin'] as const
|
||||
|
||||
function roleTone(role: string) {
|
||||
if (role === 'super_admin') return 'red'
|
||||
@@ -56,15 +47,8 @@ function roleTone(role: string) {
|
||||
return 'default'
|
||||
}
|
||||
|
||||
function roleLabel(role: string) {
|
||||
return roleOptions.find((option) => option.value === role)?.label || role
|
||||
}
|
||||
|
||||
function gatekeeperLabel(group: string) {
|
||||
return gatekeeperOptions.find((option) => option.value === group)?.label || group
|
||||
}
|
||||
|
||||
export default function Users() {
|
||||
const { t } = useTranslation()
|
||||
const { user: currentUser } = useAuthStore()
|
||||
const { toast } = useToast()
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
@@ -74,6 +58,23 @@ export default function Users() {
|
||||
const [deleteTarget, setDeleteTarget] = useState<User | null>(null)
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const isSuperAdmin = currentUser?.role === 'super_admin'
|
||||
const userSchema = useMemo(() => z.object({
|
||||
username: z.string().min(1, t('auth.username')),
|
||||
email: z.string().email(t('auth.email')),
|
||||
password: z.string().optional(),
|
||||
role: z.string().min(1, t('users.role')),
|
||||
gatekeeper_groups: z.array(z.string()).optional(),
|
||||
}), [t])
|
||||
const roleOptions = useMemo(() => roleValues.map((value) => ({
|
||||
value,
|
||||
label: t(`users.roles.${value}`),
|
||||
})), [t])
|
||||
const gatekeeperOptions = useMemo(() => gatekeeperValues.map((value) => ({
|
||||
value,
|
||||
label: t(`users.gatekeeper.${value}`),
|
||||
})), [t])
|
||||
const roleLabel = (role: string) => roleOptions.find((option) => option.value === role)?.label || role
|
||||
const gatekeeperLabel = (group: string) => gatekeeperOptions.find((option) => option.value === group)?.label || group
|
||||
|
||||
const form = useForm<UserFormValues>({
|
||||
resolver: zodResolver(userSchema),
|
||||
@@ -125,17 +126,16 @@ export default function Users() {
|
||||
if (!isSuperAdmin) delete payload.gatekeeper_groups
|
||||
if (editingUser) {
|
||||
await axios.put(`/api/v1/users/${editingUser.id}`, payload)
|
||||
toast({ tone: 'success', title: '更新成功' })
|
||||
toast({ tone: 'success', title: t('users.updateSuccess') })
|
||||
} else {
|
||||
const createPayload = { ...payload, password: values.password || '' }
|
||||
await axios.post('/api/v1/users', createPayload)
|
||||
toast({ tone: 'success', title: '创建成功' })
|
||||
toast({ tone: 'success', title: t('users.createSuccess') })
|
||||
}
|
||||
setModalVisible(false)
|
||||
void fetchUsers()
|
||||
} catch (error: unknown) {
|
||||
const err = error as { response?: { data?: { detail?: string } } }
|
||||
toast({ tone: 'error', title: '操作失败', description: err.response?.data?.detail || '请稍后重试' })
|
||||
toast({ tone: 'error', title: t('common.operationFailed'), description: describeApiError(error, t('users.retryLater')) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,22 +143,21 @@ export default function Users() {
|
||||
if (!deleteTarget) return
|
||||
try {
|
||||
await axios.delete(`/api/v1/users/${deleteTarget.id}`)
|
||||
toast({ tone: 'success', title: '删除成功' })
|
||||
toast({ tone: 'success', title: t('users.deleteSuccess') })
|
||||
setDeleteTarget(null)
|
||||
void fetchUsers()
|
||||
} catch (error: unknown) {
|
||||
const err = error as { response?: { data?: { detail?: string } } }
|
||||
toast({ tone: 'error', title: '删除失败', description: err.response?.data?.detail || '请稍后重试' })
|
||||
toast({ tone: 'error', title: t('users.deleteFailed'), description: describeApiError(error, t('users.retryLater')) })
|
||||
}
|
||||
}
|
||||
|
||||
const columns = useMemo<Array<ColumnDef<User>>>(() => [
|
||||
{ accessorKey: 'id', header: 'ID', size: 80 },
|
||||
{ accessorKey: 'username', header: '用户名', size: 180 },
|
||||
{ accessorKey: 'email', header: '邮箱', size: 260 },
|
||||
{ accessorKey: 'username', header: t('auth.username'), size: 180 },
|
||||
{ accessorKey: 'email', header: t('auth.email'), size: 260 },
|
||||
{
|
||||
accessorKey: 'role',
|
||||
header: '角色',
|
||||
header: t('users.role'),
|
||||
size: 140,
|
||||
cell: ({ row }) => <Badge tone={roleTone(row.original.role)} title={row.original.role}>{roleLabel(row.original.role)}</Badge>,
|
||||
},
|
||||
@@ -175,30 +174,30 @@ export default function Users() {
|
||||
<Badge key={group} tone={group === 'docs_admin' ? 'red' : group === 'docs_developer' ? 'blue' : 'green'}>
|
||||
{gatekeeperLabel(group)}
|
||||
</Badge>
|
||||
)) : <Badge tone="slate">未配置</Badge>}
|
||||
)) : <Badge tone="slate">{t('users.unconfigured')}</Badge>}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'is_active',
|
||||
header: '状态',
|
||||
header: t('users.status'),
|
||||
size: 120,
|
||||
cell: ({ row }) => <Badge tone={row.original.is_active ? 'green' : 'red'}>{row.original.is_active ? '活跃' : '禁用'}</Badge>,
|
||||
cell: ({ row }) => <Badge tone={row.original.is_active ? 'green' : 'red'}>{row.original.is_active ? t('users.active') : t('users.disabled')}</Badge>,
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
header: '操作',
|
||||
header: t('users.actions'),
|
||||
size: 148,
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<div className="an-row-actions">
|
||||
<Button size="sm" variant="ghost" onClick={() => handleEdit(row.original)}><Edit size={14} />编辑</Button>
|
||||
<Button size="sm" variant="ghost" className="is-danger" onClick={() => setDeleteTarget(row.original)}><Trash2 size={14} />删除</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleEdit(row.original)}><Edit size={14} />{t('users.edit')}</Button>
|
||||
<Button size="sm" variant="ghost" className="is-danger" onClick={() => setDeleteTarget(row.original)}><Trash2 size={14} />{t('common.delete')}</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
], [])
|
||||
], [gatekeeperOptions, roleOptions, t])
|
||||
|
||||
const filteredUsers = useMemo(() => {
|
||||
const keyword = searchText.trim().toLowerCase()
|
||||
@@ -218,8 +217,8 @@ export default function Users() {
|
||||
<div className="an-page">
|
||||
<div className="an-page__header">
|
||||
<div>
|
||||
<h1>用户管理</h1>
|
||||
<p>维护后台账号、角色与文档权限组。</p>
|
||||
<h1>{t('admin.routes.users')}</h1>
|
||||
<p>{t('users.description')}</p>
|
||||
</div>
|
||||
<div className="an-toolbar">
|
||||
<div className="an-search-box">
|
||||
@@ -227,15 +226,15 @@ export default function Users() {
|
||||
<Input
|
||||
value={searchText}
|
||||
onChange={(event) => setSearchText(event.target.value)}
|
||||
placeholder="搜索用户、邮箱、角色"
|
||||
placeholder={t('users.searchPlaceholder')}
|
||||
/>
|
||||
{searchText ? (
|
||||
<Button size="icon" variant="ghost" onClick={() => setSearchText('')} aria-label="清空搜索" title="清空搜索">
|
||||
<Button size="icon" variant="ghost" onClick={() => setSearchText('')} aria-label={t('users.clearSearch')} title={t('users.clearSearch')}>
|
||||
<X size={14} />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<Button variant="primary" onClick={handleAdd}><Plus size={16} />添加用户</Button>
|
||||
<Button variant="primary" onClick={handleAdd}><Plus size={16} />{t('users.addUser')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="an-page__body">
|
||||
@@ -244,40 +243,40 @@ export default function Users() {
|
||||
</div>
|
||||
|
||||
<Dialog
|
||||
title={editingUser ? '编辑用户' : '添加用户'}
|
||||
title={editingUser ? t('users.editUser') : t('users.addUser')}
|
||||
open={modalVisible}
|
||||
onOpenChange={setModalVisible}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="subtle" onClick={() => setModalVisible(false)}>取消</Button>
|
||||
<Button variant="primary" loading={form.formState.isSubmitting} onClick={form.handleSubmit(handleSubmit)}>提交</Button>
|
||||
<Button variant="subtle" onClick={() => setModalVisible(false)}>{t('common.cancel')}</Button>
|
||||
<Button variant="primary" loading={form.formState.isSubmitting} onClick={form.handleSubmit(handleSubmit)}>{t('users.submit')}</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<form className="an-form" onSubmit={form.handleSubmit(handleSubmit)}>
|
||||
<label className="an-field">
|
||||
<span>用户名</span>
|
||||
<span>{t('auth.username')}</span>
|
||||
<Input {...form.register('username')} />
|
||||
{form.formState.errors.username ? <em>{form.formState.errors.username.message}</em> : null}
|
||||
</label>
|
||||
<label className="an-field">
|
||||
<span>邮箱</span>
|
||||
<span>{t('auth.email')}</span>
|
||||
<Input {...form.register('email')} />
|
||||
{form.formState.errors.email ? <em>{form.formState.errors.email.message}</em> : null}
|
||||
</label>
|
||||
{!editingUser ? (
|
||||
<label className="an-field">
|
||||
<span>密码</span>
|
||||
<span>{t('auth.password')}</span>
|
||||
<Input type="password" {...form.register('password', { required: true, minLength: 8 })} />
|
||||
{form.formState.errors.password ? <em>密码至少 8 位</em> : null}
|
||||
{form.formState.errors.password ? <em>{t('auth.passwordHint')}</em> : null}
|
||||
</label>
|
||||
) : null}
|
||||
<label className="an-field">
|
||||
<span>角色</span>
|
||||
<span>{t('users.role')}</span>
|
||||
<Select value={form.watch('role')} onValueChange={(value) => form.setValue('role', value)} options={roleOptions} />
|
||||
</label>
|
||||
<div className="an-field">
|
||||
<span>Gatekeeper 权限组</span>
|
||||
<span>{t('users.gatekeeperGroups')}</span>
|
||||
<div className="an-checkbox-list" aria-disabled={!isSuperAdmin}>
|
||||
{gatekeeperOptions.map((option) => (
|
||||
<label key={option.value}>
|
||||
@@ -301,14 +300,14 @@ export default function Users() {
|
||||
</Dialog>
|
||||
|
||||
<ConfirmDialog
|
||||
title="确认删除"
|
||||
title={t('users.confirmDelete')}
|
||||
open={Boolean(deleteTarget)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
description={`确定要删除用户 ${deleteTarget?.username || ''} 吗?`}
|
||||
description={t('users.confirmDeleteDescription', { username: deleteTarget?.username || '' })}
|
||||
danger
|
||||
confirmLabel="删除"
|
||||
confirmLabel={t('common.delete')}
|
||||
onConfirm={() => void handleDelete()}
|
||||
/>
|
||||
</AdminLayout>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
export interface AdminRouteItem {
|
||||
path: string
|
||||
label: string
|
||||
labelKey: string
|
||||
group: string
|
||||
icon: LucideIcon
|
||||
keywords: string[]
|
||||
@@ -26,33 +27,34 @@ export interface AdminRouteItem {
|
||||
export interface AdminRouteGroup {
|
||||
key: string
|
||||
label: string
|
||||
labelKey: string
|
||||
icon: LucideIcon
|
||||
}
|
||||
|
||||
export const adminRouteGroups: AdminRouteGroup[] = [
|
||||
{ key: 'overview', label: '总览', icon: CircleGauge },
|
||||
{ key: 'collection', label: '采集与数据', icon: HardDrive },
|
||||
{ key: 'observability', label: '专题观测', icon: AppWindow },
|
||||
{ key: 'alerts', label: '告警与研判', icon: ShieldAlert },
|
||||
{ key: 'ops', label: '运维与配置', icon: Settings },
|
||||
{ key: 'overview', label: '总览', labelKey: 'admin.groups.overview', icon: CircleGauge },
|
||||
{ key: 'collection', label: '采集与数据', labelKey: 'admin.groups.collection', icon: HardDrive },
|
||||
{ key: 'observability', label: '专题观测', labelKey: 'admin.groups.observability', icon: AppWindow },
|
||||
{ key: 'alerts', label: '告警与研判', labelKey: 'admin.groups.alerts', icon: ShieldAlert },
|
||||
{ key: 'ops', label: '运维与配置', labelKey: 'admin.groups.ops', icon: Settings },
|
||||
]
|
||||
|
||||
export const adminRoutes: AdminRouteItem[] = [
|
||||
{ path: '/admin', label: '仪表盘', group: 'overview', icon: CircleGauge, keywords: ['dashboard', '总览', '驾驶舱'] },
|
||||
{ path: '/earth', label: '智能星球', group: 'overview', icon: Globe2, keywords: ['earth', '地球', '智能星球'] },
|
||||
{ path: '/docs', label: '文档', group: 'overview', icon: FileText, keywords: ['docs', '文档', 'manual', '使用手册'] },
|
||||
{ path: '/datasources', label: '数据源', group: 'collection', icon: Database, keywords: ['datasource', '采集', '目录'] },
|
||||
{ path: '/data', label: '采集数据', group: 'collection', icon: AppWindow, keywords: ['data', 'records', '采集数据'] },
|
||||
{ path: '/bgp', label: 'BGP观测', group: 'observability', icon: Network, keywords: ['bgp', '观测', '网络'] },
|
||||
{ path: '/alerts/system', label: '系统告警', group: 'alerts', icon: AlertTriangle, keywords: ['alert', 'system', '告警'] },
|
||||
{ path: '/alerts/bgp', label: 'BGP 告警', group: 'alerts', icon: Network, keywords: ['alert', 'bgp', '风险'] },
|
||||
{ path: '/alerts/situational', label: '态势告警', group: 'alerts', icon: Globe2, keywords: ['situational', '态势', '研判'] },
|
||||
{ path: '/ai', label: 'AI', group: 'ops', icon: Bot, keywords: ['ai', 'provider', 'playground', 'prompt'] },
|
||||
{ path: '/earth-content', label: '智能星球内容', group: 'ops', icon: Globe2, keywords: ['earth', '地球', '智能星球', 'tv', 'boundary', 'brand', 'news', 'rss', '新闻源'] },
|
||||
{ path: '/collection-management', label: '采集管理', group: 'ops', icon: Database, keywords: ['collector', 'mapping', 'custom source'] },
|
||||
{ path: '/logs', label: '系统日志', group: 'ops', icon: FileText, keywords: ['log', '日志', 'tail'], superAdminOnly: true },
|
||||
{ path: '/users', label: '用户管理', group: 'ops', icon: Users, keywords: ['users', 'role', 'gatekeeper'] },
|
||||
{ path: '/settings', label: '系统设置', group: 'ops', icon: Settings, keywords: ['settings', 'smtp', 'security'] },
|
||||
{ path: '/admin', label: '仪表盘', labelKey: 'admin.routes.dashboard', group: 'overview', icon: CircleGauge, keywords: ['dashboard', '总览', '驾驶舱'] },
|
||||
{ path: '/earth', label: '智能星球', labelKey: 'admin.routes.earth', group: 'overview', icon: Globe2, keywords: ['earth', '地球', '智能星球'] },
|
||||
{ path: '/docs', label: '文档', labelKey: 'admin.routes.docs', group: 'overview', icon: FileText, keywords: ['docs', '文档', 'manual', '使用手册'] },
|
||||
{ path: '/datasources', label: '数据源', labelKey: 'admin.routes.datasources', group: 'collection', icon: Database, keywords: ['datasource', '采集', '目录'] },
|
||||
{ path: '/data', label: '采集数据', labelKey: 'admin.routes.data', group: 'collection', icon: AppWindow, keywords: ['data', 'records', '采集数据'] },
|
||||
{ path: '/bgp', label: 'BGP观测', labelKey: 'admin.routes.bgp', group: 'observability', icon: Network, keywords: ['bgp', '观测', '网络'] },
|
||||
{ path: '/alerts/system', label: '系统告警', labelKey: 'admin.routes.systemAlerts', group: 'alerts', icon: AlertTriangle, keywords: ['alert', 'system', '告警'] },
|
||||
{ path: '/alerts/bgp', label: 'BGP 告警', labelKey: 'admin.routes.bgpAlerts', group: 'alerts', icon: Network, keywords: ['alert', 'bgp', '风险'] },
|
||||
{ path: '/alerts/situational', label: '态势告警', labelKey: 'admin.routes.situationalAlerts', group: 'alerts', icon: Globe2, keywords: ['situational', '态势', '研判'] },
|
||||
{ path: '/ai', label: 'AI', labelKey: 'admin.routes.ai', group: 'ops', icon: Bot, keywords: ['ai', 'provider', 'playground', 'prompt'] },
|
||||
{ path: '/earth-content', label: '智能星球内容', labelKey: 'admin.routes.earthContent', group: 'ops', icon: Globe2, keywords: ['earth', '地球', '智能星球', 'tv', 'boundary', 'brand', 'news', 'rss', '新闻源'] },
|
||||
{ path: '/collection-management', label: '采集管理', labelKey: 'admin.routes.collectionManagement', group: 'ops', icon: Database, keywords: ['collector', 'mapping', 'custom source'] },
|
||||
{ path: '/logs', label: '系统日志', labelKey: 'admin.routes.logs', group: 'ops', icon: FileText, keywords: ['log', '日志', 'tail'], superAdminOnly: true },
|
||||
{ path: '/users', label: '用户管理', labelKey: 'admin.routes.users', group: 'ops', icon: Users, keywords: ['users', 'role', 'gatekeeper'] },
|
||||
{ path: '/settings', label: '系统设置', labelKey: 'admin.routes.settings', group: 'ops', icon: Settings, keywords: ['settings', 'smtp', 'security'] },
|
||||
]
|
||||
|
||||
export function getVisibleAdminRoutes(isSuperAdmin: boolean) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import { buildDynamicAdminTargets, buildStaticAdminTargets, searchAdminTargets } from './indexers'
|
||||
@@ -26,13 +27,14 @@ function targetSearchParams(target: AdminSearchTarget) {
|
||||
export function AdminSearchProvider({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { i18n } = useTranslation()
|
||||
const { user } = useAuthStore()
|
||||
const isSuperAdmin = user?.role === 'super_admin'
|
||||
const [dynamicTargets, setDynamicTargets] = useState<AdminSearchTarget[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const loadedRef = useRef(false)
|
||||
const loadingRef = useRef<Promise<void> | null>(null)
|
||||
const staticTargets = useMemo(() => buildStaticAdminTargets(isSuperAdmin), [isSuperAdmin])
|
||||
const staticTargets = useMemo(() => buildStaticAdminTargets(isSuperAdmin), [i18n.language, isSuperAdmin])
|
||||
const targets = useMemo(() => {
|
||||
const byId = new Map<string, AdminSearchTarget>()
|
||||
staticTargets.forEach((target) => byId.set(target.id, target))
|
||||
@@ -44,7 +46,7 @@ export function AdminSearchProvider({ children }: { children: ReactNode }) {
|
||||
loadedRef.current = false
|
||||
loadingRef.current = null
|
||||
setDynamicTargets([])
|
||||
}, [isSuperAdmin])
|
||||
}, [i18n.language, isSuperAdmin])
|
||||
|
||||
const ensureDynamicIndex = useCallback(async (query: string) => {
|
||||
if (query.trim().length < 2 || loadedRef.current) return
|
||||
|
||||
@@ -14,10 +14,11 @@ import {
|
||||
ShieldAlert,
|
||||
Users,
|
||||
} from 'lucide-react'
|
||||
import i18n from '../../i18n'
|
||||
import { adminRoutes, getVisibleAdminRoutes } from '../routes/manifest'
|
||||
import type { AdminSearchTarget } from './types'
|
||||
|
||||
const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || '/api/v1'
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api/v1'
|
||||
|
||||
function apiPath(path: string) {
|
||||
if (path.startsWith('/api/')) return path
|
||||
@@ -50,11 +51,68 @@ function targetId(parts: Array<string | undefined>) {
|
||||
return parts.filter(Boolean).join(':')
|
||||
}
|
||||
|
||||
const labelKeys: Record<string, string> = {
|
||||
'AI': 'admin.routes.ai',
|
||||
'BGP观测': 'admin.routes.bgp',
|
||||
'BGP': 'admin.sections.bgpOverview',
|
||||
'BGP 事故': 'admin.sections.alerts',
|
||||
'BGP 告警': 'admin.routes.bgpAlerts',
|
||||
'Playground': 'admin.sections.aiPlayground',
|
||||
'SMTP 邮件': 'admin.sections.smtp',
|
||||
'工具调用': 'admin.sections.aiTools',
|
||||
'提示词': 'admin.sections.aiPrompts',
|
||||
'日志': 'admin.routes.logs',
|
||||
'日志源': 'admin.sections.logsSources',
|
||||
'智能星球内容': 'admin.routes.earthContent',
|
||||
'模型供应商': 'admin.sections.aiIntegrations',
|
||||
'模型预设': 'admin.sections.aiIntegrations',
|
||||
'电视直播': 'admin.sections.tv',
|
||||
'系统告警': 'admin.routes.systemAlerts',
|
||||
'系统显示': 'admin.sections.settingsSystem',
|
||||
'系统设置': 'admin.routes.settings',
|
||||
'采集历史': 'admin.sections.collectionHistory',
|
||||
'采集历史 / 快照': 'admin.sections.collectionHistory',
|
||||
'采集器': 'admin.sections.collectorCredentials',
|
||||
'采集数据': 'admin.routes.data',
|
||||
'采集管理': 'admin.routes.collectionManagement',
|
||||
'采集调度': 'admin.sections.collectors',
|
||||
'数据源': 'admin.routes.datasources',
|
||||
'用户': 'admin.routes.users',
|
||||
'用户管理': 'admin.routes.users',
|
||||
'告警记录': 'admin.sections.alerts',
|
||||
'国界精度': 'admin.sections.earthAssets',
|
||||
'品牌标识': 'admin.sections.earthBrand',
|
||||
'态势告警': 'admin.routes.situationalAlerts',
|
||||
'通知策略': 'admin.sections.notifications',
|
||||
'安全策略': 'admin.sections.security',
|
||||
'新闻源': 'admin.sections.newsSources',
|
||||
'页面': 'admin.search.pageContext',
|
||||
}
|
||||
|
||||
function translateLabel(label: string | undefined): string | undefined {
|
||||
if (!label) return label
|
||||
const key = labelKeys[label]
|
||||
return key ? i18n.t(key) : label
|
||||
}
|
||||
|
||||
function makeTarget(target: Omit<AdminSearchTarget, 'id'> & { id?: string }): AdminSearchTarget {
|
||||
const routeLabel = translateLabel(target.routeLabel) || target.routeLabel
|
||||
const sectionLabel = translateLabel(target.sectionLabel) || target.sectionLabel
|
||||
const label = translateLabel(target.label) || target.label
|
||||
const contextLabel = translateLabel(target.contextLabel) || target.contextLabel
|
||||
|
||||
return {
|
||||
...target,
|
||||
contextLabel,
|
||||
id: target.id || targetId([target.routePath, target.sectionKey, target.groupKey, target.fieldKey, target.label]),
|
||||
label,
|
||||
routeLabel,
|
||||
sectionLabel,
|
||||
terms: Array.from(new Set([
|
||||
label,
|
||||
routeLabel,
|
||||
sectionLabel,
|
||||
contextLabel,
|
||||
target.routeLabel,
|
||||
target.sectionLabel,
|
||||
target.contextLabel,
|
||||
@@ -88,7 +146,7 @@ const sectionTargets = [
|
||||
{ key: 'collectors', label: '采集调度', terms: ['schedule', 'frequency'] },
|
||||
{ key: 'collection_history', label: '采集历史 / 快照', terms: ['history', 'snapshot'] },
|
||||
] },
|
||||
{ routePath: '/settings', routeLabel: '设置', icon: Settings, sections: [
|
||||
{ routePath: '/settings', routeLabel: '系统设置', icon: Settings, sections: [
|
||||
{ key: 'system', label: '系统显示', terms: ['system', 'display'] },
|
||||
{ key: 'notifications', label: '通知策略', terms: ['notification', 'email'] },
|
||||
{ key: 'security', label: '安全策略', terms: ['security', 'password'] },
|
||||
@@ -117,7 +175,7 @@ const fieldTargets = [
|
||||
{ routePath: '/ai', routeLabel: 'AI', sectionKey: 'prompts', sectionLabel: '提示词', labels: ['System Prompt', '任务提示词', '重置 Prompt'] },
|
||||
{ routePath: '/collection-management', routeLabel: '采集管理', sectionKey: 'collector_credentials', sectionLabel: '采集器', labels: ['凭证教程', '生成凭证教程', '采集器配置', '映射模板', '目标 Schema'] },
|
||||
{ routePath: '/earth-content', routeLabel: '智能星球内容', sectionKey: 'tv', sectionLabel: '电视直播', labels: ['默认频道', '自动回退', '直播源', '频道', '主页地址'] },
|
||||
{ routePath: '/settings', routeLabel: '设置', sectionKey: 'smtp', sectionLabel: 'SMTP 邮件', labels: ['主机', '端口', '用户名', '密码', '使用 TLS', '发件邮箱'] },
|
||||
{ routePath: '/settings', routeLabel: '系统设置', sectionKey: 'smtp', sectionLabel: 'SMTP 邮件', labels: ['主机', '端口', '用户名', '密码', '使用 TLS', '发件邮箱'] },
|
||||
]
|
||||
|
||||
const curatedDynamicLikeTargets = [
|
||||
@@ -153,9 +211,9 @@ export function buildStaticAdminTargets(isSuperAdmin: boolean): AdminSearchTarge
|
||||
.filter((route) => visiblePaths.has(route.path))
|
||||
.map((route) => makeTarget({
|
||||
routePath: route.path,
|
||||
routeLabel: route.label,
|
||||
label: route.label,
|
||||
contextLabel: '页面',
|
||||
routeLabel: i18n.t(route.labelKey),
|
||||
label: i18n.t(route.labelKey),
|
||||
contextLabel: i18n.t('admin.search.pageContext'),
|
||||
terms: route.keywords,
|
||||
icon: route.icon,
|
||||
}))
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
.admin-theme-root {
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
--an-page-padding: 16px;
|
||||
--an-section-gap: 16px;
|
||||
--an-panel-gap: 12px;
|
||||
@@ -117,10 +120,10 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin {
|
||||
min-height: 100vh;
|
||||
height: 100vh;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 236px minmax(0, 1fr);
|
||||
grid-template-columns: 264px minmax(0, 1fr);
|
||||
background: var(--an-bg);
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -128,7 +131,10 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
.admin__sider {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--an-surface);
|
||||
border-right: 1px solid var(--an-border);
|
||||
}
|
||||
@@ -145,19 +151,33 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
height: 58px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 10px;
|
||||
padding: 0 14px;
|
||||
border-bottom: 1px solid var(--an-border);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__brand-copy {
|
||||
display: grid;
|
||||
justify-items: start;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__brand-text {
|
||||
font-weight: 700;
|
||||
font-size: 16px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin__brand-subtitle {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin__brand-subtitle,
|
||||
@@ -171,24 +191,35 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin__nav-scroll {
|
||||
flex: 1;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.admin__nav {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 10px;
|
||||
display: grid;
|
||||
justify-items: stretch;
|
||||
gap: 6px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__nav-group {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
justify-items: stretch;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.admin__nav-group-button,
|
||||
.admin__nav-link {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--an-text);
|
||||
@@ -197,11 +228,28 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
padding: 0 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 10px;
|
||||
text-align: left;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.admin__nav-group-button svg,
|
||||
.admin__nav-link svg {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.admin__nav-group-button span,
|
||||
.admin__nav-link span {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-align: left;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin__nav-group-button:hover,
|
||||
.admin__nav-link:hover,
|
||||
.admin__nav-link.is-active {
|
||||
@@ -213,7 +261,11 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin__nav-children {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
justify-items: stretch;
|
||||
gap: 3px;
|
||||
padding-left: 22px;
|
||||
}
|
||||
@@ -229,6 +281,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
|
||||
.admin__nav-chevron {
|
||||
margin-left: auto;
|
||||
flex: 0 0 auto;
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
@@ -237,18 +290,26 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin__account {
|
||||
flex: 0 0 auto;
|
||||
border-top: 1px solid var(--an-border);
|
||||
padding: 12px;
|
||||
background: color-mix(in srgb, var(--an-bg) 42%, var(--an-surface));
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
gap: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__account-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
justify-content: flex-start;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__account-row--primary {
|
||||
min-height: 34px;
|
||||
}
|
||||
|
||||
.admin__account-row > div {
|
||||
@@ -257,15 +318,94 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.admin__account-profile {
|
||||
display: flex !important;
|
||||
grid-template-columns: none;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
margin-right: 6px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__account-row .admin__account-profile {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin__account-profile > div {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
justify-items: start;
|
||||
gap: 1px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__account-avatar {
|
||||
flex: 0 0 30px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 999px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--an-accent);
|
||||
color: #ffffff;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
box-shadow: 0 6px 16px color-mix(in srgb, var(--an-accent) 22%, transparent);
|
||||
}
|
||||
|
||||
.admin__account-row .admin__account-avatar {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.admin__account-row strong {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin__account-logout {
|
||||
.admin__account-profile span:not(.admin__account-avatar) {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.admin__account-actions {
|
||||
display: flex !important;
|
||||
grid-template-columns: none;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex: 0 0 auto;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.admin__account-logout,
|
||||
.admin__account-preferences {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.admin__account-preferences {
|
||||
color: var(--an-muted);
|
||||
}
|
||||
|
||||
.admin__account-preferences svg {
|
||||
transition: color 0.18s ease, transform 0.28s cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
|
||||
.admin__account-preferences.is-active {
|
||||
color: var(--an-accent);
|
||||
background: color-mix(in srgb, var(--an-accent) 10%, var(--an-surface));
|
||||
}
|
||||
|
||||
.admin__account-preferences.is-active svg {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.admin__account-logout {
|
||||
color: var(--an-danger);
|
||||
}
|
||||
|
||||
@@ -277,11 +417,48 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.admin__preferences-drawer {
|
||||
max-height: 0;
|
||||
overflow: hidden;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateY(-5px);
|
||||
transition:
|
||||
max-height 0.24s ease,
|
||||
opacity 0.18s ease,
|
||||
transform 0.24s ease,
|
||||
visibility 0s linear 0.24s;
|
||||
}
|
||||
|
||||
.admin__preferences-drawer.is-open {
|
||||
max-height: 146px;
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateY(0);
|
||||
transition:
|
||||
max-height 0.28s ease,
|
||||
opacity 0.18s ease,
|
||||
transform 0.28s ease,
|
||||
visibility 0s;
|
||||
}
|
||||
|
||||
.admin__preferences-panel {
|
||||
margin-top: 12px;
|
||||
padding: 12px 14px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--an-border) 78%, transparent);
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--an-bg) 62%, var(--an-surface));
|
||||
display: grid;
|
||||
justify-items: stretch;
|
||||
gap: 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.admin__theme-control--sider {
|
||||
--segmented-control-radius: 8px;
|
||||
--segmented-control-slider-radius: 6px;
|
||||
--segmented-control-button-gap: 0;
|
||||
--segmented-control-icon-size: calc(17px * var(--segmented-control-scale, 1));
|
||||
--segmented-control-icon-size: 13px;
|
||||
}
|
||||
|
||||
.admin__theme-control--sider .segmented-control__button {
|
||||
@@ -309,6 +486,22 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.admin__language-control--sider {
|
||||
width: 100%;
|
||||
--segmented-control-radius: 8px;
|
||||
--segmented-control-slider-radius: 6px;
|
||||
--segmented-control-button-gap: 0;
|
||||
--segmented-control-font-size: calc(10px * var(--segmented-control-scale, 1));
|
||||
--segmented-control-font-weight: 800;
|
||||
}
|
||||
|
||||
.admin__language-control--sider .segmented-control__button {
|
||||
font-size: calc(10px * var(--segmented-control-scale, 1));
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.admin__logout {
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -597,9 +790,11 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
|
||||
.admin__content {
|
||||
min-width: 0;
|
||||
height: 100vh;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-rows: 48px minmax(0, 1fr);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.admin__topbar {
|
||||
@@ -652,6 +847,25 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
color: var(--an-muted);
|
||||
}
|
||||
|
||||
.admin__language-control {
|
||||
width: 112px;
|
||||
--segmented-control-radius: 8px;
|
||||
--segmented-control-slider-radius: 6px;
|
||||
--segmented-control-button-gap: 0;
|
||||
}
|
||||
|
||||
.admin__language-control .segmented-control__button {
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
.admin__language-control .segmented-control__icon {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin__language-control.admin__language-control--sider {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.admin__search-results {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
@@ -754,6 +968,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
.admin__content-inner {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
padding: var(--an-page-padding);
|
||||
}
|
||||
@@ -1482,6 +1697,111 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.an-brand-asset-input {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
height: 34px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--an-border);
|
||||
border-radius: 6px;
|
||||
background: var(--an-surface);
|
||||
color: var(--an-text);
|
||||
transition: border-color 0.16s ease, box-shadow 0.16s ease, background-color 0.16s ease;
|
||||
}
|
||||
|
||||
.an-brand-asset-input:focus-within {
|
||||
border-color: color-mix(in srgb, var(--an-accent) 24%, var(--an-border-strong));
|
||||
}
|
||||
|
||||
.an-brand-asset-input.is-dragging {
|
||||
border-color: var(--an-border-strong);
|
||||
background: color-mix(in srgb, var(--an-soft) 46%, var(--an-surface));
|
||||
box-shadow: 0 2px 5px rgba(15, 23, 42, 0.1), 0 8px 18px rgba(15, 23, 42, 0.06);
|
||||
}
|
||||
|
||||
.an-brand-asset-input__control {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
padding: 0 10px;
|
||||
font: inherit;
|
||||
line-height: 32px;
|
||||
}
|
||||
|
||||
.an-brand-asset-input__control:disabled {
|
||||
color: var(--an-muted);
|
||||
}
|
||||
|
||||
.an-brand-asset-input__file {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.an-brand-asset-input__upload {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
min-width: 72px;
|
||||
height: var(--tui-control-height, 28px);
|
||||
margin-right: 3px;
|
||||
padding-inline: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.an-brand-asset-input__drop-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 0 12px;
|
||||
border: 1px dashed var(--an-border-strong);
|
||||
border-radius: 5px;
|
||||
background: color-mix(in srgb, var(--an-soft) 82%, var(--an-surface));
|
||||
color: var(--an-text);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.an-brand-asset-input__drop-overlay > span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.an-brand-asset-input__drop-overlay > strong {
|
||||
min-width: max-content;
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--an-border);
|
||||
border-radius: 6px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: var(--an-surface);
|
||||
color: var(--an-text);
|
||||
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.16);
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.admin-theme-root[data-theme='dark'] .an-brand-asset-input__drop-overlay > strong {
|
||||
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.34);
|
||||
}
|
||||
|
||||
.an-mapping-form {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
@@ -1633,7 +1953,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
color: var(--an-text);
|
||||
padding: 8px 10px;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 104px;
|
||||
grid-template-columns: minmax(0, 1fr) max-content;
|
||||
align-items: start;
|
||||
gap: 10px;
|
||||
text-align: left;
|
||||
@@ -1683,19 +2003,22 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.an-hierarchy-group__meta {
|
||||
width: 104px;
|
||||
max-width: 104px;
|
||||
width: max-content;
|
||||
max-width: none;
|
||||
min-width: max-content;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 5px;
|
||||
overflow: hidden;
|
||||
justify-self: end;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.an-hierarchy-group__meta .an-status-pill {
|
||||
flex: 0 0 74px;
|
||||
width: 74px;
|
||||
max-width: 74px;
|
||||
flex: 0 0 auto;
|
||||
width: auto;
|
||||
min-width: max-content;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.an-hierarchy-group__meta em {
|
||||
@@ -2038,7 +2361,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
font-size: calc(0.74rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.3;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
letter-spacing: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
@@ -2048,12 +2371,37 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.6rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.3;
|
||||
letter-spacing: 0.08em;
|
||||
letter-spacing: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.an-earth-brand-preview .hud-panel-brand .earth-brand--en {
|
||||
--brand-copy-width: 172px;
|
||||
}
|
||||
|
||||
.an-earth-brand-preview .hud-panel-brand .earth-brand--en .earth-brand__subtitle,
|
||||
.an-earth-brand-preview .hud-panel-brand .earth-brand--en .earth-brand__description {
|
||||
font-family: "Roboto Condensed", "Arial Narrow", "Trebuchet MS", "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
white-space: normal;
|
||||
word-break: normal;
|
||||
overflow-wrap: normal;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.an-earth-brand-preview .hud-panel-brand .earth-brand--en .earth-brand__subtitle {
|
||||
font-size: calc(0.58rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.an-earth-brand-preview .hud-panel-brand .earth-brand--en .earth-brand__description {
|
||||
font-size: calc(0.5rem * var(--hud-scale) * var(--brand-scale));
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.an-tv-earth-preview {
|
||||
--hud-scale: 0.82;
|
||||
--hud-gap-xs: calc(6px * var(--hud-scale));
|
||||
@@ -2183,7 +2531,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
font-size: calc(0.62rem * var(--hud-scale));
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
letter-spacing: 0.04em;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.an-tv-earth-preview .tv-panel-tag--status {
|
||||
@@ -2221,7 +2569,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
|
||||
.an-tv-earth-preview .tv-panel-catalog {
|
||||
font-size: calc(0.66rem * var(--hud-scale));
|
||||
letter-spacing: 0.04em;
|
||||
letter-spacing: 0;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
@@ -2371,6 +2719,24 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.an-connection-test-input {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.an-connection-test-input__control {
|
||||
padding-right: 38px;
|
||||
}
|
||||
|
||||
.an-connection-test-input > .tui-button {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 4px;
|
||||
width: 28px;
|
||||
height: 24px;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.an-news-feed-list {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
@@ -3832,12 +4198,16 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.an-segmented button {
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--an-muted);
|
||||
border-radius: 4px;
|
||||
padding: 0 10px;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.an-segmented button.is-active {
|
||||
@@ -4066,7 +4436,7 @@ body:has(.admin-theme-root[data-theme='dark']) .an-toast {
|
||||
}
|
||||
|
||||
.admin__content {
|
||||
height: 100vh;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.admin__topbar {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import { memo, useEffect, useId, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { PointerEvent as ReactPointerEvent, ReactNode, WheelEvent as ReactWheelEvent } from 'react'
|
||||
|
||||
import Scrollbar from '../Scrollbar/Scrollbar'
|
||||
@@ -167,6 +168,7 @@ function isMermaidTextTarget(target: EventTarget | null): boolean {
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, language }: { code: string; language?: string }) {
|
||||
const { t } = useTranslation()
|
||||
const [copied, setCopied] = useState(false)
|
||||
const label = language?.trim() || 'text'
|
||||
const codeClassName = language
|
||||
@@ -187,8 +189,8 @@ function MarkdownCodeBlock({ code, language }: { code: string; language?: string
|
||||
type="button"
|
||||
className="markdown-renderer__code-copy"
|
||||
onClick={handleCopy}
|
||||
aria-label={copied ? '已复制代码' : '复制代码'}
|
||||
title={copied ? '已复制' : '复制代码'}
|
||||
aria-label={copied ? t('markdown.copiedCode') : t('markdown.copyCode')}
|
||||
title={copied ? t('markdown.copied') : t('markdown.copyCode')}
|
||||
>
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
</button>
|
||||
@@ -201,6 +203,7 @@ function MarkdownCodeBlock({ code, language }: { code: string; language?: string
|
||||
}
|
||||
|
||||
function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
const { t } = useTranslation()
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [svg, setSvg] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
@@ -266,7 +269,7 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
} catch (renderError) {
|
||||
if (!cancelled) {
|
||||
setSvg('')
|
||||
setError(renderError instanceof Error ? renderError.message : 'Mermaid 渲染失败')
|
||||
setError(renderError instanceof Error ? renderError.message : t('markdown.mermaidRenderFailed'))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,7 +279,7 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [blockId, code, themeMode])
|
||||
}, [blockId, code, t, themeMode])
|
||||
|
||||
const handleCopy = async () => {
|
||||
await copyToClipboard(code)
|
||||
@@ -339,8 +342,8 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
type="button"
|
||||
className="markdown-renderer__code-copy"
|
||||
onClick={handleCopy}
|
||||
aria-label={copied ? '已复制图表源码' : '复制图表源码'}
|
||||
title={copied ? '已复制' : '复制图表源码'}
|
||||
aria-label={copied ? t('markdown.copiedChartSource') : t('markdown.copyChartSource')}
|
||||
title={copied ? t('markdown.copied') : t('markdown.copyChartSource')}
|
||||
>
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
</button>
|
||||
@@ -361,8 +364,8 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
openExpanded()
|
||||
}
|
||||
}}
|
||||
aria-label="放大查看 Mermaid 图表"
|
||||
title="点击放大查看"
|
||||
aria-label={t('markdown.expandMermaid')}
|
||||
title={t('markdown.clickToExpand')}
|
||||
>
|
||||
<span className="markdown-renderer__mermaid-canvas-inner" dangerouslySetInnerHTML={{ __html: svg }} />
|
||||
</div>
|
||||
@@ -381,15 +384,15 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
className="markdown-renderer__mermaid-viewer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Mermaid 图表查看器"
|
||||
aria-label={t('markdown.mermaidViewer')}
|
||||
onClick={closeExpanded}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="markdown-renderer__mermaid-viewer-close"
|
||||
onClick={closeExpanded}
|
||||
aria-label="关闭 Mermaid 图表查看器"
|
||||
title="关闭"
|
||||
aria-label={t('markdown.closeMermaid')}
|
||||
title={t('common.close')}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
@@ -411,7 +414,7 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
|
||||
/>
|
||||
</div>
|
||||
<div className="markdown-renderer__mermaid-viewer-hint">
|
||||
拖拽移动 · 滚轮缩放 · 点击空白关闭
|
||||
{t('markdown.viewerHint')}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
font: inherit;
|
||||
font-size: var(--segmented-control-font-size, calc(10px * var(--segmented-control-scale, 1)));
|
||||
font-weight: var(--segmented-control-font-weight, 800);
|
||||
letter-spacing: var(--segmented-control-letter-spacing, 0.04em);
|
||||
letter-spacing: var(--segmented-control-letter-spacing, 0);
|
||||
cursor: pointer;
|
||||
transition: color 0.18s ease, transform 0.18s ease;
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ const DEFAULT_WS_URL = (() => {
|
||||
return `${protocol}//${window.location.host}/ws`
|
||||
})()
|
||||
|
||||
const WS_URL = (import.meta as any).env?.VITE_WS_URL || DEFAULT_WS_URL
|
||||
const WS_URL = import.meta.env.VITE_WS_URL || DEFAULT_WS_URL
|
||||
const WS_CONNECT_TIMEOUT_MS = 4500
|
||||
|
||||
function buildWebSocketCandidates(): string[] {
|
||||
if ((import.meta as any).env?.VITE_WS_URL) {
|
||||
if (import.meta.env.VITE_WS_URL) {
|
||||
return [WS_URL]
|
||||
}
|
||||
|
||||
|
||||
168
frontend/src/i18n/LegacyI18nBridge.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { legacyUiTextEnUS } from './legacy-ui'
|
||||
import { normalizeLocale } from './locale'
|
||||
|
||||
const attributeNames = ['aria-label', 'placeholder', 'title']
|
||||
const selector = '.admin-theme-root, .auth-shell'
|
||||
const reverseLegacyUiText = Object.fromEntries(
|
||||
Object.entries(legacyUiTextEnUS).map(([source, target]) => [target, source]),
|
||||
)
|
||||
|
||||
type LegacyTextPattern = {
|
||||
match: RegExp
|
||||
replace: (match: RegExpMatchArray) => string
|
||||
}
|
||||
|
||||
const legacyTextPatternsEnUS: LegacyTextPattern[] = [
|
||||
{ match: /^结果\s+(.+)\s+条$/, replace: (match) => `Results ${match[1]}` },
|
||||
{ match: /^筛选\s+(.+)\s+项$/, replace: (match) => `${match[1]} filters` },
|
||||
{ match: /^共\s+(.+)\s+条结果$/, replace: (match) => `${match[1]} results` },
|
||||
{ match: /^(.+)\s+条新闻。$/, replace: (match) => `${match[1]} news items.` },
|
||||
{ match: /^(.+)\s+个历史快照,选择后查看该版本详情。$/, replace: (match) => `${match[1]} historical snapshots. Select one to view that version.` },
|
||||
{ match: /^(.+)\s+字段$/, replace: (match) => `${match[1]} fields` },
|
||||
{ match: /^(.+)\s+个源 \/ (.+)\s+个类型$/, replace: (match) => `${match[1]} sources / ${match[2]} categories` },
|
||||
{ match: /^(.+)\s+个来源$/, replace: (match) => `${match[1]} sources` },
|
||||
{ match: /^(.+)\s+个聚合项$/, replace: (match) => `${match[1]} aggregations` },
|
||||
{ match: /^(.+)\s+条$/, replace: (match) => `${match[1]} items` },
|
||||
{ match: /^(.+)\s+行$/, replace: (match) => `${match[1]} lines` },
|
||||
{ match: /^(.+)\s+次$/, replace: (match) => `${match[1]} times` },
|
||||
{ match: /^最后更新:\s*(.+)$/, replace: (match) => `Last updated: ${match[1]}` },
|
||||
{ match: /^任务已创建:\s*(.+)$/, replace: (match) => `Task created: ${match[1]}` },
|
||||
{ match: /^执行命令\s+(.+)$/, replace: (match) => `Command ${match[1]}` },
|
||||
{ match: /^任务 ID\s+(.+)$/, replace: (match) => `Task ID ${match[1]}` },
|
||||
{ match: /^触发已选\s+(.+)$/, replace: (match) => `Trigger selected ${match[1]}` },
|
||||
{ match: /^新闻直播源\s+(.+)$/, replace: (match) => `News stream source ${match[1]}` },
|
||||
{ match: /^新增新闻源\s+(.+)$/, replace: (match) => `New news source ${match[1]}` },
|
||||
{ match: /^最终指标:(.+)$/, replace: (match) => `Final metric: ${match[1]}` },
|
||||
{ match: /^指纹\s+(.+)$/, replace: (match) => `Fingerprint ${match[1]}` },
|
||||
{ match: /^首次\s+(.+)\s+·\s+最近\s+(.+)$/, replace: (match) => `First ${match[1]} · Latest ${match[2]}` },
|
||||
{ match: /^已导出\s+(.+)$/, replace: (match) => `Exported ${match[1]}` },
|
||||
{ match: /^(.+)\s+采集失败$/, replace: (match) => `${match[1]} collection failed` },
|
||||
{ match: /^(.+)\s+采集已取消$/, replace: (match) => `${match[1]} collection cancelled` },
|
||||
{ match: /^选择(.+)$/, replace: (match) => `Select ${match[1]}` },
|
||||
]
|
||||
|
||||
const legacyTextPatternsZhCN: LegacyTextPattern[] = [
|
||||
{ match: /^Results\s+(.+)$/, replace: (match) => `结果 ${match[1]} 条` },
|
||||
{ match: /^(.+)\s+filters$/, replace: (match) => `筛选 ${match[1]} 项` },
|
||||
{ match: /^(.+)\s+results$/, replace: (match) => `共 ${match[1]} 条结果` },
|
||||
{ match: /^(.+)\s+news items\.$/, replace: (match) => `${match[1]} 条新闻。` },
|
||||
{ match: /^(.+)\s+historical snapshots\. Select one to view that version\.$/, replace: (match) => `${match[1]} 个历史快照,选择后查看该版本详情。` },
|
||||
{ match: /^(.+)\s+fields$/, replace: (match) => `${match[1]} 字段` },
|
||||
{ match: /^(.+)\s+sources \/ (.+)\s+categories$/, replace: (match) => `${match[1]} 个源 / ${match[2]} 个类型` },
|
||||
{ match: /^(.+)\s+sources$/, replace: (match) => `${match[1]} 个来源` },
|
||||
{ match: /^(.+)\s+aggregations$/, replace: (match) => `${match[1]} 个聚合项` },
|
||||
{ match: /^(.+)\s+items$/, replace: (match) => `${match[1]} 条` },
|
||||
{ match: /^(.+)\s+lines$/, replace: (match) => `${match[1]} 行` },
|
||||
{ match: /^(.+)\s+times$/, replace: (match) => `${match[1]} 次` },
|
||||
{ match: /^Last updated:\s*(.+)$/, replace: (match) => `最后更新: ${match[1]}` },
|
||||
{ match: /^Task created:\s*(.+)$/, replace: (match) => `任务已创建: ${match[1]}` },
|
||||
{ match: /^Command\s+(.+)$/, replace: (match) => `执行命令 ${match[1]}` },
|
||||
{ match: /^Task ID\s+(.+)$/, replace: (match) => `任务 ID ${match[1]}` },
|
||||
{ match: /^Trigger selected\s+(.+)$/, replace: (match) => `触发已选 ${match[1]}` },
|
||||
{ match: /^News stream source\s+(.+)$/, replace: (match) => `新闻直播源 ${match[1]}` },
|
||||
{ match: /^New news source\s+(.+)$/, replace: (match) => `新增新闻源 ${match[1]}` },
|
||||
{ match: /^Final metric:\s*(.+)$/, replace: (match) => `最终指标:${match[1]}` },
|
||||
{ match: /^Fingerprint\s+(.+)$/, replace: (match) => `指纹 ${match[1]}` },
|
||||
{ match: /^First\s+(.+)\s+·\s+Latest\s+(.+)$/, replace: (match) => `首次 ${match[1]} · 最近 ${match[2]}` },
|
||||
{ match: /^Exported\s+(.+)$/, replace: (match) => `已导出 ${match[1]}` },
|
||||
{ match: /^(.+)\s+collection failed$/, replace: (match) => `${match[1]} 采集失败` },
|
||||
{ match: /^(.+)\s+collection cancelled$/, replace: (match) => `${match[1]} 采集已取消` },
|
||||
{ match: /^Select\s+(.+)$/, replace: (match) => `选择${match[1]}` },
|
||||
]
|
||||
|
||||
function preserveOuterWhitespace(source: string, replacement: string) {
|
||||
const leading = source.match(/^\s*/)?.[0] || ''
|
||||
const trailing = source.match(/\s*$/)?.[0] || ''
|
||||
return `${leading}${replacement}${trailing}`
|
||||
}
|
||||
|
||||
function translatePatternText(value: string, locale: string) {
|
||||
const text = value.trim()
|
||||
if (!text || text.length > 160) return value
|
||||
const patterns = normalizeLocale(locale) === 'en-US' ? legacyTextPatternsEnUS : legacyTextPatternsZhCN
|
||||
for (const pattern of patterns) {
|
||||
const matched = text.match(pattern.match)
|
||||
if (matched) return preserveOuterWhitespace(value, pattern.replace(matched))
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function translateText(value: string, locale: string) {
|
||||
const text = value.trim()
|
||||
if (!text) return value
|
||||
const dictionary = normalizeLocale(locale) === 'en-US' ? legacyUiTextEnUS : reverseLegacyUiText
|
||||
const replacement = dictionary[text]
|
||||
if (replacement) return preserveOuterWhitespace(value, replacement)
|
||||
const patternTranslated = translatePatternText(value, locale)
|
||||
if (patternTranslated !== value) return patternTranslated
|
||||
if (text.length > 240) return value
|
||||
const entries = Object.entries(dictionary)
|
||||
.filter(([source]) => source && text.includes(source))
|
||||
.sort(([left], [right]) => right.length - left.length)
|
||||
if (!entries.length) return value
|
||||
return entries.reduce((next, [source, target]) => next.split(source).join(target), value)
|
||||
}
|
||||
|
||||
function translateElementAttributes(element: Element, locale: string) {
|
||||
attributeNames.forEach((attributeName) => {
|
||||
const value = element.getAttribute(attributeName)
|
||||
if (!value) return
|
||||
const translated = translateText(value, locale)
|
||||
if (translated !== value) element.setAttribute(attributeName, translated)
|
||||
})
|
||||
}
|
||||
|
||||
function translateNodeText(root: Element, locale: string) {
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
|
||||
let node = walker.nextNode()
|
||||
while (node) {
|
||||
const value = node.textContent || ''
|
||||
const translated = translateText(value, locale)
|
||||
if (translated !== value) node.textContent = translated
|
||||
node = walker.nextNode()
|
||||
}
|
||||
}
|
||||
|
||||
function translateRoot(root: Element, locale: string) {
|
||||
translateElementAttributes(root, locale)
|
||||
root.querySelectorAll('*').forEach((element) => translateElementAttributes(element, locale))
|
||||
translateNodeText(root, locale)
|
||||
}
|
||||
|
||||
export default function LegacyI18nBridge() {
|
||||
const { i18n } = useTranslation()
|
||||
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
|
||||
|
||||
useEffect(() => {
|
||||
let frameId = 0
|
||||
const translate = () => {
|
||||
document.querySelectorAll(selector).forEach((root) => translateRoot(root, locale))
|
||||
}
|
||||
const scheduleTranslate = () => {
|
||||
window.cancelAnimationFrame(frameId)
|
||||
frameId = window.requestAnimationFrame(translate)
|
||||
}
|
||||
|
||||
scheduleTranslate()
|
||||
const observer = new MutationObserver(scheduleTranslate)
|
||||
if (document.body) {
|
||||
observer.observe(document.body, {
|
||||
attributes: true,
|
||||
attributeFilter: attributeNames,
|
||||
characterData: true,
|
||||
childList: true,
|
||||
subtree: true,
|
||||
})
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [locale])
|
||||
|
||||
return null
|
||||
}
|
||||
93
frontend/src/i18n/api-errors.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import i18n from './index'
|
||||
import { legacyUiTextEnUS } from './legacy-ui'
|
||||
import { normalizeLocale } from './locale'
|
||||
|
||||
type ApiErrorPayload = {
|
||||
detail?: unknown
|
||||
error?: unknown
|
||||
message?: unknown
|
||||
}
|
||||
|
||||
type ApiErrorLike = {
|
||||
message?: unknown
|
||||
response?: {
|
||||
data?: ApiErrorPayload
|
||||
}
|
||||
}
|
||||
|
||||
const cjkPattern = /[\u3400-\u9fff]/
|
||||
const genericEnglishFallback = 'Operation failed'
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value))
|
||||
}
|
||||
|
||||
function currentLocale() {
|
||||
return normalizeLocale(i18n.resolvedLanguage || i18n.language)
|
||||
}
|
||||
|
||||
export function hasCjkText(value: string) {
|
||||
return cjkPattern.test(value)
|
||||
}
|
||||
|
||||
function englishFallbackFor(fallback: string) {
|
||||
const normalized = fallback.trim()
|
||||
if (!normalized) return genericEnglishFallback
|
||||
if (!hasCjkText(normalized)) return normalized
|
||||
return legacyUiTextEnUS[normalized] || genericEnglishFallback
|
||||
}
|
||||
|
||||
function stringFromApiValue(value: unknown): string {
|
||||
if (value === null || value === undefined || value === '') return ''
|
||||
if (typeof value === 'string') return value
|
||||
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
|
||||
if (Array.isArray(value)) {
|
||||
const firstMessage = value
|
||||
.map((item) => stringFromApiValue(item))
|
||||
.find(Boolean)
|
||||
return firstMessage || ''
|
||||
}
|
||||
if (isRecord(value)) {
|
||||
const directMessage = stringFromApiValue(value.message || value.detail || value.error)
|
||||
if (directMessage) return directMessage
|
||||
const code = stringFromApiValue(value.code)
|
||||
if (code) return code
|
||||
try {
|
||||
return JSON.stringify(value)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export function localizeApiMessage(message: string, fallback = genericEnglishFallback) {
|
||||
const normalized = message.trim()
|
||||
if (currentLocale() !== 'en-US') return normalized || fallback
|
||||
const englishFallback = englishFallbackFor(fallback)
|
||||
if (!normalized) return englishFallback
|
||||
const exactLegacy = legacyUiTextEnUS[normalized]
|
||||
if (exactLegacy) return exactLegacy
|
||||
if (hasCjkText(normalized)) return englishFallback
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function describeApiValue(value: unknown, fallback = genericEnglishFallback) {
|
||||
return localizeApiMessage(stringFromApiValue(value), fallback)
|
||||
}
|
||||
|
||||
export function describeApiError(error: unknown, fallback = genericEnglishFallback) {
|
||||
if (isRecord(error)) {
|
||||
const apiError = error as ApiErrorLike
|
||||
const payload = apiError.response?.data
|
||||
if (payload) {
|
||||
const responseValue = payload.detail ?? payload.message ?? payload.error
|
||||
const responseMessage = describeApiValue(responseValue, fallback)
|
||||
if (responseMessage) return responseMessage
|
||||
}
|
||||
const errorMessage = stringFromApiValue(apiError.message)
|
||||
if (errorMessage) return localizeApiMessage(errorMessage, fallback)
|
||||
}
|
||||
if (error instanceof Error) return localizeApiMessage(error.message, fallback)
|
||||
return localizeApiMessage('', fallback)
|
||||
}
|
||||
27
frontend/src/i18n/index.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import i18n from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
|
||||
import { readStoredLocale, syncDocumentLocale } from './locale'
|
||||
import { resources } from './resources'
|
||||
|
||||
const initialLocale = readStoredLocale()
|
||||
|
||||
syncDocumentLocale(initialLocale)
|
||||
|
||||
void i18n
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
fallbackLng: 'zh-CN',
|
||||
interpolation: {
|
||||
escapeValue: false,
|
||||
},
|
||||
lng: initialLocale,
|
||||
resources,
|
||||
returnEmptyString: false,
|
||||
})
|
||||
|
||||
i18n.on('languageChanged', (locale) => {
|
||||
syncDocumentLocale(locale === 'en-US' ? 'en-US' : 'zh-CN')
|
||||
})
|
||||
|
||||
export default i18n
|
||||
851
frontend/src/i18n/legacy-ui.ts
Normal file
@@ -0,0 +1,851 @@
|
||||
export const legacyUiTextEnUS: Record<string, string> = {
|
||||
'3D 模型': '3D models',
|
||||
'AI 生成教程': 'AI-generated guide',
|
||||
'AI 分区': 'AI sections',
|
||||
'AI 配置详情': 'AI configuration details',
|
||||
'AI 集成': 'AI integrations',
|
||||
'AI 简报': 'AI brief',
|
||||
'BGP 事故': 'BGP incident',
|
||||
'BGP 事件与简报': 'BGP events and briefs',
|
||||
'BGP 告警列表': 'BGP alert list',
|
||||
'BGP 告警详情': 'BGP alert details',
|
||||
'BGP 异常': 'BGP anomaly',
|
||||
'BGP 概览': 'BGP overview',
|
||||
'BGP 简报': 'BGP brief',
|
||||
'BGP 详情': 'BGP details',
|
||||
'BGP 观测': 'BGP Observatory',
|
||||
'BGP 告警': 'BGP alert',
|
||||
'BGP观测': 'BGP Observatory',
|
||||
'Feed 信息页': 'Feed info page',
|
||||
'Feed 地址': 'Feed URL',
|
||||
'Feed 标签': 'Feed tags',
|
||||
'Feed 类型': 'Feed type',
|
||||
'Feed 名称': 'Feed name',
|
||||
'Feed ID': 'Feed ID',
|
||||
'Gatekeeper 权限组': 'Gatekeeper groups',
|
||||
'RSS 来源': 'RSS source',
|
||||
'RSS 来源只读,新闻由抓取与增强链路维护。': 'RSS sources are read-only. News is maintained by the collection and enrichment pipeline.',
|
||||
'RSS 订阅中心或 Feed 聚合页,只用于人工查看,不参与抓取。': 'RSS directory or feed aggregation page for manual review only. It is not fetched.',
|
||||
'SMTP 邮件': 'SMTP email',
|
||||
'System Prompt': 'System prompt',
|
||||
'Time Capsule': 'Time Capsule',
|
||||
'Web Search 预设': 'Web Search presets',
|
||||
'不可用': 'Unavailable',
|
||||
'事故': 'Incident',
|
||||
'交互正常': 'Interactive',
|
||||
'个来源': 'sources',
|
||||
'个聚合项': 'aggregations',
|
||||
'任务提示词': 'Task prompt',
|
||||
'仪表盘': 'Dashboard',
|
||||
'任务': 'Task',
|
||||
'任务 ID': 'Task ID',
|
||||
'任务已取消': 'Task cancelled',
|
||||
'任务状态': 'Task status',
|
||||
'今日任务': 'Tasks today',
|
||||
'供应商': 'Provider',
|
||||
'供应商状态': 'Provider status',
|
||||
'供应商配置': 'Provider configuration',
|
||||
'事件': 'Event',
|
||||
'保存': 'Save',
|
||||
'保存并重试': 'Save and retry',
|
||||
'保存后会进入清洗、翻译、分类和定位队列。': 'After saving, the item enters the cleaning, translation, classification, and geocoding queue.',
|
||||
'保存后才会固化到新闻源配置。': 'Changes are persisted to the news source configuration only after saving.',
|
||||
'保存新闻': 'Save news item',
|
||||
'修改邮箱': 'Change email',
|
||||
'停止': 'Stop',
|
||||
'停止采集': 'Stop collection',
|
||||
'停止生成': 'Stop generation',
|
||||
'停用': 'Disabled',
|
||||
'关闭': 'Close',
|
||||
'关于': 'About',
|
||||
'关于配置': 'About configuration',
|
||||
'内置源': 'Built-in sources',
|
||||
'全部区域': 'All regions',
|
||||
'全部国家/地区': 'All countries / regions',
|
||||
'全部层级': 'All levels',
|
||||
'全部级别': 'All levels',
|
||||
'全部产品域': 'All product domains',
|
||||
'全部执行状态': 'All execution statuses',
|
||||
'全部数据源': 'All datasources',
|
||||
'全部数据状态': 'All data statuses',
|
||||
'全部源属性': 'All source attributes',
|
||||
'全部状态': 'All statuses',
|
||||
'全部类型': 'All types',
|
||||
'其他': 'Other',
|
||||
'刷新': 'Refresh',
|
||||
'刷新当前 Provider 的模型配置': 'Refresh current provider model configuration',
|
||||
'刷新间隔(秒)': 'Refresh interval (seconds)',
|
||||
'刷新模型': 'Refresh models',
|
||||
'刷新模型列表': 'Refresh model list',
|
||||
'刷新线程': 'Refresh thread',
|
||||
'分类': 'Category',
|
||||
'副标题': 'Subtitle',
|
||||
'标题图地址': 'Title image URL',
|
||||
'标题图替代文本': 'Title image alt text',
|
||||
'标题文字': 'Title text',
|
||||
'删除 Feed 子项': 'Delete feed entry',
|
||||
'删除': 'Delete',
|
||||
'删除失败': 'Delete failed',
|
||||
'删除完成': 'Deletion complete',
|
||||
'删除成功': 'Deleted',
|
||||
'删除已取消': 'Deletion cancelled',
|
||||
'删除新闻': 'Delete news item',
|
||||
'删除新闻源': 'Delete news source',
|
||||
'删除中': 'Deleting',
|
||||
'删除直播源': 'Delete stream source',
|
||||
'删除品牌配置': 'Delete brand configuration',
|
||||
'前往登录': 'Go to login',
|
||||
'加载中': 'Loading',
|
||||
'加载日志内容失败': 'Failed to load log content',
|
||||
'加载日志源失败': 'Failed to load log sources',
|
||||
'加载重复日志详情失败': 'Failed to load duplicate log details',
|
||||
'加载重复日志统计失败': 'Failed to load duplicate log stats',
|
||||
'启动采集': 'Start collection',
|
||||
'启动实时源': 'Start realtime source',
|
||||
'启动边界构建': 'Start boundary build',
|
||||
'启用': 'Enabled',
|
||||
'启用 WebSearch': 'Enable WebSearch',
|
||||
'启用 OCR': 'Enable OCR',
|
||||
'启用邮件通知': 'Enable email notifications',
|
||||
'启用抓取': 'Enable fetching',
|
||||
'启用映射': 'Enable mapping',
|
||||
'启用筛选': 'Active filters',
|
||||
'告警': 'Alert',
|
||||
'告警记录': 'Alert records',
|
||||
'告警统计': 'Alert stats',
|
||||
'名称': 'Name',
|
||||
'认证方式': 'Auth method',
|
||||
'后台账号': 'Console account',
|
||||
'回到首页': 'Back to overview',
|
||||
'国界精度': 'Boundary accuracy',
|
||||
'国家': 'Country',
|
||||
'地址': 'Address',
|
||||
'基础字段': 'Basic fields',
|
||||
'基础信息': 'Basic information',
|
||||
'城市': 'City',
|
||||
'字段': 'Fields',
|
||||
'安全策略': 'Security policy',
|
||||
'完成': 'Complete',
|
||||
'密码': 'Password',
|
||||
'导航': 'Navigation',
|
||||
'已加载分区': 'Loaded section',
|
||||
'已加载分区汇总': 'Loaded section total',
|
||||
'工具调用': 'Tool calls',
|
||||
'已保存': 'Saved',
|
||||
'已保存密钥不回传明文,输入新值可替换': 'Saved secrets are not returned; enter a new value to replace it',
|
||||
'已取消': 'Cancelled',
|
||||
'已处理': 'Resolved',
|
||||
'已提交': 'Submitted',
|
||||
'已读取': 'Loaded',
|
||||
'已启用': 'Enabled',
|
||||
'已定位': 'Located',
|
||||
'已配置': 'Configured',
|
||||
'已停止': 'Stopped',
|
||||
'已停用': 'Disabled',
|
||||
'已就绪': 'Ready',
|
||||
'已跳过': 'Skipped',
|
||||
'有效': 'Valid',
|
||||
'已有新闻': 'Existing news',
|
||||
'已有任务运行': 'Task already running',
|
||||
'已有账号,去登录': 'Already have an account? Log in',
|
||||
'开始日期': 'Start date',
|
||||
'底图资源': 'Basemap assets',
|
||||
'开启后访问智能星球会直接显示 OOBE 引导,不再要求首次采集条件,也会忽略本机“先浏览”临时跳过。': 'When enabled, Intelligent Planet opens directly into the OOBE guide, skips first-collection requirements, and ignores local temporary browse-first skips.',
|
||||
'态势告警': 'Situational alerts',
|
||||
'态势告警列表': 'Situational alert list',
|
||||
'态势详情': 'Situational details',
|
||||
'态势统计': 'Situational stats',
|
||||
'快速访问地球可视化页面': 'Quickly open the Earth visualization page',
|
||||
'恢复当前表单': 'Restore current form',
|
||||
'恢复默认关于信息': 'Restore default about information',
|
||||
'恢复默认配置': 'Restore defaults',
|
||||
'恢复超时,请手动检查服务状态。': 'Recovery timed out. Please check service status manually.',
|
||||
'成功': 'Success',
|
||||
'成功率': 'Success rate',
|
||||
'手动新闻组': 'Manual news group',
|
||||
'手动新闻': 'Manual news',
|
||||
'打开智能星球内容': 'Open Intelligent Planet content',
|
||||
'打开智能星球': 'Open Intelligent Planet',
|
||||
'处理告警': 'Resolve alert',
|
||||
'播放与扩展': 'Playback and extensions',
|
||||
'接入在线': 'Endpoints online',
|
||||
'接口在线': 'Endpoints online',
|
||||
'接口失败': 'Endpoint failed',
|
||||
'接口请求失败': 'Endpoint request failed',
|
||||
'接口路径': 'Endpoint path',
|
||||
'提示': 'Info',
|
||||
'操作失败': 'Operation failed',
|
||||
'控制台不混入其他配置或假数据。': 'The console does not mix in unrelated configuration or mock data.',
|
||||
'控制台发生错误,请刷新页面重试。': 'The console encountered an error. Please refresh and try again.',
|
||||
'控制台渲染错误': 'Console render error',
|
||||
'拖动调整数据概览宽度': 'Drag to resize data overview',
|
||||
'提交': 'Submit',
|
||||
'提交失败': 'Submission failed',
|
||||
'提交重启任务失败': 'Failed to submit restart task',
|
||||
'提示词': 'Prompts',
|
||||
'搜索日志正文': 'Search log text',
|
||||
'搜索名称、描述、元数据等': 'Search name, description, metadata, and more',
|
||||
'搜索供应商': 'Search provider',
|
||||
'搜索': 'Search',
|
||||
'搜索深度': 'Search depth',
|
||||
'搜索用户、邮箱、角色': 'Search users, email, or role',
|
||||
'数据源': 'Datasources',
|
||||
'数据源列表': 'Datasource list',
|
||||
'数据源详情': 'Datasource details',
|
||||
'数据源总数': 'Total datasources',
|
||||
'数据源状态': 'Datasource status',
|
||||
'数据概览': 'Data overview',
|
||||
'数据列表': 'Data list',
|
||||
'数据类型': 'Data type',
|
||||
'数据集': 'Dataset',
|
||||
'数据状态': 'Data status',
|
||||
'采集数据': 'Collected data',
|
||||
'采集配置列表': 'Collection configuration list',
|
||||
'采集器': 'Collectors',
|
||||
'采集器详情': 'Collector details',
|
||||
'采集器配置': 'Collector configuration',
|
||||
'采集快照': 'Collection snapshot',
|
||||
'采集历史 / 快照': 'Collection history / snapshots',
|
||||
'采集时间': 'Collected at',
|
||||
'采集已取消': 'Collection cancelled',
|
||||
'采集失败': 'Collection failed',
|
||||
'采集成功': 'Collection succeeded',
|
||||
'采集完成': 'Collection complete',
|
||||
'采集中': 'Collecting',
|
||||
'采集管理': 'Collection Management',
|
||||
'采集调度': 'Collection schedule',
|
||||
'采样': 'Sample',
|
||||
'采样数据': 'Sample data',
|
||||
'重新处理': 'Reprocess',
|
||||
'重新处理新闻': 'Reprocess news item',
|
||||
'新增 Feed 子项': 'Add feed entry',
|
||||
'新增新闻': 'Add news item',
|
||||
'新建': 'Create',
|
||||
'新增新闻源': 'Add news source',
|
||||
'新增新闻组': 'Add news group',
|
||||
'新增采集器配置': 'Add collector configuration',
|
||||
'新增 Schema 映射': 'Add schema mapping',
|
||||
'新增直播源': 'Add stream source',
|
||||
'新闻内容': 'News content',
|
||||
'新闻条目': 'News items',
|
||||
'新闻源': 'News sources',
|
||||
'新闻源 ID 不能为空。': 'News source ID is required.',
|
||||
'新闻源名称不能为空。': 'News source name is required.',
|
||||
'新闻源配置': 'News source configuration',
|
||||
'新闻源详情': 'News source details',
|
||||
'新闻源测试失败': 'News source test failed',
|
||||
'新闻组': 'News group',
|
||||
'新闻类型': 'News category',
|
||||
'新闻直播源': 'News stream source',
|
||||
'无权访问': 'Permission required',
|
||||
'无权限': 'No permission',
|
||||
'无效': 'Invalid',
|
||||
'暂无 Feed 子项': 'No feed entries',
|
||||
'暂无会话': 'No conversation',
|
||||
'暂无分组': 'No groups',
|
||||
'暂无快照': 'No snapshots',
|
||||
'暂无数据': 'No data',
|
||||
'暂无新闻': 'No news items',
|
||||
'暂无发生明细': 'No occurrences',
|
||||
'暂无日志': 'No logs',
|
||||
'暂无日志内容': 'No log content',
|
||||
'暂无重复日志': 'No duplicate logs',
|
||||
'暂无上报': 'No reports',
|
||||
'暂无摘要': 'No summary',
|
||||
'日志': 'Logs',
|
||||
'日志源': 'Log sources',
|
||||
'日志源不可用': 'Log source unavailable',
|
||||
'日志详情': 'Log details',
|
||||
'日志视图': 'Log views',
|
||||
'日志跟随连接失败,可暂停后使用手动刷新。': 'Log follow connection failed. Pause it and refresh manually.',
|
||||
'日志已复制': 'Logs copied',
|
||||
'明细': 'Details',
|
||||
'是否启用': 'Enabled',
|
||||
'实时同步中': 'Syncing live',
|
||||
'实时连接': 'Live connection',
|
||||
'旧密码': 'Old password',
|
||||
'映射模板': 'Mapping templates',
|
||||
'映射预览': 'Mapping preview',
|
||||
'显示名称': 'Display name',
|
||||
'显示 LLM API Key / Service Token': 'Show LLM API Key / Service Token',
|
||||
'显示': 'Display',
|
||||
'智能星球': 'Intelligent Planet',
|
||||
'智能星球计划': 'Intelligent Planet Program',
|
||||
'智能星球计划品牌标识': 'Intelligent Planet Program brand banner',
|
||||
'智能星球内容配置': 'Intelligent Planet content configuration',
|
||||
'智能星球配置详情': 'Intelligent Planet configuration details',
|
||||
'智能星球内容': 'Planet Content',
|
||||
'未知': 'Unknown',
|
||||
'未配置': 'Not configured',
|
||||
'未启用': 'Not enabled',
|
||||
'未测试': 'Untested',
|
||||
'未选择记录': 'No record selected',
|
||||
'查看日志': 'View logs',
|
||||
'最近': 'Latest',
|
||||
'最后更新:': 'Last updated:',
|
||||
'最大 Token': 'Max tokens',
|
||||
'最大并发任务数': 'Max concurrent tasks',
|
||||
'最大登录尝试次数': 'Max login attempts',
|
||||
'最大结果数': 'Max results',
|
||||
'最大文件(MB)': 'Max file size (MB)',
|
||||
'标签': 'Tags',
|
||||
'标题': 'Title',
|
||||
'模型': 'Model',
|
||||
'模型供应商': 'Model providers',
|
||||
'模型预设': 'Model presets',
|
||||
'清理数据库数据': 'Clear database data',
|
||||
'清理智能星球图层缓存': 'Clear planet layer cache',
|
||||
'清理缓存': 'Clear cache',
|
||||
'测试 Web Search 连通性': 'Test Web Search connectivity',
|
||||
'测试 AI Provider 连通性': 'Test AI Provider connectivity',
|
||||
'测试当前 Feed': 'Test current feed',
|
||||
'测试当前新闻源': 'Test current news source',
|
||||
'测试收件人': 'Test recipient',
|
||||
'测试 SMTP': 'Test SMTP',
|
||||
'状态': 'Status',
|
||||
'活跃数据源': 'Active datasources',
|
||||
'海底光缆': 'Submarine cable',
|
||||
'海缆': 'Cable',
|
||||
'海缆登陆关系': 'Cable landing relation',
|
||||
'海缆系统': 'Cable system',
|
||||
'后端已停止响应,正在等待服务恢复。': 'Backend stopped responding. Waiting for service recovery.',
|
||||
'源 ID': 'Source ID',
|
||||
'源名称': 'Source name',
|
||||
'源属性标签': 'Source attribute tags',
|
||||
'源类型': 'Source type',
|
||||
'源配置': 'Source configuration',
|
||||
'源属性': 'Source attributes',
|
||||
'源详情': 'Source details',
|
||||
'源健康': 'Source health',
|
||||
'来源': 'Source',
|
||||
'区域': 'Region',
|
||||
'按数据源': 'Source',
|
||||
'按类型': 'Type',
|
||||
'排序': 'Sort order',
|
||||
'单条添加': 'Add one item',
|
||||
'单源配置': 'Single-source configuration',
|
||||
'上传': 'Upload',
|
||||
'上传 JSON': 'Upload JSON',
|
||||
'用户管理': 'User Management',
|
||||
'电商': 'E-commerce',
|
||||
'电视直播': 'TV streams',
|
||||
'直播源': 'Stream sources',
|
||||
'直播源详情': 'Stream source details',
|
||||
'目标 Schema': 'Target schema',
|
||||
'直达': 'Open',
|
||||
'确认': 'Confirm',
|
||||
'确认删除': 'Confirm deletion',
|
||||
'确认告警': 'Confirm alert',
|
||||
'确认操作': 'Confirm action',
|
||||
'禁用': 'Disabled',
|
||||
'空': 'Empty',
|
||||
'空闲': 'Idle',
|
||||
'等待中': 'Pending',
|
||||
'简报': 'Brief',
|
||||
'结果': 'Results',
|
||||
'系统告警列表': 'System alert list',
|
||||
'系统告警': 'System Alerts',
|
||||
'系统数据库日志': 'System database logs',
|
||||
'系统日志': 'System Logs',
|
||||
'系统显示': 'System display',
|
||||
'系统名称': 'System name',
|
||||
'系统设置': 'System Settings',
|
||||
'系统总览与实时态势': 'System overview and realtime status',
|
||||
'设置': 'Settings',
|
||||
'设置详情': 'Settings details',
|
||||
'设置分区': 'Settings sections',
|
||||
'记录数': 'Records',
|
||||
'计算中心': 'Compute center',
|
||||
'选择 JSON 文件': 'Select JSON file',
|
||||
'选择一条记录': 'Select a record',
|
||||
'选择一组重复日志': 'Select a duplicate log group',
|
||||
'选择左侧父级后编辑它的子配置。': 'Select a parent item on the left to edit its child configuration.',
|
||||
'选择日志源后读取快照。': 'Select a log source to read its snapshot.',
|
||||
'选择新闻直播源': 'Select news stream source',
|
||||
'层级': 'Level',
|
||||
'纬度': 'Latitude',
|
||||
'经度': 'Longitude',
|
||||
'统计': 'Stats',
|
||||
'组内可按条添加,也可以上传 JSON 数组批量导入。': 'You can add items one by one or upload a JSON array for bulk import.',
|
||||
'编辑': 'Edit',
|
||||
'编辑新闻': 'Edit news',
|
||||
'缺失': 'Missing',
|
||||
'免费': 'Free',
|
||||
'网络': 'Network',
|
||||
'自定义': 'Custom',
|
||||
'自定义源': 'Custom sources',
|
||||
'演示模式': 'Demo mode',
|
||||
'自治系统统计': 'Autonomous system stats',
|
||||
'自动回退': 'Auto fallback',
|
||||
'英文标题': 'English title',
|
||||
'英文摘要': 'English summary',
|
||||
'英文正文': 'English content',
|
||||
'英文分类': 'English category',
|
||||
'草稿': 'Draft',
|
||||
'警告': 'Warning',
|
||||
'警告告警通知': 'Warning alerts',
|
||||
'设备统计': 'Device stats',
|
||||
'触发全部': 'Trigger all',
|
||||
'触发采集': 'Trigger collection',
|
||||
'访问智能星球': 'Open Intelligent Planet',
|
||||
'访问官网': 'Open website',
|
||||
'详 情': 'Details',
|
||||
'详情': 'Details',
|
||||
'详情/统计': 'Details / stats',
|
||||
'详情会在右侧完整显示,不会挤压主表区域。': 'Details appear in the right pane without compressing the main table.',
|
||||
'调试': 'Debug',
|
||||
'请稍后重试': 'Please try again later',
|
||||
'连接失败': 'Connection failed',
|
||||
'连接中': 'Connecting',
|
||||
'正在连接': 'Connecting',
|
||||
'连接测试': 'Connection test',
|
||||
'连通性': 'Connectivity',
|
||||
'连通正常': 'Connectivity normal',
|
||||
'连通性失败': 'Connectivity failed',
|
||||
'运行': 'Run',
|
||||
'运行中': 'Running',
|
||||
'运行状态': 'Runtime status',
|
||||
'运维与配置': 'Operations and Settings',
|
||||
'过滤': 'Filters',
|
||||
'跟随中': 'Following',
|
||||
'跟随日志': 'Follow logs',
|
||||
'输入': 'Input',
|
||||
'返回上一级详情': 'Back to parent details',
|
||||
'返回列表': 'Back to list',
|
||||
'通知策略': 'Notification policy',
|
||||
'通知邮箱': 'Notification email',
|
||||
'配置错误': 'Configuration error',
|
||||
'配置源': 'Configuration source',
|
||||
'重要度与健康策略': 'Importance and health policy',
|
||||
'重启': 'Restart',
|
||||
'重启 AI Provider': 'Restart AI Provider',
|
||||
'重启后端': 'Restart backend',
|
||||
'重启服务': 'Restart service',
|
||||
'重启前端': 'Restart frontend',
|
||||
'重启数据库': 'Restart database',
|
||||
'重启动作': 'Restart action',
|
||||
'重启任务失败': 'Restart task failed',
|
||||
'重复日志详情': 'Duplicate log details',
|
||||
'重复日志统计': 'Duplicate log stats',
|
||||
'重复统计': 'Duplicate stats',
|
||||
'重启实时源': 'Restart realtime source',
|
||||
'重置': 'Reset',
|
||||
'重置 Prompt': 'Reset prompt',
|
||||
'重置为默认内容': 'Reset to default content',
|
||||
'重置为默认教程': 'Reset to default guide',
|
||||
'重置品牌配置': 'Reset brand configuration',
|
||||
'重试': 'Retry',
|
||||
'重试次数': 'Retries',
|
||||
'错误': 'Error',
|
||||
'覆盖类型': 'Covered types',
|
||||
'覆盖数据源': 'Covered datasources',
|
||||
'执行命令': 'Command',
|
||||
'暂停日志跟随': 'Pause log follow',
|
||||
'隐藏 LLM API Key / Service Token': 'Hide LLM API Key / Service Token',
|
||||
'隐藏': 'Hide',
|
||||
'首页地址': 'Homepage URL',
|
||||
'主页地址': 'Homepage URL',
|
||||
'默认新闻类型': 'Default news category',
|
||||
'默认': 'Default',
|
||||
'默认教程': 'Default guide',
|
||||
'默认模型': 'Default model',
|
||||
'默认频道': 'Default channel',
|
||||
'高亮命中': 'Highlighted match',
|
||||
'AIS 船舶': 'AIS vessels',
|
||||
'BGP 更新': 'BGP updates',
|
||||
'BGP 路由': 'BGP route',
|
||||
'BGP 路由表': 'BGP RIB',
|
||||
'BGP 事件': 'BGP event',
|
||||
'Docker 不可用': 'Docker unavailable',
|
||||
'GPU 集群': 'GPU clusters',
|
||||
'HTTP 失败': 'HTTP failed',
|
||||
'Anthropic 版本': 'Anthropic version',
|
||||
'Earth 左上角品牌实际渲染预览': 'Rendered preview of the top-left Earth brand',
|
||||
'LLM 基础地址': 'LLM base URL',
|
||||
'Logo 替代文本': 'Logo alt text',
|
||||
'当前分区没有可用后端能力,控制台不混入其他配置或假数据。': 'This section has no backend capability yet; the console does not mix in unrelated configuration or fake data.',
|
||||
'当前分区没有可配置项。': 'This section has no configurable items.',
|
||||
'当前模块暂无数据': 'No data in this module',
|
||||
'当前已是默认': 'Already default',
|
||||
'当前已是默认频道': 'Already the default channel',
|
||||
'当前配置可以连通。': 'Current configuration can connect.',
|
||||
'当前配置连通性检查失败。': 'Configuration connectivity check failed.',
|
||||
'当前采集源没有可查看的历史版本。': 'This collection source has no historical versions.',
|
||||
'待定位': 'Pending location',
|
||||
'后端能力未提供': 'Backend capability unavailable',
|
||||
'只展示智能星球品牌、边界构建和电视内容配置。': 'Only Intelligent Planet branding, boundary build, and TV content configuration are shown.',
|
||||
'只展示数据源相关接口,不混入其他设置对象。': 'Only datasource-related endpoints are shown; unrelated settings are not mixed in.',
|
||||
'只展示系统设置分区;AI 集成和采集器调度分别在对应模块管理。': 'Only system settings sections are shown. AI integrations and collector schedules are managed in their own modules.',
|
||||
'只展示 BGP 事故、异常与简报。': 'Only BGP incidents, anomalies, and briefs are shown.',
|
||||
'只记录官网、报告页或未来采集器线索,不参与 RSS/Atom 抓取;如需抓取,请改为 RSS、Atom 或 Aggregated。': 'Records official sites, reports, or future collector leads only. It does not participate in RSS/Atom fetching. Use RSS, Atom, or Aggregated to fetch.',
|
||||
'只编辑当前新闻源;保存后才会固化到新闻源配置。': 'Only edits the current news source. Save to persist it into the news source configuration.',
|
||||
'只重启 AI Provider 适配服务,前端页面通常保持在线。': 'Restart only the AI Provider adapter. The frontend usually stays online.',
|
||||
'只重启后端服务,页面通常会短暂失联后自动恢复。': 'Restart only the backend service. The page may briefly disconnect and recover automatically.',
|
||||
'只重启前端开发服务,页面会短暂不可用,恢复后自动刷新。': 'Restart only the frontend dev service. The page will be briefly unavailable and refresh after recovery.',
|
||||
'失败时页面仍可操作': 'Page remains usable when requests fail',
|
||||
'打开': 'Open',
|
||||
'观测台': 'Observatory',
|
||||
'概览': 'Overview',
|
||||
'概览摘要': 'Overview summary',
|
||||
'告警详情': 'Alert details',
|
||||
'查看智能星球图层缓存': 'View Intelligent Planet layer cache',
|
||||
'描述来源属性,不是媒体来源名;多个标签用逗号分隔,例如 business_news, ecommerce, china。': 'Describe source attributes, not media source names. Separate multiple tags with commas, for example business_news, ecommerce, china.',
|
||||
'浏览采集结果、筛选数据源和查看原始元数据。': 'Browse collected results, filter datasources, and inspect raw metadata.',
|
||||
'管理采集器、采集调度和采集历史 / 快照。': 'Manage collectors, collection schedules, and collection history / snapshots.',
|
||||
'管理智能星球品牌、边界、电视内容和内容资产。': 'Manage Intelligent Planet branding, boundaries, TV content, and content assets.',
|
||||
'管理模型供应商、工具调用、提示词和 Playground。': 'Manage model providers, tool calls, prompts, and Playground.',
|
||||
'管理系统显示、通知策略、安全策略和 SMTP 邮件。': 'Manage system display, notification policy, security policy, and SMTP email.',
|
||||
'统一查看内置源、自定义源、实时源与任务状态,保留触发、启停和连接状态入口。': 'View built-in, custom, and realtime sources plus task status in one place, with trigger, start/stop, and connectivity entries.',
|
||||
'严重告警': 'Critical alerts',
|
||||
'严重告警通知': 'Critical alerts',
|
||||
'查看日志源、读取快照、复制原始输出,按控制台阅读方式组织。': 'View log sources, read snapshots, and copy raw output in a console-friendly layout.',
|
||||
'查看日志源、按级别/日期/搜索条件读取快照,并复制原始输出。': 'View log sources, read snapshots by level, date, and search filters, then copy raw output.',
|
||||
'显示系统告警记录和统计,不混入 BGP 概览以外的数据。': 'Shows system alert records and stats without mixing in data outside the BGP overview.',
|
||||
'显示态势统计与告警记录。': 'Shows situational stats and alert records.',
|
||||
'查看态势统计、严重度、AI 简报入口和处理状态。': 'View situational stats, severity, AI brief entry points, and handling status.',
|
||||
'系统告警、确认处理、AI 摘要和处置状态集中到一张低噪声列表。': 'System alerts, acknowledgements, AI summaries, and resolution status are collected into one low-noise list.',
|
||||
'聚合 BGP 事故、异常和 AI 简报,突出严重度、影响范围和事件链路。': 'Aggregates BGP incidents, anomalies, and AI briefs, highlighting severity, affected scope, and event chains.',
|
||||
'查看采集器、事故、异常、事件与 AI 简报;这是信息观测页,采用列表加详情。': 'View collectors, incidents, anomalies, events, and AI briefs in an information page with list plus detail.',
|
||||
'按 BGP 实体聚合展示,保留事件、异常、事故和简报语义。': 'Aggregates by BGP entity while preserving event, anomaly, incident, and brief semantics.',
|
||||
'配置类页面采用分层结构:先选父级,再编辑子配置。': 'Configuration pages use a hierarchy: select a parent first, then edit child configuration.',
|
||||
'仅展示系统设置分区;AI 集成和采集器调度分别在对应模块管理。': 'Only system setting sections are shown; AI integrations and collector schedules are managed in their own modules.',
|
||||
'仅展示数据源相关接口,不混入其他设置对象。': 'Only datasource endpoints are shown; unrelated settings objects are not mixed in.',
|
||||
'仅展示智能星球品牌、边界构建和电视内容配置。': 'Only Intelligent Planet branding, boundary builds, and TV content configuration are shown.',
|
||||
'读取快照': 'Read snapshot',
|
||||
'触发全部数据源': 'Trigger all datasources',
|
||||
'数据源任务,暂无任务': 'Datasource tasks, no tasks',
|
||||
'生成 BGP AI 简报': 'Generate BGP AI brief',
|
||||
'生成系统告警 AI 简报': 'Generate system alert AI brief',
|
||||
'生成态势告警 AI 简报': 'Generate situational alert AI brief',
|
||||
'生成简报': 'Generate brief',
|
||||
'模块': 'Module',
|
||||
'模块分区': 'Module sections',
|
||||
'指标': 'Metric',
|
||||
'支持 png, jpg, jpeg, webp, svg': 'Supports png, jpg, jpeg, webp, svg',
|
||||
'协议适配': 'Protocol adapter',
|
||||
'代理 Token': 'Proxy token',
|
||||
'代理地址': 'Proxy URL',
|
||||
'设为默认': 'Set as default',
|
||||
'输入新的 LLM API Key': 'Enter new LLM API key',
|
||||
'输入新的代理 Token': 'Enter new proxy token',
|
||||
'显示LLM API Key': 'Show LLM API key',
|
||||
'隐藏LLM API Key': 'Hide LLM API key',
|
||||
'显示代理 Token': 'Show proxy token',
|
||||
'隐藏代理 Token': 'Hide proxy token',
|
||||
'显示API Key': 'Show API key',
|
||||
'隐藏API Key': 'Hide API key',
|
||||
'最大输出 Tokens': 'Max output tokens',
|
||||
'超时(秒)': 'Timeout (seconds)',
|
||||
'拖动调整详情宽度': 'Drag to resize details',
|
||||
'异常': 'Anomaly',
|
||||
'播放类型': 'Playback type',
|
||||
'上次状态': 'Last status',
|
||||
'上次执行': 'Last run',
|
||||
'需要凭证': 'Requires credentials',
|
||||
'凭证提供方': 'Credential provider',
|
||||
'凭证教程': 'Credential guide',
|
||||
'接口地址': 'Endpoint URL',
|
||||
'输入要发送给 AI 的内容': 'Enter content to send to AI',
|
||||
'发送': 'Send',
|
||||
'会话': 'Conversation',
|
||||
'会话写入后端,刷新后保留线程状态。': 'Conversation state is stored in the backend and persists after refresh.',
|
||||
'Playground 设置': 'Playground settings',
|
||||
'预设': 'Preset',
|
||||
'目标': 'Objective',
|
||||
'约束': 'Constraints',
|
||||
'描述': 'Description',
|
||||
'每日摘要': 'Daily digest',
|
||||
'Logo 地址': 'Logo URL',
|
||||
'上传 Logo': 'Upload logo',
|
||||
'上传标题图片': 'Upload title image',
|
||||
'上传中': 'Uploading',
|
||||
'将图片拖到这里': 'Drop file here',
|
||||
'复制为 Logo': 'Copy as logo',
|
||||
'复制为标题图': 'Copy as title image',
|
||||
'Logo 图片已上传': 'Logo image uploaded',
|
||||
'标题图片已上传': 'Title image uploaded',
|
||||
'请拖入图片文件': 'Drop an image file',
|
||||
'API 基础地址': 'API base URL',
|
||||
'Firecrawl 抓取路径': 'Firecrawl scrape path',
|
||||
'Firecrawl 搜索路径': 'Firecrawl search path',
|
||||
'SearXNG 分类': 'SearXNG categories',
|
||||
'SerpAPI 引擎': 'SerpAPI engine',
|
||||
'OCR 基础地址': 'OCR base URL',
|
||||
'OCR 供应商': 'OCR provider',
|
||||
'包含答案': 'Include answer',
|
||||
'包含原始内容': 'Include raw content',
|
||||
'包含正文': 'Include text',
|
||||
'输入新的 OCR API Key': 'Enter new OCR API key',
|
||||
'输入新的 WebSearch API Key': 'Enter new WebSearch API key',
|
||||
'每个搜索 provider 有独立 API 与高级参数': 'Each search provider has its own API and advanced parameters',
|
||||
'OCR provider、模型、语言和文件限制': 'OCR provider, model, language, and file limits',
|
||||
'优先级': 'Priority',
|
||||
'边界状态': 'Boundary status',
|
||||
'边界构建': 'Boundary build',
|
||||
'边界构建任务': 'Boundary build task',
|
||||
'品牌': 'Brand',
|
||||
'品牌标识': 'Branding',
|
||||
'品牌配置': 'Brand configuration',
|
||||
'异常接口': 'Failing endpoints',
|
||||
'图层资源': 'Layer resources',
|
||||
'采集源': 'Collected sources',
|
||||
'实时源': 'Realtime sources',
|
||||
'重复日志': 'Duplicate logs',
|
||||
'原始日志': 'Raw logs',
|
||||
'审计事件': 'Audit events',
|
||||
'审计日志': 'Audit logs',
|
||||
'审计来源': 'Audit sources',
|
||||
'原始ID': 'Raw ID',
|
||||
'原始元数据': 'Raw metadata',
|
||||
'扩展字段': 'Extended fields',
|
||||
'参考日期': 'Reference date',
|
||||
'快捷入口': 'Quick links',
|
||||
'行': 'lines',
|
||||
'次': 'times',
|
||||
'首次': 'First',
|
||||
'指纹': 'Fingerprint',
|
||||
'离线': 'Offline',
|
||||
'等待创建': 'Waiting to create',
|
||||
'等待操作': 'Waiting for action',
|
||||
'将重启服务。': 'The service will restart.',
|
||||
'完全重启': 'Full restart',
|
||||
'重启 PostgreSQL 和 Redis 容器,前端页面保持在线。': 'Restart the PostgreSQL and Redis containers while the frontend stays online.',
|
||||
'重启前后端和相关服务,页面会短暂不可用,恢复后自动刷新。': 'Restart frontend, backend, and related services. The page will be briefly unavailable and refresh after recovery.',
|
||||
'已发送重启指令,正在等待服务进入重启流程。': 'Restart command sent. Waiting for services to enter the restart flow.',
|
||||
'重启任务正在执行': 'Restart task is running',
|
||||
'服务已恢复,正在刷新页面。': 'Service recovered. Refreshing the page.',
|
||||
'前端已恢复,正在刷新页面。': 'Frontend recovered. Refreshing the page.',
|
||||
'前端正在重启,正在等待页面入口恢复访问。': 'Frontend is restarting. Waiting for the page entry to recover.',
|
||||
'获取数据失败': 'Failed to load data',
|
||||
'最后更新': 'Last updated',
|
||||
'总记录': 'Total records',
|
||||
'筛选结果': 'Filtered results',
|
||||
'清空': 'Clear',
|
||||
'导出失败': 'Export failed',
|
||||
'导出 JSON': 'Export JSON',
|
||||
'导出 CSV': 'Export CSV',
|
||||
'数据详情': 'Data details',
|
||||
'数据保留天数': 'Data retention days',
|
||||
'按级别/日期/搜索条件读取快照': 'Read snapshots by level, date, and search filters',
|
||||
'点击左侧聚合项查看每次发生时间。': 'Click an aggregation on the left to view each occurrence time.',
|
||||
'管理员敏感操作和安全审计记录。': 'Sensitive admin operations and security audit records.',
|
||||
'当前账号没有系统日志访问权限。': 'This account does not have system log access.',
|
||||
'仅超级管理员可查看系统日志。': 'Only super admins can view system logs.',
|
||||
'左侧展示按 fingerprint 聚合后的运行时错误。': 'The left side shows runtime errors grouped by fingerprint.',
|
||||
'调整筛选条件或刷新日志源。': 'Adjust filters or refresh log sources.',
|
||||
'复制日志': 'Copy logs',
|
||||
'刷新日志': 'Refresh logs',
|
||||
'刷新日志源': 'Refresh log sources',
|
||||
'结束日期': 'End date',
|
||||
'信息': 'Info',
|
||||
'可用': 'Available',
|
||||
'可读取': 'Readable',
|
||||
'可编辑': 'Editable',
|
||||
'只读': 'Read-only',
|
||||
'暂无日志源': 'No log sources',
|
||||
'登陆点': 'Landing point',
|
||||
'算力中心': 'Compute center',
|
||||
'互联网交换点': 'Internet exchange point',
|
||||
'前缀地理位置': 'Prefix geography',
|
||||
'卫星轨道根数': 'Satellite TLE',
|
||||
'空间': 'Space',
|
||||
'超算': 'Supercomputer',
|
||||
'通用数据': 'Generic data',
|
||||
'通用记录': 'Generic records',
|
||||
'船舶': 'Vessel',
|
||||
'设施': 'Facility',
|
||||
'流量统计': 'Traffic stats',
|
||||
'条': 'items',
|
||||
'项': 'items',
|
||||
'条结果': 'results',
|
||||
'筛选': 'Filters',
|
||||
'共': 'Total',
|
||||
'现实层宇宙全息感知系统': 'Reality-layer holographic awareness system',
|
||||
'卫星 · 海底光缆 · 算力基础设施': 'Satellites · Submarine cables · Computing infrastructure',
|
||||
'选择/拖入资产': 'Select / drop asset',
|
||||
'元数据 / 原始字段': 'Metadata / raw fields',
|
||||
'全部启用状态': 'All enabled states',
|
||||
'失败': 'Failed',
|
||||
'未执行': 'Not run',
|
||||
'已采集': 'Collected',
|
||||
'未采集': 'Not collected',
|
||||
'当前分区暂无记录': 'No records in this section',
|
||||
'切换上方分区可精准查看不同配置和接口。': 'Switch sections above to inspect different configurations and endpoints.',
|
||||
'详情会在右侧完整滚动显示,不会挤压主表区域。': 'Details scroll fully on the right without compressing the main table.',
|
||||
'连接、采样、运行和凭证配置': 'Connection, sampling, runtime, and credential configuration',
|
||||
'采样 payload 到目标 Schema 的字段映射': 'Field mapping from sample payload to target schema',
|
||||
'采集数据落库目标结构': 'Target schema for persisted collected data',
|
||||
'标识': 'Identifier',
|
||||
'更新时间': 'Updated at',
|
||||
'卫星': 'Satellite',
|
||||
'算力': 'Compute',
|
||||
'媒体': 'Media',
|
||||
'参考': 'Reference',
|
||||
'参考链接': 'Reference link',
|
||||
'参考链接不参与抓取': 'Reference links are not fetched',
|
||||
'亚太': 'Asia-Pacific',
|
||||
'中国': 'China',
|
||||
'中东与非洲': 'Middle East and Africa',
|
||||
'全球': 'Global',
|
||||
'欧洲': 'Europe',
|
||||
'美国': 'United States',
|
||||
'美洲': 'Americas',
|
||||
'36氪': '36Kr',
|
||||
'亿邦动力': 'Ebrun',
|
||||
'商务数据中心': 'MOFCOM Data Center',
|
||||
'商务部电商动态': 'MOFCOM E-Commerce',
|
||||
'国家统计局数据发布': 'National Bureau of Statistics',
|
||||
'电商物流指数': 'China E-Commerce Logistics Index',
|
||||
'综合资讯': 'General',
|
||||
'文章资讯': 'Articles',
|
||||
'最新快讯': 'Newsflash',
|
||||
'动态内容': 'Updates',
|
||||
'零售': 'Retail',
|
||||
'服务': 'Services',
|
||||
'商业': 'Business',
|
||||
'政治': 'Politics',
|
||||
'金融': 'Finance',
|
||||
'科技': 'Technology',
|
||||
'无条目': 'No entries',
|
||||
'格式错误': 'Format error',
|
||||
'超时': 'Timeout',
|
||||
'尚未测试当前源。': 'This source has not been tested yet.',
|
||||
'来源官网、栏目页或报告页,不作为抓取入口。': 'Official site, section page, or report page. It is not used as the fetch entry.',
|
||||
'默认类型': 'Default category',
|
||||
'重要度权重': 'Importance weight',
|
||||
'抓取间隔(分钟)': 'Fetch interval (minutes)',
|
||||
'失败阈值': 'Failure threshold',
|
||||
'熔断冷却(分钟)': 'Circuit-breaker cooldown (minutes)',
|
||||
'熔断开关': 'Circuit breaker',
|
||||
'组名 / 来源名': 'Group / source name',
|
||||
'组类型': 'Group type',
|
||||
'新闻数量': 'News count',
|
||||
'内容来源': 'Content source',
|
||||
'原文链接': 'Original URL',
|
||||
'缺省区域': 'Default region',
|
||||
'Feed 子项': 'Feed entries',
|
||||
'每个子项都是一个真实 RSS/Atom/Aggregated 抓取入口,可单独启停和设置默认新闻类型。': 'Each entry is a real RSS/Atom/Aggregated fetch entry and can be enabled, disabled, and assigned its own default category.',
|
||||
'添加一个真实 RSS/Atom/Aggregated 地址后才能抓取。': 'Add a real RSS/Atom/Aggregated URL before fetching.',
|
||||
'启用 Feed': 'Enable feed',
|
||||
'停用 Feed': 'Disable feed',
|
||||
'用于新闻排序、抓取频率、超时和熔断控制。': 'Used for news ranking, fetch frequency, timeout, and circuit-breaker control.',
|
||||
'频道身份、状态和排序。': 'Channel identity, status, and sort order.',
|
||||
'播放地址、封面、YouTube 信息和其他高级字段。': 'Playback URL, cover image, YouTube metadata, and other advanced fields.',
|
||||
'配置表单': 'Configuration form',
|
||||
'常用字段直接编辑;复杂对象保留结构化子字段,不再把整条记录只丢进 JSON。': 'Common fields are edited directly; complex objects keep structured child fields instead of sending the whole record into JSON only.',
|
||||
'查看完整 JSON': 'View full JSON',
|
||||
'原始数据': 'Raw data',
|
||||
'日志正文': 'Log text',
|
||||
'正在加载数据': 'Loading data',
|
||||
'同步中': 'Syncing',
|
||||
'就绪': 'Ready',
|
||||
'进度': 'Progress',
|
||||
'取消任务': 'Cancel task',
|
||||
'清空已结束队列项': 'Clear completed queue items',
|
||||
'暂无数据源任务': 'No datasource tasks',
|
||||
'进行': 'Running',
|
||||
'跳过': 'Skipped',
|
||||
'可选模型': 'Available models',
|
||||
'快照版本': 'Snapshot version',
|
||||
'快照摘要': 'Snapshot summary',
|
||||
'采集任务': 'Collection task',
|
||||
'当前没有运行中的任务。': 'No task is currently running.',
|
||||
'没有可用 WebSearch 证据,已保留默认教程。': 'No WebSearch evidence is available, so the default guide was kept.',
|
||||
'首版只支持顶层为数组的 JSON 文件;取消不会清空当前新闻组详情。': 'The first version only supports JSON files whose top-level value is an array. Canceling does not clear the current news group details.',
|
||||
'选择文件': 'Select file',
|
||||
'实时启停': 'Start / stop realtime source',
|
||||
'采集位置': 'Collect location',
|
||||
'拉取详情': 'Fetch details',
|
||||
'预览': 'Preview',
|
||||
'预览映射': 'Preview mapping',
|
||||
'到采集管理编辑': 'Edit in Collection Management',
|
||||
'测试启用源': 'Test enabled sources',
|
||||
'重置默认新闻源': 'Reset default news sources',
|
||||
'重置新闻源': 'Reset news sources',
|
||||
'删除数据': 'Delete data',
|
||||
'清理数据源缓存': 'Clear datasource cache',
|
||||
'停止删除': 'Stop deletion',
|
||||
'停止已选': 'Stop selected',
|
||||
'触发已选': 'Trigger selected',
|
||||
'已取消新增直播源': 'New stream source cancelled',
|
||||
'已取消新增新闻源': 'New news source cancelled',
|
||||
'已取消新增配置': 'New configuration cancelled',
|
||||
'已恢复当前项': 'Current item restored',
|
||||
'表单已恢复到加载时状态。': 'The form has been restored to its loaded state.',
|
||||
'当前分区未找到该数据源': 'Datasource not found in the current section',
|
||||
'可切回内置源或刷新后再查看。': 'Switch back to built-in sources or refresh before viewing it again.',
|
||||
'无法重试': 'Cannot retry',
|
||||
'当前列表中没有找到对应数据源。': 'The matching datasource was not found in the current list.',
|
||||
'读取凭证失败': 'Failed to read credentials',
|
||||
'JSON 格式错误': 'Invalid JSON',
|
||||
'请修正高级编辑内容后再保存。': 'Fix the advanced editor content before saving.',
|
||||
'请修正映射内容后再保存。': 'Fix the mapping content before saving.',
|
||||
'请修正映射内容后再预览。': 'Fix the mapping content before previewing.',
|
||||
'新闻源配置不完整': 'News source configuration is incomplete',
|
||||
'参考链接不能启用抓取,请改为 RSS/Atom/Aggregated 或关闭启用。': 'Reference links cannot be fetched. Use RSS/Atom/Aggregated or disable fetching.',
|
||||
'RSS/Atom/Aggregated 新闻源需要至少一个 Feed 子项。': 'RSS/Atom/Aggregated news sources need at least one feed entry.',
|
||||
'新闻标题不能为空。': 'News title is required.',
|
||||
'坐标必须是数字。': 'Coordinates must be numeric.',
|
||||
'坐标超出范围。': 'Coordinates are out of range.',
|
||||
'新闻源缺少已启用的 Feed 子项。': 'The news source has no enabled feed entries.',
|
||||
'OCR 配置': 'OCR configuration',
|
||||
'个入口': 'entries',
|
||||
'条消息': 'messages',
|
||||
'发送一条消息开始测试 AI 链路。': 'Send a message to test the AI link.',
|
||||
'数据源健康': 'Datasource health',
|
||||
'链路探测': 'Link smoke test',
|
||||
'AI 链路探测': 'AI link smoke test',
|
||||
'BGP 告警态势简报': 'BGP alert situational brief',
|
||||
'总结当前告警的主要风险、优先级与建议动作。': 'Summarize the main risks, priorities, and recommended actions for the current alerts.',
|
||||
'结论要简洁\n优先给出操作建议': 'Keep conclusions concise\nPrioritize operational recommendations',
|
||||
'出现新的高危告警\n部分观测站最近 24h 事件增多\n请先给出风险摘要,再列出建议动作。': 'New high-risk alerts appeared\nSome observatories have more events in the last 24h\nStart with a risk summary, then list recommended actions.',
|
||||
'采集器健康检查说明': 'Collector health check guide',
|
||||
'判断当前采集器失败是否属于上游接口失效、限流、结构变更或临时波动。': 'Determine whether the current collector failure is caused by upstream outage, rate limiting, schema drift, or temporary fluctuation.',
|
||||
'区分事实与推断\n先给排障优先级': 'Separate facts from inference\nPrioritize troubleshooting first',
|
||||
'最近 3 次任务失败\n部分数据源响应时间抬升\n个别接口返回结构不稳定\n请帮我先做排障优先级排序。': 'The last 3 tasks failed\nSome datasources have slower responses\nA few endpoints return unstable structures\nPlease prioritize troubleshooting.',
|
||||
'验证 backend -> aiprovider -> model provider 调用链路是否正常。': 'Verify whether the backend -> aiprovider -> model provider call chain works.',
|
||||
'输出简洁\n包含一段明确结论': 'Keep output concise\nInclude a clear conclusion',
|
||||
'当前从 Playground 发起测试,希望确认 provider 配置和返回结构正常,请直接给我链路结论。': 'This Playground test should confirm provider configuration and response structure. Give the link conclusion directly.',
|
||||
'无障碍标签': 'Accessibility label',
|
||||
'版本': 'Version',
|
||||
'版本号来自当前系统版本,只读展示,不会随关于信息提交。': 'The version comes from the current system version. It is read-only and is not submitted with About information.',
|
||||
'边界': 'Boundary',
|
||||
'构建': 'Build',
|
||||
'内置': 'Built-in',
|
||||
'Live 新闻': 'Live News',
|
||||
'直播加载中': 'Live stream loading',
|
||||
'个频道': 'channels',
|
||||
'尚未同步': 'Not synced yet',
|
||||
'提供方': 'Provider',
|
||||
'地区': 'Region',
|
||||
'语言': 'Language',
|
||||
'可回退': 'Fallback',
|
||||
'备注': 'Notes',
|
||||
'播放流地址': 'Stream URL',
|
||||
'嵌入地址': 'Embed URL',
|
||||
'封面地址': 'Poster URL',
|
||||
'YouTube 视频 ID': 'YouTube video ID',
|
||||
'YouTube 频道': 'YouTube channel',
|
||||
'Earth TV 实际渲染预览': 'Rendered Earth TV preview',
|
||||
'商业新闻': 'Business news',
|
||||
'连通不稳定': 'Unstable connectivity',
|
||||
'官方数据': 'Official data',
|
||||
'来源类型': 'Source type',
|
||||
'条新闻。': 'news items.',
|
||||
'单条标题只在这里展示,左侧保持来源/组聚合。': 'Only item titles are shown here; the left side keeps source/group aggregation.',
|
||||
'可以单条添加或上传 JSON 数组导入。': 'You can add items one by one or upload a JSON array.',
|
||||
'是': 'Yes',
|
||||
'否': 'No',
|
||||
'采集间隔(分钟)': 'Collection interval (minutes)',
|
||||
'无时间': 'No timestamp',
|
||||
'自动刷新': 'Auto refresh',
|
||||
'会话超时(分钟)': 'Session timeout (minutes)',
|
||||
'密码策略': 'Password policy',
|
||||
'主机': 'Host',
|
||||
'端口': 'Port',
|
||||
'用户名': 'Username',
|
||||
'使用 TLS': 'Use TLS',
|
||||
'发件邮箱': 'Sender email',
|
||||
'发件人名称': 'Sender name',
|
||||
'个历史快照,选择后查看该版本详情。': 'historical snapshots. Select one to view that version.',
|
||||
}
|
||||
68
frontend/src/i18n/locale.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
export type SupportedLocale = 'zh-CN' | 'en-US'
|
||||
export type DocsLang = 'zh' | 'en'
|
||||
|
||||
export const defaultLocale: SupportedLocale = 'zh-CN'
|
||||
export const localeStorageKey = 'planet-locale'
|
||||
const legacyDocsLangStorageKey = 'docs-lang'
|
||||
|
||||
export const localeOptions: Array<{ value: SupportedLocale; labelKey: string; titleKey: string }> = [
|
||||
{ value: 'zh-CN', labelKey: 'common.zh', titleKey: 'common.zh' },
|
||||
{ value: 'en-US', labelKey: 'common.en', titleKey: 'common.en' },
|
||||
]
|
||||
|
||||
export function normalizeLocale(value: string | null | undefined): SupportedLocale {
|
||||
if (!value) return defaultLocale
|
||||
const normalized = value.toLowerCase()
|
||||
if (normalized === 'en' || normalized === 'en-us' || normalized.startsWith('en-')) return 'en-US'
|
||||
if (normalized === 'zh' || normalized === 'zh-cn' || normalized.startsWith('zh-')) return 'zh-CN'
|
||||
return defaultLocale
|
||||
}
|
||||
|
||||
export function docsLangFromLocale(locale: SupportedLocale): DocsLang {
|
||||
return locale === 'en-US' ? 'en' : 'zh'
|
||||
}
|
||||
|
||||
export function localeFromDocsLang(lang: DocsLang): SupportedLocale {
|
||||
return lang === 'en' ? 'en-US' : 'zh-CN'
|
||||
}
|
||||
|
||||
export function readStoredLocale(): SupportedLocale {
|
||||
if (typeof window === 'undefined') return defaultLocale
|
||||
const storedLocale = window.localStorage.getItem(localeStorageKey)
|
||||
if (storedLocale) return normalizeLocale(storedLocale)
|
||||
|
||||
const legacyDocsLang = window.localStorage.getItem(legacyDocsLangStorageKey)
|
||||
if (legacyDocsLang === 'en' || legacyDocsLang === 'zh') {
|
||||
return localeFromDocsLang(legacyDocsLang)
|
||||
}
|
||||
|
||||
return defaultLocale
|
||||
}
|
||||
|
||||
export function persistLocale(locale: SupportedLocale) {
|
||||
if (typeof window === 'undefined') return
|
||||
window.localStorage.setItem(localeStorageKey, locale)
|
||||
window.localStorage.setItem(legacyDocsLangStorageKey, docsLangFromLocale(locale))
|
||||
}
|
||||
|
||||
export function syncDocumentLocale(locale: SupportedLocale) {
|
||||
if (typeof document === 'undefined') return
|
||||
document.documentElement.lang = locale
|
||||
}
|
||||
|
||||
export function useLocale() {
|
||||
const { i18n } = useTranslation()
|
||||
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
|
||||
const docsLang = docsLangFromLocale(locale)
|
||||
|
||||
const setLocale = useCallback((nextLocale: SupportedLocale) => {
|
||||
persistLocale(nextLocale)
|
||||
syncDocumentLocale(nextLocale)
|
||||
void i18n.changeLanguage(nextLocale)
|
||||
}, [i18n])
|
||||
|
||||
return { docsLang, locale, setLocale }
|
||||
}
|
||||
432
frontend/src/i18n/resources.ts
Normal file
@@ -0,0 +1,432 @@
|
||||
export const zhCN = {
|
||||
app: {
|
||||
title: '智能星球计划',
|
||||
routeLoading: '正在加载',
|
||||
},
|
||||
common: {
|
||||
cancel: '取消',
|
||||
close: '关闭',
|
||||
confirm: '确认',
|
||||
delete: '删除',
|
||||
language: '语言',
|
||||
loading: '加载中',
|
||||
noData: '暂无数据',
|
||||
operationFailed: '操作失败',
|
||||
page: '第 {{page}} / {{totalPages}} 页,共 {{total}} 条',
|
||||
previousPage: '上一页',
|
||||
nextPage: '下一页',
|
||||
selectRow: '选择行',
|
||||
selectVisibleRows: '选择当前可见数据',
|
||||
theme: '主题',
|
||||
themeLight: '浅色',
|
||||
themeDark: '深色',
|
||||
themeSystem: '系统',
|
||||
themeFollowSystem: '跟随系统',
|
||||
zh: '中文',
|
||||
en: 'EN',
|
||||
},
|
||||
admin: {
|
||||
brandTitle: '智能星球',
|
||||
brandSubtitle: '控制台',
|
||||
collapseMenu: '折叠菜单',
|
||||
expandMenu: '展开菜单',
|
||||
openNav: '打开导航',
|
||||
closeNav: '关闭导航',
|
||||
logout: '退出登录',
|
||||
greeting: '您好,{{name}}',
|
||||
version: '版本号',
|
||||
themeControl: '控制台主题',
|
||||
languageControl: '控制台语言',
|
||||
expandPreferences: '展开偏好设置',
|
||||
collapsePreferences: '收起偏好设置',
|
||||
search: {
|
||||
label: '搜索功能、配置和文字',
|
||||
placeholder: '搜索功能、配置和文字',
|
||||
current: '当前:{{label}}',
|
||||
results: 'Admin 搜索结果',
|
||||
loading: '正在加载搜索索引…',
|
||||
empty: '没有找到匹配内容',
|
||||
pageContext: '页面',
|
||||
},
|
||||
groups: {
|
||||
overview: '总览',
|
||||
collection: '采集与数据',
|
||||
observability: '专题观测',
|
||||
alerts: '告警与研判',
|
||||
ops: '运维与配置',
|
||||
},
|
||||
routes: {
|
||||
dashboard: '仪表盘',
|
||||
earth: '智能星球',
|
||||
docs: '文档',
|
||||
datasources: '数据源',
|
||||
data: '采集数据',
|
||||
bgp: 'BGP观测',
|
||||
systemAlerts: '系统告警',
|
||||
bgpAlerts: 'BGP 告警',
|
||||
situationalAlerts: '态势告警',
|
||||
ai: 'AI',
|
||||
earthContent: '智能星球内容',
|
||||
collectionManagement: '采集管理',
|
||||
logs: '系统日志',
|
||||
users: '用户管理',
|
||||
settings: '系统设置',
|
||||
},
|
||||
sections: {
|
||||
alerts: '告警记录',
|
||||
aiIntegrations: '模型供应商',
|
||||
aiTools: '工具调用',
|
||||
aiPrompts: '提示词',
|
||||
aiPlayground: 'Playground',
|
||||
bgpOverview: 'BGP',
|
||||
collectionHistory: '采集历史 / 快照',
|
||||
collectorCredentials: '采集器',
|
||||
collectors: '采集调度',
|
||||
earthAssets: '国界精度',
|
||||
earthBrand: '品牌标识',
|
||||
logsSources: '日志源',
|
||||
newsSources: '新闻源',
|
||||
notifications: '通知策略',
|
||||
security: '安全策略',
|
||||
settingsSystem: '系统显示',
|
||||
smtp: 'SMTP 邮件',
|
||||
tv: '电视直播',
|
||||
},
|
||||
},
|
||||
auth: {
|
||||
accountRecovery: '账号恢复',
|
||||
alreadyHaveAccount: '已有账号,去登录',
|
||||
backToLogin: '返回登录',
|
||||
code: '验证码',
|
||||
codeSent: '验证码已发送至 <strong>{{email}}</strong>,10 分钟内有效。',
|
||||
createAccount: '创建账号',
|
||||
email: '邮箱',
|
||||
emailVerification: '邮箱验证',
|
||||
emailNotVerified: '邮箱未验证,请先完成邮箱验证。',
|
||||
forgotPassword: '忘记密码?',
|
||||
forgotPasswordDescription: '通过邮箱验证码重置后台账号密码。',
|
||||
forgotPasswordTitle: '找回密码',
|
||||
loginButton: '登录',
|
||||
loginDescription: '使用你的后台账号进入运维工作台。',
|
||||
loginFailed: '登录失败,请检查账号或密码。',
|
||||
loginSuccess: '登录成功,正在进入控制台。',
|
||||
loginTitle: '登录 Planet 控制台',
|
||||
newPassword: '新密码',
|
||||
password: '密码',
|
||||
passwordHint: '至少 8 位',
|
||||
passwordResetSuccess: '密码已重置,请用新密码登录。',
|
||||
recoveryCodeSent: '若该邮箱已注册,验证码已发送。请到邮箱查收。',
|
||||
register: '注册',
|
||||
registerAccount: '注册账户',
|
||||
registerDescription: '创建账号后需要完成邮箱验证,验证成功会自动进入控制台。',
|
||||
resend: '重新发送验证码',
|
||||
resendCountdown: '重发 ({{seconds}}s)',
|
||||
resendSuccess: '验证码已重发。',
|
||||
resetPassword: '重置密码',
|
||||
sendCode: '发送验证码',
|
||||
updateEmail: '修改邮箱',
|
||||
username: '用户名',
|
||||
usernameHint: '3-50 个字符',
|
||||
verificationSent: '验证码已发送到邮箱。',
|
||||
verifyAndLogin: '验证并登录',
|
||||
verifyEmail: '验证邮箱',
|
||||
verifyEmailDescription: '输入邮箱验证码后会自动登录并进入控制台。',
|
||||
welcomeBack: '欢迎回来',
|
||||
shell: {
|
||||
product: 'Planet',
|
||||
subtitle: 'Operations Console',
|
||||
kicker: '现代控制台',
|
||||
title: '把数据、告警、AI 和 Earth 运维放在同一个清爽工作台。',
|
||||
description: '控制台默认进入现代化工作流,登录后直接使用 `/admin` 即可。',
|
||||
},
|
||||
},
|
||||
docs: {
|
||||
brandMark: '智',
|
||||
brandTitle: '智能星球文档',
|
||||
brandSubtitle: '开发者和用户手册',
|
||||
documentUnavailable: '文档不可用',
|
||||
docs: '文档',
|
||||
footerLanguage: 'Language',
|
||||
footerTheme: 'Theme',
|
||||
loading: '加载中...',
|
||||
loginRequired: '需要登录',
|
||||
loginRequiredDescription: '这份文档需要登录并具备对应 Gatekeeper 权限组后才能阅读。',
|
||||
goToLogin: '前往登录',
|
||||
forbidden: '无权访问',
|
||||
forbiddenDescription: '当前账号没有阅读这份文档所需的 Gatekeeper 权限组。',
|
||||
notFound: '文档未找到',
|
||||
notFoundDescription: '请求的文档不存在,或当前语言没有对应内容。',
|
||||
returnOverview: '返回文档首页',
|
||||
searchLabel: '搜索文档',
|
||||
searchPlaceholder: '搜索文档...',
|
||||
searchEmpty: '未找到匹配文档',
|
||||
toc: '本页目录',
|
||||
tocEmpty: '暂无章节',
|
||||
},
|
||||
markdown: {
|
||||
copyCode: '复制代码',
|
||||
copied: '已复制',
|
||||
copiedCode: '已复制代码',
|
||||
copyChartSource: '复制图表源码',
|
||||
copiedChartSource: '已复制图表源码',
|
||||
expandMermaid: '放大查看 Mermaid 图表',
|
||||
clickToExpand: '点击放大查看',
|
||||
closeMermaid: '关闭 Mermaid 图表查看器',
|
||||
mermaidViewer: 'Mermaid 图表查看器',
|
||||
mermaidRenderFailed: 'Mermaid 渲染失败',
|
||||
viewerHint: '拖拽移动 · 滚轮缩放 · 点击空白关闭',
|
||||
},
|
||||
users: {
|
||||
actions: '操作',
|
||||
active: '活跃',
|
||||
addUser: '添加用户',
|
||||
clearSearch: '清空搜索',
|
||||
confirmDelete: '确认删除',
|
||||
confirmDeleteDescription: '确定要删除用户 {{username}} 吗?',
|
||||
createSuccess: '创建成功',
|
||||
deleteFailed: '删除失败',
|
||||
deleteSuccess: '删除成功',
|
||||
description: '维护后台账号、角色与文档权限组。',
|
||||
disabled: '禁用',
|
||||
edit: '编辑',
|
||||
editUser: '编辑用户',
|
||||
gatekeeperGroups: 'Gatekeeper 权限组',
|
||||
retryLater: '请稍后重试',
|
||||
role: '角色',
|
||||
searchPlaceholder: '搜索用户、邮箱、角色',
|
||||
status: '状态',
|
||||
submit: '提交',
|
||||
unconfigured: '未配置',
|
||||
updateSuccess: '更新成功',
|
||||
roles: {
|
||||
super_admin: '超级管理员',
|
||||
admin: '管理员',
|
||||
operator: '操作员',
|
||||
viewer: '只读用户',
|
||||
},
|
||||
gatekeeper: {
|
||||
docs_user: '文档:用户文档',
|
||||
docs_developer: '文档:开发文档',
|
||||
docs_admin: '文档:管理/运维文档',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const enUS = {
|
||||
app: {
|
||||
title: 'Intelligent Planet Plan',
|
||||
routeLoading: 'Loading',
|
||||
},
|
||||
common: {
|
||||
cancel: 'Cancel',
|
||||
close: 'Close',
|
||||
confirm: 'Confirm',
|
||||
delete: 'Delete',
|
||||
language: 'Language',
|
||||
loading: 'Loading',
|
||||
noData: 'No data',
|
||||
operationFailed: 'Operation failed',
|
||||
page: 'Page {{page}} / {{totalPages}}, {{total}} total',
|
||||
previousPage: 'Previous',
|
||||
nextPage: 'Next',
|
||||
selectRow: 'Select row',
|
||||
selectVisibleRows: 'Select visible rows',
|
||||
theme: 'Theme',
|
||||
themeLight: 'Light',
|
||||
themeDark: 'Dark',
|
||||
themeSystem: 'System',
|
||||
themeFollowSystem: 'Follow system',
|
||||
zh: '中文',
|
||||
en: 'EN',
|
||||
},
|
||||
admin: {
|
||||
brandTitle: 'Intelligent Planet',
|
||||
brandSubtitle: 'Console',
|
||||
collapseMenu: 'Collapse menu',
|
||||
expandMenu: 'Expand menu',
|
||||
openNav: 'Open navigation',
|
||||
closeNav: 'Close navigation',
|
||||
logout: 'Log out',
|
||||
greeting: 'Hi, {{name}}',
|
||||
version: 'Version',
|
||||
themeControl: 'Console theme',
|
||||
languageControl: 'Console language',
|
||||
expandPreferences: 'Expand preferences',
|
||||
collapsePreferences: 'Collapse preferences',
|
||||
search: {
|
||||
label: 'Search features, settings, and text',
|
||||
placeholder: 'Search features, settings, and text',
|
||||
current: 'Current: {{label}}',
|
||||
results: 'Admin search results',
|
||||
loading: 'Loading search index...',
|
||||
empty: 'No matching content',
|
||||
pageContext: 'Page',
|
||||
},
|
||||
groups: {
|
||||
overview: 'Overview',
|
||||
collection: 'Collection and Data',
|
||||
observability: 'Observability',
|
||||
alerts: 'Alerts and Analysis',
|
||||
ops: 'Operations and Settings',
|
||||
},
|
||||
routes: {
|
||||
dashboard: 'Dashboard',
|
||||
earth: 'Intelligent Planet',
|
||||
docs: 'Docs',
|
||||
datasources: 'Datasources',
|
||||
data: 'Collected Data',
|
||||
bgp: 'BGP Observatory',
|
||||
systemAlerts: 'System Alerts',
|
||||
bgpAlerts: 'BGP Alerts',
|
||||
situationalAlerts: 'Situational Alerts',
|
||||
ai: 'AI',
|
||||
earthContent: 'Planet Content',
|
||||
collectionManagement: 'Collection Management',
|
||||
logs: 'System Logs',
|
||||
users: 'User Management',
|
||||
settings: 'System Settings',
|
||||
},
|
||||
sections: {
|
||||
alerts: 'Alert Records',
|
||||
aiIntegrations: 'Model Providers',
|
||||
aiTools: 'Tool Calls',
|
||||
aiPrompts: 'Prompts',
|
||||
aiPlayground: 'Playground',
|
||||
bgpOverview: 'BGP',
|
||||
collectionHistory: 'Collection History / Snapshots',
|
||||
collectorCredentials: 'Collectors',
|
||||
collectors: 'Collection Schedule',
|
||||
earthAssets: 'Boundary Accuracy',
|
||||
earthBrand: 'Branding',
|
||||
logsSources: 'Log Sources',
|
||||
newsSources: 'News Sources',
|
||||
notifications: 'Notification Policy',
|
||||
security: 'Security Policy',
|
||||
settingsSystem: 'System Display',
|
||||
smtp: 'SMTP Email',
|
||||
tv: 'TV Streams',
|
||||
},
|
||||
},
|
||||
auth: {
|
||||
accountRecovery: 'Account recovery',
|
||||
alreadyHaveAccount: 'Already have an account? Log in',
|
||||
backToLogin: 'Back to login',
|
||||
code: 'Verification code',
|
||||
codeSent: 'A 6-digit code was sent to <strong>{{email}}</strong>. It is valid for 10 minutes.',
|
||||
createAccount: 'Create account',
|
||||
email: 'Email',
|
||||
emailVerification: 'Email verification',
|
||||
emailNotVerified: 'Email is not verified. Please verify your email first.',
|
||||
forgotPassword: 'Forgot password?',
|
||||
forgotPasswordDescription: 'Reset your console password with an email verification code.',
|
||||
forgotPasswordTitle: 'Reset password',
|
||||
loginButton: 'Log in',
|
||||
loginDescription: 'Use your admin account to enter the operations workspace.',
|
||||
loginFailed: 'Login failed. Check your account or password.',
|
||||
loginSuccess: 'Login succeeded. Opening the console.',
|
||||
loginTitle: 'Log in to Planet Console',
|
||||
newPassword: 'New password',
|
||||
password: 'Password',
|
||||
passwordHint: 'At least 8 characters',
|
||||
passwordResetSuccess: 'Password reset. Log in with your new password.',
|
||||
recoveryCodeSent: 'If this email is registered, a code has been sent. Please check your inbox.',
|
||||
register: 'Register',
|
||||
registerAccount: 'Register account',
|
||||
registerDescription: 'Create an account, verify your email, then enter the console automatically.',
|
||||
resend: 'Resend code',
|
||||
resendCountdown: 'Resend ({{seconds}}s)',
|
||||
resendSuccess: 'Verification code resent.',
|
||||
resetPassword: 'Reset password',
|
||||
sendCode: 'Send code',
|
||||
updateEmail: 'Change email',
|
||||
username: 'Username',
|
||||
usernameHint: '3-50 characters',
|
||||
verificationSent: 'Verification code sent to your email.',
|
||||
verifyAndLogin: 'Verify and log in',
|
||||
verifyEmail: 'Verify email',
|
||||
verifyEmailDescription: 'Enter the email verification code to log in and open the console.',
|
||||
welcomeBack: 'Welcome back',
|
||||
shell: {
|
||||
product: 'Planet',
|
||||
subtitle: 'Operations Console',
|
||||
kicker: 'Modern console',
|
||||
title: 'Bring data, alerts, AI, and Earth operations into one focused workspace.',
|
||||
description: 'The console opens the modern workflow by default. Use `/admin` after login.',
|
||||
},
|
||||
},
|
||||
docs: {
|
||||
brandMark: 'IP',
|
||||
brandTitle: 'Intelligent Planet Docs',
|
||||
brandSubtitle: 'Developer & User Guide',
|
||||
documentUnavailable: 'Document unavailable',
|
||||
docs: 'Docs',
|
||||
footerLanguage: 'Language',
|
||||
footerTheme: 'Theme',
|
||||
loading: 'Loading document...',
|
||||
loginRequired: 'Login required',
|
||||
loginRequiredDescription: 'This document requires login and the matching Gatekeeper permission group.',
|
||||
goToLogin: 'Go to login',
|
||||
forbidden: 'Permission required',
|
||||
forbiddenDescription: 'Your account does not have the Gatekeeper permission group required for this document.',
|
||||
notFound: 'Document not found',
|
||||
notFoundDescription: 'The requested guide does not exist or is not available in the current language.',
|
||||
returnOverview: 'Return to docs overview',
|
||||
searchLabel: 'Search docs',
|
||||
searchPlaceholder: 'Search guides, APIs, layers...',
|
||||
searchEmpty: 'No matching docs',
|
||||
toc: 'On this page',
|
||||
tocEmpty: 'No sections',
|
||||
},
|
||||
markdown: {
|
||||
copyCode: 'Copy code',
|
||||
copied: 'Copied',
|
||||
copiedCode: 'Code copied',
|
||||
copyChartSource: 'Copy chart source',
|
||||
copiedChartSource: 'Chart source copied',
|
||||
expandMermaid: 'Expand Mermaid diagram',
|
||||
clickToExpand: 'Click to expand',
|
||||
closeMermaid: 'Close Mermaid diagram viewer',
|
||||
mermaidViewer: 'Mermaid diagram viewer',
|
||||
mermaidRenderFailed: 'Mermaid render failed',
|
||||
viewerHint: 'Drag to pan · Scroll to zoom · Click blank space to close',
|
||||
},
|
||||
users: {
|
||||
actions: 'Actions',
|
||||
active: 'Active',
|
||||
addUser: 'Add user',
|
||||
clearSearch: 'Clear search',
|
||||
confirmDelete: 'Confirm deletion',
|
||||
confirmDeleteDescription: 'Delete user {{username}}?',
|
||||
createSuccess: 'Created',
|
||||
deleteFailed: 'Delete failed',
|
||||
deleteSuccess: 'Deleted',
|
||||
description: 'Maintain console accounts, roles, and Docs permission groups.',
|
||||
disabled: 'Disabled',
|
||||
edit: 'Edit',
|
||||
editUser: 'Edit user',
|
||||
gatekeeperGroups: 'Gatekeeper groups',
|
||||
retryLater: 'Please try again later',
|
||||
role: 'Role',
|
||||
searchPlaceholder: 'Search users, email, or role',
|
||||
status: 'Status',
|
||||
submit: 'Submit',
|
||||
unconfigured: 'Not configured',
|
||||
updateSuccess: 'Updated',
|
||||
roles: {
|
||||
super_admin: 'Super admin',
|
||||
admin: 'Admin',
|
||||
operator: 'Operator',
|
||||
viewer: 'Viewer',
|
||||
},
|
||||
gatekeeper: {
|
||||
docs_user: 'Docs: user docs',
|
||||
docs_developer: 'Docs: developer docs',
|
||||
docs_admin: 'Docs: admin / ops docs',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const resources = {
|
||||
'zh-CN': { translation: zhCN },
|
||||
'en-US': { translation: enUS },
|
||||
} as const
|
||||
@@ -63,6 +63,7 @@ select {
|
||||
}
|
||||
|
||||
.auth-shell__panel {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -70,6 +71,13 @@ select {
|
||||
padding: clamp(28px, 5vw, 56px);
|
||||
}
|
||||
|
||||
.auth-shell__language {
|
||||
position: absolute;
|
||||
top: 34px;
|
||||
right: 34px;
|
||||
width: 118px;
|
||||
}
|
||||
|
||||
.auth-shell__brand {
|
||||
position: absolute;
|
||||
top: 34px;
|
||||
@@ -117,13 +125,13 @@ select {
|
||||
color: #2563eb;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.08em;
|
||||
letter-spacing: 0;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.auth-shell__heading h1 {
|
||||
margin-top: 10px;
|
||||
font-size: clamp(28px, 4vw, 38px);
|
||||
font-size: 38px;
|
||||
line-height: 1.12;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
@@ -240,7 +248,7 @@ select {
|
||||
max-width: 720px;
|
||||
margin-top: 14px;
|
||||
color: #081424;
|
||||
font-size: clamp(30px, 5vw, 52px);
|
||||
font-size: 52px;
|
||||
line-height: 1.05;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
@@ -266,4 +274,8 @@ select {
|
||||
min-height: calc(100vh - 20px);
|
||||
border-radius: 22px;
|
||||
}
|
||||
|
||||
.auth-shell__heading h1 {
|
||||
font-size: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import { registerAdminRuntimeErrorHandlers } from './admin/runtimeLogs'
|
||||
import './i18n'
|
||||
import './index.css'
|
||||
|
||||
registerAdminRuntimeErrorHandlers()
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { ArrowLeft, Loader2, Sparkles } from 'lucide-react'
|
||||
import { type FormEvent, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import SegmentedControl from '../../components/SegmentedControl/SegmentedControl'
|
||||
import { localeOptions, useLocale, type SupportedLocale } from '../../i18n/locale'
|
||||
|
||||
interface AuthShellProps {
|
||||
eyebrow: string
|
||||
@@ -11,14 +14,30 @@ interface AuthShellProps {
|
||||
}
|
||||
|
||||
export function AuthShell({ eyebrow, title, description, children, aside }: AuthShellProps) {
|
||||
const { t } = useTranslation()
|
||||
const { locale, setLocale } = useLocale()
|
||||
const languageOptions = localeOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: t(option.labelKey),
|
||||
title: t(option.titleKey),
|
||||
}))
|
||||
|
||||
return (
|
||||
<main className="auth-shell">
|
||||
<section className="auth-shell__panel">
|
||||
<SegmentedControl<SupportedLocale>
|
||||
ariaLabel={t('common.language')}
|
||||
className="auth-shell__language"
|
||||
options={languageOptions}
|
||||
scale={0.78}
|
||||
value={locale}
|
||||
onChange={setLocale}
|
||||
/>
|
||||
<div className="auth-shell__brand">
|
||||
<span className="auth-shell__logo"><Sparkles size={20} /></span>
|
||||
<div>
|
||||
<strong>Planet</strong>
|
||||
<span>Operations Console</span>
|
||||
<strong>{t('auth.shell.product')}</strong>
|
||||
<span>{t('auth.shell.subtitle')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="auth-shell__heading">
|
||||
@@ -31,9 +50,9 @@ export function AuthShell({ eyebrow, title, description, children, aside }: Auth
|
||||
<aside className="auth-shell__aside">
|
||||
{aside || (
|
||||
<>
|
||||
<span className="auth-shell__aside-kicker">现代控制台</span>
|
||||
<h2>把数据、告警、AI 和 Earth 运维放在同一个清爽工作台。</h2>
|
||||
<p>控制台默认进入现代化工作流,登录后直接使用 `/admin` 即可。</p>
|
||||
<span className="auth-shell__aside-kicker">{t('auth.shell.kicker')}</span>
|
||||
<h2>{t('auth.shell.title')}</h2>
|
||||
<p>{t('auth.shell.description')}</p>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
@@ -71,10 +90,15 @@ export function AuthButton({
|
||||
loading,
|
||||
children,
|
||||
variant = 'primary',
|
||||
type = 'button',
|
||||
disabled,
|
||||
className,
|
||||
...props
|
||||
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { loading?: boolean; variant?: 'primary' | 'secondary' | 'ghost' }) {
|
||||
const buttonClassName = ['auth-button', `auth-button--${variant}`, className].filter(Boolean).join(' ')
|
||||
|
||||
return (
|
||||
<button className={`auth-button auth-button--${variant}`} disabled={props.disabled || loading} {...props}>
|
||||
<button {...props} type={type} className={buttonClassName} disabled={disabled || loading}>
|
||||
{loading ? <Loader2 className="auth-button__spinner" size={16} /> : null}
|
||||
{children}
|
||||
</button>
|
||||
@@ -90,10 +114,12 @@ export function AuthLinks({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
export function BackToLogin() {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<Link className="auth-link auth-link--back" to="/login">
|
||||
<ArrowLeft size={15} />
|
||||
返回登录
|
||||
{t('auth.backToLogin')}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@
|
||||
/* ─── Page shell ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
.docs-page {
|
||||
height: 100vh;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr);
|
||||
background: var(--d-bg);
|
||||
@@ -887,7 +887,7 @@
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.docs-toc__nav {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import axios from 'axios'
|
||||
|
||||
import MarkdownRenderer from '../../components/MarkdownRenderer/MarkdownRenderer'
|
||||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||||
import SegmentedControl from '../../components/SegmentedControl/SegmentedControl'
|
||||
import { localeFromDocsLang, useLocale } from '../../i18n/locale'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import {
|
||||
createHeadingIdResolver,
|
||||
@@ -46,11 +48,6 @@ function getHashFromHref(href: string): string {
|
||||
return hashIndex >= 0 ? href.slice(hashIndex) : ''
|
||||
}
|
||||
|
||||
function readStoredLang(): DocsLang {
|
||||
const stored = localStorage.getItem('docs-lang')
|
||||
return stored === 'en' ? 'en' : 'zh'
|
||||
}
|
||||
|
||||
function readStoredThemeMode(): DocsThemeMode {
|
||||
const stored = localStorage.getItem('docs-theme')
|
||||
if (stored === 'system' || stored === 'light' || stored === 'dark') {
|
||||
@@ -69,9 +66,11 @@ function getSystemTheme(): 'light' | 'dark' {
|
||||
export default function Docs() {
|
||||
const { slug } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation()
|
||||
const { docsLang, setLocale } = useLocale()
|
||||
const { token } = useAuthStore()
|
||||
const lang = docsLang
|
||||
|
||||
const [lang, setLang] = useState<DocsLang>(readStoredLang)
|
||||
const [themeMode, setThemeMode] = useState<DocsThemeMode>(readStoredThemeMode)
|
||||
const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(getSystemTheme)
|
||||
const [catalogItems, setCatalogItems] = useState<DocsCatalogItem[]>([])
|
||||
@@ -94,14 +93,14 @@ export default function Docs() {
|
||||
const groupedEntries = useMemo(() => groupDocsEntries(docsEntries), [docsEntries])
|
||||
const effectiveTheme = themeMode === 'system' ? systemTheme : themeMode
|
||||
const langOptions = useMemo(() => [
|
||||
{ value: 'zh' as const, label: '中文' },
|
||||
{ value: 'en' as const, label: 'EN' },
|
||||
], [])
|
||||
{ value: 'zh' as const, label: t('common.zh') },
|
||||
{ value: 'en' as const, label: t('common.en') },
|
||||
], [t])
|
||||
const themeOptions = useMemo(() => [
|
||||
{
|
||||
value: 'light' as const,
|
||||
label: '浅色',
|
||||
title: '浅色',
|
||||
label: t('common.themeLight'),
|
||||
title: t('common.themeLight'),
|
||||
icon: (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
@@ -111,8 +110,8 @@ export default function Docs() {
|
||||
},
|
||||
{
|
||||
value: 'system' as const,
|
||||
label: '系统',
|
||||
title: '跟随系统',
|
||||
label: t('common.themeSystem'),
|
||||
title: t('common.themeFollowSystem'),
|
||||
icon: (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
|
||||
@@ -122,20 +121,19 @@ export default function Docs() {
|
||||
},
|
||||
{
|
||||
value: 'dark' as const,
|
||||
label: '深色',
|
||||
title: '深色',
|
||||
label: t('common.themeDark'),
|
||||
title: t('common.themeDark'),
|
||||
icon: (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
], [])
|
||||
], [t])
|
||||
|
||||
const handleLangChange = useCallback((newLang: DocsLang) => {
|
||||
setLang(newLang)
|
||||
localStorage.setItem('docs-lang', newLang)
|
||||
}, [])
|
||||
setLocale(localeFromDocsLang(newLang))
|
||||
}, [setLocale])
|
||||
|
||||
const handleThemeModeChange = useCallback((nextMode: DocsThemeMode) => {
|
||||
setThemeMode(nextMode)
|
||||
@@ -310,13 +308,13 @@ export default function Docs() {
|
||||
<main className="docs-page" data-theme={effectiveTheme}>
|
||||
<aside className="docs-sidebar" aria-label="Documentation navigation">
|
||||
<Link className="docs-brand" to="/docs">
|
||||
<span className="docs-brand__mark">智</span>
|
||||
<span className="docs-brand__mark">{t('docs.brandMark')}</span>
|
||||
<span>
|
||||
<span className="docs-brand__title">
|
||||
{lang === 'zh' ? '智能星球文档' : 'Intelligent Planet Docs'}
|
||||
{t('docs.brandTitle')}
|
||||
</span>
|
||||
<span className="docs-brand__subtitle">
|
||||
{lang === 'zh' ? '开发者和用户手册' : 'Developer & User Guide'}
|
||||
{t('docs.brandSubtitle')}
|
||||
</span>
|
||||
</span>
|
||||
</Link>
|
||||
@@ -359,7 +357,7 @@ export default function Docs() {
|
||||
<footer className="docs-sidebar-footer">
|
||||
<div className="docs-footer-row docs-footer-row--language">
|
||||
<SegmentedControl
|
||||
ariaLabel="Language"
|
||||
ariaLabel={t('docs.footerLanguage')}
|
||||
className="docs-lang-toggle"
|
||||
options={langOptions}
|
||||
scale={FOOTER_CONTROL_SCALE}
|
||||
@@ -370,7 +368,7 @@ export default function Docs() {
|
||||
|
||||
<div className="docs-footer-row">
|
||||
<SegmentedControl
|
||||
ariaLabel="Theme"
|
||||
ariaLabel={t('docs.footerTheme')}
|
||||
className="docs-theme-toggle"
|
||||
options={themeOptions}
|
||||
scale={FOOTER_CONTROL_SCALE}
|
||||
@@ -385,16 +383,16 @@ export default function Docs() {
|
||||
<header className="docs-header">
|
||||
<div>
|
||||
<p className="docs-header__eyebrow">
|
||||
{activeHeaderEntry ? getDocsGroupLabel(activeHeaderEntry.group, lang) : lang === 'zh' ? '文档' : 'Docs'}
|
||||
{activeHeaderEntry ? getDocsGroupLabel(activeHeaderEntry.group, lang) : t('docs.docs')}
|
||||
</p>
|
||||
<h1 className="docs-header__title">
|
||||
{activeHeaderEntry?.title || (lang === 'zh' ? '文档不可用' : 'Document unavailable')}
|
||||
{activeHeaderEntry?.title || t('docs.documentUnavailable')}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="docs-search" ref={searchRef}>
|
||||
<label className="docs-search__label" htmlFor="docs-search-input">
|
||||
{lang === 'zh' ? '搜索文档' : 'Search docs'}
|
||||
{t('docs.searchLabel')}
|
||||
</label>
|
||||
<input
|
||||
id="docs-search-input"
|
||||
@@ -409,7 +407,7 @@ export default function Docs() {
|
||||
setIsSearchOpen(true)
|
||||
}
|
||||
}}
|
||||
placeholder={lang === 'zh' ? '搜索文档...' : 'Search guides, APIs, layers...'}
|
||||
placeholder={t('docs.searchPlaceholder')}
|
||||
type="search"
|
||||
/>
|
||||
{shouldShowSearchResults && (
|
||||
@@ -432,7 +430,7 @@ export default function Docs() {
|
||||
))
|
||||
) : (
|
||||
<div className="docs-search__empty">
|
||||
{lang === 'zh' ? '未找到匹配文档' : 'No matching docs'}
|
||||
{t('docs.searchEmpty')}
|
||||
</div>
|
||||
)}
|
||||
</Scrollbar>
|
||||
@@ -445,7 +443,7 @@ export default function Docs() {
|
||||
<Scrollbar className="docs-article" viewportRef={articleRef}>
|
||||
{isCatalogLoading || isLoading ? (
|
||||
<div className="docs-state">
|
||||
{lang === 'zh' ? '加载中...' : 'Loading document...'}
|
||||
{t('docs.loading')}
|
||||
</div>
|
||||
) : docError === 'none' ? (
|
||||
<MarkdownRenderer
|
||||
@@ -458,33 +456,27 @@ export default function Docs() {
|
||||
<div className="docs-not-found">
|
||||
{docError === 'unauthenticated' ? (
|
||||
<>
|
||||
<h2>{lang === 'zh' ? '需要登录' : 'Login required'}</h2>
|
||||
<h2>{t('docs.loginRequired')}</h2>
|
||||
<p>
|
||||
{lang === 'zh'
|
||||
? '这份文档需要登录并具备对应 Gatekeeper 权限组后才能阅读。'
|
||||
: 'This document requires login and the matching Gatekeeper permission group.'}
|
||||
{t('docs.loginRequiredDescription')}
|
||||
</p>
|
||||
<Link to="/admin">{lang === 'zh' ? '前往登录' : 'Go to login'}</Link>
|
||||
<Link to="/admin">{t('docs.goToLogin')}</Link>
|
||||
</>
|
||||
) : docError === 'forbidden' ? (
|
||||
<>
|
||||
<h2>{lang === 'zh' ? '无权访问' : 'Permission required'}</h2>
|
||||
<h2>{t('docs.forbidden')}</h2>
|
||||
<p>
|
||||
{lang === 'zh'
|
||||
? '当前账号没有阅读这份文档所需的 Gatekeeper 权限组。'
|
||||
: 'Your account does not have the Gatekeeper permission group required for this document.'}
|
||||
{t('docs.forbiddenDescription')}
|
||||
</p>
|
||||
<Link to="/docs">{lang === 'zh' ? '返回文档首页' : 'Return to docs overview'}</Link>
|
||||
<Link to="/docs">{t('docs.returnOverview')}</Link>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2>{lang === 'zh' ? '文档未找到' : 'Document not found'}</h2>
|
||||
<h2>{t('docs.notFound')}</h2>
|
||||
<p>
|
||||
{lang === 'zh'
|
||||
? '请求的文档不存在,或当前语言没有对应内容。'
|
||||
: 'The requested guide does not exist or is not available in the current language.'}
|
||||
{t('docs.notFoundDescription')}
|
||||
</p>
|
||||
<Link to="/docs">{lang === 'zh' ? '返回文档首页' : 'Return to docs overview'}</Link>
|
||||
<Link to="/docs">{t('docs.returnOverview')}</Link>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -494,7 +486,7 @@ export default function Docs() {
|
||||
<aside className="docs-toc" aria-label="Document table of contents">
|
||||
<Scrollbar className="docs-toc__inner">
|
||||
<h2 className="docs-toc__title">
|
||||
{lang === 'zh' ? '本页目录' : 'On this page'}
|
||||
{t('docs.toc')}
|
||||
</h2>
|
||||
{headings.length > 0 ? (
|
||||
<nav className="docs-toc__nav">
|
||||
@@ -515,7 +507,7 @@ export default function Docs() {
|
||||
</nav>
|
||||
) : (
|
||||
<p className="docs-toc__empty">
|
||||
{lang === 'zh' ? '暂无章节' : 'No sections'}
|
||||
{t('docs.tocEmpty')}
|
||||
</p>
|
||||
)}
|
||||
</Scrollbar>
|
||||
|
||||
6
frontend/src/pages/Earth/Earth.css
Normal file
@@ -0,0 +1,6 @@
|
||||
.earth-page-frame {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
display: block;
|
||||
}
|
||||
@@ -1,16 +1,13 @@
|
||||
import './Earth.css'
|
||||
|
||||
function Earth() {
|
||||
return (
|
||||
<iframe
|
||||
className="earth-page-frame"
|
||||
src="/earth/index.html"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
border: "none",
|
||||
display: "block",
|
||||
}}
|
||||
title="3D Earth"
|
||||
/>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export default Earth;
|
||||
export default Earth
|
||||
|
||||