All files / src/components ConnectionStatus.tsx

0% Statements 0/196
0% Branches 0/1
0% Functions 0/1
0% Lines 0/196

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * ConnectionStatus Component
 *
 * Displays the current Gateway connection status with visual indicators.
 * Supports automatic reconnect and manual reconnect button.
 * Includes health status indicator for OpenFang backend.
 */
 
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Wifi, WifiOff, Loader2, RefreshCw, Heart, HeartPulse } from 'lucide-react';
import { useConnectionStore, getClient } from '../store/connectionStore';
import {
  createHealthCheckScheduler,
  getHealthStatusLabel,
  formatHealthCheckTime,
  type HealthCheckResult,
  type HealthStatus,
} from '../lib/health-check';
 
interface ConnectionStatusProps {
  /** Show compact version (just icon and status text) */
  compact?: boolean;
  /** Show reconnect button when disconnected */
  showReconnectButton?: boolean;
  /** Additional CSS classes */
  className?: string;
}
 
interface ReconnectInfo {
  attempt: number;
  delay: number;
  maxAttempts: number;
}
 
type StatusType = 'disconnected' | 'connecting' | 'handshaking' | 'connected' | 'reconnecting';
 
const statusConfig: Record<StatusType, {
  color: string;
  bgColor: string;
  label: string;
  icon: typeof Wifi;
  animate?: boolean;
}> = {
  disconnected: {
    color: 'text-red-500',
    bgColor: 'bg-red-50 dark:bg-red-900/20',
    label: '已断开',
    icon: WifiOff,
  },
  connecting: {
    color: 'text-yellow-500',
    bgColor: 'bg-yellow-50 dark:bg-yellow-900/20',
    label: '连接中...',
    icon: Loader2,
    animate: true,
  },
  handshaking: {
    color: 'text-yellow-500',
    bgColor: 'bg-yellow-50 dark:bg-yellow-900/20',
    label: '认证中...',
    icon: Loader2,
    animate: true,
  },
  connected: {
    color: 'text-green-500',
    bgColor: 'bg-green-50 dark:bg-green-900/20',
    label: '已连接',
    icon: Wifi,
  },
  reconnecting: {
    color: 'text-orange-500',
    bgColor: 'bg-orange-50 dark:bg-orange-900/20',
    label: '重连中...',
    icon: RefreshCw,
    animate: true,
  },
};
 
export function ConnectionStatus({
  compact = false,
  showReconnectButton = true,
  className = '',
}: ConnectionStatusProps) {
  const connectionState = useConnectionStore((s) => s.connectionState);
  const connect = useConnectionStore((s) => s.connect);
  const [showPrompt, setShowPrompt] = useState(false);
  const [reconnectInfo, setReconnectInfo] = useState<ReconnectInfo | null>(null);
 
  // Listen for reconnect events
  useEffect(() => {
    const client = getClient();
 
    const unsubReconnecting = client.on('reconnecting', (info) => {
      setReconnectInfo(info as ReconnectInfo);
    });
 
    const unsubFailed = client.on('reconnect_failed', () => {
      setShowPrompt(true);
      setReconnectInfo(null);
    });
 
    const unsubConnected = client.on('connected', () => {
      setShowPrompt(false);
      setReconnectInfo(null);
    });
 
    return () => {
      unsubReconnecting();
      unsubFailed();
      unsubConnected();
    };
  }, []);
 
  const config = statusConfig[connectionState];
  const Icon = config.icon;
  const isDisconnected = connectionState === 'disconnected';
  const isReconnecting = connectionState === 'reconnecting';
 
  const handleReconnect = async () => {
    setShowPrompt(false);
    try {
      await connect();
    } catch (error) {
      console.error('Manual reconnect failed:', error);
    }
  };
 
  // Compact version
  if (compact) {
    return (
      <div className={`flex items-center gap-1.5 ${className}`}>
        <Icon
          className={`w-3.5 h-3.5 ${config.color} ${config.animate ? 'animate-spin' : ''}`}
        />
        <span className={`text-xs ${config.color}`}>
          {isReconnecting && reconnectInfo
            ? `${config.label} (${reconnectInfo.attempt}/${reconnectInfo.maxAttempts})`
            : config.label}
        </span>
        {showPrompt && showReconnectButton && (
          <button
            onClick={handleReconnect}
            className="text-xs text-blue-500 hover:text-blue-600 ml-1"
          >
            重连
          </button>
        )}
      </div>
    );
  }
 
  // Full version
  return (
    <div className={`flex items-center gap-3 ${config.bgColor} rounded-lg px-3 py-2 ${className}`}>
      <motion.div
        initial={false}
        animate={{ rotate: config.animate ? 360 : 0 }}
        transition={config.animate ? { duration: 1, repeat: Infinity, ease: 'linear' } : {}}
      >
        <Icon className={`w-5 h-5 ${config.color}`} />
      </motion.div>
 
      <div className="flex-1">
        <div className={`text-sm font-medium ${config.color}`}>
          {isReconnecting && reconnectInfo
            ? `${config.label} (${reconnectInfo.attempt}/${reconnectInfo.maxAttempts})`
            : config.label}
        </div>
        {reconnectInfo && (
          <div className="text-xs text-gray-500 dark:text-gray-400">
            {Math.round(reconnectInfo.delay / 1000)}秒后重试
          </div>
        )}
      </div>
 
      <AnimatePresence>
        {showPrompt && isDisconnected && showReconnectButton && (
          <motion.button
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.9 }}
            onClick={handleReconnect}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded-md transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            重新连接
          </motion.button>
        )}
      </AnimatePresence>
    </div>
  );
}
 
/**
 * ConnectionIndicator - Minimal connection indicator for headers
 */
export function ConnectionIndicator({ className = '' }: { className?: string }) {
  const connectionState = useConnectionStore((s) => s.connectionState);
 
  const isConnected = connectionState === 'connected';
  const isReconnecting = connectionState === 'reconnecting';
 
  return (
    <span className={`text-xs flex items-center gap-1 ${className}`}>
      <span
        className={`w-1.5 h-1.5 rounded-full ${
          isConnected
            ? 'bg-green-400'
            : isReconnecting
            ? 'bg-orange-400 animate-pulse'
            : 'bg-red-400'
        }`}
      />
      <span className={
        isConnected
          ? 'text-green-500'
          : isReconnecting
          ? 'text-orange-500'
          : 'text-red-500'
      }>
        {isConnected
          ? 'Gateway 已连接'
          : isReconnecting
          ? '重连中...'
          : 'Gateway 未连接'}
      </span>
    </span>
  );
}
 
/**
 * HealthStatusIndicator - Displays OpenFang backend health status
 */
export function HealthStatusIndicator({
  className = '',
  showDetails = false,
}: {
  className?: string;
  showDetails?: boolean;
}) {
  const [healthResult, setHealthResult] = useState<HealthCheckResult | null>(null);
 
  useEffect(() => {
    // Start periodic health checks
    const cleanup = createHealthCheckScheduler((result) => {
      setHealthResult(result);
    }, 30000); // Check every 30 seconds
 
    return cleanup;
  }, []);
 
  if (!healthResult) {
    return (
      <span className={`text-xs flex items-center gap-1 ${className}`}>
        <Heart className="w-3.5 h-3.5 text-gray-400" />
        <span className="text-gray-400">检查中...</span>
      </span>
    );
  }
 
  const statusColors: Record<HealthStatus, { dot: string; text: string; icon: typeof Heart }> = {
    healthy: { dot: 'bg-green-400', text: 'text-green-500', icon: Heart },
    unhealthy: { dot: 'bg-red-400', text: 'text-red-500', icon: HeartPulse },
    unknown: { dot: 'bg-gray-400', text: 'text-gray-500', icon: Heart },
  };
 
  const config = statusColors[healthResult.status];
  const Icon = config.icon;
 
  return (
    <span className={`text-xs flex items-center gap-1 ${className}`}>
      <Icon className={`w-3.5 h-3.5 ${config.text}`} />
      <span className={config.text}>
        {getHealthStatusLabel(healthResult.status)}
      </span>
      {showDetails && healthResult.message && (
        <span className="text-gray-400 ml-1" title={healthResult.message}>
          ({formatHealthCheckTime(healthResult.timestamp)})
        </span>
      )}
    </span>
  );
}
 
export default ConnectionStatus;