Files
web-Iot/src/components/devices/DPadControl.tsx

466 lines
11 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 React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { subscribeEmergencyStop } from './emergencyStopControl';
import {
ChevronUp,
ChevronDown,
ChevronLeft,
ChevronRight,
Circle,
ShieldAlert,
} from 'lucide-react';
export interface GamepadState {
buttons: boolean[];
axes: number[];
connected: boolean;
ts?: number;
}
interface DPadControlProps {
onGamepadUpdate?: (state: GamepadState) => void;
onSpeedChange?: (speed: number) => void;
disabled?: boolean;
onEmergencyStop?: () => void;
}
// 键盘按键映射
const KEY_MAP: Record<string, string> = {
ArrowUp: 'up',
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowRight: 'right',
w: 'up',
s: 'down',
a: 'left',
d: 'right',
W: 'up',
S: 'down',
A: 'left',
D: 'right',
};
const KEY_LABELS: Record<string, string> = {
up: 'W/↑',
down: 'S/↓',
left: 'A/←',
right: 'D/→',
center: 'SPACE'
};
const DIRECTIONS = ['up', 'down', 'left', 'right'];
const DPadControl: React.FC<DPadControlProps> = ({
onGamepadUpdate,
onSpeedChange,
disabled = false,
onEmergencyStop,
}) => {
const { t } = useTranslation();
const [pressed, setPressed] = useState<Record<string, boolean>>({});
const [speed, setSpeed] = useState(0.5);
// 急停锁存状态:与其他入口(手柄 / 功能按钮)共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
// 每个物理输入单独记录,避免同方向不同按键互相干扰
// 例如 ArrowUp 和 W 可以同时按下
const activeInputsRef = useRef<Map<string, string>>(new Map());
const pressedRef = useRef<Record<string, boolean>>({});
const speedRef = useRef(0.5);
const pressTimer = useRef<number | null>(null);
const disabledRef = useRef(disabled);
const onGamepadUpdateRef = useRef(onGamepadUpdate);
const onSpeedChangeRef = useRef(onSpeedChange);
const onEmergencyStopRef = useRef(onEmergencyStop);
onGamepadUpdateRef.current = onGamepadUpdate;
onSpeedChangeRef.current = onSpeedChange;
onEmergencyStopRef.current = onEmergencyStop;
disabledRef.current = disabled;
// 根据所有仍然按住的输入,重新计算方向状态
const syncPressed = useCallback(() => {
const next: Record<string, boolean> = {};
for (const direction of DIRECTIONS) {
next[direction] = false;
}
for (const direction of activeInputsRef.current.values()) {
next[direction] = true;
}
// center 不参与摇杆坐标计算
next.center = pressedRef.current.center ?? false;
pressedRef.current = next;
setPressed(next);
return next;
}, []);
// 生成摇杆状态
const buildState = useCallback((): GamepadState => {
const current = pressedRef.current;
const spd = speedRef.current;
let axisX = 0;
let axisY = 0;
if (current.left) axisX -= spd;
if (current.right) axisX += spd;
if (current.up) axisY -= spd;
if (current.down) axisY += spd;
// 对角线归一化,避免斜向速度超过直线速度
if (axisX !== 0 && axisY !== 0) {
const scale = 1 / Math.sqrt(2);
axisX *= scale;
axisY *= scale;
}
return {
buttons: new Array(17).fill(false),
axes: [0, axisY, axisX, 0],
connected: true,
ts: Date.now(),
};
}, []);
const emit = useCallback(() => {
if (disabledRef.current) return;
onGamepadUpdateRef.current?.(buildState());
}, [buildState]);
// 始终只保留一个定时器
const startTimer = useCallback(() => {
if (pressTimer.current !== null) return;
pressTimer.current = window.setInterval(() => {
emit();
}, 100);
}, [emit]);
const stopTimer = useCallback(() => {
if (pressTimer.current !== null) {
window.clearInterval(pressTimer.current);
pressTimer.current = null;
}
}, []);
// 开始按住某个输入
const startPress = useCallback(
(sourceId: string, direction: string) => {
if (disabledRef.current) return;
// 防止同一物理输入重复触发
if (activeInputsRef.current.has(sourceId)) return;
activeInputsRef.current.set(sourceId, direction);
syncPressed();
emit();
startTimer();
},
[syncPressed, emit, startTimer],
);
// 释放某个输入,但保留其他仍按住的方向
const endPress = useCallback(
(sourceId: string) => {
if (!activeInputsRef.current.has(sourceId)) return;
activeInputsRef.current.delete(sourceId);
syncPressed();
if (activeInputsRef.current.size === 0) {
stopTimer();
}
// 立即发送最新状态,避免松开后残留旧方向
emit();
},
[syncPressed, stopTimer, emit],
);
// 清除所有输入并发送停止状态
const releaseAll = useCallback(() => {
activeInputsRef.current.clear();
const next: Record<string, boolean> = {
up: false,
down: false,
left: false,
right: false,
center: pressedRef.current.center ?? false,
};
pressedRef.current = next;
setPressed(next);
stopTimer();
emit();
}, [stopTimer, emit]);
// 急停:切换锁存状态(第一次按下→发送 eStop=1,第二次按下→发送 eStop=0)
// 视觉由订阅到的共享锁存状态驱动,与手柄 / 其他入口保持一致
const toggleEmergency = useCallback(() => {
if (disabledRef.current) return;
onEmergencyStopRef.current?.();
}, []);
// 键盘控制:支持方向键 + WASD 组合
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const target = e.target as HTMLElement | null;
if (
target &&
(target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.isContentEditable)
) {
return;
}
if (e.code === 'Space') {
e.preventDefault();
// 防止长按空格时重复触发急停
if (!e.repeat) {
toggleEmergency();
}
return;
}
const direction = KEY_MAP[e.key];
if (!direction) return;
e.preventDefault();
// 使用物理按键标识,而不是方向名
// 这样 ArrowUp 和 W 不会被当成同一个输入
startPress(`keyboard:${e.code}`, direction);
};
const handleKeyUp = (e: KeyboardEvent) => {
const direction = KEY_MAP[e.key];
if (!direction) return;
e.preventDefault();
endPress(`keyboard:${e.code}`);
};
const handleBlur = () => {
releaseAll();
};
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
window.addEventListener('blur', handleBlur);
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
};
}, [startPress, endPress, releaseAll, toggleEmergency]);
// 禁用时立即停止;卸载时清理定时器
useEffect(() => {
if (disabled) {
activeInputsRef.current.clear();
pressedRef.current = {
up: false,
down: false,
left: false,
right: false,
center: false,
};
setPressed(pressedRef.current);
stopTimer();
// 直接发送中立轴状态,避免 emit 因 disabled 而跳过
onGamepadUpdateRef.current?.({
buttons: new Array(17).fill(false),
axes: [0, 0, 0, 0],
connected: true,
ts: Date.now(),
});
}
return () => {
stopTimer();
};
}, [disabled, stopTimer]);
// 急停锁存相关清理
//useEffect(() => {
// return () => {
// if (emergencyTimer.current !== null) {
// window.clearTimeout(emergencyTimer.current);
// }
// stopTimer();
// };
//}, [stopTimer]);
const btnBase =
'flex items-center justify-center w-8 h-8 rounded-xl border transition-all duration-150 select-none active:scale-95 touch-none';
const btnActive =
'border-cyan-400 bg-cyan-500/30 text-cyan-300 shadow-[0_0_16px_rgba(34,211,238,0.4)]';
const btnIdle =
'border-slate-600 bg-slate-800/60 text-slate-300 hover:border-cyan-500/60 hover:text-cyan-300';
const renderBtn = (
key: string,
icon: React.ReactNode,
ariaLabel: string,
) => (
<button
key={key}
type="button"
aria-label={ariaLabel}
disabled={disabled}
className={`${btnBase} relative ${pressed[key] ? btnActive : btnIdle
} ${disabled
? 'opacity-40 cursor-not-allowed'
: 'cursor-pointer'
}`}
onPointerDown={(e) => {
if (disabled) return;
e.preventDefault();
const sourceId = `pointer:${e.pointerId}`;
startPress(sourceId, key);
try {
e.currentTarget.setPointerCapture(e.pointerId);
} catch {
// 某些环境可能不支持 pointer capture
}
}}
onPointerUp={(e) => {
endPress(`pointer:${e.pointerId}`);
}}
onPointerCancel={(e) => {
endPress(`pointer:${e.pointerId}`);
}}
onLostPointerCapture={(e) => {
endPress(`pointer:${e.pointerId}`);
}}
onContextMenu={(e) => e.preventDefault()}
>
{icon}
<span className="absolute -top-4 -right+1 px-1 bg-slate-900/80 text-[8px] text-slate-400 rounded border border-slate-700 pointer-events-none group-hover:text-cyan-400 transition-colors">
{KEY_LABELS[key]}
</span>
</button>
);
const renderEmergency = () => (
<button
type="button"
aria-label={t('devices.emergencyStop')}
disabled={disabled}
className={`${btnBase} relative ${eStopActive
? 'border-red-500 bg-red-500/40 text-white shadow-[0_0_16px_rgba(239,68,68,0.6)]'
: 'border-red-500/70 bg-red-500/10 text-red-400 hover:bg-red-500/20'
} ${disabled
? 'opacity-40 cursor-not-allowed'
: 'cursor-pointer'
}`}
onClick={toggleEmergency}
>
<ShieldAlert className="w-5 h-5" />
<span className="absolute -top-1 -right-1 px-1 bg-slate-900/80 text-[8px] text-red-400/80 rounded border border-red-500/30 pointer-events-none">
{KEY_LABELS.center}
</span>
</button>
);
return (
<div className="flex flex-col items-center gap-1 w-full">
{/* 十字方向键 */}
<div className="grid grid-cols-3 grid-rows-3 gap-2.5">
<div />
{renderBtn('up', <ChevronUp className="w-6 h-6" />, t('devices.dpad.up'))}
<div />
{renderBtn('left', <ChevronLeft className="w-6 h-6" />, t('devices.dpad.left'))}
{onEmergencyStop
? renderEmergency()
: renderBtn(
'center',
<Circle className="w-5 h-5 fill-current" />,
t('devices.dpad.center'),
)}
{renderBtn('right', <ChevronRight className="w-6 h-6" />, t('devices.dpad.right'))}
<div />
{renderBtn('down', <ChevronDown className="w-6 h-6" />, t('devices.dpad.down'))}
<div />
</div>
{/* 速度滑块 */}
<div className="w-full px-3">
<div className="flex items-center justify-between mb-2">
<span className="text-sm text-slate-400 font-medium">
{t('devices.dpad.speed')}
</span>
<span className="text-sm font-bold text-cyan-300">
{Math.round(speed * 100)}%
</span>
</div>
<input
type="range"
min={0}
max={1}
step={0.01}
value={speed}
disabled={disabled}
onChange={(e) => {
const value = parseFloat(e.target.value);
setSpeed(value);
speedRef.current = value;
onSpeedChangeRef.current?.(value);
// 改速后立即发送新速度对应的轴值
emit();
}}
className="w-full h-2.5 rounded-full appearance-none cursor-pointer bg-slate-700 accent-cyan-400"
style={{
background: `linear-gradient(to right, #22d3ee 0%, #22d3ee ${speed * 100
}%, #334155 ${speed * 100}%, #334155 100%)`,
}}
/>
<div className="flex justify-between mt-1.5 text-[11px] text-slate-500">
<span>0%</span>
<span>50%</span>
<span>100%</span>
</div>
</div>
</div>
);
};
export default DPadControl;