305 lines
13 KiB
TypeScript
305 lines
13 KiB
TypeScript
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 (
|
|
<div className="flex items-center gap-3 bg-destructive/10 p-1.5 px-3 rounded-xl border border-destructive/30 animate-in zoom-in-95 duration-200">
|
|
<span className="text-sm font-semibold text-destructive">Supprimer {serviceName} ?</span>
|
|
<div className="flex gap-1">
|
|
<Button variant="destructive" size="sm" className="h-8 px-3 text-xs font-bold rounded-lg" onClick={onDelete}>Confirmer</Button>
|
|
<Button variant="ghost" size="sm" className="h-8 px-3 text-xs rounded-lg" onClick={() => setShowConfirm(false)}>Annuler</Button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<Button variant="outline" size="sm" onClick={() => setShowConfirm(true)} className="gap-2 border-destructive/30 text-destructive hover:bg-destructive/10 hover:border-destructive/40 rounded-xl">
|
|
<Trash2 size={15} />
|
|
<span className="hidden sm:inline">Supprimer</span>
|
|
</Button>
|
|
);
|
|
}
|
|
|
|
export default function ServiceView() {
|
|
const { id } = useParams<{ id: string }>();
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
const [service, setService] = useState<LogService | null>(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 (
|
|
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-6 fade-in">
|
|
<div className="relative">
|
|
<div className="w-12 h-12 border-2 border-primary/20 border-t-primary rounded-full animate-spin"></div>
|
|
<div className="absolute inset-0 border-2 border-transparent border-b-secondary/50 rounded-full animate-spin [animation-duration:1.5s]"></div>
|
|
</div>
|
|
<p className="text-muted-foreground font-medium animate-pulse tracking-wide">Initialisation de la console...</p>
|
|
</div>
|
|
);
|
|
|
|
if (!service) return (
|
|
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-6 fade-in text-center p-4">
|
|
<div className="w-20 h-20 rounded-3xl bg-destructive/5 flex items-center justify-center text-destructive mb-2">
|
|
<X size={40} />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<h3 className="text-2xl font-bold tracking-tight">Service introuvable</h3>
|
|
<p className="text-muted-foreground max-w-md">Ce service a peut-être été supprimé ou l'ID est incorrect.</p>
|
|
</div>
|
|
<Button variant="outline" asChild className="rounded-xl px-8 h-12">
|
|
<Link to="/"><ArrowLeft className="mr-2" size={18} /> Retour au tableau de bord</Link>
|
|
</Button>
|
|
</div>
|
|
);
|
|
|
|
return (
|
|
<div className="max-w-7xl mx-auto px-4 py-8 space-y-6 fade-in">
|
|
<Button variant="ghost" size="sm" onClick={() => navigate('/')} className="mb-2 text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded-lg">
|
|
<ArrowLeft size={16} className="mr-2" />
|
|
Retour à l'accueil
|
|
</Button>
|
|
|
|
<Card className="overflow-hidden shadow-sm border-muted/50 rounded-xl">
|
|
<CardHeader className="bg-muted/10 p-4 sm:p-8 space-y-6 flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6">
|
|
<div className="flex items-start sm:items-center gap-4 sm:gap-6 w-full">
|
|
<div className="w-12 h-12 sm:w-16 sm:h-16 rounded-xl sm:rounded-2xl bg-card border flex items-center justify-center text-primary shadow-sm shrink-0">
|
|
{service.type === 'docker' ? <DockerIcon size={24} className="sm:hidden" /> : <Server size={24} className="sm:hidden" />}
|
|
{service.type === 'docker' ? <DockerIcon size={32} className="hidden sm:block" /> : <Server size={32} className="hidden sm:block" />}
|
|
</div>
|
|
<div className="space-y-1 sm:space-y-2 min-w-0 flex-1">
|
|
<div className="flex items-center gap-2 sm:gap-3 flex-wrap">
|
|
{isEditingName ? (
|
|
<Input
|
|
className="h-9 sm:h-10 w-full sm:w-72 text-xl sm:text-2xl font-bold bg-card border-primary/30"
|
|
value={tempName}
|
|
onChange={(e) => setTempName(e.target.value)}
|
|
onBlur={handleSaveName}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'Enter') handleSaveName();
|
|
if (e.key === 'Escape') setIsEditingName(false);
|
|
}}
|
|
autoFocus
|
|
/>
|
|
) : (
|
|
<h3 className="text-xl sm:text-3xl font-bold tracking-tight cursor-pointer hover:text-primary transition-colors flex items-center gap-2 sm:gap-3 group truncate" onClick={() => { setIsEditingName(true); setTempName(service.name); }}>
|
|
<span className="truncate">{service.name}</span>
|
|
<Pencil size={16} className="opacity-0 group-hover:opacity-40 transition-opacity shrink-0" />
|
|
</h3>
|
|
)}
|
|
{typeof service.id === 'string' && service.id.startsWith('ephemeral') && !isSaved && (
|
|
<Badge variant="outline" className="bg-secondary/10 text-secondary border-secondary/20 font-bold px-2 py-0.5 sm:px-3 sm:py-1 uppercase tracking-widest text-[8px] sm:text-[10px]">Session Éphémère</Badge>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-2 sm:gap-3 overflow-hidden">
|
|
<p className="text-xs sm:text-sm font-mono text-muted-foreground opacity-70 truncate max-w-full">
|
|
{service.pathOrContainerId}
|
|
</p>
|
|
<Badge variant="outline" className="text-[8px] sm:text-[10px] font-mono opacity-50 uppercase tracking-tighter shrink-0">ID: {id}</Badge>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap items-center gap-3 sm:gap-4 shrink-0 w-full lg:w-auto justify-start lg:justify-end">
|
|
{typeof service.id === 'number' && (
|
|
<DeleteWithConfirmation onDelete={handleDelete} serviceName={service.name} />
|
|
)}
|
|
|
|
{typeof service.id === 'string' && service.id.startsWith('ephemeral') && (
|
|
<Button
|
|
variant={isSaved ? "outline" : "default"}
|
|
size="lg"
|
|
className={cn(
|
|
"h-10 sm:h-12 px-6 sm:px-8 rounded-xl sm:rounded-2xl transition-all font-semibold w-full sm:w-auto",
|
|
isSaved ? "border-green-500/50 text-green-500 hover:bg-green-500/5" : "bg-blue-700 hover:bg-blue-800 text-white border-none shadow-lg hover:shadow-blue-500/20"
|
|
)}
|
|
onClick={handleSave}
|
|
disabled={isSaving || isSaved}
|
|
>
|
|
{isSaved ? <Check size={18} className="mr-2" /> : <Save size={18} className="mr-2" />}
|
|
{isSaved ? 'Enregistré' : 'Enregistrer le service'}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</CardHeader>
|
|
|
|
<Separator />
|
|
|
|
<CardContent className="p-0 bg-transparent">
|
|
<LogTerminal service={service} initialLogs={initialLogs} />
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|