Files
simba-rmic-2026/client/src/components/SettingsPanel.tsx
T

555 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 全屏分类设置。发现列表仅在解锁期间开放,保存仍由后端逐项校验。 */
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 { aimPoint, 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";
import { Icon, type IconName } from "./Icon";
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 }
const CATEGORY_ICONS: Record<string, IconName> = {
general: "settings", devices: "devices", reticle: "target", calibration: "calibration",
grid: "grid", health: "health", feedback: "feedback", slots: "splitView", media: "camera", security: "lock",
};
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 mirrorControls = <>
<Switch checked={config.mirror} label="左右镜像画面" onChange={mirror => void run(() => api.setMirror(mirror))} />
<Switch checked={config.mirrorVertical} label="上下镜像画面" onChange={mirror => void run(() => api.setMirrorVertical(mirror))} />
</>;
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>
{mirrorControls}
<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 <>
{mirrorControls}
<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 icon="delete" 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 icon="logout" 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 icon="lock" 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}><Icon name="back" />返回 <kbd>ESC</kbd></button>
</div>
</header>
{locked && <div className="settings__locked"><span>修改设置前请先输入密码解锁。</span><button type="button" className="btn btn--ghost" onClick={() => onNeedsUnlock("修改设置需要密码")}><Icon name="unlock" />解锁设置</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)}>
<Icon name={CATEGORY_ICONS[category.id]} /><span><strong>{category.label}</strong><small>{category.en}</small></span><span className="settings__tab-arrow" aria-hidden="true"><Icon name="chevron" /></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} mirrored={config.mirror} mirroredVertical={config.mirrorVertical} />}
</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, mirrored, mirroredVertical }: { hud: HudView; team: number; mirrored: boolean; mirroredVertical: boolean }) {
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);
ctx.save();
ctx.translate(mirrored ? width : 0, mirroredVertical ? height : 0);
ctx.scale(mirrored ? -1 : 1, mirroredVertical ? -1 : 1);
// 伪画面:一块低饱和的远景色 + 一条地平线。它的作用是让准星与网格有一个"深色背景
// 之上"的参照,而不是浮在一片纯黑里看不出对比。
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);
ctx.restore();
if (hud.crosshair.visible) {
// 预览里的偏移按比例缩到这块小画布上,方向与真画面一致。
const aim = aimPoint(geometry, hud.crosshair, mirrored, width, height, mirroredVertical);
paintCrosshair(ctx, aim.x, aim.y, 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, mirrored, mirroredVertical]);
// 预览用的血量。`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 icon="reset" 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
icon="key"
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>
);
}