import { useState, useEffect } from 'react'; import { useNavigate, useParams, useLocation, Link } from 'react-router-dom'; import { ArrowLeft, Server, Trash2, Save, Check, Pencil, X } from 'lucide-react'; import type { LogService } from '../types'; import LogTerminal from '../components/LogTerminal'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardHeader } from '@/components/ui/card'; import { Separator } from '@/components/ui/separator'; import { DockerIcon } from '../components/icons/DockerIcon'; import { cn } from '@/lib/utils'; function DeleteWithConfirmation({ onDelete, serviceName }: { onDelete: () => void, serviceName: string }) { const [showConfirm, setShowConfirm] = useState(false); if (showConfirm) { return (
Supprimer {serviceName} ?
); } return ( ); } export default function ServiceView() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const location = useLocation(); const [service, setService] = useState(location.state?.service || null); const [initialLogs, setInitialLogs] = useState<{ id: string, line: string, isError: boolean }[]>([]); const [loading, setLoading] = useState(true); const [isSaving, setIsSaving] = useState(false); const [isSaved, setIsSaved] = useState(false); const [isEditingName, setIsEditingName] = useState(false); const [tempName, setTempName] = useState(''); const [isTransitioning, setIsTransitioning] = useState(false); useEffect(() => { const fetchServiceAndLogs = async () => { if (service && (service.id === Number(id) || (id === 'ephemeral' && typeof service.id === 'string'))) { setLoading(false); return; } try { const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001'; if (id === 'ephemeral') { const params = new URLSearchParams(window.location.search); const type = params.get('type') || 'docker'; const target = params.get('target') || ''; const name = params.get('name') || 'Service Éphémère'; if (!target) { navigate('/'); return; } const logsRes = await fetch(`${apiUrl}/api/logs/ephemeral?type=${type}&target=${target}&name=${encodeURIComponent(name)}`, { credentials: 'include' }); const logs = await logsRes.json(); setService({ id: `ephemeral-${target}`, name, type: type as any, pathOrContainerId: target, alertKeyword: null, createdAt: new Date().toISOString() }); setInitialLogs(logs); setLoading(false); return; } const [svcRes, logsRes] = await Promise.all([ fetch(`${apiUrl}/api/services`, { credentials: 'include' }), fetch(`${apiUrl}/api/services/${id}/logs`, { credentials: 'include' }) ]); const allServices = await svcRes.json(); const logs = await logsRes.json(); const found = Array.isArray(allServices) ? allServices.find((s: LogService) => s.id === Number(id)) : null; if (found) { setService(found); setInitialLogs(logs); const recents: number[] = JSON.parse(localStorage.getItem('recentServiceIds') || '[]'); const filtered = recents.filter(rid => rid !== Number(id)); const updated = [Number(id), ...filtered].slice(0, 5); localStorage.setItem('recentServiceIds', JSON.stringify(updated)); } else if (!isTransitioning) { navigate('/'); } } catch (e) { console.error(e); } finally { setLoading(false); } }; fetchServiceAndLogs(); return () => { const params = new URLSearchParams(window.location.search); const target = params.get('target'); if (id === 'ephemeral' && target) { const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001'; fetch(`${apiUrl}/api/logs/ephemeral?target=${target}`, { method: 'DELETE', credentials: 'include' }).catch(err => console.error('Erreur cleanup éphémère:', err)); } }; }, [id, window.location.search]); const handleSaveName = async () => { if (!service || !tempName.trim() || tempName === service.name) { setIsEditingName(false); return; } try { const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001'; if (typeof service.id === 'number') { const res = await fetch(`${apiUrl}/api/services/${service.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: tempName.trim() }), credentials: 'include' }); if (!res.ok) throw new Error('Erreur'); setService(await res.json()); } else { setService({ ...service, name: tempName.trim() }); } setIsEditingName(false); } catch (err) { console.error(err); setIsEditingName(false); } }; const handleSave = async () => { if (!service || isSaving) return; setIsSaving(true); setIsTransitioning(true); try { const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001'; const res = await fetch(`${apiUrl}/api/services`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: service.name, type: service.type, pathOrContainerId: service.pathOrContainerId, alertKeyword: service.alertKeyword }), credentials: 'include' }); const savedService = await res.json(); setIsSaved(true); setTimeout(() => { setIsSaving(false); navigate(`/service/${savedService.id}`, { replace: true, state: { service: savedService } }); }, 1000); } catch (err) { console.error(err); setIsSaving(false); setIsTransitioning(false); } }; const handleDelete = async () => { try { await fetch(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}/api/services/${id}`, { method: 'DELETE', credentials: 'include' }); navigate('/'); } catch (err) { console.error(err); } }; if (loading) return (

Initialisation de la console...

); if (!service) return (

Service introuvable

Ce service a peut-être été supprimé ou l'ID est incorrect.

); return (
{service.type === 'docker' ? : } {service.type === 'docker' ? : }
{isEditingName ? ( setTempName(e.target.value)} onBlur={handleSaveName} onKeyDown={(e) => { if (e.key === 'Enter') handleSaveName(); if (e.key === 'Escape') setIsEditingName(false); }} autoFocus /> ) : (

{ setIsEditingName(true); setTempName(service.name); }}> {service.name}

)} {typeof service.id === 'string' && service.id.startsWith('ephemeral') && !isSaved && ( Session Éphémère )}

{service.pathOrContainerId}

ID: {id}
{typeof service.id === 'number' && ( )} {typeof service.id === 'string' && service.id.startsWith('ephemeral') && ( )}
); }