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 = { 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 = { up: 'W/↑', down: 'S/↓', left: 'A/←', right: 'D/→', center: 'SPACE' }; const DIRECTIONS = ['up', 'down', 'left', 'right']; const DPadControl: React.FC = ({ onGamepadUpdate, onSpeedChange, disabled = false, onEmergencyStop, }) => { const { t } = useTranslation(); const [pressed, setPressed] = useState>({}); const [speed, setSpeed] = useState(0.5); // 急停锁存状态:与其他入口(手柄 / 功能按钮)共享同一份状态 const [eStopActive, setEStopActive] = useState(false); useEffect(() => subscribeEmergencyStop(setEStopActive), []); // 每个物理输入单独记录,避免同方向不同按键互相干扰 // 例如 ArrowUp 和 W 可以同时按下 const activeInputsRef = useRef>(new Map()); const pressedRef = useRef>({}); const speedRef = useRef(0.5); const pressTimer = useRef(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 = {}; 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 = { 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, ) => ( ); const renderEmergency = () => ( ); return (
{/* 十字方向键 */}
{renderBtn('up', , t('devices.dpad.up'))}
{renderBtn('left', , t('devices.dpad.left'))} {onEmergencyStop ? renderEmergency() : renderBtn( 'center', , t('devices.dpad.center'), )} {renderBtn('right', , t('devices.dpad.right'))}
{renderBtn('down', , t('devices.dpad.down'))}
{/* 速度滑块 */}
{t('devices.dpad.speed')} {Math.round(speed * 100)}%
{ 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%)`, }} />
0% 50% 100%
); }; export default DPadControl;