'use client'; import { useState, useEffect } from 'react'; import { Config } from '@/types'; interface CommandModalProps { config: Config; isOpen: boolean; onClose: () => void; } export function CommandModal({ config, isOpen, onClose }: CommandModalProps) { const [selectedDistro, setSelectedDistro] = useState(''); const [command, setCommand] = useState(''); const [loading, setLoading] = useState(false); const [copied, setCopied] = useState(false); // 重置状态当模态框关闭时 useEffect(() => { if (!isOpen) { setSelectedDistro(''); setCommand(''); setCopied(false); } }, [isOpen]); const distros = config.linuxCommands.map(distro => { const dirConfig = config.directories.find(d => d.name === distro); return { name: distro, description: dirConfig?.description || distro, icon: dirConfig?.icon || 'fab fa-linux', color: dirConfig?.color || '#000000' }; }); const generateCommand = async () => { if (!selectedDistro) return; setLoading(true); try { const response = await fetch('/api/command', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ distro: selectedDistro }), }); const data = await response.json(); if (data.success) { setCommand(data.data.command); } else { console.error('Failed to generate command:', data.error); } } catch (error) { console.error('Error generating command:', error); } finally { setLoading(false); } }; const copyToClipboard = async () => { try { await navigator.clipboard.writeText(command); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (error) { console.error('Failed to copy to clipboard:', error); } }; useEffect(() => { if (selectedDistro) { generateCommand(); } else { setCommand(''); } }, [selectedDistro]); // 按ESC键关闭模态框 useEffect(() => { const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape' && isOpen) { onClose(); } }; if (isOpen) { document.addEventListener('keydown', handleEscape); document.body.style.overflow = 'hidden'; // 防止背景滚动 } return () => { document.removeEventListener('keydown', handleEscape); document.body.style.overflow = 'unset'; // 恢复滚动 }; }, [isOpen, onClose]); if (!isOpen) { return null; } return (
{command}
) : (
请选择发行版
)}
{selectedDistro === 'ubuntu' || selectedDistro === 'debian'
? 'sudo apt update'
: selectedDistro === 'centos' || selectedDistro === 'fedora'
? 'sudo dnf update'
: 'sudo pacman -Syu'
}
注意事项: