feat(match): 同步比赛计时与装甲板扣血许可
构建客户端 / 检查(类型 + 单元测试) (push) Canceled after 0s
构建客户端 / Linux x64(deb + AppImage) (push) Canceled after 0s
构建客户端 / Windows x64(NSIS 安装包) (push) Canceled after 0s
构建客户端 / macOS 通用(.app + .dmg) (push) Canceled after 0s

- feat(client): 增加裁判比赛计时、技术暂停与选手端局域网同步
- feat(armor): 红蓝共用通用固件,按客户端选队并显示网络连接状态
- feat(armor): 仅在对局进行中允许扣血,其他阶段保留受击闪烁
- feat(client): 将计时置于血条中间并增加开赛前五秒全屏动画
- fix(client): 修复连续血条、对手镜像和图传断连灰度遮罩
- fix(client): 统一界面中文字体并整理各页面文案
- fix(maintenance): 备份迁移装甲板分区,恢复 SDK 构建与固件打包
- refactor(repo): 按 armor、vt 和 client 整理工程与脚本,移除旧参考实现
- test: 补充线路、受击许可、回环 UDP、维护和 HUD 验证
- docs: 同步构建、协议、比赛控制和硬件验证边界

验证:前端构建与 19 项相关测试通过;核心 91 项单元测试与 2 项回环 UDP 集成测试通过;装甲板规则 25 项、线路 26 项、Tauri 51 项测试通过;独立探测器 5 项与目录回归 4 项通过。完成 C3 两组阈值实际编译、导出与 ZIP 校验,检查 900×600 / 1280×720 页面、倒计时和随包中文字体。
未执行烧录、板上运行、跨电脑广播或硬件稳定性验证。
This commit is contained in:
sloray committed 2026-10-22 17:08:49 +08:00
1 parent 72901939c6
commit f7ca246b68
581 files changed
+6596 -7683

No files matched your search

+501
View File
@@ -0,0 +1,501 @@
/**
* 应用外壳:启动序列、连通道、拿状态、按身份分流、管住解锁流程。
*
* # 状态来自哪里
*
* 后端每 200 ms 推一份完整快照,前端不轮询。唯一在本地维护的是 **HUD 草稿**:滑杆要即时
* 反馈,等 300 ms 的后端往返会很黏手。草稿改动后节流保存,保存的结果就是后端的配置。
*
* # 解锁流程
*
* 需要密码的动作有三处入口:打开设置面板、点关闭窗口(后端会推 `confirmQuit`)、以及
* 任何一次被后端拒绝的改动。三条路径都汇到同一个 `UnlockDialog`,解锁成功后执行挂起的
* 那个动作。后端才是真正的闸门,这里只负责把话说清楚。
*
* # 外壳管什么
*
* 裁判端保留顶栏与通讯带,用户端以全画面 HUD 和 ESC 菜单为入口。
* 外壳统一管理解锁、设置、维护页与模态状态,各页面负责自己的画面和读数。
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { Boot } from "./components/Boot";
import { SetupPassword, RolePicker } from "./components/Gate";
import { CommStrip, TopBar } from "./components/TopBar";
import { Toasts, type ToastItem } from "./components/Toasts";
import { UnlockDialog } from "./components/UnlockDialog";
import { api } from "./lib/ipc";
import { startStream, streamClient, useAppStore } from "./lib/store";
import { useFullscreen } from "./lib/use-fullscreen";
import type { ConfigView, HudView, Snapshot } from "./lib/types";
import { MaintenancePage } from "./pages/MaintenancePage";
import { RefereePage } from "./pages/RefereePage";
import { TeamPage } from "./pages/TeamPage";
import { SettingsPanel } from "./components/SettingsPanel";
import { OperatorMenu } from "./components/OperatorMenu";
/** 解锁之后要做的那件事。 */
type Pending = { kind: "settings" } | { kind: "quit" } | { kind: "retry"; run: () => void };
/** 启动序列表最少要在屏幕上待多久。太短会像闪了一下,读不出"它在自检"。 */
const BOOT_MIN_MS = 1150;
/** 序列完成后的淡出时长,与 `.boot.is-leaving` 的动画一致。 */
const BOOT_EXIT_MS = 340;
export default function App() {
const { snapshot, connected, confirmQuit } = useAppStore();
const [url, setUrl] = useState<string | null>(null);
const [fatal, setFatal] = useState<string | null>(null);
const [hud, setHud] = useState<HudView | null>(null);
const [drawer, setDrawer] = useState(false);
const [drawerClosing, setDrawerClosing] = useState(false);
const [calibrating, setCalibrating] = useState(false);
const [unlockReason, setUnlockReason] = useState<string | null>(null);
const [pending, setPending] = useState<Pending | null>(null);
const [maintenance, setMaintenance] = useState(() => import.meta.env.DEV && !("__TAURI_INTERNALS__" in window) && new URLSearchParams(location.search).get("preview") === "maintenance");
const [operatorMenu, setOperatorMenu] = useState(false);
const [toasts, setToasts] = useState<ToastItem[]>([]);
const fullscreen = useFullscreen();
const hudInitialised = useRef(false);
// ---- 提示队列 ----
const pushToast = useCallback((kind: ToastItem["kind"], message: string) => {
const id = Date.now() + Math.random();
setToasts((current) => [...current.slice(-3), { id, kind, message }]);
}, []);
const dismissToast = useCallback((id: number) => {
setToasts((current) => current.filter((toast) => toast.id !== id));
}, []);
// 每条提示自己计时。错误留得久一点——现场是要照着那句话去查的。
useEffect(() => {
if (toasts.length === 0) return;
const timers = toasts.map((toast) =>
window.setTimeout(
() => dismissToast(toast.id),
toast.kind === "error" ? 12000 : 6000,
),
);
return () => timers.forEach((timer) => window.clearTimeout(timer));
}, [toasts, dismissToast]);
const onError = useCallback((message: string) => pushToast("error", message), [pushToast]);
const onInfo = useCallback((message: string) => pushToast("info", message), [pushToast]);
// ---- 启动序列 ----
const [fontsReady, setFontsReady] = useState(false);
const [minElapsed, setMinElapsed] = useState(false);
const [bootGone, setBootGone] = useState(false);
const [bootLeaving, setBootLeaving] = useState(false);
useEffect(() => {
let cancelled = false;
const done = () => {
if (!cancelled) setFontsReady(true);
};
const fonts = document.fonts;
if (fonts?.ready) {
// 字体全部落盘之后界面才出现:否则中文会先画成系统黑体再跳一次,整块布局跟着重排。
fonts.ready.then(done, done);
} else {
done();
}
const timer = window.setTimeout(() => {
if (!cancelled) setMinElapsed(true);
}, BOOT_MIN_MS);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, []);
const milestones = [
{ key: "fonts", label: "加载字体", code: "HARMONYOS · JETBRAINS", done: fontsReady },
{ key: "channel", label: "连接本机服务", code: "LOCAL IPC", done: url !== null || !!fatal },
{ key: "snapshot", label: "读取运行状态", code: "SNAPSHOT 200ms", done: snapshot !== null || !!fatal },
];
const sequenceDone = milestones.every((item) => item.done);
const progress =
(fontsReady ? 0.32 : 0) + (url !== null || fatal ? 0.24 : 0) + (snapshot !== null || fatal ? 0.44 : 0);
// 两个 effect 而不是一个,是有原因的:把"开始淡出"和"淡出之后卸载"写进同一个 effect
// 时,`setBootLeaving(true)` 会让它自己重跑,React 在重跑之前先调用上一次的清理函数,
// 于是那个 `setTimeout` 在设置的同一帧里就被 `clearTimeout` 掉了——启动页永远停在那里
// 半透明地盖着整个界面。拆成两段之后,第二段只在 `bootLeaving` 变真时启动。
useEffect(() => {
if (!sequenceDone || !minElapsed) return;
setBootLeaving(true);
}, [sequenceDone, minElapsed]);
useEffect(() => {
if (!bootLeaving) return;
const timer = window.setTimeout(() => setBootGone(true), BOOT_EXIT_MS);
return () => window.clearTimeout(timer);
}, [bootLeaving]);
// ---- 通道 ----
useEffect(() => {
void api.streamInfo().then(
(stream) => setUrl(stream.url),
(err) => setFatal(err instanceof Error ? err.message : String(err)),
);
}, []);
useEffect(() => {
if (!url) return;
const client = startStream(url);
return () => client.close();
}, [url]);
// ---- HUD 草稿 ----
useEffect(() => {
if (!snapshot || hudInitialised.current) return;
hudInitialised.current = true;
setHud(snapshot.config.hud);
}, [snapshot]);
const onConfig = useCallback((config: ConfigView) => {
// 绑定/身份改了:HUD 之外的东西都由快照带回来,这里只需要让 HUD 跟上(例如换了身份)。
setHud((current) => current ?? config.hud);
}, []);
/** 校准时拖动画面:偏移是按比例的,直接累加。 */
const onCalibrate = useCallback((dx: number, dy: number) => {
setHud((current) => {
if (!current) return current;
const clamp = (value: number) => Math.max(-0.5, Math.min(0.5, value));
return {
...current,
crosshair: {
...current.crosshair,
offsetX: clamp(current.crosshair.offsetX + dx),
offsetY: clamp(current.crosshair.offsetY + dy),
},
};
});
}, []);
// 校准改动也要落盘。和设置面板里的滑杆共用同一条节流路径。
useEffect(() => {
if (!hud || !calibrating) return;
const timer = window.setTimeout(() => {
void api.saveHud(hud).catch(() => undefined);
}, 600);
return () => window.clearTimeout(timer);
}, [hud, calibrating]);
// ---- 解锁 ----
const needsUnlock = useCallback((reason: string, next: Pending) => {
setUnlockReason(reason);
setPending(next);
}, []);
const openSettings = useCallback(() => {
if (!snapshot) return;
setOperatorMenu(false);
setDrawerClosing(false);
if (snapshot.role !== "referee" && !snapshot.unlocked) {
needsUnlock("修改图传板、装甲板绑定或队伍号需要密码。", { kind: "settings" });
return;
}
setDrawer(true);
}, [snapshot, needsUnlock]);
// 后端拦下了一次"关窗口/退出"。
useEffect(() => {
if (confirmQuit === 0) return;
needsUnlock("退出程序需要密码。", { kind: "quit" });
}, [confirmQuit, needsUnlock]);
const finishUnlock = useCallback(() => {
setUnlockReason(null);
const action = pending;
setPending(null);
switch (action?.kind) {
case "settings":
setDrawerClosing(false);
setDrawer(true);
break;
case "quit":
void api.quit().catch((err) => onError(err instanceof Error ? err.message : String(err)));
break;
case "retry":
action.run();
break;
default:
break;
}
void api.refresh();
}, [pending, onError]);
// ---- 快捷键 ----
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
const typing =
target?.tagName === "INPUT" ||
target?.tagName === "TEXTAREA" ||
target?.tagName === "SELECT" ||
target?.isContentEditable;
if (event.key === "Escape") {
if (event.repeat || maintenance || !bootGone || !snapshot?.config.roleChosen || (snapshot.role === "team" && !snapshot.config.passwordSet)) return;
event.preventDefault();
if (unlockReason) {
setUnlockReason(null);
setPending(null);
} else if (drawer) {
setCalibrating(false);
setDrawerClosing(true);
} else if (calibrating) {
setCalibrating(false);
if (hud) void api.saveHud(hud).catch(err => onError(String(err)));
setOperatorMenu(true);
} else if (snapshot.role === "team") {
setOperatorMenu(current => !current);
}
return;
}
if (typing) return;
// 裁判端保留原有桌面快捷键;用户端从 ESC 菜单进入设置。
if (snapshot?.role === "referee" && !maintenance && (event.ctrlKey || event.metaKey) && event.key === ",") {
event.preventDefault();
openSettings();
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [unlockReason, drawer, openSettings, maintenance, bootGone, snapshot, calibrating, hud, onError]);
// ---- 窗口标题 ----
useEffect(() => {
if (!snapshot) return;
const suffix = snapshot.role === "team" ? "用户端" : "裁判端";
const extra = snapshot.demo ? "(演示模式)" : "";
// `getCurrentWindow()` 在浏览器预览里会直接抛(没有 Tauri 注入),所以整段包在
// try 里——标题设不上是小事,不能让一条 effect 把界面卸掉。
try {
void getCurrentWindow()
.setTitle(`RMIC::2026 — ${suffix}${extra}`)
.catch(() => undefined);
} catch {
// 预览模式:没有窗口。
}
}, [snapshot?.role, snapshot?.demo]);
// ---- 分支 ----
// 维护页不依赖身份、摄像头绑定或后端快照;先于所有门禁渲染,烧录完再返回原页面。
if (maintenance) {
return (
<MaintenancePage
onClose={() => setMaintenance(false)}
fullscreen={fullscreen.fullscreen}
onToggleFullscreen={() => void fullscreen.toggle()}
/>
);
}
if (!bootGone) {
return (
<Boot
milestones={milestones}
progress={progress}
fatal={fatal}
leaving={bootLeaving}
/>
);
}
// 序列走完但快照还没到:给一句话,而不是一块空白。
if (!snapshot) {
return (
<div className="splash">
<span className="splash__mark label">RMIC · 2026</span>
<h1 className="splash__title">正在读取运行状态</h1>
<p className="splash__text">
{connected ? "已连接,等待状态数据…" : "正在连接本机服务…"}
</p>
<div className="scan" style={{ width: 220 }} />
</div>
);
}
if (!snapshot.config.roleChosen) {
return (
<>
<RolePicker onOpenMaintenance={() => setMaintenance(true)} />
<Toasts toasts={toasts} onDismiss={dismissToast} />
</>
);
}
if (snapshot.role === "team" && !snapshot.config.passwordSet) {
return (
<>
<SetupPassword onOpenMaintenance={() => setMaintenance(true)} />
<Toasts toasts={toasts} onDismiss={dismissToast} />
</>
);
}
return (
<div className={`app app--${snapshot.role}`}>
{snapshot.role === "referee" && <TopBar
snapshot={snapshot}
connected={connected}
fullscreen={fullscreen.fullscreen}
onOpenSettings={openSettings}
onOpenMaintenance={() => setMaintenance(true)}
onToggleFullscreen={() => void fullscreen.toggle()}
/>}
{snapshot.role === "referee" && <CommStrip />}
<div className="app__stage">
{snapshot.role === "team" ? (
<TeamPage
snapshot={snapshot}
hud={hud ?? snapshot.config.hud}
calibrating={calibrating}
onCalibrate={onCalibrate}
/>
) : (
<RefereePage
snapshot={snapshot}
hud={hud ?? snapshot.config.hud}
onOpenSettings={openSettings}
onError={onError}
onInfo={onInfo}
/>
)}
</div>
<ChannelFault snapshot={snapshot} />
{operatorMenu && snapshot.role === "team" && !drawer && !unlockReason && <OperatorMenu
snapshot={snapshot} fullscreen={fullscreen.fullscreen} onClose={() => setOperatorMenu(false)}
onSettings={openSettings} onMaintenance={() => { setOperatorMenu(false); setMaintenance(true); }}
onFullscreen={() => void fullscreen.toggle()}
onQuit={() => { setOperatorMenu(false); if (!snapshot.unlocked) needsUnlock("退出程序需要密码。", { kind: "quit" }); else void api.quit().catch(err => onError(String(err))); }}
/>}
{drawer && (
<SettingsPanel
snapshot={snapshot}
connected={connected}
closing={drawerClosing}
onExitComplete={() => {
setDrawer(false);
setDrawerClosing(false);
if (snapshot.role === "team") setOperatorMenu(true);
}}
hud={hud ?? snapshot.config.hud}
onHud={setHud}
calibrating={calibrating}
onCalibrating={(active) => {
setCalibrating(active);
if (active) { setDrawer(false); setDrawerClosing(false); }
}}
onClose={() => {
setCalibrating(false);
setDrawerClosing(true);
}}
onNeedsUnlock={(reason) => needsUnlock(reason, { kind: "settings" })}
onError={onError}
onInfo={onInfo}
onConfig={onConfig}
/>
)}
{unlockReason && (
<UnlockDialog
reason={unlockReason}
onUnlocked={finishUnlock}
onCancel={() => {
setUnlockReason(null);
setPending(null);
}}
/>
)}
{calibrating && (
<div className="calibrate-bar">
<span className="calibrate-bar__mark label">CALIBRATE</span>
<span className="calibrate-bar__text">
拖动画面调整瞄准点,完成后点击“结束校准”。
</span>
<button type="button" className="btn btn--ghost" onClick={() => setCalibrating(false)}>
结束校准
</button>
</div>
)}
<Toasts toasts={toasts} onDismiss={dismissToast} />
</div>
);
}
/**
* 通道看门狗:后端在推、前端没连上时给一句明确的话。
*
* 这一条存在的理由很实际:画面不动时,第一件要分清的事是"后端没推"还是"前端没接上"。
* 后端快照里有 `clients`,所以这两件事可以分开说。
*/
function ChannelFault({ snapshot }: { snapshot: Snapshot }) {
const { connected } = useAppStore();
if (connected) return null;
let detail = "视频通道已断开,正在重连…";
try {
detail += `(已收到 ${streamClient().counters.frames} 帧,重连 ${streamClient().counters.reconnects} 次)`;
} catch {
// 通道还没建起来。
}
if (snapshot.clients === 0 && snapshot.uptimeMs > 5000) {
detail += " 本机服务尚未检测到界面连接。";
}
return (
<div className="fault" role="alert">
<span className="fault__mark label">LINK</span>
<span className="fault__text">{detail}</span>
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { useState } from "react";
import { Button } from "./controls";
import { maintenanceApi, selectMaintenanceDirectory, type ArmorBuildRequest, type BundleInfo } from "../lib/maintenance";
export function ArmorBuildPanel({ disabled, onBusy, onBuilt, onError }: {
disabled: boolean;
onBusy: (busy: boolean) => void;
onBuilt: (bundle: BundleInfo) => void;
onError: (message: string) => void;
}) {
const [request, setRequest] = useState<ArmorBuildRequest>({ repoPath: "", targetDir: "", idfPath: "", threshold: 2000, ssid: "", password: "", proxyUrl: "" });
const [building, setBuilding] = useState(false);
const [tab, setTab] = useState<"network" | "environment">("network");
const patch = (value: Partial<ArmorBuildRequest>) => setRequest(current => ({ ...current, ...value }));
const directory = async (key: "repoPath" | "targetDir" | "idfPath", title: string) => {
try { const path = await selectMaintenanceDirectory(title); if (path) patch({ [key]: path }); }
catch (err) { onError(String(err)); }
};
const build = async () => {
setBuilding(true); onBusy(true);
try { const bundle = await maintenanceApi.buildArmor(request); onBuilt(bundle); }
catch (err) { onError(err instanceof Error ? err.message : String(err)); }
finally { setBuilding(false); onBusy(false); }
};
const ready = request.repoPath && request.targetDir && request.ssid && Number.isInteger(request.threshold) && request.threshold >= 0 && request.threshold <= 4095;
if (building) return <div className="mnt-build__body"><div className="mnt-build__team">ESP32-C3 / 通用固件 / 阈值 {request.threshold}</div><p className="mnt-hint">编译和打包完成后,会自动加载固件包供检查。此步骤不会烧录设备。</p></div>;
return <div className="mnt-build">
<nav className="mnt-tabs" aria-label="编译参数"><button className={tab === "network" ? "is-active" : ""} onClick={() => setTab("network")}>01 / 连接参数</button><button className={tab === "environment" ? "is-active" : ""} onClick={() => setTab("environment")}>02 / 构建环境</button></nav>
<div className="mnt-build__body">
{tab === "network" ? <>
<div className="mnt-build__team">通用固件 / 红蓝共用</div>
<div className="mnt-build__fields">
<label><span>裁判系统 Wi-Fi 名称</span><input className="input" value={request.ssid} autoComplete="off" disabled={disabled} onChange={event => patch({ ssid: event.target.value })} /></label>
<label><span>Wi-Fi 密码(开放网络可留空)</span><input className="input" type="password" value={request.password} autoComplete="new-password" disabled={disabled} onChange={event => patch({ password: event.target.value })} /></label>
<label><span>受击阈值(0–4095)</span><input className="input" type="number" min={0} max={4095} step={1} value={request.threshold} disabled={disabled} onChange={event => patch({ threshold: Number(event.target.value) })} /></label>
</div>
<p className="mnt-hint">在客户端选择队伍后,装甲板会切换灯色。仅对局进行中允许扣血,其他阶段受击只闪灯。Wi-Fi 名称和密码会编入镜像,不改写 .env。</p>
</> : <>
<div className="mnt-build__fields">
{([["repoPath", "项目源码根目录", "选择含 armor/ 的项目根目录"], ["targetDir", "独立构建输出目录", "Windows 建议 C:\\c3vt(最多 10 字符)"], ["idfPath", "已有 ESP-IDF(可选)", "留空下载 v6.0.1"]] as const).map(([key, label, placeholder]) => <label key={key}><span>{label}</span><div className="mnt-row"><input className="input" value={request[key]} placeholder={placeholder} disabled={disabled} onChange={event => patch({ [key]: event.target.value })} /><Button disabled={disabled} onClick={() => void directory(key, label)}>浏览</Button></div></label>)}
<label><span>构建网络代理(可选,仅本次编译)</span><input className="input" value={request.proxyUrl} placeholder="http://127.0.0.1:端口;留空沿用进程环境" disabled={disabled} onChange={event => patch({ proxyUrl: event.target.value })} /></label>
</div>
<p className="mnt-hint">需要 Rust esp-1.97.0.0、ldproxy、Python、CMake 和 Ninja。代理仅用于 Git/Python 下载,仍会校验证书。</p>
</>}
<div className="mnt-task__actions">{tab === "network" ? <Button variant="primary" onClick={() => setTab("environment")}>下一步:构建环境</Button> : <><Button variant="primary" disabled={disabled || !ready} onClick={() => void build()}>{building ? "正在编译…" : "编译并加载固件包"}</Button><Button variant="ghost" disabled={disabled} onClick={() => setTab("network")}>上一步</Button></>}</div>
</div>
</div>;
}
+190
View File
@@ -0,0 +1,190 @@
/**
* 裁判端的装甲板发现列表。
*
* 场上到底连上了几块板子、分别自报哪一队、现在多少血、多久没广播了——现场"裁判端没显示
* 血量"时,这一张表就是第一眼看的地方:它能区分"板子根本没上线"、"上线了但队伍号烧反了"
* 和"只有一条上报在发"。
*
* # 每一行都在回答三个问题
*
* 左边那四个小格是 `platesSeen` 的位图:主板一次广播四条(`index` 0..3),四条都到齐才
* 会有点亮。只有一格亮着,几乎一定是配置或固件的问题——而这一眼就能看出来,不必去翻日志。
*
* 中间是静默时间,按新鲜度上色(<0.5 s 绿、<2 s 琥珀、再久红)。数字本身不够快,颜色
* 才是"现在有没有在说话"的答案。
*
* 右边是槽位归属。手动模式烧错固件时,这一列是唯一能证明"我以为的左右,和后端以为的左右
* 不是一回事"的地方。
*/
import { elapsed, teamColor, teamName } from "../lib/format";
import type { ArmorBoardDto, SlotsDto } from "../lib/types";
interface Props {
boards: ArmorBoardDto[];
slots: SlotsDto;
/** 两边显示的名字(裁判端可改)。缺省时回落到「队伍一 / 队伍二」。 */
names?: [string, string];
/** 把注意力放在某一队上;`null` 表示全部。 */
focusTeam?: number | null;
}
/** 静默多久还算"在说话"。与后端 `STALE_AFTER` 同一量级,但这里是给人看的,可以更敏感。 */
function silenceTone(online: boolean, silenceMs: number): "good" | "warn" | "bad" {
if (!online) return "bad";
if (silenceMs < 600) return "good";
if (silenceMs < 2000) return "warn";
return "bad";
}
/** 四格位图:这一块板子的四条上报各自到没到。 */
function Plates({ seen }: { seen: number }) {
return (
<span className="armor__plates" title={`四路上报位图:${seen.toString(2).padStart(4, "0")}`}>
{[0, 1, 2, 3].map((bit) => (
<span key={bit} className={`armor__plate${(seen >> bit) & 1 ? " is-on" : ""}`} />
))}
</span>
);
}
export function ArmorTable({ boards, slots, names, focusTeam = null }: Props) {
const shown = focusTeam === null ? boards : boards.filter((board) => board.team === focusTeam);
const hidden = boards.length - shown.length;
return (
<div className="armor">
<div className="armor__head">
<span className="armor__col armor__col--plates">四路</span>
<span className="armor__col">装甲板</span>
<span className="armor__col">地址</span>
<span className="armor__col">自报队伍</span>
<span className="armor__col armor__col--hp">血量</span>
<span className="armor__col">最近上报</span>
<span className="armor__col">槽位</span>
</div>
<div className="armor__rows">
{shown.length === 0 && (
<div className="armor__empty">
{boards.length === 0 ? (
<>
尚未收到装甲板数据。主板每 200 ms 广播一次;请检查供电,并确认主板与本机
处于同一网络。
</>
) : (
<>
本队暂无装甲板上报,另一队有 {hidden} 块。按 <kbd>0</kbd> 显示全部。
</>
)}
</div>
)}
{shown.map((board) => {
const assigned =
slots.armorA === board.id
? `左 · ${teamName(0, names)}`
: slots.armorB === board.id
? `右 · ${teamName(1, names)}`
: "未分配";
const tone = silenceTone(board.online, board.silenceMs);
return (
<div
key={board.id}
className={`armor__row${board.online ? "" : " is-offline"}${
assigned === "未分配" ? " is-unassigned" : ""
}`}
>
<span className="armor__col armor__col--plates">
<Plates seen={board.reportsAllPlates ? 0b1111 : board.platesSeen} />
</span>
<span className="armor__col num armor__id">{board.idText}</span>
<span className="armor__col num armor__addr">{board.addr}</span>
<span className="armor__col" style={{ color: teamColor(board.team) }}>
{teamName(board.team, names)}
<span className="armor__team-bit num">T{board.team}</span>
</span>
<span className="armor__col armor__col--hp">
<span className={`num armor__hp${board.hp === 0 ? " is-dead" : ""}`}>
{board.hp}
</span>
<span className="armor__hp-track" aria-hidden="true">
<span
className="armor__hp-fill"
style={{
width: `${Math.max(0, Math.min(100, board.hp))}%`,
background: board.hp === 0 ? "var(--error)" : teamColor(board.team),
}}
/>
</span>
</span>
<span className={`armor__col armor__silence is-${tone}`}>
<span className={`dot dot--${tone === "good" ? "live" : tone === "warn" ? "warn" : "dead"}`} />
{board.online ? `${elapsed(board.silenceMs)}前` : "离线"}
</span>
<span className="armor__col armor__slot">{assigned}</span>
</div>
);
})}
</div>
</div>
);
}
/** 一行只读读数,裁判端每格下面用。 */
export function StatsLine({
stats,
diagnostics,
}: {
stats:
| {
status: string;
online: boolean;
hasFrames: boolean;
fps: number;
width: number;
height: number;
framesShown: number;
framesDropped: number;
lossPercent: number;
datagrams: number;
lastFrameBytes: number;
gapMs: number | null;
}
| undefined;
diagnostics: boolean;
}) {
if (!stats) {
return (
<div className="statsline statsline--empty">
<span className="dot dot--dead" />
尚未收到这一路的数据
</div>
);
}
const parts: string[] = [];
parts.push(stats.hasFrames ? `${stats.fps.toFixed(1)} fps` : "—");
if (diagnostics && stats.hasFrames) {
parts.push(`${stats.width}×${stats.height}`);
parts.push(`${(stats.lastFrameBytes / 1024).toFixed(1)} kB/帧`);
parts.push(`丢 ${stats.framesDropped}(${stats.lossPercent.toFixed(1)}%)`);
}
return (
<div className={`statsline${stats.online ? "" : " is-offline"}`}>
<span className={`dot ${stats.online ? "dot--live" : "dot--dead"}`} />
<span className="statsline__status">{stats.status}</span>
<span className="statsline__sep" aria-hidden="true" />
<span className="statsline__nums num">{parts.join(" · ")}</span>
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
/**
* 启动序列。
*
* # 它不是假的过场
*
* 每一行都对应一件**真的还没做完的事**:字体、后端通道、首份快照、身份判定。后端没起来时
* 它就停在那儿,而不是假装走到 100% 再放你进去。指南里说序列动画应当"看起来像在载入信息,
* 而不是立刻跳出来"——那是视觉要求;这里额外满足了"不许骗人"这个更硬的要求。
*
* # 为什么要等字体
*
* 中文是整个界面的主要字形,它由 82 个 unicode-range 分片按需下载。首帧如果先画成系统
* 黑体、两百毫秒后再跳成 HarmonyOS,整块布局会跟着重排一次——启动时这一个抖动比多等
* 一瞬难看得多。所以这里等 `document.fonts.ready`。
*
* # 布局
*
* 左侧是系统标记与版本,中间是逐行亮起的自检,底部一条真实进度。整屏用切角框住,
* 四角有定位括号:这是"终端在做开机自检"的画面,不是"加载中的转圈"。
*/
import { BrandMark } from "./BrandMark";
interface Milestone {
key: string;
/** 这一行显示什么(中文短语 + 一个代号)。 */
label: string;
code: string;
done: boolean;
}
interface Props {
milestones: Milestone[];
/** 走到 1 时开始淡出。 */
progress: number;
/** 起不来的那句话。有它就不显示"正在载入",而是给出原因。 */
fatal?: string | null;
/** 淡出中。 */
leaving?: boolean;
}
export function Boot({ milestones, progress, fatal, leaving = false }: Props) {
return (
<div className={`boot${leaving ? " is-leaving" : ""}`}>
<div className="boot__grid" aria-hidden="true" />
<div className="boot__scan" aria-hidden="true" />
<div className="boot__frame plate corners">
<header className="boot__head">
<span className="boot__mark" aria-hidden="true">
<BrandMark size={30} />
</span>
<div className="boot__titles">
<span className="boot__name">
RMIC<span className="boot__slash">::</span>2026
</span>
<span className="boot__sub label">裁判系统客户端 · SIMBA ROBOTICS</span>
</div>
</header>
<ul className="boot__log">
{milestones.map((item) => (
<li key={item.key} className="boot__line" data-done={item.done ? "yes" : "no"}>
<span className="boot__glyph" aria-hidden="true" />
<span className="boot__label">{item.label}</span>
<span className="boot__leader" aria-hidden="true" />
<span className="boot__code num">{item.code}</span>
</li>
))}
</ul>
{fatal ? (
<div className="boot__fatal">
<span className="boot__fatal-title">启动失败</span>
<p className="boot__fatal-text">{fatal}</p>
<p className="boot__fatal-hint">
端口可能被其他客户端占用。请关闭正在运行的客户端,再重新启动。
</p>
</div>
) : (
<div className="boot__foot">
<div className="boot__bar">
<span
className="boot__bar-fill"
style={{ width: `${Math.round(Math.max(0, Math.min(1, progress)) * 100)}%` }}
/>
</div>
<div className="boot__meta">
<span className="label">
{progress >= 1 ? "加载完成 · 正在进入" : "正在加载"}
</span>
<span className="num boot__pct">
{Math.round(Math.max(0, Math.min(1, progress)) * 100)}
<span className="boot__pct-unit">%</span>
</span>
</div>
</div>
)}
</div>
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
/**
* 队标(Simba Robotics / 黑大 602)。
*
* # 为什么内联而不是放一张图片
*
* 它出现在顶栏与启动页两处,尺寸都是 16–24 px 级别。位图在那个尺寸上要么发糊、要么
* 需要两套 @2x;而这三个路径总共不到 3 kB,内联进 JS 反而更小,还能直接吃 `currentColor`
* ——深色底上它是白的,将来放到浅色底上不用换资源。
*
* # 坐标是从原 SVG 的 viewBox 里**裁**出来的
*
* 原图是 1024×1024 的画布,标志本体只占中间一条(x 16.8–254.9,y 41.3–215.5),四周
* 留白很多。这里把 viewBox 直接收到本体上,于是 `height: 18px` 拿到的就是 18px 的标志,
* 而不是 18px 的画布里面一个 12px 的形状。
*
* 中间的圆点是队标自带的红,不是这套界面的强调色——它跟着品牌走,不跟着主题走。
*/
interface Props {
/** 显示高度(像素)。宽度按标志本身的 240:177 比例算。 */
size?: number;
/** 圆点颜色。默认用队标自己的红。 */
dot?: string;
}
export function BrandMark({ size = 18, dot = "#e8232b" }: Props) {
return (
<svg
className="brandmark"
viewBox="16 40 240 177"
height={size}
width={(size * 240) / 177}
role="img"
aria-label="Simba Robotics"
focusable="false"
>
<g fill="currentColor">
<path d="m 120.18387,65.065937 -8.00358,13.862771 h 27.77765 l 0.0541,0.09409 30.76276,53.283672 -35.41234,61.33599 -0.008,0.0143 -7.99546,13.84855 -0.008,0.0143 h 16.00718 44.01701 l -5.80572,10.05592 h -66.94744 l -0.007,0.0105 h -6.48395 l 5.81384,-10.07013 8.00358,-13.86278 28.83631,-49.94524 8.0036,-13.86276 H 142.78056 114.57375 107.01421 83.392663 67.385498 l -8.004262,13.86276 -42.562363,73.72043 -8.0035837,13.86278 H 24.822458 84.211033 l -0.0914,0.15771 h 16.007157 11.36098 l 0.007,-0.0105 h 62.07111 16.00784 l 0.0105,-0.0175 h 41.16526 15.05748 16.00718 l -8.00358,-13.86278 -5.81181,-10.06608 -8.00358,-13.86276 h -16.00718 -12.5848 -16.00784 l -0.0156,0.0278 h -1.6347 -0.80551 -12.33705 l 27.39928,-47.45699 8.00358,-13.86276 -5.11392,-8.85783 -11.76441,-20.37651 h 31.64205 l 5.06519,-8.773893 2.9384,-5.088885 h -15.13465 -48.55152 l 8.00358,13.862778 h 0.0297 l 16.87765,29.23434 -35.40286,61.31975 h -13.23258 l 27.41688,-47.48812 8.00358,-13.8621 -8.00358,-13.86276 -22.75918,-39.420912 h 60.26447 l -8.00332,-13.862894 h -32.42792 v -0.09409 z M 75.389113,143.70806 h 23.62222 7.558857 28.2075 l -28.83633,49.94523 -8.003587,13.86278 -5.11257,8.85512 -5.1119,-8.85512 -8.00427,-13.86278 H 63.701872 46.553462 l 8.574205,-14.85103 8.003585,-13.86277 z" />
<path d="m 134.72691,41.313757 -8.00358,13.862771 h 62.89352 16.00718 31.56419 l -8.00358,-13.862771 h -31.5642 -16.00717 z" />
</g>
<path
d="M 243.26673,60.098895 A 11.644196,11.644196 0 0 0 231.62281,71.742811 11.644196,11.644196 0 0 0 243.26673,83.386727 11.644196,11.644196 0 0 0 254.91131,71.742811 11.644196,11.644196 0 0 0 243.26673,60.098895 Z"
fill={dot}
/>
</svg>
);
}
+52
View File
@@ -0,0 +1,52 @@
/** 参照裸板绘制;状态只表示 USB 识别与任务进度,不推断实际灯色或外设连接。 */
function ArmorBoard() {
return <g className="device-diagram__board device-diagram__armor">
<path className="device-diagram__pcb" d="M288 83h134l16 18v30h7v98h-7v41l-15 13H288l-16-13v-41h-7v-98h7v-30Z" />
{[291, 419].flatMap(x => [105, 263].map(y => <circle className="device-diagram__hole" key={`${x}-${y}`} cx={x} cy={y} r="5" />))}
<path className="device-diagram__trace" d="M305 110h22v24h16v37m62-61h-21v24h-17v37m-62-28h15m69 0h16m-100 38h12m75 0h13m-100 38h12m75 0h13M313 248v15h25m43-15v15h25" />
{[286, 404].flatMap(x => [126, 164, 202].map(y => <g key={`${x}-${y}`}><rect className="device-diagram__pixel" x={x} y={y} width="20" height="20" rx="2" /><circle className="device-diagram__diode" cx={x + 10} cy={y + 10} r="4" /></g>))}
<rect className="device-diagram__shield" x="320" y="177" width="70" height="72" rx="3" />
<text x="355" y="207" textAnchor="middle">ESP32-C3</text><text className="device-diagram__sublabel" x="355" y="223" textAnchor="middle">MINI-1</text>
{[316, 394].flatMap(x => [183, 196, 209, 222, 235].map(y => <rect className="device-diagram__smd" key={`${x}-${y}`} x={x} y={y} width="3" height="6" />))}
{[335, 355, 375].map(x => <g key={x}><circle className="device-diagram__pad" cx={x} cy="151" r="3" /><path className="device-diagram__trace" d={`M${x} 154v14`} /></g>)}
<circle className="device-diagram__pad" cx="388" cy="174" r="4" />
<rect className="device-diagram__usb" x="342" y="269" width="26" height="18" rx="4" /><path d="M347 281h16" />
</g>;
}
function CameraBoard() {
return <g className="device-diagram__board device-diagram__camera">
<rect className="device-diagram__pcb" x="309" y="88" width="92" height="195" rx="6" />
{[310, 400].flatMap(x => Array.from({ length: 14 }, (_, i) => <circle className="device-diagram__pad" key={`${x}-${i}`} cx={x} cy={103 + i * 11} r="2.2" />))}
<rect className="device-diagram__shield" x="323" y="105" width="64" height="55" rx="2" />
<text className="device-diagram__sublabel" x="355" y="141" textAnchor="middle">ESP32-S3</text><text className="device-diagram__sublabel" x="355" y="153" textAnchor="middle">WROOM</text>
<path className="device-diagram__ribbon" d="M338 100v73h34v-73" /><rect className="device-diagram__connector" x="332" y="168" width="46" height="12" rx="1" />
<rect className="device-diagram__lens-base" x="327" y="62" width="56" height="51" rx="7" /><circle className="device-diagram__lens" cx="355" cy="87" r="21" /><circle className="device-diagram__glass" cx="355" cy="87" r="12" /><path className="device-diagram__lens-shine" d="M349 81q6-5 12 0" />
<text className="device-diagram__sublabel" x="355" y="202" textAnchor="middle">OV5640</text>
<rect className="device-diagram__chip" x="346" y="213" width="18" height="18" rx="1" />
{[324, 374].map(x => <g key={x}><rect className="device-diagram__button" x={x} y="242" width="12" height="12" rx="1" /><circle cx={x + 6} cy="248" r="3" /></g>)}
{[319, 361].map(x => <g key={x}><rect className="device-diagram__usb" x={x} y="267" width="30" height="19" rx="4" /><path d={`M${x + 5} 280h20`} /></g>)}
<path className="device-diagram__trace" d="M325 216h13v17h-12m58-17h-12v17h12" />
</g>;
}
export function DeviceDiagram({ kind, identified, portAvailable, active, failed, complete, ratio, chip }: {
kind: "" | "camera" | "armor";
identified: boolean;
portAvailable: boolean;
active: boolean;
failed: boolean;
complete: boolean;
ratio: number | null;
chip: string;
}) {
const circumference = 2 * Math.PI * 132;
return <svg className={`device-diagram${identified || complete ? " is-identified" : ""}${active ? " is-active" : ""}${failed ? " is-failed" : ""}${complete ? " is-complete" : ""}`} viewBox="0 0 580 360" role="img" aria-label={`${kind === "armor" ? "装甲板主板" : kind === "camera" ? "图传板" : "目标设备"}:${complete ? "任务已完成" : failed ? "任务未完成" : identified ? "USB 已识别" : portAvailable ? "有串口,尚未读取" : "等待 USB 连接"}`}>
<circle className="device-diagram__orbit" cx="355" cy="180" r="132" />
<g transform="rotate(-90 355 180)">{(active || complete || ratio !== null) && <circle className={`device-diagram__progress${active && ratio === null ? " is-indeterminate" : ""}`} cx="355" cy="180" r="132" strokeDasharray={circumference} strokeDashoffset={circumference * (1 - (complete ? 1 : ratio ?? .12))} />}</g>
<g className="device-diagram__computer"><rect x="28" y="142" width="82" height="58" rx="4" /><path d="M69 201v14m-24 0h48m-44-45 10 8-10 8m18 0h19" /><circle className="device-diagram__led" cx="98" cy="153" r="3" /></g>
<path className={`device-diagram__cable${portAvailable ? " is-present" : ""}`} d={`M112 171h40q18 0 18 18v92q0 18 18 18h${kind === "camera" ? 127 : 147}q19 0 19-13`} />
{kind === "armor" ? <ArmorBoard /> : kind === "camera" ? <CameraBoard /> : <g className="device-diagram__board"><rect className="device-diagram__pcb" x="290" y="112" width="130" height="158" rx="8" /><text x="355" y="186" textAnchor="middle">USB</text><text className="device-diagram__sublabel" x="355" y="207" textAnchor="middle">选择维护对象</text><rect className="device-diagram__usb" x="342" y="269" width="26" height="18" rx="4" /></g>}
<text className="device-diagram__caption" x="69" y="245" textAnchor="middle">CLIENT / USB</text><text className="device-diagram__caption" x="355" y="335" textAnchor="middle">{kind === "armor" ? "装甲板 · ESP32-C3 · 六灯珠" : kind === "camera" ? "图传板 · ESP32-S3 · OV5640" : chip || "选择维护对象"}</text>
</svg>;
}
+43
View File
@@ -0,0 +1,43 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
/** 原生模态框负责焦点约束与关闭后的焦点恢复。 */
export function Dialog({ title, children, onClose, className = "", closeDisabled = false }: {
title: string;
children: ReactNode | ((close: () => void) => ReactNode);
onClose: () => void;
className?: string;
closeDisabled?: boolean;
}) {
const ref = useRef<HTMLDialogElement>(null);
const [closing, setClosing] = useState(false);
const closeAction = useRef(onClose);
closeAction.current = onClose;
useEffect(() => {
const dialog = ref.current;
if (dialog && !dialog.open) dialog.showModal();
dialog?.querySelector<HTMLElement>("[data-initial-focus]")?.focus();
return () => dialog?.close();
}, []);
useEffect(() => {
if (!closing) return;
if (closeDisabled) { setClosing(false); return; }
const dialog = ref.current;
if (!dialog) return;
// 与 CSS 的 Material 退出时长保持一致,系统减少动效时直接关闭。
const duration = window.getComputedStyle(dialog).animationDuration.split(",")[0].trim();
const milliseconds = Number.parseFloat(duration) * (duration.endsWith("ms") ? 1 : 1000);
const timer = window.setTimeout(() => closeAction.current(), Number.isFinite(milliseconds) ? milliseconds : 0);
return () => window.clearTimeout(timer);
}, [closing, closeDisabled]);
const requestClose = () => {
if (closeDisabled || closing) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) closeAction.current();
else setClosing(true);
};
return <dialog ref={ref} className={`ui-dialog ${className}${closing ? " is-closing" : ""}`} aria-label={title} inert={closing}
onKeyDown={event => { if (event.key === "Escape") event.stopPropagation(); }}
onCancel={event => { event.preventDefault(); requestClose(); }}>
<header className="ui-dialog__head"><h2>{title}</h2><button type="button" className="btn btn--quiet" onClick={requestClose} disabled={closeDisabled || closing} aria-label="关闭">关闭 <kbd>ESC</kbd></button></header>
{typeof children === "function" ? children(requestClose) : children}
</dialog>;
}
+255
View File
@@ -0,0 +1,255 @@
/**
* 首次启动的两道门:先选身份,再设密码。
*
* 身份必须问一次,因为 `role` 的默认值(裁判端)既可能是人选了裁判端,也可能只是还没人
* 碰过这个文件——后者让用户端的人第一次打开会直接进裁判端,然后以为这个程序只有那一种
* 界面。所以后端单独记了一个 `roleChosen`。
*
* # 为什么是"装一个模块"而不是"选一个选项"
*
* 这两条路后面接的是两套完全不同的界面与权限,是这台机器**要变成什么**,不是这次会话里
* 的一个偏好。所以它长得像在装模块:一张编号的板子、一句"它会用到什么"、一个明确的
* 确认动作。选完就锁进去,下次启动直接进这一端。
*
* 密码那一道同理:它不是"注册账号",是给这台机器配一把现场用的钥匙,所以文案讲的是
* "它挡住什么、绕不过什么",而不是"请设置一个强密码"。
*/
import { useEffect, useRef, useState } from "react";
import { api } from "../lib/ipc";
import { pushNote } from "../lib/store";
import type { Role } from "../lib/types";
const MODULES: {
role: Role;
index: string;
cn: string;
en: string;
summary: string;
needs: string[];
}[] = [
{
role: "team",
index: "01",
cn: "用户端",
en: "OPERATOR",
summary: "供操作手使用:本队画面、双方血条、瞄准器和命中反馈。",
needs: ["绑定一块图传板", "绑定一块装甲板", "设置现场密码"],
},
{
role: "referee",
index: "02",
cn: "裁判端",
en: "REFEREE",
summary: "供场边裁判使用:双路画面、双方血量、装甲板列表、截图和录制。",
needs: ["无需绑定设备", "无需密码", "自动分配左右槽位"],
},
];
export function RolePicker({ onOpenMaintenance }: { onOpenMaintenance?: () => void }) {
const [busy, setBusy] = useState<Role | null>(null);
const [error, setError] = useState<string | null>(null);
const choose = async (role: Role) => {
setBusy(role);
setError(null);
try {
await api.setRole(role);
await api.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(null);
}
};
return (
<div className="gate">
<div className="gate__grid" aria-hidden="true" />
<header className="gate__head">
<span className="gate__brand">
RMIC<span className="gate__slash">::</span>2026
</span>
<span className="gate__phase label">FIRST RUN · 选择运行模式</span>
</header>
<div className="gate__lede">
<h1 className="gate__title">选择运行模式</h1>
<p className="gate__hint">
下次启动会沿用所选模式。也可在设置中切换;从用户端切换模式需要密码。
</p>
</div>
<div className="gate__choices">
{MODULES.map((module) => (
<button
key={module.role}
type="button"
className={`module plate${busy === module.role ? " is-busy" : ""}`}
disabled={busy !== null}
onClick={() => void choose(module.role)}
>
<span className="module__index num">{module.index}</span>
<span className="module__name">
{module.cn}
<span className="module__en label">{module.en}</span>
</span>
<span className="module__summary">{module.summary}</span>
<span className="module__needs">
{module.needs.map((need) => (
<span key={need} className="module__need">
{need}
</span>
))}
</span>
<span className="module__cta">
{busy === module.role ? "正在切换…" : "使用此模式"}
<span className="module__arrow" aria-hidden="true">
→
</span>
</span>
<span className="module__corners" aria-hidden="true" />
</button>
))}
</div>
{error && <p className="gate__error">{error}</p>}
{onOpenMaintenance && (
<button type="button" className="gate__maintenance" onClick={onOpenMaintenance} disabled={busy !== null}>
打开固件维护
</button>
)}
</div>
);
}
export function SetupPassword({ onOpenMaintenance }: { onOpenMaintenance?: () => void }) {
const [first, setFirst] = useState("");
const [again, setAgain] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const input = useRef<HTMLInputElement | null>(null);
useEffect(() => {
input.current?.focus();
}, []);
const submit = async () => {
if (busy) return;
if (first !== again) {
setError("两次输入的密码不一致");
setAgain("");
return;
}
setBusy(true);
setError(null);
try {
await api.setPassword(first);
await api.refresh();
pushNote("密码已设置。修改图传板或装甲板绑定、切换队伍号、退出程序时需要输入密码。");
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
};
const strength = Math.min(4, Math.floor(first.length / 2));
return (
<div className="gate gate--narrow">
<div className="gate__grid" aria-hidden="true" />
<header className="gate__head">
<span className="gate__brand">
RMIC<span className="gate__slash">::</span>2026
</span>
<span className="gate__phase label">OPERATOR · 现场密码</span>
</header>
<div className="gate__lede">
<h1 className="gate__title">设置现场密码</h1>
<p className="gate__hint">
修改用户端的设备绑定、切换队伍号或退出程序时需要密码。密码至少 4 位;
本机保存 Argon2id 哈希,不保存明文。
</p>
</div>
<div className="keypad">
<label className="keypad__field">
<span className="keypad__label label">PASSWORD</span>
<input
ref={input}
className="input input--lg"
type="password"
placeholder="密码"
autoComplete="new-password"
value={first}
onChange={(event) => setFirst(event.target.value)}
/>
</label>
<label className="keypad__field">
<span className="keypad__label label">REPEAT</span>
<input
className="input input--lg"
type="password"
placeholder="再次输入密码"
autoComplete="new-password"
value={again}
onChange={(event) => setAgain(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") void submit();
}}
/>
</label>
<div className="keypad__meter" aria-hidden="true">
{[0, 1, 2, 3].map((step) => (
<span key={step} className={`keypad__cell${strength > step ? " is-on" : ""}`} />
))}
<span className="keypad__meter-note">
{first.length === 0
? "请输入密码"
: first.length < 4
? `还需要 ${4 - first.length} 位`
: "长度符合要求"}
</span>
</div>
{error && <p className="gate__error">{error}</p>}
<button
type="button"
className="btn btn--primary btn--lg keypad__submit"
onClick={() => void submit()}
disabled={busy || first.length < 4}
>
{busy ? "保存中…" : "设置密码并继续"}
<span className="btn__key">⏎</span>
</button>
</div>
<p className="gate__note">
忘记密码时,可删除配置文件中的 password 一行,或删除整个配置文件。旧客户端
(Slint 版)的配置会在首次启动时自动导入,并备份为 .bak。
</p>
{onOpenMaintenance && (
<button type="button" className="gate__maintenance" onClick={onOpenMaintenance} disabled={busy}>
打开固件维护
</button>
)}
</div>
);
}
+78
View File
@@ -0,0 +1,78 @@
/** 连续血量条:长度对应 0–100 血,右侧镜像后从画面中心向外缩短。未接入时保留空条与说明。 */
import { teamColor } from "../lib/format";
import type { HealthConfig, TeamHealthDto } from "../lib/types";
interface Props {
health: TeamHealthDto;
config: HealthConfig;
/** 挂在画面哪一角。`right` 会把条整个镜像过来(含缺血的退向)。 */
align: "left" | "right";
/** 这一格是谁:用户端用「我方 / 对手」把两条同色的血区分开。 */
tag?: string;
/** 休眠态:只留数字,标签与提示退到背景里。 */
asleep?: boolean;
}
export function HealthBar({ health, config, align, tag, asleep = false }: Props) {
// 脉动交给 CSS,减少动态效果时仍保留低血颜色,停止闪动。
const pulsing = config.pulse && health.available && health.critical;
const color = health.critical ? "var(--error)" : teamColor(health.team);
const raw = health.available ? Math.max(0, Math.min(100, health.hp ?? 0)) : 0;
const showThreshold = config.lowThreshold > 0 && config.lowThreshold < 100;
// 宽度按配置收窄。它挂在画面角上,太宽会盖住画面本身。
const width = `${Math.round(config.width * 100)}%`;
return (
<div
className={`hp hp--${align}${asleep ? " hp--asleep" : ""}${
pulsing ? " hp--pulsing" : ""
}${health.critical ? " hp--critical" : ""}`}
style={{ width }}
title={health.available ? undefined : health.placeholder}
>
<div className="hp__head">
{tag && <span className="hp__tag">{tag}</span>}
{config.showTeamName && (
<span className="hp__name" style={{ color }} title={health.name}>
{health.name}
</span>
)}
{health.available ? (
config.showNumbers && (
<span className="hp__value num" style={{ color }}>
{raw}
</span>
)
) : (
<span className="hp__missing">装甲板未接入</span>
)}
</div>
<div className="hp__track-wrap">
<div className="hp__track" aria-hidden="true">
<div className="hp__meter">
<span className="hp__fill" style={{ width: `${raw}%`, backgroundColor: color }}>
{health.available && raw > 0 && <span key={raw} className="hp__impact" />}
</span>
{/* 刻度与填充共用坐标;镜像整条时会一起翻到右侧。 */}
{showThreshold && <span className="hp__threshold" style={{ left: `${config.lowThreshold}%` }} />}
</div>
</div>
</div>
</div>
);
}
/**
* 这一格是谁。
*
* 用户端两条血分别属于两边,而形状是对称的——没有这个标签,"左边这条是我的"要靠位置猜。
*/
export function healthTag(health: TeamHealthDto, myTeam: number): string {
return health.team === myTeam ? "我方" : "对手";
}
+61
View File
@@ -0,0 +1,61 @@
/**
* 命中反馈的整屏层:边沿泛红 + 条上的读数。
*
* # 大号数字刻意不放在画面正中
*
* 第一版把 `-7 / 100 → 93` 放在正中,结果它正好压在瞄准点上——被打中的那一下恰恰是最
* 需要看着准星的时候。现在数字由 `VideoSurface` 画在**准星旁边**(跟着瞄准点走,不挡
* 目标),这里只留边沿泛红与顶部一条读数。
*
* # 泛红为什么贴着边沿
*
* 旧版是一整块径向渐变盖在画面上,等于在最要紧的一瞬间把画面调暗。现在颜色只在四条边上
* 用 `inset` 阴影渗进来,中间保持原样——"被打到"这件事从四周传来,而不是挡在眼前。
*
* # 不给方向
*
* 命中事件里的 `index` 是**哪一条上报先发现了掉血**,不是"从哪一侧打来的"(主板一次广播
* 四条、血值相同,谁先到达取决于 UDP)。把它画成方向箭头会是一条看起来很专业、实际上
* 完全错误的线索,比不画糟得多。所以这一层是对称的。
*
* `key={hit.seq}` 是让 CSS 动画每次都从头开始的关键:同一个元素上换属性不会重启动画,
* 于是第二下命中就再也闪不出来了——一个"第一次有效"的 bug。
*/
import type { HitPulseRecord } from "../lib/store";
import type { HitFeedbackConfig } from "../lib/types";
interface Props {
hit: HitPulseRecord | null;
config: HitFeedbackConfig;
/** 这一下是不是打在我这一边(裁判端两边都显示,但只有相关那一路闪)。 */
relevant: boolean;
label?: string;
}
export function HitFlash({ hit, config, relevant, label }: Props) {
if (!hit || !relevant || !config.flash) return null;
// 强度换算成"边沿渗进来多深"。上限压在 70px:再深就开始吃掉画面。
const depth = Math.round(38 + 34 * Math.min(2, Math.max(0.2, config.intensity)));
return (
<div
key={hit.seq}
className="hit"
style={{ ["--hit-depth" as string]: `${depth}px` }}
aria-hidden="true"
>
<span className="hit__edge" />
<span className="hit__tick">
{label && <span className="hit__tick-label">{label}</span>}
<span className="hit__tick-damage num">−{hit.damage}</span>
<span className="hit__tick-hp num">
{hit.from}
<span className="hit__tick-arrow">→</span>
{hit.to}
</span>
</span>
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
/**
* 图传中央的胜负结算:一边归零之后,画面正中给出「胜利 / 落败」。
*
* # 为什么这次放在正中
*
* 命中反馈那一套刻意避开正中(伤害数字放在准星旁),因为被打中的那一下恰恰最需要看着
* 准星。**胜负不是那种信息**:它是一局的结束,此刻不再需要瞄准;反过来说,它是这一屏
* 上唯一还重要的事,放在角上会让人错过整场比赛的结论。
*
* # 它一直显示到血量被重置
*
* 不做 3 秒淡出:淡出之后屏幕上就再没有"这局结束了"的痕迹,截图、回放、现场的争议都
* 无从对照。血量被重置(长按 BOOT / 下一局开始)时它自己消失——那个动作本来就是
* "这局翻篇了"。
*
* # 为什么要加电影黑边
*
*"结算"和"正在打"必须是两种构图。上下两条黑边把画面压成宽幅,视线自然收到中间那行字上;
* 同时它们给了一处能放次要读数(谁、输赢给谁看)的地方,不必把字塞进画面。
*/
import type { MatchOutcome } from "../lib/types";
interface Props {
/** 从这一边看的结论。两边都活着时是 null,什么都不显示。 */
outcome: MatchOutcome | null;
/** 我这一边的名字。 */
mine: string;
/** 对手的名字。 */
theirs: string;
/** 比分感的补充读数,例如「对手 0 血」。 */
detail?: string;
}
const WORD: Record<MatchOutcome, string> = {
victory: "胜利",
defeat: "落败",
draw: "平局",
};
const CODE: Record<MatchOutcome, string> = {
victory: "MATCH · WIN",
defeat: "MATCH · LOSS",
draw: "MATCH · DRAW",
};
export function MatchBanner({ outcome, mine, theirs, detail }: Props) {
if (!outcome) return null;
const caption =
outcome === "victory"
? `击败 ${theirs}`
: outcome === "defeat"
? `被 ${theirs} 击败`
: "双方装甲板同时归零";
return (
<div className={`verdict verdict--${outcome}`} role="status">
<span className="verdict__bar verdict__bar--top" />
<span className="verdict__bar verdict__bar--bottom" />
<div className="verdict__card">
<span className="verdict__code label">{CODE[outcome]}</span>
<span className="verdict__mine">{mine}</span>
<span className="verdict__word">{WORD[outcome]}</span>
<span className="verdict__rule" aria-hidden="true" />
<span className="verdict__caption">{caption}</span>
{detail && <span className="verdict__detail num">{detail}</span>}
</div>
</div>
);
}
+113
View File
@@ -0,0 +1,113 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { Dialog } from "./Dialog";
import { api } from "../lib/ipc";
import { useAppStore } from "../lib/store";
import { MATCH_PHASE, matchTime, projectMatch } from "../lib/match-time";
import type { MatchAction, MatchClockView, Snapshot } from "../lib/types";
function useClock(view: MatchClockView) {
const { connected } = useAppStore();
const origin = useMemo(() => ({ at: performance.now(), view }), [view]);
const [now, setNow] = useState(performance.now());
useEffect(() => { const timer = window.setInterval(() => setNow(performance.now()), 100); return () => window.clearInterval(timer); }, []);
return projectMatch(origin.view, Math.max(0, now - origin.at), connected);
}
function Readout({ clock, names }: { clock: MatchClockView; names: string[] }) {
const paused = clock.phase === "paused";
const expired = paused && clock.pauseKind === "player" && clock.pauseRemainingMs === 0;
const label = !paused ? MATCH_PHASE[clock.phase] : clock.pauseKind === "player" ? `选手技术暂停 · ${names[clock.applicant ?? 0]}` : "官方技术暂停";
return <div className={`match-readout${paused ? " is-paused" : ""}${!clock.connected ? " is-stale" : ""}`}>
<div className="match-readout__phase"><i />{label}</div>
<div className="match-readout__digits num">{paused ? matchTime(clock.pauseRemainingMs ?? clock.pauseElapsedMs, clock.pauseKind === "official") : clock.phase === "idle" ? "—:—" : matchTime(clock.remainingMs)}</div>
<div className="match-readout__detail">{!clock.connected ? clock.source ? "计时同步中断 · 已冻结" : "等待裁判计时同步" : expired ? "暂停时间已到 · 等待裁判恢复" : paused ? `${clock.pauseKind === "official" ? "暂停已用时" : "暂停剩余"} · 暂停前剩余 ${matchTime(clock.remainingMs)}` : clock.phase === "running" || clock.phase === "finished" ? `对局已用时 ${matchTime(clock.elapsedMs, true)}` : clock.phase === "ready" ? "等待裁判确认开赛" : clock.phase === "countdown" ? "倒计时结束后开始对局" : "准备 3 分钟 / 对局 3 分钟"}</div>
{paused && <p className="match-readout__reason" title={clock.reason}>{clock.reason}</p>}
</div>;
}
export function TeamMatchClock({ snapshot }: { snapshot: Snapshot }) {
const clock = useClock(snapshot.matchClock);
const paused = clock.phase === "paused";
const label = !clock.connected ? clock.source ? "同步中断" : "等待裁判" : paused ? clock.pauseKind === "official" ? "官方暂停" : "选手暂停"
: clock.phase === "running" ? "对局剩余" : clock.phase === "preparation" ? "准备剩余" : clock.phase === "ready" ? "等待开赛"
: clock.phase === "countdown" ? "即将开赛" : clock.phase === "finished" ? "计时结束" : "尚未开始";
const time = clock.phase === "idle" ? "—:—" : paused
? matchTime(clock.pauseRemainingMs ?? clock.pauseElapsedMs, clock.pauseKind === "official") : matchTime(clock.remainingMs);
const detail = clock.syncError ?? (!clock.connected ? clock.source ? "计时同步中断,时间已冻结" : "等待裁判发送比赛计时" : paused
? `${clock.reason};${clock.pauseRemainingMs === 0 ? "暂停时间已到,等待裁判恢复;" : ""}对局已用时 ${matchTime(clock.elapsedMs, true)}`
: `对局已用时 ${matchTime(clock.elapsedMs, true)}`);
return <div className={`team-match-clock${paused ? " is-paused" : ""}${!clock.connected ? " is-stale" : ""}`} role="timer" aria-label={`${label} ${time},${detail}`} title={detail}>
<span className="team-match-clock__label">{label}</span>
<strong className="team-match-clock__time num">{time}</strong>
</div>;
}
/** 最后 5 秒覆盖画面;仅收到权威的开赛状态后才显示“开始”。 */
export function TeamMatchCountdown({ snapshot }: { snapshot: Snapshot }) {
const clock = useClock(snapshot.matchClock);
const previous = useRef({ phase: clock.phase, connected: clock.connected });
const [started, setStarted] = useState(false);
useEffect(() => {
const was = previous.current;
previous.current = { phase: clock.phase, connected: clock.connected };
if (was.phase === "countdown" && was.connected && clock.connected && clock.phase === "running" && clock.elapsedMs < 1500) {
setStarted(true);
} else if (!clock.connected || clock.phase !== "running") setStarted(false);
}, [clock.phase, clock.connected, clock.elapsedMs]);
useEffect(() => {
if (!started) return;
const timer = window.setTimeout(() => setStarted(false), 750);
return () => window.clearTimeout(timer);
}, [started]);
const visible = clock.connected && clock.phase === "countdown" && clock.remainingMs > 0 && clock.remainingMs <= 5000;
if (!visible && !started) return null;
const seconds = Math.max(1, Math.ceil(clock.remainingMs / 1000));
return <div className={`match-countdown${started ? " is-started" : ""}${!started && seconds <= 2 ? " is-urgent" : ""}`} aria-label="开赛全屏倒计时">
<div className="match-countdown__scan" aria-hidden="true" />
<div className="match-countdown__center">
<span className="match-countdown__label">{started ? "对局开始" : "准备开赛"}</span>
<div className="match-countdown__dial" aria-hidden="true"><i /><i /></div>
<strong key={started ? "start" : seconds} className={`match-countdown__number${started ? " match-countdown__number--start" : " num"}`} aria-live="assertive" aria-atomic="true">{started ? "开始" : seconds}</strong>
<div className="match-countdown__steps" aria-hidden="true">{[5, 4, 3, 2, 1].map(step => <i key={step} className={seconds <= step ? "is-passed" : ""} />)}</div>
<span className="match-countdown__caption">{started ? "" : "请选手就位"}</span>
</div>
<div className="match-countdown__progress" aria-hidden="true"><i style={{ transform: `scaleX(${started ? 0 : clock.remainingMs / 5000})` }} /></div>
</div>;
}
export function RefereeMatchControl({ snapshot, onError }: { snapshot: Snapshot; onError: (message: string) => void }) {
const clock = useClock(snapshot.matchClock);
const [dialog, setDialog] = useState<"player" | "official" | "end" | null>(null);
const [reason, setReason] = useState("");
const [team, setTeam] = useState(0);
const [approved, setApproved] = useState(false);
const [seconds, setSeconds] = useState(5);
const [busy, setBusy] = useState(false);
const active = ["preparation", "ready", "countdown", "running"].includes(clock.phase);
const run = async (action: MatchAction, close?: () => void) => {
if (busy) return;
setBusy(true);
try { await api.matchAction(action); close?.(); } catch (error) { onError(error instanceof Error ? error.message : String(error)); }
finally { setBusy(false); }
};
const openPause = (kind: "player" | "official") => { setReason(""); setApproved(false); setDialog(kind); };
const reasonValid = reason.trim().length > 0 && new TextEncoder().encode(reason.trim()).length <= 192 && !/[\u0000-\u001f\u007f]/.test(reason);
return <section className="match-control" aria-label="裁判比赛计时控制">
<div className="match-control__identity"><span className="label">MATCH CONTROL</span><span>{snapshot.demo ? "本机演示 · 合成计时" : "裁判计时 / 局域网同步"}</span>{!snapshot.demo && <small className={snapshot.matchClock.syncError ? "is-error" : ""}>{snapshot.matchClock.syncError ?? "仅对局进行中扣血;准备与暂停时只闪灯"}</small>}</div>
<Readout clock={clock} names={snapshot.config.teamNames} />
<div className="match-control__actions">
{clock.phase === "idle" || clock.phase === "finished" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "prepare" })}>开始 3 分钟准备</button> : clock.phase === "ready" ? <div className="match-control__start"><label>开赛倒计时 <input aria-label="开赛倒计时秒数" type="number" min="1" max="60" step="1" value={seconds} onChange={e => setSeconds(Number(e.target.value))} /> 秒</label><button className="btn btn--primary" disabled={busy || !Number.isInteger(seconds) || seconds < 1 || seconds > 60} onClick={() => void run({ type: "countdown", seconds })}>确认开赛</button></div> : clock.phase === "paused" ? <button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "resume" })}>恢复{clock.resumePhase === "preparation" ? "准备" : clock.resumePhase === "ready" ? "待开赛阶段" : clock.resumePhase === "countdown" ? "倒计时" : "对局"}</button> : <span className="match-control__hint">{clock.phase === "preparation" ? "准备结束后等待裁判确认开赛" : clock.phase === "countdown" ? "请选手就位" : "计时到零结束本局"}</span>}
<div className="match-control__buttons"><button className="btn" disabled={busy || !active} onClick={() => openPause("player")}>选手暂停</button><button className="btn" disabled={busy || !active} onClick={() => openPause("official")}>官方暂停</button>{active || clock.phase === "paused" ? <button className="btn btn--quiet" disabled={busy} onClick={() => setDialog("end")}>结束本局</button> : clock.phase === "finished" && <button className="btn btn--quiet" disabled={busy} onClick={() => void run({ type: "reset" })}>清除计时</button>}</div>
</div>
{dialog && <Dialog title={dialog === "end" ? "结束本局计时" : dialog === "player" ? "选手技术暂停" : "官方技术暂停"} closeDisabled={busy} onClose={() => setDialog(null)} className="match-dialog">
{close => <div className="match-dialog__body">{dialog === "end" ? <><p>结束当前计时并同步到选手端,同时停止装甲板扣血。比赛结果由裁判判定。</p><button className="btn btn--primary" disabled={busy} onClick={() => void run({ type: "end" }, close)}>确认结束本局</button></> : <>
<p>{dialog === "player" ? "选手技术暂停为 5 分钟,须先获得主裁判批准。时间到后,等待裁判恢复比赛。" : "官方暂停显示已用时,由裁判手动恢复。规则页未规定固定时限。"}</p>
{dialog === "player" && <label>申请队伍<select value={team} onChange={e => setTeam(Number(e.target.value))}>{snapshot.config.teamNames.map((name, i) => <option key={i} value={i}>{name}</option>)}</select></label>}
<label>暂停原因<input data-initial-focus value={reason} onChange={e => setReason(e.target.value)} maxLength={192} placeholder="例如:图传中断,需要检查接线" /></label>
<small>最多 192 个 UTF-8 字节,约 64 个汉字。</small>
{dialog === "player" && <label className="match-dialog__approval"><input type="checkbox" checked={approved} onChange={e => setApproved(e.target.checked)} />已获得主裁判批准</label>}
<button className="btn btn--primary" disabled={busy || !reasonValid || (dialog === "player" && !approved)} onClick={() => void run(dialog === "player" ? { type: "pausePlayer", team, reason, approved } : { type: "pauseOfficial", reason }, close)}>开始{dialog === "player" ? "5 分钟暂停" : "官方暂停"}</button>
</>}</div>}
</Dialog>}
</section>;
}
+262
View File
@@ -0,0 +1,262 @@
/**
* 录制、截图与录下来的东西。
*
* # 回放为什么可能失败
*
* 界面内回放走 Tauri 的资源协议,而那条协议只对 `tauri.conf.json` 里
* `assetProtocol.scope` 白名单的目录生效。默认录制目录在白名单里;如果现场把输出目录
* 改到别处,`<video>` 会加载失败——那时退回到"用系统播放器打开",而不是让人以为文件坏了。
*
* # 为什么录制中是"条"而不是一行字
*
* 录制这件事最贵的错误是"以为在录,其实没在录"。所以正在录的每一路都占一条醒目的横条:
* 跳动的红点、已写帧数、已经录了多久、写盘跟不上时丢了几帧。这些数字在录完之后就再也
* 拿不到了,只能在当下看。
*/
import { useCallback, useEffect, useState } from "react";
import { convertFileSrc } from "@tauri-apps/api/core";
import { api } from "../lib/ipc";
import { bytes, since } from "../lib/format";
import type { MediaFileDto, Snapshot } from "../lib/types";
interface Props {
snapshot: Snapshot;
onError: (message: string) => void;
onInfo: (message: string) => void;
}
export function MediaPanel({ snapshot, onError, onInfo }: Props) {
const [files, setFiles] = useState<MediaFileDto[]>([]);
const [playing, setPlaying] = useState<MediaFileDto | null>(null);
const [playbackFailed, setPlaybackFailed] = useState(false);
const [busy, setBusy] = useState(false);
const refresh = useCallback(() => {
void api.mediaFiles().then(setFiles, () => undefined);
}, []);
useEffect(() => {
refresh();
// 录制中每 2 秒刷一次列表:刚录完的那一段应该自己出现。
const timer = window.setInterval(refresh, 2000);
return () => window.clearInterval(timer);
}, [refresh]);
const active = snapshot.recordings.filter((recording) => recording.active);
const cameras = snapshot.cameras.filter((camera) => camera.online).map((camera) => camera.id);
const guard = (action: Promise<unknown>, onSuccess?: () => void) => {
setBusy(true);
void action
.then(() => {
onSuccess?.();
refresh();
return api.refresh();
})
.catch((err) => onError(err instanceof Error ? err.message : String(err)))
.finally(() => setBusy(false));
};
const shotTargets = [snapshot.slots.cameraA, snapshot.slots.cameraB].filter(
(id): id is number => id !== null,
);
return (
<div className="media">
<div className="media__actions">
<button
type="button"
className="btn btn--primary"
disabled={busy || cameras.length === 0}
title={cameras.length === 0 ? "暂无在线图传板" : undefined}
onClick={() => {
guard(api.startRecording(cameras), () =>
onInfo("已开始录制。退出程序时会先结束录制并保存文件。"),
);
}}
>
<span className="media__rec-glyph" aria-hidden="true" />
录制全部在线画面
</button>
<button
type="button"
className="btn"
disabled={busy || active.length === 0}
onClick={() => {
guard(api.stopRecording([]));
}}
>
停止全部录制
</button>
<span className="media__divider" aria-hidden="true" />
{shotTargets.map((camera) => (
<button
key={camera}
type="button"
className="btn btn--ghost"
disabled={busy}
onClick={() => {
guard(api.screenshot(camera), () =>
onInfo(
`已截图 0x${camera.toString(16).toUpperCase().padStart(8, "0")}(已保存到录制目录的 shots/)。`,
),
);
}}
>
截图
<span className="num media__cam">0x{camera.toString(16).toUpperCase().padStart(8, "0")}</span>
</button>
))}
<span className="media__spacer" />
<button
type="button"
className="btn btn--quiet"
onClick={() => {
void api
.reveal(snapshot.config.recordingDir)
.catch((err) => onError(err instanceof Error ? err.message : String(err)));
}}
>
打开录制目录
</button>
</div>
{active.length > 0 && (
<div className="media__strips">
{active.map((recording) => (
<div key={recording.camera} className="strip">
<span className="strip__pulse" aria-hidden="true" />
<span className="strip__label label">REC</span>
<span className="strip__cam num">{recording.cameraText}</span>
<span className="strip__stats num">
{recording.framesWritten} 帧
<span className="strip__dot" />
{since(recording.startedMs)}
<span className="strip__dot" />
输入帧率 {recording.inputFps.toFixed(1)} fps
</span>
{recording.framesDropped > 0 && (
<span
className="strip__warn"
title="写入速度不足时会丢帧,可能影响回放速度。"
>
丢 {recording.framesDropped} 帧
</span>
)}
{recording.error && <span className="strip__error">ffmpeg:{recording.error}</span>}
<button
type="button"
className="btn btn--ghost"
onClick={() => {
guard(api.stopRecording([recording.camera]));
}}
>
停止
</button>
</div>
))}
</div>
)}
<div className="media__list">
<div className="media__head">
<span className="media__col media__col--kind">类型</span>
<span className="media__col">文件</span>
<span className="media__col media__col--size">大小</span>
<span className="media__col media__col--acts">操作</span>
</div>
{files.length === 0 ? (
<div className="media__empty">录制目录里还没有文件。</div>
) : (
files.map((file) => (
<div key={file.path} className="media__row">
<span className="media__col media__col--kind">
<span className={`media__kind media__kind--${file.kind}`}>
{file.kind === "video" ? "MP4" : "PNG"}
</span>
</span>
<span className="media__col media__name" title={file.path}>
{file.name}
</span>
<span className="media__col media__col--size num">{bytes(file.bytes)}</span>
<span className="media__col media__col--acts">
<button
type="button"
className="btn btn--quiet"
onClick={() => {
setPlaybackFailed(false);
setPlaying(file.kind === "video" ? file : null);
if (file.kind === "image") {
void api.openFile(file.path).catch(() => undefined);
}
}}
>
{file.kind === "video" ? "播放" : "打开"}
</button>
<button
type="button"
className="btn btn--quiet"
onClick={() => {
void api
.reveal(file.path)
.catch((err) => onError(err instanceof Error ? err.message : String(err)));
}}
>
在文件夹中显示
</button>
</span>
</div>
))
)}
</div>
{playing && (
<div className="playback">
<div className="playback__head">
<span className="playback__label label">PLAYBACK</span>
<span className="playback__name num">{playing.name}</span>
<span className="playback__spacer" />
<button type="button" className="btn btn--quiet" onClick={() => setPlaying(null)}>
关闭
</button>
</div>
{playbackFailed ? (
<div className="playback__fallback">
<p className="playback__warn">
无法在界面内回放,录制目录可能不在允许访问的范围内。请改用默认录制目录,
或用系统播放器打开。
</p>
<button
type="button"
className="btn btn--primary"
onClick={() => void api.openFile(playing.path).catch(() => undefined)}
>
用系统播放器打开
</button>
</div>
) : (
<video
className="playback__video"
src={convertFileSrc(playing.path)}
controls
autoPlay
onError={() => setPlaybackFailed(true)}
/>
)}
</div>
)}
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { Dialog } from "./Dialog";
import { useState } from "react";
import { api } from "../lib/ipc";
import type { Snapshot } from "../lib/types";
export function OperatorMenu({ snapshot, fullscreen, onClose, onSettings, onMaintenance, onFullscreen, onQuit }: {
snapshot: Snapshot;
fullscreen: boolean;
onClose: () => void;
onSettings: () => void;
onMaintenance: () => void;
onFullscreen: () => void;
onQuit: () => void;
}) {
const [reconnect, setReconnect] = useState(false);
const [error, setError] = useState("");
if (reconnect) return <Dialog title="重新接收裁判计时" onClose={() => setReconnect(false)} className="match-dialog"><div className="match-dialog__body">
<p>当前来源:{snapshot.matchClock.source ?? "尚未收到"}。重新连接后,将接收下一份裁判计时广播。请确认局域网中只有一个正式裁判端。</p>
<p>裁判端重启后,请在这里重新连接。网络短暂中断时,同一裁判会话会自动恢复。</p>
{error && <p role="alert">{error}</p>}
<button className="btn btn--primary" onClick={() => { void api.releaseMatchSource().then(() => setReconnect(false)).catch(e => setError(String(e))); }}>确认重新接收</button>
</div></Dialog>;
return <Dialog title="操作菜单" className="operator-menu" onClose={onClose}>
{close => (
<div className="operator-menu__body">
<div className="operator-menu__identity"><span className="label">RMIC :: 2026 / OPERATOR</span><h1>操作菜单<span>MENU</span></h1><p>打开菜单后,图传和受击上报仍会继续。</p>{snapshot.demo && <span className="tag tag--warn">预览 / 合成数据</span>}</div>
<nav className="operator-menu__actions" aria-label="操作菜单">
<button data-initial-focus onClick={close}><span>继续操作</span><kbd>ESC</kbd></button>
<button onClick={onSettings}><span>画面与设备设置</span><small>准星 · 图传绑定 · 装甲板</small></button>
<button onClick={onMaintenance}><span>固件维护</span><small>编译与 USB 烧录</small></button>
<button onClick={() => { setError(""); setReconnect(true); }}><span>重新接收裁判计时</span><small>{snapshot.matchClock.source ?? "等待裁判广播"}</small></button>
<button onClick={onFullscreen}><span>{fullscreen ? "退出全屏" : "全屏显示"}</span><kbd>F11</kbd></button>
<button onClick={onQuit}><span>退出客户端</span><small>{snapshot.unlocked ? "退出程序" : "需要密码"}</small></button>
</nav>
</div>
)}
</Dialog>;
}
+540
View File
@@ -0,0 +1,540 @@
/** 全屏分类设置。发现列表仅在解锁期间开放,保存仍由后端逐项校验。 */
import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { api } from "../lib/ipc";
import { BUILD, VERSION_LABEL } from "../lib/version";
import { firmwareLabel, teamName } from "../lib/format";
import { paintCrosshair, paintGrid, type Geometry } from "../lib/reticle";
import type { ConfigView, CrosshairConfig, HudView, Snapshot, TeamHealthDto } from "../lib/types";
import { Button, Field, Select, Slider, Switch } from "./controls";
import { HealthBar } from "./HealthBar";
interface Props {
snapshot: Snapshot;
hud: HudView;
onHud: (hud: HudView) => void;
calibrating: boolean;
onCalibrating: (active: boolean) => void;
onClose: () => void;
closing?: boolean;
connected?: boolean;
onExitComplete?: () => void;
onNeedsUnlock: (reason: string) => void;
onError: (message: string) => void;
onInfo: (message: string) => void;
onConfig: (config: ConfigView) => void;
}
const SAVE_DEBOUNCE_MS = 350;
interface Category { id: string; label: string; en: string; hint: string; preview?: boolean }
export function SettingsPanel({ snapshot, hud, onHud, calibrating, onCalibrating, onClose,
closing = false, connected = true, onExitComplete, onNeedsUnlock, onError, onInfo, onConfig }: Props) {
const config = snapshot.config;
const locked = !snapshot.unlocked && config.role !== "referee";
const isTeam = config.role === "team";
const panelRef = useRef<HTMLElement | null>(null);
const closeButton = useRef<HTMLButtonElement | null>(null);
const unlockCallback = useRef(onNeedsUnlock);
unlockCallback.current = onNeedsUnlock;
useEffect(() => {
if (closing && window.matchMedia("(prefers-reduced-motion: reduce)").matches) onExitComplete?.();
}, [closing, onExitComplete]);
useEffect(() => {
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const panel = panelRef.current;
closeButton.current?.focus({ preventScroll: true });
return () => {
if (previous?.isConnected && (document.activeElement === document.body || panel?.contains(document.activeElement))) {
previous.focus({ preventScroll: true });
}
};
}, []);
useEffect(() => {
if (locked) return;
void api.setDiscoveryOpen(true).catch(err => unlockCallback.current(err instanceof Error ? err.message : String(err)));
return () => { void api.setDiscoveryOpen(false).catch(() => undefined); };
}, [locked]);
const [pending, setPending] = useState<HudView | null>(null);
const pendingSave = useRef<HudView | null>(null);
const saveCallbacks = useRef({ onConfig, onError });
saveCallbacks.current = { onConfig, onError };
// 立即关闭或开始画面校准时,也提交最后一份草稿。
useEffect(() => () => {
const last = pendingSave.current;
pendingSave.current = null;
if (last) void api.saveHud(last).then(saveCallbacks.current.onConfig).catch(err => saveCallbacks.current.onError(String(err)));
}, []);
useEffect(() => {
if (!pending) return;
const timer = window.setTimeout(() => {
pendingSave.current = null;
setPending(null);
void api.saveHud(pending).then(onConfig).catch(err => onError(err instanceof Error ? err.message : String(err)));
}, SAVE_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [pending, onConfig, onError]);
const update = useCallback((change: (draft: HudView) => void) => {
const next = structuredClone(hud);
change(next);
onHud(next);
pendingSave.current = next;
setPending(next);
}, [hud, onHud]);
const run = async (action: () => Promise<ConfigView>) => {
try { onConfig(await action()); await api.refresh(); }
catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (message.includes("密码")) onNeedsUnlock(message);
else onError(message);
}
};
const cameraOptions = useMemo(() => snapshot.cameras.map(camera => ({
value: camera.id, label: camera.idText,
hint: `${camera.addr} · ${camera.online ? "在线" : "离线"} · 固件 ${firmwareLabel(camera)}${camera.compatible ? "" : ` · 协议 ${camera.protocol} 不匹配`}`,
})), [snapshot.cameras]);
const armorOptions = useMemo(() => snapshot.armorBoards.map(board => ({
value: board.id, label: board.idText,
hint: `${board.addr} · ${teamName(board.team, config.teamNames)} · ${board.hp} 血 · ${board.online ? "在线" : "离线"}`,
})), [snapshot.armorBoards, config.teamNames]);
const categories = useMemo<Category[]>(() => [
{ id: "general", label: "常规", en: "GENERAL", hint: "选择客户端的运行模式。" },
...(isTeam ? [
{ id: "devices", label: "设备绑定", en: "DEVICES", hint: "选择本机接收的图传板与装甲板,核对所属队伍。" },
{ id: "reticle", label: "瞄准器", en: "RETICLE", hint: "调整准星外观,预览效果与操作画面一致。", preview: true },
{ id: "calibration", label: "瞄点校准", en: "CALIBRATION", hint: "调整镜头与弹着点的偏移,偏移按画面比例保存。", preview: true },
{ id: "grid", label: "辅助网格", en: "GRID", hint: "选择画面辅助线的样式、密度和透明度。", preview: true },
{ id: "health", label: "血条", en: "ARMOR", hint: "左侧显示本队血量,右侧显示对手血量;血条长度与剩余血量成正比。", preview: true },
{ id: "feedback", label: "受击与提示", en: "FEEDBACK", hint: "设置受击反馈和画面读数。" },
] : [{ id: "slots", label: "画面槽位", en: "SLOTS", hint: "自动分配两队的图传与装甲板,也可手动调整。" }]),
{ id: "media", label: "录制与截图", en: "CAPTURE", hint: "截图保存为 PNG;录制保存为 MP4,需要 ffmpeg。" },
{ id: "security", label: "安全", en: "ACCESS", hint: "密码用于防止现场误改;能修改本机配置或程序的人仍可绕过。" },
], [isTeam]);
const [active, setActive] = useState("general");
const [next, setNext] = useState<string | null>(null);
const [direction, setDirection] = useState(1);
const current = categories.find(category => category.id === active) ?? categories[0];
const selected = next ?? current.id;
const switchCategory = (id: string) => {
if (id === current.id) { setNext(null); return; }
setDirection(categories.findIndex(item => item.id === id) > categories.findIndex(item => item.id === current.id) ? 1 : -1);
setNext(id);
};
const navigate = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
let target = index;
if (event.key === "ArrowDown") target = (index + 1) % categories.length;
else if (event.key === "ArrowUp") target = (index - 1 + categories.length) % categories.length;
else if (event.key === "Home") target = 0;
else if (event.key === "End") target = categories.length - 1;
else return;
event.preventDefault();
switchCategory(categories[target].id);
panelRef.current?.querySelector<HTMLButtonElement>(`#settings-tab-${categories[target].id}`)?.focus();
};
const trapFocus = (event: KeyboardEvent<HTMLElement>) => {
if (event.key !== "Tab") return;
const nodes = Array.from(panelRef.current?.querySelectorAll<HTMLElement>(
'button:not(:disabled), input:not(:disabled), select:not(:disabled), [tabindex="0"]',
) ?? []).filter(node => node.tabIndex >= 0 && node.getClientRects().length > 0);
const first = nodes[0], last = nodes[nodes.length - 1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
};
const camera = snapshot.cameras.find(item => item.id === config.cameraId);
const cameraStats = snapshot.stats.find(item => item.camera === config.cameraId);
const board = snapshot.armorBoards.find(item => item.id === config.armorId);
const cameraState = !connected ? "本地通道断开" : config.cameraId === null ? "未绑定" : !camera?.online ? "离线" : !camera.compatible ? "协议不匹配" : cameraStats?.online && cameraStats.hasFrames ? "正在接收" : "已发现 · 等待画面";
const armorState = !connected ? "本地通道断开" : config.armorId === null ? "未绑定" : !board?.online ? "离线" : board.team === 255 ? "等待队伍设置" : board.team !== config.team ? "队伍不匹配" : "在线";
const content = () => {
switch (current.id) {
case "general": return <>
<Field label="运行模式" hint="离开用户端需要密码。">
<Select value={config.role} options={[
{ value: "team", label: "用户端", hint: "一路画面、血条和瞄准器" },
{ value: "referee", label: "裁判端", hint: "双路画面、双方血量和录制" },
]} onChange={role => void run(() => api.setRole(role))} />
</Field>
<div className="settings__summary settings__span">
<span className="label">{isTeam ? "OPERATOR" : "REFEREE"}</span>
<strong>{isTeam ? "用户端" : "裁判端"}</strong>
<p>{isTeam ? "操作画面显示血量、计时和连接状态,按 ESC 打开菜单。" : "双路监看、装甲板槽位、录制和回放在裁判界面中使用。"}</p>
</div>
</>;
case "devices": return <>
<Field label="图传板">
<Select value={config.cameraId} options={cameraOptions} onChange={id => void run(() => api.bindCamera(id))} />
</Field>
<Field label="装甲板主板">
<Select value={config.armorId} options={armorOptions} onChange={id => void run(() => api.bindArmor(id))} />
</Field>
<Field label="所属队伍" hint="绑定后,装甲板按所选队伍亮红灯或蓝灯。黄灯闪烁表示未连 Wi-Fi,绿灯闪烁表示等待客户端。扣血控制需使用新版装甲板固件。">
<Select value={config.team} options={[
{ value: 0, label: `${teamName(0, config.teamNames)}(红)` },
{ value: 1, label: `${teamName(1, config.teamNames)}(蓝)` },
]} onChange={team => void run(() => api.setTeam(team))} />
</Field>
<Switch checked={config.mirror} label="左右镜像画面" onChange={mirror => void run(() => api.setMirror(mirror))} />
<div className="settings__device-state settings__span" aria-live="polite">
<span><b>图传</b><strong>{config.cameraIdText ?? "—"}</strong><em>{cameraState}</em></span>
<span><b>装甲板</b><strong>{config.armorIdText ?? "—"}</strong><em>{armorState}</em></span>
</div>
{cameraOptions.length === 0 && <p className="sect__warn settings__span">尚未发现图传板。请检查供电、Wi-Fi 与防火墙,确认设备与本机处于同一网络。</p>}
</>;
case "reticle": return <>
<Switch checked={hud.crosshair.visible} label="显示瞄准器" onChange={visible => update(draft => { draft.crosshair.visible = visible; })} />
<Field label="准星样式"><Select value={hud.crosshair.style} options={[
{ value: "cross", label: "四臂十字" }, { value: "cross-dot", label: "十字 + 中心点" },
{ value: "circle-dot", label: "圆环 + 中心点" }, { value: "dot", label: "中心点" },
]} onChange={style => update(draft => { draft.crosshair.style = style; })} /></Field>
<Field label="大小" hint="占画面短边的比例"><Slider value={hud.crosshair.size} min={0.01} max={0.2} step={0.005} format={value => `${(value * 100).toFixed(1)}%`} onChange={size => update(draft => { draft.crosshair.size = size; })} /></Field>
<Field label="线宽"><Slider value={hud.crosshair.thickness} min={0.001} max={0.02} step={0.0005} format={value => value.toFixed(4)} onChange={thickness => update(draft => { draft.crosshair.thickness = thickness; })} /></Field>
<Field label="中心空隙"><Slider value={hud.crosshair.gap} min={0} max={0.1} step={0.002} format={value => `${(value * 100).toFixed(1)}%`} onChange={gap => update(draft => { draft.crosshair.gap = gap; })} /></Field>
<Field label="颜色"><div className="settings__color"><input className="color" type="color" value={hud.crosshair.color} onChange={event => update(draft => { draft.crosshair.color = event.target.value; })} /><span className="num">{hud.crosshair.color.toUpperCase()}</span></div></Field>
</>;
case "calibration": return <div className="settings__span"><Calibration crosshair={hud.crosshair} calibrating={calibrating} onCalibrating={onCalibrating} onChange={(offsetX, offsetY) => update(draft => { draft.crosshair.offsetX = offsetX; draft.crosshair.offsetY = offsetY; })} /></div>;
case "grid": return <>
<Switch checked={hud.grid.visible} label="显示辅助网格" onChange={visible => update(draft => { draft.grid.visible = visible; })} />
<Field label="网格样式"><Select value={hud.grid.style} options={[
{ value: "thirds", label: "三分线" }, { value: "squares", label: "等分方格" }, { value: "cross", label: "中心十字" },
]} onChange={style => update(draft => { draft.grid.style = style; })} /></Field>
<Field label="等分数" hint="使用等分方格时生效"><Slider value={hud.grid.divisions} min={2} max={16} step={1} disabled={hud.grid.style !== "squares"} format={value => `${value} 格`} onChange={divisions => update(draft => { draft.grid.divisions = divisions; })} /></Field>
<Field label="网格不透明度"><Slider value={hud.grid.opacity} min={0.05} max={1} step={0.01} format={value => `${Math.round(value * 100)}%`} onChange={opacity => update(draft => { draft.grid.opacity = opacity; })} /></Field>
</>;
case "health": return <>
<Switch checked={hud.health.visible} label="显示血条" onChange={visible => update(draft => { draft.health.visible = visible; })} />
<Switch checked={hud.health.showNumbers} label="显示血量数字" onChange={showNumbers => update(draft => { draft.health.showNumbers = showNumbers; })} />
<Switch checked={hud.health.showTeamName} label="显示队伍名" onChange={showTeamName => update(draft => { draft.health.showTeamName = showTeamName; })} />
<Switch checked={hud.health.pulse} label="低血量时脉动提示" onChange={pulse => update(draft => { draft.health.pulse = pulse; })} />
<Field label="低血阈值" hint="达到此值或更低时提示"><Slider value={hud.health.lowThreshold} min={5} max={100} step={5} format={value => `${value} 血`} onChange={lowThreshold => update(draft => { draft.health.lowThreshold = lowThreshold; })} /></Field>
<Field label="血条宽度" hint="分别限制在计时两侧"><Slider value={hud.health.width} min={0.15} max={0.9} step={0.01} format={value => `${(value * 100).toFixed(0)}%`} onChange={width => update(draft => { draft.health.width = width; })} /></Field>
</>;
case "feedback": return <>
<Switch checked={hud.hitFeedback.flash} label="受击时画面四周泛红" onChange={flash => update(draft => { draft.hitFeedback.flash = flash; })} />
<Switch checked={hud.hitFeedback.marker} label="在瞄点旁显示伤害数字" onChange={marker => update(draft => { draft.hitFeedback.marker = marker; })} />
<Field label="泛红强度"><Slider value={hud.hitFeedback.intensity} min={0.2} max={2} step={0.1} format={value => `${value.toFixed(1)}×`} onChange={intensity => update(draft => { draft.hitFeedback.intensity = intensity; })} /></Field>
<Switch checked={hud.showZoom} label="显示放大倍率" onChange={showZoom => update(draft => { draft.showZoom = showZoom; })} />
{snapshot.diagnostics && <Switch checked={hud.showStats} label="显示丢包率(诊断模式)" onChange={showStats => update(draft => { draft.showStats = showStats; })} />}
</>;
case "slots": return <>
<div className="settings__span"><Switch checked={snapshot.slots.manual} label="手动指定槽位" onChange={manual => void run(() => api.setRefereeSlots({ ...snapshot.slots, manual }))} /></div>
<Field label={`左格 · ${teamName(0, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraA} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraA => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraA, manual: true }))} /></Field>
<Field label={`右格 · ${teamName(1, config.teamNames)} 图传`}><Select value={snapshot.slots.cameraB} options={cameraOptions} disabled={!snapshot.slots.manual} onChange={cameraB => void run(() => api.setRefereeSlots({ ...snapshot.slots, cameraB, manual: true }))} /></Field>
<Field label={`左格 · ${teamName(0, config.teamNames)} 装甲板`}><Select value={snapshot.slots.armorA} options={armorOptions} disabled={!snapshot.slots.manual} onChange={armorA => void run(() => api.setRefereeSlots({ ...snapshot.slots, armorA, manual: true }))} /></Field>
<Field label={`右格 · ${teamName(1, config.teamNames)} 装甲板`}><Select value={snapshot.slots.armorB} options={armorOptions} disabled={!snapshot.slots.manual} onChange={armorB => void run(() => api.setRefereeSlots({ ...snapshot.slots, armorB, manual: true }))} /></Field>
</>;
case "media": return <>
<div className="settings__span"><Field label="输出目录"><input className="input" type="text" defaultValue={config.recordingDir} onBlur={event => {
const value = event.target.value.trim();
if (value !== config.recordingDir) void run(() => api.setRecordingOptions({ dir: value, ffmpeg: null, crf: null, preset: null }));
}} /></Field></div>
<div className="settings__span"><Field label="ffmpeg 路径" hint="默认从 PATH 查找。未找到时无法录制,其他功能仍可用。"><input className="input" type="text" defaultValue={config.ffmpeg} onBlur={event => {
const value = event.target.value.trim();
if (value && value !== config.ffmpeg) void run(() => api.setRecordingOptions({ dir: null, ffmpeg: value, crf: null, preset: null }));
}} /></Field></div>
<p className="sect__note settings__span">界面内回放仅支持允许访问的目录,默认包含 ~/Movies/cam-desktop。其他目录中的视频可用系统播放器打开。</p>
</>;
case "security": return <>
<div className="settings__span"><ChangePassword onDone={onInfo} onError={onError} /></div>
<div className="settings__danger settings__span">
<div><strong>清空本机配置</strong><p>原配置备份为 .bak,之后需重启程序。</p></div>
<Button variant="danger" onClick={() => {
if (!window.confirm("清空配置并重启设置流程?旧配置将备份为 .bak,操作后需重启程序。")) return;
void api.clearConfig().then(onInfo, err => { const text = err instanceof Error ? err.message : String(err); if (text.includes("密码")) onNeedsUnlock(text); else onError(text); });
}}>清空配置</Button>
</div>
<div className="settings__danger settings__span">
<div><strong>退出客户端</strong><p>正在进行的录制会先结束并保存。</p></div>
<Button variant="danger" onClick={() => {
if (!window.confirm("退出程序?正在进行的录制将先结束并保存。")) return;
void api.quit().catch(err => { const text = err instanceof Error ? err.message : String(err); if (text.includes("密码")) onNeedsUnlock(text); else onError(text); });
}}>退出程序</Button>
</div>
</>;
}
};
return <aside ref={panelRef} className={`settings drawer${closing ? " is-closing" : ""}`} role="dialog" aria-modal="true" aria-label="设置" onKeyDown={trapFocus}
onAnimationEnd={event => { if (event.target === event.currentTarget && event.animationName === "settings-out") onExitComplete?.(); }}>
<header className="settings__head">
<div><span className="label">{isTeam ? "OPERATOR" : "REFEREE"} / CONFIGURATION</span><h1>设置</h1></div>
<div className="settings__head-actions">
{isTeam && snapshot.unlocked && <Button variant="ghost" disabled={closing} onClick={() => { void api.lock().then(() => { onInfo("已重新上锁。"); onClose(); }); }} title="锁定设置,修改时需重新输入密码">上锁</Button>}
<button ref={closeButton} type="button" className="btn btn--ghost settings__back" disabled={closing} onClick={onClose}><kbd>ESC</kbd> 返回</button>
</div>
</header>
{locked && <div className="settings__locked"><span>修改设置前请先输入密码解锁。</span><button type="button" className="btn btn--ghost" onClick={() => onNeedsUnlock("修改设置需要密码")}>解锁设置</button></div>}
<div className="settings__main">
<nav className="settings__nav" role="tablist" aria-orientation="vertical" aria-label="设置分类">
{categories.map((category, index) => <button key={category.id} id={`settings-tab-${category.id}`} type="button" role="tab" aria-selected={selected === category.id} aria-controls="settings-page" tabIndex={selected === category.id ? 0 : -1}
className={`settings__tab${selected === category.id ? " is-active" : ""}`} disabled={closing} onClick={() => switchCategory(category.id)} onKeyDown={event => navigate(event, index)}>
<span className="settings__tab-index num">{String(index + 1).padStart(2, "0")}</span><span><strong>{category.label}</strong><small>{category.en}</small></span><span className="settings__tab-arrow" aria-hidden="true">›</span>
</button>)}
</nav>
<div className="settings__viewport">
<div key={current.id} id="settings-page" role="tabpanel" aria-labelledby={`settings-tab-${current.id}`} className={`settings__page${next ? " is-leaving" : ""}${current.preview ? " settings__page--preview" : ""}`} style={{ ["--page-direction" as string]: direction }}
onAnimationEnd={event => { if (event.target === event.currentTarget && event.animationName === "settings-page-out" && next) { setActive(next); setNext(null); } }}>
<div className="settings__page-head"><span className="label">{current.en}</span><h2>{current.label}</h2><p>{current.hint}</p></div>
<div className="settings__workspace">
<fieldset className="settings__form" disabled={locked || closing}>{content()}</fieldset>
{current.preview && <Preview hud={hud} team={snapshot.team} />}
</div>
</div>
</div>
</div>
<footer className="settings__foot"><span>{pending ? "等待保存…" : "修改自动保存"}<span className="settings__save-note"> · 停止拖动滑杆 350 ms 后自动保存</span></span><span className="num">{VERSION_LABEL} · 线路协议 {BUILD.protocol}</span></footer>
</aside>;
}
/* ───────────────────────────────────────────────────────────── 实时预览 */
/**
* 预览窗:用真正的绘制代码画一遍当前设置。
*
* 它不是一个示意图——`paintCrosshair` / `paintGrid` 就是画面里用的那两个函数。所以"预览里
* 对、画面上偏"这种最坏的情况在这里不可能发生。
*
* 血量那根滑杆是刻意加的:低血阈值与脉动只有真的把血拖下去才看得见。
*/
function Preview({ hud, team }: { hud: HudView; team: number }) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const [demoHp, setDemoHp] = useState(68);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const paint = () => {
const dpr = window.devicePixelRatio || 1;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (width === 0 || height === 0) return;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
// 伪画面:一块低饱和的远景色 + 一条地平线。它的作用是让准星与网格有一个"深色背景
// 之上"的参照,而不是浮在一片纯黑里看不出对比。
const sky = ctx.createLinearGradient(0, 0, 0, height);
sky.addColorStop(0, "#141d25");
sky.addColorStop(0.55, "#1b2630");
sky.addColorStop(1, "#0b1015");
ctx.fillStyle = sky;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "rgba(120, 150, 170, 0.16)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, height * 0.62);
ctx.lineTo(width, height * 0.62);
ctx.stroke();
const geometry: Geometry = {
left: 0,
top: 0,
drawWidth: width,
drawHeight: height,
};
if (hud.grid.visible) paintGrid(ctx, geometry, hud.grid);
if (hud.crosshair.visible) {
// 预览里的偏移按比例缩到这块小画布上,方向与真画面一致。
const cx = width * (0.5 + hud.crosshair.offsetX);
const cy = height * (0.5 + hud.crosshair.offsetY);
paintCrosshair(ctx, cx, cy, Math.min(width, height), hud.crosshair);
}
};
paint();
// 字体与尺寸都可能在挂载之后才稳定:等一帧再画一次,别拿一个 0×0 的画布交付。
const raf = requestAnimationFrame(paint);
const observer = new ResizeObserver(paint);
observer.observe(canvas);
return () => {
cancelAnimationFrame(raf);
observer.disconnect();
};
}, [hud]);
// 预览用的血量。`available` 恒为 true:占位符的形态在真画面上看更清楚。
const mock: TeamHealthDto = {
team,
name: "预览",
available: true,
placeholder: "",
hp: demoHp,
hps: [],
board: null,
boardText: null,
critical: demoHp <= hud.health.lowThreshold,
outcome: null,
};
return (
<div className="preview">
<div className="preview__head">
<span className="label">HUD PREVIEW</span>
<span className="preview__note">合成画面 · 非设备图传</span>
</div>
<div className="preview__frame corners">
<canvas ref={canvasRef} className="preview__canvas" />
{hud.health.visible && (
<div className="preview__hp">
<HealthBar
health={mock}
config={{ ...hud.health, width: Math.min(1, hud.health.width * 2) }}
align="left"
tag="我方"
/>
</div>
)}
</div>
<div className="preview__control">
<span className="preview__control-label">预览血量</span>
<Slider
value={demoHp}
min={0}
max={100}
step={1}
format={(value) => `${value}`}
onChange={setDemoHp}
/>
<span className="preview__threshold num">低血 ≤{hud.health.lowThreshold}</span>
</div>
</div>
);
}
/* ───────────────────────────────────────────────────────────── 校准 */
/** 瞄准器偏移:拖画面校准 + 数值微调 + 归零。 */
function Calibration({
crosshair,
calibrating,
onCalibrating,
onChange,
}: {
crosshair: CrosshairConfig;
calibrating: boolean;
onCalibrating: (active: boolean) => void;
onChange: (offsetX: number, offsetY: number) => void;
}) {
return (
<div className="calib">
<Switch checked={calibrating} label="拖动画面校准瞄准点" onChange={onCalibrating} />
<p className="sect__note">
摄像头与枪管不同轴时,可将瞄准点调整到弹着点。偏移按
<span className="em">画面比例</span>保存,更换分辨率或调整窗口大小后仍有效。
</p>
<Field label="水平偏移">
<Slider
value={crosshair.offsetX}
min={-0.3}
max={0.3}
step={0.001}
format={(value) => `${(value * 100).toFixed(2)}%`}
onChange={(value) => onChange(value, crosshair.offsetY)}
/>
</Field>
<Field label="垂直偏移">
<Slider
value={crosshair.offsetY}
min={-0.3}
max={0.3}
step={0.001}
format={(value) => `${(value * 100).toFixed(2)}%`}
onChange={(value) => onChange(crosshair.offsetX, value)}
/>
</Field>
<div className="sect__row">
<Button variant="ghost" onClick={() => onChange(0, 0)}>
偏移归零
</Button>
</div>
</div>
);
}
/* ───────────────────────────────────────────────────────── 改密码 */
/** 改密码。 */
function ChangePassword({
onDone,
onError,
}: {
onDone: (message: string) => void;
onError: (message: string) => void;
}) {
const [current, setCurrent] = useState("");
const [fresh, setFresh] = useState("");
const [busy, setBusy] = useState(false);
return (
<div className="pw">
<input
className="input"
type="password"
aria-label="当前密码"
placeholder="当前密码"
autoComplete="off"
value={current}
onChange={(event) => setCurrent(event.target.value)}
/>
<input
className="input"
type="password"
aria-label="新密码"
placeholder="新密码(≥4 位)"
autoComplete="new-password"
value={fresh}
onChange={(event) => setFresh(event.target.value)}
/>
<div className="pw__actions">
<span className="pw__meter" aria-hidden="true">
{[0, 1, 2, 3].map((step) => (
<span key={step} className={`pw__cell${fresh.length > step ? " is-on" : ""}`} />
))}
</span>
<Button
disabled={busy || fresh.length < 4}
onClick={() => {
setBusy(true);
void api
.setPassword(fresh, current)
.then(() => {
onDone("密码已更新。");
setCurrent("");
setFresh("");
})
.catch((err) => onError(err instanceof Error ? err.message : String(err)))
.finally(() => setBusy(false));
}}
>
{busy ? "保存中…" : "修改密码"}
</Button>
</div>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
/**
* 底部遥测条。
*
* 它不承载操作,只回答"这一路现在怎么样":链路状态、帧率、分辨率、丢包、丢帧。
* 这些数字每一份快照(200 ms)都在变,所以排版必须是**定宽**的——值一变就换行或推动
* 邻格,会让整条一直在轻轻抖。
*
* 两侧留了两个槽给页面自己用(左边一般是状态,右边一般是操作提示),中间放读数。
*/
import type { ReactNode } from "react";
interface Props {
left?: ReactNode;
center?: ReactNode;
right?: ReactNode;
}
export function StatusBar({ left, center, right }: Props) {
return (
<footer className="statusbar">
<div className="statusbar__clamp">{left}</div>
<div className="statusbar__clamp statusbar__clamp--center">{center}</div>
<div className="statusbar__clamp statusbar__clamp--end">{right}</div>
</footer>
);
}
/**
* 一格读数:上面一个微标签,下面一个等宽值。
*
* `tone` 是有意义的:`warn` / `bad` 只在真的异常时出现,平时不抢注意力。
*/
export function Stat({
label,
value,
tone = "plain",
title,
}: {
label: string;
value: ReactNode;
tone?: "plain" | "hot" | "warn" | "bad" | "good";
title?: string;
}) {
return (
<span className={`stat stat--${tone}`} title={title}>
<span className="stat__label">{label}</span>
<span className="stat__value num">{value}</span>
</span>
);
}
+117
View File
@@ -0,0 +1,117 @@
/**
* 裁判端就地改队伍名。
*
* # 为什么是输入框而不是设置面板里的两项
*
* 现场改名字的时机是"比赛开始前,两队报上名来"。那时候裁判盯着的是两格画面,让他在
* 设置面板的某一节里找到对应项、改完再关掉,是一次没有必要的往返。名字就放在两格画面
* 各自下面,改完直接看到装甲条上的名字变了。
*
* # 回车/失焦才提交
*
* 逐字提交会在每次按键后写一次配置文件(还带一次原子替换),而且中间态("红"、"红队")
* 会被后端截断/回落规则改写一次,光标跟着跳。失焦提交是唯一不会跟打字打架的时机。
*
* 超过上限的字数由后端统一截断(`TEAM_NAME_MAX_CHARS`),这里也限一下长度——输入框
* 里就能看到"打不进去了",比提交后被悄悄截掉诚实。
*
* # 静止时它是一条读数
*
* 没在编辑的时候,它长得和旁边的帧率、状态一样:一个暗标签加一个值。只有点进去才展开成
* 带边框的输入框,并露出 `⏎ 保存` / `⎋ 撤销`。这样两格画面下面不会永远趴着两个表单控件。
*/
import { useEffect, useRef, useState } from "react";
import { DEFAULT_TEAM_NAMES, teamColor } from "../lib/format";
/** 与 Rust 侧的 `config::TEAM_NAME_MAX_CHARS` 一致。 */
const MAX_CHARS = 12;
interface Props {
team: number;
/** 当前生效的名字(来自快照,可能已经被后端规范化过)。 */
name: string;
/** 提交。后端会规范化,成功之后快照会带新名字回来。 */
onSave: (name: string) => void;
disabled?: boolean;
}
export function TeamNameEditor({ team, name, onSave, disabled }: Props) {
const [draft, setDraft] = useState(name);
const [editing, setEditing] = useState(false);
const focused = useRef(false);
/** Esc 已经改回去了,紧接着的那次失焦不该再提交。 */
const reverted = useRef(false);
// 焦点不在输入框里时跟着快照走:改完之后后端返回的规范名要能显示出来,而正在打字时
// 不能被一份恰好到达的快照顶掉。
useEffect(() => {
if (!focused.current) setDraft(name);
}, [name]);
const commit = () => {
focused.current = false;
setEditing(false);
if (reverted.current) {
reverted.current = false;
return;
}
if (draft === name) return;
const trimmed = draft.trim();
setDraft(trimmed);
onSave(trimmed);
};
const color = teamColor(team);
return (
<label
className={`tname${editing ? " is-editing" : ""}${disabled ? " is-disabled" : ""}`}
style={{ ["--team" as string]: color }}
>
<span className="tname__label" style={{ color }}>
{team === 0 ? "A" : "B"}
</span>
<input
className="tname__input"
value={draft}
maxLength={MAX_CHARS}
disabled={disabled}
placeholder={DEFAULT_TEAM_NAMES[team] ?? "队伍"}
title="按回车或点击别处保存,按 Esc 取消;留空使用默认队名"
onChange={(event) => setDraft(event.target.value)}
onFocus={() => {
focused.current = true;
setEditing(true);
}}
onBlur={commit}
onKeyDown={(event) => {
if (event.key === "Enter") {
// 只走失焦这一条提交路径,避免回车与失焦各提交一次。
event.currentTarget.blur();
} else if (event.key === "Escape") {
// 注意:不能只 `setDraft(name)` 再 blur——blur 是同一次事件里同步发生的,
// `commit` 读到的还是这一帧的旧 draft,于是"取消"反而把改动存了下去。
reverted.current = true;
setDraft(name);
event.currentTarget.blur();
}
}}
/>
<span className="tname__hint" aria-hidden="true">
<span className="tname__keys">
<kbd>⏎</kbd>保存 <kbd>⎋</kbd>取消
</span>
<span className="tname__count num">
{draft.length}/{MAX_CHARS}
</span>
</span>
</label>
);
}
+51
View File
@@ -0,0 +1,51 @@
/**
* 右下角的"调度单":错误与说明。
*
* # 为什么改成队列
*
* 原来只有 `error` / `info` 两个槽:后一条会把前一条顶掉。现场最容易出现的恰恰是**连着
* 两条**——比如"密码不对"紧跟着"绑定失败"。第二条盖住第一条,等于把第一句诊断吃掉了。
* 现在是一个最多四条的小队列,后来的排下面,各自计时。
*
* # 它自己会走,但也能留在那儿
*
* 说明类 6 秒、错误类 12 秒;鼠标停在上面时暂停计时(`onPointerEnter/Leave` 交给 CSS 的
* `animation-play-state` 不够用,所以计时在 JS 里)。点一下立刻收起。
*/
export interface ToastItem {
id: number;
kind: "info" | "error";
message: string;
}
interface Props {
toasts: ToastItem[];
onDismiss: (id: number) => void;
}
export function Toasts({ toasts, onDismiss }: Props) {
if (toasts.length === 0) return null;
return (
<div className="toasts" role="log" aria-live="polite">
{toasts.map((toast) => (
<div
key={toast.id}
className={`toast toast--${toast.kind}`}
role={toast.kind === "error" ? "alert" : "status"}
onClick={() => onDismiss(toast.id)}
>
<span className="toast__bar" aria-hidden="true" />
<span className="toast__code label">
{toast.kind === "error" ? "ERR" : "NOTE"}
</span>
<span className="toast__text">{toast.message}</span>
<span className="toast__close" aria-hidden="true">
✕
</span>
</div>
))}
</div>
);
}
+154
View File
@@ -0,0 +1,154 @@
/**
* 顶部状态条:身份、链路、演练模式、录制,以及三个入口。
*
* # 它不只是导航
*
* 这一条是"终端在运行"的唯一常驻证据:左边是系统自己的身份(我是谁、跑在什么状态下),
* 中间是链路的实况,右边是能做的事。所以它按"从系统到自己"的顺序排,而不是按"按钮放哪
* 顺手"。
*
* # 演练模式的标记**必须显眼**
*
* 那一整屏画面与血量都是本机合成的。截图或验收时把它当成真实链路会得出完全错误的结论,
* 所以它是一个虚线框的琥珀标签,并且点得动——点开就说清楚这次演示合成了什么。
*/
import type { ReactNode } from "react";
import { dismissNote, pushNote, useAppStore } from "../lib/store";
import type { Snapshot } from "../lib/types";
interface Props {
snapshot: Snapshot;
connected: boolean;
fullscreen: boolean;
onOpenSettings: () => void;
onOpenMaintenance?: () => void;
onToggleFullscreen: () => void;
/** 这一页自己的东西,插在中间。 */
children?: ReactNode;
}
export function TopBar({
snapshot,
connected,
fullscreen,
onOpenSettings,
onOpenMaintenance,
onToggleFullscreen,
children,
}: Props) {
const team = snapshot.role === "team";
const recording = snapshot.recordings.length;
return (
<header className={`topbar topbar--${snapshot.role}`}>
<div className="topbar__cluster">
{/* 队标只以"字标"的形态出现在顶栏:它的笔画在 17px 上只剩 1px,缩到这么小
会糊成一团反而更难看。完整的队标留给启动页(在那里它有 30px)。 */}
<span className="topbar__brand" title="RMIC::2026 · Simba Robotics">
<span className="topbar__wordmark">
RMIC<span className="topbar__slash">::</span>2026
</span>
</span>
<span className={`topbar__role role--${snapshot.role}`}>
<span className="topbar__role-cn">{team ? "用户端" : "裁判端"}</span>
<span className="topbar__role-en">{team ? "OPERATOR" : "REFEREE"}</span>
</span>
{snapshot.demo && (
<button
type="button"
className="tag tag--warn tag--button"
title="画面与血量由本机合成,不代表现场裁判系统状态。"
onClick={() =>
pushNote(
"演示模式:画面与血量均为本机合成数据。截图和测试记录中请注明。",
)
}
>
演示 · 合成数据
</button>
)}
{snapshot.diagnostics && <span className="tag tag--link">诊断</span>}
{!connected && (
<span className="tag tag--warn">
<span className="dot dot--warn" />
通道断开 · 重连中
</span>
)}
{recording > 0 && (
<span className="tag tag--danger">
<span className="rec-dot" />
录制 ×{recording}
</span>
)}
</div>
<div className="topbar__cluster topbar__cluster--center">{children}</div>
<div className="topbar__cluster topbar__cluster--end">
<span className="topbar__clients num" title="连接本机服务的界面数">
{snapshot.clients}
<span className="topbar__clients-unit">UI</span>
</span>
<span className="topbar__sep" aria-hidden="true" />
{onOpenMaintenance && (
<button type="button" className="btn btn--quiet" onClick={onOpenMaintenance}>
固件
</button>
)}
<button
type="button"
className="btn btn--quiet"
onClick={onToggleFullscreen}
title="F11 / Alt+Enter"
>
{fullscreen ? "退出全屏" : "全屏"}
</button>
<button type="button" className="btn btn--ghost topbar__settings" onClick={onOpenSettings}>
设置
<span className="topbar__kbd">⌘,</span>
</button>
</div>
</header>
);
}
/**
* 一条"通讯":后端推来的说明,或本机校验失败时塞进来的话。
*
* 只显示最新一条。它是一条会自己消失的横带,不是弹窗——现场的说法是"一句顶一句",
* 一次铺开六条谁也读不完。
*/
export function CommStrip() {
const { notes } = useAppStore();
const latest = notes.at(-1);
if (!latest) return null;
return (
<div className="comm" role="status">
<span className="comm__marker label">COMM</span>
<span className="comm__text">{latest}</span>
<button
type="button"
className="comm__close"
onClick={() => dismissNote(notes.length - 1)}
title="收起"
>
✕
</button>
</div>
);
}
+141
View File
@@ -0,0 +1,141 @@
/**
* 解锁对话框。
*
* 它只是**入口**,不是闸门:真正拦住改绑的是后端的 `require_unlocked`。所以这里即使
* 被人绕过、甚至被改成永远返回成功,配置也改不动。
*
* # 它是"校验"而不是"弹窗"
*
* 这一层出现时,背后的一切都停了:整屏压暗、面板上扫过一条校验线、左下角挂着 `LOCKED`。
* 现场有人要改绑定,多半是在出问题的时候;那时候界面必须明确地说"现在这一步是在验证身份",
* 而不是给出一个和别处一样的灰色小框。
*/
import { useEffect, useRef, useState } from "react";
import { api } from "../lib/ipc";
interface Props {
/** 为什么需要密码:显示在标题下。 */
reason: string;
onUnlocked: () => void;
onCancel: () => void;
}
export function UnlockDialog({ reason, onUnlocked, onCancel }: Props) {
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const input = useRef<HTMLInputElement | null>(null);
const dialogRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const dialog = dialogRef.current;
input.current?.focus({ preventScroll: true });
return () => {
if (previous?.isConnected && (document.activeElement === document.body || dialog?.contains(document.activeElement))) {
previous.focus({ preventScroll: true });
}
};
}, []);
const submit = async () => {
if (busy) return;
setBusy(true);
setError(null);
try {
const ok = await api.unlock(password);
if (ok) {
onUnlocked();
} else {
setError("密码错误");
setPassword("");
input.current?.focus();
}
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
};
return (
<div ref={dialogRef} className="overlay" role="dialog" aria-modal="true" aria-label="需要密码" tabIndex={-1}
onKeyDown={event => {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
onCancel();
return;
}
if (event.key !== "Tab") return;
const controls = event.currentTarget.querySelectorAll<HTMLElement>(
'button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])',
);
const first = controls[0];
const last = controls[controls.length - 1];
if (!first) {
event.preventDefault();
event.currentTarget.focus();
} else if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}}>
<div className={`lock plate${error ? " is-wrong" : ""}`}>
<span className="lock__scan" aria-hidden="true" />
<span className="lock__tag label">LOCKED</span>
<header className="lock__head">
<h2 className="lock__title">需要密码</h2>
<p className="lock__reason">{reason}</p>
</header>
<label className="lock__field">
<span className="lock__field-label label">ACCESS KEY</span>
<input
ref={input}
className="input input--lg"
type="password"
value={password}
placeholder="输入现场密码"
autoComplete="off"
onChange={(event) => setPassword(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") void submit();
}}
/>
</label>
{error && <p className="lock__error">{error}</p>}
<p className="lock__note">
密码用于防止现场误改设置;能修改本机配置或程序的人仍可绕过。
忘记密码时,可删除配置文件中的 password 一行。
</p>
<div className="lock__actions">
<button type="button" className="btn btn--ghost" onClick={onCancel}>
取消
</button>
<button
type="button"
className="btn btn--primary"
onClick={() => void submit()}
disabled={busy || password.length === 0}
>
{busy ? "校验中…" : "解锁"}
<span className="btn__key">⏎</span>
</button>
</div>
</div>
</div>
);
}
+445
View File
@@ -0,0 +1,445 @@
/**
* 一路画面:canvas 绘制 + 缩放/平移 + 网格 + 瞄准器 + 命中反馈 + 取景框。
*
* # 为什么画在 canvas 上而不是用 CSS 变换 `<img>`
*
* 瞄准器必须跟着**画面**走:它标的是相机光轴上的一个点。用 DOM 摆一个 `<img>` 再叠一层
* `transform` 的话,"图像落在哪、瞄准点落在哪"要算两遍,而两份实现迟早会不一致——表现
* 是放大之后瞄准器偏了,恰恰发生在这件事最要紧的时候。
*
* 所以变换只算一次(`computeLayout`),图像、网格、瞄准器、伤害数字全都用同一组数画出来。
*
* # 尺寸与缩放的关系
*
* - 图像按 `contain` 放进窗格,再乘 `zoom`。
* - **网格**画在图像矩形里,跟着缩放走:它标的是画面里的比例,用来估距离。
* - **瞄准器**的**位置**跟着图像走,**大小**不跟着:像真瞄具一样,放大之后准星不会
* 跟着变粗,而是覆盖画面里更小的一块——那正是放大有用武之地的原因。
* - 镜像靠 `scale(-1, 1)`,同时把拖动方向也翻过来,否则向右拖画面会往左走。
*
* # 缩放是"追"上去的,平移是"贴"着手的
*
* 滚轮换倍率时,画面用三帧左右追到目标值:一下子跳过去会让人失去"放大了多少"的感觉。
* 反过来,拖动必须 1:1——指针走一像素,画面就走一像素,中间加任何缓动都会变成黏手。
* 两者由 `dragging` 这个 ref 分开:拖动期间平移直接跟,其余时候参与插值。
*/
import { useEffect, useRef, type ReactNode } from "react";
import { streamClient } from "../lib/store";
import {
aimPoint,
computeLayout,
paintCrosshair,
paintGrid,
type Geometry,
} from "../lib/reticle";
import type { CrosshairConfig, GridConfig, HitFeedbackConfig } from "../lib/types";
import type { FrameInfo } from "../lib/stream";
export interface ViewTransform {
zoom: number;
x: number;
y: number;
}
export const IDENTITY_VIEW: ViewTransform = { zoom: 1, x: 0, y: 0 };
/** 缩放上下限。再多只是把像素拉大。 */
export const MIN_ZOOM = 1;
export const MAX_ZOOM = 8;
export const ZOOM_STEP = 1.25;
export interface HitPulse {
/** 每次命中都不同,用来重启动画。 */
seq: number;
damage: number;
/** `performance.now()` 时刻。 */
at: number;
}
interface Props {
camera: number | null;
emptyText: string;
mirrored: boolean;
crosshair: CrosshairConfig | null;
grid: GridConfig | null;
view: ViewTransform;
onView: (view: ViewTransform) => void;
/** 校准模式:拖动画面来挪瞄准点。 */
calibrating?: boolean;
onCalibrate?: (dxFraction: number, dyFraction: number) => void;
/** 命中脉冲。只有属于这一路的命中才该传进来。 */
hit?: HitPulse | null;
hitFeedback: HitFeedbackConfig;
showZoom: boolean;
showResetControl?: boolean;
/** 图传不可用时保留最后一帧,并用灰度与遮罩标记旧画面。 */
signalLost?: boolean;
children?: ReactNode;
/** Only used by the opt-in screen/camera calibration page. */
onFramePainted?: (canvas: HTMLCanvasElement, frame: FrameInfo, drawMs: number) => void;
/** 左上角的代号(`CAM · A`、队名)。缺省时不画。 */
label?: string;
/** 这一路被"选中"了(裁判端的 scope)。视觉上给一圈亮框。 */
focused?: boolean;
/** 按下左键时通知外层。裁判端用它把下方控制台切到这一路。 */
onSelect?: () => void;
}
/** 命中动画持续多久。与 CSS 里的 `hit-*` 动画保持一致。 */
const HIT_MS = 700;
/** 缩放插值系数。0.28 在 60 fps 下约 3 帧收敛,够快,又不至于看不出在放大。 */
const ZOOM_LERP = 0.28;
/** 复位时平移的插值系数。比缩放慢一点,让"收回去"这个动作看得见。 */
const PAN_LERP = 0.2;
export function VideoSurface({
camera,
emptyText,
mirrored,
crosshair,
grid,
view,
onView,
calibrating = false,
onCalibrate,
hit = null,
hitFeedback,
showZoom,
showResetControl = true,
signalLost = false,
children,
onFramePainted,
label,
focused = false,
onSelect,
}: Props) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
// 绘制循环不随 props 重建,所以最新一份 props 放在 ref 里给它读。
const props = useRef({ camera, mirrored, crosshair, grid, view, hit, hitFeedback, onFramePainted });
props.current = { camera, mirrored, crosshair, grid, view, hit, hitFeedback, onFramePainted };
/** 屏幕上**当前**的视图。它追着 `view` 走,但有自己的惯性。 */
const shown = useRef<ViewTransform>({ ...view });
const dragging = useRef(false);
const drag = useRef<{ x: number; y: number; originX: number; originY: number } | null>(null);
const dirty = useRef(true);
const lastFrameId = useRef<number | null>(null);
useEffect(() => {
dirty.current = true;
}, [camera, mirrored, crosshair, grid, view, hit, hitFeedback]);
// canvas 的像素尺寸跟着 CSS 尺寸与 DPR 走。不这么做的话在 Retina 上会糊。
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const resize = () => {
const dpr = window.devicePixelRatio || 1;
const width = Math.max(1, Math.round(canvas.clientWidth * dpr));
const height = Math.max(1, Math.round(canvas.clientHeight * dpr));
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
dirty.current = true;
}
};
resize();
const observer = new ResizeObserver(resize);
observer.observe(canvas);
return () => observer.disconnect();
}, []);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
let raf = 0;
const loop = (timestamp: number) => {
raf = requestAnimationFrame(loop);
const current = props.current;
const frame = streamClient().latest(current.camera);
const newFrame = frame && frame.frameId !== lastFrameId.current;
if (newFrame) {
lastFrameId.current = frame.frameId;
dirty.current = true;
}
// 视图追上去。拖动时平移不许插值(会黏手),其余时候连平移一起缓动。
const target = current.view;
const next = shown.current;
const before = `${next.zoom}|${next.x}|${next.y}`;
if (Math.abs(next.zoom - target.zoom) > 0.0005) {
next.zoom += (target.zoom - next.zoom) * ZOOM_LERP;
} else {
next.zoom = target.zoom;
}
if (dragging.current) {
next.x = target.x;
next.y = target.y;
} else {
const k = target.zoom <= MIN_ZOOM + 0.0005 ? PAN_LERP : 1;
next.x += (target.x - next.x) * k;
next.y += (target.y - next.y) * k;
if (Math.abs(next.x - target.x) < 0.4) next.x = target.x;
if (Math.abs(next.y - target.y) < 0.4) next.y = target.y;
}
if (before !== `${next.zoom}|${next.x}|${next.y}`) dirty.current = true;
// 命中动画期间必须持续重绘,否则闪红/伤害数字只画了一帧就停住。
//
// **抖动没有了**(见 `HitFeedbackConfig::shake` 的文档):不再有"整幅图跟着晃"的
// 那一路,所以这里也不再需要因为抖动而复绘。
const pulseAge = current.hit ? timestamp - current.hit.at : Number.POSITIVE_INFINITY;
const animating =
pulseAge < HIT_MS && (current.hitFeedback.marker || current.hitFeedback.flash);
if (!dirty.current && !animating) return;
dirty.current = false;
draw(canvas, current, shown.current, frame, timestamp);
if (newFrame && current.onFramePainted) {
current.onFramePainted(canvas, frame, performance.now());
}
};
raf = requestAnimationFrame(loop);
return () => cancelAnimationFrame(raf);
}, []);
// ---- 输入 ----
const onWheel = (event: React.WheelEvent<HTMLDivElement>) => {
const factor = event.deltaY > 0 ? 1 / ZOOM_STEP : ZOOM_STEP;
const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);
// 缩回 1 时顺便归位:此时画面完整可见,平移没有意义,留着会让下一次放大从偏移位置
// 开始,看起来像"跳了一下"。
onView(zoom <= MIN_ZOOM ? IDENTITY_VIEW : { ...view, zoom });
};
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
event.currentTarget.setPointerCapture(event.pointerId);
dragging.current = true;
drag.current = { x: event.clientX, y: event.clientY, originX: view.x, originY: view.y };
onSelect?.();
};
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
const start = drag.current;
if (!start) return;
const dx = event.clientX - start.x;
const dy = event.clientY - start.y;
if (calibrating) {
// 校准:把屏幕上的位移换算成画面里的比例位移。用当前显示出来的图像尺寸做分母,
// 所以放大之后校准更精细——这正是需要的。
const box = canvasRef.current;
if (!box || !onCalibrate) return;
const frame = streamClient().latest(camera);
if (!frame) return;
const { drawWidth, drawHeight } = computeLayout(box, frame.width, frame.height, view);
if (drawWidth <= 0 || drawHeight <= 0) return;
// 一次移动一小步,然后把起点挪过来。
drag.current = { ...start, x: event.clientX, y: event.clientY };
const sign = mirrored ? -1 : 1;
onCalibrate((sign * dx) / drawWidth, dy / drawHeight);
return;
}
if (view.zoom <= MIN_ZOOM) return;
// 镜像时把横向拖动也翻过来:否则向右拖,画面往左走,看起来像拖动坏了。
const sign = mirrored ? -1 : 1;
onView({ ...view, x: start.originX + sign * dx, y: start.originY + dy });
};
const endDrag = () => {
dragging.current = false;
drag.current = null;
};
const cursor = calibrating ? "crosshair" : view.zoom > MIN_ZOOM ? "grab" : "default";
const zoomed = shown.current.zoom > MIN_ZOOM + 0.05;
const moved = view.zoom > MIN_ZOOM + 0.05 || view.x !== 0 || view.y !== 0;
// 倍率在右缘的"尺"上用一个游标表示。对数刻度:8 倍是 0 到 1 的满格,2 倍在中段——
// 线性刻度会让 1..2 挤成一条线,而那正是最常待的区间。
const zoomT = Math.log(view.zoom) / Math.log(MAX_ZOOM);
return (
<div
className={`vsurface${focused ? " vsurface--focused" : ""}${
calibrating ? " vsurface--calibrating" : ""
}${signalLost ? " vsurface--signal-lost" : ""}`}
style={{ cursor }}
onWheel={onWheel}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
onDoubleClick={() => onView(IDENTITY_VIEW)}
>
<canvas ref={canvasRef} className="vsurface__canvas" />
{signalLost && <div className="vsurface__signal-mask" aria-hidden="true" />}
{/* 取景框:四角括号 + 一条从左上角伸出来指向画面中心的引线。
它们是"这是一个被观察的窗口"的唯一提示,不占像素、不挡画面。 */}
<div className="vsurface__reticle-frame" aria-hidden="true">
<span className="vsurface__corner vsurface__corner--tl" />
<span className="vsurface__corner vsurface__corner--tr" />
<span className="vsurface__corner vsurface__corner--bl" />
<span className="vsurface__corner vsurface__corner--br" />
</div>
{label && <div className="vsurface__label label">{label}</div>}
{emptyText !== "" && (
<div className="vsurface__empty">
<span className="vsurface__empty-mark" aria-hidden="true" />
<span>{emptyText}</span>
</div>
)}
{showZoom && zoomed && (
<div className="vsurface__ruler" aria-hidden="true">
<span className="vsurface__ruler-cursor" style={{ top: `${(1 - zoomT) * 100}%` }}>
<span className="num">×{view.zoom.toFixed(2)}</span>
</span>
</div>
)}
{moved && showResetControl && (
<button
type="button"
className="vsurface__reset"
onClick={() => onView(IDENTITY_VIEW)}
onPointerDown={(event) => event.stopPropagation()}
title="重置缩放与平移(也可双击画面)"
>
<span className="vsurface__reset-key">⤢</span>
复位
</button>
)}
{calibrating && (
<div className="vsurface__calibrating">
<span className="dot dot--live" />
校准中 · 拖动画面调整瞄准点
</div>
)}
{children}
</div>
);
}
// ---------------------------------------------------------------------------
// 绘制
// ---------------------------------------------------------------------------
interface CanvasProps {
camera: number | null;
mirrored: boolean;
crosshair: CrosshairConfig | null;
grid: GridConfig | null;
hit: HitPulse | null;
hitFeedback: HitFeedbackConfig;
}
function draw(
canvas: HTMLCanvasElement,
current: CanvasProps,
view: ViewTransform,
frame: { bitmap: ImageBitmap; width: number; height: number } | undefined,
timestamp: number,
) {
const dpr = window.devicePixelRatio || 1;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const box = { clientWidth: width, clientHeight: height };
// 没有画面时把瞄准器留在窗格中心:录像断了,准星不该跟着消失。
const geometry: Geometry = frame
? computeLayout(box, frame.width, frame.height, view)
: { left: 0, top: 0, drawWidth: 0, drawHeight: 0 };
if (frame) {
ctx.save();
if (current.mirrored) {
ctx.translate(width, 0);
ctx.scale(-1, 1);
}
// 放大超过 3 倍时关掉插值:这时候要看的是像素本身,双线性插值只会把它糊掉。
ctx.imageSmoothingEnabled = view.zoom < 3;
ctx.drawImage(frame.bitmap, geometry.left, geometry.top, geometry.drawWidth, geometry.drawHeight);
ctx.restore();
if (current.grid?.visible) paintGrid(ctx, geometry, current.grid);
}
const crosshair = current.crosshair;
const aim = aimPoint(geometry, crosshair, current.mirrored, width, height);
if (crosshair?.visible) {
paintCrosshair(ctx, aim.x, aim.y, Math.min(width, height), crosshair);
}
// 伤害数字:画在屏幕坐标里,不跟着缩放走。位置在瞄点右上,向上飘并淡出。
if (current.hit && current.hitFeedback.marker) {
const age = timestamp - current.hit.at;
if (age >= 0 && age < HIT_MS) {
const progress = age / HIT_MS;
const size = Math.round(Math.max(15, Math.min(width, height) * 0.052));
ctx.save();
ctx.globalAlpha = 1 - progress * progress;
ctx.font = `700 ${size}px "JetBrains Mono", ui-monospace, monospace`;
ctx.textAlign = "left";
ctx.textBaseline = "middle";
const text = `−${current.hit.damage}`;
const x = aim.x + size * 1.4;
const y = aim.y - size * 1.2 - progress * size * 1.6;
// 两层:一层深色描边保证在任何画面上可读,一层纯色本体。
ctx.lineWidth = Math.max(2, size * 0.16);
ctx.strokeStyle = "rgba(0, 0, 0, 0.75)";
ctx.strokeText(text, x, y);
ctx.fillStyle = "#ff6a52";
ctx.fillText(text, x, y);
ctx.restore();
}
}
}
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
+192
View File
@@ -0,0 +1,192 @@
/** 设置面板里复用的几个小控件。分成单独文件只是为了不把面板本身撑成一千行。
*
* 它们的排版约定写在 `styles/base.css` 里(`.btn`、`.switch`、`.slider`、`.select`、
* `.field`、`.readout`)。这里只负责把 props 翻译成结构。
*/
import type { ChangeEvent, ReactNode } from "react";
export function Section({
title,
hint,
children,
index,
id,
}: {
title: string;
hint?: string;
children: ReactNode;
/** 小节编号。设置面板是分节滚动的,编号让"第几节"这件事在滚动时还看得见。 */
index?: number;
/** 锚点。设置面板左侧的竖向导航靠它跳转,滚动时的联动也靠它。 */
id?: string;
}) {
return (
<section className="sect" id={id}>
<header className="sect__head">
{index !== undefined && (
<span className="sect__index num">{String(index).padStart(2, "0")}</span>
)}
<h3 className="sect__title">{title}</h3>
<span className="sect__rule" aria-hidden="true" />
</header>
{hint && <p className="sect__hint">{hint}</p>}
<div className="sect__body">{children}</div>
</section>
);
}
export function Field({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: ReactNode;
}) {
return (
<label className="field">
<span className="field__label">{label}</span>
<span className="field__control">{children}</span>
{hint && <span className="field__hint">{hint}</span>}
</label>
);
}
export function Switch({
checked,
onChange,
label,
disabled = false,
}: {
checked: boolean;
onChange: (value: boolean) => void;
label: string;
disabled?: boolean;
}) {
return (
<label className={`switch${disabled ? " switch--disabled" : ""}`}>
<input
type="checkbox"
checked={checked}
disabled={disabled}
onChange={(event: ChangeEvent<HTMLInputElement>) => onChange(event.target.checked)}
/>
<span className="switch__track">
<span className="switch__knob" />
</span>
<span className="switch__label">{label}</span>
</label>
);
}
export function Slider({
value,
min,
max,
step,
onChange,
format,
disabled = false,
}: {
value: number;
min: number;
max: number;
step: number;
onChange: (value: number) => void;
format?: (value: number) => string;
disabled?: boolean;
}) {
// 轨道的填充比例由 `--fill` 交给 CSS。反正要算,就一起算完,别让 CSS 再猜一次。
const span = max - min;
const ratio = span === 0 ? 0 : (value - min) / span;
return (
<span className="slider">
<input
type="range"
min={min}
max={max}
step={step}
value={value}
disabled={disabled}
style={{ ["--fill" as string]: `${Math.max(0, Math.min(1, ratio)) * 100}%` }}
onChange={(event) => onChange(Number(event.target.value))}
/>
<span className="slider__value">{format ? format(value) : value.toFixed(2)}</span>
</span>
);
}
export function Select<T extends string | number>({
value,
options,
onChange,
disabled = false,
}: {
value: T | null;
options: { value: T; label: string; hint?: string }[];
onChange: (value: T) => void;
disabled?: boolean;
}) {
// 已绑定的板子可能离线并从发现列表移除。保留真实选中值,避免原生
// select 静默显示第一块候选设备,让用户以为已经改绑成功。
const missing = value !== null && !options.some(option => String(option.value) === String(value));
return (
<select
className="select"
value={value === null ? "" : String(value)}
disabled={disabled}
onChange={(event) => {
const raw = event.target.value;
const match = options.find((option) => String(option.value) === raw);
if (match) onChange(match.value);
}}
>
{value === null && <option value="">(未选择)</option>}
{missing && <option value={String(value)} disabled>当前选择未发现,请重新选择</option>}
{options.map((option) => (
<option key={String(option.value)} value={String(option.value)}>
{option.hint ? `${option.label} — ${option.hint}` : option.label}
</option>
))}
</select>
);
}
export function Button({
children,
onClick,
variant = "default",
disabled = false,
title,
}: {
children: ReactNode;
onClick: () => void;
variant?: "default" | "primary" | "danger" | "ghost";
disabled?: boolean;
title?: string;
}) {
return (
<button
type="button"
className={`btn btn--${variant}`}
onClick={onClick}
disabled={disabled}
title={title}
>
{children}
</button>
);
}
/** 一行只读信息:左边标题、右边值。 */
export function Readout({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="readout">
<span className="readout__label">{label}</span>
<span className="readout__value">{value}</span>
</div>
);
}
+575
View File
@@ -0,0 +1,575 @@
/**
* 仅开发用的浏览器预览。
*
* # 它解决什么问题
*
* Tauri 的界面跑在 WKWebView 里,改一行 CSS 要走一次 cargo 构建;而且截图要靠 macOS 的
* 屏幕录制权限。预览模式让同一套 React 组件在浏览器里跑起来:状态由本文件合成,画面用
* `createImageBitmap` 从一块 canvas 上取——`VideoSurface`、血条、瞄准器、命中反馈全都是
* 真代码,只有"后端"是假的。
*
* # 它绝不可能进到正式构建里
*
* 两重门:
*
* 1. `import.meta.env.DEV` —— 只在 `vite dev` 下为真;`vite build` 时是 false,
* 2. 并且页面里没有 Tauri 注入的 `__TAURI_INTERNALS__`。
*
* 调用点还用 `await import(...)`:条件为假时整个模块不会被打进产物,而不是打进去再靠
* 运行时不走。
*
* # 用法
*
* ```sh
* pnpm dev # 用户端
* open 'http://127.0.0.1:1420/?preview=referee' # 裁判端
* ```
*/
import { DEFAULT_TEAM_NAMES } from "./format";
import { previewMatch, previewMatchAction } from "./match-preview";
import type { MatchAction } from "./types";
import type { StreamClient } from "./stream";
import type {
ConfigView,
HudView,
Snapshot,
WireMsg,
} from "./types";
/** 页面里有没有 Tauri 注入。 */
function hasTauri(): boolean {
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
}
/** 现在是不是在预览模式。 */
export function isPreview(): boolean {
return import.meta.env.DEV && !hasTauri();
}
const params = new URLSearchParams(typeof location === "undefined" ? "" : location.search);
const startAsReferee = params.get("preview") === "referee";
/**
* 首次启动的两道门。
*
* `?preview=first-run` 让 `roleChosen` 为假、`?preview=password` 让 `passwordSet` 为假,
* 这样不删配置也能看到那两块界面。它们只在预览里存在,正式构建里这段代码不会被打进去。
*/
const firstRun = params.get("preview") === "first-run";
const needsPassword = params.get("preview") === "password";
// 复现无信号时的 HUD;仍然使用合成状态,不连接真实设备。
const offlinePreview = params.get("preview") === "offline";
// 前 12 秒收流,随后断流 12 秒,再恢复;用于检查最后一帧的灰度遮罩。
const reconnectPreview = params.get("preview") === "reconnect";
const previewStartedAt = performance.now();
const missingBindingPreview = params.get("preview") === "missing-binding";
const wideLayoutPreview = params.get("layout") === "wide";
function videoOffline(): boolean {
const elapsed = performance.now() - previewStartedAt;
return offlinePreview || (reconnectPreview && elapsed >= 12_000 && elapsed < 24_000);
}
// ---------------------------------------------------------------------------
// 可变状态:设置面板里的改动会落到这里,界面因此是可交互的
// ---------------------------------------------------------------------------
const DEFAULT_HUD: HudView = {
health: {
visible: true,
showNumbers: true,
showTeamName: true,
lowThreshold: 30,
pulse: true,
width: 0.42,
},
crosshair: {
visible: true,
style: "cross-dot",
size: 0.045,
thickness: 0.004,
gap: 0.012,
color: "#3dff88",
offsetX: 0,
offsetY: 0,
},
grid: { visible: false, style: "thirds", divisions: 6, opacity: 0.22 },
hitFeedback: { flash: true, shake: false, marker: true, intensity: 1 },
showZoom: true,
showStats: true,
};
const CAMERA_A = 0x0de0_0001;
const CAMERA_B = 0x0de0_0002;
const ARMOR_A = 0x0a20_0001;
const ARMOR_B = 0x0a20_0002;
interface PreviewState {
role: "team" | "referee";
hud: HudView;
cameraId: number | null;
armorId: number | null;
team: number;
/** 两边显示的名字,与后端配置里的 `teamNames` 对应。 */
teamNames: [string, string];
mirror: boolean;
unlocked: boolean;
password: string | null;
calibrating: boolean;
recordings: { camera: number; frames: number; startedMs: number }[];
hp: [number, number];
}
const state: PreviewState = {
role: startAsReferee ? "referee" : "team",
hud: { ...structuredClone(DEFAULT_HUD), health: { ...DEFAULT_HUD.health, width: wideLayoutPreview ? 0.9 : DEFAULT_HUD.health.width } },
cameraId: startAsReferee ? null : missingBindingPreview ? 0x0de0_9999 : CAMERA_A,
armorId: startAsReferee ? null : ARMOR_A,
team: 0,
teamNames: wideLayoutPreview ? ["用户端长队名布局验证一队", "用户端长队名布局验证二队"] : ["队伍一", "队伍二"],
mirror: true,
// 预览里直接是已解锁状态,免得每次刷新都要输密码。
unlocked: false,
password: "1234",
calibrating: false,
recordings: [],
hp: [100, 100],
};
// ---------------------------------------------------------------------------
// 假的命令实现
// ---------------------------------------------------------------------------
/** 供 `ipc.ts` 在有 Tauri 时不会走到的分支上用。 */
export async function previewInvoke<T>(command: string, args?: Record<string, unknown>): Promise<T> {
const value = handle(command, args ?? {});
return value as T;
}
function handle(command: string, args: Record<string, unknown>): unknown {
switch (command) {
case "match_action":
if (state.role !== "referee") throw new Error("只有裁判端可以控制比赛计时");
previewMatchAction(args.action as MatchAction);
return;
case "release_match_source": return;
case "stream_info":
return { url: "preview://", port: 0, clients: 1 };
case "get_snapshot":
return snapshot();
case "get_config":
return configView();
case "list_media_files":
return [];
case "config_path":
return "/预览模式/没有真实配置文件";
case "unlock":
state.unlocked = String(args.password) === state.password;
return state.unlocked;
case "lock":
state.unlocked = false;
return undefined;
case "set_password":
state.password = String(args.fresh);
state.unlocked = true;
return configView();
case "set_discovery_open":
return undefined;
case "bind_camera":
guard();
state.cameraId = (args.cameraId as number | null) ?? null;
return configView();
case "bind_armor":
guard();
state.armorId = (args.armorId as number | null) ?? null;
return configView();
case "set_team":
guard();
state.team = Number(args.team);
return configView();
case "set_team_name": {
guard();
const team = Number(args.team);
if (team !== 0 && team !== 1) throw new Error("队伍号只能是 0 或 1");
// 与后端一样:合并空白、按字符截断、留空回落默认名。
state.teamNames[team] = sanitizeName(String(args.name ?? ""), team);
return configView();
}
case "set_role":
state.role = args.role as "team" | "referee";
return configView();
case "set_mirror":
state.mirror = Boolean(args.mirror);
return configView();
case "save_hud":
state.hud = args.hud as HudView;
return configView();
case "set_referee_slots":
return configView();
case "set_recording_options":
return configView();
case "screenshot":
return "/预览模式/没有截图";
case "start_recording": {
const cameras = (args.cameras as number[]) ?? [];
const startedMs = Date.now();
for (const camera of cameras) {
if (!state.recordings.some((r) => r.camera === camera)) {
state.recordings.push({ camera, frames: 0, startedMs });
}
}
return recordings();
}
case "stop_recording": {
const cameras = (args.cameras as number[]) ?? [];
state.recordings = cameras.length
? state.recordings.filter((r) => !cameras.includes(r.camera))
: [];
return recordings();
}
case "refresh":
case "reveal":
case "open_file":
return undefined;
case "clear_config":
return "预览模式:没有真实配置可清空";
case "quit":
return undefined;
default:
throw new Error(`预览模式没有实现命令 ${command}`);
}
}
/** 预览里模拟后端的密码闸门,好让解锁流程也能被看到。 */
function guard() {
if (state.role === "team" && state.password !== null && !state.unlocked) {
throw new Error("修改设置需要密码。请先解锁,预览模式密码为 1234。");
}
}
function configView(): ConfigView {
return {
role: state.role,
roleChosen: !firstRun,
team: state.team,
teamNames: [...state.teamNames] as [string, string],
cameraId: state.cameraId,
cameraIdText: state.cameraId === null ? null : hex(state.cameraId),
armorId: state.armorId,
armorIdText: state.armorId === null ? null : hex(state.armorId),
mirror: state.mirror,
passwordSet: needsPassword ? false : state.password !== null,
hud: structuredClone(state.hud),
recordingDir: "/预览模式/recordings",
ffmpeg: "ffmpeg",
};
}
function recordings() {
return state.recordings.map((recording) => ({
camera: recording.camera,
cameraText: hex(recording.camera),
active: true,
path: `/预览模式/rec-${recording.camera.toString(16)}.mp4`,
inputFps: 20,
framesWritten: recording.frames,
framesDropped: 0,
startedMs: recording.startedMs,
error: null,
}));
}
/** 与后端 `config::sanitize_team_name` 一致:合并空白、按字符截断、留空回落默认名。 */
function sanitizeName(name: string | undefined, team: number): string {
const collapsed = (name ?? "").split(/\s+/).filter(Boolean).join(" ");
const text = collapsed.length > 0 ? collapsed : DEFAULT_TEAM_NAMES[team];
return [...text].slice(0, 12).join("");
}
function hex(id: number): string {
return `0x${id.toString(16).toUpperCase().padStart(8, "0")}`;
}
function snapshot(): Snapshot {
const cameraOffline = videoOffline();
const cameras = [
{ id: CAMERA_A, team: 0 },
{ id: CAMERA_B, team: 1 },
].map(({ id, team }) => ({
id,
idText: hex(id),
addr: team === 0 ? "192.168.1.41" : "192.168.1.42",
online: !cameraOffline,
silenceMs: 120,
// 预览里模拟一块"版本对得上"的板子:界面上的固件标签因此能被看到。
firmwareVersion: "0.2.0",
firmwareBuild: 34,
protocol: 1,
compatible: true,
}));
const boards = [
{ id: ARMOR_A, team: 0 },
{ id: ARMOR_B, team: 1 },
].map(({ id, team }, index) => ({
id,
idText: hex(id),
addr: team === 0 ? "192.168.1.51" : "192.168.1.52",
online: !offlinePreview,
team,
hp: state.hp[index],
platesSeen: 4,
reportsAllPlates: true,
silenceMs: 90,
}));
const stats = cameras.map((camera) => ({
camera: camera.id,
cameraText: camera.idText,
online: !cameraOffline,
status: camera.idText,
hasFrames: !offlinePreview,
fps: cameraOffline ? 0 : 20,
width: 640,
height: 480,
framesShown: 1000,
framesDropped: 3,
lossPercent: 0.3,
datagrams: 17000,
lastFrameBytes: 22000,
gapMs: 50,
}));
// 与后端 `cam_core::snapshot::resolve_outcomes` 同一套规则,包括那条不对称:
// 输只看自己,赢要看对手归零**且**自己还活着。
const outcomeFor = (team: number) => {
const mine = state.hp[team];
const theirs = state.hp[team === 0 ? 1 : 0];
if (mine === 0 && theirs === 0) return "draw" as const;
if (theirs === 0 && mine > 0) return "victory" as const;
if (mine === 0) return "defeat" as const;
return null;
};
const healthFor = (team: number) => {
const hp = state.hp[team];
const board = team === 0 ? ARMOR_A : ARMOR_B;
return {
team,
name: state.teamNames[team],
available: !offlinePreview,
placeholder: offlinePreview ? "装甲板未接入" : "",
hp: offlinePreview ? null : hp,
hps: [hp, hp, hp, hp],
board,
boardText: hex(board),
critical: hp === 0 || hp <= state.hud.health.lowThreshold,
outcome: outcomeFor(team),
};
};
return {
role: state.role,
team: state.team,
mirrored: state.mirror,
matchClock: previewMatch(),
demo: true,
diagnostics: true,
unlocked: state.unlocked || state.role === "referee",
discoveryOpen: true,
uptimeMs: performance.now(),
clients: 1,
config: configView(),
cameras,
armorBoards: boards,
stats,
slots: {
cameraA: state.role === "referee" ? CAMERA_A : state.cameraId,
cameraB: state.role === "referee" ? CAMERA_B : null,
armorA: state.role === "referee" ? ARMOR_A : state.armorId,
armorB: state.role === "referee" ? ARMOR_B : null,
manual: false,
},
// 两边都给:用户端也要显示对手的血量(画面右上角那一条)。
health: [healthFor(0), healthFor(1)],
recordings: recordings(),
notes: ["浏览器预览:状态与画面均为合成数据,不代表真实链路。"],
};
}
// ---------------------------------------------------------------------------
// 假的画面与心跳
// ---------------------------------------------------------------------------
/** 启动预览的数据源:每 200ms 一份快照,每 50ms 一帧画面。 */
export function startPreview(client: StreamClient, emit: (msg: WireMsg) => void) {
let frameId = 0;
const started = performance.now();
// 快照。
const snapshotTimer = window.setInterval(() => {
emit({ t: "snapshot", ...snapshot() } as WireMsg);
}, 200);
// 两路画面,各 20fps。
const canvases = new Map<number, HTMLCanvasElement>();
const render = async (camera: number, team: number) => {
const canvas = canvases.get(camera) ?? makeCanvas();
canvases.set(camera, canvas);
draw(canvas, team, frameId);
const bitmap = await createImageBitmap(canvas);
client.injectFrame(camera, frameId, canvas.width, canvas.height, bitmap);
};
const frameTimer = window.setInterval(() => {
if (videoOffline()) return;
frameId += 1;
const cameras =
state.role === "referee"
? [
[CAMERA_A, 0],
[CAMERA_B, 1],
]
: state.cameraId === CAMERA_A || state.cameraId === CAMERA_B
? [[state.cameraId, state.cameraId === CAMERA_A ? 0 : 1]]
: [];
for (const [camera, team] of cameras as [number, number][]) {
void render(camera, team);
}
for (const recording of state.recordings) recording.frames += 1;
}, 50);
// 掉血:每 3 秒一次,轮流打两块板子,顺便把命中反馈也验证了。
//
// 打空的那一拍只做重置、不出命中(胜负横幅要真的能看到),其余每一拍都出一次
// 命中。早先的写法是 `to = from === 0 ? 100 : ...` 然后按 `to >= from` 判断——那样一旦
// 两块都打空,之后每次都是重置,命中就再也不会出现,盯着界面等闪红会等到超时。
let tick = 0;
const hitTimer = window.setInterval(() => {
if (offlinePreview) return;
tick += 1;
const team = tick % 2;
if (state.hp[team] === 0) {
state.hp[team] = 100;
return;
}
const from = state.hp[team];
const damage = 3 + ((tick * 7) % 20);
const to = Math.max(0, from - damage);
state.hp[team] = to;
emit({
t: "hit",
board: team === 0 ? ARMOR_A : ARMOR_B,
team,
index: 0,
from,
to,
damage: from - to,
atMs: Date.now(),
} as WireMsg);
}, 3000);
// 第一帧不必等 200ms。
emit({ t: "snapshot", ...snapshot() } as WireMsg);
return () => {
window.clearInterval(snapshotTimer);
window.clearInterval(frameTimer);
window.clearInterval(hitTimer);
void started;
};
}
function makeCanvas(): HTMLCanvasElement {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
return canvas;
}
/** 与 `src-tauri/src/demo.rs` 画的是同一类东西:底色区分两路、中心靶心、二进制帧号。 */
function draw(canvas: HTMLCanvasElement, team: number, frameId: number) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const { width, height } = canvas;
const tint = team === 0 ? [0, 46, 40] : [58, 30, 0];
const gradient = ctx.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(0, `rgb(${18 + tint[0] / 3}, ${18 + tint[1] / 3}, ${22 + tint[2] / 3})`);
gradient.addColorStop(1, `rgb(${78 + tint[0] / 3}, ${78 + tint[1] / 3}, ${82 + tint[2] / 3})`);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = "rgba(255,255,255,0.07)";
ctx.lineWidth = 1;
for (let x = 0; x < width; x += 40) {
ctx.beginPath();
ctx.moveTo(x + 0.5, 0);
ctx.lineTo(x + 0.5, height);
ctx.stroke();
}
for (let y = 0; y < height; y += 40) {
ctx.beginPath();
ctx.moveTo(0, y + 0.5);
ctx.lineTo(width, y + 0.5);
ctx.stroke();
}
const cx = width / 2;
const cy = height / 2;
ctx.strokeStyle = "#c8c8d2";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(cx, cy, 60, 0, Math.PI * 2);
ctx.stroke();
ctx.strokeStyle = "#96969f";
ctx.beginPath();
ctx.arc(cx, cy, 28, 0, Math.PI * 2);
ctx.stroke();
ctx.strokeStyle = "#78788a";
for (const [dx, dy] of [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
]) {
ctx.beginPath();
ctx.moveTo(cx + dx * 40, cy + dy * 40);
ctx.lineTo(cx + dx * 90, cy + dy * 90);
ctx.stroke();
}
for (let bit = 0; bit < 16; bit += 1) {
const on = ((frameId >> bit) & 1) === 1;
ctx.fillStyle = on ? "#78ffa0" : "#34343c";
ctx.fillRect(12 + bit * 14, 12, 10, 10);
}
const t = frameId / 20;
const phase = team === 0 ? 0 : 1.7;
ctx.fillStyle = "#ffd25a";
ctx.beginPath();
ctx.arc(cx + 250 * Math.sin(t * 0.9 + phase), cy + 150 * Math.cos(t * 1.3 + phase), 26, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#5ac8ff";
ctx.fillRect(((t * 60) % (width - 80)) | 0, height - 24, 60, 8);
ctx.font = "600 20px ui-monospace, monospace";
ctx.fillStyle = "#e8e8ec";
ctx.fillText(team === 0 ? "PREVIEW · TEAM 1" : "PREVIEW · TEAM 2", 14, height - 40);
ctx.font = "500 16px ui-monospace, monospace";
ctx.fillStyle = "#8a8a95";
ctx.fillText(`frame ${frameId}`, 14, height - 16);
}
+92
View File
@@ -0,0 +1,92 @@
/** 纯格式化函数。界面里所有"给人看的数字"都从这里过一遍。 */
/** `0x3D4D8A9A`。与 Rust 侧的 `snapshot::id_text` 输出一致。 */
export function idText(id: number | null | undefined): string {
if (id === null || id === undefined) return "—";
return `0x${id.toString(16).toUpperCase().padStart(8, "0")}`;
}
/** 22000 → `21.5 kB`。 */
export function bytes(value: number): string {
if (value <= 0) return "—";
if (value < 1024) return `${value} B`;
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} kB`;
return `${(value / 1024 / 1024).toFixed(2)} MB`;
}
/** 毫秒 → 人话。 */
export function elapsed(ms: number | null | undefined): string {
if (ms === null || ms === undefined) return "—";
if (ms < 1000) return `${Math.round(ms)} ms`;
if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
const totalSeconds = Math.round(ms / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes < 60) return `${minutes} 分 ${seconds} 秒`;
const hours = Math.floor(minutes / 60);
return `${hours} 小时 ${minutes % 60} 分`;
}
/** 录制时长:从开始到现在的墙钟。 */
export function since(ms: number | null | undefined, now = Date.now()): string {
if (!ms) return "—";
return elapsed(now - ms);
}
/** Unix 毫秒 → `14:03:22`。 */
export function clockTime(ms: number | null | undefined): string {
if (!ms) return "—";
const date = new Date(ms);
const pad = (value: number) => value.toString().padStart(2, "0");
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
/** 队伍名的兜底值。与 Rust 侧的 `config::DEFAULT_TEAM_NAMES` 一致。 */
export const DEFAULT_TEAM_NAMES = ["队伍一", "队伍二"];
/**
* 队伍名。
*
* 名字是**配置里可以改的**(裁判端能直接编辑),所以显示的地方一律从这里取:散在各处的
* `team === 0 ? "队伍一" : "队伍二"` 会在改名之后留下一半旧名字,而且不会报错。
*
* `names` 传配置里的两条;缺省或留空时回落到默认名。
*/
export function teamName(team: number, names?: readonly string[] | null): string {
if (team === 255) return "待分配队伍";
const custom = names?.[team]?.trim();
if (custom) return custom;
return DEFAULT_TEAM_NAMES[team] ?? "队伍";
}
/**
* 队伍配色:与装甲板灯色一致(队伍一红、队伍二蓝)。
*
* 返回的是 CSS 变量而不是十六进制:这两个颜色是设计令牌(`tokens.css`),改一处就该
* 全站跟着变。返回值直接塞进 `style` 也行,`var()` 在那里是合法的。
*/
export function teamColor(team: number): string {
if (team === 255) return "var(--text-muted)";
return team === 0 ? "var(--team-0)" : "var(--team-1)";
}
/**
* 固件版本的一行标签:`v0.2.0 · 34`。
*
* 板子太老、没带版本字段时返回"版本未知"——不要拼出一个 `v0.0.0`,那是假信息。
*/
export function firmwareLabel(camera: {
firmwareVersion: string | null;
firmwareBuild: number;
}): string {
if (!camera.firmwareVersion) {
return camera.firmwareBuild > 0 ? `构建 ${camera.firmwareBuild}` : "版本未知";
}
return camera.firmwareBuild > 0
? `v${camera.firmwareVersion} · ${camera.firmwareBuild}`
: `v${camera.firmwareVersion}`;
}
+104
View File
@@ -0,0 +1,104 @@
/**
* 后端命令的封装。
*
* 每个函数对应 `client/src-tauri/src/commands.rs` 里的一个 `#[tauri::command]`。
* Tauri 会把 JS 侧的 camelCase 参数名转成 Rust 侧的 snake_case,所以这里的参数名写成
* 前端习惯的样子即可。
*
* # 错误
*
* 后端的 `Err(String)` 会以 rejected promise 的形式回来,字符串就是给现场的人看的那句
* 话。`call()` 把 `unknown` 归一成 `Error`,调用方只管 `catch (err) { err.message }`。
*/
import { invoke } from "@tauri-apps/api/core";
import type {
ConfigView,
HudView,
MediaFileDto,
RecordingDto,
Role,
Snapshot,
MatchAction,
StreamInfo,
} from "./types";
/**
* 把后端的字符串错误变成真正的 `Error`。
*
* 在没有 Tauri 的 `vite dev` 会话里(`?preview=` 那种),这条走预览实现——它用
* `await import()` 引入,所以正式构建里那段代码根本不会被打进产物(见 `dev-preview.ts`)。
*/
async function call<T>(command: string, args?: Record<string, unknown>): Promise<T> {
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) {
const preview = await import("./dev-preview");
return preview.previewInvoke<T>(command, args);
}
try {
return await invoke<T>(command, args);
} catch (raw) {
throw new Error(typeof raw === "string" ? raw : String(raw));
}
}
export const api = {
matchAction: (action: MatchAction) => call<void>("match_action", { action }),
releaseMatchSource: () => call<void>("release_match_source"),
// ---- 只读 ----
streamInfo: () => call<StreamInfo>("stream_info"),
snapshot: () => call<Snapshot>("get_snapshot"),
config: () => call<ConfigView>("get_config"),
mediaFiles: () => call<MediaFileDto[]>("list_media_files"),
configPath: () => call<string>("config_path"),
// ---- 密码 ----
unlock: (password: string) => call<boolean>("unlock", { password }),
lock: () => call<void>("lock"),
setPassword: (fresh: string, current?: string) =>
call<ConfigView>("set_password", { current: current ?? null, fresh }),
setDiscoveryOpen: (open: boolean) => call<void>("set_discovery_open", { open }),
// ---- 绑定与身份 ----
bindCamera: (cameraId: number | null, password?: string) =>
call<ConfigView>("bind_camera", { cameraId, password: password ?? null }),
bindArmor: (armorId: number | null, password?: string) =>
call<ConfigView>("bind_armor", { armorId, password: password ?? null }),
setTeam: (team: number, password?: string) =>
call<ConfigView>("set_team", { team, password: password ?? null }),
setRole: (role: Role, password?: string) =>
call<ConfigView>("set_role", { role, password: password ?? null }),
setMirror: (mirror: boolean) => call<ConfigView>("set_mirror", { mirror }),
saveHud: (hud: HudView) => call<ConfigView>("save_hud", { hud }),
/** 改一边的队名(0 = 队伍一,1 = 队伍二)。一次只改一边,避免覆盖另一边的改动。 */
setTeamName: (team: number, name: string, password?: string) =>
call<ConfigView>("set_team_name", { team, name, password: password ?? null }),
setRefereeSlots: (slots: {
cameraA: number | null;
cameraB: number | null;
armorA: number | null;
armorB: number | null;
manual: boolean;
}) => call<ConfigView>("set_referee_slots", slots),
setRecordingOptions: (options: {
dir: string | null;
ffmpeg: string | null;
crf: number | null;
preset: string | null;
}) => call<ConfigView>("set_recording_options", options),
// ---- 截图与录制 ----
screenshot: (camera: number) => call<string>("screenshot", { camera }),
startRecording: (cameras: number[]) => call<RecordingDto[]>("start_recording", { cameras }),
stopRecording: (cameras: number[]) => call<RecordingDto[]>("stop_recording", { cameras }),
reveal: (path: string) => call<void>("reveal", { path }),
openFile: (path: string) => call<void>("open_file", { path }),
// ---- 退出与重置 ----
clearConfig: (password?: string) =>
call<string>("clear_config", { password: password ?? null }),
quit: (password?: string) => call<void>("quit_app", { password: password ?? null }),
refresh: () => call<void>("refresh"),
};
+101
View File
@@ -0,0 +1,101 @@
/** A screen marker observed through the real camera. No device clock sync. */
export type Point = { x: number; y: number };
export const CORNERS = [[255,32,32],[32,255,32],[32,96,255],[255,32,255]] as const;
export const MARKER_BITS = 16;
export function markerBits(counter: number): number[] {
const gray=(counter&4095)^((counter&4095)>>>1);
return [1,0,1,0,...Array.from({length:12},(_,i)=>(gray>>>(11-i))&1)];
}
export function drawMarker(ctx: CanvasRenderingContext2D, counter:number) {
const w=ctx.canvas.width,h=ctx.canvas.height;
ctx.fillStyle='#30363e';ctx.fillRect(0,0,w,h);
// Static coloured detail keeps the target from being an unrealistically tiny JPEG.
for(let y=0;y<8;y++) for(let x=0;x<12;x++) {
ctx.fillStyle=`hsl(${(x*31+y*47)%360} 10% ${20+(x+y)%3*7}%)`;
ctx.fillRect(x*w/12,y*h/8,w/12,h/8);
}
[[.06,.08],[.94,.08],[.94,.92],[.06,.92]].forEach(([x,y],i)=>{
ctx.fillStyle=`rgb(${CORNERS[i].join(',')})`;
ctx.fillRect(x*w-.035*w,y*h-.045*h,.07*w,.09*h);
});
const bits=markerBits(counter);
ctx.fillStyle='#222';ctx.fillRect(.12*w,.34*h,.76*w,.32*h);
bits.forEach((bit,i)=>{
const x=(.14+.72*i/MARKER_BITS)*w,cw=.72*w/MARKER_BITS;
ctx.fillStyle=bit?'#fff':'#000';ctx.fillRect(x,.38*h,cw,.10*h);
ctx.fillStyle=bit?'#000':'#fff';ctx.fillRect(x,.52*h,cw,.10*h);
});
}
function colour(r:number,g:number,b:number):number {
// Screen primaries can clip and bloom through exposure/white balance.
// Absolute channel separation admits pastel green/cyan while excluding
// the low-saturation background (which can otherwise look more blue).
if(r>150 && b>150 && r-g>40 && b-g>40 && Math.abs(r-b)<100) return 4;
if(r>150 && r-g>40 && r-b>40) return 1;
if(g>150 && g-r>35 && g-b>30) return 2;
if(b>150 && b>r*1.7 && b-g>20) return 3;
return 0;
}
function project(corners:Point[],u:number,v:number):Point|null {
const [p0,p1,p2,p3]=corners;
const dx1=p1.x-p2.x, dx2=p3.x-p2.x, dx3=p0.x-p1.x+p2.x-p3.x;
const dy1=p1.y-p2.y, dy2=p3.y-p2.y, dy3=p0.y-p1.y+p2.y-p3.y;
const det=dx1*dy2-dx2*dy1;
if(Math.abs(det)<1e-6) return null;
const g=(dx3*dy2-dx2*dy3)/det, h=(dx1*dy3-dx3*dy1)/det;
const den=g*u+h*v+1;
if(Math.abs(den)<.01) return null;
return {x:((p1.x-p0.x+g*p1.x)*u+(p3.x-p0.x+h*p3.x)*v+p0.x)/den,
y:((p1.y-p0.y+g*p1.y)*u+(p3.y-p0.y+h*p3.y)*v+p0.y)/den};
}
export function decodeMarker(pixels:Uint8ClampedArray,w:number,h:number):{counter:number;corners:Point[]}|null {
const labels=new Uint8Array(w*h);
for(let i=0;i<labels.length;i++) labels[i]=colour(pixels[i*4],pixels[i*4+1],pixels[i*4+2]);
const best=Array.from({length:4},()=>({count:0,x:0,y:0}));
const queue=new Int32Array(w*h);
for(let start=0;start<labels.length;start++) {
const cls=labels[start]; if(!cls) continue;
let head=0,tail=1,count=0,sx=0,sy=0;
queue[0]=start;labels[start]=0;
while(head<tail) {
const i=queue[head++],x=i%w,y=Math.floor(i/w);
count++;sx+=x;sy+=y;
for(const n of [x>0?i-1:-1,x<w-1?i+1:-1,y>0?i-w:-1,y<h-1?i+w:-1]) {
if(n>=0 && labels[n]===cls) { labels[n]=0;queue[tail++]=n; }
}
}
if(count>=6 && count<w*h/6 && count>best[cls-1].count) best[cls-1]={count,x:sx/count,y:sy/count};
}
if(best.some(b=>!b.count)) return null;
const corners=best.map(({x,y})=>({x,y}));
const area=Math.abs(corners.reduce((a,p,i)=>a+p.x*corners[(i+1)%4].y-p.y*corners[(i+1)%4].x,0))/2;
if(area<1500) return null;
const luma=(x:number,y:number)=>{
let total=0,count=0;
for(let dy=-1;dy<=1;dy++) for(let dx=-1;dx<=1;dx++) {
const xx=Math.round(x)+dx,yy=Math.round(y)+dy;
if(xx<0||xx>=w||yy<0||yy>=h) continue;
const i=(yy*w+xx)*4;total+=(pixels[i]+pixels[i+1]+pixels[i+2])/3;count++;
}
return count?total/count:NaN;
};
const bits:number[]=[];
for(let i=0;i<MARKER_BITS;i++) {
const x=.14+.72*(i+.5)/MARKER_BITS;
const top=project(corners,(x-.06)/.88,(.43-.08)/.84);
const bottom=project(corners,(x-.06)/.88,(.57-.08)/.84);
if(!top||!bottom) return null;
const delta=luma(top.x,top.y)-luma(bottom.x,bottom.y);
if(!Number.isFinite(delta)||Math.abs(delta)<60) return null;
bits.push(delta>0?1:0);
}
if(bits.slice(0,4).join('')!=='1010') return null;
let gray=bits.slice(4).reduce((n,b)=>(n<<1)|b,0),counter=gray;
while(gray>>>=1) counter^=gray;
return {counter,corners};
}
+22
View File
@@ -0,0 +1,22 @@
/** 仅开发浏览器预览,展示合成设备/进度;不模拟可调用的 USB 后端。 */
import type { BundleInfo, DeviceSnapshot, FlashPlan, FlashReport } from "./maintenance";
export function maintenancePreview(stage: string) {
const partitions = [
{ name: "nvs", kind: 1, subtype: 2, offset: 0x9000, size: 0x6000, flags: 0 },
{ name: "phy_init", kind: 1, subtype: 1, offset: 0xf000, size: 0x1000, flags: 0 },
{ name: "factory", kind: 0, subtype: 0, offset: 0x10000, size: 0x200000, flags: 0 },
];
const hash = "0".repeat(64);
const device: DeviceSnapshot = { port: "PREVIEW-USB", chip: "esp32c3", revision: "v0.4", flashSize: 0x400000, flashSizeText: "4 MB", mac: "02:00:00:00:00:01", features: [], secureBoot: false, secureDownload: false, flashEncryption: false, securityFlags: 0, flashCryptCnt: 0, partitionTable: partitions, app: null, freeRanges: [], tableSha256: hash };
const bundle: BundleInfo = { firmwareKind: "armor", armorTeam: stage === "mismatch" ? 0 : null, armorThreshold: 2000, path: "PREVIEW ONLY", sourceKind: "zip", sourcePath: "PREVIEW ONLY", sourceSha256: hash, entryCount: 4, name: "合成装甲板固件", version: "预览", chip: "esp32c3", appFile: "armor-app.bin", appSha256: hash, appSize: 1084736, partitionTableFile: "partition-table.bin", partitionTableSha256: hash, bootloaderFile: "bootloader.bin", bootloaderSha256: hash, appPartitionSize: 0x200000, flashSize: "4mb", flashSizeBytes: 0x400000, flashMode: "dio", flashFrequency: "40mhz", notes: "合成数据,不可烧录" };
const plan: FlashPlan = { mode: "armor-install", confirmation: "PREVIEW ONLY", port: device.port, device, bundle, candidates: [{ offset: 0x10000, size: 0x200000 }], targetOffset: 0x10000, targetSize: 0x200000, appSize: bundle.appSize, appPartitionSize: 0x200000, currentFactoryOffset: 0x10000, currentFactorySize: 0x200000, currentTable: partitions, patchedTable: partitions, tableShaBefore: hash, tableShaAfter: hash, oldAppPreserved: false, warnings: ["C3 固定地址安装:写入 Bootloader(0x0)、分区表(0x8000)和 App(0x10000),旧 App 会被覆盖。", "先完整备份 4 MB Flash,备份失败则停止;失败后需用同一设备的完整备份恢复,仅恢复分区表无效。", "保留 NVS / PHY;通用固件在客户端绑定后按所选队伍改变灯色。"], canFlash: true };
if (stage === "migrate") {
device.partitionTable = partitions.map(entry => entry.name === "factory" ? { ...entry, size: 0x100000 } : entry);
plan.currentTable = device.partitionTable;
plan.currentFactorySize = 0x100000;
plan.warnings[2] = "现有布局需迁移:完整备份成功后初始化新布局的 NVS / PHY(0x9000–0x10000),原配置会清除;旧数据可通过完整备份恢复。";
}
const report: FlashReport = { mode: "armor-install", bootloaderVerified: true, ok: stage !== "failure", port: device.port, chip: device.chip, mac: device.mac, bundleName: bundle.name, bundleVersion: bundle.version, targetOffset: 0x10000, targetSize: 0x200000, appSize: bundle.appSize, appSha256: hash, tableShaBefore: hash, tableShaAfter: hash, attempts: [], appVerified: stage !== "failure", tableVerified: stage !== "failure", tableRestored: false, needsRollback: stage === "failure", bootOk: null, bootLog: "合成日志 / 未连接设备", backupDir: "PREVIEW ONLY", note: "合成结果,不能代表硬件验证。", error: stage === "failure" ? "合成故障:App 回读不一致。" : null, startedAt: "PREVIEW ONLY", finishedAt: "PREVIEW ONLY" };
return { device, bundle, plan, report };
}
+16
View File
@@ -0,0 +1,16 @@
import type { BundleInfo, DeviceSnapshot } from "./maintenance";
export function maintenanceMismatch(
kind: "" | "camera" | "armor",
team: string,
device: Pick<DeviceSnapshot, "chip"> | null,
bundle: Pick<BundleInfo, "firmwareKind" | "armorTeam"> | null,
): string | null {
if (!kind) return "请先选择维护对象。";
const chip = kind === "armor" ? "esp32c3" : "esp32s3";
if (device && device.chip !== chip) return `所选对象需要 ${chip},读取到 ${device.chip}。请核对设备和串口。`;
if (bundle && bundle.firmwareKind !== kind) return "固件包与所选设备类型不符,请重新选择。";
if (kind === "armor" && bundle?.armorTeam != null && team !== "0" && team !== "1") return "请先选择目标装甲板的队伍,再核对固件包是否对应。";
if (kind === "armor" && bundle?.armorTeam != null && bundle.armorTeam !== Number(team)) return "固件包队伍与目标队伍不同,请重新编译或选择对应队伍的包。";
return null;
}
+240
View File
@@ -0,0 +1,240 @@
/**
* 固件维护页的 IPC 与 DTO。
*
* 字段名与 `client/src-tauri/src/maintenance.rs` 的 `#[serde(rename_all = "camelCase")]`
* 一一对应;改一边必须改另一边。
*/
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
export interface PortInfo {
portName: string;
label: string;
vid: number | null;
pid: number | null;
likelyEsp: boolean;
}
export interface PartitionEntry {
name: string;
kind: number;
subtype: number;
offset: number;
size: number;
flags: number;
}
export interface FreeRange {
start: number;
size: number;
}
export interface AppInfo {
offset: number;
version: string;
projectName: string;
buildTime: string;
idfVersion: string;
}
export interface DeviceSnapshot {
port: string;
chip: string;
revision: string | null;
flashSize: number;
flashSizeText: string;
mac: string | null;
features: string[];
secureBoot: boolean;
secureDownload: boolean;
flashEncryption: boolean;
securityFlags: number;
flashCryptCnt: number;
partitionTable: PartitionEntry[];
app: AppInfo | null;
freeRanges: FreeRange[];
tableSha256: string;
}
export interface BundleInfo {
firmwareKind: "camera" | "armor";
armorTeam: number | null;
armorThreshold: number | null;
path: string;
sourceKind: string;
sourcePath: string;
sourceSha256: string | null;
entryCount: number | null;
name: string;
version: string;
chip: string;
appFile: string;
appSha256: string;
appSize: number;
partitionTableFile: string;
partitionTableSha256: string;
bootloaderFile: string | null;
bootloaderSha256: string | null;
appPartitionSize: number;
flashSize: string;
flashSizeBytes: number;
flashMode: string;
flashFrequency: string;
notes: string | null;
}
export interface SlotCandidate {
offset: number;
size: number;
}
export interface FlashPlan {
mode: "camera-relocate" | "armor-install";
confirmation: string;
port: string;
device: DeviceSnapshot;
bundle: BundleInfo;
candidates: SlotCandidate[];
targetOffset: number;
targetSize: number;
appSize: number;
appPartitionSize: number;
currentFactoryOffset: number;
currentFactorySize: number;
currentTable: PartitionEntry[];
patchedTable: PartitionEntry[];
tableShaBefore: string;
tableShaAfter: string;
oldAppPreserved: boolean;
warnings: string[];
canFlash: boolean;
}
export interface Mismatch {
offset: number;
expected: number;
actual: number;
}
export interface SlotAttempt {
offset: number;
size: number;
writeOk: boolean;
verifyOk: boolean;
mismatches: Mismatch[];
badSectors: number[];
error: string | null;
}
export interface FlashProgress {
phase: string;
message: string;
current: number;
total: number;
}
export interface FlashReport {
mode: "camera-relocate" | "armor-install";
bootloaderVerified: boolean;
ok: boolean;
port: string;
chip: string;
mac: string | null;
bundleName: string;
bundleVersion: string;
targetOffset: number;
targetSize: number;
appSize: number;
appSha256: string;
tableShaBefore: string;
tableShaAfter: string;
attempts: SlotAttempt[];
appVerified: boolean;
tableVerified: boolean;
tableRestored: boolean;
needsRollback: boolean;
bootOk: boolean | null;
bootLog: string;
backupDir: string;
note: string | null;
error: string | null;
startedAt: string;
finishedAt: string;
}
async function call<T>(command: string, args?: Record<string, unknown>): Promise<T> {
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) {
if (command === "maintenance_list_ports") return [] as T;
throw new Error("浏览器预览仅展示界面;编译和 USB 烧录请在原生客户端操作。");
}
try {
return await invoke<T>(command, args);
} catch (raw) {
throw new Error(typeof raw === "string" ? raw : String(raw));
}
}
export const maintenanceApi = {
buildArmor: (request: ArmorBuildRequest) => call<BundleInfo>("maintenance_build_armor", { request }),
listPorts: () => call<PortInfo[]>("maintenance_list_ports"),
loadBundle: (path: string) => call<BundleInfo>("maintenance_load_bundle", { path }),
probe: (port: string) => call<DeviceSnapshot>("maintenance_probe", { port }),
plan: (port: string, bundlePath: string) =>
call<FlashPlan>("maintenance_plan", { port, bundlePath }),
flash: (port: string, bundlePath: string, confirmation: string, backupApp = true) =>
call<FlashReport>("maintenance_flash", { port, bundlePath, backupApp, confirmation }),
restoreTable: (port: string, backupDir: string, firmwareKind: "camera" | "armor") =>
call<string>("maintenance_restore_table", { port, backupDir, firmwareKind }),
cancel: () => call<void>("maintenance_cancel"),
};
export interface ArmorBuildRequest {
repoPath: string;
targetDir: string;
idfPath: string;
threshold: number;
ssid: string;
password: string;
proxyUrl: string;
}
export async function selectMaintenanceDirectory(title: string): Promise<string | null> {
const selected = await open({ directory: true, multiple: false, title });
return typeof selected === "string" ? selected : null;
}
/** 原生 .zip 选择。返回 null 表示用户取消。 */
export async function selectBundleZip(): Promise<string | null> {
const selected = await open({
directory: false,
multiple: false,
title: "选择对应设备的固件包(.zip)",
filters: [{ name: "固件包", extensions: ["zip"] }],
});
return typeof selected === "string" ? selected : null;
}
/** 兼容旧包:选择目录。返回 null 表示用户取消。 */
export async function selectBundleDirectory(): Promise<string | null> {
const selected = await open({
directory: true,
multiple: false,
title: "选择固件包目录(含 bundle.json)",
});
return typeof selected === "string" ? selected : null;
}
export function formatBytes(value: number): string {
if (value >= 1024 * 1024) return `${(value / (1024 * 1024)).toFixed(2)} MiB`;
if (value >= 1024) return `${(value / 1024).toFixed(1)} KiB`;
return `${value} B`;
}
export function formatOffset(value: number): string {
return `0x${value.toString(16).toUpperCase().padStart(6, "0")}`;
}
export function shortSha(value: string): string {
return value.length > 16 ? `${value.slice(0, 12)}…${value.slice(-4)}` : value;
}
+44
View File
@@ -0,0 +1,44 @@
/** 仅被 dev-preview 引用的合成计时,不能作为网络同步测试。 */
import { projectMatch } from "./match-time";
import type { MatchAction, MatchClockView, MatchPhase } from "./types";
const scenario = new URLSearchParams(location.search).get("match");
const blank = (): MatchClockView => ({ phase: "idle", resumePhase: "idle", pauseKind: null, applicant: null,
reason: "", remainingMs: 0, elapsedMs: 0, pauseRemainingMs: null, pauseElapsedMs: 0,
connected: true, freshForMs: 1500, source: "预览 / 合成数据", syncError: null });
let view = blank();
let at = performance.now();
if (scenario === "offline") Object.assign(view, { phase: "running", remainingMs: 93_000, elapsedMs: 87_000, connected: false });
if (["preparation", "ready", "countdown", "running", "finished"].includes(scenario ?? "")) {
view.phase = scenario as MatchPhase;
view.remainingMs = scenario === "countdown" ? 5000 : scenario === "ready" || scenario === "finished" ? 0 : 180_000;
}
if (scenario?.startsWith("paused")) {
Object.assign(view, { phase: "paused", resumePhase: "running", remainingMs: 93_000, elapsedMs: 87_000,
pauseKind: scenario === "paused-official" ? "official" : "player", applicant: scenario === "paused-official" ? null : 0,
reason: "合成演示:检查图传接线", pauseRemainingMs: scenario === "paused-official" ? null : scenario === "paused-expired" ? 0 : 300_000 });
}
export function previewMatch(): MatchClockView {
const now = performance.now();
// 预览的合成来源持续在线;通过查询参数单独复现掉线。
view = projectMatch({ ...view, freshForMs: Number.MAX_SAFE_INTEGER }, now - at, true); at = now;
if (view.phase === "preparation" && view.remainingMs === 0) view.phase = "ready";
if (view.phase === "countdown" && view.remainingMs === 0) { view.phase = "running"; view.remainingMs = 180_000; }
if (view.phase === "running" && view.remainingMs === 0) view.phase = "finished";
return { ...view, connected: scenario !== "offline", freshForMs: scenario === "offline" ? 0 : 1500 };
}
export function previewMatchAction(action: MatchAction) {
previewMatch();
switch (action.type) {
case "prepare": view = { ...blank(), phase: "preparation", remainingMs: 180_000 }; break;
case "countdown": view.phase = "countdown"; view.remainingMs = action.seconds * 1000; break;
case "pausePlayer":
if (!action.approved) throw new Error("选手技术暂停须经主裁判批准");
view = { ...view, resumePhase: view.phase, phase: "paused", pauseKind: "player", applicant: action.team, reason: action.reason, pauseElapsedMs: 0, pauseRemainingMs: 300_000 }; break;
case "pauseOfficial": view = { ...view, resumePhase: view.phase, phase: "paused", pauseKind: "official", applicant: null, reason: action.reason, pauseElapsedMs: 0, pauseRemainingMs: null }; break;
case "resume": view = { ...view, phase: view.resumePhase, resumePhase: "idle", pauseKind: null, applicant: null, reason: "", pauseRemainingMs: null, pauseElapsedMs: 0 }; break;
case "end": view.phase = "finished"; view.pauseKind = null; break;
case "reset": view = blank(); break;
}
at = performance.now();
}
+23
View File
@@ -0,0 +1,23 @@
import type { MatchClockView, MatchPhase } from "./types";
export const MATCH_PHASE: Record<MatchPhase, string> = {
idle: "等待准备", preparation: "赛前准备", ready: "准备结束 · 等待裁判", countdown: "开赛倒计时",
running: "对局进行中", paused: "技术暂停", finished: "本局计时结束",
};
export function matchTime(ms: number, countingUp = false): string {
const seconds = Math.max(0, countingUp ? Math.floor(ms / 1000) : Math.ceil(ms / 1000));
return `${Math.floor(seconds / 60).toString().padStart(2, "0")}:${(seconds % 60).toString().padStart(2, "0")}`;
}
/** 只插值当前快照,不在界面自行切换比赛阶段。后端或网络失联时停止。 */
export function projectMatch(view: MatchClockView, age: number, transportLive: boolean) {
const delta = transportLive && view.connected ? Math.min(Math.max(0, age), view.freshForMs) : 0;
const moving = ["preparation", "countdown", "running"].includes(view.phase);
const spent = moving ? Math.min(view.remainingMs, delta) : 0;
return { ...view,
connected: transportLive && view.connected && age < view.freshForMs,
remainingMs: view.remainingMs - spent,
elapsedMs: view.elapsedMs + (view.phase === "running" ? spent : 0),
pauseElapsedMs: view.pauseElapsedMs + (view.phase === "paused" ? delta : 0),
pauseRemainingMs: view.pauseRemainingMs === null ? null : Math.max(0, view.pauseRemainingMs - (view.phase === "paused" ? delta : 0)),
};
}
+187
View File
@@ -0,0 +1,187 @@
/**
* 画面上的叠加图形:瞄准器、网格,以及"图像落在哪"的那一道换算。
*
* # 为什么单独拆出来
*
* 这三段代码现在有两个使用者:`VideoSurface` 里的真画面,和设置面板里的小预览窗。预览窗
* 存在的意义就是"改完立刻看见",如果它另写一套绘制,两边迟早会不一样——而出现差异时,
* 用户看到的是预览里对、画面上偏,这比没有预览更糟。
*
* 所以这里只放**纯函数**:给 ctx 和数字,画完就退出。不碰 React、不碰请求、不认识 store。
*/
import type { CrosshairConfig, GridConfig } from "./types";
/** 图像在窗格里的落点与大小(CSS 像素)。 */
export interface Geometry {
left: number;
top: number;
drawWidth: number;
drawHeight: number;
}
export interface Box {
clientWidth: number;
clientHeight: number;
}
/**
* 把一帧按 `contain` 放进窗格,再乘缩放。
*
* 平移是**屏幕像素**而不是画面比例:拖动时手感必须是 1:1 的,否则放大之后拖动会变黏。
*/
export function computeLayout(
box: Box,
frameWidth: number,
frameHeight: number,
view: { zoom: number; x: number; y: number },
): Geometry {
const width = box.clientWidth;
const height = box.clientHeight;
if (frameWidth <= 0 || frameHeight <= 0) {
return { left: 0, top: 0, drawWidth: 0, drawHeight: 0 };
}
const fit = Math.min(width / frameWidth, height / frameHeight);
const drawWidth = frameWidth * fit * view.zoom;
const drawHeight = frameHeight * fit * view.zoom;
return {
left: (width - drawWidth) / 2 + view.x,
top: (height - drawHeight) / 2 + view.y,
drawWidth,
drawHeight,
};
}
/**
* 瞄准点的屏幕位置。
*
* 图像坐标系里的 `(0.5 + offsetX, 0.5 + offsetY)` 再换到屏幕。镜像时横向要翻过来,
* 否则准星会站在画面的另一边——偏移量是相对**摄像头光轴**定的,光轴在镜像之后换了位置。
*/
export function aimPoint(
geometry: Geometry,
crosshair: CrosshairConfig | null,
mirrored: boolean,
canvasWidth: number,
canvasHeight: number,
): { x: number; y: number } {
if (!crosshair || geometry.drawWidth <= 0) {
return { x: canvasWidth / 2, y: canvasHeight / 2 };
}
const rawX = geometry.left + (0.5 + crosshair.offsetX) * geometry.drawWidth;
return {
x: mirrored ? canvasWidth - rawX : rawX,
y: geometry.top + (0.5 + crosshair.offsetY) * geometry.drawHeight,
};
}
/** 画网格。网格画在**图像矩形**里:它标的是画面里的比例,用来估距离。 */
export function paintGrid(
ctx: CanvasRenderingContext2D,
geometry: Geometry,
grid: GridConfig,
): void {
if (geometry.drawWidth <= 0 || geometry.drawHeight <= 0) return;
ctx.save();
ctx.strokeStyle = `rgba(255, 255, 255, ${grid.opacity})`;
ctx.lineWidth = 1;
const x0 = geometry.left;
const y0 = geometry.top;
const x1 = x0 + geometry.drawWidth;
const y1 = y0 + geometry.drawHeight;
if (grid.style === "thirds") {
for (const fraction of [1 / 3, 2 / 3]) {
line(ctx, x0 + geometry.drawWidth * fraction, y0, x0 + geometry.drawWidth * fraction, y1);
line(ctx, x0, y0 + geometry.drawHeight * fraction, x1, y0 + geometry.drawHeight * fraction);
}
} else if (grid.style === "squares") {
const divisions = Math.max(2, grid.divisions);
for (let i = 1; i < divisions; i += 1) {
const fraction = i / divisions;
line(ctx, x0 + geometry.drawWidth * fraction, y0, x0 + geometry.drawWidth * fraction, y1);
line(ctx, x0, y0 + geometry.drawHeight * fraction, x1, y0 + geometry.drawHeight * fraction);
}
} else {
line(ctx, x0 + geometry.drawWidth / 2, y0, x0 + geometry.drawWidth / 2, y1);
line(ctx, x0, y0 + geometry.drawHeight / 2, x1, y0 + geometry.drawHeight / 2);
}
ctx.restore();
}
/**
* 画瞄准器。
*
* 两遍描边:先一圈半透明的深色(光环),再画本体。浅色背景下亮绿准星会消失,这一圈让
* 它在任何画面上都看得见——这是可读性要求,不是装饰。
*/
export function paintCrosshair(
ctx: CanvasRenderingContext2D,
cx: number,
cy: number,
shortSide: number,
config: CrosshairConfig,
): void {
const arm = Math.max(3, config.size * shortSide);
const gap = config.gap * shortSide;
const thickness = Math.max(1, config.thickness * shortSide);
const stroke = (color: string, width: number, radius: number) => {
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.beginPath();
if (config.style === "circle-dot") {
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
} else {
ctx.moveTo(cx - radius, cy);
ctx.lineTo(cx - gap, cy);
ctx.moveTo(cx + gap, cy);
ctx.lineTo(cx + radius, cy);
ctx.moveTo(cx, cy - radius);
ctx.lineTo(cx, cy - gap);
ctx.moveTo(cx, cy + gap);
ctx.lineTo(cx, cy + radius);
}
ctx.stroke();
};
stroke("rgba(0, 0, 0, 0.55)", thickness + 2, arm + 1);
stroke(config.color, thickness, arm);
if (config.style !== "cross") {
const dot = Math.max(1.2, thickness * 0.9);
ctx.fillStyle = "rgba(0, 0, 0, 0.55)";
ctx.beginPath();
ctx.arc(cx, cy, dot + 1, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = config.color;
ctx.beginPath();
ctx.arc(cx, cy, dot, 0, Math.PI * 2);
ctx.fill();
}
}
/** 半像素偏移,让 1px 的线落在像素中心而不是跨两个像素发虚。 */
function line(
ctx: CanvasRenderingContext2D,
x0: number,
y0: number,
x1: number,
y1: number,
): void {
ctx.beginPath();
ctx.moveTo(Math.round(x0) + 0.5, Math.round(y0) + 0.5);
ctx.lineTo(Math.round(x1) + 0.5, Math.round(y1) + 0.5);
ctx.stroke();
}
+143
View File
@@ -0,0 +1,143 @@
/**
* 后端状态的订阅式存储。
*
* 后端每 200 ms 推一份完整快照,前端只做渲染——没有轮询、没有"各处分别拉数据"带来的
* 两种时刻的状态混在一起。实现用一个模块级单例 + `useSyncExternalStore`。
*
* 快照对象**每次整体替换**:`useSyncExternalStore` 靠引用比较判断要不要重渲染,就地
* 修改字段不会触发更新。
*/
import { useSyncExternalStore } from "react";
import { StreamClient } from "./stream";
import type { HitEvent, Snapshot, WireMsg } from "./types";
/**
* 一次掉血在界面上的记录。
*
* `receivedAt` 用 `performance.now()` 而不是后端给的 `atMs`(Unix 毫秒):动画的时钟必须
* 与 `requestAnimationFrame` 的时间戳同源,把两个时钟相减会得到一个荒唐的年龄,动画也
* 就不会出现。
*/
export interface HitPulseRecord extends HitEvent {
seq: number;
receivedAt: number;
}
export interface AppStore {
/** 还没收到第一份快照时为 null。 */
snapshot: Snapshot | null;
/** 与后端的视频通道是否连着。 */
connected: boolean;
/** 最近一次掉血,界面用它做闪红与伤害数字。 */
lastHit: HitPulseRecord | null;
/** 后端要求弹出解锁框(用户端点关闭窗口时)。 */
confirmQuit: number;
/** 一条条要显示的说明。 */
notes: string[];
/** 通道本身的问题(连不上、丢帧)。 */
channelError: string | null;
}
const initial: AppStore = {
snapshot: null,
connected: false,
lastHit: null,
confirmQuit: 0,
notes: [],
channelError: null,
};
let store: AppStore = initial;
let hitSeq = 0;
const listeners = new Set<() => void>();
function emit(next: Partial<AppStore>) {
store = { ...store, ...next };
for (const listener of listeners) listener();
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
}
/** 组件里读状态。 */
export function useAppStore(): AppStore {
return useSyncExternalStore(subscribe, () => store);
}
/** 组件外读状态(事件处理、命令回调里用)。 */
export function currentStore(): AppStore {
return store;
}
function handleMessage(msg: WireMsg) {
switch (msg.t) {
case "frameTiming":
return; // Consumed by StreamClient before reaching application state.
case "snapshot": {
const { t: _tag, ...snapshot } = msg;
emit({ snapshot: snapshot as Snapshot });
return;
}
case "hit":
hitSeq += 1;
emit({ lastHit: { ...msg, seq: hitSeq, receivedAt: performance.now() } });
return;
case "note":
emit({ notes: [...store.notes, msg.message].slice(-6) });
return;
case "confirmQuit":
emit({ confirmQuit: store.confirmQuit + 1 });
return;
}
}
let client: StreamClient | null = null;
/**
* 建立与后端的通道。整个界面只调一次(在 `App` 里)。
*/
export function startStream(url: string): StreamClient {
client?.close();
client = new StreamClient({
onMessage: handleMessage,
onConnection: (connected) =>
emit({
connected,
channelError: connected ? null : "本机视频服务已断开,正在重新连接…",
}),
});
// 浏览器预览:没有 WebSocket,状态与画面由 dev-preview.ts 合成。
// 动态引入让这段代码在正式构建里被完全剔掉。
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) {
emit({ connected: true });
const current = client;
void import("./dev-preview").then((preview) => preview.startPreview(current, handleMessage));
return client;
}
client.connect(url);
return client;
}
export function streamClient(): StreamClient {
if (!client) throw new Error("视频通道尚未启动");
return client;
}
/** 手动塞一条说明(本地校验失败之类)。 */
export function pushNote(message: string) {
emit({ notes: [...store.notes, message].slice(-6) });
}
/** 关掉一条说明。 */
export function dismissNote(index: number) {
emit({ notes: store.notes.filter((_, i) => i !== index) });
}
+274
View File
@@ -0,0 +1,274 @@
/**
* 视频与状态通道的客户端。
*
* # 为什么是 WebSocket 而不是 invoke
*
* 两路 22fps、每帧约 22 kB,也就是每秒约 1 MB 的裸 JPEG。走 IPC 的话它要变成 base64
* 再涨 1/3,然后在 JS 里解回来——CPU 花在没人需要的编解码上。二进制 WebSocket 帧把
* 原始 JPEG 字节直接交给我们,交给 `createImageBitmap` 解码。
*
* # 解码是异步的,所以帧号要看着用
*
* `createImageBitmap` 返回 Promise,两个相邻帧的解码**可能**乱序完成。所以每路记住最后
* 画过的帧号,只有更新的那帧才会被采用。没有这一步,画面会偶发地往回跳一帧——看起来
* 像"卡了一下",极难归因。
*
* # `ImageBitmap` 必须显式 close
*
* 它持有解码后的像素(不吃 GC 的账)。每收到新帧就替换旧的那张并不够,必须把旧的那张
* `close()` 掉,否则两路 22fps 跑上几分钟就是几百 MB 的显存/内存。
*/
import { FRAME_HEADER_LEN, type WireMsg } from "./types";
/** 每路最新一张画面。 */
export interface FrameInfo {
camera: number;
frameId: number;
width: number;
height: number;
bitmap: ImageBitmap;
/** 本地完成解码的时刻(`performance.now()`),用于判断帧的新旧。 */
receivedAt: number;
}
interface Handlers {
onMessage: (msg: WireMsg) => void;
onConnection: (connected: boolean) => void;
}
/** 断线重连的退避上限。 */
const MAX_BACKOFF_MS = 3000;
const MAX_LOCAL_VIDEO_AGE_MS = 100;
interface PendingFrame {
bytes: ArrayBuffer;
arrivedAt: number;
publishedUnixMs?: number;
}
export class StreamClient {
private ws: WebSocket | null = null;
private url: string | null = null;
private readonly frames = new Map<number, FrameInfo>();
private readonly handlers: Handlers;
private retryTimer: number | null = null;
private backoff = 250;
private closed = false;
private generation = 0;
private readonly pending = new Map<number, PendingFrame>();
private readonly frameTimes = new Map<number, { frameId: number; publishedUnixMs: number }>();
private readonly decoding = new Map<number, number>();
/** 统计:收到多少帧、解码失败多少张。界面用它区分"链路没数据"和"数据坏了"。 */
readonly counters = { frames: 0, decodeFailures: 0, reconnects: 0, skippedDecodes: 0, staleFrames: 0 };
constructor(handlers: Handlers, private readonly now = () => performance.now(), private readonly wallNow = () => Date.now()) {
this.handlers = handlers;
}
connect(url: string) {
this.close();
this.url = url;
this.closed = false;
this.open();
}
private open() {
if (!this.url || this.closed) return;
let socket: WebSocket;
try {
socket = new WebSocket(this.url);
} catch {
this.scheduleReconnect();
return;
}
socket.binaryType = "arraybuffer";
this.ws = socket;
socket.onopen = () => {
if (this.ws !== socket) return;
this.backoff = 250;
this.handlers.onConnection(true);
};
socket.onclose = () => {
if (this.ws !== socket) return;
this.generation += 1;
this.pending.clear();
this.frameTimes.clear();
this.decoding.clear();
this.handlers.onConnection(false);
this.scheduleReconnect();
};
socket.onerror = () => {
// onerror 之后一定会有 onclose,重连交给那一条路径。
};
socket.onmessage = (event) => {
if (this.ws !== socket) return;
if (typeof event.data === "string") {
try {
const message = JSON.parse(event.data) as WireMsg;
if (message.t === "frameTiming") this.onTiming(message);
else this.handlers.onMessage(message);
} catch {
// 前端解析不了的消息只可能是版本不匹配,忽略比崩掉好。
}
return;
}
void this.onBinary(event.data as ArrayBuffer);
};
}
private onTiming(message: { camera: number; frameId: number; publishedUnixMs: number }) {
if (Number.isFinite(message.publishedUnixMs) && message.publishedUnixMs > 0) {
this.frameTimes.set(message.camera, message);
}
}
private expired(frame: PendingFrame): boolean {
return this.now() - frame.arrivedAt >= MAX_LOCAL_VIDEO_AGE_MS ||
(frame.publishedUnixMs !== undefined && this.wallNow() - frame.publishedUnixMs >= MAX_LOCAL_VIDEO_AGE_MS);
}
private async onBinary(buffer: ArrayBuffer) {
if (this.closed || buffer.byteLength < FRAME_HEADER_LEN) return;
const view = new DataView(buffer);
const camera = view.getUint32(0, true);
const length = view.getUint32(12, true);
if (buffer.byteLength !== FRAME_HEADER_LEN + length) return;
this.counters.frames += 1;
const timing = this.frameTimes.get(camera);
const received: PendingFrame = { bytes: buffer, arrivedAt: this.now(),
publishedUnixMs: timing?.frameId === view.getUint32(4, true) ? timing.publishedUnixMs : undefined };
if (this.expired(received)) { this.counters.staleFrames += 1; return; }
if (this.pending.has(camera)) this.counters.skippedDecodes += 1;
this.pending.set(camera, received);
if (this.decoding.has(camera)) return;
const generation = this.generation;
this.decoding.set(camera, generation);
try {
while (!this.closed && this.generation === generation) {
const next = this.pending.get(camera);
if (!next) break;
this.pending.delete(camera);
if (this.expired(next)) { this.counters.staleFrames += 1; continue; }
const header = new DataView(next.bytes);
const jpeg = new Uint8Array(next.bytes, FRAME_HEADER_LEN);
let bitmap: ImageBitmap;
try {
bitmap = await createImageBitmap(new Blob([jpeg], { type: "image/jpeg" }));
} catch {
this.counters.decodeFailures += 1;
continue;
}
if (this.closed || this.generation !== generation) {
bitmap.close();
break;
}
if (this.expired(next)) {
bitmap.close();
this.counters.staleFrames += 1;
continue;
}
this.store(camera, header.getUint32(4, true), header.getUint16(8, true), header.getUint16(10, true), bitmap);
}
} finally {
if (this.decoding.get(camera) === generation) this.decoding.delete(camera);
}
}
/**
* 放进一帧。
*
* 解码是异步的,所以这里要再判一次"更新的一帧有没有先到":`createImageBitmap` 的
* 完成顺序不保证与发起顺序一致,不判的话画面会偶发地往回跳一帧。
*
* 预览模式(`dev-preview.ts`)直接调它,绕过 WebSocket——两条路径共用同一套存储逻辑,
* 所以预览里看到的画面行为与真机一致。
*/
private store(
camera: number,
frameId: number,
width: number,
height: number,
bitmap: ImageBitmap,
) {
const current = this.frames.get(camera);
// 带符号差处理 u32 回绕。
// After a quiet interval the board may have rebooted and restarted its
// frame counter. An older in-flight decode cannot hold the display forever.
if (current && ((frameId - current.frameId) | 0) <= 0 && this.now() - current.receivedAt < 1000) {
bitmap.close();
return;
}
current?.bitmap.close();
this.frames.set(camera, {
camera,
frameId,
width,
height,
bitmap,
receivedAt: this.now(),
});
}
/** 给预览模式用的入口:直接塞一帧。 */
injectFrame(
camera: number,
frameId: number,
width: number,
height: number,
bitmap: ImageBitmap,
) {
this.counters.frames += 1;
this.store(camera, frameId, width, height, bitmap);
}
private scheduleReconnect() {
if (this.closed || this.retryTimer !== null) return;
this.retryTimer = window.setTimeout(() => {
this.retryTimer = null;
this.counters.reconnects += 1;
this.backoff = Math.min(this.backoff * 2, MAX_BACKOFF_MS);
this.open();
}, this.backoff);
}
/** 某一路最新的一帧。 */
latest(camera: number | null | undefined): FrameInfo | undefined {
if (camera === null || camera === undefined) return undefined;
return this.frames.get(camera);
}
close() {
this.closed = true;
this.generation += 1;
this.pending.clear();
this.frameTimes.clear();
this.decoding.clear();
if (this.retryTimer !== null) {
window.clearTimeout(this.retryTimer);
this.retryTimer = null;
}
this.ws?.close();
this.ws = null;
for (const frame of this.frames.values()) frame.bitmap.close();
this.frames.clear();
}
}
+277
View File
@@ -0,0 +1,277 @@
/**
* 与 Rust 侧 DTO 一一对应的类型。
*
* 这些名字不是随手起的:Rust 那边的结构体带 `#[serde(rename_all = "camelCase")]`,
* 字段名就是这里写的这样。改任何一边都要同时改另一边——**编译器不会帮你发现这件事**,
* 所以两边都留了指向对方的注释。
*
* 对应的 Rust 定义在 `client/core/src/snapshot.rs` 与 `client/src-tauri/src/recording.rs`。
*/
export type Role = "team" | "referee";
/** `cam_core::config::CrosshairStyle` */
export type CrosshairStyle = "cross" | "cross-dot" | "circle-dot" | "dot";
/** `cam_core::config::GridStyle` */
export type GridStyle = "thirds" | "squares" | "cross";
/** `cam_core::config::HealthConfig` */
export interface HealthConfig {
visible: boolean;
showNumbers: boolean;
showTeamName: boolean;
lowThreshold: number;
pulse: boolean;
/** 血条宽度占画面宽度的比例。 */
width: number;
}
/** `cam_core::config::CrosshairConfig` */
export interface CrosshairConfig {
visible: boolean;
style: CrosshairStyle;
/** 臂长 / 半径,画面短边的比例。 */
size: number;
/** 线宽,画面短边的比例。 */
thickness: number;
/** 中心空隙,画面短边的比例。 */
gap: number;
/** `#RRGGBB` */
color: string;
/** 校准偏移,画面宽度的比例,正数向右。 */
offsetX: number;
/** 校准偏移,画面高度的比例,正数向下。 */
offsetY: number;
}
/** `cam_core::config::GridConfig` */
export interface GridConfig {
visible: boolean;
style: GridStyle;
divisions: number;
opacity: number;
}
/** `cam_core::config::HitFeedbackConfig` */
export interface HitFeedbackConfig {
flash: boolean;
/**
* 已废弃:命中时不再抖动画面。
*
* 字段留着只是为了读得进旧配置文件(Rust 侧 `deny_unknown_fields`,删字段会让写过
* `shake = true` 的配置直接解析失败)。界面不读它。
*/
shake: boolean;
marker: boolean;
intensity: number;
}
/** `cam_core::snapshot::HudView` */
export interface HudView {
health: HealthConfig;
crosshair: CrosshairConfig;
grid: GridConfig;
hitFeedback: HitFeedbackConfig;
showZoom: boolean;
showStats: boolean;
}
/** `cam_core::snapshot::ConfigView`(不含密码哈希) */
export interface ConfigView {
role: Role;
roleChosen: boolean;
team: number;
/** 两边在界面上显示的名字,下标就是队伍号。裁判端可以直接改。 */
teamNames: [string, string];
cameraId: number | null;
cameraIdText: string | null;
armorId: number | null;
armorIdText: string | null;
mirror: boolean;
passwordSet: boolean;
hud: HudView;
recordingDir: string;
ffmpeg: string;
}
/** `cam_core::snapshot::CameraDto` */
export interface CameraDto {
id: number;
idText: string;
addr: string;
online: boolean;
silenceMs: number;
/**
* 固件版本,来自板子广播的 Hello。固件太老、没带这个字段时是 `null`——
* 这时界面显示"版本未知",而不是一个看起来像真值的 `0.0.0`。
*/
firmwareVersion: string | null;
/** 自增构建号,0 = 未知。 */
firmwareBuild: number;
/** 板子自报的线路协议版本。 */
protocol: number;
/**
* 本客户端能不能和它通信。
*
* 为 `false` 时它不会有画面(帧被严格解析挡掉了),但界面**能说出原因**——
* 这正是把版本号放进 Hello 的全部意义。
*/
compatible: boolean;
}
/** `cam_core::snapshot::ArmorBoardDto` */
export interface ArmorBoardDto {
id: number;
idText: string;
addr: string;
online: boolean;
team: number;
hp: number;
platesSeen: number;
reportsAllPlates: boolean;
silenceMs: number;
}
/** `cam_core::snapshot::CameraStatsDto` */
export interface CameraStatsDto {
camera: number;
cameraText: string;
online: boolean;
status: string;
hasFrames: boolean;
fps: number;
width: number;
height: number;
framesShown: number;
framesDropped: number;
lossPercent: number;
datagrams: number;
lastFrameBytes: number;
gapMs: number | null;
}
/** `cam_core::snapshot::SlotsDto` */
export interface SlotsDto {
cameraA: number | null;
cameraB: number | null;
armorA: number | null;
armorB: number | null;
manual: boolean;
}
/**
* `cam_core::snapshot::MatchOutcome`。
*
* 是**从这一边看**的结论,不是"谁赢了"这个全局判断:同一场对局里两边的 DTO 各带一份。
*/
export type MatchOutcome = "victory" | "defeat" | "draw";
/** `cam_core::snapshot::TeamHealthDto` */
export interface TeamHealthDto {
team: number;
name: string;
available: boolean;
placeholder: string;
hp: number | null;
hps: number[];
board: number | null;
boardText: string | null;
critical: boolean;
/** 有结论时(有人归零)才有值;两边都活着时是 null。 */
outcome: MatchOutcome | null;
}
/** `cam_core::snapshot::RecordingDto` */
export interface RecordingDto {
camera: number;
cameraText: string;
active: boolean;
path: string | null;
inputFps: number;
framesWritten: number;
framesDropped: number;
startedMs: number | null;
error: string | null;
}
/** `client/src-tauri/src/recording.rs` 的 `MediaFileDto` */
export interface MediaFileDto {
name: string;
path: string;
kind: "video" | "image";
bytes: number;
modifiedMs: number;
}
/** `cam_core::snapshot::Snapshot` */
export interface Snapshot {
matchClock: MatchClockView;
role: Role;
team: number;
mirrored: boolean;
demo: boolean;
diagnostics: boolean;
unlocked: boolean;
discoveryOpen: boolean;
uptimeMs: number;
clients: number;
config: ConfigView;
cameras: CameraDto[];
armorBoards: ArmorBoardDto[];
stats: CameraStatsDto[];
slots: SlotsDto;
health: TeamHealthDto[];
recordings: RecordingDto[];
notes: string[];
}
export type MatchPhase = "idle" | "preparation" | "ready" | "countdown" | "running" | "paused" | "finished";
export interface MatchClockView {
phase: MatchPhase;
resumePhase: MatchPhase;
pauseKind: "player" | "official" | null;
applicant: number | null;
reason: string;
remainingMs: number;
elapsedMs: number;
pauseRemainingMs: number | null;
pauseElapsedMs: number;
connected: boolean;
freshForMs: number;
source: string | null;
syncError: string | null;
}
export type MatchAction = { type: "prepare" | "resume" | "end" | "reset" }
| { type: "countdown"; seconds: number }
| { type: "pausePlayer"; team: number; reason: string; approved: boolean }
| { type: "pauseOfficial"; reason: string };
/** `client/src-tauri/src/server.rs` 的 `StreamInfo` */
export interface StreamInfo {
url: string;
port: number;
clients: number;
}
/** `server::WireMsg` 的 `Hit`。 */
export interface HitEvent {
board: number;
team: number;
index: number;
from: number;
to: number;
damage: number;
atMs: number;
}
/** `server::WireMsg` 的文本信封。`t` 是 serde 的内部标签。 */
export type WireMsg =
| ({ t: "snapshot" } & Snapshot)
| ({ t: "hit" } & HitEvent)
| { t: "note"; message: string }
| { t: "frameTiming"; camera: number; frameId: number; publishedUnixMs: number }
| { t: "confirmQuit" };
/** 二进制视频帧的头部长度,与 `server::FRAME_HEADER_LEN` 一致。 */
export const FRAME_HEADER_LEN = 16;
+86
View File
@@ -0,0 +1,86 @@
/**
* F11 / Alt+Enter 全屏切换。
*
* 状态由 Tauri 窗口持有,不落 localStorage:现场重启后回到窗口化更安全。
* 400 ms 去抖避免 F11 自动重复把窗口来回切;输入框内不抢键。
*
* # 为什么每一处都要先看 `__TAURI_INTERNALS__`
*
* `getCurrentWindow()` 不是一个"返回 null"的函数:没有 Tauri 注入时它会在**取
* metadata 的那一步直接抛**(`Cannot read properties of undefined`)。而抛在
* `getCurrentWindow().isFullscreen()` 里意味着抛在 effect 的同步段——React 接不住,
* 整棵树会被卸掉,浏览器里 `pnpm dev` 的预览就变成一块空白。
*
* 所以这里不写 try/catch 去兜:先判断在不在 Tauri 里,不在就整段跳过。
*/
import { useCallback, useEffect, useRef, useState } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
/** 页面里有没有 Tauri 注入。与 `dev-preview.ts` 用同一个判据。 */
function hasTauri(): boolean {
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
}
export function useFullscreen() {
const [fullscreen, setFullscreen] = useState(false);
const lastToggle = useRef(0);
const toggle = useCallback(async () => {
const now = Date.now();
if (now - lastToggle.current < 400) return;
lastToggle.current = now;
if (!hasTauri()) {
setFullscreen((value) => !value);
return;
}
try {
const window = getCurrentWindow();
const next = !(await window.isFullscreen());
await window.setFullscreen(next);
setFullscreen(next);
} catch {
// 窗口在切换途中被销毁之类。界面不应该为此报错。
}
}, []);
useEffect(() => {
if (!hasTauri()) return;
try {
void getCurrentWindow()
.isFullscreen()
.then(setFullscreen)
.catch(() => undefined);
} catch {
// 同上:没有窗口也要能跑。
}
}, []);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
const tag = target?.tagName;
if (
tag === "INPUT" ||
tag === "TEXTAREA" ||
tag === "SELECT" ||
target?.isContentEditable
) {
return;
}
if (event.key === "F11" || (event.altKey && event.key === "Enter")) {
event.preventDefault();
void toggle();
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [toggle]);
return { fullscreen, toggle };
}
+64
View File
@@ -0,0 +1,64 @@
/**
* 几个只服务于界面节奏的小 hook。
*
* 它们都不碰后端状态——快照每 200 ms 已经推过来了,重算一次读数不需要再发命令。
*/
import { useEffect, useRef, useState } from "react";
/**
* 「多久没有新的输入了」。
*
* 用户端用它做 HUD 的休眠:没人碰、没挨打的时候,角上的标签与提示淡下去,把注意力还给
* 画面本身;一旦有事件(鼠标、滚轮、键、命中)就整块醒过来。这不是装饰——它是"朴素"
* 那一条的落地方式:不动的时候屏幕上的东西越少越好。
*/
export function useIdle(delay = 6000): boolean {
const [idle, setIdle] = useState(false);
const timer = useRef<number | undefined>(undefined);
useEffect(() => {
const wake = () => {
setIdle(false);
window.clearTimeout(timer.current);
timer.current = window.setTimeout(() => setIdle(true), delay);
};
wake();
const events: (keyof WindowEventMap)[] = [
"pointermove",
"pointerdown",
"wheel",
"keydown",
"focus",
];
for (const name of events) window.addEventListener(name, wake, { passive: true });
return () => {
window.clearTimeout(timer.current);
for (const name of events) window.removeEventListener(name, wake);
};
}, [delay]);
return idle;
}
/**
* 一个以固定频率重算的时钟。
*
* 录制时长、"静默 3.2 秒前"这类读数如果没有自己的节拍,就只能等下一份快照才更新——而快照
* 200 ms 一份,等于一直在跳。反过来,秒级的读数每秒动一次就够了。
*
* 返回的 `now` 是墙钟毫秒(`Date.now()`),与快照里的 `startedMs` 同源。
*/
export function useNow(intervalMs = 1000): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
return () => window.clearInterval(timer);
}, [intervalMs]);
return now;
}
+22
View File
@@ -0,0 +1,22 @@
/**
* 构建信息。**由 `scripts/version.mjs` 生成,请勿手改。**
*
* 版本号与构建号都从 git 历史算出来(见该脚本的文件头),所以界面显示的一定就是
* 这一份二进制的来源,不会出现"装包里写着 0.1.0,其实是两周后的代码"。
*/
export const BUILD = {
version: "0.3.0",
major: 0,
minor: 3,
patch: 0,
/** git 提交数,单调递增。 */
build: 41,
/** 线路协议版本。与固件自报的那个数直接比对。 */
protocol: 1,
/** 生成时的提交日期(`YYYY-MM-DD`)。 */
date: "2026-10-22",
} as const;
/** `"0.2.0+57"` —— 界面上放得下的那一行。 */
export const VERSION_LABEL = `v${BUILD.version}+${BUILD.build}`;
+20
View File
@@ -0,0 +1,20 @@
import { createRoot } from "react-dom/client";
import App from "./App";
import { LatencyPage } from './pages/LatencyPage';
import { invoke } from '@tauri-apps/api/core';
import "./styles/index.css";
const container = document.getElementById("root");
if (!container) {
throw new Error("index.html 里没有 #root");
}
// 不用 StrictMode:这个界面的关键路径是命令式的(WebSocket、requestAnimationFrame 绘制
// 循环、canvas 尺寸)。StrictMode 在开发下会把每个 effect 跑两遍,于是连接与绘制循环会
// 短暂地建两份——排查起来的噪音大于它带来的收益。生产构建的行为与这里一致。
const root=createRoot(container);
if('__TAURI_INTERNALS__' in window) {
void invoke<boolean>('latency_enabled').then(enabled=>root.render(enabled?<LatencyPage/>:<App/>),()=>root.render(<App/>));
} else root.render(<App/>);
+101
View File
@@ -0,0 +1,101 @@
import { useEffect,useRef,useState } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { api } from '../lib/ipc';
import { startStream,useAppStore } from '../lib/store';
import { decodeMarker,drawMarker } from '../lib/latency-marker';
import { VideoSurface,IDENTITY_VIEW } from '../components/VideoSurface';
import type { FrameInfo } from '../lib/stream';
type Stamp={draw:number;next:number|null;sampled:boolean};
const feedback={flash:false,shake:false,marker:false,intensity:0};
export function LatencyPage() {
const {snapshot,connected}=useAppStore();
const [camera,setCamera]=useState<number|null>(null);
const [status,setStatus]=useState('等待摄像头与屏幕标记');
const [summary,setSummary]=useState({samples:0,p50:0,p95:0,refresh:0});
const target=useRef<HTMLCanvasElement>(null);
const history=useRef(new Map<number,Stamp>());
const scratch=useRef<HTMLCanvasElement|null>(null);
const values=useRef<number[]>([]);
const lastSample=useRef(-Infinity);
const refresh=useRef(16.7);
const active=useRef(true);
useEffect(()=>{
let client:ReturnType<typeof startStream>|null=null,disposed=false;
void api.streamInfo().then(info=>{if(!disposed)client=startStream(info.url);}).catch(e=>setStatus(String(e)));
return()=>{disposed=true;client?.close();};
},[]);
useEffect(()=>{
if(camera===null && snapshot) {
const found=snapshot.cameras.find(c=>c.online);
if(found)setCamera(found.id);
}
},[snapshot,camera]);
useEffect(()=>{
active.current=true;
const canvas=target.current;if(!canvas)return;
const ctx=canvas.getContext('2d');if(!ctx)return;
let raf=0,counter=0,previous:Stamp|null=null,last=0,lastMarker=-Infinity;
const loop=(now:number)=>{
if(previous){previous.next=now;previous=null;}
if(last && now-last<50)refresh.current=refresh.current*.9+(now-last)*.1;
last=now;
// A 180 Hz display can change several IDs within one camera exposure.
// Hold each event for 50 ms, and record only its first decodable echo.
if(now-lastMarker>=50){
lastMarker=now;counter=(counter+1)&4095;
drawMarker(ctx,counter);
const stamp={draw:performance.now(),next:null,sampled:false};
history.current.set(counter,stamp);previous=stamp;
}
// Only the most recent five seconds count, including counter wrap.
for(const [id,value] of history.current) if(now-value.draw>5000)history.current.delete(id);
raf=requestAnimationFrame(loop);
};
raf=requestAnimationFrame(loop);
return()=>{active.current=false;cancelAnimationFrame(raf);};
},[]);
const painted=(canvas:HTMLCanvasElement,frame:FrameInfo,drawMs:number)=>{
if(drawMs-lastSample.current<25)return;
lastSample.current=drawMs;
const started=performance.now();
const small=scratch.current??(scratch.current=document.createElement('canvas'));
small.width=320;small.height=240;
const ctx=small.getContext('2d',{willReadFrequently:true});if(!ctx)return;
// Read the canvas after the production renderer has painted the frame.
ctx.drawImage(canvas,0,0,320,240);
const marker=decodeMarker(ctx.getImageData(0,0,320,240).data,320,240);
const analysisMs=performance.now()-started;
if(!marker){setStatus('未识别到四角标记:请完整拍入左侧标记,并放大其在画面中的占比');return;}
const source=history.current.get(marker.counter);
if(!source||source.next===null||source.draw>drawMs){setStatus('等待本次校准的有效标记');return;}
if(source.sampled)return;
source.sampled=true;
requestAnimationFrame(nextRafMs=>{
if(!active.current)return;
const lowerMs=Math.max(0,drawMs-source.next!);
const upperMs=nextRafMs-source.draw;
if(upperMs<lowerMs||upperMs>5000)return;
const value=(lowerMs+upperMs)/2;
values.current.push(value);
const sorted=[...values.current].sort((a,b)=>a-b);
setStatus('已识别标记,正在测量实际相机到客户端画布的延迟');
setSummary({samples:sorted.length,p50:sorted[Math.floor((sorted.length-1)*.5)],p95:sorted[Math.floor((sorted.length-1)*.95)],refresh:refresh.current});
void invoke('latency_sample',{sample:{frameId:frame.frameId,counter:marker.counter,sourceDrawMs:source.draw,
drawMs,nextRafMs,lowerMs,upperMs,decodeToDrawMs:drawMs-frame.receivedAt,analysisMs}}).catch(e=>setStatus(`报告写入失败:${String(e)}`));
});
};
return <main style={{height:'100vh',display:'flex',flexDirection:'column',padding:20,gap:12,background:'#111820',color:'#f3f6fa'}}>
<h1 style={{fontSize:24}}>屏幕 → 摄像头 → 客户端绘制延迟校准</h1>
<p>将摄像头固定对准左侧标记,完整拍到四个彩色角块。不要拍右侧回显区域;保持窗口位置不动。</p>
<div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16,flex:1,minHeight:0}}>
<canvas ref={target} width={800} height={600} style={{width:'100%',height:'100%',objectFit:'contain'}}/>
<div style={{position:'relative',minHeight:0}}><VideoSurface camera={camera} emptyText="等待真实摄像头" mirrored={false}
crosshair={null} grid={null} view={IDENTITY_VIEW} onView={()=>{}} hitFeedback={feedback} showZoom={false} onFramePainted={painted}/></div>
</div>
<p>{connected?'已连接':'连接中'} · {status}</p>
<p style={{fontSize:22}}>样本 {summary.samples} · P50 {summary.p50.toFixed(1)} ms · P95 {summary.p95.toFixed(1)} ms</p>
<p>每 50 ms 更新标记,记录首次可解码回显,包含相机取样等待、曝光、采集、传输和绘制;混合曝光帧不计入。相邻 rAF 夹定绘制时间,刷新间隔约 {summary.refresh.toFixed(1)} ms;面板像素响应需高速相机复核。</p>
</main>;
}
+452
View File
@@ -0,0 +1,452 @@
/** 固件维护:固定视口、设备图示和分步操作;写入校验仍由现有后端执行。 */
import { useCallback, useEffect, useRef, useState } from "react";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { Button } from "../components/controls";
import { ArmorBuildPanel } from "../components/ArmorBuildPanel";
import { DeviceDiagram } from "../components/DeviceDiagram";
import { Dialog } from "../components/Dialog";
import { api } from "../lib/ipc";
import { maintenanceMismatch } from "../lib/maintenance-safety";
import {
formatBytes, formatOffset, maintenanceApi, selectBundleDirectory, selectBundleZip,
selectMaintenanceDirectory,
type BundleInfo, type DeviceSnapshot, type FlashPlan, type FlashProgress, type FlashReport, type PortInfo,
} from "../lib/maintenance";
type Busy = null | "ports" | "probe" | "bundle" | "plan" | "flash" | "restore" | "build";
type ViewStep = "device" | "bundle" | "confirm" | "result";
const BUSY_TEXT = { ports: "刷新串口", probe: "读取设备", bundle: "校验固件", plan: "核对计划", flash: "烧录与回读", restore: "恢复备份", build: "编译装甲板" } as const;
function message(err: unknown): string { return err instanceof Error ? err.message : String(err); }
export function MaintenancePage({ onClose, fullscreen, onToggleFullscreen }: { onClose: () => void; fullscreen: boolean; onToggleFullscreen: () => void }) {
const [viewStep, setViewStep] = useState<ViewStep>("device");
const [modal, setModal] = useState<"build" | "details" | null>(null);
const [detailsTab, setDetailsTab] = useState<"log" | "data">("log");
const [ports, setPorts] = useState<PortInfo[]>([]);
const [port, setPort] = useState("");
const [device, setDevice] = useState<DeviceSnapshot | null>(null);
const [bundle, setBundle] = useState<BundleInfo | null>(null);
const [plan, setPlan] = useState<FlashPlan | null>(null);
const [report, setReport] = useState<FlashReport | null>(null);
const [progress, setProgress] = useState<FlashProgress | null>(null);
const [busy, setBusy] = useState<Busy>(null);
const [error, setError] = useState<string | null>(null);
const [logs, setLogs] = useState<string[]>([]);
const [backupApp, setBackupApp] = useState(true);
const [firmwareKind, setFirmwareKind] = useState<"" | "camera" | "armor">("");
const [expectedTeam, setExpectedTeam] = useState("");
const [confirmedTarget, setConfirmedTarget] = useState(false);
const [confirmedOverwrite, setConfirmedOverwrite] = useState(false);
useEffect(() => {
if (!import.meta.env.DEV || "__TAURI_INTERNALS__" in window) return;
const stage = new URLSearchParams(location.search).get("stage");
if (!stage || !["confirm", "migrate", "flash", "result", "failure", "mismatch"].includes(stage)) return;
let disposed = false;
void import("../lib/maintenance-preview").then(({ maintenancePreview }) => {
if (disposed) return;
const sample = maintenancePreview(stage);
setModal(null); setFirmwareKind("armor"); setExpectedTeam(stage === "mismatch" ? "1" : "0");
setPort(sample.device.port); setPorts([{ portName: sample.device.port, label: "合成串口", vid: null, pid: null, likelyEsp: true }]);
setDevice(sample.device); setBundle(sample.bundle); setPlan(sample.plan);
setViewStep(stage === "result" || stage === "failure" ? "result" : "confirm");
if (stage === "result" || stage === "failure") { setReport(sample.report); setDevice(null); setPlan(null); }
if (stage === "flash") { setBusy("flash"); setProgress({ phase: "回读 App", message: "合成进度:回读 App,未连接硬件", current: 524288, total: 1048576 }); }
});
return () => { disposed = true; };
}, []);
useEffect(() => {
setConfirmedTarget(false); setConfirmedOverwrite(false);
}, [plan, port, bundle, firmwareKind, expectedTeam]);
const logEnd = useRef<HTMLDivElement | null>(null);
const lastProgressPhase = useRef("");
const lastProgressAt = useRef(0);
const appendLog = useCallback((line: string) => {
setLogs((current) => [...current.slice(-240), line]);
}, []);
useEffect(() => {
// 只滚动诊断框中的日志,主页面与设备图保持固定。
const scroller = logEnd.current?.parentElement;
if (scroller) scroller.scrollTop = scroller.scrollHeight;
}, [logs, modal, detailsTab]);
const probePort = useCallback(
async (target: string) => {
if (!target) return;
setBusy("probe");
setProgress(null);
setError(null);
setPlan(null);
setReport(null);
appendLog(`读取 ${target} …(设备会复位一次)`);
try {
const snapshot = await maintenanceApi.probe(target);
setDevice(snapshot);
setViewStep("bundle");
appendLog(
`设备:${snapshot.chip} ${snapshot.mac ?? "MAC 未知"} · ${snapshot.flashSizeText} · ` +
`${snapshot.app ? `App ${snapshot.app.version}` : "未识别 App"}`,
);
} catch (err) {
setDevice(null);
setError(message(err));
appendLog(`读取失败:${message(err)}`);
} finally {
setBusy(null);
}
},
[appendLog],
);
const refreshPorts = useCallback(
async (autoProbe: boolean) => {
setBusy("ports");
setProgress(null);
setError(null);
try {
const list = await maintenanceApi.listPorts();
setPorts(list);
setDevice(null); setPlan(null); setReport(null); setProgress(null);
const next = list.find((entry) => entry.likelyEsp)?.portName ?? list[0]?.portName ?? "";
setPort(next);
appendLog(`发现 ${list.length} 个串口${next ? `,选中 ${next}` : ""}`);
if (autoProbe && next) {
await probePort(next);
}
} catch (err) {
setError(message(err));
} finally {
setBusy(null);
}
},
[appendLog, probePort],
);
useEffect(() => {
void refreshPorts(false);
// 读取会复位设备,首次进入只枚举串口,由用户主动读取。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
let dispose: UnlistenFn | undefined;
let disposed = false;
void listen<FlashProgress>("maintenance-progress", (event) => {
if (disposed) return;
const payload = event.payload;
setProgress(payload);
const now = Date.now();
if (payload.phase !== lastProgressPhase.current || now - lastProgressAt.current > 1000) {
lastProgressPhase.current = payload.phase;
lastProgressAt.current = now;
appendLog(`[${payload.phase}] ${payload.message}`);
}
})
.then((unlisten) => {
if (disposed) unlisten();
else dispose = unlisten;
})
.catch(() => undefined);
return () => {
disposed = true;
dispose?.();
};
}, [appendLog]);
useEffect(() => {
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) return;
let disposed = false;
let stop: UnlistenFn | undefined;
void listen<string>("maintenance-build-log", event => appendLog(event.payload)).then(unlisten => {
if (disposed) unlisten(); else stop = unlisten;
});
return () => { disposed = true; stop?.(); };
}, [appendLog]);
useEffect(() => {
if (import.meta.env.DEV && !("__TAURI_INTERNALS__" in window)) return;
let disposed = false;
let stop: UnlistenFn | undefined;
void listen<string>("maintenance-close-blocked", event => { setError(event.payload); appendLog(event.payload); }).then(unlisten => {
if (disposed) unlisten(); else stop = unlisten;
});
return () => { disposed = true; stop?.(); };
}, [appendLog]);
const chooseBundle = useCallback(async (kind: "zip" | "dir") => {
setBusy("bundle");
setProgress(null);
setError(null);
try {
const path = kind === "zip" ? await selectBundleZip() : await selectBundleDirectory();
if (!path) return;
setBundle(null); setPlan(null); setReport(null); setProgress(null);
const info = await maintenanceApi.loadBundle(path);
setBundle(info);
setPlan(null);
setReport(null);
appendLog(
`固件包:${info.name} ${info.version}(${info.chip},App ${formatBytes(info.appSize)})`,
);
} catch (err) {
setError(message(err));
appendLog(`固件包加载失败:${message(err)}`);
} finally {
setBusy(null);
}
}, [appendLog]);
const makePlan = useCallback(async () => {
if (!port || !bundle) return;
setBusy("plan");
setProgress(null);
setError(null);
setPlan(null);
setReport(null);
appendLog("生成烧录计划…");
try {
const next = await maintenanceApi.plan(port, bundle.path);
setPlan(next);
setViewStep("confirm");
setDevice(next.device); setBundle(next.bundle); setProgress(null);
appendLog(
`计划:目标 ${formatOffset(next.targetOffset)},共 ${next.candidates.length} 个候选槽位`,
);
for (const warning of next.warnings) appendLog(`注意:${warning}`);
} catch (err) {
setError(message(err));
appendLog(`无法生成烧录计划:${message(err)}`);
} finally {
setBusy(null);
}
}, [port, bundle, appendLog]);
const startFlash = useCallback(async () => {
if (!port || !bundle || !plan || !confirmedTarget || (plan.mode === "armor-install" && !confirmedOverwrite)) return;
const confirmed = window.confirm(
`${port} · ${plan.device.chip} · MAC ${plan.device.mac}\n${plan.bundle.name} ${plan.bundle.version}\n` +
(plan.mode === "armor-install" ?
`${plan.bundle.armorTeam == null ? "通用固件(客户端选择队伍)" : `旧版固定队伍${plan.bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} · 阈值 ${plan.bundle.armorThreshold}\n\n` +
`将先完整备份 4 MB Flash,再覆盖 Bootloader、App 和分区表;迁移旧布局时会清除原配置。旧 App 会被覆盖;恢复必须使用完整备份。\n烧录期间请勿断电或拔线。继续?` :
`将把 App 写入 ${formatOffset(plan.targetOffset)}(${formatBytes(plan.appSize)}),` +
`整段回读通过后才切换分区表。\n\n` +
`旧 App 保留在 ${formatOffset(plan.currentFactoryOffset)}。${backupApp ? "会先备份旧 App。" : "本次不另存旧 App 备份。"}\n` +
`烧录期间设备会复位,视频流会中断。继续?`),
);
if (!confirmed) return;
setBusy("flash");
setError(null);
setReport(null);
setProgress(null);
setLogs([]);
lastProgressPhase.current = "";
lastProgressAt.current = 0;
appendLog("开始烧录…");
try {
const result = await maintenanceApi.flash(port, bundle.path, plan.confirmation, backupApp);
setReport(result);
setViewStep("result");
setPlan(null); setConfirmedTarget(false); setDevice(null);
appendLog(
result.ok
? `烧录成功:${formatOffset(result.targetOffset)}`
: `烧录失败:${result.error ?? "未知错误"}`,
);
if (result.note) appendLog(`提示:${result.note}`);
} catch (err) {
setError(message(err));
appendLog(`烧录异常:${message(err)}`);
} finally {
setPlan(null); setDevice(null);
setBusy(null);
}
}, [port, bundle, plan, backupApp, appendLog, confirmedTarget, confirmedOverwrite]);
const cancelFlash = useCallback(async () => {
try {
await maintenanceApi.cancel();
appendLog(busy === "build" ? "已请求取消编译,正在结束构建子进程。" : "已请求取消;当前正在进行的写入/回读步骤结束后停止。");
} catch (err) {
setError(message(err));
}
}, [appendLog, busy]);
const restoreTable = useCallback(async () => {
if (!port || !report?.backupDir) return;
if (!window.confirm(report.mode === "armor-install"
? "将向同一 MAC 的装甲板恢复完整 4 MB Flash,覆盖当前固件及设置。恢复期间请勿断电或拔线。继续?"
: "将把备份分区表写回 0x8000,设备会复位到旧 App。继续?")) return;
setBusy("restore");
setProgress(null);
setError(null);
try {
const result = await maintenanceApi.restoreTable(port, report.backupDir, report.mode === "armor-install" ? "armor" : "camera");
appendLog(result);
setReport(null);
setPlan(null);
await probePort(port);
} catch (err) {
setError(message(err));
appendLog(`恢复失败:${message(err)}`);
} finally {
setBusy(null);
}
}, [port, report, appendLog, probePort]);
const revealBackup = useCallback(() => {
if (!report?.backupDir) return;
void api.reveal(report.backupDir).catch((err) => setError(message(err)));
}, [report]);
const restoreFromDirectory = async () => {
if (!port) return;
setBusy("restore"); setProgress(null); setError(null);
try {
const path = await selectMaintenanceDirectory("选择含 armor-backup.json 与 flash-old.bin 的完整备份目录");
if (!path || !window.confirm(`将向 ${port} 恢复完整 Flash,覆盖当前固件和设置。后端会核对备份哈希、芯片和 MAC。恢复期间请勿断电或拔线。继续?`)) return;
appendLog(await maintenanceApi.restoreTable(port, path, "armor"));
setDevice(null); setPlan(null); setReport(null); setProgress(null);
} catch (err) { setError(message(err)); appendLog(`恢复失败:${message(err)}`); }
finally { setBusy(null); }
};
const anyBusy = busy !== null;
const mismatch = maintenanceMismatch(firmwareKind, expectedTeam, device, bundle);
const securityEnabled = Boolean(
device && (device.secureBoot || device.secureDownload || device.flashEncryption),
);
const portAvailable = ports.some(entry => entry.portName === port);
const ratio = progress && progress.total > 0 ? Math.max(0, Math.min(1, progress.current / progress.total)) : null;
const preview = import.meta.env.DEV && !("__TAURI_INTERNALS__" in window);
const visualState = busy ?? (report ? report.ok ? "complete" : "failed" : device ? "identified" : portAvailable ? "available" : "waiting");
// 仅枚举端口,不打开串口或复位。拔线后立即使旧计划失效。
useEffect(() => {
if (anyBusy || preview) return;
let disposed = false;
const poll = window.setInterval(() => {
void maintenanceApi.listPorts().then(list => {
if (disposed) return;
setPorts(list);
if (port && !list.some(entry => entry.portName === port)) { setDevice(null); setPlan(null); }
}).catch(() => undefined);
}, 2000);
return () => { disposed = true; window.clearInterval(poll); };
}, [anyBusy, port, preview]);
useEffect(() => {
const key = (event: KeyboardEvent) => {
if (event.key === "Escape" && !modal && !anyBusy) { event.preventDefault(); onClose(); }
};
window.addEventListener("keydown", key);
return () => window.removeEventListener("keydown", key);
}, [modal, anyBusy, onClose]);
return <main className="mnt">
<header className="mnt-head">
<div><span className="label mnt-kicker">RMIC / DEVICE SERVICE</span><h1>固件维护</h1></div>
<div className="mnt-head__actions">
{preview && <span className="tag tag--warn">预览 · 合成数据 / 无 USB 操作</span>}
<Button variant="ghost" onClick={onToggleFullscreen}>{fullscreen ? "退出全屏" : "全屏"}</Button>
<Button variant="ghost" disabled={anyBusy} onClick={onClose}>返回 <kbd>ESC</kbd></Button>
</div>
</header>
<div className="mnt-workspace">
<section className="mnt-visual" aria-label="设备与任务状态">
<div className="mnt-visual__head"><span className="label">USB / {firmwareKind === "armor" ? "ARMOR" : firmwareKind === "camera" ? "VIDEO" : "DEVICE"}</span><span className={`mnt-link${device ? " is-live" : ""}`}><i />{device ? "已读取" : portAvailable ? "端口可用 · 待读取" : "未发现目标串口"}</span></div>
<DeviceDiagram kind={firmwareKind} identified={!!device} portAvailable={portAvailable} active={anyBusy} failed={!!error || !!report && !report.ok} complete={!!report?.ok} ratio={ratio} chip={device?.chip ?? (firmwareKind === "armor" ? "ESP32-C3" : firmwareKind === "camera" ? "ESP32-S3" : "MCU")} />
<div key={visualState} className="mnt-visual__status" role="status">
<span className="label">{report ? "RESULT" : busy ? "CURRENT PHASE" : "DEVICE STATUS"}</span>
<h2>{busy ? BUSY_TEXT[busy] : report ? report.ok ? "写入与回读完成" : "烧录未完成" : device ? "设备已识别" : "等待读取设备"}{busy && ratio !== null && <span className="num"> {Math.round(ratio * 100)}%</span>}</h2>
<p>{anyBusy ? progress?.message ?? (busy === "build" ? "构建日志可在诊断中查看" : "请保持 USB 连接") : report ? "上次操作结果 · 仍需检查板上运行情况" : device ? `${device.chip.toUpperCase()} · ${device.flashSizeText}` : portAvailable ? `${port} · 点击读取设备` : "连接 USB 后刷新串口"}</p>
</div>
<dl className="mnt-identity"><div><dt>串口</dt><dd>{port || "—"}</dd></div><div><dt>MAC</dt><dd>{device?.mac ?? report?.mac ?? "—"}</dd></div><div><dt>队伍设置</dt><dd>{firmwareKind === "armor" ? bundle?.armorTeam != null ? `旧版 / ${expectedTeam === "" ? "待核对" : expectedTeam === "0" ? "红" : "蓝"}` : "客户端选择" : "—"}</dd></div></dl>
</section>
<section className="mnt-task" aria-label="固件操作">
<nav className="mnt-nav" aria-label="维护步骤">
{([{ key: "device", label: "连接" }, { key: "bundle", label: "固件" }, { key: "confirm", label: "烧录" }, { key: "result", label: "结果" }] as const).map((step, index) => <button key={step.key} className={viewStep === step.key ? "is-active" : ""} aria-current={viewStep === step.key ? "step" : undefined} disabled={anyBusy || step.key === "bundle" && (!firmwareKind) || step.key === "confirm" && !plan || step.key === "result" && !report} onClick={() => setViewStep(step.key)}><span className="num">0{index + 1}</span>{step.label}</button>)}
</nav>
{error && <div className="mnt-error" role="alert">{error}</div>}
<div key={viewStep} className={`mnt-task__body mnt-task__body--${viewStep}`}>
{viewStep === "device" && <>
<div className="mnt-task__title"><span className="label">01 / CONNECT</span><h2>连接哪一种设备?</h2></div>
<div className="mnt-kind" role="group" aria-label="维护对象">
<button className={firmwareKind === "camera" ? "is-selected" : ""} disabled={anyBusy} onClick={() => { setFirmwareKind("camera"); setPlan(null); setReport(null); setProgress(null); }} aria-pressed={firmwareKind === "camera"}>图传板<small>ESP32-S3</small></button>
<button className={firmwareKind === "armor" ? "is-selected" : ""} disabled={anyBusy} onClick={() => { setFirmwareKind("armor"); setPlan(null); setReport(null); setProgress(null); }} aria-pressed={firmwareKind === "armor"}>装甲板主板<small>ESP32-C3</small></button>
</div>
<div className={`mnt-connection-fields${firmwareKind === "armor" && bundle?.armorTeam != null ? " has-team" : ""}`}>
{firmwareKind === "armor" && bundle?.armorTeam != null && <label className="mnt-field"><span>旧版固件目标队伍</span><select className="select" value={expectedTeam} disabled={anyBusy} onChange={event => { setExpectedTeam(event.target.value); setPlan(null); }}><option value="">选择这块板的队伍</option><option value="0">队伍一(红,0)</option><option value="1">队伍二(蓝,1)</option></select></label>}
<label className="mnt-field"><span>USB 串口</span><div className="mnt-row"><select className="select" value={port} disabled={anyBusy} onChange={event => { setPort(event.target.value); setDevice(null); setPlan(null); setReport(null); setProgress(null); }}>{ports.length === 0 && <option value="">未发现串口</option>}{ports.map(entry => <option key={entry.portName} value={entry.portName}>{entry.portName} · {entry.label}</option>)}</select><Button disabled={anyBusy} onClick={() => void refreshPorts(false)}>刷新</Button></div></label>
</div>
<p className="mnt-hint">请只连接要维护的主板。读取设备信息时,主板会复位。</p>
<div className="mnt-task__actions"><Button variant="primary" disabled={anyBusy || !port || !firmwareKind} onClick={() => void probePort(port)}>读取设备并继续</Button><Button variant="ghost" disabled={anyBusy || !firmwareKind} onClick={() => setViewStep("bundle")}>准备固件包</Button></div>
{firmwareKind === "armor" && <Button variant="ghost" disabled={anyBusy || !port} onClick={() => void restoreFromDirectory()}>恢复完整备份</Button>}
</>}
{viewStep === "bundle" && <>
<div className="mnt-task__title"><span className="label">02 / FIRMWARE</span><h2>选择对应固件</h2></div>
<div className="mnt-package"><span className="mnt-package__symbol" aria-hidden="true">↓</span><strong>{bundle ? `${bundle.name} ${bundle.version}` : "选择固件 ZIP"}</strong><span>{bundle ? `${bundle.chip.toUpperCase()} · ${formatBytes(bundle.appSize)}` : firmwareKind === "armor" ? "ESP32-C3 / 装甲板固件" : "ESP32-S3 / 图传固件"}</span>{bundle?.firmwareKind === "armor" && <b>{bundle.armorTeam == null ? "通用固件 / 客户端选择队伍" : `旧版固定队伍${bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} · 阈值 {bundle.armorThreshold}</b>}<Button disabled={anyBusy} onClick={() => void chooseBundle("zip")}>{bundle ? "更换 ZIP" : "选择 ZIP"}</Button></div>
{bundle?.firmwareKind === "armor" && bundle.armorTeam != null && <label className="mnt-field"><span>旧版包:核对实物队伍</span><select className="select" value={expectedTeam} disabled={anyBusy} onChange={event => { setExpectedTeam(event.target.value); setPlan(null); }}><option value="">请选择</option><option value="0">队伍一(红)</option><option value="1">队伍二(蓝)</option></select></label>}
<div className="mnt-row mnt-secondary">{firmwareKind === "armor" && <Button variant="ghost" disabled={anyBusy} onClick={() => setModal("build")}>从源码编译</Button>}<Button variant="ghost" disabled={anyBusy} onClick={() => void chooseBundle("dir")}>选择目录包</Button></div>
{mismatch && <p className="mnt-note warn" role="alert">{mismatch}</p>}
<div className="mnt-task__actions"><Button variant="primary" disabled={!device || !bundle || anyBusy || !!mismatch || securityEnabled} onClick={() => void makePlan()}>核对固件并继续</Button><Button variant="ghost" disabled={anyBusy} onClick={() => setViewStep("device")}>上一步</Button></div>
{securityEnabled && <p className="mnt-note warn">设备启用了安全启动或加密,不能使用此流程。</p>}
</>}
{viewStep === "confirm" && <>
<div className="mnt-task__title"><span className="label">03 / FLASH</span><h2>{busy === "flash" || busy === "restore" ? "请保持连接" : "确认烧录信息"}</h2></div>
{plan && busy === "flash" ? <>
<div className="mnt-confirmation"><strong className="num">{plan.device.port} / {plan.device.chip.toUpperCase()}</strong><span className="num">MAC {plan.device.mac}</span><span>{plan.bundle.name} {plan.bundle.version}</span></div>
<div className="mnt-running"><span className="label">CURRENT PHASE</span><h3>{progress?.phase ?? "准备设备"}</h3><p>{progress?.message ?? "正在核对设备与准备备份"}</p><span className="mnt-hint">左侧显示当前进度,操作结束后会显示结果。</span></div>
</> : plan ? <>
<div className="mnt-confirmation"><strong className="num">{plan.device.port} / {plan.device.chip.toUpperCase()}</strong><span className="num">MAC {plan.device.mac ?? "未知"}</span><span>{plan.bundle.name} {plan.bundle.version}</span>{plan.mode === "armor-install" && <b>{plan.bundle.armorTeam == null ? "通用固件 / 客户端选择队伍" : `旧版固定队伍${plan.bundle.armorTeam === 0 ? "一(红)" : "二(蓝)"}`} · 阈值 {plan.bundle.armorThreshold}</b>}</div>
<ul className="mnt-warnings">{plan.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>
{plan.mode !== "armor-install" && <label className="mnt-check"><input type="checkbox" checked={backupApp} disabled={anyBusy} onChange={event => setBackupApp(event.target.checked)} />备份旧 App</label>}
<label className="mnt-check"><input type="checkbox" checked={confirmedTarget} disabled={anyBusy} onChange={event => setConfirmedTarget(event.target.checked)} />已核对实物、串口、MAC、固件用途{plan.bundle.armorTeam != null ? "与队伍" : ""}</label>
{plan.mode === "armor-install" && <label className="mnt-check"><input type="checkbox" checked={confirmedOverwrite} disabled={anyBusy} onChange={event => setConfirmedOverwrite(event.target.checked)} />确认覆盖旧固件,恢复需用此板的完整备份</label>}
{mismatch && <p className="mnt-note warn" role="alert">{mismatch}</p>}
<div className="mnt-task__actions"><Button variant="primary" disabled={!plan.canFlash || anyBusy || !!mismatch || !confirmedTarget || plan.mode === "armor-install" && !confirmedOverwrite} onClick={() => void startFlash()}>开始烧录</Button>{busy === "flash" ? <Button variant="danger" onClick={() => void cancelFlash()}>请求取消</Button> : <Button variant="ghost" disabled={anyBusy} onClick={() => setViewStep("bundle")}>上一步</Button>}</div>
</> : <><p className="mnt-hint">计划已失效,请重新读取设备。</p><Button disabled={anyBusy} onClick={() => setViewStep("device")}>返回连接</Button></>}
</>}
{viewStep === "result" && report && <>
<div className="mnt-task__title"><span className="label">04 / RESULT</span><h2>{report.ok ? "回读校验通过" : "需要处理"}</h2></div>
<div className={`mnt-result${report.ok ? " is-ok" : " is-failed"}`}><span className="mnt-result__mark">{report.ok ? "✓" : "!"}</span><strong>{report.bundleName} {report.bundleVersion}</strong><p>{report.error ?? report.note ?? "请检查设备启动、灯色与上报。"}</p></div>
<div className="mnt-verifications"><span>App <b>{report.appVerified ? "一致" : "未通过"}</b></span><span>分区表 <b>{report.tableVerified ? "一致" : "未通过"}</b></span>{report.mode === "armor-install" && <span>Bootloader <b>{report.bootloaderVerified ? "一致" : "未通过"}</b></span>}<span>启动标志 <b>{report.bootOk === true ? "已捕获" : report.bootOk === false ? "异常" : "未确认"}</b></span></div>
<div className="mnt-task__actions"><Button onClick={revealBackup}>打开备份</Button>{report.needsRollback && <Button variant="danger" disabled={anyBusy} onClick={() => void restoreTable()}>{report.mode === "armor-install" ? "恢复完整备份" : "恢复旧分区表"}</Button>}<Button variant="ghost" disabled={anyBusy} onClick={() => { setViewStep("device"); setDevice(null); setPlan(null); setReport(null); setProgress(null); if (firmwareKind === "armor") setExpectedTeam(""); }}>更新另一块板</Button></div>
</>}
</div>
</section>
</div>
<footer className="mnt-foot"><span>{busy ? `正在${BUSY_TEXT[busy]} · 请勿拔线` : "USB 固件维护 / ESP32-S3 · ESP32-C3"}</span><div>{(busy === "flash" || busy === "build") && <Button variant="danger" onClick={() => void cancelFlash()}>请求取消</Button>}<Button variant="ghost" onClick={() => setModal("details")}>诊断 / 日志 {logs.length > 0 ? `(${logs.length})` : ""}</Button></div></footer>
{modal === "build" && <Dialog title="编译装甲板固件" className="mnt-build-dialog" onClose={() => setModal(null)} closeDisabled={anyBusy}>
<ArmorBuildPanel disabled={anyBusy} onBusy={value => { setBusy(value ? "build" : null); if (value) { setBundle(null); setPlan(null); setReport(null); setProgress(null); setError(null); } }} onBuilt={info => { setBundle(info); setModal(null); appendLog(`已生成固件:${info.sourcePath}`); }} onError={value => { setError(value); appendLog(value); }} />
{busy === "build" && <div className="mnt-build-status"><p>正在编译,SDK 首次下载可能需要较长时间。</p><pre>{logs.at(-1) ?? "等待编译器输出"}</pre><Button variant="danger" onClick={() => void cancelFlash()}>取消编译</Button></div>}
{error && <p className="mnt-error" role="alert">{error}</p>}
</Dialog>}
{modal === "details" && <Dialog title="诊断与日志" className="mnt-details" onClose={() => setModal(null)}><div className="mnt-tabs"><button className={detailsTab === "log" ? "is-active" : ""} onClick={() => setDetailsTab("log")}>运行日志</button><button className={detailsTab === "data" ? "is-active" : ""} onClick={() => setDetailsTab("data")}>设备 / 计划 / 报告</button></div><div className="mnt-details__scroll" role={detailsTab === "log" ? "log" : undefined}>{detailsTab === "log" ? <>{logs.map((line, index) => <pre key={index}>{line}</pre>)}{logs.length === 0 && <p>尚未执行操作</p>}<div ref={logEnd} /></> : <pre>{JSON.stringify({ device, bundle, plan, report }, null, 2)}</pre>}</div></Dialog>}
</main>;
}
+483
View File
@@ -0,0 +1,483 @@
/**
* 裁判端:两路画面 + 双方装甲条 + 装甲板发现列表 + 截图与录制。
*
* 布局的诉求与用户端不同:这里要**一眼比出两边的状态**,所以两格并排、血量各自贴在画面的
* 上角(左格左上、右格右上,与用户端的"自己在左上、对手在右上"是同一套读法)、缩放置互相
* 独立(滚轮只作用于鼠标所在的那一路)。
*
* 两格等宽这件事在旧客户端上是踩过坑的:`HorizontalLayout` 先按内容的**最大**需求分配,
* 剩下的才按 stretch 分。一格写着"已连接,等待画面…"(8 字),另一格只有"未收到画面"
* (5 字),于是左边多要十几个像素——实测 55% / 45%。解法是让两格的需求只由画面决定:
* 统一的 `preferred-width` 加 `min-width`,文字用绝对定位不参与布局。CSS 的 flex 里
* 用 `flex: 1 1 0` + `min-width: 0` 达到同一件事。
*
* # 这一页最顺手的操作是什么
*
* 裁判的手在鼠标上,而他反复做的是三件事:**比两边**、**看某一边**、**留下证据**。所以
* 这一页的交互不是"再开一个页面",而是让鼠标停在哪里,下面那块控制台就跟着看哪里:
*
* 1. **按下左边那一路**,下方列表立刻只显示这一队的装甲板;再按一次回到全部。这不是开关,
* 是"把注意力放过去",所以它不需要确认,也不需要记住。
* 2. **中间那条竖线可以拖**:谁的那一格更重要,就把它拉宽。双击回到五五开。
* 3. **画面与下方控制台之间的横线也能拖**:录回放的时候把播放器拉大,比双看见更多帧更要紧。
*
* 三件事都不用去找按钮,这就是这一页想要的"顺手"。
*
* # 队名可以直接改
*
* 名字属于这一场比赛,所以它放在两格画面各自下面(见 `TeamNameEditor`),改完立刻反映到
* 装甲条、装甲板表与等待画面的文字上。命令在 Rust 侧,规范化也在那边统一做。
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { ArmorTable, StatsLine } from "../components/ArmorTable";
import { HealthBar } from "../components/HealthBar";
import { HitFlash } from "../components/HitFlash";
import { MatchBanner } from "../components/MatchBanner";
import { RefereeMatchControl } from "../components/MatchClock";
import { MediaPanel } from "../components/MediaPanel";
import { StatusBar, Stat } from "../components/StatusBar";
import { TeamNameEditor } from "../components/TeamNameEditor";
import { IDENTITY_VIEW, VideoSurface, type ViewTransform } from "../components/VideoSurface";
import { clockTime, firmwareLabel, teamColor, teamName } from "../lib/format";
import { api } from "../lib/ipc";
import { useAppStore, type HitPulseRecord } from "../lib/store";
import type { HudView, Snapshot } from "../lib/types";
interface Props {
snapshot: Snapshot;
hud: HudView;
onOpenSettings: () => void;
onError: (message: string) => void;
onInfo: (message: string) => void;
}
/** 下方控制台的两个页签。 */
type Tab = "armor" | "media";
/** 下方控制台的观察范围:全部,或只看某一路。 */
type Scope = "all" | "a" | "b";
/** 中缝能让到多窄 / 多宽(百分比)。 */
const SPLIT_MIN = 26;
const SPLIT_MAX = 74;
/** 下方控制台的高度范围(像素)。 */
const CONSOLE_MIN = 132;
const CONSOLE_MAX_RATIO = 0.62;
export function RefereePage({ snapshot, hud, onOpenSettings, onError, onInfo }: Props) {
const { lastHit } = useAppStore();
const [tab, setTab] = useState<Tab>("armor");
const [scope, setScope] = useState<Scope>("all");
const [split, setSplit] = useState(50);
const [consoleHeight, setConsoleHeight] = useState(210);
// 两路各自独立的缩放与平移。
const [viewA, setViewA] = useState<ViewTransform>(IDENTITY_VIEW);
const [viewB, setViewB] = useState<ViewTransform>(IDENTITY_VIEW);
// 队名以快照为准(后端会规范化)。
const names = snapshot.config.teamNames;
const rootRef = useRef<HTMLDivElement | null>(null);
const stageRef = useRef<HTMLDivElement | null>(null);
const dragKind = useRef<"split" | "console" | null>(null);
const dragOrigin = useRef({ value: 0, pointer: 0 });
// 命中流水:最近三次,放在控制台头部。裁判在争执时需要的是"刚才谁掉了多少"。
const [ledger, setLedger] = useState<HitPulseRecord[]>([]);
useEffect(() => {
if (!lastHit) return;
setLedger((current) => [lastHit, ...current].slice(0, 3));
}, [lastHit]);
const panes = useMemo(
() =>
[
{
key: "a" as const,
camera: snapshot.slots.cameraA,
armor: snapshot.slots.armorA,
team: 0,
// 左格的血条贴左上角,右格贴右上角:与用户端"自己在左上、对手在右上"一致。
align: "left" as const,
view: viewA,
onView: setViewA,
},
{
key: "b" as const,
camera: snapshot.slots.cameraB,
armor: snapshot.slots.armorB,
team: 1,
align: "right" as const,
view: viewB,
onView: setViewB,
},
].map((pane) => ({
...pane,
stats: snapshot.stats.find((entry) => entry.camera === pane.camera),
health: snapshot.health.find((entry) => entry.team === pane.team) ?? snapshot.health[0],
opponent: snapshot.health.find((entry) => entry.team !== pane.team) ?? null,
cameraInfo: snapshot.cameras.find((entry) => entry.id === pane.camera) ?? null,
})),
[snapshot.slots, snapshot.stats, snapshot.health, viewA, viewB],
);
/**
* 改一边的队名。
*
* 命令一次只改一边,所以这里**不**把另一边的名字一起带上:那是"读两条、写两条",
* 而读来的值来自最多 200 ms 前的快照——紧接着改另一边就会把它覆盖回去。
*/
const saveName = (team: number, value: string) => {
void api.setTeamName(team, value).catch((err) => {
onError(err instanceof Error ? err.message : String(err));
});
};
// ---- 拖拽 ----
const beginDrag = (kind: "split" | "console") => (event: React.PointerEvent<HTMLElement>) => {
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
dragKind.current = kind;
dragOrigin.current = {
value: kind === "split" ? split : consoleHeight,
pointer: kind === "split" ? event.clientX : event.clientY,
};
};
const moveDrag = (event: React.PointerEvent<HTMLElement>) => {
const kind = dragKind.current;
if (!kind) return;
if (kind === "split") {
const box = stageRef.current?.getBoundingClientRect();
if (!box || box.width === 0) return;
const next = ((event.clientX - box.left) / box.width) * 100;
setSplit(Math.max(SPLIT_MIN, Math.min(SPLIT_MAX, next)));
return;
}
const height = rootRef.current?.clientHeight ?? window.innerHeight;
const max = Math.max(CONSOLE_MIN, height * CONSOLE_MAX_RATIO);
const next = dragOrigin.current.value - (event.clientY - dragOrigin.current.pointer);
setConsoleHeight(Math.max(CONSOLE_MIN, Math.min(max, next)));
};
const endDrag = () => {
dragKind.current = null;
};
// 键盘:1 / 2 把注意力放到某一路,0 收回全部。全屏看录像的人手不必离开键位。
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const target = event.target as HTMLElement | null;
if (
target?.tagName === "INPUT" ||
target?.tagName === "TEXTAREA" ||
target?.tagName === "SELECT" ||
event.ctrlKey ||
event.metaKey ||
event.altKey
) {
return;
}
if (event.key === "1") setScope((current) => (current === "a" ? "all" : "a"));
if (event.key === "2") setScope((current) => (current === "b" ? "all" : "b"));
if (event.key === "0") setScope("all");
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, []);
const focusTeam = scope === "a" ? 0 : scope === "b" ? 1 : null;
return (
<div className="ref" ref={rootRef}>
<RefereeMatchControl snapshot={snapshot} onError={onError} />
<div
className="ref__stage"
ref={stageRef}
style={{ ["--split" as string]: `${split}%` }}
>
{panes.map((pane, index) => {
// 这一下落在哪一格:指定了装甲板就比板子 id,否则退回比队伍号。
const hitRelevant = Boolean(
lastHit &&
(pane.armor !== null ? lastHit.board === pane.armor : lastHit.team === pane.team),
);
const label = teamName(pane.team, names);
const focused = scope === pane.key;
const dimmed = scope !== "all" && !focused;
return (
<section key={pane.key} className="ref__pane">
{index === 1 && (
<div
className="ref__splitter"
role="separator"
aria-orientation="vertical"
title="拖动调整两路画面宽度,双击恢复等宽"
onPointerDown={beginDrag("split")}
onPointerMove={moveDrag}
onPointerUp={endDrag}
onPointerCancel={endDrag}
onDoubleClick={() => setSplit(50)}
>
<span className="ref__splitter-grip" />
</div>
)}
<div className={`ref__feed${dimmed ? " is-dimmed" : ""}`}>
<VideoSurface
camera={pane.camera}
label={`${pane.key.toUpperCase()} · ${label}`}
emptyText={
pane.stats?.hasFrames
? ""
: pane.stats?.online
? "已连接,等待画面…"
: `等待${label}的图传`
}
mirrored={snapshot.mirrored}
// 裁判端不给瞄准器:这里没有人在瞄。网格留着,用来比对两路的取景。
crosshair={null}
grid={hud.grid}
view={pane.view}
onView={pane.onView}
hit={
hitRelevant && lastHit
? { seq: lastHit.seq, damage: lastHit.damage, at: lastHit.receivedAt }
: null
}
hitFeedback={hud.hitFeedback}
showZoom
focused={focused}
onSelect={() => setScope((current) => (current === pane.key ? "all" : pane.key))}
>
{hud.health.visible && pane.health && (
<div className={`ref__bar ref__bar--${pane.align}`}>
<HealthBar health={pane.health} config={hud.health} align={pane.align} />
</div>
)}
<MatchBanner
outcome={pane.health?.outcome ?? null}
mine={pane.health?.name ?? label}
theirs={pane.opponent?.name ?? teamName(pane.team === 0 ? 1 : 0, names)}
/>
<HitFlash
hit={lastHit}
config={hud.hitFeedback}
relevant={hitRelevant}
label={`${label}受到攻击`}
/>
</VideoSurface>
<div className="ref__foot">
<TeamNameEditor
team={pane.team}
name={pane.health?.name ?? label}
onSave={(value) => saveName(pane.team, value)}
/>
<StatsLine stats={pane.stats} diagnostics={snapshot.diagnostics} />
{pane.cameraInfo && (
<span
className={`ref__fw num${
pane.cameraInfo.compatible ? "" : " is-bad"
}`}
title={
pane.cameraInfo.compatible
? `固件 ${firmwareLabel(pane.cameraInfo)}`
: `固件 ${firmwareLabel(pane.cameraInfo)},协议 ${
pane.cameraInfo.protocol
} 与本客户端不符,画面会被丢弃`
}
>
{firmwareLabel(pane.cameraInfo)}
</span>
)}
</div>
</div>
</section>
);
})}
</div>
<div
className="ref__console-grip"
role="separator"
aria-orientation="horizontal"
title="拖动调整下方控制台的高度"
onPointerDown={beginDrag("console")}
onPointerMove={moveDrag}
onPointerUp={endDrag}
onPointerCancel={endDrag}
onDoubleClick={() => setConsoleHeight(210)}
>
<span className="ref__console-grip-bar" />
</div>
<div className="ref__console" style={{ height: consoleHeight }}>
<div className="ref__console-head">
<div className="seg ref__scope" style={{ ["--count" as string]: 3, ["--index" as string]: scope === "all" ? 0 : scope === "a" ? 1 : 2 }}>
<span className="seg__glider" aria-hidden="true" />
{(
[
{ key: "all", label: "全部", hint: "同时查看两路" },
{ key: "a", label: "左路", hint: "键 1" },
{ key: "b", label: "右路", hint: "键 2" },
] as const
).map((item) => (
<button
key={item.key}
type="button"
role="tab"
aria-selected={scope === item.key}
className="seg__item"
onClick={() => setScope(item.key)}
title={`观察范围:${item.hint}`}
>
<span
className="ref__scope-dot"
style={{ color: item.key === "all" ? "var(--ink-3)" : teamColor(item.key === "a" ? 0 : 1) }}
/>
{item.label}
</button>
))}
</div>
<div className="seg ref__tabs" style={{ ["--count" as string]: 2, ["--index" as string]: tab === "armor" ? 0 : 1 }}>
<span className="seg__glider" aria-hidden="true" />
<button
type="button"
role="tab"
aria-selected={tab === "armor"}
className="seg__item"
onClick={() => setTab("armor")}
>
装甲板
<span className="ref__count num">{snapshot.armorBoards.length}</span>
</button>
<button
type="button"
role="tab"
aria-selected={tab === "media"}
className="seg__item"
onClick={() => setTab("media")}
>
录制与回放
{snapshot.recordings.length > 0 && (
<span className="ref__count ref__count--live num">
{snapshot.recordings.length}
</span>
)}
</button>
</div>
<div className="ref__ledger" aria-live="off">
{ledger.length === 0 ? (
<span className="ref__ledger-empty label">NO HITS</span>
) : (
ledger.map((hit) => (
<span
key={hit.seq}
className="ref__ledger-item"
title={`${hit.board === null ? "" : `板 `}${hit.from} → ${hit.to}`}
>
<span
className="ref__ledger-team"
style={{ color: teamColor(hit.team) }}
>
{hit.team === 0 ? "A" : "B"}
</span>
<span className="num">−{hit.damage}</span>
<span className="ref__ledger-time num">{clockTime(hit.atMs)}</span>
</span>
))
)}
</div>
<span className="ref__spacer" />
<button
type="button"
className="btn btn--quiet"
onClick={() =>
void api
.refresh()
.catch((err) => onError(err instanceof Error ? err.message : String(err)))
}
>
刷新
</button>
<button type="button" className="btn btn--ghost" onClick={onOpenSettings}>
设置
</button>
</div>
<div className="ref__console-body">
{tab === "armor" ? (
<ArmorTable
boards={snapshot.armorBoards}
slots={snapshot.slots}
names={names}
focusTeam={focusTeam}
/>
) : (
<MediaPanel snapshot={snapshot} onError={onError} onInfo={onInfo} />
)}
</div>
</div>
<StatusBar
left={
<span className="statusbar__state">
<span className={`dot ${snapshot.clients > 0 ? "dot--live" : "dot--warn"}`} />
同时查看两路画面 · 滚轮缩放鼠标所在的画面
</span>
}
center={
<>
{panes.map((pane) => (
<Stat
key={pane.key}
label={pane.key.toUpperCase()}
value={
pane.stats
? pane.stats.hasFrames
? `${pane.stats.fps.toFixed(1)} fps`
: pane.stats.online
? "无信号"
: "离线"
: "未分配"
}
tone={
pane.stats
? pane.stats.hasFrames
? "plain"
: pane.stats.online
? "warn"
: "bad"
: "bad"
}
/>
))}
</>
}
right={
<span className="statusbar__hint">
{scope === "all" ? "按 1 / 2 查看单路" : `正在看 ${scope === "a" ? "左路" : "右路"} · 按 0 显示全部`}
</span>
}
/>
</div>
);
}
+79
View File
@@ -0,0 +1,79 @@
/** 用户端保留取景画面、血量和链路读数;调整入口统一放在 ESC 菜单。 */
import { useState } from "react";
import { IDENTITY_VIEW, VideoSurface, type ViewTransform } from "../components/VideoSurface";
import { HealthBar, healthTag } from "../components/HealthBar";
import { HitFlash } from "../components/HitFlash";
import { MatchBanner } from "../components/MatchBanner";
import { TeamMatchClock, TeamMatchCountdown } from "../components/MatchClock";
import { firmwareLabel, teamName, idText } from "../lib/format";
import { useAppStore } from "../lib/store";
import { BUILD } from "../lib/version";
import type { HudView, Snapshot } from "../lib/types";
interface Props {
snapshot: Snapshot;
hud: HudView;
calibrating: boolean;
onCalibrate: (dxFraction: number, dyFraction: number) => void;
}
export function TeamPage({ snapshot, hud, calibrating, onCalibrate }: Props) {
const [view, setView] = useState<ViewTransform>(IDENTITY_VIEW);
const { lastHit, connected } = useAppStore();
const camera = snapshot.config.cameraId;
const stats = snapshot.stats.find(entry => entry.camera === camera);
const boundCamera = snapshot.cameras.find(entry => entry.id === camera);
const board = snapshot.armorBoards.find(entry => entry.id === snapshot.config.armorId);
const mine = snapshot.health.find(entry => entry.team === snapshot.team) ?? null;
const theirs = snapshot.health.find(entry => entry.team !== snapshot.team) ?? null;
const myName = mine?.name ?? teamName(snapshot.team, snapshot.config.teamNames);
const theirName = theirs?.name ?? teamName(snapshot.team === 0 ? 1 : 0, snapshot.config.teamNames);
const cameraLive = connected && !!boundCamera?.online && !!stats?.online && boundCamera.compatible;
const armorLive = connected && !!board?.online && board.team === snapshot.team;
const cameraState = camera === null ? "未绑定" : !connected ? "服务断开" : boundCamera && !boundCamera.compatible ? "协议不匹配" : cameraLive ? (stats?.hasFrames ? "接收中" : "等待画面") : "离线";
const armorState = snapshot.config.armorId === null ? "未绑定" : !connected ? "服务断开" : board?.team === 255 ? "等待队伍设置" : board && board.team !== snapshot.team ? "队伍不符" : armorLive ? "在线" : "离线";
const hitIsMine = Boolean(lastHit && (mine?.board != null ? lastHit.board === mine.board : lastHit.team === snapshot.team));
const pulse = hitIsMine && lastHit ? { seq: lastHit.seq, damage: lastHit.damage, at: lastHit.receivedAt } : null;
// 两侧各自使用独立列;放大血条也不能跨过中线压住对方。
const healthConfig = { ...hud.health, width: Math.min(1, hud.health.width * 2) };
const hasVideo = cameraLive && !!stats?.hasFrames;
const emptyText = camera === null ? "未绑定图传板 · 按 ESC 配置"
: !connected ? "本机服务断开,正在重连"
: !boundCamera ? "尚未发现绑定的图传板 · 按 ESC 检查设备"
: !boundCamera.compatible ? "图传协议不匹配 · 按 ESC 检查固件"
: !cameraLive ? "图传板离线,等待重新连接"
: !stats?.hasFrames ? "已连接,等待画面" : "";
return <div className="op cockpit">
<div className="op__stage">
<VideoSurface camera={camera} label="" emptyText={emptyText} signalLost={!hasVideo}
mirrored={snapshot.mirrored} crosshair={hasVideo ? hud.crosshair : null} grid={hasVideo ? hud.grid : null} view={view} onView={setView}
calibrating={calibrating} onCalibrate={calibrating ? onCalibrate : undefined} hit={pulse} hitFeedback={hud.hitFeedback} showZoom={hud.showZoom} showResetControl={false}>
<div className="cockpit__overlay">
<div className="cockpit__health">
{hud.health.visible && mine && <div className="cockpit__health-side"><HealthBar health={mine} config={healthConfig} align="left" tag={healthTag(mine, snapshot.team)} /></div>}
<TeamMatchClock snapshot={snapshot} />
{hud.health.visible && theirs && <div className="cockpit__health-side cockpit__health-side--right"><HealthBar health={theirs} config={healthConfig} align="right" tag={healthTag(theirs, snapshot.team)} /></div>}
</div>
<div className="cockpit__header">
<div className="cockpit__identity"><span className="label">RMIC / OPERATOR</span><span title={myName}>{myName}</span>{snapshot.demo && <b>演示 · 合成数据</b>}</div>
<div className="cockpit__links" aria-label="连接状态">
<span className={cameraLive ? "is-live" : "is-offline"}><i />图传 <b>{cameraState}</b></span>
<span className={armorLive ? "is-live" : "is-offline"}><i />装甲板 <b>{armorState}</b></span>
</div>
</div>
<div className="cockpit__frame" aria-hidden="true"><i /><i /><i /><i /></div>
<div className="cockpit__telemetry">
<div className="cockpit__feed"><span className="label">VIDEO SOURCE</span><strong className="num">{camera === null ? "NO BINDING" : boundCamera?.idText ?? idText(camera)}</strong><span>{cameraLive && stats?.hasFrames ? `${stats.width} × ${stats.height}${snapshot.mirrored ? " / 镜像" : ""}` : "等待图传连接"}</span></div>
<div className="cockpit__fps"><span className="label">RECEIVE / FPS</span><strong className="num">{cameraLive && stats?.hasFrames ? stats.fps.toFixed(1) : "—"}</strong>{hud.showStats && snapshot.diagnostics && <span>丢包 {cameraLive && stats?.hasFrames ? `${stats.lossPercent.toFixed(1)}%` : "—"}</span>}</div>
</div>
<div className="cockpit__footer"><span><kbd>ESC</kbd> 菜单 / 设置</span><span className="num">{calibrating ? "瞄准校准中" : hud.showZoom ? `OPTICAL ×${view.zoom.toFixed(1)}` : ""}</span><span>{snapshot.config.armorId === null ? "ARMOR / —" : `ARMOR / ${board?.idText ?? idText(snapshot.config.armorId)}`}</span></div>
</div>
<MatchBanner outcome={mine?.outcome ?? null} mine={myName} theirs={theirName} detail={mine?.outcome === "defeat" && theirs?.hp != null ? `对手剩余 ${theirs.hp}` : mine?.outcome === "victory" && mine?.hp != null ? `剩余 ${mine.hp}` : undefined} />
<HitFlash hit={lastHit} config={hud.hitFeedback} relevant={hitIsMine} />
<TeamMatchCountdown snapshot={snapshot} />
{boundCamera && !boundCamera.compatible && <div className="fwfault" role="alert"><span className="fwfault__tag label">协议不匹配</span><span className="fwfault__text">图传固件 {firmwareLabel(boundCamera)} · 协议 {boundCamera.protocol} / 客户端 {BUILD.protocol}。按 ESC 进入固件维护。</span></div>}
</VideoSurface>
</div>
</div>;
}
+811
View File
@@ -0,0 +1,811 @@
/* 基础层:复位、排版默认值,以及全站复用的最小控件。
*
* 这里只放"到处都在用、且长得完全一样"的东西:切角面板、按钮、标签、输入、开关、滑杆、
* 分段控件、细线尺。某一页独有的排布一律写进该页的样式文件,免得这一份又长成第二个
* global.css。
*/
/* ──────────────────────────────────────────────────────────────── 复位 */
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
--control-height: 32px;
background: var(--void);
color: var(--ink);
font-family: var(--font-ui);
font-size: var(--fs-12);
line-height: 1.5;
letter-spacing: var(--track-tight);
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
overflow: hidden;
/* 这是一个给现场看的仪表:选中文字几乎只会是误触。需要复制的地方(日志、地址)
自己把 user-select 打开。 */
user-select: none;
cursor: default;
}
h1,
h2,
h3,
h4,
p {
margin: 0;
}
button {
font: inherit;
color: inherit;
background: none;
border: none;
padding: 0;
cursor: pointer;
}
input,
select,
textarea {
font: inherit;
color: inherit;
}
code,
kbd {
font-family: var(--font-mono);
font-size: 0.95em;
}
::selection {
background: var(--primary);
color: #0a0203;
}
/* 滚动条:细、暗、悬停才亮。滚动条完全不画会让人以为日志只有一屏。 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--line-2);
border: 2px solid transparent;
background-clip: padding-box;
}
::-webkit-scrollbar-thumb:hover {
background: var(--line-3);
background-clip: padding-box;
}
/* ──────────────────────────────────────────────────────────── 排版工具 */
/* 读数:等宽 + 等宽数字。`tabular-nums` 是关键——列里数字跳动时不能左右抖。 */
.num {
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
font-feature-settings: "tnum" 1;
}
/* 微标签:全大写、宽字距、暗。只放代号,不放句子。 */
.label {
font-family: var(--font-mono);
font-size: var(--fs-10);
line-height: 1;
letter-spacing: var(--track-wide);
text-transform: uppercase;
color: var(--ink-3);
}
.dim {
color: var(--ink-2);
}
.faint {
color: var(--ink-3);
}
.hot {
color: var(--primary);
}
.warn {
color: var(--warn);
}
.danger {
color: var(--error);
}
.ok {
color: var(--ok);
}
.link {
color: var(--ink);
}
/* 正文里要点出来的词。JSX 里的 `**` 不会被渲染成粗体,它会原样显示——那不该出现在
现场的屏幕上,所以强调一律走这个类。 */
.em {
color: var(--ink);
font-weight: 500;
}
/* 状态点:一颗 5px 的方块。它是全站唯一表示"某物在线/在跑"的记号。 */
.dot {
display: inline-block;
flex: none;
width: 5px;
height: 5px;
background: currentColor;
}
.dot--live {
color: var(--ok);
box-shadow: 0 0 0 2px rgba(63, 201, 138, 0.18);
animation: dot-breathe 2.4s var(--e-hud) infinite;
}
.dot--warn {
color: var(--warn);
}
.dot--dead {
color: var(--ink-4);
}
@keyframes dot-breathe {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.42;
}
}
/* ──────────────────────────────────────────────────────────── 面板 */
/* 全站唯一的"卡片":一个矩形,一圈 1px 线。没有切角、没有圆角、没有阴影。
*
* 形状上的克制是刻意的——这套界面里"斜的"只允许出现在一处,就是装甲条(平行四边形),
* 因为它要在满屏斜线与矩形里被一眼认成"这是血,不是别的东西"。别的元素一旦也开始切角,
* 那个形状就不再携带信息了。 */
.plate {
--plate-bg: var(--panel);
--plate-line: var(--line-2);
position: relative;
background: var(--plate-bg);
border: 1px solid var(--plate-line);
}
/* 四角定位括号。只在"被框住的东西"上用:取景器、结算、预览窗。 */
.corners {
position: relative;
}
.corners::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
--c: var(--line-3);
--l: 14px;
background:
linear-gradient(var(--c), var(--c)) left top / var(--l) 1px no-repeat,
linear-gradient(var(--c), var(--c)) left top / 1px var(--l) no-repeat,
linear-gradient(var(--c), var(--c)) right top / var(--l) 1px no-repeat,
linear-gradient(var(--c), var(--c)) right top / 1px var(--l) no-repeat,
linear-gradient(var(--c), var(--c)) left bottom / var(--l) 1px no-repeat,
linear-gradient(var(--c), var(--c)) left bottom / 1px var(--l) no-repeat,
linear-gradient(var(--c), var(--c)) right bottom / var(--l) 1px no-repeat,
linear-gradient(var(--c), var(--c)) right bottom / 1px var(--l) no-repeat;
}
/* 细分隔线:一排 1px 短刻线。用于"这里换了一组读数",比实线轻,比留白明确。 */
.rule {
height: 3px;
background-image: linear-gradient(90deg, var(--line-2) 0 5px, transparent 5px 9px);
background-size: 9px 1px;
background-repeat: repeat-x;
background-position: 0 1px;
}
/* ─────────────────────────────────────────────────────────────── 按钮 */
.btn {
--btn-line: var(--line-2);
--btn-bg: var(--panel-2);
--btn-ink: var(--ink);
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--s2);
flex: none;
height: var(--control-height);
padding: 0 var(--s3);
border: 1px solid var(--btn-line);
background: var(--btn-bg);
color: var(--btn-ink);
font-size: var(--fs-11);
letter-spacing: var(--track);
white-space: nowrap;
transition:
color var(--dur-short3) var(--m3-standard),
border-color var(--dur-short3) var(--m3-standard),
background-color var(--dur-short3) var(--m3-standard);
}
/* M3 状态层:悬停、键盘聚焦和按下只改变覆盖透明度,不推动相邻控件。 */
.btn::after {
content: "";
position: absolute;
inset: 0;
background: currentColor;
opacity: 0;
transition: opacity var(--dur-short3) var(--m3-standard);
pointer-events: none;
}
.btn:hover:not(:disabled)::after {
opacity: .08;
}
.btn:active:not(:disabled)::after,
.btn:focus-visible::after {
opacity: .12;
}
.btn:focus-visible,
.seg__item:focus-visible,
.tag--button:focus-visible {
outline: 2px solid var(--primary);
outline-offset: 2px;
}
.btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.btn--primary {
--btn-line: var(--primary-line);
--btn-bg: var(--primary-soft);
--btn-ink: var(--primary-hi);
}
.btn--primary:hover:not(:disabled) {
--btn-line: var(--primary);
}
.btn--danger {
--btn-line: var(--error-line);
--btn-bg: rgba(255, 84, 73, 0.1);
--btn-ink: var(--error);
}
.btn--ghost {
--btn-bg: transparent;
--btn-ink: var(--ink-2);
}
.btn--ghost:hover:not(:disabled) {
--btn-ink: var(--ink);
--btn-line: var(--line-3);
}
.btn--quiet {
--btn-bg: transparent;
--btn-line: transparent;
--btn-ink: var(--ink-3);
}
.btn--quiet:hover:not(:disabled) {
--btn-ink: var(--primary);
}
.btn--lg {
height: calc(var(--control-height) + 4px);
padding: 0 var(--s4);
font-size: var(--fs-12);
}
.btn[aria-pressed="true"] {
--btn-line: var(--line-hot);
--btn-ink: var(--primary-hi);
}
/* ─────────────────────────────────────────────────────────────── 标签 */
.tag {
display: inline-flex;
align-items: center;
gap: 5px;
height: 18px;
padding: 0 6px;
border: 1px solid var(--line-2);
color: var(--ink-2);
font-family: var(--font-mono);
font-size: var(--fs-10);
letter-spacing: var(--track);
text-transform: uppercase;
white-space: nowrap;
}
.tag--hot {
color: var(--primary-hi);
border-color: var(--primary-line);
background: var(--primary-soft);
}
.tag--danger {
color: var(--error);
border-color: var(--error-line);
background: var(--error-soft);
}
.tag--warn {
color: var(--warn);
border-color: var(--warn-line);
background: var(--warn-soft);
}
.tag--ok {
color: var(--ok);
border-color: var(--ok-line);
background: var(--ok-soft);
}
.tag--link {
color: var(--ink);
border-color: var(--line-3);
background: var(--primary-soft);
}
.tag--team-0 {
color: var(--team-0);
border-color: rgba(255, 107, 94, 0.44);
background: var(--team-0-soft);
}
.tag--team-1 {
color: var(--team-1);
border-color: rgba(74, 155, 255, 0.44);
background: var(--team-1-soft);
}
/* 能点的标签(演示模式、说明)。悬停给一条下划线,不改变尺寸。 */
.tag--button {
cursor: pointer;
border-style: dashed;
}
.tag--button:hover {
border-style: solid;
color: var(--ink);
}
/* ────────────────────────────────────────────────────── 输入与下拉 */
.input,
.select {
width: 100%;
min-width: 0;
height: var(--control-height);
padding: 0 var(--s2);
background: var(--deep);
border: 1px solid var(--line-2);
color: var(--ink);
font-family: var(--font-mono);
font-size: var(--fs-12);
letter-spacing: var(--track-tight);
outline: none;
transition:
border-color var(--dur-short3) var(--m3-standard),
background-color var(--dur-short3) var(--m3-standard),
box-shadow var(--dur-short3) var(--m3-standard);
}
/* 输入、选择与按钮共享同一焦点色;外沿不改变控件尺寸。 */
.input:focus,
.select:focus {
border-color: var(--primary);
background-color: var(--deep);
box-shadow: 0 0 0 1px var(--primary);
}
.input:hover:not(:disabled):not(:focus),
.select:hover:not(:disabled):not(:focus) {
border-color: var(--line-3);
}
/* WebView 会在密码框右侧画一个"显示密码"的小眼睛。它不是这个界面的一部分,
而且在现场等于一键把密码亮给旁边的人看。去掉。 */
.input::-ms-reveal,
.input::-ms-clear {
display: none;
}
.input::-webkit-credentials-auto-fill-button,
.input::-webkit-contacts-auto-fill-button {
visibility: hidden;
display: none !important;
pointer-events: none;
}
.input::placeholder {
color: var(--ink-4);
}
/* 确认框在设置和固件页共用轮廓、状态层与键盘焦点。 */
input[type="checkbox"]:not(.switch input) {
appearance: none;
display: inline-grid;
place-content: center;
width: 16px;
height: 16px;
border: 1px solid var(--line-3);
border-radius: var(--radius);
background: var(--deep);
cursor: pointer;
transition: background-color var(--dur-short3) var(--m3-standard), border-color var(--dur-short3) var(--m3-standard);
}
input[type="checkbox"]:not(.switch input)::before {
content: "";
width: 8px;
height: 5px;
border: solid var(--ink);
border-width: 0 0 2px 2px;
transform: translateY(-1px) rotate(-45deg);
opacity: 0;
transition: opacity var(--dur-short3) var(--m3-standard);
}
input[type="checkbox"]:not(.switch input):checked {
background: var(--primary-soft);
border-color: var(--primary);
}
input[type="checkbox"]:not(.switch input):checked::before { opacity: 1; }
input[type="checkbox"]:not(.switch input):hover:not(:disabled) { border-color: var(--ink-2); }
input[type="checkbox"]:not(.switch input):focus-visible { outline: 2px solid var(--primary); outline-offset: 3px; }
input[type="checkbox"]:disabled { cursor: not-allowed; opacity: .4; }
.input:disabled,
.select:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.select {
appearance: none;
padding-right: 24px;
cursor: pointer;
background-image: linear-gradient(45deg, transparent 50%, var(--ink-3) 50%),
linear-gradient(135deg, var(--ink-3) 50%, transparent 50%);
background-position: calc(100% - 12px) 50%, calc(100% - 8px) 50%;
background-size: 4px 4px, 4px 4px;
background-repeat: no-repeat;
}
.select option {
background: var(--panel);
color: var(--ink);
}
/* ─────────────────────────────────────────────────────────────── 开关 */
/* 二值控件沿用矩形轮廓,选中、聚焦与按压遵循同一状态层。 */
.switch {
position: relative;
display: flex;
align-items: center;
gap: var(--s2);
min-height: var(--control-height);
cursor: pointer;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch__track {
position: relative;
flex: none;
width: 32px;
height: 16px;
border: 1px solid var(--line-2);
background: var(--deep);
transition:
background-color var(--dur-short3) var(--m3-standard),
border-color var(--dur-short3) var(--m3-standard);
}
.switch__knob {
position: absolute;
top: 2px;
left: 2px;
width: 10px;
height: 10px;
background: var(--ink-4);
transition:
transform var(--dur-short4) var(--m3-standard),
background-color var(--dur-short3) var(--m3-standard);
}
.switch__label {
font-size: var(--fs-12);
color: var(--ink-2);
transition: color var(--dur-short3) var(--m3-standard);
}
.switch:not(.switch--disabled):hover .switch__label {
color: var(--ink);
}
.switch:not(.switch--disabled):hover .switch__track {
border-color: var(--line-3);
}
.switch input:checked + .switch__track {
border-color: var(--primary-line);
background: var(--primary-soft);
}
.switch input:checked + .switch__track .switch__knob {
transform: translateX(16px);
background: var(--primary-hi);
}
.switch input:checked ~ .switch__label {
color: var(--ink);
}
.switch input:focus-visible + .switch__track {
outline: 2px solid var(--primary);
outline-offset: 3px;
}
.switch--disabled {
opacity: 0.4;
cursor: not-allowed;
}
/* ─────────────────────────────────────────────────────────────── 滑杆 */
/* 轨道用 `--fill` 区分已选范围;按压和键盘操作以强调色标明当前滑块。 */
.slider {
display: flex;
align-items: center;
gap: var(--s2);
width: 100%;
min-width: 0;
}
.slider input[type="range"] {
--fill: 0%;
appearance: none;
flex: 1;
min-width: 0;
margin: 0;
height: var(--control-height);
background: transparent;
outline: none;
cursor: ew-resize;
}
.slider input[type="range"]::-webkit-slider-runnable-track {
height: 2px;
background: linear-gradient(
to right,
var(--ink-2) 0 var(--fill),
var(--line-2) var(--fill) 100%
);
}
.slider input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 8px;
height: 16px;
margin-top: -7px;
background: var(--ink);
border: none;
transition:
background-color var(--dur-short3) var(--m3-standard),
box-shadow var(--dur-short3) var(--m3-standard);
}
.slider input[type="range"]:hover:not(:disabled)::-webkit-slider-thumb {
box-shadow: 0 0 0 5px var(--primary-soft);
}
.slider input[type="range"]:focus-visible::-webkit-slider-thumb,
.slider input[type="range"]:active::-webkit-slider-thumb {
background: var(--primary);
box-shadow: 0 0 0 5px var(--primary-soft);
}
.slider input[type="range"]:focus-visible {
outline: 2px solid var(--primary);
outline-offset: 2px;
}
.slider input[type="range"]:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.slider__value {
flex: none;
min-width: 56px;
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
font-size: var(--fs-11);
color: var(--ink-2);
text-align: right;
}
/* ────────────────────────────────────────────────────── 分段控件 */
/* 一排互斥选项。选中的记号是**底沿一条会滑动的 2px 线**(`--index` 决定它停在哪),
不是整块红底:一组按钮里只该有一个地方被染色,而"我在哪一组"这条信息由位置本身说。 */
.seg {
position: relative;
display: inline-flex;
align-items: stretch;
border-bottom: 1px solid var(--line-2);
}
.seg__glider {
position: absolute;
left: 0;
bottom: -1px;
height: 2px;
width: calc(100% / var(--count, 1));
background: var(--primary);
transform: translateX(calc(100% * var(--index, 0)));
transition: transform var(--dur-medium2) var(--m3-emphasized);
pointer-events: none;
}
.seg__item {
position: relative;
z-index: 1;
flex: 1 1 0;
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--s2);
min-height: var(--control-height);
padding: 0 var(--s3);
font-family: var(--font-mono);
font-size: var(--fs-11);
letter-spacing: var(--track);
color: var(--ink-3);
white-space: nowrap;
transition: color var(--dur-short3) var(--m3-standard), background-color var(--dur-short3) var(--m3-standard);
}
.seg__item:hover {
color: var(--ink-2);
background: var(--panel-2);
}
.seg__item[aria-selected="true"] {
color: var(--ink);
}
/* ─────────────────────────────────────────────────────────────── 读数 */
/* 一条"标签 —— 值"的对齐行。值靠右、等宽、可换行(长的路径要能折)。 */
.readout {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--s3);
padding: 3px 0;
font-size: var(--fs-11);
}
.readout__label {
flex: none;
color: var(--ink-3);
letter-spacing: var(--track);
}
.readout__value {
min-width: 0;
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
color: var(--ink);
text-align: right;
overflow-wrap: anywhere;
}
/* ──────────────────────────────────────────────────────────────── 字段 */
.field {
display: grid;
grid-template-columns: 128px minmax(0, 1fr);
gap: var(--s1) var(--s3);
align-items: center;
}
.field__label {
font-size: var(--fs-11);
color: var(--ink-2);
letter-spacing: var(--track-tight);
}
.field__control {
min-width: 0;
display: flex;
align-items: center;
}
.field__hint {
grid-column: 2;
font-family: var(--font-mono);
font-size: var(--fs-10);
color: var(--ink-4);
letter-spacing: var(--track-tight);
}
/* ──────────────────────────────────────────────────────── 加载指示 */
/* 进行中的任务使用匀速指示,表示等待,不表示实际百分比。 */
.scan {
position: relative;
overflow: hidden;
height: 1px;
background: var(--line);
}
.scan::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
width: 34%;
background: linear-gradient(90deg, transparent, var(--primary), transparent);
animation: scan-run 1.4s linear infinite;
}
@keyframes scan-run {
from {
transform: translateX(-100%);
}
to {
transform: translateX(320%);
}
}
/* 骨架方块:还没拿到数据时的占位。它不闪,只是比周围暗一档。 */
.skeleton {
background: var(--panel-2);
height: 8px;
}
@media (prefers-reduced-motion: reduce) {
.scan::after, .dot--live { animation: none; }
}
File diff suppressed because it is too large. Load diff
+573
View File
@@ -0,0 +1,573 @@
/* 控制台:装甲板表、录制与回放、队伍名。
*
* 这些是"低头看"的东西,所以它们可以密、可以有刻度和线——画面那一层不可以。
*/
/* ───────────────────────────────────────────────────── 装甲板列表 */
.armor {
display: flex;
flex-direction: column;
min-width: 0;
}
/* 七列的宽度是固定的,除了最后一列(槽位)用剩余空间。定宽的意义在于:血量从 100 变成
7 时,后面的列不许挪位——那样每掉一次血整张表都会抖一下。 */
.armor__head,
.armor__row {
display: grid;
/* 地址列按内容吃掉自己的宽度,剩下的全给"槽位"——否则长窗口下中间会空出一大片,
而真正需要横向余量的槽位说明被挤成一截。 */
grid-template-columns:
46px 118px minmax(110px, max-content) 118px
132px 104px minmax(96px, 1fr);
gap: var(--s2);
align-items: center;
padding: 0 var(--s2);
}
.armor__head {
height: 22px;
border-bottom: 1px solid var(--line-2);
}
.armor__col {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.armor__head .armor__col {
font-family: var(--font-mono);
font-size: var(--fs-9);
letter-spacing: var(--track-wide);
color: var(--ink-4);
}
.armor__rows {
display: flex;
flex-direction: column;
}
.armor__row {
height: 26px;
border-bottom: 1px solid var(--line);
font-size: var(--fs-11);
transition: background-color var(--d-2) var(--e-out);
}
.armor__row:hover {
background: var(--panel-2);
}
.armor__row.is-offline {
opacity: 0.45;
}
.armor__row.is-unassigned .armor__slot {
color: var(--ink-4);
}
/* 四条上报的位图。它一眼回答"这块板子是不是只在报一条"。 */
.armor__plates {
display: inline-flex;
gap: 2px;
align-items: center;
}
.armor__plate {
width: 6px;
height: 10px;
background: var(--line-2);
transition: background-color var(--d-2) var(--e-out);
}
.armor__plate.is-on {
background: var(--ink-2);
}
.armor__id {
color: var(--ink);
letter-spacing: var(--track-tight);
}
.armor__addr {
color: var(--ink-3);
font-size: var(--fs-10);
}
.armor__team-bit {
margin-left: 6px;
padding: 0 4px;
border: 1px solid currentColor;
font-size: var(--fs-9);
opacity: 0.6;
}
.armor__col--hp {
display: flex;
align-items: center;
gap: var(--s2);
}
.armor__hp {
flex: none;
min-width: 26px;
color: var(--ink);
font-size: var(--fs-12);
}
.armor__hp.is-dead {
color: var(--error);
}
.armor__hp-track {
flex: 1;
min-width: 0;
height: 3px;
background: var(--line-2);
overflow: hidden;
}
.armor__hp-fill {
display: block;
height: 100%;
transition: width var(--d-3) var(--e-out);
}
.armor__silence {
display: inline-flex;
align-items: center;
gap: 5px;
font-family: var(--font-mono);
font-size: var(--fs-10);
}
.armor__silence.is-good {
color: var(--ink-2);
}
.armor__silence.is-warn {
color: var(--warn);
}
.armor__silence.is-bad {
color: var(--error);
}
.armor__slot {
color: var(--ink-2);
font-size: var(--fs-10);
}
.armor__empty {
padding: var(--s4) var(--s2);
max-width: 620px;
color: var(--ink-3);
font-size: var(--fs-11);
line-height: 1.8;
}
.armor__empty kbd {
padding: 0 4px;
border: 1px solid var(--line-3);
color: var(--ink-2);
font-size: var(--fs-10);
}
/* ───────────────────────────────────────────────────── 帧率读数行 */
.statsline {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
font-size: var(--fs-10);
color: var(--ink-2);
white-space: nowrap;
overflow: hidden;
}
.statsline.is-offline {
color: var(--warn);
}
.statsline--empty {
color: var(--ink-4);
}
.statsline__status {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.statsline__sep {
width: 1px;
height: 9px;
background: var(--line-2);
flex: none;
}
.statsline__nums {
color: var(--ink-3);
font-size: var(--fs-10);
}
/* ───────────────────────────────────────────────────────── 队名 */
/* 静止时它是一条读数:一个队色方块 + 一个看着像文本的值。
点进去才展开边框、键位提示与字数。两格画面下面不该永远趴着两个表单控件。 */
.tname {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
flex: 0 1 auto;
padding: 2px 4px 2px 0;
border: 1px solid transparent;
transition: border-color var(--d-2) var(--e-out);
}
.tname.is-editing {
border-color: var(--line-3);
background: var(--deep);
}
.tname.is-disabled {
opacity: 0.5;
}
.tname__label {
flex: none;
width: 16px;
height: 16px;
display: inline-flex;
align-items: center;
justify-content: center;
font-family: var(--font-mono);
font-size: var(--fs-10);
font-weight: 700;
border: 1px solid currentColor;
line-height: 1;
}
.tname__input {
flex: 1;
min-width: 60px;
max-width: 150px;
padding: 1px 2px;
background: transparent;
border: none;
border-bottom: 1px dashed var(--line-2);
color: var(--ink);
font-size: var(--fs-12);
outline: none;
transition: border-color var(--d-2) var(--e-out);
}
.tname__input:hover:not(:disabled) {
border-bottom-color: var(--line-3);
}
.tname.is-editing .tname__input {
border-bottom: 1px solid var(--primary);
}
.tname__input::placeholder {
color: var(--ink-4);
}
/* 提示只在编辑时出现:平时它会把这一行撑宽,而这一行要装帧率。 */
.tname__hint {
display: none;
align-items: center;
gap: var(--s2);
flex: none;
}
.tname.is-editing .tname__hint {
display: flex;
}
.tname__keys {
font-size: var(--fs-9);
color: var(--ink-4);
letter-spacing: var(--track-tight);
}
.tname__keys kbd {
padding: 0 3px;
margin-right: 1px;
border: 1px solid var(--line-2);
color: var(--ink-3);
font-size: var(--fs-9);
}
.tname__count {
font-size: var(--fs-9);
color: var(--ink-4);
}
/* ─────────────────────────────────────────────────── 录制与回放 */
.media {
display: flex;
flex-direction: column;
gap: var(--s2);
min-width: 0;
}
.media__actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--s2);
}
.media__rec-glyph {
width: 7px;
height: 7px;
background: currentColor;
}
.media__divider {
width: 1px;
height: 16px;
background: var(--line-2);
margin: 0 var(--s1);
}
.media__cam {
font-size: var(--fs-9);
color: var(--ink-3);
}
.media__spacer {
flex: 1;
}
/* —— 录制中的横条 —— */
.media__strips {
display: flex;
flex-direction: column;
gap: 3px;
}
.strip {
display: flex;
align-items: center;
gap: var(--s2);
padding: 4px var(--s2);
background: rgba(255, 84, 73, 0.08);
border: 1px solid var(--error-line);
border-left-width: 2px;
font-size: var(--fs-11);
}
.strip__pulse {
width: 6px;
height: 6px;
background: var(--error);
animation: rec-blink 1.1s steps(2, start) infinite;
}
.strip__label {
color: var(--error);
}
.strip__cam {
color: var(--ink);
font-size: var(--fs-10);
}
.strip__stats {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--ink-2);
font-size: var(--fs-10);
}
.strip__dot {
width: 2px;
height: 2px;
background: var(--ink-4);
}
.strip__warn {
color: var(--warn);
font-size: var(--fs-10);
}
.strip__error {
color: var(--error);
font-size: var(--fs-10);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.strip > .btn {
margin-left: auto;
height: 22px;
}
/* —— 文件列表 —— */
.media__list {
display: flex;
flex-direction: column;
min-width: 0;
}
.media__head,
.media__row {
display: grid;
grid-template-columns: 52px minmax(0, 1fr) 88px 116px;
gap: var(--s2);
align-items: center;
padding: 0 var(--s2);
}
.media__head {
height: 22px;
border-bottom: 1px solid var(--line-2);
}
.media__head .media__col {
font-family: var(--font-mono);
font-size: var(--fs-9);
letter-spacing: var(--track-wide);
color: var(--ink-4);
}
.media__row {
height: 26px;
border-bottom: 1px solid var(--line);
font-size: var(--fs-11);
transition: background-color var(--d-2) var(--e-out);
}
.media__row:hover {
background: var(--panel-2);
}
.media__col {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.media__col--size {
color: var(--ink-3);
font-size: var(--fs-10);
text-align: right;
}
.media__col--acts {
display: flex;
justify-content: flex-end;
gap: 2px;
}
.media__col--acts .btn {
height: 20px;
padding: 0 6px;
font-size: var(--fs-10);
}
.media__kind {
display: inline-block;
padding: 1px 5px;
border: 1px solid var(--line-3);
font-family: var(--font-mono);
font-size: var(--fs-9);
letter-spacing: var(--track);
color: var(--ink-3);
}
.media__kind--video {
color: var(--ink);
border-color: var(--line-3);
}
.media__kind--image {
color: var(--ink-2);
}
.media__name {
color: var(--ink);
font-family: var(--font-mono);
font-size: var(--fs-10);
}
.media__empty {
padding: var(--s4) var(--s2);
color: var(--ink-3);
font-size: var(--fs-11);
}
/* —— 播放器 —— */
.playback {
margin-top: var(--s1);
border: 1px solid var(--line-2);
background: #000;
}
.playback__head {
display: flex;
align-items: center;
gap: var(--s2);
padding: 4px var(--s2);
background: var(--panel-2);
border-bottom: 1px solid var(--line-2);
}
.playback__label {
color: var(--primary);
}
.playback__name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--fs-10);
color: var(--ink-2);
}
.playback__spacer {
flex: 1;
}
.playback__head .btn {
height: 20px;
}
.playback__video {
display: block;
width: 100%;
max-height: 300px;
background: #000;
}
.playback__fallback {
display: flex;
flex-direction: column;
gap: var(--s3);
align-items: flex-start;
padding: var(--s3);
background: var(--panel);
}
.playback__warn {
color: var(--warn);
font-size: var(--fs-11);
line-height: 1.7;
}
+74
View File
@@ -0,0 +1,74 @@
/* 字体基线:拉丁文走 JetBrains Mono,中文走 HarmonyOS Sans SC。
*
* # 为什么要两套字
*
* 这套界面是"终端/仪表",拉丁字母与数字承担全部读数(帧率、血量、地址、倍率、时间码),
* 它们的首要任务是**对齐**——等宽字体里 `1` 与 `8` 占同一格,一列数字跳变时不会左右抖。
* 中文承担叙述与标签,它的首要任务是**在小字号下看得清**,这正好是 HarmonyOS Sans 的
* 长处(字面方正、撇捺收敛、11px 仍然立得住)。
*
* # 两者怎么合到一句话里
*
* 不做"语言判断",靠**逐字回退**:`--font-ui` 把 JetBrains Mono 写在前面,它里面没有汉字,
* 浏览器就逐个汉字往下找,落到 HarmonyOS Sans SC。于是"血量 87"里数字是等宽的、汉字是
* HarmonyOS 的,一件 font-family 声明同时满足两个要求。
*
* # 文件在哪
*
* 两个字体都以 woff2 自托管在 `public/fonts/`,随 Tauri 的 frontendDist 一起进安装包,
* 运行时不碰网络(CSP 里 `default-src 'self'` 也不允许)。
*
* - `public/fonts/harmonyos-sans-sc/` —— 由 cn-font-split 切片的 82 个 unicode-range 分片
* × 3 个字重。分片的好处是**只下载页面真正用到的那几十个**,而不是一上来吞 14 MB。
* 三个字重各有一份 CSS,在 `index.html` 里直接 link(它们是生成物,不该混进源码)。
* - `public/fonts/jetbrains-mono/` —— 拉丁子集,三个字重,各 ~21 kB,下面的 @font-face 声明。
*/
/* 拉丁子集只需要声明一次。unicode-range 显式写出来有两个作用:
*
* 1. 明确告诉浏览器"这一份只管这些码位",剩下的(汉字、全角标点、框线字符)交给后面的
* HarmonyOS Sans SC,不会被一个缺字的字体挡住;
* 2. 三个字重共用同一份范围,换成 `local()` 或未来的可变字体时不会漏掉某个字重。
*
* 这个范围与 Google Fonts 的 `latin` 子集一致:Basic Latin + Latin-1 补充 + 常用标点
* (U+2000-206F,也就是 `·`、`—`、`×`、`≤`、方向引号那些)+ 少量箭头与数学符号。 */
@font-face {
font-family: "JetBrains Mono";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/jetbrains-mono/jetbrains-mono-latin-400-normal.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304,
U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "JetBrains Mono";
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/jetbrains-mono/jetbrains-mono-latin-500-normal.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304,
U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: "JetBrains Mono";
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/jetbrains-mono/jetbrains-mono-latin-700-normal.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304,
U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
:root {
/* 数字保持等宽;混入中文的标签、路径和 SVG 同样回退到 HarmonyOS。 */
--font-mono: "JetBrains Mono", "HarmonyOS Sans SC", "HarmonyOS Sans", ui-monospace,
SFMono-Regular, Menlo, Consolas, "Microsoft YaHei", monospace;
/* 仅中文(长篇叙述、按钮文字)。 */
--font-cn: "HarmonyOS Sans SC", "HarmonyOS Sans", "PingFang SC", "Microsoft YaHei", sans-serif;
/* 界面默认:先找等宽的拉丁,缺字落到 HarmonyOS。绝大多数元素用这一个。 */
--font-ui: "JetBrains Mono", "HarmonyOS Sans SC", "HarmonyOS Sans", ui-monospace,
"PingFang SC", monospace;
}
+26
View File
@@ -0,0 +1,26 @@
/* 样式入口。
*
* 分成几份而不是一个文件,是按"谁会一起改"切的:
*
* - `fonts` 字体与字形回退(几乎不动)
* - `tokens` 颜色、字号、间距、动效曲线、层叠(一动全动)
* - `base` 复位与全站复用的最小控件(按钮、开关、滑杆、切角面板……)
* - `chrome` 外壳:顶栏、通讯带、状态行、启动序列、门、覆盖层
* - `stage` 舞台:取景器、装甲条、命中、结算
* - `console` 控制台:装甲板表、录制与回放、队伍名
* - `settings` 设置抽屉
* - `maintenance` 固件维护
*
* 顺序有意义:后面的文件可以用前面的令牌与原子,但不能反过来。
*/
@import "./fonts.css";
@import "./tokens.css";
@import "./base.css";
@import "./chrome.css";
@import "./stage.css";
@import "./console.css";
@import "./settings.css";
@import "./maintenance.css";
@import "./operator.css";
@import "./match.css";
+180
View File
@@ -0,0 +1,180 @@
/* 固件页在视口内切换步骤,设备图与阶段进度始终可见。 */
.mnt { height: 100dvh; display: flex; flex-direction: column; overflow: hidden; padding: 0 36px; background: var(--void); color: var(--ink); }
.mnt-head { flex: none; height: 100px; display: flex; justify-content: space-between; align-items: center; gap: 20px; border-bottom: 1px solid var(--line-2); }
.mnt-kicker { color: var(--ink-4); font-size: 9px; letter-spacing: .18em; }
.mnt-head h1 { font-size: 24px; font-weight: 500; margin-top: 4px; }
.mnt-head__actions { display: flex; align-items: center; gap: 12px; min-width: 0; }
.mnt-head__actions > .btn { flex: none; }
.mnt-head__actions > .tag { white-space: normal; line-height: 1.5; height: auto; min-height: 18px; padding: 3px 6px; min-width: 0; overflow-wrap: anywhere; }
.mnt-head__actions kbd { opacity: .5; font-size: 10px; margin-left: 8px; }
.mnt-workspace { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) minmax(390px, .82fr); gap: 38px; padding: 28px 0 24px; max-width: 1500px; width: 100%; align-self: center; }
.mnt-visual { min-height: 0; min-width: 0; display: flex; flex-direction: column; align-items: center; position: relative; border: 1px solid var(--line); background: radial-gradient(ellipse at center, var(--panel-2), transparent 70%); }
.mnt-visual__head { align-self: stretch; display: flex; align-items: center; justify-content: space-between; padding: 22px 24px 0; gap: 12px; color: var(--ink-4); }
.mnt-visual__head > .label { font-size: 10px; }
.mnt-link { display: inline-flex; align-items: center; gap: 7px; color: var(--ink-3); font-size: 11px; transition: color var(--dur-short3) var(--m3-standard); }
.mnt-link i { width: 5px; height: 5px; background: currentColor; }
.mnt-link.is-live { color: var(--ok); }
.device-diagram { flex: 1; min-height: 0; width: 100%; max-height: 370px; overflow: visible; color: var(--ink-4); }
.device-diagram rect, .device-diagram circle, .device-diagram path { fill: none; stroke: currentColor; stroke-width: 1.4; transition: stroke var(--dur-short4) var(--m3-standard), fill var(--dur-short4) var(--m3-standard), opacity var(--dur-short4) var(--m3-standard); }
.device-diagram .device-diagram__orbit { stroke: var(--line-2); stroke-dasharray: 3 9; stroke-width: 1; }
.device-diagram .device-diagram__chip { fill: var(--deep); stroke: var(--ink-3); }
.device-diagram text { fill: var(--ink-2); stroke: none; font: 11px var(--font-mono); }
.device-diagram .device-diagram__sublabel { font-size: 8px; fill: var(--ink-3); letter-spacing: .12em; }
.device-diagram .device-diagram__caption { font-size: 10px; fill: var(--ink-3); letter-spacing: .1em; }
.device-diagram .device-diagram__cable { stroke-dasharray: 5 6; stroke: var(--line-3); }
.device-diagram .device-diagram__cable.is-present { stroke: var(--ink-2); stroke-dasharray: none; }
.device-diagram.is-active .device-diagram__cable.is-present { stroke-dasharray: 5 6; animation: device-transfer 1s linear infinite; }
.device-diagram .device-diagram__led { fill: var(--line-3); stroke: none; }
.device-diagram.is-identified .device-diagram__led { fill: var(--ok); }
.device-diagram.is-identified .device-diagram__pcb { stroke: var(--ink-2); }
.device-diagram .device-diagram__progress { stroke: var(--ink); stroke-width: 3; transition: stroke-dashoffset var(--dur-short4) linear, stroke var(--dur-short4) var(--m3-standard); }
.device-diagram .device-diagram__pcb { fill: #15252e; stroke: #617783; stroke-width: 1.5; }
.device-diagram .device-diagram__camera .device-diagram__pcb { fill: #181e24; }
.device-diagram .device-diagram__hole { fill: var(--void); stroke: #8a9a94; stroke-width: 2.5; }
.device-diagram .device-diagram__trace { stroke: #688783; stroke-width: .8; opacity: .7; }
.device-diagram .device-diagram__pad { fill: #3a3430; stroke: #a58d63; stroke-width: 1; }
.device-diagram .device-diagram__pixel { fill: #c8ccc6; stroke: #879991; }
.device-diagram .device-diagram__diode { fill: #a9b39a; stroke: #697b68; stroke-width: .8; }
.device-diagram .device-diagram__shield { fill: #647078; stroke: #a3afb3; }
.device-diagram .device-diagram__board text { fill: #dce4e5; font-size: 10px; }
.device-diagram .device-diagram__board .device-diagram__sublabel { font-size: 7px; }
.device-diagram .device-diagram__smd { fill: #a6a293; stroke: #514a41; stroke-width: .6; }
.device-diagram .device-diagram__usb { fill: #78868b; stroke: #b8c3c5; }
.device-diagram .device-diagram__ribbon { fill: #a46b36; stroke: #d29a56; stroke-width: 1; }
.device-diagram .device-diagram__connector { fill: #d3ccac; stroke: #988e6c; }
.device-diagram .device-diagram__lens-base { fill: #262d34; stroke: #6c7b85; }
.device-diagram .device-diagram__lens { fill: #101820; stroke: #6e7c89; stroke-width: 3; }
.device-diagram .device-diagram__glass { fill: #243e58; stroke: #547da1; }
.device-diagram .device-diagram__lens-shine { stroke: #96bddc; stroke-width: 1.5; }
.device-diagram .device-diagram__button { fill: #718083; stroke: #9ca9ab; }
.device-diagram.is-complete .device-diagram__progress { stroke: var(--ok); }
.device-diagram.is-failed .device-diagram__progress, .device-diagram.is-failed .device-diagram__pcb { stroke: var(--error); }
.device-diagram__progress.is-indeterminate { transform-origin: 355px 180px; animation: device-wait 3s linear infinite; }
@keyframes device-wait { to { transform: rotate(360deg); } }
@keyframes device-transfer { to { stroke-dashoffset: -22; } }
@keyframes maintenance-enter { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
.mnt-visual__status { text-align: center; padding: 0 20px 22px; flex: none; animation: maintenance-enter var(--dur-medium2) var(--m3-emphasized-decelerate) both; }
.mnt-visual__status > .label { font-size: 9px; letter-spacing: .18em; color: var(--ink-4); }
.mnt-visual__status h2 { margin: 8px 0; font-size: 23px; font-weight: 400; color: var(--ink); }
.mnt-visual__status p { font-size: 11px; color: var(--ink-3); max-width: 450px; overflow-wrap: anywhere; }
.mnt-identity { flex: none; display: flex; width: 100%; margin: 0; padding: 18px 24px; border-top: 1px solid var(--line); justify-content: space-between; gap: 10px; }
.mnt-identity dt { font-size: 10px; color: var(--ink-4); margin-bottom: 5px; }
.mnt-identity > div { min-width: 0; }
.mnt-identity dd { margin: 0; font: 11px var(--font-mono); color: var(--ink-2); overflow-wrap: anywhere; }
.mnt-task { min-height: 0; min-width: 0; display: flex; flex-direction: column; border: 1px solid var(--line-2); background: var(--panel); }
.mnt-nav { flex: none; display: grid; grid-template-columns: repeat(4, 1fr); height: 55px; border-bottom: 1px solid var(--line-2); }
.mnt-nav button { display: flex; align-items: center; justify-content: center; gap: 9px; font-size: 12px; color: var(--ink-3); border-bottom: 2px solid transparent; transition: color var(--dur-short3) var(--m3-standard), border-color var(--dur-short3) var(--m3-standard), background-color var(--dur-short3) var(--m3-standard); }
.mnt-nav .num { font-size: 10px; color: var(--ink-4); }
.mnt-nav button.is-active { color: var(--ink); border-color: var(--primary); background: var(--primary-soft); }
.mnt-nav button:disabled { cursor: default; opacity: .4; }
.mnt-nav button.is-active:disabled { opacity: 1; }
.mnt-task__body { flex: 1; min-height: 0; min-width: 0; display: flex; flex-direction: column; align-items: stretch; gap: 18px; padding: 26px; animation: maintenance-enter var(--dur-medium2) var(--m3-emphasized-decelerate) both; }
.mnt-task__body > * { flex-shrink: 0; min-width: 0; }
.mnt-task__title .label { font-size: 9px; letter-spacing: .16em; color: var(--ink-4); }
.mnt-task__title h2 { font-size: 21px; font-weight: 400; margin-top: 8px; }
.mnt-kind { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.mnt-kind button { border: 1px solid var(--line-2); padding: 18px; text-align: left; color: var(--ink-3); transition: border-color var(--dur-short3) var(--m3-standard), color var(--dur-short3) var(--m3-standard), background-color var(--dur-short3) var(--m3-standard); }
.mnt-kind button:hover:not(:disabled) { border-color: var(--line-3); background: var(--panel-2); }
.mnt-kind button:active:not(:disabled) { background: var(--panel-3); }
.mnt-nav button:focus-visible, .mnt-kind button:focus-visible, .mnt-tabs button:focus-visible { outline: 2px solid var(--primary); outline-offset: -3px; }
.mnt-kind button small { display: block; margin-top: 6px; font: 10px var(--font-mono); color: var(--ink-4); }
.mnt-kind button.is-selected { border-color: var(--primary-line); background: var(--primary-soft); color: var(--ink); }
.mnt-field, .mnt-build__fields label { display: flex; flex-direction: column; gap: 7px; font-size: 11px; color: var(--ink-3); min-width: 0; }
.mnt-field .select { width: 100%; min-width: 0; }
.mnt-connection-fields { display: grid; gap: 18px; }
.mnt-row { display: flex; gap: 9px; align-items: center; min-width: 0; }
.mnt-row > .select, .mnt-row > .input { flex: 1; width: 0; min-width: 0; }
.mnt-row > .btn { flex: none; }
.mnt-task__actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: auto; padding-top: 5px; flex: none; }
.mnt-task__actions > .btn { min-height: var(--control-height); }
.mnt-hint { color: var(--ink-4); font-size: 11px; line-height: 1.7; }
.mnt-note { font-size: 11px; line-height: 1.7; }
.mnt-error { flex: none; margin: 10px 20px 0; padding: 10px 12px; color: var(--error); border-left: 2px solid var(--error); background: var(--error-soft); font-size: 11px; max-height: 90px; overflow: auto; user-select: text; overflow-wrap: anywhere; }
.mnt-package { display: flex; align-items: center; flex-direction: column; gap: 10px; padding: 25px 20px; border: 1px dashed var(--line-3); background: var(--deep); text-align: center; }
.mnt-package__symbol { font-size: 27px; color: var(--ink-2); line-height: 1; margin-bottom: 2px; }
.mnt-package strong { font-size: 13px; font-weight: 500; overflow-wrap: anywhere; max-width: 100%; max-height: 3.4em; overflow: auto; }
.mnt-package > span:not(.mnt-package__symbol) { font: 10px var(--font-mono); color: var(--ink-4); }
.mnt-package b { color: var(--ink-2); font-size: 11px; font-weight: 400; }
.mnt-secondary { justify-content: center; }
.mnt-confirmation { display: flex; flex-direction: column; gap: 5px; padding: 14px 16px; border-left: 2px solid var(--line-3); background: var(--panel-2); color: var(--ink-3); font-size: 11px; overflow-wrap: anywhere; }
.mnt-confirmation strong { color: var(--ink); font-size: 12px; font-weight: 400; }
.mnt-confirmation > span { max-height: 3.4em; overflow: auto; }
.mnt-confirmation b { color: var(--ink); font-weight: 400; }
.mnt-running { margin: auto 0; border-top: 1px solid var(--line); padding: 24px 0; }
.mnt-running .label { color: var(--ink-4); font-size: 9px; }
.mnt-running h3 { color: var(--ink); font-size: 24px; font-weight: 400; margin: 15px 0; }
.mnt-running p { color: var(--ink-3); font-size: 12px; margin-bottom: 20px; }
.mnt-warnings { margin: 0; padding-left: 15px; color: var(--warn); font-size: 10px; line-height: 1.65; display: flex; flex-direction: column; gap: 4px; min-height: 32px; flex-shrink: 1; overflow: auto; overflow-wrap: anywhere; }
.mnt-warnings li { flex: none; }
.mnt-check { display: flex; align-items: flex-start; gap: 8px; font-size: 11px; line-height: 1.7; color: var(--ink-2); cursor: pointer; }
.mnt-check input { flex: none; margin: 2px 0 0; }
.mnt-result { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 12px; font-size: 12px; min-height: 0; flex-shrink: 1; }
.mnt-result > strong { flex: none; max-width: 100%; max-height: 3.4em; overflow: auto; overflow-wrap: anywhere; }
.mnt-result__mark { width: 60px; height: 60px; flex: none; border: 1px solid var(--ok-line); border-radius: 50%; display: grid; place-items: center; font: 32px var(--font-mono); color: var(--ok); }
.mnt-result.is-failed .mnt-result__mark { color: var(--error); border-color: var(--error-line); }
.mnt-result p { color: var(--ink-3); line-height: 1.8; overflow-wrap: anywhere; max-width: 100%; max-height: 5.4em; min-height: 1.8em; overflow: auto; }
.mnt-verifications { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding-top: 12px; border-top: 1px solid var(--line); font-size: 11px; }
.mnt-verifications span { display: flex; justify-content: space-between; color: var(--ink-4); }
.mnt-verifications b { font-weight: 400; color: var(--ink-2); }
.mnt-foot { height: 48px; border-top: 1px solid var(--line-2); display: flex; align-items: center; justify-content: space-between; color: var(--ink-4); font-size: 10px; flex: none; }
.mnt-foot > div { display: flex; align-items: center; gap: 12px; }
.mnt-tabs { display: flex; border-bottom: 1px solid var(--line-2); padding: 0 24px; flex: none; }
.mnt-tabs button { padding: 14px 18px; border-bottom: 2px solid transparent; color: var(--ink-4); font-size: 11px; transition: color var(--dur-short3) var(--m3-standard), border-color var(--dur-short3) var(--m3-standard); }
.mnt-tabs button.is-active { color: var(--ink); border-color: var(--primary); }
.mnt-build__body { padding: 24px; display: flex; flex-direction: column; gap: 18px; }
.mnt-build__team { border-left: 2px solid var(--primary); padding: 10px 16px; color: var(--ink-2); background: var(--primary-soft); }
.mnt-build__fields { display: flex; flex-direction: column; gap: 16px; }
.mnt-build__fields .input { width: 100%; }
.mnt-build__fields .mnt-row .input { width: 0; }
.mnt-build-status { padding: 0 24px 22px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; color: var(--ink-3); font-size: 11px; }
.mnt-build-status pre { margin: 0; flex-basis: 100%; max-height: 45px; overflow: hidden; font: 10px var(--font-mono); white-space: pre-wrap; overflow-wrap: anywhere; color: var(--ink-4); }
.mnt-build-dialog .mnt-error { max-height: 64px; margin-bottom: 12px; }
.mnt-details { width: min(960px, calc(100vw - 40px)); }
.mnt-details__scroll { height: min(550px, calc(100dvh - 200px)); overflow: auto; padding: 20px 24px; user-select: text; font: 11px/1.8 var(--font-mono); color: var(--ink-3); }
.mnt-details__scroll pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
@media (max-width: 1100px) {
.mnt { padding: 0 22px; }
.mnt-workspace { gap: 18px; grid-template-columns: minmax(0, 1fr) minmax(360px, 1fr); }
.mnt-task__body { padding: 20px; gap: 14px; }
.mnt-identity { padding: 14px; flex-wrap: wrap; }
.mnt-head__actions { gap: 5px; }
.mnt-head__actions > .tag { max-width: 120px; font-size: 9px; }
}
@media (max-height: 750px) {
.mnt-head { height: 78px; }
.mnt-head h1 { font-size: 21px; }
.mnt-workspace { padding: 18px 0; }
.mnt-task__body { gap: 12px; padding: 20px; }
.mnt-connection-fields { gap: 12px; }
.mnt-task__title h2 { font-size: 18px; margin-top: 4px; }
.mnt-kind button { padding: 13px 15px; }
.mnt-package { padding: 18px 16px; gap: 8px; }
.mnt-visual__status { padding-bottom: 14px; }
.mnt-visual__status h2 { font-size: 20px; }
.mnt-identity { padding: 14px 18px; }
.mnt-build__body { gap: 12px; padding: 18px 24px; }
.mnt-build__fields { gap: 10px; }
.mnt-confirmation { padding: 10px 12px; gap: 3px; }
.mnt-warnings { font-size: 10px; gap: 2px; }
}
@media (max-height: 650px) {
.mnt-head { height: 70px; }
.mnt-workspace { padding: 14px 0; }
.mnt-foot { height: 44px; }
.mnt-nav { height: 48px; }
.mnt-task__body { padding: 16px; gap: 9px; }
.mnt-task > .mnt-error { max-height: 64px; margin: 8px 16px 0; padding: 7px 10px; }
.mnt-connection-fields { gap: 9px; }
.mnt-connection-fields.has-team { grid-template-columns: minmax(0, .85fr) minmax(0, 1.15fr); }
.mnt-connection-fields .mnt-row { gap: 5px; }
.mnt-connection-fields .btn { padding-right: 9px; padding-left: 9px; }
.mnt-task__actions > .btn { min-height: 32px; }
.mnt-visual__head { padding: 16px 18px 0; }
}
@media (prefers-reduced-motion: reduce) {
.mnt-task__body, .mnt-visual__status, .device-diagram__progress.is-indeterminate,
.device-diagram.is-active .device-diagram__cable.is-present { animation: none; }
.mnt-link, .mnt-nav button, .mnt-kind button, .mnt-tabs button,
.device-diagram rect, .device-diagram circle, .device-diagram path,
.device-diagram .device-diagram__progress { transition: none; }
}
+62
View File
@@ -0,0 +1,62 @@
.match-control { flex: none; display: grid; grid-template-columns: minmax(0, 1fr) 280px minmax(0, 1fr); align-items: center; gap: 22px; padding: 14px 24px; border-bottom: 1px solid var(--line-2); background: var(--panel); }
.match-control__identity { display: flex; flex-direction: column; gap: 6px; font-size: 11px; color: var(--ink-2); }
.match-control__identity .label { color: var(--ink-4); font-size: 9px; letter-spacing: .14em; }
.match-control__identity small { color: var(--ink-3); line-height: 1.5; font-size: 10px; overflow-wrap: anywhere; }
.match-control__identity small.is-error { color: var(--error); }
.match-readout { text-align: center; color: var(--ink); }
.match-readout__phase { display: flex; justify-content: center; align-items: center; gap: 6px; font-size: 11px; color: var(--ok); }
.match-readout__phase i { width: 4px; height: 4px; background: currentColor; }
.match-readout__digits { font-size: 36px; line-height: 1.25; letter-spacing: .05em; font-variant-numeric: tabular-nums; }
.match-readout__detail { font-size: 10px; color: var(--ink-3); line-height: 1.5; }
.match-readout__reason { font-size: 11px; line-height: 1.4; color: var(--ink-2); margin: 4px 0 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 280px; }
.match-readout.is-paused .match-readout__phase, .match-readout.is-paused .match-readout__digits { color: var(--warn); }
.match-readout.is-stale .match-readout__phase, .match-readout.is-stale .match-readout__digits { color: var(--ink-3); }
.match-control__actions { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; min-width: 0; }
.match-control__buttons, .match-control__start { display: flex; align-items: center; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
.match-control__hint { font-size: 11px; color: var(--ink-3); }
.match-control__start label { font-size: 11px; color: var(--ink-2); }
.match-control__start input { width: 52px; padding: 5px; }
.match-dialog { width: min(480px, 90vw); }
.match-dialog__body { display: flex; flex-direction: column; gap: 18px; padding: 24px; }
.match-dialog__body p { font-size: 12px; line-height: 1.8; color: var(--ink-2); }
.match-dialog__body > label { display: flex; flex-direction: column; gap: 8px; font-size: 12px; }
.match-dialog__body input:not([type=checkbox]), .match-dialog__body select { width: 100%; padding: 10px; }
.match-dialog__body small { font-size: 10px; color: var(--ink-3); }
.match-dialog__body label.match-dialog__approval { flex-direction: row; align-items: center; }
.team-match-clock { grid-column: 2; grid-row: 1; min-width: 0; text-align: center; align-self: start; line-height: 1; color: var(--ink); pointer-events: auto; }
.team-match-clock__label { display: block; color: var(--hud-dim); font: 9px/1.2 var(--font-cn); margin-bottom: 3px; }
.team-match-clock__time { display: block; font-size: 23px; font-weight: 500; letter-spacing: .04em; font-variant-numeric: tabular-nums; }
.team-match-clock.is-paused .team-match-clock__label, .team-match-clock.is-paused .team-match-clock__time { color: var(--warn); }
.team-match-clock.is-stale .team-match-clock__label, .team-match-clock.is-stale .team-match-clock__time { color: var(--ink-2); }
.match-countdown { position: absolute; inset: 0; z-index: 50; display: grid; place-items: center; overflow: hidden; pointer-events: none; color: var(--ink); background: radial-gradient(ellipse at 50% 50%, #53101c99, #080b13e8 65%); animation: match-countdown-enter 180ms ease-out both; }
.match-countdown__center { position: relative; display: flex; flex-direction: column; align-items: center; justify-content: center; width: min(76vmin, 560px); aspect-ratio: 1; }
.match-countdown__label { z-index: 1; color: #ffb4b9; font: 14px var(--font-cn); letter-spacing: .3em; }
.match-countdown__number { z-index: 1; display: grid; place-items: center; font-size: clamp(140px, 30vmin, 300px); line-height: 1.12; font-weight: 500; text-shadow: 0 0 60px #e8232b66; animation: match-countdown-beat 1s cubic-bezier(.2,.7,.2,1) both; }
.match-countdown__number--start { font-family: var(--font-cn); font-size: clamp(80px, 18vmin, 160px); letter-spacing: .16em; padding-left: .16em; animation: match-countdown-start 750ms ease-out both; }
.match-countdown__dial { position: absolute; inset: 4%; border: 1px solid #f46a7644; border-radius: 50%; }
.match-countdown__dial i { position: absolute; border: 2px solid transparent; border-top-color: #ff6b75; border-bottom-color: #ff6b7544; inset: -6%; border-radius: 50%; animation: match-countdown-orbit 5s linear both; }
.match-countdown__dial i + i { inset: 5%; border-width: 1px; border-top-color: #ffadb544; border-bottom-color: #ffadb588; animation-direction: reverse; }
.match-countdown__steps { z-index: 1; display: flex; gap: 10px; padding-top: 10px; }
.match-countdown__steps i { width: 28px; height: 3px; background: #66323d; }
.match-countdown__steps i.is-passed { background: #ffadb5; box-shadow: 0 0 12px #ff6b7555; }
.match-countdown__caption { z-index: 1; margin-top: 20px; font: 11px var(--font-cn); color: #d4a6ae; letter-spacing: .2em; }
.match-countdown__scan { position: absolute; inset: 0; opacity: .2; background: repeating-linear-gradient(0deg, transparent 0 5px, #b4334814 5px 6px); }
.match-countdown__progress { position: absolute; bottom: 0; left: 0; right: 0; height: 3px; background: #45232c; }
.match-countdown__progress i { display: block; height: 100%; background: #ff6b75; transform-origin: left; transition: transform 100ms linear; }
.match-countdown.is-urgent .match-countdown__number { color: #ffb4b9; text-shadow: 0 0 80px #e8232baa; }
.match-countdown.is-started { background: radial-gradient(ellipse at center, #174939cc, #080b13e8 70%); }
.match-countdown.is-started .match-countdown__label { color: #98ebc6; }
.match-countdown.is-started .match-countdown__dial, .match-countdown.is-started .match-countdown__steps { opacity: 0; }
@keyframes match-countdown-enter { from { opacity: 0; } to { opacity: 1; } }
@keyframes match-countdown-beat { 0% { opacity: .45; transform: scale(1.16); } 22% { opacity: 1; transform: scale(1); } 100% { opacity: 1; transform: scale(.96); } }
@keyframes match-countdown-orbit { to { transform: rotate(180deg); } }
@keyframes match-countdown-start { 0% { opacity: 0; transform: scale(.8); } 22%, 65% { opacity: 1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.08); } }
@media (max-width: 1000px) {
.match-control { grid-template-columns: minmax(0, 1fr) 240px minmax(0, 1fr); gap: 12px; padding: 10px 16px; }
.match-control__identity { font-size: 10px; }
.match-readout__digits { font-size: 30px; }
}
@media (prefers-reduced-motion: reduce) {
.match-countdown, .match-countdown__number, .match-countdown__dial i { animation: none; }
.match-countdown__progress i { transition: none; }
}
+108
View File
@@ -0,0 +1,108 @@
/* HUD 用独立行保留读数空间;装饰框只占据中间的取景区域。 */
.app--team { background: #030906; }
.cockpit { --hud: #a6f7c2; --hud-dim: #74af8b; color: var(--hud); }
.cockpit .op__stage { padding: 0; }
.cockpit .vsurface { background: radial-gradient(ellipse at center, #07100d, #020604); }
.cockpit .vsurface::after { box-shadow: inset 0 0 100px 28px #0008; }
.cockpit .vsurface__reticle-frame { display: none; }
.cockpit .vsurface__empty { color: var(--hud-dim); font-size: 14px; text-shadow: 0 2px 4px #000; gap: 28px; animation: hud-reveal var(--dur-medium1) var(--m3-emphasized-decelerate) both; }
.cockpit .vsurface__empty-mark { width: 22px; height: 22px; border-color: #74af8b55; border-radius: 50%; }
.cockpit .vsurface__empty-mark::after { inset: -6px; border: 1px solid transparent; border-top-color: var(--hud); border-right-color: #74af8b55; border-radius: 50%; animation: empty-orbit 2.4s linear infinite; }
.cockpit__overlay { position: absolute; inset: clamp(18px, 2.5vw, 36px); top: clamp(8px, 1.2vh, 12px); z-index: 12; display: grid; grid-template-rows: auto auto minmax(0, 1fr) auto auto; gap: clamp(18px, 3vh, 32px); pointer-events: none; text-shadow: 0 1px 5px #000, 0 0 16px #000; font-family: var(--font-mono); animation: hud-reveal var(--dur-medium2) var(--m3-emphasized-decelerate) both; }
.cockpit__header { display: flex; justify-content: space-between; align-items: center; gap: 24px; min-width: 0; }
.cockpit__identity { min-width: 0; display: flex; align-items: center; gap: 16px; font-size: 12px; }
.cockpit__identity .label { color: var(--hud-dim); flex: none; }
.cockpit__identity > span:not(.label) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cockpit__identity b { flex: none; color: var(--warn); font: 11px var(--font-ui); border: 1px solid var(--warn-line); padding: 2px 8px; background: #0009; }
.cockpit__links { flex: none; display: flex; gap: 26px; font: 12px var(--font-ui); }
.cockpit__links span { display: flex; align-items: center; gap: 7px; transition: color var(--dur-short4) var(--m3-standard); white-space: nowrap; }
.cockpit__links b { font-weight: 500; }
.cockpit__links i { width: 5px; height: 5px; background: currentColor; transition: background-color var(--dur-short4) var(--m3-standard), box-shadow var(--dur-short4) var(--m3-standard); }
.cockpit__links .is-live i { box-shadow: 0 0 7px #a6f7c255; }
.cockpit__links .is-offline { color: #ffbe78; }
.cockpit__health { display: grid; grid-template-columns: minmax(0, 1fr) 128px minmax(0, 1fr); gap: 16px; padding: 0 14px; align-items: start; }
.cockpit__health-side { display: flex; min-width: 0; }
.cockpit__health-side--right { grid-column: 3; justify-content: flex-end; }
.cockpit .hp { min-width: min(220px, 100%); max-width: 100%; }
.cockpit .hp__name { flex-shrink: 1; }
.cockpit .hp__missing, .cockpit .hp__value { flex: none; white-space: nowrap; }
.cockpit__frame { position: relative; min-height: 0; opacity: .4; }
.cockpit__frame i { position: absolute; width: 30px; height: 22px; border: 1px solid var(--hud); }
.cockpit__frame i:nth-child(1) { left: 0; top: 0; border-right: 0; border-bottom: 0; }
.cockpit__frame i:nth-child(2) { right: 0; top: 0; border-left: 0; border-bottom: 0; }
.cockpit__frame i:nth-child(3) { left: 0; bottom: 0; border-top: 0; border-right: 0; }
.cockpit__frame i:nth-child(4) { right: 0; bottom: 0; border-top: 0; border-left: 0; }
.cockpit__telemetry { display: flex; align-items: end; justify-content: space-between; gap: 32px; padding: 0 14px; }
.cockpit__feed, .cockpit__fps { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
.cockpit__feed { border-left: 2px solid var(--hud-dim); padding-left: 13px; }
.cockpit__feed strong { font-size: 18px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cockpit__feed > span:last-child, .cockpit__fps > span:last-child { font-size: 11px; color: var(--hud-dim); }
.cockpit__fps { flex: none; align-items: flex-end; }
.cockpit__fps strong { font-size: 40px; line-height: 1.1; font-weight: 400; font-variant-numeric: tabular-nums; }
.cockpit__footer { display: grid; grid-template-columns: 1fr auto 1fr; gap: 20px; align-items: center; color: var(--hud-dim); font-size: 10px; letter-spacing: .06em; }
.cockpit__footer > span:last-child { text-align: right; }
.cockpit__footer kbd { border: 1px solid #74af8b66; padding: 2px 5px; margin-right: 6px; color: var(--hud); }
.cockpit .vsurface__calibrating { display: none; }
.app--team .fault { position: absolute; top: 50%; bottom: auto; left: 50%; transform: translate(-50%, 58px); width: max-content; max-width: min(520px, 75%); z-index: 15; background: #100b07e8; }
@keyframes hud-reveal { from { opacity: 0; } to { opacity: 1; } }
.ui-dialog { color: var(--ink); padding: 0; border: 1px solid var(--line-3); background: var(--panel); width: min(720px, calc(100vw - 48px)); max-height: calc(100dvh - 40px); overflow: hidden; box-shadow: 0 28px 100px #0009; }
.ui-dialog::backdrop { background: rgb(2 6 12 / .72); backdrop-filter: blur(9px); }
.ui-dialog__head { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; border-bottom: 1px solid var(--line-2); }
.ui-dialog__head h2 { font-size: 16px; font-weight: 500; }
.ui-dialog__head kbd { margin-left: 8px; opacity: .55; font-size: 10px; }
.operator-menu { width: min(860px, calc(100vw - 64px)); border-color: var(--line-3); background: var(--panel); }
.operator-menu .ui-dialog__head { border-color: var(--line-2); color: var(--ink); }
.operator-menu__body { padding: 44px; display: grid; grid-template-columns: 1fr 1.1fr; gap: 48px; }
.operator-menu__identity > .label { font-size: 10px; color: var(--ink-3); }
.operator-menu__identity h1 { margin: 22px 0; color: var(--ink); font-size: 32px; font-weight: 400; letter-spacing: .08em; }
.operator-menu__identity h1 span { display: block; margin-top: 6px; color: var(--ink-3); font: 11px var(--font-mono); letter-spacing: .3em; }
.operator-menu__identity p { max-width: 210px; font-size: 12px; line-height: 1.8; color: var(--ink-2); margin-bottom: 18px; }
.operator-menu__actions { display: flex; flex-direction: column; gap: 6px; }
.operator-menu__actions button { display: flex; flex-direction: column; align-items: flex-start; position: relative; gap: 4px; padding: 14px 20px; text-align: left; border: 1px solid transparent; color: var(--ink); }
.operator-menu__actions button:hover, .operator-menu__actions button:focus-visible { background: var(--panel-2); border-color: var(--line-3); }
.operator-menu__actions button:first-child { border-left: 2px solid var(--primary); }
.operator-menu__actions button > span { font-size: 16px; }
.operator-menu__actions small { font-size: 10px; color: var(--ink-3); }
.operator-menu__actions kbd { position: absolute; right: 18px; top: 20px; color: var(--ink-3); font-size: 10px; }
@media (max-width: 1050px) {
.cockpit__identity { gap: 10px; }
.cockpit__identity > .label { display: none; }
.cockpit__links { gap: 16px; }
}
@media (max-width: 800px) {
.cockpit__footer > span:last-child { display: none; }
.cockpit__footer { grid-template-columns: 1fr auto; }
.cockpit__header { gap: 12px; }
.operator-menu__body { padding: 24px; gap: 20px; }
}
@media (max-height: 650px) {
.cockpit__overlay { inset: 8px 24px 18px; gap: 18px; }
.cockpit__fps strong { font-size: 32px; }
.operator-menu__body { padding: 18px 30px; }
.operator-menu__actions button { padding: 10px 16px; }
}
@media (prefers-reduced-motion: reduce) {
.cockpit__overlay, .cockpit .vsurface__empty, .cockpit .vsurface__empty-mark::after { animation: none; }
.cockpit__links span, .cockpit__links i { transition: none; }
}
/* 弹窗与按钮只动画透明度和位移,不让布局跟着缩放。 */
.ui-dialog[open] { animation: dialog-in var(--dur-medium2) var(--m3-emphasized-decelerate) both; }
.ui-dialog[open]::backdrop { animation: hud-reveal var(--dur-short4) var(--m3-standard-decelerate) both; }
.ui-dialog.is-closing { animation: dialog-out var(--dur-short3) var(--m3-emphasized-accelerate) both; pointer-events: none; }
.ui-dialog.is-closing::backdrop { animation: backdrop-out var(--dur-short3) var(--m3-standard-accelerate) both; }
.operator-menu__actions button { transition: background-color var(--dur-short3) var(--m3-standard), border-color var(--dur-short3) var(--m3-standard), color var(--dur-short3) var(--m3-standard); }
.operator-menu__actions button:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
.operator-menu__actions button:active { background: var(--panel-3); }
.operator-menu__actions button:first-child { padding-right: 60px; }
@keyframes dialog-in { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
@keyframes dialog-out { to { opacity: 0; transform: translateY(8px); } }
@keyframes backdrop-out { to { opacity: 0; } }
@media (prefers-reduced-motion: reduce) {
.ui-dialog[open], .ui-dialog[open]::backdrop, .ui-dialog.is-closing, .ui-dialog.is-closing::backdrop { animation: none; }
.operator-menu__actions button { transition: none; }
.operator-menu__actions button:hover, .operator-menu__actions button:active { transform: none; }
}
/* 异常与校准提示避开顶部血条及底部读数。 */
.cockpit .fwfault { top: calc(50% + 64px); bottom: auto; width: max-content; max-width: min(620px, 78%); z-index: 15; }
.app--team .calibrate-bar { top: 140px; max-width: calc(100% - 120px); }
+164
View File
@@ -0,0 +1,164 @@
/* 全屏分类设置;操作 HUD 的绿色只在预览图中按用户配置呈现。 */
.settings {
--control-height: 36px;
position: absolute;
inset: 0;
z-index: var(--z-panel);
display: flex;
flex-direction: column;
overflow: hidden;
color: var(--ink);
background: var(--panel);
animation: settings-in var(--d-4) var(--e-out) both;
}
.settings.is-closing { pointer-events: none; animation: settings-out var(--d-3) var(--e-in) both; }
.settings__head { flex: none; height: 100px; display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 0 clamp(28px, 4vw, 70px); border-bottom: 1px solid var(--line-2); background: var(--deep); }
.settings__head .label { color: var(--ink-4); font-size: 10px; }
.settings__head h1 { margin: 7px 0 0; font-size: 27px; font-weight: 500; letter-spacing: .12em; }
.settings__head-actions { display: flex; align-items: center; gap: 12px; }
.settings__back { min-width: 110px; }
.settings__back kbd { color: var(--ink-3); font: 10px var(--font-mono); }
.settings__locked { flex: none; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 6px 30px; background: var(--warn-soft); color: var(--warn); font-size: 12px; }
.settings__main { flex: 1; min-height: 0; display: flex; }
.settings__nav { flex: 0 0 clamp(172px, 18vw, 244px); padding: 20px 0; display: flex; flex-direction: column; gap: 3px; border-right: 1px solid var(--line-2); background: var(--deep); overflow-y: auto; }
.settings__tab { position: relative; display: grid; grid-template-columns: 22px minmax(0, 1fr) 12px; align-items: center; gap: 12px; min-height: 56px; padding: 8px 22px; text-align: left; color: var(--ink-3); border-left: 3px solid transparent; transition: color var(--d-2) var(--e-step), background-color var(--d-2) var(--e-step), border-color var(--d-2) var(--e-step); }
.settings__tab:hover { color: var(--ink); background: var(--panel-2); }
.settings__tab.is-active { color: var(--ink); border-left-color: var(--primary); background: var(--panel-3); }
.settings__tab:focus-visible { outline: 2px solid var(--primary); outline-offset: -4px; }
.settings__tab-index { font-size: 10px; color: var(--ink-4); }
.settings__tab strong { display: block; font-size: 13px; font-weight: 500; }
.settings__tab small { display: block; margin-top: 3px; color: var(--ink-4); font: 9px var(--font-mono); letter-spacing: .08em; }
.settings__tab-arrow { font: 20px var(--font-mono); opacity: 0; transition: opacity var(--d-2) var(--e-step); }
.settings__tab.is-active .settings__tab-arrow { opacity: 1; color: var(--primary-hi); }
.settings__viewport { flex: 1; min-width: 0; min-height: 0; overflow: hidden; }
.settings__page { height: 100%; min-width: 0; display: flex; flex-direction: column; padding: clamp(24px, 3.4vw, 50px); animation: settings-page-in var(--d-3) var(--e-out) both; }
.settings__page.is-leaving { pointer-events: none; animation: settings-page-out var(--dur-short3) var(--e-in) both; }
.settings__page-head { flex: none; margin-bottom: 28px; }
.settings__page-head .label { color: var(--ink-4); font-size: 10px; }
.settings__page-head h2 { margin: 7px 0 10px; font-size: 23px; font-weight: 500; }
.settings__page-head p { margin: 0; color: var(--ink-3); font-size: 12px; line-height: 1.65; }
.settings__workspace { display: flex; gap: clamp(22px, 3vw, 48px); flex: 1; min-width: 0; min-height: 0; align-items: flex-start; }
.settings__form { flex: 1; min-width: 0; max-width: 900px; min-height: 0; max-height: 100%; margin: 0; padding: 0 4px 4px 0; border: 0; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 22px 24px; align-content: start; overflow-y: auto; overflow-x: hidden; }
.settings__form > * { min-width: 0; }
.settings__span { grid-column: 1 / -1; }
.settings .field { display: flex; flex-direction: column; align-items: stretch; gap: 8px; }
.settings .field__label { font-size: 12px; color: var(--ink-2); }
.settings .field__control { min-width: 0; min-height: var(--control-height); }
.settings .field__hint { font: 10px/1.6 var(--font-ui); color: var(--ink-4); }
.settings .input, .settings .select { width: 100%; min-width: 0; font-size: 12px; }
.settings .select { text-overflow: ellipsis; }
.settings .slider { width: 100%; min-width: 0; }
.settings .slider__value { min-width: 44px; font-size: 11px; }
.settings .switch { min-height: var(--control-height); align-self: start; padding: 7px 0; }
.settings .switch__label { font-size: 12px; line-height: 1.5; }
.settings .sect__note { color: var(--ink-3); font-size: 11px; line-height: 1.8; margin: 0; }
.settings .sect__warn { margin: 0; padding: 10px 12px; background: var(--warn-soft); border: 1px solid var(--warn-line); color: var(--warn); font-size: 11px; line-height: 1.8; }
.settings .sect__row { display: flex; gap: 12px; }
.settings__summary { margin-top: 10px; padding: 24px; border: 1px solid var(--line-2); background: var(--deep); }
.settings__summary > .label { display: block; color: var(--ink-4); margin-bottom: 14px; }
.settings__summary strong { font-size: 20px; font-weight: 500; }
.settings__summary p { margin: 12px 0 0; font-size: 12px; line-height: 1.8; color: var(--ink-3); }
.settings__device-state { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; padding: 16px; border: 1px solid var(--line-2); background: var(--deep); }
.settings__device-state > span { display: flex; flex-wrap: wrap; align-items: baseline; gap: 7px 12px; min-width: 0; }
.settings__device-state b { color: var(--ink-3); font-size: 11px; font-weight: 400; }
.settings__device-state strong { font: 12px var(--font-mono); color: var(--ink-2); }
.settings__device-state em { flex: 0 0 100%; font-size: 11px; font-style: normal; color: var(--ink-3); }
.settings__color { display: flex; align-items: center; gap: 12px; color: var(--ink-3); font-size: 11px; }
.settings .color { width: 60px; height: var(--control-height); padding: 4px; background: var(--deep); border: 1px solid var(--line-2); cursor: pointer; transition: border-color var(--d-2) var(--e-step); }
.settings .color:hover { border-color: var(--line-3); }
.settings .color:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
.settings .color::-webkit-color-swatch-wrapper { padding: 0; }
.settings .color::-webkit-color-swatch { border: 0; }
.settings__danger { display: flex; align-items: center; justify-content: space-between; gap: 22px; padding: 18px 0 0; border-top: 1px solid var(--line-2); }
.settings__danger strong { font-size: 12px; font-weight: 500; }
.settings__danger p { margin: 5px 0 0; color: var(--ink-4); font-size: 11px; line-height: 1.65; }
.settings__foot { flex: none; min-height: 42px; padding: 10px 28px; display: flex; justify-content: space-between; align-items: center; gap: 20px; border-top: 1px solid var(--line-2); color: var(--ink-4); font-size: 10px; background: var(--deep); }
/* 只有外观相关分类显示此预览,样本始终标注为合成数据。 */
.settings .preview { flex: 0 0 clamp(244px, 25vw, 400px); min-width: 0; margin: 0; border: 1px solid var(--line-2); background: var(--deep); }
.preview__head { display: flex; flex-direction: column; gap: 6px; padding: 12px; border-bottom: 1px solid var(--line); }
.preview__head .label { color: var(--ink-3); font-size: 10px; }
.preview__note { font-size: 10px; color: var(--ink-4); }
.preview__frame { position: relative; aspect-ratio: 4 / 3; overflow: hidden; background: var(--deep); }
.preview__frame::after { --c: var(--line-3); --l: 10px; }
.preview__canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.preview__hp { position: absolute; top: 12px; left: 12px; width: calc(100% - 24px); pointer-events: none; }
.preview__control { padding: 12px; display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 10px 8px; border-top: 1px solid var(--line); }
.preview__control-label { font-size: 10px; color: var(--ink-3); }
.preview__control .slider { grid-column: 1 / -1; grid-row: 2; }
.preview__threshold { font-size: 10px; color: var(--ink-4); }
.calib { display: flex; flex-direction: column; gap: 18px; }
.calib .sect__note { padding-bottom: 4px; }
.pw { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
.pw__actions { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; gap: 16px; }
.pw__meter { display: inline-flex; gap: 4px; }
.pw__cell { width: 24px; height: 3px; background: var(--line-2); transition: background-color var(--d-2) var(--e-step); }
.pw__cell.is-on { background: var(--primary); }
@keyframes settings-in { from { opacity: 0; transform: translateY(20px); } }
@keyframes settings-out { to { opacity: 0; transform: translateY(16px); } }
@keyframes settings-page-in { from { opacity: 0; transform: translateY(calc(var(--page-direction, 1) * 12px)); } }
@keyframes settings-page-out { to { opacity: 0; transform: translateY(calc(var(--page-direction, 1) * -8px)); } }
@media (max-width: 1200px) {
.settings__head { height: 82px; padding-inline: 28px; }
.settings__nav { flex-basis: 172px; padding-block: 12px; }
.settings__tab { min-height: 50px; gap: 8px; padding-inline: 15px; }
.settings__page { padding: 24px; }
.settings__form { gap: 18px; }
.settings__workspace { gap: 20px; }
.settings .preview { flex-basis: 250px; }
.settings__page--preview .settings__form { gap: 20px 18px; }
}
@media (max-height: 760px) {
.settings__head { height: 76px; }
.settings__head h1 { margin-top: 4px; font-size: 24px; }
.settings__nav { padding-block: 10px; gap: 0; }
.settings__tab { min-height: 47px; padding-block: 6px; }
.settings__page { padding-block: 22px; }
.settings__page-head { margin-bottom: 20px; }
.settings__page-head h2 { font-size: 21px; margin-block: 5px 7px; }
.settings__form { gap: 18px; }
.settings__page--preview .settings__form { gap: 11px; }
.settings .preview { flex-basis: 244px; }
.settings .preview__frame { aspect-ratio: 4 / 3; }
}
@media (max-width: 1000px), (max-height: 650px) {
.settings { --control-height: 32px; }
.settings__head { height: 68px; padding-inline: 22px; }
.settings__head h1 { font-size: 22px; }
.settings__nav { flex-basis: 158px; padding-block: 10px; }
.settings__tab { min-height: 47px; padding-inline: 12px; gap: 7px; }
.settings__tab strong { font-size: 12px; }
.settings__tab small { font-size: 8px; margin-top: 2px; }
.settings__page { padding: 18px 22px; }
.settings__page-head { margin-bottom: 18px; }
.settings__page-head p { font-size: 11px; }
.settings__page-head h2 { font-size: 20px; }
.settings__workspace { gap: 20px; }
.settings .preview { flex-basis: 230px; }
.settings .preview__frame { aspect-ratio: 4 / 3; }
.settings__page--preview .settings__form { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px 16px; }
.settings .field { gap: 6px; }
.settings .field__label, .settings .switch__label { font-size: 11px; }
.settings .field__hint { font-size: 9px; }
.settings__form { gap: 18px; }
.settings__foot { min-height: 38px; padding-inline: 22px; }
.settings__danger { padding-top: 12px; }
.calib { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 18px; }
.calib > .switch, .calib > .sect__note, .calib > .sect__row { grid-column: 1 / -1; }
.calib .sect__note { font-size: 10px; line-height: 1.6; }
}
@media (max-width: 760px) {
.settings__nav { flex-basis: 120px; }
.settings__tab { grid-template-columns: minmax(0, 1fr) 10px; gap: 5px; }
.settings__tab-index { display: none; }
.settings__page { padding-inline: 16px; }
.settings__page--preview .preview { grid-template-columns: minmax(0, 1fr) 170px; }
.settings__page--preview .preview__head { display: none; }
.settings__save-note { display: none; }
}
@media (prefers-reduced-motion: reduce) {
.settings, .settings__page { transform: none !important; }
.settings__form { scroll-behavior: auto; }
}
File diff suppressed because it is too large. Load diff
+190
View File
@@ -0,0 +1,190 @@
/* 设计令牌:颜色、字号、间距、动效曲线、层叠。
*
* 这一份只有变量,没有选择器(`:root` 除外)。它存在的理由是:整套界面的"手感"必须是
* 同一套数字,而散落在各处的 #e8232b 迟早会分裂成几个近似的红。
*
* # 配色:墨黑蓝打底,只有一种强调色
*
* 底色是一组低饱和的冷蓝黑(`--void` 到 `--panel-3`),它承担全部面积;文字是同一族冷白。
* **红只有一支**(`--primary`),并且只允许出现在"必须被看见"的地方:焦点、选中、录制、
* 错误、临界血量。除此之外界面是单色的——这不是节俭,是因为当一个红色读数和一个红色
* 装饰同时存在时,现场的注意力会被后者分走。
*
* 状态色(`--error` / `--warn` / `--ok`)各有语义,不与强调色混用;`--team-0/1` 是**硬件
* 约束**(装甲板 LED 的红与蓝),不是设计选择。
*/
:root {
color-scheme: dark;
/* ── 底色 ───────────────────────────────────────────────────────────────
* 墨黑蓝:从最深到最浅五级,每一级只差一点冷色,靠 1px 线而不是阴影分层。 */
--void: #05070d; /* 最底:页面背景 */
--deep: #080b13; /* 视频窗格、日志底、输入框 */
--panel: #0b111c; /* 常规面板 */
--panel-2: #101725; /* 抬高一档(行、卡、悬停) */
--panel-3: #172032; /* 选中、按下 */
/* ── 线 ─────────────────────────────────────────────────────────────────
* 全站只有 1px 的线。粗线是分区,细线是分隔,两者都不要用色块代替。 */
--line: #1a2434;
--line-2: #26344a;
--line-3: #35475f;
--line-hot: rgba(232, 35, 43, 0.46); /* 焦点 */
/* ── 文字 ───────────────────────────────────────────────────────────────
* 四档就够。第四档是"占位与禁用",它必须暗到不像真信息。 */
--ink: #e7ecf5;
--ink-2: #94a1b8;
--ink-3: #616e86;
--ink-4: #3a4457;
/* ── 强调:红 ───────────────────────────────────────────────────────────
* 界面里唯一的强调色。`--primary` 是本体,`-hi` 用于深底上的文字(更亮才够对比),
* `-lo` 用于大面积底色的边缘,`-soft` / `-line` 是它的两块淡化。 */
--primary: #e8232b;
--primary-hi: #ff5a5f;
--primary-lo: #6d0f13;
--primary-soft: rgba(232, 35, 43, 0.12);
--primary-line: rgba(232, 35, 43, 0.44);
/* ── 状态 ───────────────────────────────────────────────────────────────
* 红用在这里表示"坏了",比 `--primary` 亮一点,好让"强调"与"故障"在同一屏上区分得开。 */
--error: #ff5449;
--error-soft: rgba(255, 84, 73, 0.13);
--error-line: rgba(255, 84, 73, 0.44);
--warn: #f2b33d;
--warn-soft: rgba(242, 179, 61, 0.12);
--warn-line: rgba(242, 179, 61, 0.42);
--ok: #3fc98a;
--ok-soft: rgba(63, 201, 138, 0.12);
--ok-line: rgba(63, 201, 138, 0.4);
/* ── 队伍色 ─────────────────────────────────────────────────────────────
* 这两个值不是设计选择,是**硬件约束**:装甲板的 LED 就是红/蓝,界面必须与车对上,
* 否则现场把"红队"这个词和"红色"这件事当两回事,血条会被读错边。不要改成别的。
* 队红刻意做得比 `--primary` 更暖更浅,免得两条并列时被误读成"系统在报警"。 */
--team-0: #ff6b5e;
--team-1: #4a9bff;
--team-0-soft: rgba(255, 107, 94, 0.14);
--team-1-soft: rgba(74, 155, 255, 0.14);
/* ── 字号 ───────────────────────────────────────────────────────────────
* 12 是正文,11 是标签,10 与 9 是"仪器上的小字"(只放代号,不放句子)。 */
--fs-9: 9px;
--fs-10: 10px;
--fs-11: 11px;
--fs-12: 12px;
--fs-13: 13px;
--fs-15: 15px;
--fs-18: 18px;
--fs-22: 22px;
--fs-28: 28px;
--fs-40: 40px;
/* 字距。全大写英文与微标签需要放宽,否则等宽字体挤成一团。 */
--track-tight: 0.02em;
--track: 0.08em;
--track-wide: 0.16em;
/* ── 间距 ───────────────────────────────────────────────────────────────
* 4 的倍数。`--gutter` 是外壳的内边距,改它就能整体收放。 */
--s1: 4px;
--s2: 8px;
--s3: 12px;
--s4: 16px;
--s5: 24px;
--s6: 32px;
--gutter: 10px;
/* ── 圆角 ───────────────────────────────────────────────────────────────
* 零。全局是矩形:切角、圆角、药丸都不再用。唯一的斜边留给装甲条(平行四边形)。 */
--radius: 0px;
/* ── 动效:Material 3 ───────────────────────────────────────────────────
* 曲线与时长照抄 Material Design 3 的 motion spec,不自己发明贝塞尔。
*
* M3 把缓动分成三组语义:
* emphasized —— 需要"存在感"的转场(面板展开、结算浮现);
* decelerate —— **进入**:快起慢收,元素像是被抛到位;
* accelerate —— **退出**:慢起快走,元素像是被抽走。
* 时长分短(short1-4)/中(medium1-4)/长(long1-4)几档,短时长配小位移、长时长配大位移。
*
* 老代码里的 `--e-*` / `--d-*` 保留为别名,全部指到 M3 上——这样一条规则都不用改,
* 而全站曲线已经是同一套。 */
--m3-emphasized: cubic-bezier(0.2, 0, 0, 1);
--m3-emphasized-decelerate: cubic-bezier(0.05, 0.7, 0.1, 1);
--m3-emphasized-accelerate: cubic-bezier(0.3, 0, 0.8, 0.15);
--m3-standard: cubic-bezier(0.2, 0, 0, 1);
--m3-standard-decelerate: cubic-bezier(0, 0, 0, 1);
--m3-standard-accelerate: cubic-bezier(0.3, 0, 1, 1);
--m3-linear: cubic-bezier(0, 0, 1, 1);
--dur-short1: 50ms;
--dur-short2: 100ms;
--dur-short3: 150ms;
--dur-short4: 200ms;
--dur-medium1: 250ms;
--dur-medium2: 300ms;
--dur-medium3: 350ms;
--dur-medium4: 400ms;
--dur-long1: 450ms;
--dur-long2: 500ms;
--dur-long3: 550ms;
--dur-long4: 600ms;
/* 别名:进入 / 退出 / 强调转场 */
--e-out: var(--m3-emphasized-decelerate);
--e-in: var(--m3-emphasized-accelerate);
--e-in-out: var(--m3-emphasized);
--e-hud: var(--m3-emphasized-decelerate);
--e-step: var(--m3-standard);
--d-1: var(--dur-short3); /* 按压反馈 */
--d-2: var(--dur-short4); /* 悬停、状态翻转 */
--d-3: var(--dur-medium2); /* 面板切换 */
--d-4: var(--dur-medium4); /* 大块进出 */
--d-5: var(--dur-long3); /* 叙事动画 */
/* ── 层叠 ───────────────────────────────────────────────────────────────
* 只列名字,不列魔法数字;组件里一律引用这里。 */
--z-stage: 1;
--z-hud: 10;
--z-overlay: 20;
--z-chrome: 30;
--z-panel: 40;
--z-dialog: 50;
--z-toast: 60;
--z-boot: 90;
/* ── 构型 ───────────────────────────────────────────────────────────────
* 顶栏与底栏的高度是**契约**:覆盖层的 top/bottom 靠它算位置。 */
--h-topbar: 46px;
--h-statusbar: 30px;
}
/* 用户把系统动效关掉时,时长压到 0(M3 的 reduced-motion 要求是"去掉位移与时长",
* 不是"换一条更快的曲线")。 */
@media (prefers-reduced-motion: reduce) {
:root {
--d-1: 0.001ms;
--d-2: 0.001ms;
--d-3: 0.001ms;
--d-4: 0.001ms;
--d-5: 0.001ms;
--dur-short1: 0.001ms;
--dur-short2: 0.001ms;
--dur-short3: 0.001ms;
--dur-short4: 0.001ms;
--dur-medium1: 0.001ms;
--dur-medium2: 0.001ms;
--dur-medium3: 0.001ms;
--dur-medium4: 0.001ms;
--dur-long1: 0.001ms;
--dur-long2: 0.001ms;
--dur-long3: 0.001ms;
--dur-long4: 0.001ms;
}
}